如何从熊猫数据框中的多列中删除字符?

时间:2019-03-31 02:51:24

标签: python python-3.x

我想从熊猫数据框中的列中删除字符。我大约有10列,每列都有字符。请参阅示例列。列类型是一个字符串,想删除字符并转换为int float列

10.2\I

10.1\Y

NAN

12.5\T

13.3\T

9.4\J

NAN

12.2\N

NAN

11.9\U

NAN

12.4\O

NAN

8.3\U

13.5\B

NAN

13.1\V

11.0\Q

11.0\X

8.200000000000001\U

NAN

13.1\T

8.1\O

9.4\N

我想删除所有字母中的'\',并将其变成一个浮点数。我不想更改NAN。

我使用了df[column name'] = df.str[:4]-它删除了一些单元格,但不是全部单元格。另外,由于出现错误,无法转换为浮动

df[column name'] = df.str[:4]

df['column name'].astype(float)

0     10.2

1     10.1

2      NaN

3     12.5

4     13.3

5     9.4\

6     8.3\

22    8.1\

27    9.4\
28     NaN
29    10.6
30    10.8
31     NaN
32    7.3\
33    9.8\
34     NaN
35    12.4
36    8.1\

仍然没有转换其他单元格

在尝试转换为浮点数时出现错误

  

ValueError:无法将字符串转换为float:'10 .2 \ I'

1 个答案:

答案 0 :(得分:0)

我可以看到您的代码无法正常工作的两个原因:

  • 在您的示例中,使用[:4]并非对所有值都有效,因为小数点前(以及显然在小数点后)的位数有所变化。
  • df['column name'] = df.str[:4]分配中,等号的右侧需要有相同的列标识符。

这是一个带有示例数据帧的解决方案,我准备了带有两个缩写列的示例数据框,如您的示例所示。它使用[:-2]从右侧截断每个值,然后在转换为float之前用原始NAN替换剩余的N。

import pandas as pd

col = pd.Series(["10.2\I","10.1\Y",'NAN','12.5\T'])
col2 = pd.Series(["11.0\Q","11.0\X",'NAN',r'8.200000000000001\U'])

df = pd.concat([col,col2],axis=1)
df.rename(columns={0:'col1',1:'col2'},inplace=True)
df

    col1     col2
0   10.2\I   11.0\Q
1   10.1\Y   11.0\X
2   NAN      NAN
3   12.5\T   8.200000000000001\U

#apply the conversion to all columns in the dataframe
for col in df:
    df[col] = df[col].str[:-2].replace('N','NAN').astype(float)

df
    col1    col2
0   10.2    11.0
1   10.1    11.0
2   NaN     NaN
3   12.5    8.2