【问题标题】:Matching multiple column and add to dataframe匹配多列并添加到数据框
【发布时间】:2020-02-03 09:05:58
【问题描述】:

假设的数据集,

df1

num1 num2
27    1
973   3
1410  3
724   1
346   5

df2

 a1     a2   c1      c2
27.0    1   red    apple
131.0   1   blue   banana
2124.0  3   green  apple
1345.0  1   red    orange
346.0   5   blue   grape

我想比较 num1 - a1 & num2 - a2,如果两个条件相同, 我想将 c1 和 c2 中的值添加到列表中。(假设开头是一个空列表)

条件

  1. 如您所见,num1-a1、num2&a2 的形状不同。

  2. 只有添加到列表中的值是 'c1' 和 'c2'

    (num1, num2, a1, a2 只是用来比较和匹配)

  3. 顺序混乱,数据帧大小不一。 (不同的列长)

我想要的输出

上面的例子,2 个匹配项,(27-1 , 346-5),所以

mylist = [red, apple, blue, grape]

我该怎么做?

感谢您的阅读。

【问题讨论】:

  • 看来'blue', 'banana'也匹配了。

标签: python pandas dataframe match multiple-columns


【解决方案1】:

使用Series.str.zfillDataFrame.assign 添加0 匹配df2,然后使用DataFrame.merge 和默认连接,最后使用DataFrame.stack 匹配Series 并转换为列表:

mylist = (df1.assign(num1 = df1['num1'].astype(str).str.zfill(4),
                     num2 = df1['num2'].astype(str).str.zfill(3))
              .merge(df2, left_on=['num1','num2'], right_on=['a1','a2'])[['c1','c2']]
              .stack()
              .tolist())
print (mylist)
['green', 'apple', 'orange', 'melon',
 'blue', 'banana', 'purple', 'peach']

【讨论】:

  • 感谢您的高效代码,但现在我正在阅读真实数据,我将问题修改为与我想的形状有点不同。你能再检查一下是否可以吗?
  • @ybin - 我看到你的答案,它是正确的,只是省略 .assign(num1 = df1['num1'].astype(str).str.zfill(4), num2 = df1['num2'].astype(str).str.zfill(3))
猜你喜欢
  • 1970-01-01
  • 2021-01-15
  • 2018-02-15
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 2019-09-17
  • 2021-12-16
相关资源
最近更新 更多