5

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.

rafaelc
  • 57,686
  • 15
  • 58
  • 82
primadonna
  • 142
  • 4
  • 12
  • 4
    What should be displayed if you have several entries in your dataframe? – cglacet Apr 06 '19 at 23:09
  • Then I have to somehow print that info for only one row. For example I have rows "car1", "car2", "car3". If user types "car1" I need to print car1 line – primadonna Apr 10 '19 at 19:50

3 Answers3

2

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
cglacet
  • 8,873
  • 4
  • 45
  • 60
1

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.

  • ```for i in range (len (dtf)): print(f'{dtf.loc[i]}\n')``` or ```for row in dtf.to_string(index = False).split('\n'): print(row)``` may also be used but not what author has asked. – Subham Mar 18 '21 at 03:33
0

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]
Subham
  • 397
  • 1
  • 6
  • 14