![](/img/trans.png)
[英]How to Conditionally Fill Pandas Column based on Cell Values in another column
[英]How to fill null values in a column conditionally in pandas
我有以下數據框:
time label
2020-03-03 08:35:03.585 ok
2020-03-03 08:05:01.288 ok
2020-03-03 11:50:01.944 faulty
2020-03-03 08:45:04.540 ok
2020-03-12 10:30:02.227 None
2020-03-12 11:10:02.385 None
2020-03-05 11:15:03.526 None
2020-03-10 10:55:01.084 faulty
2020-03-05 11:35:04.563 None
我只想在time
小於2020-03-10
label
列中填充空值。
我試過
df[df["label"].isna()] =np.where(df['triggerTs'] < '2020-03-10', 'ok' ,'no label')
但顯然這不是正確的方法,因為返回此錯誤
ValueError: Must have equal len keys and value when setting with an iterable
在您的解決方案中,必須過濾兩側的缺失行,以便為label
列分配相同長度的數組:
m = df["label"].isna()
df.loc[m, 'label'] = np.where(df.loc[m, 'time'] < '2020-03-10', 'ok' ,'no label')
print (df)
time label
0 2020-03-03 08:35:03.585 ok
1 2020-03-03 08:05:01.288 ok
2 2020-03-03 11:50:01.944 faulty
3 2020-03-03 08:45:04.540 ok
4 2020-03-12 10:30:02.227 no label
5 2020-03-12 11:10:02.385 no label
6 2020-03-05 11:15:03.526 ok
7 2020-03-10 10:55:01.084 faulty
8 2020-03-05 11:35:04.563 ok
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.