简体   繁体   中英

df.loc - ValueError: Buffer has wrong number of dimensions (expected 1, got 0)

I currently have the following code - I am trying to get a matching row in one dataframe based on the Last Name column.

def rule(row):
    name = row['Last Name']
    return rules.loc[rules['Last Name'] == name]['Type']

df['Type'] = df.apply(rule, axis=1)

When I run this I get an error, because of the == name in the rule method - how do I fix it?

ValueError: ('Buffer has wrong number of dimensions (expected 1, got 0)', 'occurred at index 0')

This is what rules looks like:

  Last Name      Type
0     Smith         A
1     Doe           B

and df :

             Name First Name Last Name
0      John Smith      John      Smith
1        Jane Doe      Jane      Doe
2        John Doe      John      Doe

I want the final to look like:

             Name First Name Last Name  Type
0      John Smith      John      Smith     A
1        Jane Doe      Jane      Doe       B
2        John Doe      John      Doe       B

EDIT: Added example rules and df

df1 = pd.DataFrame({'First Name': ['John', 'Jane','John'], 'Last Name': ['Smith','Doe','Doe']})
print(df1)

rules = pd.DataFrame({'Last Name':['Smith', 'Doe'], 'Type': ['A','B']})
print(rules)

Output is:

    First Name Last Name
0       John     Smith 
1       Jane       Doe
2       John       Doe
   Last Name Type
0     Smith    A
1       Doe    B

df1.merge(rules)

output is:

    First Name  Last Name   Type
0       John    Smith   A
1       Jane    Doe     B
2       John    Doe     B

is it your desire answer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM