英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论