我想将vlookup函数变成python脚本,但我真的不知道如何制作。附图是我在Excel应用程序中应用的vlookup函数。 Lookup_value 将是 Excel A 中的列名称“声明时的 HS 代码”,而 table_array 将是 Excel B 中的 A 列到 B 列。有人可以帮我弄清楚如何将其转换为 python 脚本吗?
就是这个:
import pandas as pd
df1 = pd.read_excel('path to filename abc/abc.xlsx')
df2 = pd.read_excel('path to filename abc2/abc2.xlsx')
result_df = pd.merge(df1, df2, how='left', left_on='a', right_on='a')
print(result_df)
abc.xlsx:
a b c d
1 1 2 3
2 1 2 3
3 1 2 3
4 1 2 3
3 3 3 3
abc2.xlsx:
a b c d
1 4 5 6
2 4 5 6
3 4 5 6
4 4 5 6
5 4 5 6
输出:
a b_x c_x d_x b_y c_y d_y
0 1 1 2 3 4 5 6
1 2 1 2 3 4 5 6
2 3 1 2 3 4 5 6
3 4 1 2 3 4 5 6
4 5 1 2 3 4 5 6
对于您的情况,代码将如下所示:
import pandas as pd
df1 = pd.read_excel('path to filename done/done.xlsx')
df2 = pd.read_excel('path to filename CORRELATION TABLE_EXCEL_HS 2022-2017/CORRELATION TABLE_EXCEL_HS 2022-2017.xlsx')
result_df = pd.merge(df1, df2, how='left', left_on='HS CODE 2017', right_on='PDF2017')
print(result_df)
我通过使用chatgpt找到了解决方案:
import pandas as pd
def vlookup(excel_a_path, excel_b_path):
# Load Excel files into pandas dataframes
df_a = pd.read_excel(excel_a_path)
df_b = pd.read_excel(excel_b_path, sheet_name='Table 1')
# Define the columns for lookup
lookup_column = 'HS code on declaration'
table_array_columns = ['PDK2022', 'PDK2017']
range_lookup = False # Use exact match, equivalent to 0 in Excel
# Perform VLOOKUP
result_df = pd.merge(df_a[[lookup_column]], df_b[table_array_columns], how='left', left_on=lookup_column, right_on=table_array_columns[0])
# Extract the result column as a list
result_column = result_df[table_array_columns[1]].tolist()
return result_column
# Example usage:
excel_a_path = 'path_to_excel_A.xlsx'
excel_b_path = 'path_to_excel_B.xlsx'
result_list = vlookup(excel_a_path, excel_b_path)
print(result_list)