在下面的代码中,我迭代了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()
:
因为它将给出KeyError
。在
使用^{} :
输出:
^{pr2}$编辑:
或者使用Fast integer location scalar accessor.
您可以使用^{} 来获取列},或者使用^{} 列名的索引的第一个值。在
b
的位置,因此可能只使用iat
或{或者在按列标签选择之后,^{} 或^{} 按位置选择:
相关问题 更多 >
编程相关推荐