【发布时间】:2016-04-09 16:24:37
【问题描述】:
我有以下数据框,我尝试将其转换为数据类型。
In [5]:
df = pd.io.json.json_normalize(data)
df.head()
Out[5]:
a b c d e f g
2014-09-10 5.38 5.45 5.35 1769 10000002 34 6651569991
2014-09-11 5.44 5.48 5.38 1863 10000002 34 8147338425
2014-09-12 5.35 5.45 5.32 1792 10000002 34 10549259297
2014-09-13 5.41 5.48 5.3099 2136 10000002 34 9408246021
2014-09-14 5.43 5.47 5.39 2174 10000002 34 9385610951
In [6]:
df.dtypes
Out[6]:
a object
b object
c object
d object
e object
f object
g object
dtype: object
在 17.0 更新之前,我使用的解决方案是:
df = df.convert_objects(convert_numeric=True) 效果很好,但现在已弃用。现在我正在尝试使用:pd.to_numeric(df, errors='ignore'),但得到错误arg must be a list, tuple, 1-d array, or Series。
在玩了之后,我设法想出了以下解决方案,我使用 pandas 系列并迭代每一列以获得适合转换的一维数组:
for col in df:
df[col] = pd.to_numeric(pd.Series(df[col]), errors='ignore')
这是进行转换的最佳方式还是有更优雅的解决方案?我在问,因为我仍然对 Pandas 有所了解,也许它对某人有用,因为我无法找到明确的答案。
【问题讨论】:
-
df = df.apply(lambda x: pd.to_numeric(x), axis=0) --> 会得到你想要的。
标签: python-3.x pandas multidimensional-array dataframe type-conversion