Pandas重采样不累加

2024-09-27 02:25:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框,包含461只股票的收盘价。在

In [43]: pdata
Out[43]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 3418 entries, 2000-01-03 00:00:00 to 2013-02-06 00:00:00
Columns: 461 entries, AKM to ZIM
dtypes: float64(461)

我正在根据过去130天的回报率对股票进行排名,并选出表现最好的10家

^{pr2}$

如果我取行的总和,它们都等于10,正如我所料。在

In [48]: x=rank.groupby(rank.sum(axis=1))

In [49]: x.sum()
Out[49]: 
<class 'pandas.core.frame.DataFrame'>
Index: 1 entries, 10.0 to 10.0          # all rows sum to 10 as expected.
Columns: 461 entries, AKM to ZIM
dtypes: float64(461)

然后我重新对数据帧进行采样,如下所示

In [50]: port = rank.resample('20B', how='first')

In [51]: y=port.groupby(port.sum(axis=1))

但现在当我把行数相加时,它们不等于10?在

In [52]: y.sum()
Out[52]: 
<class 'pandas.core.frame.DataFrame'>
Index: 4 entries, 10.0 to 13.0          # 4 entries ranging between 10 and 13??
Columns: 461 entries, AKM to ZIM
dtypes: float64(461)

我不明白为什么会这样。我做错什么了还是这是个错误?在

我刚刚意识到如果我用0代替NaN,我就没有问题了。在

In [67]: rank=rank.fillna(0)

In [68]: x=rank.groupby(rank.sum(axis=1))

In [69]: x.sum()
Out[69]: 
<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, 0.0 to 10.0     # 2 entries, 0 and 10
Columns: 461 entries, AKM to ZIM
dtypes: float64(461)

In [70]: port = rank.resample('20B', how='first')

In [71]: y=port.groupby(port.sum(axis=1))

In [72]: y.sum()
Out[72]: 
<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, 0.0 to 10.0    # 2 entries again, 0 and 10
Columns: 461 entries, AKM to ZIM
dtypes: float64(461)

但我想重新取样,而不是用0填充NaN's。有可能吗? 谢谢


Tags: columnstoincoredataframepandasportout
1条回答
网友
1楼 · 发布于 2024-09-27 02:25:47

{non-reason>从每个列中取一个值,因为这是第一个。这就是为什么在NAs中填充0可以得到正确的答案。要在不填充NAs的情况下获得所需的行为,可以将自定义函数传递给how,而不管它是否为NA:

In [47]: port = rank.resample('20B', how=lambda x: x.ix[0])

In [48]: y=port.groupby(port.sum(axis=1))

In [49]: y.sum()
Out[49]: 
<class 'pandas.core.frame.DataFrame'>
Index: 1 entries, 10.0 to 10.0
Columns: 461 entries, AKM to ZIM
dtypes: float64(461)

相关问题 更多 >

    热门问题