【问题标题】:Pandas DataFrame take automatically wrong value as indexPandas DataFrame 自动将错误值作为索引
【发布时间】:2019-01-21 11:48:12
【问题描述】:

我尝试从 JSON 文件创建 DataFrame。

我有一个名为“Series_participants”的列表,其中包含此 JSON 文件的一部分。当我打印它时,我的列表看起来像 thise。

participantId                                                                1
championId                                                                  76
stats                        {'item0': 3265, 'item2': 3143, 'totalUnitsHeal...
teamId                                                                     100
timeline                     {'participantId': 1, 'csDiffPerMinDeltas': {'1...
spell1Id                                                                     4
spell2Id                                                                    12
highestAchievedSeasonTier                                               SILVER
dtype: object
<class 'list'>

在我尝试将此列表转换为这样的 DataFrame 之后

pd.DataFrame(Series_participants)

但 pandas 使用“stats”和“timeline”的值作为 DataFrame 的索引。我希望有自动索引范围 (0, ..., n)

编辑 1:

   participantId    championId     stats  teamId    timeline    spell1Id  spell2Id  highestAchievedSeasonTier
0       1               76         3265     100       NaN          4          12     SILVER

我想要一个带有“stats”和“timeline”列的数据框,其中包含它们在系列显示中的值的字典。

我的错误是什么?

编辑2:

我尝试手动创建 DataFrame,但 pandas 没有考虑我的选择,最终采用了 Series 的“stats”键的索引。

这是我的代码:

for j in range(0,len(df.participants[0])):

    for i in range(0,len(df.participants[0][0])):

        Series_participants = pd.Series(df.participants[0][i])
        test = {'participantId':Series_participants.values[0],'championId':Series_participants.values[1],'stats':Series_participants.values[2],'teamId':Series_participants.values[3],'timeline':Series_participants.values[4],'spell1Id':Series_participants.values[5],'spell2Id':Series_participants.values[6],'highestAchievedSeasonTier':Series_participants.values[7]}

        if j == 0:
            df_participants = pd.DataFrame(test)

        else:
            df_participants.append(test, ignore_index=True)

双循环是解析我的JSON文件的所有“参与者”。

最后编辑:

我用下面的代码实现了我想要的:

for i in range(0,len(df.participants[0])):

    Series_participants = pd.Series(df.participants[0][i])

    df_test = pd.DataFrame(data=[Series_participants.values], columns=['participantId','championId','stats','teamId','timeline','spell1Id','spell2Id','highestAchievedSeasonTier'])

    if i == 0:
        df_participants = pd.DataFrame(df_test)
    else:
        df_participants = df_participants.append(df_test, ignore_index=True)

print(df_participants)

感谢大家的帮助!

【问题讨论】:

    标签: python json python-3.x pandas dataframe


    【解决方案1】:

    为了提高效率,您应该在构建数据框时尝试操作数据,而不是作为一个单独的步骤。

    但是,要拆分字典键和值,您可以使用 numpy.repeatitertools.chain 的组合。这是一个最小的例子:

    df = pd.DataFrame({'A': [1, 2],
                       'B': [{'key1': 'val0', 'key2': 'val9'},
                             {'key1': 'val1', 'key2': 'val2'}],
                       'C': [{'key3': 'val10', 'key4': 'val8'},
                             {'key3': 'val3', 'key4': 'val4'}]})
    
    import numpy as np
    from itertools import chain
    
    chainer = chain.from_iterable
    
    lens = df['B'].map(len)
    
    res = pd.DataFrame({'A': np.repeat(df['A'], lens),
                        'B': list(chainer(df['B'].map(lambda x: x.values())))})
    
    res.index = chainer(df['B'].map(lambda x: x.keys()))
    
    print(res)
    
          A     B
    key1  1  val0
    key2  1  val9
    key1  2  val1
    key2  2  val2
    

    【讨论】:

      【解决方案2】:

      如果您尝试将包含字典的列表、系列或数组输入到对象构造函数中,它无法识别您正在尝试执行的操作。解决此问题的一种方法是手动设置:

      df.at['a', 'b'] = {'x':value}
      

      请注意,上述方法仅在您的 DataFrame 中已创建列 索引时才有效。

      【讨论】:

        【解决方案3】:

        按 cmets 更新:Pandas 数据框可以保存字典,但不建议这样做。

        Pandas 解释说您希望为每个字典键创建一个索引,然后在它们之间广播单个项目列。

        因此,为了帮助您尝试做的事情,我建议您将字典中的项目作为列阅读。这是数据帧通常用于并且非常擅长的。

        由于 pandas 尝试通过键、值对读取字典而导致的示例错误:

        df = pd.DataFrame(columns= ['a', 'b'], index=['a', 'b'])
        df.loc['a','a'] = {'apple': 2}
        

        返回

        ValueError: Incompatible indexer with Series
        

        下面cmets中的每个jpp(使用构造方法时):

        "它们可以保存任意类型,例如

        df.iat[0, 0] = {'apple': 2}
        

        但是,不建议以这种方式使用 Pandas。”

        【讨论】:

        • df['a','a'] 在 python 中是非法的。
        • 好消息……太早了……不知道我在想什么。
        • I do not believe that pandas dataframes can hold dictionaries. 不正确。它们可以保存任意类型,例如df.iat[0, 0] = {'apple': 2}。但是,不建议以这种方式使用 Pandas。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-24
        • 1970-01-01
        • 2020-01-21
        • 2014-11-26
        • 2015-07-19
        • 2013-08-23
        • 1970-01-01
        相关资源
        最近更新 更多