Keyerror 0 python pandas

Keyerror 0 python pandas

You can only assign the key if it isn’t already present in the dictionary.

Copied!
employee = 'name': 'Alice' > if 'address' not in employee: employee['address'] = > employee['address']['country'] = 'Austria' # 👇️ > print(employee)

The if statement is only run if the address key is not in the dictionary.

# Using the defaultdict class to set a default value for keys that don’t exist

You can also use the defaultdict class to set default values for keys that don’t already exist in the dictionary.

Copied!
from collections import defaultdict employee = defaultdict(dict) employee['address']['country'] = 'Austria' # 👇️ defaultdict(, >) print(employee) print(employee['address']) # 👉️

The defaultdict class takes a default_factory argument which it calls to provide a default value for the given key.

The value for the key is inserted in the dictionary and is returned.

We passed the dict class to the constructor, so every time we try to access a key that doesn’t exist, the dict class is called without any arguments and a dict object is set for the key.

Here is a simple example of how defaultdict objects work.

Copied!
from collections import defaultdict my_dict = defaultdict(int) print(my_dict['a']) # 👉️ 0

The a key is not present in the dict , so the int() class gets invoked without any arguments and a 0 value gets set for the key we tried to access.

# Using a try/except statement when setting the key

You can also use a try/except statement to handle a KeyError exception while adding a new key to a dictionary.

Copied!
employee = 'name': 'Alice' > try: employee['address']['country'] = 'Austria' except KeyError: employee['address'] = > employee['address']['country'] = 'Austria' # 👇️ > print(employee)

The KeyError exception gets handled by the except clause where we assign the address key and set a value for the nested country key.

# (JSON) KeyError exception in Python

To solve the (JSON) KeyError exception in Python, use the json.loads() method to parse the JSON string into a native Python object and conditionally check if the key is present in the dictionary before accessing it.

Copied!
import json my_json = r'' # 👇️ parse JSON string to Python dict my_dict = json.loads(my_json) print(my_dict) # 👉️ # 👇️ check if key is present in dictionary if 'country' in my_dict: print(my_dict['country'])

The json.loads method parses a JSON string into a native Python object.

We used the in operator to check if the country key is present in the dictionary before accessing it.

When used with a dictionary, the operators check for the existence of the specified key in the dict object.

# Setting the key to a default value if it isn’t present

Alternatively, you can check if the key is not in the dictionary and set it to a default value, e.g. an empty string or an empty list.

Copied!
import json my_json = r'' my_dict = json.loads(my_json) print(my_dict) # 👉️ if 'country' not in my_dict: my_dict['country'] = '' print(my_dict['country']) # 👉️ ''

We only set the country key to an empty string if it isn’t already present in the dictionary.

When debugging, use the dict.keys() method to print the dictionary’s keys.

Copied!
import json my_json = r'' my_dict = json.loads(my_json) print(my_dict) # 👉️ # 👇️ ['name', 'age'] print(list(my_dict.keys()))

If you try to access any other key, you’d get the KeyError exception.

# Ignoring the KeyError exception

If you only need to access a specific key and need to ignore the KeyError exception, use the dict.get() method.

Copied!
import json my_json = r'' my_dict = json.loads(my_json) print(my_dict) # 👉️ print(my_dict.get('country')) # 👉️ None print(my_dict.get('country', 'default value')) # 👉️ 'default value'

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 arguments:

Name Description
key The key for which to return the value
default The default value to be returned if the provided key is not present in the dictionary (optional)

If a value for the default parameter is not provided, it defaults to None , so the get() method never raises a KeyError .

# Make sure to access the key correctly

Make sure you aren’t trying to access the key incorrectly.

Copied!
import json my_json = r'>' my_dict = json.loads(my_json) print(my_dict) # 👉️ > print(my_dict['address']['country']) # 👉️ 'Austria'

Notice that we first have to access the address key before accessing the nested country key.

If you have an array, make sure to access it at a specific index before trying to access a key.

Copied!
import json my_json = r'[>]' my_list = json.loads(my_json) print(my_list) # 👉️ [>] print(my_list[0]['address']['country']) # 👉️ 'Austria'

We parsed the JSON string into a list. Notice that we first have to access the list at index 0 to get a dict object.

Once we have a dict object, we can access its specific keys.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

KeyError:0 — Create DataFrame in Pandas

In this tutorial, we’ll take a look at the Pandas error:

First, we’ll create an example of how to reproduce it. Next, we’ll explain the reason and finally, we’ll see how to fix it.

Example

Let’s work with the following DataFrame:

import pandas as pd data= df = pd.DataFrame(data) 
day numeric
1 22
2 222
3 22K
4 2M
5 0.01 B

Reason

There are multiple reasons to get error like:

Not existing column

One reason is trying to access column which don’t exist:

Bad Input — Creating DataFrame with dict

Sometimes when we work with API we get dict as input. Some dict elements might cause similar problems.

In that case we need to drop elements from the input by:

In this case the element ‘episode of’ is pointing to an instance.

Working with IMDB library cinemagoer return result as:

