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
列
最好的方法是什么?
推荐答案
你可以定义一个函数来返回你的不同状态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(row):
if row['used'] == 1.0:
return 'Full'
elif row['used'] == 0.0:
return 'Empty'
elif 0.0 < row['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 数据框中生成新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用条件在 pandas 数据框中生成新列


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01