我有以下数据帧
<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
如果能帮上忙我会很感激的。谢谢
正如注释中指出的,您需要使用
to_numeric
函数错误的意思是,您试图转换的值包含除
0-9
(base10)以外的字符因此,您可以选择使用
pd.to_numeric
,并将所有不一致的值设置为NaN
,或者以某种方式将其转换假设你有这样一个数据帧
使用
pd.to_numeric
将生成这样的输出。但是这些值是浮动的另一个选择是像这样转换它
相关问题 更多 >
编程相关推荐