作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我创建了一个 Pandas 数据透视表:
adults_per_hh= pd.pivot_table(data,index=["hh_id"],values=["adult"],aggfunc=np.sum)
adults_per_hh.shape
(1000,1)
最佳答案
我想你需要 reset_index
如果使用 pivot_table
,因为第一列是 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
关于pandas - 如何在 Pandas 数据透视表中保留索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40859591/
我是一名优秀的程序员,十分优秀!