如何在pandas透视表中保留索引

4
假设我创建了一个 pandas 透视表:
  adults_per_hh= pd.pivot_table(data,index=["hh_id"],values=["adult"],aggfunc=np.sum)
  adults_per_hh.shape
  (1000,1)

我希望在adult列的基础上保留hh_id列。最有效的方法是什么?

1个回答

2

如果你使用 pivot_table,我认为你需要使用 reset_index,因为第一列是 index

print (data)
   adult  hh_id
0      4      1
1      5      1
2      6      3
3      1      2
4      2      2

print (pd.pivot_table(data,index=["hh_id"],values=["adult"],aggfunc=np.sum))
       adult
hh_id       
1          9
2          3
3          6

adults_per_hh= pd.pivot_table(data,index=["hh_id"],values=["adult"],aggfunc=np.sum)
                .reset_index()
print (adults_per_hh)
   hh_id  adult
0      1      9
1      2      3
2      3      6

另一种解决方案是使用 groupby 和聚合函数 sum
adults_per_hh = data.groupby("hh_id")["adult"].sum().reset_index()
print (adults_per_hh)
   hh_id  adult
0      1      9
1      2      3
2      3      6

时间:

#random dataframe
np.random.seed(100)
N = 10000000
data = pd.DataFrame(np.random.randint(50, size=(N,2)), columns=['hh_id','adult'])
#[10000000 rows x 2 columns]
print (data)

In [60]: %timeit (pd.pivot_table(data,index=["hh_id"],values=["adult"],aggfunc=np.sum).reset_index())
1 loop, best of 3: 384 ms per loop

In [61]: %timeit (data.groupby("hh_id", as_index=False)["adult"].sum())
1 loop, best of 3: 381 ms per loop

In [62]: %timeit (data.groupby("hh_id")["adult"].sum().reset_index())
1 loop, best of 3: 355 ms per loop

我不想要1000列。我只需要2列,一列是hh_id,另一列是成年人数量。 - lord12
我添加了计时,似乎使用groupbysumreset_index是最快的。 - jezrael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接