Python Pandas - 数据帧列中的查询和布尔值

问题描述 投票:0回答:1

我有一个包含多个列的数据框,我想根据几个标准进行查询。

我的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':是的,'CostTable':'标准'}

我想做一个像这样的查询df.query('IsInScope'== True&'CostTable'=='标准')但是当我这样做时,我得到一个空的df。我认为问题来自于pandas在查询中管理布尔值的方式,阅读了这个帖子:How to use query function with bool in python pandas?

当我通过'YES'/'NO'等字符串更改我的'IsInScope'输入时,我使用'YES'而不是True进行查询,那么它完美地工作,所以我知道它来自查询部分。

唯一的问题是我不知道如何在这个例子中正确地进行我的查询。

我应该将我的列转换为字符串而不使用布尔值吗?

我试图将IsInScope列的dtype更改为bool,并且它不会改变任何内容。

我的'IsInCEEScope'的类型是bool。

我希望我已经清楚了

谢谢你的帮助

问候,

埃里克

python pandas dataframe
1个回答
1
投票

我们可以通过多种方式解决您的问题,我将在这里向您展示两种方式。

  1. 随着Boolean indexing
  2. 随着查询。

请注意,由于您的IsInScope列是bool类型,我们可以清理您的代码,如下所示:


1. Boolean indexing

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

2. DataFrame.query

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 qazxsw poi:

IsInScope == True

产量

x = [True, False]

for y in x:
    if y:
        print(y)
© www.soinside.com 2019 - 2024. All rights reserved.