【发布时间】:2016-08-21 15:25:18
【问题描述】:
我知道 Pandas 并不是真正为与 for 循环一起使用而构建的,但我有一个特定的任务我必须做很多次,如果我可以将其中的一些抽象出来,真的会节省很多时间有一个我可以调用的函数。
我的数据框的通用版本如下所示:
df = pd.DataFrame({'Name': pd.Categorical(['John Doe', 'Jane Doe', 'Bob Smith']), 'Score1': np.arange(3), 'Score2': np.arange(3, 6, 1)})
Name Score1 Score2
0 John Doe 0 3
1 Jane Doe 1 4
2 Bob Smith 2 5
我要做的是采取方法:
df.loc[df.Name == 'Jane Doe', 'Score2']
应该返回 4,但使用这样的 for 循环遍历它:
def pull_score(people, score):
for i in people:
print df.loc[df.Name == people[i], score]
所以如果我愿意,我可以打电话:
the_names = ['John Doe', 'Jane Doe', 'Bob Smith']
pull_score(the_names, 'Score2')
得到:
3
4
5
我目前得到的错误信息是:
TypeError: list indices must be integers, not str
我查看了与此错误消息和 Pandas 相关的其他一些答案,例如这个:Python and JSON - TypeError list indices must be integers not str 和这个:How to solve TypeError: list indices must be integers, not list?
但没有看到我正在尝试做的事情的答案,我不相信iterrows() 或itertuple() 会适用,因为我需要 Pandas 先找到值。
【问题讨论】: