Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 数据帧自动将错误值作为索引_Python_Json_Python 3.x_Pandas_Dataframe - Fatal编程技术网

Python 数据帧自动将错误值作为索引

Python 数据帧自动将错误值作为索引,python,json,python-3.x,pandas,dataframe,Python,Json,Python 3.x,Pandas,Dataframe,我试图从JSON文件创建数据帧 我有一个名为“Series_参与者”的列表,其中包含这个JSON文件的一部分。我的列表在打印时是这样的 participantId 1 championId 76 stats

我试图从JSON文件创建数据帧

我有一个名为“Series_参与者”的列表,其中包含这个JSON文件的一部分。我的列表在打印时是这样的

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'>
但是熊猫使用“stats”和“timeline”的值作为数据帧的索引。我希望有自动索引范围(0,…,n)

编辑1:

   participantId    championId     stats  teamId    timeline    spell1Id  spell2Id  highestAchievedSeasonTier
0       1               76         3265     100       NaN          4          12     SILVER
我希望有一个数据框,其中包含“stats”和“timeline”列,其中包含其值的dict,如系列显示中所示

我的错误是什么

编辑2:

我曾尝试手动创建数据帧,但pandas没有考虑我的选择,最终对该系列的“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)

谢谢大家的帮助

根据注释更新:熊猫数据框可以容纳字典,但不建议这样做

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

因此,为了帮助你做什么,我建议你在字典中阅读列项目。这就是数据帧通常使用的功能,并且非常擅长

熊猫试图通过键、值对读取字典时出现的示例错误:

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

ValueError: Incompatible indexer with Series
根据以下注释中的jpp(使用构造函数方法时):

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

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

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

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

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

注意,只有在数据框中已经创建了列索引时,上述操作才有效。

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

但是,要拆分字典键和值,可以使用
numpy.repeat
itertools.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

df['a','a']
在python中是非法的。很好的捕获。。。太早了。。。我不知道我在想什么。
我不相信熊猫数据框可以容纳字典。
不是真的。它们可以保存任意类型,例如
df.iat[0,0]={'apple':2}
。然而,不建议以这种方式使用熊猫。
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