2017-01-20 242 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'? –