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

2024-09-26 18:15:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe,它有几个列,我想根据几个标准进行查询。在

我的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'}

我想做一个这样的查询数据框查询('IsInScope'==True&;CostTable'=='Standard'),但是当我这样做时,我得到一个空的df。我认为问题来自pandas在查询中管理boolean的方式,读过这个线程:How to use query function with bool in python pandas?

当我用'YES'/'NO'这样的字符串更改'isnscope'输入,并且我用'YES'代替True执行查询,那么它就完美地工作了,所以我知道它来自查询部分。在

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

我是否应该将列转换为字符串而不使用布尔值?在

我试图将IsInScope列的数据类型更改为bool,但它不会更改任何内容。在

我的“isincescope”的类型是bool。在

我希望我已经说清楚了

谢谢你的帮助

谨致问候

埃里克


Tags: 字符串true类型dataframepandasdf主题标准
1条回答
网友
1楼 · 发布于 2024-09-26 18:15:36

我们可以用几种方法来解决你的问题,我在这里向你展示两种方法。在

  1. 使用Boolean indexing
  2. 带查询。在

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


1。布尔索引

df1 = df[df['IsInScope'] & (df['CostTable'] == 'Standard')]

输出

^{pr2}$

2。数据帧.查询在

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

相关问题 更多 >

    热门问题