Skip to main content
 首页 » 编程设计

python之对 Dataframe 中的每月缩写列(Jan、Feb、Mar 等)进行排序(目前按字母顺序排序)

2024年11月01日15davidwang456

我有一个根据股票数据创建的数据框。我正在使用数据透视表按月和按年计算“关闭 > 打开”的次数。如果我每个月都使用整数,我的表的顺序是正确的。如果我每个月都使用 3 个字母的缩写,它会按字母顺序排序。如何让月份缩写以正确的顺序出现?我确信有一个简单的解决方案。

这是我的代码:

data = pd.read_csv('SPY.CSV') 
data['Date'] = pd.to_datetime(data['Date']) 
data.set_index('Date', inplace=True) 
data['UpClose'] = np.where(data['Close'] > data['Open'], 1, 0) 
data['Year'] = data.index.year 
data['Month'] = data.index.month 
data['Month'] = pd.to_datetime(data['Month'], format='%m').dt.month_name().str.slice(stop=3) 
table = pd.pivot_table(data, values='UpClose', index=['Year'],columns=['Month'], aggfunc=np.sum).reset_index().rename_axis(None, axis=1) 

输出(按字母顺序排列的月份缩写名称):

    Year    Apr  Aug  Dec  Feb  Jan  Jul  Jun  Mar  May  Nov  Oct  Sep 
0   1997    NaN  NaN  10.0 NaN  NaN  NaN  NaN  NaN  NaN  12.0 9.0  7.0 
1   1998    10.0 8.0  12.0 11.0 11.0 11.0 13.0 13.0 9.0  12.0 12.0 11.0 
2   1999    11.0 11.0 15.0 9.0  10.0 10.0 13.0 13.0 10.0 11.0 12.0 7.0 
3   2000    7.0  15.0 10.0 9.0  8.0  10.0 11.0 14.0 9.0  8.0  11.0 7.0 

如果我使用整数而不是月份缩写,这是正确的顺序:

    Year  1    2    3    4    5    6    7    8    9    10   11   12 
0   1997  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  7.0  9.0  12.0 10.0 
1   1998  11.0 11.0 13.0 10.0 9.0  13.0 11.0 8.0  11.0 12.0 12.0 12.0 
2   1999  10.0 9.0  13.0 11.0 10.0 13.0 10.0 11.0 7.0  12.0 11.0 15.0 
3   2000  8.0  9.0  14.0 7.0  9.0  11.0 10.0 15.0 7.0  11.0 8.0  10.0 

期望的输出(按正确顺序排列的月份缩写):

     Year  Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec 
0    1997  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  7.0  9.0  12.0 10.0 
1    1998  11.0 11.0 13.0 10.0 9.0  13.0 11.0 8.0  11.0 12.0 12.0 12.0 
2    1999  10.0 9.0  13.0 11.0 10.0 13.0 10.0 11.0 7.0  12.0 11.0 15.0 
3    2000  8.0  9.0  14.0 7.0  9.0  11.0 10.0 15.0 7.0  11.0 8.0  10.0 

请您参考如下方法:

正如 WeNYoBen 评论的那样,实现字符串自定义排序的一种方法是通过有序分类。

另一件需要注意的事情是,您可以对 bool 值 (True=1, False=0) 进行数值运算(例如求和),因此 np.where(data['Close'] > data['Open '], 1, 0) 真的没必要,data['Close'] > data['Open'] 就行了

import numpy as np 
import pandas_datareader as pdr      # Get SPY Data 
from pandas.api.types import CategoricalDtype 
 
# Define month order 
month_lst = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] 
 
# Create ordered month 
cat_type = CategoricalDtype(categories=month_lst, ordered=True) 
 
 
data = (pdr.get_data_yahoo('SPY',start='1997',end='2001')  
           .assign(UpClose=lambda x:x.Close > x.Open, 
                   Year=lambda x:x.index.year, 
                   Month=lambda x:x.index.month_name().astype(cat_type)) 
           .pivot_table(index='Year',columns='Month',values='UpClose',aggfunc=np.sum))