2017-01-20 526 views
1

我有一个我创建的熊猫df。东风的结构如下: -将json元素添加到熊猫数据框中

A B C D 
0 a b c NaN 
2 x y z NaN 
. 
. 

现在也有一个列表列表1具有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] 

它给了我没有名为错误的索引。我在这里做什么错了?

回答

2

解决方案如果list1length是一样的DataFrame长度:

您需要创建Series先用相同的索引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} 

DataFrame.assign另一种解决方案:

df = df.assign(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} 

S olution对此事发表评论,谢谢Nickil Maveli

df.loc[:, 'D'] = list1 

或者更好:

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} 

如果lenghts是不同的,它是一个比较复杂 - 通过df.indexlength的位置需要选择并通过list1length

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} 
+0

这里是不是一个简单的'loc'就足够了 - 'df.loc [:,'D'] = L'? –