【问题标题】:Is it possible to use pandas shift function and keep the dtypes?是否可以使用 pandas shift 功能并保留 dtypes?
【发布时间】:2020-04-29 01:17:13
【问题描述】:

当使用 Pandas 的 shift 方法时,它会重新分配与原始数据帧不同的 dtype,是否可以在不发生这种情况的情况下进行转移? (但仍在使用 pandas shift)

使用fill_value 参数几乎就足够了,但如果有任何不是数字的dtype,它仍然会改变dtype。

import pandas as pd

data = [
  {'a': 1, 'b': 5.2, 'c': True},
  {'a': 5, 'b': 8.5, 'c': False},
  {'a': 2, 'b': 2.6, 'c': True}
]

df = pd.DataFrame(data)

print(df.dtypes)
print(df.shift(1).dtypes)
print(df.shift(1, fill_value=0).dtypes)

输出:

a      int64
b    float64
c       bool
dtype: object

a    float64
b    float64
c     object
dtype: object

a      int64
b    float64
c     object
dtype: object

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

您可以使用convert_dtypes 喜欢:

print (df.shift(1).convert_dtypes().dtypes)
a      Int64
b    float64
c    boolean
dtype: object

不完全是 bool 类型,而是 boolean 但我猜它比 object 更好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2017-03-15
    • 1970-01-01
    • 2020-07-10
    • 2015-04-01
    • 2015-11-07
    • 1970-01-01
    相关资源
    最近更新 更多