数据集:
First_Name Last_Name Location
Green White US
Lew Edward UK
Ravi Kumar India
Naveen Reddy France
Yi Ling Singapore
Xin Yi Taiwan
Ryan Nicholas Singapore
Python代码:
import pandas as pd
import numpy as np
df = pd.read_csv (r'data.csv')
def name():
for row in df.iterrows():
name1 = df['First_name']
name2 = df['Last_name']
location = df['Location']
while True:
print(name)
评论:
上面的代码将返回完整的数据帧,并且看起来像一次循环所有df
行。
有没有一种方法可以只循环一行?
示例:
loop1 - Green White US
loop2 - Lew Edward UK
loop3 - Ravi Kumar India
答案 0 :(得分:0)
iterrows()
允许遍历元组索引的行
这是遍历整个数据帧的快速解决方案:
def names():
for i, row in df.iterrows():
name1 = row['First_name']
name2 = row['Last_name']
location = row['Location']
print('{} {} {}'.format(name1, name2, location))
names()