繁体   English   中英

如何在熊猫数据框的列上应用if函数

[英]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数组:数组(可选,即通过或不通过)

  • 如果所有参数–> condition,x和y都在numpy.where()中传递,则它将返回x和y中选择的元素,具体取决于条件产生的布尔数组中的值。 所有3个数组的大小必须相同。
  • 如果不传递x&y参数,并且仅传递条件参数,则它将返回一个数组元组(每个轴一个),其中包含条件返回的布尔numpy数组中True元素的索引。

例:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM