簡體   English   中英

基於相同的日期時間將具有來自一個 dataframe 的值的列添加到另一個

[英]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

反正我能做到嗎?

使用pandas.DataFrame.merge

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_datetimedf2["DateTime"]轉換為日期時間:

df2['DateTime'] = pd.to_datetime(df2.DateTime)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM