使用默认值填充数据帧列,如果findall返回无匹配项。

2024-04-18 04:14:15 发布

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

我尝试默认为findall方法返回0或找不到任何内容的字符串值。你知道吗

已尝试:

df['C'] = np.where(df['A']=='123',df['B'].str.findall('listofvalues').apply(', '.join), ''), 'N/A'

以及:

df['C'] = np.where(df['A']=='123',df['B'].str.findall('listofvalues').apply(', '.join), '') | df['C']='N/A'

还有其他一些变化。你知道吗

input  
A      B  
123    A B C  
123    B C D  
123    X Y Z  
321    E B G  
321    H I B  

desired output  
A      B        C  
123    A B C    B, C  
123    B C D    B, C  
123    X Y Z    **N/A**  
321    E B G  
321    H I B  

这很有效。。。我只想把它合并成一行

df['C'] = np.where(df['A']=='123',df['B'].str.findall('listofvalues').apply(', '.join), ''), 'N/A'
df['C'] = np.where(df['A']=='123', df['C'].replace(r'', 'N/A'), df['C'])

Tags: 方法字符串内容dfinputoutputnpwhere
1条回答
网友
1楼 · 发布于 2024-04-18 04:14:15

值得注意的是.str也适用于列表。如果.str.len大于1,则可以使用.str[0]对值进行切片,而不是join。你知道吗

(df['B']
 .findall('listofvalues')
 .pipe(lambda s: s.where(s.str.len() >= 1, ['N/A'])
 .str[0])

相关问题 更多 >