add new column to dataframe with values matching the keys with existing column in dataframe in python
Question:
fairly new to python and pandas/numpy. I have a data frame and a dictionary. I need to add a new column in the data frame where the values would be the values from dictionary for the matching dictionary keys with the existing column in data frame. and have empty string for non matching values.
Name
Fonder
Year
0
company1
person1
1999
1
company2
person2
2000
2
company3
person3
2001
3
company4
person4
2002
4
company5
person5
2003
col_dict = {'company2': 'abc', 'company4': 'xyz',}
I want the following
Name
Fonder
Year
new_col
0
company1
person1
1999
1
company2
person2
2000
abc
2
company3
person3
2001
3
company4
person4
2002
xyz
4
company5
person5
2003
Answers:
You can use map
:
df['new_col'] = df['Name'].map(col_dict).fillna('')
print(df)
# Output
Name Fonder Year new_col
0 company1 person1 1999
1 company2 person2 2000 abc
2 company3 person3 2001
3 company4 person4 2002 xyz
4 company5 person5 2003
fairly new to python and pandas/numpy. I have a data frame and a dictionary. I need to add a new column in the data frame where the values would be the values from dictionary for the matching dictionary keys with the existing column in data frame. and have empty string for non matching values.
Name | Fonder | Year | |
---|---|---|---|
0 | company1 | person1 | 1999 |
1 | company2 | person2 | 2000 |
2 | company3 | person3 | 2001 |
3 | company4 | person4 | 2002 |
4 | company5 | person5 | 2003 |
col_dict = {'company2': 'abc', 'company4': 'xyz',}
I want the following
Name | Fonder | Year | new_col | |
---|---|---|---|---|
0 | company1 | person1 | 1999 | |
1 | company2 | person2 | 2000 | abc |
2 | company3 | person3 | 2001 | |
3 | company4 | person4 | 2002 | xyz |
4 | company5 | person5 | 2003 |
You can use map
:
df['new_col'] = df['Name'].map(col_dict).fillna('')
print(df)
# Output
Name Fonder Year new_col
0 company1 person1 1999
1 company2 person2 2000 abc
2 company3 person3 2001
3 company4 person4 2002 xyz
4 company5 person5 2003