重新索引数据透视表索引是否按顺序排列?

时间:2019-12-26 22:45:48

标签: python pandas matplotlib pivot-table

在这里编辑是数据框的局部视图

     Day        Forecast     Temperatures  City
0   Tonight     Partly Cloudy   46         DC
1   Thursday    Mostly Cloudy   44         DC
2   Tonight     Mostly Sunny    71         Mia
3   Thursday    Partly Sunny    73         Mia

我在数据框上使用了数据透视表,并以升序对其进行排序。

 weather.pivot_table(index=['Day'], values='Temperatures',columns = 'City', aggfunc='mean')

结果

 City     Mia   DC

 Day        
Friday    72    51
Saturday  74    50
Sunday    67    55
Thursday  73    44
Tonight   71    46

如何重新按顺序排列索引表索引“天”(今天晚上,星期四,星期五,星期六,星期日)

  City    Mia   DC

 Day
Tonight   71    46  
Thursday  73    44  
Friday    72    51
Saturday  74    50
Sunday    67    55

2 个答案:

答案 0 :(得分:1)

从字面上重新索引:

df = weather.pivot_table(index=['Day'], ...)
new_index = ['Tonight', 'Thursday', 'Friday', 'Saturday', 'Sunday']
df.reindex(new_index)

P.S。我撤回删除NaN的建议。它们在这里是有原因的,应该保留以进行进一步处理。

答案 1 :(得分:0)

尝试一下,如果您有那样的风景,我会添加更多数据:

import pandas as pd
from io import StringIO
data = """
Day,Forecast,Temperatures,City
Tonight,Partly Cloudy,46,DC
Thursday, Mostly Cloudy,44,DC
Tonight,Mostly Sunny,71,Mia
Thursday,Partly Sunny,73,Mia
Friday,Partly Sunny,12,Mia
Friday,Partly Sunny,12,CA
"""
df = pd.read_csv(StringIO(data),sep=',')
print(df.pivot_table(index=['Day'], values='Temperatures',columns = 'City', aggfunc='mean').reindex(['Tonight', 'Monday','Tuesday','Wednesday','Thursday','Friday']).fillna(0))

结果:

City       CA  DC Mia
Day                  
Tonight        46  71
Monday               
Tuesday              
Wednesday            
Thursday       44  73
Friday     12      12