Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.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_Pandas_Dictionary_Dataframe_Append - Fatal编程技术网

Python 在数据框上添加列,其中包含字典中的数据

Python 在数据框上添加列,其中包含字典中的数据,python,pandas,dictionary,dataframe,append,Python,Pandas,Dictionary,Dataframe,Append,我有一个像这样的熊猫数据帧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 149

我有一个像这样的熊猫数据帧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'
   },
   ...
}
当dict中的键也存在于timestamp列中时,我想添加包含在observations子dict中的所有值,并使用它们各自的键作为列名,以便生成的数据帧是

        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与fillna我有这个错误:在blk ref_locs中提高断言错误间隔,没有它工作:2在我的dict中,我有很多键不包含在数据帧中,因此合并给了我很多空的Rowsorry,没有仔细阅读你的问题。看起来您需要左连接而不是完全连接;不过我不确定菲尔纳的问题。我以前从来没有遇到过这样的错误。
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