0

I try to iterate over a specific column called Description of the dataframe RCMLocations.

When the value of the column "Description" is equal to the value found in another dataframe called "ultimo_data", then take the value of dataframe "ulimo_data" column "Systeemdeelnummer" and place it in a new column "ID" in the dataframe "RCMLocations".

However, with the code below I can not iterate over the dataframe RCMLocations. How do I solve this problem?

beheerobjecten = ultimo_data["Specifieke_omschrijving_beheerobject"].unique()
RCMLocations["ID"] = ""
for i, row in RCMLocations.iterrows:
    RCMLocations["ID"] = ultimo_data.loc[ultimo_data["Specifieke_omschrijving_beheerobject"] == row["Description"], "Systeemdeelnummer"]

Below is reproducible example of a dataframe:

RCMLocations = pd.DataFrame({"Description": ["Description 0 Weg, 4,300 tm 16,765 KP Zaandam - Purmerend Noord", "Description 1 Weg, 16,765 tm 34,032 Purmerend Noord - Hoorn Noord", "Description 2 Weg, 50,212 tm 64,565 Middenmeer - Den Oever"]})
Tessa
  • 53
  • 6

1 Answers1

0

Besides the typo in your code that will trigger a TypeError, one way to avoid iterrows, is to use :

d = ultimo_data.set_index("Specifieke_omschrijving_beheerobject")["Systeemdeelnummer"]

RCMLocations["ID"] = RCMLocations["Description"].map(d)
Timeless
  • 22,580
  • 4
  • 12
  • 30
  • Thank you for the reply. I got the following error with the code "Reindexing only valid with uniquely valued Index objects". I tried RCMLocations = RCMLocations.reset_index(), but that didn't work. – Tessa May 16 '23 at 13:59
  • Can you make a [minimal-reproducible-example](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) that triggers the error + add it to your question *as text* ? – Timeless May 16 '23 at 14:23
  • The duplicates in my dataframe cause the error. I adjusted your code as follow: d = ultimo_data.drop_duplicates("Specifieke_omschrijving_beheerobject").set_index("Specifieke_omschrijving_beheerobject")["Systeemdeelnummer"]. Here is a link to another post where I found the solution: https://stackoverflow.com/a/50389166/17931594 – Tessa May 22 '23 at 06:00