【发布时间】:2018-07-26 21:29:37
【问题描述】:
我对 python pandas 中的类型转换感到困惑
df = pd.DataFrame({'a':['1.23', '0.123']})
type(df['a'])
df['a'].astype(float)
这里df是一个pandas系列,它的内容是2个字符串,然后我可以在这个pandas系列上应用astype(float),它正确地将所有字符串转换为float。不过
df['a'][1].astype(float)
给我 AttributeError: 'str' object has no attribute 'astype'。我的问题是:怎么可能?我可以将整个系列从字符串转换为浮点数,但我无法将这个系列的条目从字符串转换为浮点数?
另外,我加载了我的原始数据集
df['id'].astype(int)
它生成 ValueError: invalid literal for int() with base 10: ''
这似乎表明我的df['id'] 中有一个空白。所以我通过输入来检查它是否是真的
'' in df['id']
它说的是假的。所以我很困惑。
【问题讨论】:
-
你必须像这样使用df['a'].iloc[1].astype(float),它不会抛出错误
标签: python pandas type-conversion