python怎样根据索引得到值_python-通过列索引获取值,其中行是特定值

我有一个数据框sheet_overview:

Unnamed: 0 Headline Unnamed: 2 Unnamed: 3

0 nan 1. 1. username Erik

1 nan 1. 2. userage 23

2 nan 1. 3. favorite ice

我想通过查找“ 1. 2”来获得值23.在第二栏中.

如果不想查看列名,则必须使用索引.我的问题是,如果我的方法太复杂了.

它可以工作,但似乎太多了,但不是很Pythonic:

age = sheet_overview.iloc[

sheet_overview[

sheet_overview.iloc[:, 1] == '1. 2.']

.index[0], 3]

解决方法:

将values用于numpy数组,以iloc作为过滤器,然后将next用于返回第一个匹配的值-如果不存在,则会丢失:

a = sheet_overview.iloc[(sheet_overview.iloc[:, 1] == '1. 2.').values, 3]

a = next(iter(a), 'missing')

print (a)

23

如果性能很重要,请使用numba:

from numba import njit

@njit

def first_val(A, k):

a = A[:, 0]

b = A[:, 1]

for i in range(len(a)):

if a[i] == k:

return b[i]

return 'missing'

a = first_val(sheet_overview.iloc[:, [1,3]].values, '1. 2.')

标签:pandas,python-3-x,python

来源: https://codeday.me/bug/20191108/2007848.html

你可能感兴趣的:(python怎样根据索引得到值)