满足特定条件时将数据填充到数据框中

时间:2020-02-24 11:09:02

标签: pandas

id       date         idx   comments
 1       01-05-2018    0      null
 2       02-05-2018    0      null
 3       03-05-2018    Y      null
 4       04-05-2018    Y      null 

idx = 0时,评论列需要更新为',对于ID(提及相应ID)和日期(提及相应的日期)”

1 个答案:

答案 0 :(得分:0)

list comprehensionzipf-strings结合使用:

df['comments'] = [f'flow reported as null for id {i} and date {d}' if idx == '0' else 'NULL' 
                  for i, d, idx in zip(df['id'], df['date'], df['idx'])]

   id        date idx                                           comments
0   1  01-05-2018   0  flow reported as null for id 1 and date 01-05-...
1   2  02-05-2018   0  flow reported as null for id 2 and date 02-05-...
2   3  03-05-2018   Y                                               NULL
3   4  04-05-2018   Y                                               NULL

或使用apply

df['comments'] = (
    df.apply(lambda x: f'flow reported as null for id {x["id"]} and date {x["date"]}' 
             if x['idx'] == '0' else 'NULL', axis=1)
)