我有一个数据框架,里面有一些重复的内容。它们位于每一行的特定数量的列索引中:
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...
.
.在来自索引4-7的row 1中,有来自索引8-11的重复的[0, 2, 0, 3],然后来自索引12-15的重复的来自16-19的[4, 5, 6, 2]。
我需要的是检测每一行中的每个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...
.
.psudo代码类似于:
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]有没有一种简单的方法来完成这件事?
发布于 2019-05-14 03:42:47
这看起来像是一个疯狂的解决方案。主要思想是使用python的hash函数检查重复:
# 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 2https://stackoverflow.com/questions/56118338
复制相似问题