Search code examples
pythonpython-3.xpandasdataframesklearn-pandas

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.


Solution

  • 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