在pandas中将百分比列转换为浮点数



我试图把一组列变成一个浮动对象,但我一直得到一个值错误。我试过使用.astype('float'),我仍然以同样的错误结束。下面是我现在使用的代码。


for column in pct_columns:
df[column] = df[column].apply(lambda X: float(X.replace('%',''))/100)

这是我得到的错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [127], in <cell line: 3>()
1 pct_columns = ['R_SIG_STR_pct', 'B_SIG_STR_pct', 'R_TD_pct', 'B_TD_pct']
3 for column in pct_columns:
----> 4     df[column] = df[column].apply(lambda X: float(X.replace('%',''))/100)
File ~/opt/anaconda3/envs/book_env/lib/python3.8/site-packages/pandas/core/series.py:4108, in Series.apply(self, func, convert_dtype, args, **kwds)
4106     else:
4107         values = self.astype(object)._values
-> 4108         mapped = lib.map_infer(values, f, convert=convert_dtype)
4110 if len(mapped) and isinstance(mapped[0], Series):
4111     # GH 25959 use pd.array instead of tolist
4112     # so extension arrays can be used
4113     return self._constructor_expanddim(pd_array(mapped), index=self.index)
File pandas/_libs/lib.pyx:2467, in pandas._libs.lib.map_infer()
Input In [127], in <lambda>(X)
1 pct_columns = ['R_SIG_STR_pct', 'B_SIG_STR_pct', 'R_TD_pct', 'B_TD_pct']
3 for column in pct_columns:
----> 4     df[column] = df[column].apply(lambda X: float(X.replace('%',''))/100)
ValueError: could not convert string to float: '---'

您应该关注这个确切的问题:

ValueError: could not convert string to float: '---'

两种可能的方法是:

  1. 删除行包含价值'---'之前做字符串转换浮动。
import pandas as pd
df = pd.DataFrame({
'A': ['foo', 'bar', 'foo', 'bar', 'foo', '---', 'foo', 'bar', 'foo', 'bar'],
'B': ['one', '---', 'two', 'three', 'two', 'two', 'one', 'three', 'one', 'three'],
'C': ['---', '25.84%', '---', '54.32%', '---', '42.73%', '---', '---', '---', '---']
})
df = df[~df.eq('---').any(1)]
  1. '---'的值替换为可以转换为float的值
import pandas as pd
df = pd.DataFrame({
'A': ['foo', 'bar', 'foo', 'bar', 'foo', '---', 'foo', 'bar', 'foo', 'bar'],
'B': ['one', '---', 'two', 'three', 'two', 'two', 'one', 'three', 'one', 'three'],
'C': ['---', '25.84%', '---', '54.32%', '---', '42.73%', '---', '---', '---', '---']
})
df.replace('---', '0.00%', inplace=True)

当然,您也可以将其替换为浮点值,例如0.00,但这实际上取决于您的需要。

最新更新