Home > front end >  How to write in a specific cell with pandas and iterrows?
How to write in a specific cell with pandas and iterrows?

Time:10-29

I'm trying to learn how to use both excel and python. And i'm trying to found out how to write in a speicific cell with pandas. This is what i tought would work :

import pandas as pd

raw_data = pd.read_excel(filepath, sheet_name="Feuil2")

for row in raw_data.iterrows():
    print(row[1]['name'])
    row[1]['name'] = "Cassandra"

I very much like the fact that it's loops through the cells in a column and it would be easier doing this (i found) than using OpenPyxl and doing something like this :

from openpyxl import load_workbook
workbook = load_workbook(filepath)
sheet = workbook.worksheets[1]

my_cell = sheet['A6']

my_cell.value = "ME"

What i really need help on is using the iterrows function and write in a cell.

CodePudding user response:

Your code doesn't work because df.itterrows() yields new Series, and you're modifying those instead of your original dataframe. Additionally, your "row" is a tuple of the row index and the row object, which may be confusing you. Here's how you could do it (or via some of the other indexing methods).

for i, row in df.iterrows():
    df.loc[i, 'name'] = "Cassandra"
  • Related