Python 将json元素添加到数据帧
我有一个我创建的熊猫df。df的结构如下所示:-Python 将json元素添加到数据帧,python,json,pandas,Python,Json,Pandas,我有一个我创建的熊猫df。df的结构如下所示:- A B C D 0 a b c NaN 2 x y z NaN . . 现在还有一个listlist1,其中包含json元素,如 [{a:1,b:2},{c:1,d:2},....] 我想将列表中的元素添加到json df中,使我的df看起来像 A B C D 0 a b c {a:1,b:2} 2 x y z {c:1,d:2} . . 当我这么做的时候 df['D'].iloc[0]
A B C D
0 a b c NaN
2 x y z NaN
.
.
现在还有一个listlist1,其中包含json元素,如
[{a:1,b:2},{c:1,d:2},....]
我想将列表中的元素添加到json df中,使我的df看起来像
A B C D
0 a b c {a:1,b:2}
2 x y z {c:1,d:2}
.
.
当我这么做的时候
df['D'].iloc[0] = list[0]
它没有给我命名为error的索引。如果
list1
的length
与DataFrame
的长度相同,我在这里做错了什么?解决方案:
您需要首先使用与df
相同的索引创建系列
,然后分配给新列:
print (pd.Series(list1, index=df.index))
0 {'b': 2, 'a': 1}
2 {'d': 2, 'c': 1}
dtype: object
df['D'] = pd.Series(list1, index=df.index)
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
另一个解决方案包括:
解决方案征求意见,谢谢:
或者更好:
df['D'] = list1
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
如果长度不同,则要复杂一点-需要通过df.index的length
和list1的length
按位置选择:
print (df)
A B C D
0 a b c NaN
2 x y z NaN
5 y e t NaN
list1 = [{'a':1,'b':2},{'c':1,'d':2}]
df['D'] = pd.Series(list1[:len(df.index)], index=df.index[:len(list1)])
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
5 y e t NaN
在这里,一个简单的loc
就足够了-df.loc[:,'D']=L
?
df['D'] = list1
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
print (df)
A B C D
0 a b c NaN
2 x y z NaN
5 y e t NaN
list1 = [{'a':1,'b':2},{'c':1,'d':2}]
df['D'] = pd.Series(list1[:len(df.index)], index=df.index[:len(list1)])
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
5 y e t NaN
print (df)
A B C D
0 a b c NaN
2 x y z NaN
5 y e t NaN
list1 = [{'a':1,'b':2},{'c':1,'d':2}, {'a':1,'b':2},{'c':1,'d':2}]
df['D'] = pd.Series(list1[:len(df.index)], index=df.index[:len(list1)])
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
5 y e t {'b': 2, 'a': 1}