将pandas._period.Period类型的列名称转换为小写

发布于 2021-01-29 15:04:25

我有一个带有列名称的数据集“城市”

2000-01,2000-02,2000-03,2000-04,2000-05,......,2010-08,2010-09,2010-10,2010-11,2010-12.

我使用以下代码,并将列名命名为

2000Q1 , 2000Q2, 2000Q3, ......, 2010Q4

在pandas._period.Period数据类型中。

def Problem():
    hd = pd.read_csv('City.csv')
    hd = hd.groupby(pd.PeriodIndex(hd.columns, freq='Q'), axis =1).mean()
    return hd
Problem()

我希望列为

2000q1, 2000q2, 2000q3, ....... ,2010q4

我希望在输出列名称中使用小写字母“ q”。

谢谢。

关注者
0
被浏览
68
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您需要使用strftime什么PeriodIndex

    hd.columns = hd.columns.strftime('%Yq%q')
    

    样品:

    hd = pd.DataFrame({'2000-01':[1,3], '2000-05':[5,6]})
    hd = hd.groupby(pd.PeriodIndex(hd.columns, freq='Q'), axis =1).mean()
    print (hd)
       2000Q1  2000Q2
    0       1       5
    1       3       6
    
    hd.columns = hd.columns.strftime('%Yq%q')
    print (hd)
       2000q1  2000q2
    0       1       5
    1       3       6
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看