【问题标题】:Compare two different sheets in one Excel-File with each other比较一个 Excel 文件中的两个不同工作表
【发布时间】:2019-05-09 09:50:51
【问题描述】:

我有一个带有两张纸的 Excel 文件。 一个包含df1:

Country City Population Planet
Germany  Berlin 30500    Earth
Spain    Madrid  21021   Earth
...

第二个包含df2:

Country   City   Population Planet
Spain    Madrid  21021   Earth
...

现在我想比较两个数据帧并检查 df1 中是否有行也在 df2 中,如果是,则: 我想在 df1 中添加一个名为 double 的新列,如果该行在 df1 和 df2 中,我只想添加一个“X”。

【问题讨论】:

  • 您可以按照this answer 中的建议使用pandas 来读取两个Excel 工作表。将 sheet2 读入列表,并且 - 在遍历 sheet1 中的行时 - 您可以检查该行是否存在于您的列表中并相应地附加该信息。

标签: python excel pandas


【解决方案1】:
# create string data

df1_str = '''Country,City,Population,Planet
Germany,Berlin,30500,Earth
Spain,Madrid,21021,Earth'''

df2_str = '''Country,City,Population,Planet
Spain,Madrid,21021,Earth'''
# read in to dataframe
df1 = pd.read_csv(io.StringIO(df1_str))
# read in to list for iteration
df1_list = pd.read_csv(io.StringIO(df1_str)).values.tolist()
df2_list = pd.read_csv(io.StringIO(df2_str)).values.tolist()

# join all columns and make a unique combination
df1_list = ["-".join(map(str, item)) for item in df1_list]
df2_list = ["-".join(map(str, item)) for item in df2_list]

# check the combinations exist in both data frame
common_flag = []
for item1 in df1_list:
    for item2 in df2_list:
        if item1 in item2: # you might prefer item1 == item2:
            common_flag.append("X")
        else:
            common_flag.append(None)

# add the result to datagrame df1
df1["double"] = pd.Series(common_flag)

创建组合list时,确保两个数据框中的列顺序相同。

输出:

   Country    City  Population Planet double
0  Germany  Berlin       30500  Earth   None
1    Spain  Madrid       21021  Earth      X

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多