在 pandas 中转换数据框和计数值
Transform dataframe and count values in pandas
我有一个数据框 df 看起来像
Date Type
2010 A
1998 A
2003 B
2003 C
2007 D
2010 D
2015 B
2015 B
2006 C
2006 C
1998 D
我需要对其进行转换并计算每年每种类型的出现次数。所以我的预期输出是:
1998 2003 2006 2007 2010 2015
A 1 0 0 0 1 0
B 0 1 0 0 0 2
C 0 1 2 0 0 0
D 1 0 0 1 1 0
据我了解,我需要在这里使用pivot
,对吗?
类似于 df.pivot(index='Type', columns='Data', values=???)
您可以使用 pivot_table 并传递 len
作为聚合函数:
df.pivot_table(index="Type", columns="Date", aggfunc=len).fillna(0).astype(int)
Out[152]:
Date 1998 2003 2006 2007 2010 2015
Type
A 1 0 0 0 1 0
B 0 1 0 0 0 2
C 0 1 2 0 0 0
D 1 0 0 1 1 0
像一样,你也可以使用交叉表:
pd.crosstab(df['Type'], df['Date'])
Out[153]:
Date 1998 2003 2006 2007 2010 2015
Type
A 1 0 0 0 1 0
B 0 1 0 0 0 2
C 0 1 2 0 0 0
D 1 0 0 1 1 0
如果你不想显示空值,你也可以使用:
df.groupby(['Date', 'Type']).size().reset_index()
这会给出:
Date Type 0
0 1998 A 1
1 1998 D 1
2 2003 B 1
3 2003 C 1
4 2006 C 2
5 2007 D 1
6 2010 A 1
7 2010 D 1
8 2015 B 2
我有一个数据框 df 看起来像
Date Type
2010 A
1998 A
2003 B
2003 C
2007 D
2010 D
2015 B
2015 B
2006 C
2006 C
1998 D
我需要对其进行转换并计算每年每种类型的出现次数。所以我的预期输出是:
1998 2003 2006 2007 2010 2015
A 1 0 0 0 1 0
B 0 1 0 0 0 2
C 0 1 2 0 0 0
D 1 0 0 1 1 0
据我了解,我需要在这里使用pivot
,对吗?
类似于 df.pivot(index='Type', columns='Data', values=???)
您可以使用 pivot_table 并传递 len
作为聚合函数:
df.pivot_table(index="Type", columns="Date", aggfunc=len).fillna(0).astype(int)
Out[152]:
Date 1998 2003 2006 2007 2010 2015
Type
A 1 0 0 0 1 0
B 0 1 0 0 0 2
C 0 1 2 0 0 0
D 1 0 0 1 1 0
像
pd.crosstab(df['Type'], df['Date'])
Out[153]:
Date 1998 2003 2006 2007 2010 2015
Type
A 1 0 0 0 1 0
B 0 1 0 0 0 2
C 0 1 2 0 0 0
D 1 0 0 1 1 0
如果你不想显示空值,你也可以使用:
df.groupby(['Date', 'Type']).size().reset_index()
这会给出:
Date Type 0
0 1998 A 1
1 1998 D 1
2 2003 B 1
3 2003 C 1
4 2006 C 2
5 2007 D 1
6 2010 A 1
7 2010 D 1
8 2015 B 2