我想更高效地从Pandas DataFrame中获取单一值.

这就是我现在的做法:

# import pandas
import pandas as pd

# set up the dataframe
df = pd.DataFrame({'col1':['a','a','b'],'col2':[10,20,20],'col3':[100.0,200.0,300.0]})

# STEP 1 - filter down to a single row with loc
row_of_interest = df.loc[(df['col1'] == 'a') & (df['col2'] > 11)]

# STEP 2 - specify the column of interest
column_and_row_of_interest = row_of_interest['col3']

# STEP 3 - get the value out of dataframe format using to_list and list indexing
value_of_interest = column_and_row_of_interest.to_list()[0]

当然,我可以在一行代码中执行步骤1—3,如下所示:

value_of_interest = df.loc[(df['col1'] == 'a') & (df['col2'] > 11)]['col3'].to_list()[0]  

我想第一步和第二步可能是不可避免的,但第三步感觉笨重.有没有比使用. to_list()[0]更好的方法从形状为(1,1)的DataFrame中获取值?

推荐答案

您可以:

print(column_and_row_of_interest.squeeze())

-哦,不.

print(column_and_row_of_interest.iat[0])

这打印:

200.0

Python相关问答推荐

更改matplotlib彩色条的字体并勾选标签?

pandas DataFrame GroupBy.diff函数的意外输出

try 与gemini-pro进行多轮聊天时出错

由于NEP 50,向uint 8添加-256的代码是否会在numpy 2中失败?

对于一个给定的数字,找出一个整数的最小和最大可能的和

为什么带有dropna=False的groupby会阻止后续的MultiIndex.dropna()工作?

如何将一个动态分配的C数组转换为Numpy数组,并在C扩展模块中返回给Python

isinstance()在使用dill.dump和dill.load后,对列表中包含的对象失败

在www.example.com中使用`package_data`包含不包含__init__. py的非Python文件

什么是合并两个embrame的最佳方法,其中一个有日期范围,另一个有日期没有任何共享列?

使用Python和文件进行模糊输出

使用特定值作为引用替换数据框行上的值

如何杀死一个进程,我的Python可执行文件以sudo启动?

跳过嵌套JSON中的级别并转换为Pandas Rame

递归函数修饰器

有没有一种方法可以在朗肯代理中集成向量嵌入

奇怪的Base64 Python解码

#将多条一维曲线计算成其二维数组(图像)表示

将Pandas DataFrame中的列名的长文本打断/换行为_STRING输出?

如何批量训练样本大小为奇数的神经网络?