Python 在熊猫应用函数中获取行的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26658240/
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
getting the index of a row in a pandas apply function
提问by Mike
I am trying to access the index of a row in a function applied across an entire DataFramein Pandas. I have something like this:
我正在尝试访问DataFrame在 Pandas 中应用于整个函数的行的索引。我有这样的事情:
df = pandas.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df
a b c
0 1 2 3
1 4 5 6
and I'll define a function that access elements with a given row
我将定义一个函数来访问具有给定行的元素
def rowFunc(row):
return row['a'] + row['b'] * row['c']
I can apply it like so:
我可以这样应用它:
df['d'] = df.apply(rowFunc, axis=1)
>>> df
a b c d
0 1 2 3 7
1 4 5 6 34
Awesome! Now what if I want to incorporate the index into my function?
The index of any given row in this DataFramebefore adding dwould be Index([u'a', u'b', u'c', u'd'], dtype='object'), but I want the 0 and 1. So I can't just access row.index.
惊人的!现在如果我想将索引合并到我的函数中怎么办?DataFrame添加之前任何给定行的索引d都是Index([u'a', u'b', u'c', u'd'], dtype='object'),但我想要 0 和 1。所以我不能只访问row.index.
I know I could create a temporary column in the table where I store the index, but I'm wondering if it is stored in the row object somewhere.
我知道我可以在存储索引的表中创建一个临时列,但我想知道它是否存储在行对象中的某处。
采纳答案by EdChum
To access the index in this case you access the nameattribute:
要在这种情况下访问索引,请访问name属性:
In [182]:
df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
def rowFunc(row):
return row['a'] + row['b'] * row['c']
def rowIndex(row):
return row.name
df['d'] = df.apply(rowFunc, axis=1)
df['rowIndex'] = df.apply(rowIndex, axis=1)
df
Out[182]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
Note that if this is really what you are trying to do that the following works and is much faster:
请注意,如果这确实是您要尝试执行的操作,则以下方法有效并且速度要快得多:
In [198]:
df['d'] = df['a'] + df['b'] * df['c']
df
Out[198]:
a b c d
0 1 2 3 7
1 4 5 6 34
In [199]:
%timeit df['a'] + df['b'] * df['c']
%timeit df.apply(rowIndex, axis=1)
10000 loops, best of 3: 163 μs per loop
1000 loops, best of 3: 286 μs per loop
EDIT
编辑
Looking at this question 3+ years later, you could just do:
3 年后看这个问题,你可以这样做:
In[15]:
df['d'],df['rowIndex'] = df['a'] + df['b'] * df['c'], df.index
df
Out[15]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
but assuming it isn't as trivial as this, whatever your rowFuncis really doing, you should look to use the vectorised functions, and then use them against the df index:
但假设它不像这样微不足道,无论您rowFunc真正在做什么,您都应该考虑使用矢量化函数,然后将它们用于 df 索引:
In[16]:
df['newCol'] = df['a'] + df['b'] + df['c'] + df.index
df
Out[16]:
a b c d rowIndex newCol
0 1 2 3 7 0 6
1 4 5 6 34 1 16
回答by smci
Either:
任何一个:
1. with row.nameinside the apply(..., axis=1)call:
1.与row.name内apply(..., axis=1)通话:
df = pandas.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'], index=['x','y'])
a b c
x 1 2 3
y 4 5 6
df.apply(lambda row: row.name, axis=1)
x x
y y
2. with iterrows()(slower)
2.与iterrows()(较慢)
DataFrame.iterrows()allows you to iterate over rows, and access their index:
DataFrame.iterrows()允许您遍历行,并访问它们的索引:
for idx, row in df.iterrows():
...
回答by Freek Wiekmeijer
To answer the original question: yes, you can access the index value of a row in apply(). It is available under the key nameand requires that you specify axis=1(because the lambda processes the columns of a row and not the rows of a column).
要回答原始问题:是的,您可以访问apply(). 它在键下可用name并且需要您指定axis=1(因为 lambda 处理行的列而不是列的行)。
Working example (pandas 0.23.4):
工作示例(熊猫 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40

