【问题标题】:Advice needed: convert objects of dataframe in pandas需要的建议:在熊猫中转换数据框的对象
【发布时间】: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


【解决方案1】:

使用apply 函数。

In [34]: df = df.apply(lambda x: pd.to_numeric(x), axis=0)

In [36]: df.dtypes
Out[36]:
a    float64
b    float64
c    float64
d      int64
e      int64
f      int64
g      int64
dtype: object

【讨论】:

  • 像魅力一样工作。谢谢,很高兴知道
猜你喜欢
  • 2012-11-30
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
  • 2021-05-27
  • 1970-01-01
  • 2016-01-20
  • 2020-12-27
相关资源
最近更新 更多