获取大 pandas 应用功能中的一行的索引 [英] getting the index of a row in a pandas apply function
问题描述
我正在尝试访问在Panda中整个 DataFrame
中应用的函数中的一行的索引。我有这样的东西:
I am trying to access the index of a row in a function applied across an entire DataFrame
in Pandas. I have something like this:
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']
应用它像这样:
df['d'] = df.apply(rowFunc, axis=1)
>>> df
a b c d
0 1 2 3 7
1 4 5 6 34
真棒!现在如果我想将索引并入我的函数呢?
在添加 d
之前, DataFrame
中任何给定行的索引将为索引([u'a',u'b',u'c',u'd'],dtype ='object')
,但我想要0和1.所以我可以'我只需访问 row.index
。
Awesome! Now what if I want to incorporate the index into my function?
The index of any given row in this DataFrame
before adding d
would 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
.
我知道我可以在表中创建一个临时列,索引,但我想知道它是否在某个地方的行对象中被放置。
I know I could create a temporary column in the table where I store the index, but I"m wondering if it is sotred in the row object somewhere.
推荐答案
在这种情况下访问索引访问名称
属性:
To access the index in this case you access the name
attribute:
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
这篇关于获取大 pandas 应用功能中的一行的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!