对 pandas DataFrame 中每一行的操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26243993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Operations on every row in pandas DataFrame
提问by user3264659
I want to iterate through every row in a pandas DataFrame, and do something with the elements in each row.
我想遍历 Pandas DataFrame 中的每一行,并对每一行中的元素做一些事情。
Right now I have
现在我有
for row in df.iterrows():
if row['col'] > 1.5:
doSomething
but it tells me that the 'tuple indices must be integers, not str' . How do I access the column that I want in a certain row?
但它告诉我 '元组索引必须是整数,而不是 str' 。如何访问特定行中所需的列?
回答by unutbu
iterrowsyields (index, Series) pairs. Therefore, use:
iterrows产生 (index, Series) 对。因此,使用:
for index, row in df.iterrows():
if row['col'] > 1.5:
doSomething
Note, however, that a DataFrame is a primarily column-based data structure, so you'll get better performance if you can structure your code around column-wise operations, instead of row-wise operations.
但是请注意,DataFrame 主要是基于列的数据结构,因此如果您可以围绕列操作而不是行操作来构建代码,您将获得更好的性能。
回答by ProfVersaggi
Probably the simplest solution is to use the APPLYMAPor APPLYfucntions which applies the function to every data value in the entire data set.
可能最简单的解决方案是使用APPLYMAP或APPLY函数,将函数应用于整个数据集中的每个数据值。
You can execute this in a few ways:
您可以通过以下几种方式执行此操作:
df.applymap(someFunction)
or
或者
df[["YourColumns"]].apply(someFunction)
The Links are below:
链接如下:

