panda: 更改列的数据类型
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df
Out[16]:
one two three
0 a 1.2 4.2
1 b 70 0.03
2 x 5 0
df.dtypes
Out[17]:
one object
two object
three object
df[['two', 'three']] = df[['two', 'three']].astype(float)
df.dtypes
Out[19]:
one object
two float64
three float64
如前所述在上面的评论中, convert_objects
可以用来强迫 object
列在DataFrame更合适的数据类型。
这里方法的优点是可以一次性应用到整个 DataFrame: 不需要单独选择列并使用 astype
。 如果列不能转换为non-object数据类型,则只剩下一个列。
例如该方法将强制DataFrame的列将数字字符串保存到适当的数字数据类型:
>>> vals = [['q', '1', '4.2'], ['e', '70', '0.03'], ['d', '5', '0']]
>>> df = pd.DataFrame(vals, columns=['a', 'b', 'c'])
>>> df
a b c
0 q 1 4.2
1 e 70 0.03
2 d 5 0
>>> df.dtypes # all columns have the object datatype
a object
b object
c object
>>> df.convert_objects(convert_numeric=True).dtypes # some columns can be converted
a object
b int64
c float64