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
您可以使用numpy.where()实现
您可以提取} 中的^{} 选择
()
之间的值,但只能提取由^{$
的行:或者,如果可能,用从
()
提取的值替换total
中缺少的值,使用:相关问题 更多 >
编程相关推荐