簡體   English   中英

Pandas數據幀 - 行和列的多索引?

[英]Pandas dataframe - multiindex for both rows and columns?

想象一下這是我的輸入數據:

    data = [("France",    "Paris",      "Male",   "1"),
            ("France",    "Paris",      "Female", "6"),
            ("France",    "Nice",       "Male",   "2"),
            ("France",    "Nice",       "Female", "7"),
            ("Germany",   "Berlin",     "Male",   "3"),
            ("Germany",   "Berlin",     "Female", "8"),
            ("Germany",   "Munchen",    "Male",   "4"),
            ("Germany",   "Munchen",    "Female", "9"),
            ("Germany",   "Koln",       "Male",   "5"),
            ("Germany",   "Koln",       "Female", "10")]

我想把它放到像這樣的數據幀中:

Country City       Sex
                   Male     Female
France  Paris       1         6
        Nice        2         7
Germany Berlin      3         8
        Munchen     4         9
        Koln        5         10

第一部分很簡單:

df = pd.DataFrame(data, columns=["country", "city", "sex", "count"])
df = df.set_index(["country", "city"])

給我輸出:

                   sex  count
country city                 
France  Paris      Male     1
        Paris    Female     6
        Nice       Male     2
        Nice     Female     7
Germany Berlin     Male     3
        Berlin   Female     8
        Munchen    Male     4
        Munchen  Female     9
        Koln       Male     5
        Koln     Female    10

因此行是可以的,但現在我想將'sex'列中的值放入列多索引中。 有可能這樣做,如果是這樣,怎么樣?

添加列Sexlistset_index並調用unstack

df = df.set_index(["country", "city",'sex']).unstack()
#data cleaning - remove columns name sex and rename column count
df = df.rename_axis((None, None),axis=1).rename(columns={'count':'Sex'})
print (df)
                   Sex     
                Female Male
country city               
France  Nice         7    2
        Paris        6    1
Germany Berlin       8    3
        Koln        10    5
        Munchen      9    4

使用樞軸取代堆疊的另一種方法(兩者幾乎意味着相同)即

df.set_index(['country','city']).pivot(columns='sex')
count     
sex             Female Male
country city               
France  Nice         7    2
        Paris        6    1
Germany Berlin       8    3
        Koln        10    5
        Munchen      9    4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM