在行上出现Pandas键错误,尽管该键存在。

huangapple go评论68阅读模式
英文:

Getting Pandas Key Error on Row although the key exists

问题

我有一个包含列'App'、'Query'和'Label'的数据框。

train_data = pd.DataFrame({
'Query':['鞋架','鞋架','鞋架','鞋架','耐克鞋'],
'App': ['亚马逊', '亚马逊', '亚马逊', '亚马逊', 'Zalando'],
'Label':[1, 1, 1, 1, 1]})

现在,如果我进行简单的应用:

train_data.apply(lambda row: print(row['App']))

我得到:

KeyError: 'App'

根据这个链接: https://stackoverflow.com/questions/33518124/how-to-apply-a-function-on-every-row-on-a-dataframe
应该按行正常工作,为什么如果键存在会出现关键错误?

英文:

I have a dataframe which consists of the columns 'App', 'Query' and 'Label'

train_data = pd.DataFrame({
     'Query':['shoerack','shoerack','shoerack','shoerack', 'nike shoes'], 
     'App':  ['amazon', 'amazon', 'amazon', 'amazon', 'zalando'],
     'Label':[1, 1, 1, 1, 1]})

now if I do a simple apply:

train_data.apply(lambda row: print(row['App']))

I get:

KeyError                                  Traceback (most recent call last)
Cell In[20], line 4
  1 train_data = pd.DataFrame({'Query': ['shoerack','shoerack','shoerack','shoerack', 'nike shoes'], 
  2                            'App': ['amazon', 'amazon', 'amazon', 'amazon', 'zalando'],
  3                            'Label': [1, 1, 1, 1, 1]})
 ----> 4 train_data.apply(lambda row: print(row['App']))
 
KeyError: 'App'

According to this: https://stackoverflow.com/questions/33518124/how-to-apply-a-function-on-every-row-on-a-dataframe
the apply should work fine as it is per row. Why do I get a Key Error if the key exists?

答案1

得分: 0

使用apply默认轴运行将在上执行。索引中没有App指数,因此会引发KeyError

您需要使用axis=1

train_data.apply(lambda row: print(row['App']), axis=1)

输出:

# 打印
amazon
amazon
amazon
amazon
zalando

# 返回值
0    None
1    None
2    None
3    None
4    None
dtype: object
英文:

Using apply with the default axis will run on columns. The is no App indice in your index, thus the KeyError.

You need to use axis=1:

train_data.apply(lambda row: print(row['App']), axis=1)

Output:

# printed
amazon
amazon
amazon
amazon
zalando

# returned value
0    None
1    None
2    None
3    None
4    None
dtype: object

huangapple
  • 本文由 发表于 2023年4月20日 04:49:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058701.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定