如何迭代一个数据帧中唯一行的列值,该数据帧具有排序的数值索引,并且在pandas中有重复项?

2024-04-25 02:01:27 发布

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

我有一个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的类型时,我得到重复索引项的系列条目。在

^{pr2}$

输出:

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

Tags: core示例类型dataframepandasdfindex排序
3条回答

首先按掩码删除重复的索引并按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'>

无循环解决方案-将^{}^{}一起使用,并使用~反转掩码:

^{pr2}$

如果按照您的评论,相同的索引意味着相同的数据,这看起来是一个XY Problem。在

你也不需要一个循环。在

假设您想删除重复的行并只提取第一列(即3,5),下面的内容就足够了。在

res = df.drop_duplicates().loc[:, 'a']

# 1    3
# 2    5
# Name: a, dtype: int64

要返回类型:

^{pr2}$

尝试np.unique

_, i = np.unique(df.index, return_index=True)
df.iloc[i, df.columns.get_loc('a')].tolist() 

[3, 5]

相关问题 更多 >