簡體   English   中英

根據第三個變量中的多個條件,在數據框中為多個子組創建一個新變量

[英]Create a new variable in dataframe for multiple subgroups, depending on multiple conditions in a third variable

我有一個數據框,其中包含一列主題 ID,一列包含日期,第三列包含評論(“可用”/“不可用”/“有問題”)。 一個例子:

import pandas as pd

df = pd.DataFrame({'ID':[1,1,1,1,2,2,2],
                   'Date':[20191219,
                           20191219,
                           20191220,
                           20191220,
                           20191219,
                           20191219,
                           20191219],
                           'Notes':['usable','usable','unusable','questionable','usable','usable','unusable']})

這給了你:

   ID      Date         Notes
0   1  20191219        usable
1   1  20191219        usable
2   1  20191220      unusable
3   1  20191220  questionable
4   2  20191219        usable
5   2  20191219        usable
6   2  20191219      unusable

對於每個主題和每個相應的日期,我想檢查字符串“有問題”或“不可用”是否出現在“注釋”列中。 如果是這種情況,我想將值“檢查”添加到與該日期對應的所有行的第三列。 輸出應如下所示:

   ID      Date         Notes Comment
0   1  20191219        usable  usable
1   1  20191219        usable  usable
2   1  20191220      unusable   check
3   1  20191220  questionable   check
4   2  20191219        usable   check
5   2  20191219        usable   check
6   2  20191219      unusable   check

有誰知道如何做到這一點?

您可以使用series.isin() + df.groupby()transformany為每個組創建條件列,其次是np.where()

c=(df['Notes'].isin(['unusable','questionable'])
                 .groupby([df['ID'],df['Date']]).transform('any'))
df['Comment']=np.where(c,'check',df['Notes'])
print(df)

   ID      Date         Notes Comment
0   1  20191219        usable  usable
1   1  20191219        usable  usable
2   1  20191220      unusable   check
3   1  20191220  questionable   check
4   2  20191219        usable   check
5   2  20191219        usable   check
6   2  20191219      unusable   check

暫無
暫無

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

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