在Python中将重复行从列的子集移动到另一个数据帧

2024-04-19 21:32:03 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python和Pandas,我希望在一个数据帧中找到所有具有重复行的列,并将它们移动到另一个数据帧。 例如,我可能有:

cats, tigers, 3.5, 1, cars, 2, 5
cats, tigers, 3.5, 6, 7.2, 22.6, 5
cats, tigers, 3.5, test, 2.6, 99, 52.3

我想要猫,老虎,3.5在一个数据框里

cats, tigers, 3.5

在另一个数据帧中

   1, cars, 2, 5
   6, 7.2, 22.6, 5
   test, 2.6, 99, 52.3

代码应该检查每一列的重复行,并且只删除所有行中重复出现的列。你知道吗

  1. 有些情况下没有列重复。你知道吗
  2. 有些时候不止前三列有重复。它应该检查所有列,因为在任何列中都可能发生重复

我怎么能这么做?你知道吗


Tags: 数据代码testpandas情况carscats框里
2条回答

方法一:
nuniquedropna=False一起使用

m = df.nunique(dropna=False).eq(1)

df_dup = df.iloc[[0], m.values]

Out[121]:
      0       1    2
0  cats  tigers  3.5

df_notdup = df.loc[:, ~m]

Out[123]:
      3     4     5     6
0     1  cars   2.0   5.0
1     6   7.2  22.6   5.0
2  test   2.6  99.0  52.3

方法2:
使用listcomp并在每个列上检查带有选项keep=Falseduplicated,然后检查all

m = np.array([df[x].duplicated(keep=False).all() for x in df])

df_dup = df.loc[:, m]

Out[65]:
      0       1    2
0  cats  tigers  3.5
1  cats  tigers  3.5
2  cats  tigers  3.5

正如@Moys所提到的,如果您只想要df_dup中的一行,您可以使用drop_duplicates或简单地使用.head(1)iloc

df_dup = df.loc[:, m].head(1)

或者

df_dup = df.iloc[[0], m]

Out[91]:
      0       1    2
0  cats  tigers  3.5

对于非重复行:

df_notdup = df.loc[:, ~m]

Out[75]:
      3     4     5     6
0     1  cars   2.0   5.0
1     6   7.2  22.6   5.0
2  test   2.6  99.0  52.3

你可以用

df1 = pd.DataFrame(df.val.str.extract('([a-zA-Z ]+)', expand=False).str.strip().drop_duplicates()) #'val' is the column in which you have these values
print(df1)

输出

     val
0   ABCD

以及

df2 = pd.DataFrame(df.val.str.extract('([0-9]+)', expand=False).str.strip().drop_duplicates()) #'val' is the column in which you have these values
print(df2)

输出

     val
0   1234
1   6578
2   4432

相关问题 更多 >