我想更高效地从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中获取值?