Pandas - 当密钥存在时出现密钥错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43771654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas - Getting a Key Error when the Key Exists
提问by DixieFlatline
I'm trying to join two dataframes in Pandas.
我正在尝试在 Pandas 中加入两个数据框。
The first frame is called Trades and has these columns:
第一帧称为交易,包含以下列:
TRADE DATE
ACCOUNT
COMPANY
COST CENTER
CURRENCY
The second frame is called Company_Mapping and has these columns:
第二个框架称为 Company_Mapping 并具有以下列:
ACTUAL_COMPANY_ID
MAPPED_COMPANY_ID
I'm trying to join them with this code:
我正在尝试使用以下代码加入他们:
trade_df = pd.merge(left=Trades, right = Company_Mapping, how = 'left', left_on = 'COMPANY', right_on = 'ACTUAL_COMPANY_ID'
This returns:
这将返回:
KeyError: 'COMPANY'
I've double checked the spelling and COMPANY is clearly in Trades, and I have no clue what would cause this.
我已经仔细检查了拼写,并且 COMPANY 显然在 Trades 中,我不知道是什么导致了这种情况。
Any ideas?
有任何想法吗?
Thanks!
谢谢!
采纳答案by piRSquared
Your Trades
dataframe has a single column with all the intended column names mashed together into a single string. Check the code that parses your file.
您的Trades
数据框有一个列,其中所有预期的列名称都混在一起成为一个字符串。检查解析文件的代码。
回答by Azum
Essentially keyError is shown in pandas python when there is no such column name for example you are typing df.loc[df['one']==10]
but column name 'one does not exist' whoever if it exist and you are still getting the same error try place try and except statement my problem was solved using try and except statement.
本质上,当没有这样的列名时,pandas python 中会显示 keyError 例如,您正在键入df.loc[df['one']==10]
但列名“一个不存在”,如果它存在并且您仍然遇到相同的错误 try place try and except 语句,我的问题已解决使用 try 和 except 语句。
for example
例如
try:
df_new = df.loc[df['one']==10]
except KeyError:
print('No KeyError')