gpt4 book ai didi

python - Pandas 根据另一列 python 在一列中获取唯一值

转载 作者:行者123 更新时间:2023-12-05 02:41:31 33 4
gpt4 key购买 nike

这里我有一个如下所示的数据框:

Variable    Groups
1 [0-10]
1 [0-10]
2 [0-10]
2 [0-10]
3 [0-10]
3 [10-20]
4 [10-20]
4 [10-20]
5 [10-20]
5 [10-20]

我只想为 Variable 列获取唯一值,但不想丢失不同 Groups 中的任何重复值,例如:

Variable    Groups
1 [0-10]
2 [0-10]
3 [0-10]
3 [10-20]
4 [10-20]
5 [10-20]

请注意,仍然有一个重复的 3,因为每个组中都有一个。我试过了

df_unique = df['Groups'].groupby(df['Variable']).unique().apply(pd.Series)

但这只会返回一团糟。不知道该怎么做,感谢帮助。

最佳答案

您可以使用 SeriesGroupBy.unique()连同 .explode().reset_index() ,如下:

df.groupby('Variable')['Groups'].unique().explode().reset_index()

另一个解决方案是使用 GroupBy.first() ,如下:

df.groupby(['Variable', 'Groups'], as_index=False).first()

结果:

   Variable   Groups
0 1 [0-10]
1 2 [0-10]
2 3 [0-10]
3 3 [10-20]
4 4 [10-20]
5 5 [10-20]

关于python - Pandas 根据另一列 python 在一列中获取唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68091878/

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