【问题标题】:How to remove the characters from multiple columns in pandas data frame?如何从熊猫数据框中的多列中删除字符?
【发布时间】:2019-03-31 02:51:23
【问题描述】:

我想从 pandas 数据框中的列中删除字符。我有大约 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:无法将字符串转换为浮点数:'10.2\I'

【问题讨论】:

  • 嗨!坦率地说,解析您的帖子非常困难。请使用一些可用的降价/代码标签等更清楚地格式化它,然后我相信人们会很乐意提供帮助。

标签: python python-3.x


【解决方案1】:

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

  • 使用[:4] 不适用于您的示例中的所有值,因为小数点前(显然小数点后)的位数会有所不同。
  • 在df['column name'] = df.str[:4] 赋值中,等号右侧需要有相同的列标识符。

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

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

【讨论】:

    猜你喜欢
    • 2017-07-27
    • 2021-09-10
    • 2016-01-29
    • 2018-03-23
    • 2021-08-12
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    相关资源
    最近更新 更多