如何使用交叉表显示频率列表?

时间:2017-07-22 07:51:51

标签: python pandas crosstab

嘿,我有这样的数据

[ID] [DATE]  [STOCK]
1 1/1/1 123
1 1/2/1 125
2 1/2/1 223
1 2/2/1 234
1 1/1/1 R123

我已经将CROSS TAB标记为日期ID并将其记录下来: -

train_ = pd.crosstab(train.ID, train.DATE)
[ID] [1/1/1] [1/2/1] [2/2/1]
1 1 1 1
2 0 1 0

我想要输出

[ID] [1/1/1] [1/2/1] [2/2/1]
1 [123,R123] [125] [234]
2 [] [223] []

1 个答案:

答案 0 :(得分:2)

您需要使用pivotset_index + unstack进行重塑:

df1 = df.pivot(index='ID', columns='DATE', values='STOCK')
print (df1)
DATE  1/1/1  1/2/1  2/2/1
ID                       
1     123.0  125.0  234.0
2       NaN  223.0    NaN

df1 = df.set_index(['ID','DATE'])['STOCK'].unstack()
print (df1)
DATE  1/1/1  1/2/1  2/2/1
ID                       
1     123.0  125.0  234.0
2       NaN  223.0    NaN

如果列中有重复项,则创建新的索引和列:

print (df)
   ID   DATE  STOCK
0   1  1/1/1  123.0<-same ID=1, DATE=1/1/1
1   1  1/1/1  200.0<-same ID=1, DATE=1/1/1
2   1  1/2/1  125.0
3   2  1/2/1  223.0
4   1  2/2/1  234.0

...然后需要groupby + apply + unstack

df1 = df.groupby(['ID','DATE'])['STOCK'].apply(list).unstack()
print (df1)
DATE           1/1/1    1/2/1    2/2/1
ID                                    
1     [123.0, 200.0]  [125.0]  [234.0]
2               None  [223.0]     None

None替换为empty list并非易事:

a = [[[] for x in range(len(df1.columns))] for y in range(len(df1.index))]
df2 = pd.DataFrame(a, index=df1.index, columns=df1.columns)
df1 = df1.fillna(df2)
print (df1)
DATE           1/1/1    1/2/1    2/2/1
ID                                    
1     [123.0, 200.0]  [125.0]  [234.0]
2                 []  [223.0]       []