pandas中行列转换

来源:互联网 发布:淘宝台湾版 编辑:程序博客网 时间:2024/05/04 06:38

①列转行方法

  • stack函数:pandas.DataFrame.stack(self, level=-1, dropna=True)
通过?pandas.DataFrame.stack命令查看帮助文档
[python] view plain copy
  1. Signature: pandas.DataFrame.stack(self, level=-1, dropna=True)  
  2. Docstring:  
  3. Pivot a level of the (possibly hierarchical) column labels, returning a  
  4. DataFrame (or Series in the case of an object with a single level of  
  5. column labels) having a hierarchical index with a new inner-most level  
  6. of row labels.  
  7. The level involved will automatically get sorted.  
a、对于普通的DataFrame而言,直接列索引转换到最内层行索引,生一个Series对象
[python] view plain copy
  1. In [16]: import pandas as pd  
  2.     ...: import numpy as np  
  3.     ...: df = pd.DataFrame(np.arange(6).reshape(2,3),index=['AA','BB'],columns=  
  4.     ...: ['three','two','one'])  
  5.     ...: df  
  6.     ...:  
  7. Out[16]:  
  8.     three  two  one  
  9. AA      0    1    2  
  10. BB      3    4    5  
  11.   
  12. In [17]: df.stack()  
  13. Out[17]:  
  14. AA  three    0  
  15.     two      1  
  16.     one      2  
  17. BB  three    3  
  18.     two      4  
  19.     one      5  
  20. dtype: int32  
  21.   
  22. In [18]: df.stack(level=0)  
  23. Out[18]:  
  24. AA  three    0  
  25.     two      1  
  26.     one      2  
  27. BB  three    3  
  28.     two      4  
  29.     one      5  
  30. dtype: int32  
  31.   
  32. In [19]: df.stack(level=-1)  
  33. Out[19]:  
  34. AA  three    0  
  35.     two      1  
  36.     one      2  
  37. BB  three    3  
  38.     two      4  
  39.     one      5  
  40. dtype: int32  
b、对于层次化索引的DataFrame而言,可以将指定的索引层转换到行上,默认是将最内层的列索引转换到最内层行
[python] view plain copy
  1. In [31]: import pandas as pd  
  2.     ...: import numpy as np  
  3.     ...: df = pd.DataFrame(np.arange(8).reshape(2,4),index=['AA','BB'],columns=  
  4.     ...: [['two','two','one','one'],['A','B','C','D']])  
  5.     ...: df  
  6.     ...:  
  7. Out[31]:  
  8.    two    one  
  9.      A  B   C  D  
  10. AA   0  1   2  3  
  11. BB   4  5   6  7  
  12.   
  13. In [32]: df.stack()  
  14. Out[32]:  
  15.       one  two  
  16. AA A  NaN  0.0  
  17.    B  NaN  1.0  
  18.    C  2.0  NaN  
  19.    D  3.0  NaN  
  20. BB A  NaN  4.0  
  21.    B  NaN  5.0  
  22.    C  6.0  NaN  
  23.    D  7.0  NaN  
  24.   
  25. In [33]: df.stack(level=0)  
  26. Out[33]:  
  27.           A    B    C    D  
  28. AA one  NaN  NaN  2.0  3.0  
  29.    two  0.0  1.0  NaN  NaN  
  30. BB one  NaN  NaN  6.0  7.0  
  31.    two  4.0  5.0  NaN  NaN  
  32.   
  33. In [34]: df.stack(level=1)  
  34. Out[34]:  
  35.       one  two  
  36. AA A  NaN  0.0  
  37.    B  NaN  1.0  
  38.    C  2.0  NaN  
  39.    D  3.0  NaN  
  40. BB A  NaN  4.0  
  41.    B  NaN  5.0  
  42.    C  6.0  NaN  
  43.    D  7.0  NaN  
  44.   
  45. In [35]: df.stack(level=-1)  
  46. Out[35]:  
  47.       one  two  
  48. AA A  NaN  0.0  
  49.    B  NaN  1.0  
  50.    C  2.0  NaN  
  51.    D  3.0  NaN  
  52. BB A  NaN  4.0  
  53.    B  NaN  5.0  
  54.    C  6.0  NaN  
  55.    D  7.0  NaN  
  56.   
  57. In [36]: df.stack(level=[0,1])  
  58. Out[36]:  
  59. AA  one  C    2.0  
  60.          D    3.0  
  61.     two  A    0.0  
  62.          B    1.0  
  63. BB  one  C    6.0  
  64.          D    7.0  
  65.     two  A    4.0  
  66.          B    5.0  
  67. dtype: float64  
  • unstack函数:pandas.DataFrame.unstack(self, level=-1, fill_value=None)
