列中的DataFrame对象类型

2024-09-21 01:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 20 entries, 0 to 19
Data columns (total 7 columns):
Borough        20 non-null object
Indian         20 non-null object
Pakistani      20 non-null object
Bangladeshi    20 non-null object
Chinese        20 non-null object
Other_Asian    20 non-null object
Total_Asian    20 non-null object
dtypes: object(7)

只有“Borough”列是string,其他列应该是int或float。 我正在尝试使用astype(int)进行转换。我已经尝试了所有在互联网上提到的选项,但仍然得到错误

df_LondonEthnicity['Indian'] = df_LondonEthnicity['Indian'].astype(int)

错误是:

invalid literal for int() with base 10:

我也试过了

df_LondonEthnicity['Indian'] = df_LondonEthnicity.astype({'Indian': int}).dtypes

我也试过了

cols = ['Indian', 'Pakistani', 'Bangladeshi', 'Chinese', 'Other_Asian', 'Total_Asian']  

for col in cols:  # Iterate over chosen columns
  df_LondonEthnicity[col] = pd.to_numeric(df_LondonEthnicity[col])

还尝试将got字符串转换为float

如果能帮上忙我会很感激的。谢谢


Tags: columnstodfobjectcolnullintindian
1条回答
网友
1楼 · 发布于 2024-09-21 01:27:41

正如注释中指出的,您需要使用to_numeric函数

错误的意思是,您试图转换的值包含除0-9(base10)以外的字符

因此,您可以选择使用pd.to_numeric,并将所有不一致的值设置为NaN,或者以某种方式将其转换

假设你有这样一个数据帧

>>> df
       X
0    123
1   123,
2    200
3  200.1

使用pd.to_numeric将生成这样的输出。但是这些值是浮动的

>>> pd.to_numeric(df.X, errors='coerce')
0    123.0
1      NaN
2    200.0
3    200.1
Name: X, dtype: float64

另一个选择是像这样转换它

>>> df.X.str.extract(r'([\d]+)').astype(int)
     0
0  123
1  123
2  200
3  200

相关问题 更多 >

    热门问题