【发布时间】:2020-04-13 04:52:02
【问题描述】:
我有以下数据框
<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' 列是字符串,其他应该是 int 或 float。 我正在尝试使用 astype(int) 进行转换。我已经尝试了互联网上提到的所有选项,但仍然出现错误。
df_LondonEthnicity['Indian'] = df_LondonEthnicity['Indian'].astype(int)
错误是:
以 10 为底的 int() 的无效文字:
我也试过了
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])
还尝试将得到的字符串转换为浮点数
我很感激这方面的一些帮助。谢谢
【问题讨论】:
-
能否提供
df_LondonEthnicity的样本数据? -
stackoverflow.com/questions/18434208/…。
pd.to_numeric是正确的转换工具。如果pandas没有自动将列解析为数字 dtype,那么astype将无济于事。to_numeric允许您将所有非数字数据转换为NaN -
df_LondonEthnicity['Indian']中有什么?如果有空字符串或带有文本而不是数字的字符串,则无法转换它