通过?pandas.DataFrame.unstack命令查看帮助文档
[python] view plain copy
  1. Signature: pandas.DataFrame.unstack(self, level=-1, fill_value=None)  
  2. Docstring:  
  3. Pivot a level of the (necessarily hierarchical) index labels, returning  
  4. a DataFrame having a new level of column labels whose inner-most level  
  5. consists of the pivoted index labels. If the index is not a MultiIndex,  
  6. the output will be a Series (the analogue of stack when the columns are  
  7. not a MultiIndex).  
  8. The level involved will automatically get sorted.  
a、对于普通的DataFrame而言,直接将列索引转换到行索引的最外层索引,生成一个Series对象
[python] view plain copy
  1. In [20]: df  
  2. Out[20]:  
  3.     three  two  one  
  4. AA      0    1    2  
  5. BB      3    4    5  
  6.   
  7. In [21]: df.unstack()  
  8. Out[21]:  
  9. three  AA    0  
  10.        BB    3  
  11. two    AA    1  
  12.        BB    4  
  13. one    AA    2  
  14.        BB    5  
  15. dtype: int32  
  16.   
  17. In [22]: df.unstack(0)  
  18. Out[22]:  
  19. three  AA    0  
  20.        BB    3  
  21. two    AA    1  
  22.        BB    4  
  23. one    AA    2  
  24.        BB    5  
  25. dtype: int32  
  26.   
  27. In [23]: df.unstack(-1)  
  28. Out[23]:  
  29. three  AA    0  
  30.        BB    3  
  31. two    AA    1  
  32.        BB    4  
  33. one    AA    2  
  34.        BB    5  
  35. dtype: int32  
b、对于层次化索引的DataFrame而言,和stack函数类似,似乎把两层索引当作一个整体,当level为列表时报错
[python] view plain copy
  1. In [37]: df  
  2. Out[37]:  
  3.    two    one  
  4.      A  B   C  D  
  5. AA   0  1   2  3  
  6. BB   4  5   6  7  
  7.   
  8. In [38]: df.unstack()  
  9. Out[38]:  
  10. two  A  AA    0  
  11.         BB    4  
  12.      B  AA    1  
  13.         BB    5  
  14. one  C  AA    2  
  15.         BB    6  
  16.      D  AA    3  
  17.         BB    7  
  18. dtype: int32  
  19.   
  20. In [39]: df.unstack(0)  
  21. Out[39]:  
  22. two  A  AA    0  
  23.         BB    4  
  24.      B  AA    1  
  25.         BB    5  
  26. one  C  AA    2  
  27.         BB    6  
  28.      D  AA    3  
  29.         BB    7  
  30. dtype: int32  
  31.   
  32. In [40]: df.unstack(1)  
  33. Out[40]:  
  34. two  A  AA    0  
  35.         BB    4  
  36.      B  AA    1  
  37.         BB    5  
  38. one  C  AA    2  
  39.         BB    6  
  40.      D  AA    3  
  41.         BB    7  
  42. dtype: int32  
  43.   
  44. In [41]: df.unstack(-1)  
  45. Out[41]:  
  46. two  A  AA    0  
  47.         BB    4  
  48.      B  AA    1  
  49.         BB    5  
  50. one  C  AA    2  
  51.         BB    6  
  52.      D  AA    3  
  53.         BB    7  
  54. dtype: int32  
  55.   
  56. In [42]: df.unstack(level=[0,1])  
  57.   
  58. IndexError: Too many levels: Index has only 1 level, not 2  
那再试下level=5,发现也正常,这里的level怎么理解?--遗留问题
[python] view plain copy
  1. In [44]: df  
  2. Out[44]:  
  3.    two    one  
  4.      A  B   C  D  
  5. AA   0  1   2  3  
  6. BB   4  5   6  7  
  7.   
  8. In [45]: df.unstack(level=5)  
  9. Out[45]:  
  10. two  A  AA    0  
  11.         BB    4  
  12.      B  AA    1  
  13.         BB    5  
  14. one  C  AA    2  
  15.         BB    6  
  16.      D  AA    3  
  17.         BB    7  
  18. dtype: int32  
  • melt函数:pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None)
