python - 仅当特定列中出现子字符串(或符号)时才将值复制到另一列,否则将另一列保持不变 DataFrame
问题描述
我有数据框:
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'中已经存在的值。我可以将“真/假”值放入新列,但这似乎不是正确的方法。
解决方案
您可以提取之间的值,()
但仅适用于由in$
选择的行:Series.str.contains
Series.mask
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
推荐阅读
- python-3.x - 如何计算csv文件行中句子的代词、名词和动词
- android-layout - Android:布局重力
- c# - 更改操作系统级别虚拟内存设置和打开 LargeAddressAware 标志的含义?
- asp.net - 我尝试使用移动端通过web api提供的access_token从google api获取用户信息,但出现401错误
- javascript - 代码块在 api 调用得到响应之前运行
- codenameone - 当我保存 theme.res 文件时,为什么“仅顶部”矩形边框变为“仅底部”?
- javascript - 如何在 html 页面中使用 Javascript 获取简单的日历窗口
- javascript - 我想要一个 OOP 解决方案,当我单击 div 时会发生某些事情
- php - 从文件获取内容时发出警告,如果使用“move_uploaded_file()”和“file_get_contents()”
- java - 没有 block() 就不会发送请求