基于其他列值标记行

2024-10-01 09:17:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

street_name        eircode
Malborough Road    BLT12
123 Fake Road      NaN
My Street          NaN

我想根据以下条件创建另一个名为unique的专栏:

  1. 如果它有eircode,则在unique列中返回“yes”,然后
  2. 如果没有eircode,请检查街道名称中的第一个字符串:
    • 如果第一个字符串是数字,则在unique列中返回“yes”
    • 如果不是,则在unique列中返回“no”

我提出了这个解决方案:

  1. 我将street\u nameeircode两列的数据类型都更改为string
  2. 使用lambda函数获取第一个字符串
  3. 定义了要应用于数据帧的标记函数

# 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)

问题是,我必须更改数据类型,然后必须创建单独的列。有没有更优雅的方法或更简洁的方法来达到同样的效果?你知道吗


Tags: 数据no字符串namestreetdfreturnnan
2条回答

对于Pandas,最好使用按列计算;apply和自定义函数一起表示一个低效的、Python级别的按行循环。你知道吗

df = pd.DataFrame({'street_name': ['Malborough Road', '123 Fake Road', 'My Street'],
                   'eircode': ['BLT12', None, None]})

cond1 = df['eircode'].isnull()
cond2 = ~df['street_name'].str.split(n=1).str[0].str.isdigit()

df['unique'] = np.where(cond1 & cond2, 'no', 'yes')

print(df)

  eircode      street_name unique
0   BLT12  Malborough Road    yes
1    None    123 Fake Road    yes
2    None        My Street     no

可以使用|操作符提供这些单独的条件,然后将生成的布尔数组映射到yesno。第一个条件只是查看eircode是否为null,第二个条件使用正则表达式检查street_name是否以数字开头:

df['unique'] = ((~df.eircode.isnull()) | (df.street_name.str.match('^[0-9]'))).map({True:'yes',False:'no'})
>>> df
       street_name eircode unique
0  Malborough Road   BLT12    yes
1    123 Fake Road     NaN    yes
2        My Street     NaN     no

相关问题 更多 >