簡體   English   中英

如何使熊貓多索引數據框成為只有一列行的簡單表?

[英]How to make the pandas multi-index data frame a simple table with only one column rows?

我從網站http://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html比較SQL與Pandas,然后發現在熊貓和sql中,groupby函數的結果不同。

例如:
在大熊貓中:

import pandas as pd
import numpy as np

df = pd.read_csv('https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/tips.csv')
df.head()

g = df.groupby(['smoker', 'day']).agg({'tip': [np.size, np.mean]})
print(g)

得到:

             tip          
             size      mean
smoker day                 
No     Fri    4.0  3.187500
       Sat   45.0  3.361556
       Sun   57.0  3.386491
       Thur  45.0  3.122667
Yes    Fri   15.0  3.114000
       Sat   41.0  3.048049
       Sun   19.0  3.595789
       Thur  17.0  3.030000

如何獲得像SQL給定的輸出?

  smoker   day  tip_size  tip_mean
0     No   Fri         4  2.812500
1     No   Sat        45  3.102889
2     No   Sun        57  3.167895
3     No  Thur        45  2.673778
4    Yes   Fri        15  2.714000
5    Yes   Sat        41  2.701707
6    Yes   Sun        19  3.516842
7    Yes  Thur        17  3.030000

查看g.reset_index()方法。

這樣可以解決多重索引的問題。

對於列,我建議使用get_level_values()方法展平

g.columns = g.columns.get_level_values(1) + '_' + g.get_level_values(0)

還要注意熊貓集團的文檔:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html

as_index : boolean, default True. 

對於聚合輸出,返回帶有組標簽的對象作為索引。 僅與DataFrame輸入有關。 as_index=False實際上是“ SQL風格”的分組輸出

我找到了答案。

g = g.reset_index()
print(g)

得到:

  smoker   day   tip          
                size      mean
0     No   Fri   4.0  2.812500
1     No   Sat  45.0  3.102889
2     No   Sun  57.0  3.167895
3     No  Thur  45.0  2.673778
4    Yes   Fri  15.0  2.714000
5    Yes   Sat  42.0  2.875476
6    Yes   Sun  19.0  3.516842
7    Yes  Thur  17.0  3.030000

現在, g.column.values給出:

array([('smoker', ''), ('day', ''), ('tip', 'size'), ('tip', 'mean')],
      dtype=object)

使用列表理解,我們可以獲得所需的列名

g.columns = ['_'.join(e)  if e[1] else ''.join(e)  for e in g.columns.values]
print(g)

這給出:

  smoker   day  tip_size  tip_mean
0     No   Fri       4.0  2.812500
1     No   Sat      45.0  3.102889
2     No   Sun      57.0  3.167895
3     No  Thur      45.0  2.673778
4    Yes   Fri      15.0  2.714000
5    Yes   Sat      42.0  2.875476
6    Yes   Sun      19.0  3.516842
7    Yes  Thur      17.0  3.030000

暫無
暫無

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

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