Home > Blockchain >  Pandas: Writing into cells after iterating over rows
Pandas: Writing into cells after iterating over rows

Time:12-18

I have only a descripton of my problem:

I have a xlsx-list of birthdays for different persons and I want to assign the name of the person to a pandas dataframe where the index is a date. In contrast the xlsx-list has a somewhat index the name of the persons.

There are no two persons in the list with the same birthdays.

Has someone just an easy example how to iterate and write back to a dataframe position which is a date and handles a pandas series.

For example:


df = pd.read_excel(Birthdays.xlsx)

The dataframe whould be look like this:

pd.DataFrame({'Date': [2022-05-01,2022-05-02 ,2022-05-03],},
                index=['Mark', 'Tom', 'Lara'])

for row in df.itertuples():
    if pd.to_datetime(row[0]) in Birthdays:
    df["Birthday",row] = name

Target Dataframe would be look like this:

Time          Address          Birthday
2022-05-01    345yy
2022-05-02    123xx
2022-05-03    456ll

CodePudding user response:

You can reset index on df, then create a dictionary, finally map it to target_df:

df = df.reset_index(names="Name")
birthday_mapping = dict(zip(df["Date"], df["Name"]))
target_df["Birthday"] = target_df["Time"].map(birthday_mapping)

CodePudding user response:

You usually don't need to iterate over rows in pandas. Why do you define the name column as index? Given two columns, date and name with a default index, you could just change the index to the date column:

df = pd.DataFrame({'date': ['2022-05-01', '2022-05-02' ,'2022-05-03'], 'name': ['Mark', 'Tom', 'Lara']})
df = df.set_index('date')
  • Related