【问题标题】:pandas apply changing dtypepandas 应用更改 dtype
【发布时间】:2018-08-29 13:25:38
【问题描述】:

我正在尝试将 pandas 数据框转换为一系列元组:

示例输入:

df = pd.DataFrame([[1,2,3.0],[3,4,5.0]])

期望的输出:

0    (1, 2, 3.0)
1    (3, 4, 5.0)
dtype: object    

但是,pandas 似乎将我的整数列强制为浮点数。

我试过了

import pandas as pd

df = pd.DataFrame([[1,2,3.0],[3,4,5]])
print(df)
print(df.dtypes)
print(df.apply(tuple,axis=1,reduce=False).apply(str))

实际输出:

   0  1    2
0  1  2  3.0
1  3  4  5.0

0      int64
1      int64
2    float64
dtype: object

0    (1.0, 2.0, 3.0)
1    (3.0, 4.0, 5.0)
dtype: object

This question 建议使用reduce=False,但这对我来说没有任何改变。

有人能解释一下为什么 pandas 会在某处强制转换数据类型吗?

【问题讨论】:

  • 好吧,强制的 原因pd.DataFrame.apply 从每一行创建一个系列,不能是 int 的系列(因为有一个 float ),因此向上转换为 float。 @pir 已修复。

标签: python python-3.x pandas


【解决方案1】:

pandas.DataFrame.itertuples

避免强迫你的整数浮动

pd.Series([*df.itertuples(index=False)])

0    (1, 2, 3.0)
1    (3, 4, 5.0)
dtype: object

zip, map, splat...魔法

pd.Series([*zip(*map(df.get, df))])

0    (1, 2, 3.0)
1    (3, 4, 5.0)
dtype: object

【讨论】:

  • 这看起来超级漂亮。
  • 替代:df.astype(object).apply(tuple, axis=1)
【解决方案2】:

添加python2.7兼容解决方案:

In [3]: pd.Series(tuple(i) for i in df.itertuples())
Out[4]:
0    (0, 1, 2, 3.0)
1    (1, 3, 4, 5.0)
dtype: object

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 2019-05-29
    • 2018-10-14
    • 1970-01-01
    • 2020-12-07
    • 2017-10-20
    • 2013-01-06
    相关资源
    最近更新 更多