Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

python - Convert pandas._period.Period type Column names to Lowercase

I have a dataset 'City' with Column names

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

I used the following code and got the column names as

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

in pandas._period.Period datatype.

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

I want the columns to be as

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

I want lowercase 'q' in my output column names.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need strftime what works with PeriodIndex:

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

Sample:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...