EA00
EA00

Reputation: 633

Pandas, print variable in string

I have a dataframe (new) that looks something like this:

num  name1  name2
11    A      AB
14    Y      YX
25    L      LS
39    Z      ZT
....

and I just want to extract the num value in a print statement such that I have an output that looks like this:

The value is 11
The value is 14
The value is 25
...

I'm not sure what the correct format to do this is, as the following bit of code just iterates "The value is".

 for index, row in new.iterrows():
     print('The value is').format(new['num'])

Upvotes: 5

Views: 6760

Answers (4)

BENY
BENY

Reputation: 323276

Slightly change your code

for index, row in df.iterrows():
    print('The value is {0}'.format(row['num']))
    
The value is 11
The value is 14
The value is 25
The value is 39

With f-strings:

for index, row in df.iterrows():
    print(f"The value is {row['num']}")

To print multiple columns, using dot notation:

for index, row in df.iterrows():
    print(f"{row.name1} and {row.name2} have a value of {row.num}")

A and AB have a value of 11
Y and YX have a value of 14
L and LS have a value of 25
Z and ZT have a value of 39

Upvotes: 4

niraj
niraj

Reputation: 18208

You can also try following:

for val in new.num: print('This is ', val)

Result:

This is  11
This is  14
This is  25
This is  39

Upvotes: 2

Alex Olteanu
Alex Olteanu

Reputation: 4248

You can loop directly through a Series object (unlike through a DataFrame object). This allows you to do:

for num in new['num']:
    print('The value is ' + str(num))

Upvotes: 3

piRSquared
piRSquared

Reputation: 294318

Use str.join and f-strings

print('\n'.join(f'The value is {n}' for n in new.num))

The value is 11
The value is 14
The value is 25
The value is 39

A slight variant and more to show how to use the print function...

print(*(f'The value is {n}' for n in new.num), sep='\n')

The value is 11
The value is 14
The value is 25
The value is 39

Upvotes: 5

Related Questions