Python 使用dataframe中的两列筛选器为变量赋值
我有以下数据:Python 使用dataframe中的两列筛选器为变量赋值,python,pandas,dataframe,Python,Pandas,Dataframe,我有以下数据: df Name Jan Feb Mar Description New A 34 32 54 Old B 65 98 05 Retired C 96 26 43 Description是一个索引列 我正在尝试为变量赋值,如下所示: variable=df[(df['Description']=='Reti
df
Name Jan Feb Mar
Description
New A 34 32 54
Old B 65 98 05
Retired C 96 26 43
Description是一个索引列
我正在尝试为变量赋值,如下所示:
variable=df[(df['Description']=='Retired')和(df['Name']=='C')][“Jan”]
但我得到了一个错误:
ValueError:使用序列设置数组元素
有办法吗?与比较索引一起使用-输出为系列
-具有一个或多个值:
variable = df.loc[(df.index=='Retired') & (df['Name']=='C'), "Jan"]
print (variable)
Description
Retired 96
Name: Jan, dtype: int64
如果需要,请首先选择并始终存在至少一个值,使用:
print (variable.iat[0])
96
但如果可能不匹配,则返回空序列,并且不能像上面那样选择,如果空序列:
variable = df.loc[(df.index=='Retired') & (df['Name']=='another'), "Jan"]
print (variable)
Series([], Name: Jan, dtype: int64)
print (next(iter(variable), 'no match'))
no match
另一个更好的解决方案是将Name
添加到MultiIndex
的索引中,然后选择bytuple
,如果需要标量输出:
df = df.set_index('Name', append=True)
variable = df.loc[('Retired','C'), "Jan"]
print (variable)
96
与比较索引一起使用-输出为系列
-具有一个或多个值:
variable = df.loc[(df.index=='Retired') & (df['Name']=='C'), "Jan"]
print (variable)
Description
Retired 96
Name: Jan, dtype: int64
如果需要,请首先选择并始终存在至少一个值,使用:
print (variable.iat[0])
96
但如果可能不匹配,则返回空序列,并且不能像上面那样选择,如果空序列:
variable = df.loc[(df.index=='Retired') & (df['Name']=='another'), "Jan"]
print (variable)
Series([], Name: Jan, dtype: int64)
print (next(iter(variable), 'no match'))
no match
另一个更好的解决方案是将Name
添加到MultiIndex
的索引中,然后选择bytuple
,如果需要标量输出:
df = df.set_index('Name', append=True)
variable = df.loc[('Retired','C'), "Jan"]
print (variable)
96
因为我将使用这个变量来进一步编码,所以当我输入变量时,它应该只显示96,没有其他显示。是否可以在一行代码中使用df.loc和df.at<代码>无天数=df.loc[df.index,'Name'].位于['Jan']。我无法使用此选项,因为我还必须过滤描述列。@RSM-第二个解决方案是
df=df.set_index('Name',append=True)variable=df.loc[('Retired','C'),“Jan”]print(variable)
,无法使用?抱歉@jezreal,我仍然没有得到一个数字,我得到的输出与Description Name Retired C 96 Name:Jan,dtype:float64
@RSM相同-在最后一段解决方案中?因为我将使用此变量来进一步编码,所以当我输入变量时,它应该只显示96,没有其他显示。是否可以在一行代码中使用df.loc和df.at<代码>无天数=df.loc[df.index,'Name'].位于['Jan']。我无法使用此选项,因为我还必须过滤描述列。@RSM-第二个解决方案是df=df.set_index('Name',append=True)variable=df.loc[('Retired','C'),“Jan”]print(variable)
,无法使用?抱歉@jezreal,我仍然没有得到一个数字,我得到的输出与上一段解决方案中的Description Name退役C 96 Name:Jan,dtype:float64相同?