python - 检查数据框行的各个部分在 Python 中是否相同
问题描述
我有一个数据框,其中有一些重复。它们位于每一行的特定数量的列索引中:
df_in
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19...
1 3 4 6 0 2 0 3 0 2 0 3 4 5 6 2 4 5 6 2...
.
.
在row 1
from index4-7
中有一个[0, 2, 0, 3]
from indices的重复,8-11
然后 from index12-15
有一个[4, 5, 6, 2]
from的重复16-19
。
我需要检测4 numbers
每一行中的每个是否相等,如果是,则从 DataFrame 中删除其中一个重复。
输出将是:
df_out
0 1 2 3 4 5 6 7 8 9 10 11...
1 3 4 6 0 2 0 3 4 5 6 2...
.
.
伪代码将类似于:
for index in range(4, len(df_in.columns)):
if bool((df_in.iloc[:, index] == (df_in.iloc[:, index+4]).all()) == True:
remove either df_in.iloc[:, index] or df_in.iloc[:, index]+4 and keep one
if bool((df_in.iloc[:, index] == (df_in.iloc[:, index+4]).all()) == False:
keep df_in.iloc[:, index]
有没有简单的方法来完成这项工作?
解决方案
这看起来像一个疯狂的解决方案。hash
主要思想是使用python的函数检查重复:
# original data frame
df = pd.DataFrame([1,3,4,6,0,2,0,3,0,2,0,3,4,5,6,2,4,5,6,2]).T
# we will create hash on tuple of every subsequence of length 4
sub4hash = df.iloc[0].rolling(4).apply(lambda s: hash(tuple(s))).shift(-3)
# start of duplication:
dup_start = sub4hash.duplicated()
# and we want all 4, so rolling again:
markers = dup_start.rolling(4).sum().gt(0)
# finally:
df.loc[:, ~markers]
0 1 2 3 4 5 6 7 12 13 14 15
-- --- --- --- --- --- --- --- --- ---- ---- ---- ----
0 1 3 4 6 0 2 0 3 4 5 6 2
推荐阅读
- jquery - 基于视口宽度的行高的 CSS calc
- php - 使用 PHP 和 mySQLi 的手工计数器脚本的问题
- python - 如何在 settings.py 文件中隐藏 EMAIL_HOST_PASSWORD?
- android - 使用 Dagger 将 Activity 绑定到 LifecycleOwner
- ionic-framework - Ionic 中的嵌套 JSON 数据
- razor - 如何在 .Net Core 项目的布局中包含 font-awesome(通过 nuget 安装)?
- python - 如何生成一个python字典comphrension,将键生成为值的范围函数?
- python - 如何访问烧瓶中任务队列提交的作业数据?
- apache-spark - PySpark StandardScaler 在双列上抛出错误
- reactjs - 创建项目时缺少模块 minizlib