神不在的星期二
尝试这个...import pandas as pdimport numpy as npcolumns = ["Name","Date","Score","Country"]data=[ ["John","1st Jan","5","US"], ["John","2nd Jan","6","US"], ["Phil","1st Jan","4","Canada"], ["Phil","2nd Jan","8","Canada"], ["Phil","3rd Jan","7","Canada"]]columns2 = ["Col1","Col2","Col3","Col4"]data2 = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4] ]df = pd.DataFrame(data, columns = columns)df2 = pd.DataFrame(data2, columns = columns2)print(df)print(df2)df.loc[(df['Name'] == "John") & (df['Date'] == "1st Jan")& (df['Score'] == "5") & (df['Country'] == "US"), 'New'] = df2["Col1"]name = "Phil"date = "1st Jan"score = "4"country = "Canada"df.loc[(df['Name'] == name) & (df['Date'] == date) & (df['Score'] == score) & (df['Country'] == country), 'New'] = df2["Col2"]输出:Name Date Score Country0 John 1st Jan 5 US1 John 2nd Jan 6 US2 Phil 1st Jan 4 Canada3 Phil 2nd Jan 8 Canada4 Phil 3rd Jan 7 CanadaCol1 Col2 Col3 Col40 1 2 3 41 1 2 3 42 1 2 3 43 1 2 3 4Name Date Score Country New0 John 1st Jan 5 US 1.01 John 2nd Jan 6 US NaN2 Phil 1st Jan 4 Canada 2.03 Phil 2nd Jan 8 Canada NaN4 Phil 3rd Jan 7 Canada NaN编辑您可以通过使用一个函数df.apply()和一个调用该函数的 lambda 来使其更加自动化。def lambdafunc(row): name = row[0] date = row[1] score = row[2] country = row[3] df.loc[(df['Name'] == name) & (df['Date'] == date) & (df['Score'] == score) & (df['Country'] == country), 'New'] = df2.loc[df2['Col1'] == name, 'Col4']df.apply(lambda x: lambdafunc(x), axis = 1)print(df)