使用通配符对多个列进行计数

2024-10-02 18:19:49 发布

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

我想复制Excel中的数据集

enter image description here

我的python代码如下所示:

data_frames = [df_mainstore, df_store_A, df_store_B]
df_merged = reduce(lambda  left,right: pd.merge(left,right,on=["Id_number"], how='outer'), data_frames)
print(df_merged)

由于我合并了多个数据帧(列编号和名称可能不同),因此写出在本example中完成的所有列也会很繁琐:

isY = lambda x:int(x=='Y')
countEmail= lambda row: isY(row['Store Contact A']) + isY(row['Store B Contact'])
df['Contact Email'] = df.apply(countEmail,axis=1)

我也很难表达:isY = lambda x:int(x=='@')

如何以Excel中类似的方式添加“联系人有电子邮件”列


Tags: 数据storelambdarightdfdataframescontact
2条回答

您可以使用pandas.Series.str.contains

df_merged['Contact has Email'] = df_merged['Store Contact A'].str.contains('@', na=False)|df_merged['Store B Contact'].str.contains('@', na=False)

您可以使用filter选择其中包含Contact的列,然后使用str.contains和右边的pattern for email address,最后您希望每行有any,因此:

#data sample
df_merged = pd.DataFrame({'id': [0,1,2,3], 
                          'Store A': list('abcd'),
                          'Store Contact A':['aa@bb.cc', '', 'e', 'f'], 
                          'Store B': list('ghij'),
                          'Store B Contact':['kk@ll.m', '', 'nn@ooo.pp', '']})

# define the pattern as in the link
pat = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
# create the column as wanted
df_merged['Contact has Email'] = df_merged.filter(like='Contact')\
                                          .apply(lambda x: x.str.contains(pat))\
                                          .any(1)

print (df_merged)
   id Store A Store Contact A Store B Store B Contact  Contact has Email
0   0       a        aa@bb.cc       g         kk@ll.m               True
1   1       b                       h                              False
2   2       c               e       i       nn@ooo.pp               True
3   3       d               f       j                              False

相关问题 更多 >