Python 在数据帧中迭代保存输出

Python 在数据帧中迭代保存输出,python,pandas,for-loop,Python,Pandas,For Loop,“我的数据集”包含一列,该列的名称是我要在for循环中检查的: Name Age John 32 Luke 23 Christine 54 Mary 39 AnneMarie 42 Eoin 23 # initialization name_lists, score_lists = [], [] for name in df['Name']: # missing code for c in zip(names, sc

“我的数据集”包含一列,该列的名称是我要在for循环中检查的:

Name      Age

John      32
Luke      23
Christine  54
Mary      39
AnneMarie  42
Eoin      23
# initialization
name_lists, score_lists = [], []

for name in df['Name']: 

    # missing code
    for c in zip(names, scores):
         print(c)

    name_lists.append(names)
    score_lists.append(scores)

# update the data frame
df['Friends'] = name_lists
df['Score'] = score_lists
我需要通过一个网站来检查它们,该网站会生成一对(“名称”,分数),其中分数是一个数字。 这一对来自以下代码(它无法工作,因为它仅用于显示我如何在数据帧中获得所需的数据)

例如,当
name=John
时,
c
给我以下输出:

('Julie', 6.7)
('Michael', 3.4)
('John John', 3.1)
('Ludo', 3.0)
('Chris', 3.0)
('Mary', 2.7)
('Michael', 2.1)
('Bill', 3.5)
('Jess', 3.2)
name=Luke
时,
c
给我以下输出:

('Julie', 6.7)
('Michael', 3.4)
('John John', 3.1)
('Ludo', 3.0)
('Chris', 3.0)
('Mary', 2.7)
('Michael', 2.1)
('Bill', 3.5)
('Jess', 3.2)
等等

我想在我的数据框中添加此信息,以便获得如下内容:

 Name      Age                  Friends                        Score
    
    John      32     [Julie, Michael, John John, Ludo, Chris]  [6.7, 3.4, 3.1, 3.0, 3.0]
    Luke      23     [Mary, Michael, Bill, Jess]               [2.7,2.1, 3.5, 3.2]
    Christine  54
    Mary      39
    AnneMarie  42         ....
    Eoin      23
如果您能在这方面提供帮助,我将不胜感激,告诉我如何使用
name
列中每个名称的结果c来获得类似的数据帧。

请尝试:

# add index here
for idx,name in df['Name'].iteritems(): 

    # missing code
    for c in zip(names, scores):
         print(c)

    df.loc[idx, 'Friends'] = names
    df.loc[idx, 'Score'] = scores
或者,您可以更好地聚合所有名称和分数,并在for循环后分配一次:

Name      Age

John      32
Luke      23
Christine  54
Mary      39
AnneMarie  42
Eoin      23
# initialization
name_lists, score_lists = [], []

for name in df['Name']: 

    # missing code
    for c in zip(names, scores):
         print(c)

    name_lists.append(names)
    score_lists.append(scores)

# update the data frame
df['Friends'] = name_lists
df['Score'] = score_lists
对于不太大的数据帧,后一种代码略快于前一种代码。对于较大的数据帧,
重复追加
可能非常慢