pandas中如何将object类型列转换为string类型提取货币符号与数值
问题原因及字符串转换解决方案
你之前用df['new'] = str(df['amount'])是将整个amount列的Series对象整体转为了字符串,因此所有行都会返回相同的Series摘要文本,并非逐元素转换。要实现逐元素转为字符串,使用pandas内置的astype方法即可:
# pandas 1.0及以上版本推荐使用专用String类型 df['amount_str'] = df['amount'].astype('string') # 兼容所有版本的通用写法 df['amount_str'] = df['amount'].astype(str)
转换后你就可以对每个字符串做切片、匹配等操作了。
完整的货币转GBP实现
针对你最终需要换算为GBP的需求,完整实现代码如下:
import pandas as pd import numpy as np # 示例数据 df = pd.DataFrame({'date': ['2018-11-22','2018-11-23','2018-11-24'], 'amount': ['3.80p','$4.50','\N{euro sign}3.40'], 'usd-gbp':['0.82','0.83','0.84'], 'eur-gbp':['0.91','0.92','0.93']}) # 1. 转字符串格式 df['amount'] = df['amount'].astype(str) # 2. 拆分货币类型与数值 def parse_amount(s): if s.startswith('$'): return ('USD', float(s[1:])) elif s.startswith('€'): return ('EUR', float(s[1:])) elif s.endswith('p'): return ('GBP_PENNY', float(s[:-1])) return (None, None) df[['currency', 'value']] = df['amount'].apply(lambda x: pd.Series(parse_amount(x))) # 3. 汇率列转浮点类型 df[['usd-gbp', 'eur-gbp']] = df[['usd-gbp', 'eur-gbp']].astype(float) # 4. 条件计算GBP金额 df['gbp_amount'] = np.select( condlist = [ df['currency'] == 'GBP_PENNY', df['currency'] == 'USD', df['currency'] == 'EUR' ], choicelist = [ df['value'] / 100, # 便士转英镑需除以100 df['value'] * df['usd-gbp'], df['value'] * df['eur-gbp'] ], default = np.nan )
运行后得到的gbp_amount列结果如下:
| date | amount | gbp_amount |
|---|---|---|
| 2018-11-22 | 3.80p | 0.038 |
| 2018-11-23 | $4.50 | 3.69 |
| 2018-11-24 | €3.40 | 3.094 |
内容的提问来源于stack exchange,提问作者BD12
相关产品推荐
相关产品推荐

