2

newbie to Python.

I'm trying to extract data from a dataframe and put it into a string to print to a docx file.

This is my current code:


add_run("Placeholder A").italic= True

for i in range(0, list(df.shape)[0]):
    A = df.iloc[findings][0]
    B = df.iloc[findings][1] 
    C =df.iloc[findings][2] 
output = ('The value of A: {}, B: {}, C: {}').format(A,B,C)
doc.add_paragraph(output)

The output I am after is:

Placeholder A

  • print output for row 1 of DF

Placeholder A

  • print output for row 2 of DF

Currently it is printing all the outputs of the dataframe under Placeholder A.

Any ideas where I am going wrong?

1 Answers1

1

Here (stackoverflow - How to iterate over rows in a DataFrame in Pandas?) you can find help with iterating over pandas dataframe rows. Rest to do is just to print(row) :)

edit:

Here is example (made based on answer from link) of code that prints rows from previously created dataframe:

import pandas as pd

inp = [{'c1': 10, 'c2': 100, 'c3': 100}, {'c1': 11, 'c2': 110, 'c3': 100}, {'c1': 12, 'c2': 120, 'c3': 100}]
df = pd.DataFrame(inp)

for index, row in df.iterrows():
    A = row["c1"]
    B = row["c2"]
    C = row["c3"]
    print('The value of A: {}, B: {}, C: {}'.format(A, B, C))

Community
  • 1
  • 1
Damian
  • 548
  • 6
  • 14
  • Thank you! I replaced the first line of code with `for row in df.iterrows():` , this does print only the first row, however, the loop does not go onto the next section to print row 2. Any ideas where I am going wrong? –  May 09 '19 at 13:50
  • @q21311 I edited my post and added example of iterating over rows :) – Damian May 09 '19 at 14:09