numpy 添加字符串B列,其中字符串存在于列A + np.where()+ pandas

mjqavswn  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(100)

我需要在数据集中添加一个辅助ID,其中包含多个个体的唯一条目。为此,我尝试使用np.where(),在我实现后,我意识到我每次都会覆盖最后一个条目。这是原始方法的一个示例:

df = pd.DataFrame({'Example':['1','2','3','4']})

df['Add'] = ''

df['Add'] = np.where(df['Example']== '1', 'One','')
df['Add'] = np.where(df['Example']== '2', 'Two','')
df['Add'] = np.where(df['Example']== '3', 'Three','')
df['Add'] = np.where(df['Example']== '4', 'Four','')

df.head()

字符串
作为一种变通方法,我尝试添加str.contains(''),以为当string为空时会计算True,并且在这种情况下只插入新字符串。具体如下:

df = pd.DataFrame({'Example':['1','2','3','4']})

df['Add'] = ''

df['Add'] = np.where(df['Example'].str.contains('')== '1', 'One','')
df['Add'] = np.where(df['Example'].str.contains('')== '2', 'Two','')
df['Add'] = np.where(df['Example'].str.contains('')== '3', 'Three','')
df['Add'] = np.where(df['Example'].str.contains('')== '4', 'Four','')

df.head()


在这种情况下,所有内容都被一个空字符串填充...
在用np.where()写之前,有没有一个简单的方法来检查单元格是否为空?

2hh7jdfx

2hh7jdfx1#

使用map

dmap = {'1': 'One', '2': 'Two', '3': 'Three', '4': 'Four'}

df['Add']  = df['Example'].map(dmap).fillna('')

字符串
输出量:

>>> df
  Example    Add
0       1    One
1       2    Two
2       3  Three
3       4   Four

相关问题