0

I want to search with a string in a pandas dataframe A, compare it with another dataframe B and write the value from another column of that dataframe B into the original column in dataframe A. Like:

Table_a:

fruit attribute
apple red
banana yellow
orange orange

Table_b:

fruit size abbrev.
apple large app.
orange medium oran.
peach small pea.
banana medium ban.

So the modified table_a shall be:

fruit attribute
apple app.
banana ban.
orange ora.

How can I search across two dataframes and replace with a specific column from df_b?

This has been my non-working approach so far. Can you help, pls?

table_a["attribute"] = table_a.loc[table_a["fruit"] == table_b["fruit"], table_b["attribute"]
Jones L
  • 9
  • 3
  • Does this answer your question? [Pandas Merging 101](https://stackoverflow.com/questions/53645882/pandas-merging-101) – Chris Nov 04 '21 at 21:18
  • Thanks, but not really. The order can be mixed up in my scenario. So I need something like: take: table_a["fruit"], search with that value in table_b["fruit"], return the appropriate ["abbreviation"]-value and write it in table_a["attribute"]. – Jones L Nov 04 '21 at 21:23
  • You're describing a merge. – Chris Nov 04 '21 at 21:26
  • 1
    `table_a[['fruit']].merge(table_b[['fruit','abbrev.']].rename({'abrev.':'attribute'}), on='fruit', how='left')` – Chris Nov 04 '21 at 21:30
  • Thanks @Chris Unfortunately that does not work, cuz it says: KeyError: 'fruit'. Isn't there a "search and replace"-way instead of merging? – Jones L Nov 04 '21 at 21:44
  • You must not have fruit columns in both dataframes – Chris Nov 04 '21 at 21:49
  • you are right. my bad ;) thank you again. that helped, even though it's a little detour. – Jones L Nov 04 '21 at 22:01

0 Answers0