[英]Pandas merging 2 dataframes on their similar columns(which is the index)
我有兩個數據幀,在這兩個數據幀中我都將'timeStamp'設置為索引。 df_1.set_index('timeStamp', inplace=True)
。
df_1
value
timeStamp
2016-11-23 20:00:00 37.21
2016-11-23 21:00:00 37.79
2016-11-23 22:00:00 33.99
2016-11-23 23:00:00 32.66
2016-11-24 00:00:00 31.61
df_2
value
timeStamp
2016-11-23 23:00:00 32.92
2016-11-24 00:00:00 31.54
2016-11-24 01:00:00 29.14
當共享時間時,我想制作一個比較兩個值的數據框。 我嘗試了combined_df= pd.merge(df_real, df_fc, on='timeStamp', how='inner')
並得到了一個key error
。
因此,我沒有在索引上合並兩個數據框,而是保留了沒有'timeStamp'作為其索引的數據框。 例如。
我使用df進行合並
timeStamp value
0 2016-11-23 20:00:00 37.21
1 2016-11-23 21:00:00 37.79
2 2016-11-23 22:00:00 33.99
3 2016-11-23 23:00:00 32.66
13 2016-11-24 00:00:00 31.61
然后,我能夠合並,並設置了新的df(如下所示)。 稍后,我還將索引設置為時間戳。
timeStamp value_x value_y
0 2016-11-23 23:00:00 32.66 32.92
我的問題為什么我不能合並指定為索引的列名? 我想將合並設置為新的數據框...
您需要表明您正在合並索引:
pd.merge(df_1, df_2, left_index=True, right_index=True, how='inner')
DataFrame合並/合並
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, sort=True,
suffixes=('_x', '_y'), copy=True, indicator=False,
validate=None)
嘗試這個:
df_real.merge(df_fc, on='timeStamp', how='inner')
測試代碼:
import pandas as pd
d = {'time1': ['A', 'B'], 'val1': [2, 4]}
df = pd.DataFrame(data=d)
df.set_index('time1')
d1 = {'time1': ['A', 'B','C'], 'val1': [5, 6, 9]}
df2 = pd.DataFrame(data=d1)
df2.set_index('time1')
df.merge(df2, on = 'time1')
輸出為:
time1 val1_x val1_y
0 A 2 5
1 B 4 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.