Shweta
Shweta

Reputation: 1161

Change column value in pandas depending on some dictionary data

I have some data in dictionary like and a pandas dataframe like:

s_dict = {('A1','B1'):100, ('A3','B3'):300}

df = pd.DataFrame(data={'A': ['A1', 'A2'], 'B': ['B1', 'B2'], 
                        'C': ['C1', 'C2'], 'count':[1,2]})

#    A   B   C  count
#0  A1  B1  C1      1
#1  A2  B2  C2      2

I want to replace count column of "df" if data exist in s_dict. So I want following output:

#    A   B   C  count
#0  A1  B1  C1      100
#1  A2  B2  C2      2

Upvotes: 2

Views: 69

Answers (2)

Anton vBR
Anton vBR

Reputation: 18906

Here is one way using zip() which is generally faster than .apply().

import pandas as pd

s_dict = {('A1','B1'):100, ('A3','B3'):300}
df = pd.DataFrame(data={'A': ['A1', 'A2'], 'B': ['B1', 'B2'], 
                       'C': ['C1', 'C2'], 'count':[1,2]})

# Create a map
m = pd.Series(list(zip(df['A'],df['B']))).map(s_dict).dropna()

# Assign to the index that are not nan
df.loc[m.index, 'count'] = m

Inspired by filling na with the column values you could do: (seems to be the quickest)

df['count'] = pd.Series(list(zip(df['A'],df['B']))).map(s_dict).fillna(df['count'])

Timings

df['count'] = pd.Series(list(zip(df['A'],df['B']))).map(s_dict).fillna(df['count'])
# 1.52 ms ± 85.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

df['count'] = df[['A', 'B']].apply(tuple, axis=1).map(s_dict).fillna(df['count'])
# 1.88 ms ± 100 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

dropna and loc (2 row-operation above)
# 1.93 ms ± 55.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Upvotes: 1

Ami Tavory
Ami Tavory

Reputation: 76297

You can use:

df['count'] = df[['A', 'B']].apply(tuple, axis=1).map(s_dict).fillna(df['count'])
  • apply(tuple, axis=1) creates a tuple of the relevant columns' values.
  • map(s_dict) maps the tuples to the values in s_dict.
  • fillna(df['count']) fills missing values with those of count.

Upvotes: 3

Related Questions