【问题标题】:Stripping characters out of a dataframe and converting remaining characters to a float从数据框中剥离字符并将剩余字符转换为浮点数
【发布时间】:2019-08-30 11:18:56
【问题描述】:

希望从我的 pandas 数据框中的整个列中删除英镑字符,并将剩余的字符串转换为浮点数。

我尝试过替换方法,也尝试过拆分方法。

OA_data['COST (£) charged to Wellcome (inc VAT when charged)'] = OA_data.loc[OA_data['COST (£) charged to Wellcome (inc VAT when charged)']
    .astype(str)
    .str.contains('£'),'COST (£) charged to Wellcome (inc VAT when charged)']
    .replace('£','')

OA_data['向 Wellcome 收取的费用(英镑)(收取时包括增值税)'] = OA_data['向惠康收取的费用(英镑)(收取时包括增值税)'].str.split('英镑', expand =真)

我希望数据框列中的字符串没有英镑符号,但两种方法的实际结果都是仍然包含英镑符号的列。

【问题讨论】:

  • 你能展示你创建的数据框,它的一部分吗?还有你写的代码。

标签: python pandas csv


【解决方案1】:

试试这个:

OA_data['COST (£) charged to Wellcome (inc VAT when charged)'].apply(lambda x: float(x.replace('£',' ')))

例子:

import pandas as pd
df=pd.DataFrame()
df['a']=['1£','3','5£','6 £']
df['a'].apply(lambda x: float(x.replace('£',' ')))

df['a']

Output:

0    1.0
1    3.0
2    5.0
3    6.0
Name: a, dtype: float64

请记住,您必须删除所有字符,因此如果有其他字符,也必须删除。

我想你不会想从列名中删除它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 2013-11-04
    • 2018-11-30
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多