我需要在数据集中添加一个辅助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()
写之前,有没有一个简单的方法来检查单元格是否为空?
1条答案
按热度按时间2hh7jdfx1#
使用
map
:字符串
输出量:
型