我有一个熊猫数据框,其中包含 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 名股票
In [44]: mom_ret = pdata.shift(1).pct_change(130)
In [45]: rank = mom_ret.rank(axis=1,ascending=False,method='first')
In [46]: rank[rank<=10]=1
In [47]: rank[rank>10]=0
如果我取行的总和,它们都等于我期望的 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。这可能吗?谢谢