我有一个 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 indexing
与 duplicated
和反转掩码 ~
:
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]
我是一名优秀的程序员,十分优秀!