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

时间:2019-06-17 07:32:04

标签: python jupyter-notebook

我正在尝试通过将数值列更改为类别列来应用(如果该值在4到8之间),然后是“是”,否则是“否” 最简单的方法是什么? 预先谢谢你!

2 个答案:

答案 0 :(得分:0)

尝试这样的事情

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)

答案 1 :(得分:0)

Python的numpy模块提供了一个根据条件(即条件)选择元素的功能。

numpy.where(condition[, x, y])

参数: condition :一个条件表达式,返回布尔型的Numpy数组 x,y:数组(可选,即通过或不通过)

  • 如果所有参数–> 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