我有一个包含几列的数据框,我想根据几个条件进行查询。
我的df(我不知道如何使主题上的列对齐):
Date Type IsInScope CostTable Value
2017-04-01 CostEurMWh True Standard 0.22
2018-01-01 CostEurMWh True Standard 0.80
2019-01-01 CostEurMWh True Standard 1.72
2017-04-01 CostEurMWh False Standard 0.00
我还有成千上万的其他带有其他类型和日期的行。
另一方面,我有一些要定价的东西,为了做到这一点,我需要根据参数获得适当的值。
我有一个这样的字典:{'ID':'Customer1','IsInScope':True,'CostTable':'Standard'}
我想执行类似df.query('IsInScope'== True&'CostTable'=='Standard')的查询,但是当我这样做时,会得到一个空的df。我认为问题出在阅读此线程后,是熊猫在查询中管理布尔值的方式:How to use query function with bool in python pandas?
当我通过'YES'/'NO'之类的字符串更改'IsInScope'输入时,我用'YES'而不是True进行查询,那么它运行良好,因此我知道它来自查询部分。 / p>
唯一的问题是在此示例中,我不知道如何正确地进行查询。
我应该将我的列转换为字符串而不使用布尔值吗?
我试图将IsInScope列的dtype更改为bool,并且它没有任何改变。
“ IsInCEEScope”的类型为bool。
我希望我已经清楚
感谢您的帮助
此致
埃里克
答案 0 :(得分:1)
我们可以通过多种方式解决您的问题,在这里我将向您展示两种方式。
Boolean indexing
请注意,由于您的IsInScope
列的类型为bool
,因此我们可以对您的代码进行如下整理:
df1 = df[df['IsInScope'] & (df['CostTable'] == 'Standard')]
输出
print(df1)
Date Type IsInScope CostTable Value
0 2017-04-01 CostEurMWh True Standard 0.22
1 2018-01-01 CostEurMWh True Standard 0.80
2 2019-01-01 CostEurMWh True Standard 1.72
df2 = df.query("IsInScope & CostTable == 'Standard'")
输出
print(df2)
Date Type IsInScope CostTable Value
0 2017-04-01 CostEurMWh True Standard 0.22
1 2018-01-01 CostEurMWh True Standard 0.80
2 2019-01-01 CostEurMWh True Standard 1.72
注意,我们不必明确告诉Python IsInScope == True
:
x = [True, False]
for y in x:
if y:
print(y)
输出
True