仅当特定列中出现子字符串(或符号)时,才将值复制到另一列,否则请保持另一列不变DataFrame

2024-09-29 00:14:25 发布

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

我拥有的数据帧:

cost      total     
null      $519
null      $78
xx24
($1500)   
          $51
0.00    
($924)
$33
          $78

期望的:

cost      total     
null      $519
null      $78
xx24
($1500)   $1500
          $51
0.00    
($924)    $924
$33       $33
          $78

我尝试定义方法并使用apply(),但这也将替换'total'中已经存在的值。 我可以在新列中输入'true/false'值,但这似乎不是正确的方法


Tags: 数据方法falsetruenulltotalapplycost
2条回答

您可以使用numpy.where()实现

df['total'] = np.where(df.cost.apply(lambda x:not pd.isnull(x) and '$' in x),
                  df.cost,
                  df.total)
df['total'] = df.total.apply(lambda x:x.replace('(', '').replace(')', ''))

您可以提取()之间的值,但只能提取由^{}中的^{}选择$的行:

mask = df['cost'].str.contains('$', na=False, regex=False)

df['total'] = df['total'].mask(mask, df['cost'].str.extract(r"\((.*?)\)" , expand=False))

#another solution from copy and strip () 
#df['total'] = df['total'].mask(mask, df['cost'].str.strip('()'))
print (df)
      cost  total
0      NaN   $519
1      NaN    $78
2     xx24    NaN
3  ($1500)  $1500
4      NaN    $51
5     0.00    NaN
6   ($924)   $924
7      NaN    $78

或者,如果可能,用从()提取的值替换total中缺少的值,使用:

df['total'] = df['total'].fillna(df['cost'].str.extract(r"\((.*?)\)" , expand=False))
print (df)
      cost  total
0      NaN   $519
1      NaN    $78
2     xx24    NaN
3  ($1500)  $1500
4      NaN    $51
5     0.00    NaN
6   ($924)   $924
7      NaN    $78

相关问题 更多 >