Python 如何通过位置或标签从数据帧的单元格中获取值?

Python 如何通过位置或标签从数据帧的单元格中获取值?,python,pandas,dataframe,Python,Pandas,Dataframe,我读了问题和答案。我有点困惑,在2018年,从pandas数据帧的单元格中获取值的公认方法是什么,因为已经被弃用了,关于的文档也有点稀疏。我想按标签选择行,按位置/整数选择列。以下是我在2018年采用公认方法的方法吗?我有以下代码: import pandas as pd import random import string import csv import io ## Make a table with random column labels and rows in random or

我读了问题和答案。我有点困惑,在2018年,从pandas数据帧的单元格中获取值的公认方法是什么,因为已经被弃用了,关于的文档也有点稀疏。我想按标签选择行,按位置/整数选择列。以下是我在2018年采用公认方法的方法吗?我有以下代码:

import pandas as pd
import random
import string
import csv
import io

## Make a table with random column labels and rows in random order.
s = '\n'.join((
    ## Separate columns by comma.
    ','.join((
        ## Join letters without a separator.
        ''.join((
            ## Randomly choose 3 characters for the labels from ascii_letters.
            random.choice(
                string.ascii_letters) for i in range(3))) for j in range(3))),
    ## Insert a header to distinguish rows with identical index keys x and y.
    '"Header I, II and III"',
    ## Randomly shuffle the rows under the first header.
    '\n'.join(random.sample(('x,0,1', 'y,2,3',), 2)),
    ## Insert a header to distinguish rows with identical index keys x and y.
    '"Header IV, V and VI"',
    ## Randomly shuffle the rows under the second header.
    '\n'.join(random.sample(('x,4,5', 'y,6,7'), 2)),
    ))

def preprocess(s):
    header = ''
    for l in csv.reader(io.StringIO(s)):
        if len(l) == 1:
            header = l[0]
            continue
        ## Append the header to distinguish identical labels x and y.
        l[0] = header + '; ' + l[0]
        yield l

print(s, end='\n\n')
## Preprocess the string to avoid duplicate row index keys x and y.
df = pd.DataFrame(preprocess(s))
print(df, end='\n\n')
## Set the index to be that of the first column.
df = df.set_index(0)
## First select the column by index using iloc
## and then select the relevant row by index label.
value = df.iloc[:,-1]['Header I, II and III; x']
print(value)
它生成一个字符串
s
,如下所示:

YuT,Uva,AsE
"Header I, II and III"
y,2,3
x,0,1
"Header IV, V and VI"
y,6,7
x,4,5
                         0    1    2
0                    ; YuT  Uva  AsE
1  Header I, II and III; y    2    3
2  Header I, II and III; x    0    1
3   Header IV, V and VI; y    6    7
4   Header IV, V and VI; x    4    5
通过函数
preprocess
将其转换为数据帧,如下所示:

YuT,Uva,AsE
"Header I, II and III"
y,2,3
x,0,1
"Header IV, V and VI"
y,6,7
x,4,5
                         0    1    2
0                    ; YuT  Uva  AsE
1  Header I, II and III; y    2    3
2  Header I, II and III; x    0    1
3   Header IV, V and VI; y    6    7
4   Header IV, V and VI; x    4    5
它是带有标签
标题I、II和III的行的最后一列的值(整数1);我对x感兴趣。这是2018年的正确做法吗

value = df.iloc[:,-1]['Header I, II and III; x']
我刚刚读了2015年2月和2015年7月的一些非常有趣的问题。如果我能做这样的事情那就太好了,但我不能:

value = df.at['Header I, II and III; x', -1]
value = df['Header I, II and III; x'][-1]

第一件事是第一件事
ix
已被弃用,但
ix
允许您混合使用标签和索引器,并对传递的内容进行了大量猜测

在当今时代(当前的稳定版本是
v0.22
),
ix
已被弃用,因此请坚持使用显式标签或基于位置的索引器:
loc
用于基于标签的切片,
iloc
用于基于索引的切片<代码>at
用于基于标签的项目访问,而
iat
用于基于索引的项目访问

如果您知道标签是什么,请使用
at
访问单个项目-

df.at['Header I, II and III; x', df.columns[-1]]
如果您知道位置,请使用
iat
-

df.iat[2, -1]
通常,当您想要访问单个元素时,请使用
*at
,当您想要访问行/列切片时,请使用
*loc

这肯定有效:

value = df.at['Header I, II and III; x', df.columns[-1]]
对于像我这样喜欢老式词典的人,如果数据帧不包含重复的行标签,也可以执行以下操作,这会阻止
转置
工作:

d = df.transpose().to_dict('list')
value = d['Header I, II and III; x'][-1]

df.iat[2,-1]
将是正确的方法。或者,
df.at['Header I,II和III;x',2]
@cᴏʟᴅsᴘᴇᴇᴅ 谢谢<代码>标题I、II和III;但是,x不总是在第二行。在这种情况下,
at
会更好。请看我的第二条评论。要回答你的最后一个问题,不,
df.columns
是一个列表/数组,它们支持随机访问。非常感谢!我希望文件能解释这一点。@tommy.carstensen不客气。请考虑接受答案: