Search code examples
pythonpandaspython-docx

How to print individual rows of a pandas dataframe using Python?


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?


Solution

  • 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))