gpt4 book ai didi

python - Pandas 重新采样丢弃列

转载 作者:行者123 更新时间:2023-12-01 02:56:14 26 4
gpt4 key购买 nike

Pandas 在重新采样时删除了我的一列,我不明白为什么。我读到,如果列没有正确的数字类型,就会发生这种情况,但这里的情况并非如此:

import pandas;

# movements is the target data frame with daily movements
movements = pandas.DataFrame(columns=['date', 'amount', 'cash']);
movements.set_index('date', inplace=True);

# df is a movement to add
df = pandas.DataFrame({'amount': 179,
'cash': 100.00},
index=[pandas.Timestamp('2015/12/31')]);
print(df); print(df.info()); print();

# add df to movements and resample movements
movements = movements.append(df).resample('D').sum().fillna(0);
print(movements); print(movements.info());

结果:

            amount   cash
2015-12-31 179 100.0
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1 entries, 2015-12-31 to 2015-12-31
Data columns (total 2 columns):
amount 1 non-null int64
cash 1 non-null float64
dtypes: float64(1), int64(1)
memory usage: 24.0 bytes
None

cash
2015-12-31 100.0
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1 entries, 2015-12-31 to 2015-12-31
Freq: D
Data columns (total 1 columns):
cash 1 non-null float64
dtypes: float64(1)
memory usage: 16.0 bytes
None

我注意到只有当 cash 是 float 时才会发生下降,即如果在上面的代码中 cash 设置为 100 (int ) 而不是 100.00,那么所有列都是 int 并且 amount 不会被删除。

有什么想法吗?

最佳答案

问题是当您创建移动 DF 时,列的日期类型设置为对象。

如果您预先设置列类型或稍后将其更改为数字类型,它应该可以工作。

movements.append(df).apply(pd.to_numeric).resample('D').sum().fillna(0)
Out[100]:
amount cash
2015-12-31 179 100.0

关于python - Pandas 重新采样丢弃列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44191062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com