【问题标题】:remove csv rows based on comparison between two values of two columns each in a separate csv根据单独的 csv 中两列的两个值之间的比较删除 csv 行
【发布时间】:2020-04-27 22:17:51
【问题描述】:

我有两个这样的 csv 文件:

文件1:

ID,Value
ID_15ab_type1,0
ID_15ab_type2,0
ID_19ac_type1,0
ID_19ac_type2,0
ID_26de_type1,1
ID_26de_type2,1
ID_45fe_type1,2
ID_45fe_type2,0
ID_88da_type1,0
ID_88da_type2,0
ID_45ff_type1,0
ID_45ff_type2,1

文件2:

ID,Label
ID_15ab,0
ID_26de,1
ID_45fe,0

我想保留第一个文件中的行,只保留 ID 与第二个 csv ID 中的行相似的行

输出应如下所示:

ID,Value
ID_15ab_type1,0
ID_15ab_type2,0
ID_26de_type1,1
ID_26de_type2,1
ID_45fe_type1,2
ID_45fe_type2,0

【问题讨论】:

  • 到目前为止您尝试过什么?请edit你的python代码进入你的问题。

标签: python csv comparison


【解决方案1】:

您可以通过创建一个新列来对 pandas 执行此操作(通过删除您看到的 _type\d+ 后缀并确保它们在您的第二帧中。

df1 = pd.read_csv(...)  # ... is path to file 1
df2 = pd.read_csv(...)  # ... is path to file 2

df1["ref"] = df1.ID.str.replace(r"_type\d+", "")
df = df1[df1.ref.isin(df2.ID)][["ID", "Value"]]
df.to_csv("./file3.csv")

【讨论】:

  • 谢谢它运行良好!! PS:df的第二列是Value,改一下就OK了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
  • 2019-04-28
相关资源
最近更新 更多