我有一个数据帧:
street_name eircode
Malborough Road BLT12
123 Fake Road NaN
My Street NaN
我想根据以下条件创建另一个名为unique的专栏:
我提出了这个解决方案:
# change data types
df['eircode'] = df['eircode'].astype('str')
df['street_name'] = df['street_name'].astype('str')
# get the first string from street_name column
df['first_str'] = df['street_name'].apply(lambda x: x.split()[0])
def tagging(x):
if x['eircode'] != 'nan':
return 'yes'
elif x['first_str'].isdigit() == True:
return 'yes'
else:
return 'no'
df['unique'] = df.apply(tagging, axis=1)
问题是,我必须更改数据类型,然后必须创建单独的列。有没有更优雅的方法或更简洁的方法来达到同样的效果?你知道吗
对于Pandas,最好使用按列计算;
apply
和自定义函数一起表示一个低效的、Python级别的按行循环。你知道吗可以使用
|
操作符提供这些单独的条件,然后将生成的布尔数组映射到yes
和no
。第一个条件只是查看eircode
是否为null,第二个条件使用正则表达式检查street_name
是否以数字开头:相关问题 更多 >
编程相关推荐