pandas 替换一列上的多个值(您不知道)
pandas replace multiple values (that you do not know) on one column
更改列 ('Status') 中与您要分析的仅有的两个值不同的多个值的最佳方法是什么?
例如,我的 df 是:
Id Status Email Product Age
1 ok g@ A 20
5 not ok l@ J 45
1 A a@ A 27
2 B h@ B 25
2 ok t@ B 33
3 C b@ E 23
4 not ok c@ D 30
最后,我想拥有:
Id Status Email Product Age
1 ok g@ A 20
5 not ok l@ J 45
1 other a@ A 27
2 other h@ B 25
2 ok t@ B 33
3 other b@ E 23
4 not ok c@ D 30
最大的困难是我的 df 非常大,所以我不知道所有其他不同于 'ok' 和 'not ok' 的值(我想分析的值)。
提前致谢!
np.where
+ isin
df.Status=np.where(df.Status.isin(['ok','not ok']),df.Status,'Others')
df
Out[384]:
Id Status Email Product Age
0 1 ok g@ A 20
1 5 not ok l@ J 45
2 1 Others a@ A 27
3 2 Others h@ B 25
4 2 ok t@ B 33
5 3 Others b@ E 23
6 4 not ok c@ D 30
使用申请
df['Status'] = df.apply(lambda x: 'other' if x['Status'] not in ['ok', 'not ok'] else x['Status'], axis=1)
更改列 ('Status') 中与您要分析的仅有的两个值不同的多个值的最佳方法是什么?
例如,我的 df 是:
Id Status Email Product Age
1 ok g@ A 20
5 not ok l@ J 45
1 A a@ A 27
2 B h@ B 25
2 ok t@ B 33
3 C b@ E 23
4 not ok c@ D 30
最后,我想拥有:
Id Status Email Product Age
1 ok g@ A 20
5 not ok l@ J 45
1 other a@ A 27
2 other h@ B 25
2 ok t@ B 33
3 other b@ E 23
4 not ok c@ D 30
最大的困难是我的 df 非常大,所以我不知道所有其他不同于 'ok' 和 'not ok' 的值(我想分析的值)。 提前致谢!
np.where
+ isin
df.Status=np.where(df.Status.isin(['ok','not ok']),df.Status,'Others')
df
Out[384]:
Id Status Email Product Age
0 1 ok g@ A 20
1 5 not ok l@ J 45
2 1 Others a@ A 27
3 2 Others h@ B 25
4 2 ok t@ B 33
5 3 Others b@ E 23
6 4 not ok c@ D 30
使用申请
df['Status'] = df.apply(lambda x: 'other' if x['Status'] not in ['ok', 'not ok'] else x['Status'], axis=1)