我有一个 Big Data 帧(120000x40),我试图在每一行中找到重复项并显示它们.这就是我try 的:

创建数据帧

import pandas as pd

df = pd.DataFrame({'col1':['1-233','2-766g','6-455','4-356','5-253','2-122','5-531','8-345','1-505','3-127','3-622'],
'col2':['6-998','2-766g','5-955','7-236','5-253','7-258','8-987t','7-567','1-505','6-876','NaN'],
'col3':['3-957','NaN','NaN','3-602m','1-266','2-122','7-834','8-345','2-858','7-984g', 'NaN']})

## code
df["duplicate"] = df.apply(lambda x: len(set(x[x.notna()])) != len(x[x.notna()]), axis=1)

print(df)

#output: output_code1

But what I wanted was the folling: wanted_code To see what exactly is doubled here.

推荐答案

为了保持函数可读性和通用性,使其适用于多于或少于三个列,我只需要编写一个专用函数,该函数使用pandas内置的功能来查找重复项,并将其应用于数据帧行:

import numpy as np
import pandas as pd

df = pd.DataFrame({'col1':['1-233','2-766g','6-455','4-356','5-253','2-122','5-531','8- 345','1-505','3-127','3-622'],
'col2':['6-998','2-766g','5-955','7-236','5-253','7-258','8-987t','7-567','1-505','6-876','NaN'],
'col3':['3-957','NaN','NaN','3-602m','1-266','2-122','7-834','8-345','2-858','7-984g', 'NaN']})

def get_duplicate_value(row):
    """If row has duplicates, return that value, else NaN."""
    duplicate_locations = row.duplicated()
    if duplicate_locations.any():
        dup_index = duplicate_locations.idxmax()
        return row[dup_index]
    return np.NaN

df["solution"] = df.apply(get_duplicate_value, axis=1)

查看pd.Dataframe.applypd.Series.duplicatedpd.Series.anypd.Series.idxmax的文档,了解其具体工作原理.

输出:

      col1    col2    col3 solution
0    1-233   6-998   3-957      NaN
1   2-766g  2-766g     NaN   2-766g
2    6-455   5-955     NaN      NaN
3    4-356   7-236  3-602m      NaN
4    5-253   5-253   1-266    5-253
5    2-122   7-258   2-122    2-122
6    5-531  8-987t   7-834      NaN
7   8- 345   7-567   8-345      NaN
8    1-505   1-505   2-858    1-505
9    3-127   6-876  7-984g      NaN
10   3-622     NaN     NaN      NaN

Python相关问答推荐

如何使用symy打印方程?

运行总计基于多列pandas的分组和总和

两个pandas的平均值按元素的结果串接元素.为什么?

在Mac上安装ipython

当独立的网络调用不应该互相阻塞时,'

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

当递归函数的返回值未绑定到变量时,非局部变量不更新:

Python导入某些库时非法指令(核心转储)(beautifulsoup4."" yfinance)

不能使用Gekko方程'

如何在Python中获取`Genericums`超级类型?

在Python中调用变量(特别是Tkinter)

Polars将相同的自定义函数应用于组中的多个列,

为什么t sns.barplot图例不显示所有值?'

如何在GEKKO中使用复共轭物

如何在Gekko中处理跨矢量优化

用由数据帧的相应元素形成的列表的函数来替换列的行中的值

如何在Polars中创建条件增量列?

如果列包含空值,则PANAS查询不起作用

如何在表单中添加管理员风格的输入(PDF)

如何在基于时间的数据帧中添加计算值