Pandas - Getting a Key Error when the Key Exists
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.
Keyerror even though column exists
It's the axis=1
in your .sort_values()
that's causing problems: there is no such index 'Top'
(but there is a column 'Top'
).
In other words, change your second line to:
temp_df = temp_df.sort_values(by='Top')
Why I get Key error even though column present in pandas?
Instead of manually entering the column names, try the following, as a test:
for col in data.columns:
data[col] = data[col].astype(str)
This should also work for the entire dataframe
data = data.astype('str')
Pandas get_group returns key error, even though key is in group?
It seems to me that you don't want to groupby, but simply filter your dataframe.
>>> df[df['team'] == 'Manchester City']
Use groupby
when you want to apply some logic to each group (i.e. aggregate them, filter them, modify/transform in some way etc). If you just want to list the groups, then all you need is slicing and .loc
.
You may also sort your dataframe by team to see it in a "grouped" fashion.
>>> df.sort_values(by='team')
Now, as to why you get a KeyError
: your data is likely not clean. The group name must match excatly the values in your DataFrame. For example, if you have in your df
the value " Manchester City"
, with an extra whitespace in the beginning, calling get_group('Manchester City')
will yield an error. The same is true for \n
, \t
and other invisible characters.
Make sure you have clean team names first. Usually, doing
>>> df['team'] = df['team'].str.strip()
is a good start.
Related Topics
How to Check All Versions of Python Installed on Osx and Centos
How to Delete the Words Between Two Delimiters
Printing the Number of Days in a Given Month and Year [Python]
Can Anyone Explain Me What This Python 3 Command Do
How to Convert Strings With Billion or Million Abbreviation into Integers in a List
Spark Data Frames - Check If Column Is of Type Integer
How to Sort the Letters in a String Alphabetically in Python
Combine Date and Time Columns Using Python Pandas
Why I Get Key Error Even Though Column Present in Pandas
How to Increase Dpi With Opencv
Get Only Unique Words from a Sentence in Python
How to Install Python Packages from the Tar.Gz File Without Using Pip Install
How to Pass Variables from Python Script to Bash Script
Easiest Way to Replace a String Using a Dictionary of Replacements
How to Select Last Row and Also How to Access Pyspark Dataframe by Index