gpt4 book ai didi

python - 如何使用排序的数字索引和 pandas 中的重复项迭代数据框的唯一行的列值?

转载 作者:太空宇宙 更新时间:2023-11-04 09:47:42 25 4
gpt4 key购买 nike

我有一个 pandas DataFrame,其中包含带重复项的已排序数字索引,并且列值对于给定列中索引的相同值是相同的。我想遍历给定列的值以获得索引的唯一值。

例子

df = pd.DataFrame({'a': [3, 3, 5], 'b': [4, 6, 8]}, index=[1, 1, 2])

a b
1 3 4
1 3 6
2 5 8

我想遍历 a 列中的值以获取索引中的唯一条目 - [3,5]

当我使用默认的 index 进行迭代并打印列 a 的类型时,我得到了重复索引条目的 Series 条目。

for i in df.index:
cell_value = df['a'].loc[i]
print(type(cell_value))

输出:

<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'numpy.int64'>

最佳答案

先通过掩码去除重复索引,通过arange分配位置,然后通过iloc选择:

arr = np.arange(len(df.index))
a = arr[~df.index.duplicated()]
print (a)
[0 2]

for i in a:
cell_value = df['a'].iloc[i]
print(type(cell_value))

<class 'numpy.int64'>
<class 'numpy.int64'>

无循环解决方案——使用boolean indexingduplicated和反转掩码 ~:

a = df.loc[~df.index.duplicated(), 'a']
print (a)
1 3
2 5
Name: a, dtype: int64

b = df.loc[~df.index.duplicated(), 'a'].tolist()
print (b)
[3, 5]

print (~df.index.duplicated())
[ True False True]

关于python - 如何使用排序的数字索引和 pandas 中的重复项迭代数据框的唯一行的列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49130834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com