5

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'])

4 Answers 4

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Introducing python3.5+ features in my experience never seems to work well with OPs... stackoverflow.com/q/50194179/4909087
Yeah... well... at least non-OPs are free to appreciate it (-:
4

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

Comments

3

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.