【Pandas】DataFrame groupby 中的as_index含义

本文探讨了Pandas DataFrame在使用groupby函数时as_index参数的影响。当as_index设为True(默认),'even'列将作为索引,导致在后续操作中无法直接通过列名访问。而设置as_index=False,则会保留'even'列并用新的索引替换原有索引,允许通过loc直接访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

栗子如下: 

import numpy as np
values = np.array([1, 3, 2, 4, 1, 6, 4])
example_df = pd.DataFrame({
    'value': values,
    'even': values % 2 == 0,
    'above_three': values > 3 

}, index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

print(example_df)

执行如下:

   above_three   even  value
a        False  False      1
b        False  False      3
c        False   True      2
d         True   True      4
e        False  False      1
f         True   True      6
g         True   True      4
first_even = example_df.groupby('even').first()   #此时as_index默认为True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值