How to write in a specific cell with pandas and iterrows?

Question:

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.

Asked By: clemdcz

||

Answers:

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"
Answered By: M.verdegaal
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.