2017-05-29 66 views
0

我有一个熊猫数据帧p_df这样对大熊猫数据帧的数据添加列的字典里面

 date_loc  timestamp 
id                  
1  2017-05-29 1496083649 
2  2017-05-29 1496089320 
3  2017-05-29 1496095148 
4  2017-05-30 1496100936 
... 

像这样一个

observations = { 
    '1496089320': { 
     'col_a: 'value_a', 
     'col_b: 'value_b', 
     'col_c: 'n/a' 
    }, 
    '1496100936' : { 
     'col_b: 'value_b' 
    }, 
    ... 
} 

的字典,我想添加的所有当字典中的键也存在于timestamp列中时,observations子字典中包含的值与它们各自的键作为列名,使得得到的数据帧为

 date_loc  timestamp  col_a col_b col_c 
id                  
1  2017-05-29 1496083649 
2  2017-05-29 1496089320 value_a value_b  n/a 
3  2017-05-29 1496095148 
4  2017-05-30 1496100936   value_b 
... 

我试过几种方法(agg(),apply(),iterrows()),但没有任何工作。下面是比如我的最后一次尝试

p_df['col_a'] = '' 
p_df['col_b'] = '' 
p_df['col_c'] = '' 

for index, row in p_df.iterrows(): 
    ts = p_df.loc[index, 'timestamp'] 
    if ts in observations: 
     # how to concat column values in this row? 
    # end if 
#end for 

可能我觉得也有比迭代数据帧的行一个更好的办法,所以我开到比这更好的选择。

回答

1

您可以从字典中构建一个数据帧,然后用在timestamp列中的原始数据帧合并:

import pandas as pd 
# make sure the timestamp columns are of the same type 
df.timestamp = df.timestamp.astype(str) 
​ 
df.merge(pd.DataFrame.from_dict(observations, 'index'), 
     left_on='timestamp', right_index=True, how='left').fillna('') 

#  date_loc timestamp col_b col_c col_a 
#id     
#1 2017-05-29 1496083649   
#2 2017-05-29 1496089320 value_b n/a value_a 
#3 2017-05-29 1496095148   
#4 2017-05-30 1496100936 value_b  
+0

它几乎工作,谢谢你,但1)'fillna()'我有这个错误:'提高AssertionError(“在blk ref_locs中的差距”)',没有它的作品:2)在我的字典中,我有很多键不包含在数据框内,所以合并给我很多空行 – fcalderan

+0

对不起,没有仔细阅读你的问题。看起来你需要一个左侧而不是完全加入;不知道有关'fillna()'问题。我以前没有遇到'fillna'的错误。 – Psidom

+1

谢谢,左连接工作正常。 – fcalderan