DataFrame:查询列是否具有负值和正值

ee7vknir  于 2022-09-21  发布在  其他
关注(0)|答案(4)|浏览(206)

我有一个非常大的数据框,里面有meterid零售价。当同时存在正值和零值时,我只想输出meterIds。我当前的查询性能非常重,我还无法检查其正确性。

有没有更有表现力的方式?

d = {'meterId': ["x", "x", "y", "y", "z", "z"], 'retailPrice': [1, 0, 0, 0, 1, 1]}
df = pd.DataFrame(data=d)
df
tmp = pd.DataFrame(df["meterId"])
for x in tmp["meterId"]:`
    zero_values = pd.DataFrame(df.loc[(df['meterId'] == x) & df['retailPrice'] == 0)])
    positive_values = pd.DataFrame(df.loc[(df['meterId'] == x) & (df['retailPrice'] > 0)])
    if not zero_values.empty and not positive_values.empty:
        print("meterID: " + str(x))

我的输出应该如下所示:"meterID: x"

toiithl6

toiithl61#

In [113]: pos = df.retailPrice >  0

In [114]: zer = df.retailPrice == 0

In [115]: pos.groupby(df.meterId).any() & zer.groupby(df.meterId).any()
Out[115]:
meterId
x     True
y    False
z    False
Name: retailPrice, dtype: bool

In [116]: _[_].index.tolist()
Out[116]: ['x']
  • 获取e1d0d1是否可信掩码
  • 获取zero是否屏蔽
  • 按ID对这些掩码进行分组,并检查any值是否满足它们
  • 由于需要*位置和零,&它们;提供ID的真/假序列作为所需结果
  • 使用自身对其进行索引,以仅保留WHERE True并获取索引

_是最后一个赋值的东西,所以我用它引用前面的输出。你可以在115做s = ...,也可以做s[s].index.tolist()

8yoxcaq7

8yoxcaq72#

这也是可行的:

for id_, group in df.groupby(['meterId'])['retailPrice']:
    if (group==0).any() & (group>0).any():
        print(f"meter id: {id_}")

Mustafa Aydın's更优雅。

mhd8tkvw

mhd8tkvw3#

下面是使用group by的另一种方法,让我们知道哪种方法性能更好:

res = df.groupby('meterId')['retailPrice'].apply(lambda x: (x > 0).sum() > 0 and (x == 0).sum() > 0)
out = res[res].index.tolist()
t5fffqht

t5fffqht4#

您可以尝试:


# df

    meterId retailPrice
0   x       1
1   x       0
2   y       0
3   y       0
4   z       1
5   z       1

zero_values_condition      = df['meterId'].eq('x') & df['retailPrice'].eq(0) #eq() means ==
positive_values_condition  = df['meterId'].eq('x') & df['retailPrice'].gt(0) #gt() means >
df['new_col'] = np.where((zero_values_condition|positive_values_condition), "meterID: x", '')

df
    meterId retailPrice new_col
0   x       1           meterID: x
1   x       0           meterID: x
2   y       0   
3   y       0   
4   z       1   
5   z       1

相关问题