, 'season': 8, 'episode': 6, 'rating': 4.001234567891, 'votes': 249455, 'original air date': '19 May 2019', 'year': '2019', 'plot': "\nIn the aftermath of the devastating attack on King's Landing, Daenerys must face the survivors. "> 

Solution — wrong column

For the wrong column error we can check what are the current columns of the DataFrame:

Index(['day', 'numeric'], dtype='object') 

Then we can access the correct one:

Solution — bad input

To investigate and solve bad inputs which cause:

We can try to isolate problematic values. For example creating DataFrame with line:

Dropping this line from the input by:

if 'episode of' in data.keys(): data.pop('episode of') 

By using DataScientYst — Data Science Simplified, you agree to our Cookie Policy.

Источник

Python KeyError: How to fix and avoid key errors

A KeyError occurs when a Python attempts to fetch a non-existent key from a dictionary.

This error commonly occurs in dict operations and when accessing Pandas Series or DataFrame values.

In the example below, we made a dictionary with keys 1–3 mapped to different fruit. We get a KeyError: 0 because the 0 key doesn’t exist.

There is a handful of other places where we might see the KeyError (the os and zipfile modules, for example). Yet, the main reason for the error stays the same: the searched key is not there.

The easiest, immediate, all-fitting solution to the key error would be wrapping the value-fetching portion of the code in a try-except block. Like the code below does:

The try-except construct saved our program from terminating, allowing us to avoid the keys that have no match.

In the next section, we’ll use more nuanced solutions, one of which is the _proper_ way of adding and removing dictionary elements.

Generic Solutions

Solution 1: Verifying the key using ‘ in ‘

While working with dictionaries, Series and DataFrames, we can use the in keyword to check whether a key exists.

Below you can see how we can use in with a conditional statement to check the existence of a dictionary key.

This method does not change in the slightest when applying to a Pandas Series, as you can see below:

We can use the same if key in collection structure when verifying DataFrame column names. However, we have to add a bit more if we want to check a row name.

Let’s start by building a DataFrame to work with:

Now we can check whether a column name is in df or a row name is in df.index :

Solution 2: Assigning a fall-back value using get()

We can use the get() method to fetch dictionary elements, Series values, and DataFrame columns (only _columns_, unfortunately).

The get() method does not raise a KeyError when it fails to find the key given. Instead, it returns None , which is more desirable since it doesn’t crash your program.

Take a look at the code below, where fetching the non-existent key3 returns None :

get() also allows us to define our own default values by specifying a second parameter.

For example, say we have a website with a few URLs and want to fall back to a 404 page:

The get() method also works on Pandas DataFrames.

We can try and grab two columns by name and provide a default value if one doesn’t exist:

Since not all the keys match, get() returned ‘Non-Existent’ .

Accessing Items in Pandas: The loc-iloc Mishap

Programmers learning Pandas often mistake loc for iloc , and while they both fetch items, there is a slight difference in mechanics:

  • loc uses row and column names as identifiers
  • iloc uses integer location, hence the name

Let’s create a Series to work with:

How would we retrieve the name «John» from this Series?

We can see John lies in the «a» row, which we can target using loc , like so:

If we were to use iloc for the same purpose, we’d have to use the row’s integer index. Since it’s the first row, and Series are 0-indexed, we need to do the following:

If we used an integer for loc we would get a KeyError , as you can see below:

Note that this is only true for the cases where the row labels have different values than the indexes.

Dictionary-specific solutions

Now we’ll look closer at the operations that may cause KeyError and offer good practices to help us avoid it.

Let’s give an example of how this may go wrong:

It’s clear this is a mistake since the code is trying to fetch items from an empty dictionary, but this example demonstrates the problem of wanting to use a dictionary as if it already had the keys present.

We could write another loop at the start that initializes each value to zero, but Python offers defaultdict s for such situations. They are type-specific dictionaries with defaults for handling new keys.

The only change needed is swapping in defaultdict for the empty brackets. The defaultdict is of type int , meaning that the access of any new key will auto-create that key with an initial value of 0.

This also works for more complex scenarios, like if you want a default value to be a list . In the following example, we generate ten random numbers and store them as either even or odd:

Using defaultdict(list) we’re able to immediately append to the «even» or «odd» keys without needing to inialized lists beforehand.

2. Avoiding KeyError when deleting dictionary items

Deleting dictionary keys runs into the same problem as accessing keys: first we need to get the key using \[\] to delete it.

We can always check whether the key exists before attempting to delete the value assigned to it, like so:

A quicker way, however, would be to pop() the value out of the dictionary, effectively deleting it if we don’t assign it to a variable.

pop() takes the desired key as its first parameter and, similar to get() , allows us to assign a fall-back value as the second parameter.

Since Python couldn’t find the key, pop() returned the default value we assigned.

If the key exists, Python will remove it. Let’s run pop() one more time with a key we know exists:

The ‘cat’ was found and removed.

Summary

KeyError occurs when searching for a key that does not exist. Dictionaries, Pandas Series, and DataFrames can trigger this error.

Wrapping the key-fetching code in a try-except block or simply checking whether the key exists with the in keyword before using it are common solutions to this error. One can also employ get() to access elements from a dictionary, Series or DataFrame without risking a KeyError .

Источник

Читайте также:  Javascript display none position
Оцените статью