python - Pandas Dataframe drop duplicates in a column of lists?
问题描述
I'm trying to remove duplicates in columns a
and c
.
a b c
0 [1, 0] 1 ab
1 [0, 0] 2 bc
2 [1, 0] 3 ab
Resultant Output:
a b c
0 [1, 0] 1 ab
1 [0, 0] 2 bc
What i have tried:
With out a
column being list. df.drop_duplicates(['a','c'])
works.
Without c
column being str. pd.DataFrame(np.unique(df), columns=df.columns)
works for droping duplicate lists.
How to proceed if one the columns is a list and other string.
解决方案
方法一
列表在 pandas 中不可散列,但您可以使用元组。
df['d'] = df['a'].apply(lambda x : tuple(x) if type(x) is list else x)
a b c d
0 [1, 0] 1 ab (1, 0)
1 [0, 0] 2 bc (0, 0)
2 [1, 0] 3 ab (1, 0)
然后
df = df.drop_duplicates(subset=['c', 'd'])
结果 :
a b c d
0 [1, 0] 1 ab (1, 0)
1 [0, 0] 2 bc (0, 0)
方法二
您可以将包含列表的列转换为 str。
df['a'] = df['a'].astype(str)
df = df.drop_duplicates(subset=['a', 'c'])
输出
a b c
0 [1, 0] 1 ab
1 [0, 0] 2 bc
推荐阅读
- node.js - 如何使用kafka流将视频从node.js流式传输到kafka?
- python-3.x - 计算图像中的白色像素
- html - 如何限制在角度 6 中输入旧日期?
- ubuntu - 如何在 ubuntu 中提取 .tar 文件?
- javascript - 在 React Redux 中使用 Promise
- kubernetes - 使用 helm 指定命名空间
- python - 动态如果布尔值与模块查找
- java - 处理 HicariCP Oracle 连接尝试
- c++ - 静态 constexpr 成员函数在非模板类 C++ 中不可调用
- javascript - 在 mongodb 中按给定值递增所有嵌套值