Python 数据透视
我正在尝试透视这些数据:Python 数据透视,python,pandas,Python,Pandas,我正在尝试透视这些数据: ID UserID 1 a1 1 a2 2 a1 2 a3 进入数据帧,如: UserID a1 a2 a3 1 1 1 0 2 1 0 1 我试过做下面的df=pd.pivot\u表(df,index='UserID',columns='ID'),但它给了我一个数据错误:没有要聚合的数值类型。我能做什么?第一列是索引,所以有必要
ID
UserID
1 a1
1 a2
2 a1
2 a3
进入数据帧,如:
UserID a1 a2 a3
1 1 1 0
2 1 0 1
我试过做下面的
df=pd.pivot\u表(df,index='UserID',columns='ID'
),但它给了我一个数据错误:没有要聚合的数值类型。我能做什么?第一列是索引
,所以有必要将索引='UserID'
更改为索引=df.index
此外,聚合函数是
解决方案包括:
或()解决方案-通过索引
和列一起,聚合大小
并通过以下方式重塑:
pandas bellow 0.20.1解决方案-通过以下方式将索引转换为列:
编辑:
似乎索引也可以通过索引名来选择(不确定它是否在0.20.1以下工作):
df = pd.pivot_table(df, index=df.index, columns=df['ID'], aggfunc='size', fill_value=0)
print (df)
ID a1 a2 a3
UserID
1 1 1 0
2 1 0 1
df = pd.crosstab(df.index,df['ID'])
print (df)
ID a1 a2 a3
row_0
1 1 1 0
2 1 0 1
df = df.groupby(['UserID','ID']).size().unstack(fill_value=0)
print (df)
ID a1 a2 a3
UserID
1 1 1 0
2 1 0 1
df = df.reset_index().groupby(['UserID','ID']).size().unstack(fill_value=0)
print (df)
ID a1 a2 a3
UserID
1 1 1 0
2 1 0 1
df = pd.pivot_table(df, index='UserID', columns='ID', aggfunc='size', fill_value=0)
print (df)
ID a1 a2 a3
UserID
1 1 1 0
2 1 0 1