[英]How to apply an if between function on a column in pandas' DataFrame
我试图通过应用如果数值在4到8的范围内,则将数值列更改为分类列,然后是“是”,否则是“否”,最简单的方法是什么? 先感谢您!
试试这个
from pandas import DataFrame
Numbers = {'set_of_numbers': [1,2,3,4,5,6,7,8,9,10]}
df = DataFrame(Numbers,columns=['set_of_numbers'])
df.loc[4 <= df.set_of_numbers <= 8, 'equal_or_lower_than_4?'] = 'True'
df.loc[df.set_of_numbers < 4, 'equal_or_lower_than_4?'] = 'False'
df.loc[df.set_of_numbers > 8, 'equal_or_lower_than_4?'] = 'False'
print (df)
Python的numpy
模块提供了一个根据条件选择元素的功能,即
numpy.where(condition[, x, y])
参数: condition :一个条件表达式,它返回布尔x,y的Numpy数组:数组(可选,即通过或不通过)
例:
s = pd.Series(range(5))
s.where(s > 1, 10)
输出:
0 10
1 10
2 2
3 3
4 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.