【问题标题】:Combining zip_longest() with comparison将 zip_longest() 与比较相结合
【发布时间】:2021-09-29 13:23:27
【问题描述】:

我试图在 FOR 循环中从两个数据源输出值以显示在表中。我已经部分成功了,看起来是这样的:

Customer Product Quantity Customer Product Quantity
A001 Product One 3 A001 Product One 3
A003 Product Two 5 A003 Product Two 3
A010 Product Three 21 A003 Product Two 2
A007 Product Four 1

两个数据源的记录数可能不同,这就是我此时使用 zip_longest() 的原因,而且各个值可能会出现多次。为了更好地检测差异,我想做一个匹配并使输出看起来像这样 - 如果可能的话:

Customer Product Quantity Customer Product Quantity
A001 Product One 3 A001 Product One 3
A003 Product Two 5 A003 Product Two 3
A003 Product Two 2
A010 Product Three 21
A007 Product Four 1

是否可以在同一个循环中同时使用zip_longest()==

for x, y in zip_longest(list_one, list_two, fillvalue=object()):
    print(x[0])
    print(x[1])
    print(x[2])
    print(y[0])
    print(y[1])
    print(y[2])

非常感谢。

【问题讨论】:

  • 看起来您正在尝试使用重复键执行某些版本的 mergejoin。也许考虑使用pandas
  • 很遗憾,我还没有任何使用 pandas 的经验,但在这种情况下,我会朝那个方向做一些研究。感谢您的建议。

标签: python python-3.x loops for-loop


【解决方案1】:

试试这个

import pandas as pd

list_one = [['A001', 'Product One', 3],
       ['A003', 'Product Two', 5],
       ['A010', 'Product Three', 21],
       ['A007', 'Product Four', 1]]

list_two = [['A001', 'Product One', 3],
       ['A003', 'Product Two', 3],
       ['A003', 'Product Two', 2]]

df1 = pd.DataFrame(list_one, columns = ['Customer', 'Product', 'Quantity1'])
df2 = pd.DataFrame(list_two, columns = ['Customer', 'Product', 'Quantity2'])

# adding this column to distinguish unique rows from the remainder
df1['id1'] = df1.index
df2['id2'] = df2.index

# join only unique rows
df3 = pd.merge(df1.drop_duplicates(cols), df2.drop_duplicates(cols),  how='inner', on=['Customer', 'Product'])
# then add the remainders from two dataframes to df3
df3 = pd.concat([df3, df1[~df1.id1.isin(df3.id1)], df2[~df2.id2.isin(df3.id2)]]).drop(['id1', 'id2'], axis=1)
df3 = df3.sort_values(['Customer', 'Product'])

df3

  Customer        Product  Quantity1  Quantity2
0     A001    Product One        3.0        3.0
1     A003    Product Two        5.0        3.0
2     A003    Product Two        NaN        2.0
3     A007   Product Four        1.0        NaN
2     A010  Product Three       21.0        NaN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-31
    • 2022-11-10
    • 2018-10-10
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 2012-05-19
    相关资源
    最近更新 更多