Quantcast
Channel: How to solve KeyError(f"None of [{key}] are in the [{axis_name}]") in this case (Pandas)? - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by Code_beginner for How to solve KeyError(f"None of [{key}] are in the [{axis_name}]") in this case (Pandas)?

$
0
0

Let's assume you have your dataframe already, we use the Code you provided:

import pandas as pddf = pd.read_csv("sample.csv")

Your extra columns should be stored in a list, this makes your Code easier to write and easier to understand.

additional_cols = ['grade','address','attendance','total']

The best way to add multiple columns is reindex like U11-Forward suggested.

mydf = df.reindex(df.columns.tolist() + additional_cols, axis = 1)

A similar question has been asked here[1]: How to add an empty column to a dataframe?

Regarding your error, the documentation helps you with that: The loc method is used to access elements and not to create them. If an element is not accessible a key error is returned.


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>