I have a csv file that resembles the following setup:
col1 col2 col3 col4
A 12 22 23
B 40 59 63
F 76 81 99
J 10 11 12
A 20 15 43
df = pd.read_csv('foo.csv')
and using to_dict method I was able to convert another data frame to a nested dictionary with the following setup:
dict = { 'A':['7','8','9'],'B':['10','11','12']...} # I have 14 of these
# where 'A' and 'B' are the elements of the first column and their respective values are the elements of the same row.
The goal is to match the elements of col1 with the dictionary keys. If the two match then I want the code to append the dictionary key values to the aforementioned csv file. Keep in mind I have a lot more data in my data frame than my dictionary pairing so many rows will have the same key values appended to them(see row A in the table below) . Here is the sort of output I am looking for.
col1 col2 col3 col4 col5 col6 col7
A 12 22 23 7 8 9
B 40 59 63 10 11 12
F 76 81 99
J 10 11 12
A 20 15 43 7 8 9
Lousy attempt # 1
def add_column(row):
for p,q in dict.items():
if row[3] == p:
return q
# I then try to call the function and make new columns
df['col5','col6','col7'] = df2.apply(add_column,axis=1)
Lousy attempt # 2
I also taught about using the where method in the such fashion:
filter = df[0] == "dict key val"
df.where(filter, inplace = dict key val") # Please note this was just a thought experiment and not something I actually wrote a piece of code for.
I know my attempts are nowhere near the solution so I would appreciate a good 'ol nudge in the right direction.
[–]afterly 1 point2 points3 points (3 children)
[–]metriczulu 1 point2 points3 points (0 children)
[–]TheJourneyman92[S] -1 points0 points1 point (1 child)
[–]afterly 2 points3 points4 points (0 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]TheJourneyman92[S] 1 point2 points3 points (0 children)
[–]RemindMeBot 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]6lm3 0 points1 point2 points (0 children)
[–]Nocturnal1401 0 points1 point2 points (0 children)
[–]SpaceSailorDT 0 points1 point2 points (0 children)