Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何基于两列聚合数据?_Python_Pandas_Data Science - Fatal编程技术网

Python 如何基于两列聚合数据?

Python 如何基于两列聚合数据?,python,pandas,data-science,Python,Pandas,Data Science,我有一个如上所示的表格,其中有两列(性别和年份)。我想将其转换为以下格式,如下所示。任何关于如何做到这一点的帮助都将不胜感激 您可以执行以下操作: df = pd.DataFrame({'Gender': ['m', 'm', 'm', 'm', 'f'], 'year': [2011, 2013, 2011, 2011, 2012]}) pd.crosstab(df['year'], df['Gender']) Gender f m year

我有一个如上所示的表格,其中有两列(性别和年份)。我想将其转换为以下格式,如下所示。任何关于如何做到这一点的帮助都将不胜感激

您可以执行以下操作:

df = pd.DataFrame({'Gender': ['m', 'm', 'm', 'm', 'f'],
                   'year': [2011, 2013, 2011, 2011, 2012]})
pd.crosstab(df['year'], df['Gender'])

Gender  f   m
year        
2011    0   3
2012    1   0
2013    0   1
要反转“性别”列,它将是:

pd.crosstab(df['year'], df['Gender'])[['m', 'f']]