How do I return the dictionary key if the value in a pandas DataFrame column is in the dictionary's value?
So for the df below how would you add a column col3 that returns the dictionary key i.e. odd or even based on whether col1 is in the dictionary's values?
df = pd.DataFrame({"col1": [1,2,3,4,5], "col2": [6,7,8,9,10]})
d = {"odd": [1,3,5,7,9], "even": [2,4,6,8,10]}
df["col3"] = np.where(df["col1"].isin(d.values), d.key, "") # ???
I know you can use % or something to determine whether a value is odd or even, the above is just an example, other dictionaries might be some type of config file or json that we need to read.
Want to be able to produce something like this:
col1 col2 col3
0 1 6 odd
1 2 7 even
2 3 8 odd
3 4 9 even
4 5 10 odd
CodePudding user response:
You can try
df['col3'] = df['col1'].mod(2).map({0: 'even', 1: 'odd'})
# or
d = {v:k for k, lst in d.items() for v in lst}
df['col3'] = df['col1'].map(d)
print(df)
col1 col2 col3
0 1 6 odd
1 2 7 even
2 3 8 odd
3 4 9 even
4 5 10 odd
CodePudding user response:
import pandas as pd
df = pd.DataFrame({"col1": [1,2,3,4,5], "col2": [6,7,8,9,10]})
d = {"odd": [1,3,5,7,9], "even": [2,4,6,8,10]}
data = pd.DataFrame(d).stack().reset_index()[["level_1", 0]].to_dict()['level_1']
df.col1.map(data)
CodePudding user response:
You could try something like this:
for key in d:
df.loc[df.col1.isin(d[key]), 'col3'] = key
print(df)
Output:
col1 col2 col3
0 1 6 odd
1 2 7 even
2 3 8 odd
3 4 9 even
4 5 10 odd