通过?pandas.melt查看帮助文档
[python] view plain copy
  1. Signature: pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None)  
  2. Docstring:  
  3. "Unpivots" a DataFrame from wide format to long format, optionally leaving  
  4. identifier variables set.  
  5.   
  6. This function is useful to massage a DataFrame into a format where one  
  7. or more columns are identifier variables (`id_vars`), while all other  
  8. columns, considered measured variables (`value_vars`), are "unpivoted" to  
  9. the row axis, leaving just two non-identifier columns, 'variable' and  
  10. 'value'.  
首先拿普通的DataFrame实验下,看看melt函数怎么转换的
[python] view plain copy
  1. In [46]: df = pd.DataFrame(np.arange(8).reshape(2,4),index=['AA','BB'],columns=  
  2.     ...: ['A','B','C','D'])  
  3.     ...: df  
  4.     ...:  
  5. Out[46]:  
  6.     A  B  C  D  
  7. AA  0  1  2  3  
  8. BB  4  5  6  7  
  9.   
  10. In [47]: pd.melt(df,id_vars=['A','C'],value_vars=['B','D'],var_name='B|D',value  
  11.     ...: _name='(B|D)_value')  
  12. Out[47]:  
  13.    A  C B|D  (B|D)_value  
  14. 0  0  2   B            1  
  15. 1  4  6   B            5  
  16. 2  0  2   D            3  
  17. 3  4  6   D            7  
  18.   
  19. In [48]: pd.melt(df,id_vars=['A'],value_vars=['B','D'],var_name='B|D',value_nam  
  20.     ...: e='(B|D)_value')  
  21. Out[48]:  
  22.    A B|D  (B|D)_value  
  23. 0  0   B            1  
  24. 1  4   B            5  
  25. 2  0   D            3  
  26. 3  4   D            7  
  27.   
  28. In [49]: pd.melt(df,id_vars=['A'],value_vars=['B'],var_name='B',value_name='B_v  
  29.     ...: alue')  
  30. Out[49]:  
  31.    A  B  B_value  
  32. 0  0  B        1  
  33. 1  4  B        5  
结论:从上述结果可以看出,id_vars可以理解为结果需要保留的原始列,value_vars可以理解为需需要列转行的列名;var_name把列转行的列变量重新命名,默认为variable;value_name列转行对应变量的值的名称
[python] view plain copy
  1. In [50]: df1 = pd.DataFrame(np.arange(8).reshape(2,4),columns=[list('ABCD'),lis  
  2.     ...: t('EFGH')])  
  3.     ...: df1  
  4.     ...:  
  5. Out[50]:  
  6.    A  B  C  D  
  7.    E  F  G  H  
  8. 0  0  1  2  3  
  9. 1  4  5  6  7  
  10.   
  11. In [51]: pd.melt(df1,col_level=0,id_vars=['A'],value_vars=['D'])  
  12. Out[51]:  
  13.    A variable  value  
  14. 0  0        D      3  
  15. 1  4        D      7  
②行转列方法
  • unstack函数:pandas.DataFrame.unstack(self, level=-1, fill_value=None)
[python] view plain copy
  1. In [26]: df2=df.stack()  
  2.     ...: df2  
  3.     ...:  
  4. Out[26]:  
  5. AA  three    0  
  6.     two      1  
  7.     one      2  
  8. BB  three    3  
  9.     two      4  
  10.     one      5  
  11. dtype: int32  
  12.   
  13. In [27]: df2.unstack()  
  14. Out[27]:  
  15.     three  two  one  
  16. AA      0    1    2  
  17. BB      3    4    5  
  18.   
  19. In [28]: df2.unstack(0)  
  20. Out[28]:  
  21.        AA  BB  
  22. three   0   3  
  23. two     1   4  
  24. one     2   5  
  25.   
  26. In [29]: df2.unstack(1)  
  27. Out[29]:  
  28.     three  two  one  
  29. AA      0    1    2  
  30. BB      3    4    5  
  31.   
  32. In [30]: df2.unstack(-1)  
  33. Out[30]:  
  34.     three  two  one  
  35. AA      0    1    2  
  36. BB      3    4    5  


原创粉丝点击