根据具有条件的其他列设置列的值

问题描述 投票:-1回答:2

我很高兴与Pandas合作进行一些数据处理。我遇到了一个问题,它可能通过迭代这个DataFrame的行来完成,但可能有一个更优雅的解决方案。

如果col1的值高于20,我尝试将字段'desired'创建为字符串。我尝试了np.where但没有成功。

DataFrame

谁能帮我?谢谢!

python pandas numpy
2个回答
3
投票

按条件使用numpy.where获取新列:

df['desired'] = np.where(df['col1'] > 20, 'col1 is ' + df['col1'].astype(str), '')

3
投票

这应该工作:

df['desired'] = ''
df.loc[df['col1'] > 20, 'desired'] = 'col1 is ' + df['col1'].astype(str)

import pandas as pd

df = pd.DataFrame({'col1': [25, 10, 15, 21]})

df['desired'] = ''
df.loc[df['col1'] > 20, 'desired'] = 'col1 is ' + df['col1'].astype(str)

#    col1     desired
# 0    25  col1 is 25
# 1    10            
# 2    15            
# 3    21  col1 is 21

这个问题

大熊猫的力量在于持有结构化数据。只要将字符串与数字数据组合在一起,就会丢失该结构。操作字符串很繁琐,例如,您无法将“1”添加到“所需”列。

一个更好的主意

最好使用布尔列来表示所需的条件。例如:

df['desired'] = df['col1'] > 20

这将根据指定的条件给出布尔[True或False]系列。

© www.soinside.com 2019 - 2024. All rights reserved.