primadonna
primadonna

Reputation: 152

Making a string out of pandas DataFrame

I have pandas DataFrame which looks like this:

 Name  Number    Description
 car   5         red

And I need to make a string out of it which looks like this:

"""Name: car

Number: 5 

Description: red"""

I'm a beginner and I really don't get how do I do it? I'll probably need to apply this to some similar DataFrames later.

Upvotes: 5

Views: 293

Answers (3)

Subham
Subham

Reputation: 411

Another approach,

import pandas as pd

dtf = pd.DataFrame({
    "Name": ["car", "other"],
    "Number": [5, 6],
    "Description": ["red", "green"]
})


for row_index in range(len(dtf)):
    for col in dtf.columns:
        print(f"{col}: {dtf.loc[row_index, col]}")
Name: car
Number: 5
Description: red
Name: other
Number: 6
Description: green

[Program finished]

Upvotes: 0

Zapperdulchen
Zapperdulchen

Reputation: 31

Iterating over a Dataframe is faster when using apply.

import pandas as pd

df = pd.DataFrame({
    "Name": ["car", "other"],
    "Number": [5, 6],
    "Description": ["red", "green"]
})

s = '\n'.join(
        df.apply(
            lambda row: 
            '\n'.join(f'{head}: {val}' for head, val in row.iteritems()),
            axis=1))

Of course, for this small data set a for loop is faster, but on my machine a data set with 10 rows was already processed faster.

Upvotes: 1

cglacet
cglacet

Reputation: 10944

You can use iterrows to iterate over you dataframe rows, on each row you can then get the columns and print the result the way you want. For example:

import pandas as pd

dtf = pd.DataFrame({
    "Name": ["car", "other"],
    "Number": [5, 6],
    "Description": ["red", "green"]
})

def stringify_dataframe(dtf):
    text = ""
    for i, row in dtf.iterrows():
        for col in dtf.columns.values:
            text += f"{col}: {row[col]}\n"
        text += "\n"
    return text

s = stringify_dataframe(dtf)

Now s contains the following:

>>> print(s)
Name: car
Number: 5
Description: red

Name: other
Number: 6
Description: green

Upvotes: 2

Related Questions