【发布时间】:2021-02-15 16:21:46
【问题描述】:
我有 2 个我将使用的 excel 文件。两个 excel 文件的文件路径都被传递到一个函数中。将文件路径传递给 excel file1 = "Test" 的函数。传递给 excel file2 = "Report" 函数的文件路径。该函数为输出文件创建工作簿,并将我们将要填充的工作表命名为“列表”
我想创建 2 个数据框,df1 用于 excel file1,df2 用于 excel file2。
我想将“名称”列及其值从 excel file1 放入 df1。 (只是一个小例子)
Name
0 James
1 Ben
2 Frank
3 Charles
4 Tim
我想将“名称”和“状态”列及其值从 excel file2 放入 df2。 (只是一个小例子,df2更大)
Name State
0 Ben DC
1 Sam MD
2 Tim NC
3 Charles PA
4 Frank IN
5 James VA
我想将 df1 (cv1) 的“名称”列下第一行的单元格与 df2 (cv2) 的“名称”列的第一行的单元格进行比较。
如果 cv1==cv2,我想从 df2 复制同一行的“状态”列下的单元格,并将其写入函数创建的工作簿“列表”表的“最佳”列。
否则增加df2的行,重复比较。
我想对 df1 中在“名称”列中有名称的所有行执行此操作
输出应该是这样的
Best
0 VA
1 DC
2 IN
3 PA
4 NC
以下是我用于创建数据框的代码。我不确定如何使用 for 循环进行比较。非常感谢任何和所有的帮助。
import os
import pandas as pd
def page(Test,Report):
# select columns i want to work with
compare_column1 = ["Name"]
compare_column2 = ["Name", "State"]
write_column = ["Best"]
# create dataframes for the column to copy to the output file and columns to compare
Df1 = pd.DataFrame(columns=compare_column1)
Df2 = pd.DataFrame(columns=compare_column2)
# compare cell for every row under "Name" column from df1(cv1) to every cell under “Name”
# column df2, if the 2 cells are equal, then copy the cell under the column “State” of that row
# of df2 and write it to the column “Best” of the workbook with the sheet name “List” the
# function created
# else increment the row for df2, compare cv1 to cv2…. Do this for all names in the “Name”
# column
# df1
df_file2 = pd.read_excel(Test)
df_file3 = pd.read_csv(Report)
for i in range (0, length(df1):
cv1 = df1.loc[i], compare_column1]
for j in range (0, length(df2):
cv2 = df2.loc[j], compare_column1] #not sure how to select “Name” column
if cv1==cv2:
cv1.to_excel(writer, sheet_name=write_column, header=false, index=false, startrow=1)
【问题讨论】:
-
您好,请格式化您的代码。请看:stackoverflow.com/questions/20109391/…
-
我不确定如何使用 for 循环进行比较。非常感谢任何和所有的帮助。你能更具体吗?请参阅How to Ask、help center。
-
@user106591 请通过单击我的答案旁边的复选标记接受其中一个答案作为解决方案。谢谢!
标签: python excel pandas dataframe for-loop