[英]Adding a new column to a dataframe from the values of another dataframe based on a condition
[英]Adding column with values from one dataframe to another based on same datetime
我有一個大的 dataframe 的日期時間和值,所以我將取樣 dataframe 稱為 df1
DateTime Values
2020-12-26 14:00:00 439.0
2020-12-26 14:00:00 441.0
2020-12-26 14:00:00 461.0
2020-12-27 08:00:00 536.0
2020-12-27 08:00:00 547.0
2020-12-27 08:00:00 484.0
2020-12-27 08:00:00 497.0
2020-12-27 14:00:00 491.0
2020-12-27 14:00:00 512.0
2020-12-27 14:00:00 529.0
2020-12-27 14:00:00 436.0
我還有另一個完整的 dataframe df 2
DateTime Trend
2020-12-18 14:00 no trend
2020-12-19 08:00 no trend
2020-12-19 14:00 no trend
2020-12-21 08:00 no trend
2020-12-21 14:00 no trend
2020-12-22 08:00 no trend
2020-12-22 14:00 decreasing
2020-12-23 08:00 no trend
2020-12-23 14:00 no trend
2020-12-24 08:00 no trend
2020-12-24 14:00 no trend
2020-12-25 08:00 no trend
2020-12-25 14:00 decreasing
2020-12-26 08:00 no trend
2020-12-26 14:00 decreasing
2020-12-27 08:00 no trend
2020-12-27 14:00 no trend
我正在嘗試創建一個新列 df1[Trend] 並根據正確的日期時間分配趨勢值
結果應該是這樣的
DateTime Values Trend
2020-12-26 14:00:00 439.0 decreasing
2020-12-26 14:00:00 441.0 decreasing
2020-12-26 14:00:00 461.0 decreasing
2020-12-27 08:00:00 536.0 no trend
2020-12-27 08:00:00 547.0 no trend
2020-12-27 08:00:00 484.0 no trend
2020-12-27 08:00:00 497.0 no trend
2020-12-27 14:00:00 491.0 no trend
2020-12-27 14:00:00 512.0 no trend
2020-12-27 14:00:00 529.0 no trend
2020-12-27 14:00:00 436.0 no trend
反正我能做到嗎?
df1.merge(df2)
DateTime Values Trend
0 2020-12-26 14:00:00 439.0 decreasing
1 2020-12-26 14:00:00 441.0 decreasing
2 2020-12-26 14:00:00 461.0 decreasing
3 2020-12-27 08:00:00 536.0 no trend
4 2020-12-27 08:00:00 547.0 no trend
5 2020-12-27 08:00:00 484.0 no trend
6 2020-12-27 08:00:00 497.0 no trend
7 2020-12-27 14:00:00 491.0 no trend
8 2020-12-27 14:00:00 512.0 no trend
9 2020-12-27 14:00:00 529.0 no trend
10 2020-12-27 14:00:00 436.0 no trend
編輯
你得到
ValueError:您正在嘗試合並 datetime64[ns] 和 object 列。 如果你想繼續,你應該使用 pd.concat
因為df1["DateTime"]
是一個日期時間列,但df2["DateTime"]
是一個str
列,所以你不能合並。 要修復它,請使用pandas.to_datetime
將df2["DateTime"]
轉換為日期時間:
df2['DateTime'] = pd.to_datetime(df2.DateTime)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.