![](/img/trans.png)
[英]How to combine two (or morer) DF w/ different leng and ind providing an appropriate index for both in a single DF
[英]How to combine two df with two different timestamps?
我有兩個不同的df,每個都有一個時間戳。 一種是每分鍾收集一次數據,另一種是在發生更改的情況下收集數據,因此有時是每秒一次,有時是兩排之間的幾個小時。 如何將df2的列附加到df1,以便時間戳相同? df2會在每行(每分鍾)中顯示相同的值,直到發生變化(因此填充NaN)為止。 可以通過它散布一些信息,將df放在一起更重要。 我仍然是一個初學者,所以將不勝感激。 提前致謝!
現在看起來像這樣:
In[10]: df1
Out[10]:
timestamp, X, Y, Z
2018-12-15 08:00:00, 134, 7, 276
2018-12-15 08:01:00, 130, 7, 278
2018-12-15 08:02:00, 136, 8, 291
In[11]: df2
Out[11]:
timestamp, A, B, C
2018-12-15 07:34:36, 1, 44, 21
2018-12-15 08:00:46, NaN, 50, 20
2018-12-15 08:00:52, 0, NaN, 30
應該看起來像這樣:
In[12]: df
Out[12]:
timestamp, X, Y, Z, A, B, C
2018-12-15 08:00:00, 134, 7, 276, 1, 44, 21
2018-12-15 08:01:00, 130, 7, 278, 0, 50, 30
2018-12-15 08:02:00, 136, 8, 291, 0, 50, 30
使用merge_asof
將合並在最接近的匹配 :
pd.merge_asof(df1, df2, on='timestamp')
timestamp X Y Z A B C
0 2018-12-15 08:00:00 134 7 276 1 44 21
1 2018-12-15 08:01:00 130 7 278 0 NaN 30
2 2018-12-15 08:02:00 136 8 291 0 NaN 30
請注意,如果您的timestamp
列不是datetime
格式,請首先使用to_datetime
將它們轉換為正確的格式:
df1['timestamp'] = pd.to_datetime(df1['timestamp'])
df2['timestamp'] = pd.to_datetime(df2['timestamp'])
如果要填寫NaN
使用:
df3 = df3.ffill()
我想你需要重采樣 。 首先,確保'timestamp'
的類型為datetime,並將其設置為數據幀的索引。
df1['timestamp'] = pd.to_datetime(df1['timestamp'])
df2['timestamp'] = pd.to_datetime(df2['timestamp'])
這使它們成為日期時間類型
df1.set_index('timestamp', inplace=True)
df2.set_index('timestamp', inplace=True)
這將它們設置為索引。
然后,您只需要將df2
重新采樣到1分鍾的bin中即可:
rsdf2 = df2.resample('1T').sum()
sum()
方法將在同一個容器中匯總togheter值,並將0放入空容器中。 當然,您可以根據需要使用不同的功能。 例如, .mean()
如果您想要平均值而不是總和。
現在取決於您想如何加入他們。 函數是pandas.concat 。
您要保留所有索引嗎? 采用:
pd.concat([df1, rsdf2], axis=1)
它將填充其中一個數據幀中不存在的NaN行。
您只想保留通用索引? 采用:
pd.concat([df1, rsdf2], axis=1, join='inner')
您要保留第一個數據幀的確切索引嗎? 采用:
pd.concat([df1, rsdf2], axis=1, join_axes=[df1.index])
例如,使用您的示例數據幀,這最后一個將給出:
X Y Z A B C
timestamp
2018-12-15 08:00:00 134 7 276 0.0 50.0 50.0
2018-12-15 08:01:00 130 7 278 NaN NaN NaN
2018-12-15 08:02:00 136 8 291 NaN NaN NaN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.