【问题标题】:df.loc - ValueError: Buffer has wrong number of dimensions (expected 1, got 0)df.loc - ValueError:缓冲区的维数错误(预期为 1,得到 0)
【发布时间】:2019-10-13 04:35:41
【问题描述】:

我目前有以下代码 - 我正在尝试根据 Last Name 列在一个数据框中获取匹配行。

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

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

当我运行它时,由于rule 方法中的== name 而出现错误 - 我该如何解决?

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

这是rules 的样子:

  Last Name      Type
0     Smith         A
1     Doe           B

df:

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

我希望决赛看起来像:

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

编辑:添加示例 rulesdf

【问题讨论】:

  • 请提供一些输入数据和您的预期结果
  • @splash58 我在尝试时遇到同样的错误

标签: python pandas


【解决方案1】:
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)

输出是:

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

df1.merge(规则)

输出是:

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

这是你想要的答案吗?

【讨论】:

  • 是的,但我收到一个错误 TypeError: unhashable type: 'Array' - 每行的 dtype 似乎是 object
  • 成功了。我必须将自动类型从 read_excel 转换为 str
猜你喜欢
  • 1970-01-01
  • 2022-08-07
  • 1970-01-01
  • 1970-01-01
  • 2017-10-19
  • 2018-03-19
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多