选择groupby对象的groupby索引的第一个元素,而不转换为lis

2024-04-26 03:11:13 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我迭代了groupby对象的组并打印列中的第一项 ^每组的{}。在

import pandas as pd

d = {
    'a': [1, 2, 3, 4, 5, 6],
    'b': [10, 20, 30, 10, 20, 30],
}

df = pd.DataFrame(d)
groups = df.groupby('b')

for name, group in groups:
    first_item_in_b = group['b'].tolist()[0]
    print(first_item_in_b)

因为groupby有层次索引,为了在b中选取第一个元素,我需要 先将b转换为list。在

我怎样才能避免这样的开销呢?在

我不能像这样删除tolist()

^{pr2}$

因为它将给出KeyError。在


Tags: 对象代码inimportdataframepandasdfas
2条回答

使用^{}

import pandas as pd

d = {
    'a': [1, 2, 3, 4, 5, 6],
    'b': [10, 20, 30, 10, 20, 30],
}

df = pd.DataFrame(d)
groups = df.groupby('b')

for name, group in groups:
    first_item_in_b = group['b'].iloc[0]
    print(first_item_in_b)

输出

^{pr2}$

编辑

或者使用Fast integer location scalar accessor.

您可以使用^{}来获取列b的位置,因此可能只使用iat或{},或者使用^{}列名的索引的第一个值。在

或者在按列标签选择之后,^{}^{}按位置选择:

for name, group in groups:
    #first value by positions from columns names
    first_item_in_b = group.iat[0, group.columns.get_loc('b')]
    #first value by labels from index
    first_item_in_b = group.at[group.index[0],'b']

    #fast select first value
    first_item_in_b = group['b'].iat[0]
    #alternative
    first_item_in_b = group['b'].iloc[0]
    print(first_item_in_b)

10
20
30

相关问题 更多 >