使用条件在Pandas数据框中生成新列 [英] Using conditional to generate new column in pandas dataframe
本文介绍了使用条件在Pandas数据框中生成新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫数据框,如下所示:
I have a pandas dataframe that looks like this:
portion used
0 1 1.0
1 2 0.3
2 3 0.0
3 4 0.8
我想基于used
列创建一个新列,以使df
看起来像这样:
I'd like to create a new column based on the used
column, so that the df
looks like this:
portion used alert
0 1 1.0 Full
1 2 0.3 Partial
2 3 0.0 Empty
3 4 0.8 Partial
- 基于 创建新的
- 如果
used
是1.0
,则alert
应该是Full
. - 如果
used
是0.0
,则alert
应该是Empty
. - 否则,
alert
应该为Partial
. - Create a new
alert
column based on - If
used
is1.0
,alert
should beFull
. - If
used
is0.0
,alert
should beEmpty
. - Otherwise,
alert
should bePartial
.
alert
列
做到这一点的最佳方法是什么?
What's the best way to do that?
推荐答案
您可以定义一个返回不同状态"Full","Partial","Empty"等的函数,然后使用df.apply
来应用该函数每行.请注意,您必须传递关键字参数axis=1
以确保它将参数应用于行.
You can define a function which returns your different states "Full", "Partial", "Empty", etc and then use df.apply
to apply the function to each row. Note that you have to pass the keyword argument axis=1
to ensure that it applies the function to rows.
import pandas as pd
def alert(c):
if c['used'] == 1.0:
return 'Full'
elif c['used'] == 0.0:
return 'Empty'
elif 0.0 < c['used'] < 1.0:
return 'Partial'
else:
return 'Undefined'
df = pd.DataFrame(data={'portion':[1, 2, 3, 4], 'used':[1.0, 0.3, 0.0, 0.8]})
df['alert'] = df.apply(alert, axis=1)
# portion used alert
# 0 1 1.0 Full
# 1 2 0.3 Partial
# 2 3 0.0 Empty
# 3 4 0.8 Partial
这篇关于使用条件在Pandas数据框中生成新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文