dataframe apply += if index does not exist

Viewed 113

For a dataframe, we know that

df.loc['a', 'col1'] = 1

If index 'a' does not exist, it will automatically create a row with index 'a' and set column col1 = 1. But it seems not work for

df.loc['a', 'col1'] += 1

How to solve it without checking if the index exists? i.e. if index 'a' does not exist, it will automatically create row with index 'a' and set column col1 = 0, then add 1 to 'col1'.

I tried for dictionary:

dict = {}
dict['a'] += 1

It seems also not allowed, which is different with the map in C++

1 Answers

Here is one way to do it:

import pandas as pd

df = pd.DataFrame()  # Empty dataframe
def add_assign(df, idx, col):
    """Define a helper function.
    """
    try:
        df.loc[idx, col] += 1
    except KeyError:
        df.loc[idx, col] = 1
    return df
df = df.pipe(add_assign, "a", "col1")

print(df)
# Output with no error raised
   col1
a   1.0
Related