我有一个看起来像这样的数据框(新):
num name1 name2
11 A AB
14 Y YX
25 L LS
39 Z ZT
....
我只是想在print语句中提取num值,这样我的输出看起来像这样:
The value is 11
The value is 14
The value is 25
...
我不确定这样做的正确格式是什么,因为下面的代码只是迭代“值是”。
for index, row in new.iterrows():
print('The value is').format(new['num'])
答案 0 :(得分:5)
使用str.join
和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
略有变化,以及更多显示如何使用print
功能...
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
答案 1 :(得分:3)
略微更改您的代码
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
答案 2 :(得分:2)
您可以直接遍历Series
对象(与DataFrame
对象不同)。这允许你这样做:
for num in new['num']:
print('The value is ' + str(num))
答案 3 :(得分:2)
您还可以尝试以下操作:
for val in new.num: print('This is ', val)
结果:
This is 11
This is 14
This is 25
This is 39