簡體   English   中英

用其他數據框的值填充列,並在pandas中添加相應的ID

[英]Fill columns with values from other dataframe with corresponding id in pandas

我有一個數據框,我必須在其中執行一些操作。 我一切都很好,像這樣:

 ID  Value      Date          Date_diff_cumsum     Val     Weight
  1   0.000000 2017-02-13 20:54:00     0.0       0.000000     nan
  1   0.029598 2017-02-13 21:02:00     8.0       0.029598     nan
  1   0.273000 2017-02-13 22:33:00    99.0       0.273000     nan
  1   0.153000 2017-02-13 23:24:00    150.0      0.15300      nan

我還有另一個具有權重的數據集,如下所示:

ID   Value
 1   78.0
 2   75.0
 3   83.0
 4   60.0

我想用每個ID的權重重復來填充原始數據框的weigth列,例如:

 ID  Value      Date          Date_diff_cumsum   Val        Weight
  1   0.000000 2017-02-13 20:54:00     0.0       0.000000     78.0
  1   0.029598 2017-02-13 21:02:00     8.0       0.029598     78.0
  1   0.273000 2017-02-13 22:33:00    99.0       0.273000     78.0
  1   0.153000 2017-02-13 23:24:00    150.0      0.15300      78.0
  ...    ...          ...              ...          ...         ...
  4   ....      .....      ....        ....        ...         60.0
  4   ....      .....      ....        ....        ...         60.0

這是因為我需要使用以下公式進行計算:

  • 對於每個ID,(Val * 1000)/(weight * Date_diff_cumsum),即:將每個Val乘以1000,然后將其除以權重再乘以i和i-1時間范圍之間的時間差(Date_diff_cumsum)並存儲它在一個數據框中,我可以在其中繪制分辨率

那是我的代碼:

df = df[['ID','Value', 'Date']]
df = df.sort_values(by=['Date'])
df['Date_diff_cumsum'] = df.groupby('ID').Date.diff().dt.seconds / 60.0
df['Date_diff_cumsum'] = 
df.groupby('ID').Date_diff_cumsum.cumsum().fillna(0)
df['TempVal'] = df.groupby('ID')['Value'].transform(lambda x:(x- 
x.iloc[0]*1000))

我該如何執行將第二個數據幀中的Weigth重復項添加到第一個數據幀中的操作? 有沒有更有效的方法? 因為我需要使用相同的方法來計算最終結果,但是對於每個ID,使用其他名稱不同但值相似的3個其他數據框,例如:

score = df1[(Val*1000)/(weight*Date_diff_cumsum)]+ 
df2(Val*1000)/(weight*Date_diff_cumsum)]+...

非常感謝你

編輯:現在它正在工作,但是每當我嘗試查找最終數據框時:

score = df1.TempVal + df2.TempVal + df3.TempVal

我得到一個充滿nans的空數據框。 你知道為什么嗎? 我需要為每個ID打印所有tempVal並進行繪制

只需將權重映射為:

df["Weight"] = df["ID"].map(weights["Value"])

weights是其他數據集的位置(並且還需要將ID設置為該數據集的索引)。

您可以使用map將值從df2映射到Weight。 由於您已經通過按ID分組計算了date_diff_cumsum,因此您可以直接從df1計算tempval,

df1['Weight'] = df1['ID'].map(df2.set_index('ID')['Value'])

df1['TempVal'] = df1['Value']*1000/(df1['Weight'] * df1['Date_diff_cumsum'])

    ID  Value       Date              Date_diff_cumsum  Val       Weight    TempVal
0   1   0.000000    2017-02-13 20:54:00 0.0             0.000000    78.0    NaN
1   1   0.029598    2017-02-13 21:02:00 8.0             0.029598    78.0    0.047433
2   1   0.273000    2017-02-13 22:33:00 99.0            0.273000    78.0    0.035354
3   1   0.153000    2017-02-13 23:24:00 150.0           0.153000    78.0    0.013077

暫無
暫無

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

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