我很高兴与Pandas合作进行一些数据处理。我遇到了一个问题,它可能通过迭代这个DataFrame的行来完成,但可能有一个更优雅的解决方案。
如果col1的值高于20,我尝试将字段'desired'创建为字符串。我尝试了np.where但没有成功。
谁能帮我?谢谢!
按条件使用numpy.where
获取新列:
df['desired'] = np.where(df['col1'] > 20, 'col1 is ' + df['col1'].astype(str), '')
这应该工作:
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]系列。