Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.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 - Fatal编程技术网

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