获取pandas应用函数中的行索引

时间:2014-10-30 16:22:14

标签: python-2.7 pandas dataframe

我正在尝试访问Pandas中整个DataFrame中应用的函数中的行索引。我有这样的事情:

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

我将定义一个访问具有给定行

的元素的函数
def rowFunc(row):
    return row['a'] + row['b'] * row['c']

我可以这样申请:

df['d'] = df.apply(rowFunc, axis=1)
>>> df
   a  b  c   d
0  1  2  3   7
1  4  5  6  34

真棒!现在如果我想将索引合并到我的函数中呢? 在添加DataFrame之前,此d中任何给定行的索引都是Index([u'a', u'b', u'c', u'd'], dtype='object'),但我想要0和1.所以我不能只访问row.index。< / p>

我知道我可以在存储索引的表中创建一个临时列,但我想知道它是否在某个行对象中被放置了。

3 个答案:

答案 0 :(得分:94)

要在这种情况下访问索引,请访问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

请注意,如果您真的想要这样做,那么以下工作会更快:

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

修改

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

但是假设它不像这样微不足道,无论你的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

答案 1 :(得分:6)

apply()不是您正在寻找的机器人。

DataFrame.iterrows()允许您迭代行,并访问其名称:

for name, row in df.iterrows():
    ...

答案 2 :(得分:2)

要回答原始问题:是的,您可以访问apply()中一行的索引值。它在键name下可用,并且要求您指定axis=1(因为lambda处理一行的列而不是列的行)。

工作示例(熊猫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