我需要将单个条件应用于数据帧的 3 列,并在不使用 or 语句的情况下更改第四列的值。
我可以用 np.where
来做但如果列数很大,就会花费很多时间
import pandas as pd
import numpy as np
df = pd.DataFrame({'a':[1,2,3,4],'b':[1,3,6,7],'c':[4,6,4,1], 'd':['p','f','p','u'],'e':['a','a','b','c']})
df['d'] = np.where(df.a > 4 | df.b > 4 | df.c > 4 , 'p',df['d'])
df = pd.DataFrame({'a':[1,2,3,4,5],'b':[1,3,6,7],'c':[4,6,4,1], 'd':['p','f','p','f']})
df['d']=np.where(df.a > 4 | df.b > 4 | df.c > 4 , 'p','f')
我需要某种方法来实现相同的条件 > , <
到列列表而不使用或 for every。
最佳答案
使用DataFrame.gt与np.where
一起:
import numpy as np
import pandas as pd
df = pd.DataFrame({'a':[1,2,3,4],'b':[1,3,6,7],'c':[4,6,4,1], 'd':['p','f','p','u'],'e':['a','a','b','c']})
# create a subset of a dataframe on which you want to check condition
new_df = df[['a','b','c']]
mask = new_df.gt(4).any(axis=1) # check if any value is greater than 4
df['d'] = np.where(mask, 'p','f')
print(df)
输出:
a b c d e
0 1 1 4 f a
1 2 3 6 p a
2 3 6 4 p b
3 4 7 1 p c
关于python - 如何将单个条件应用于数据框中的列列表并将值添加到第四列而不使用多个 OR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54670877/