繁体   English   中英

根据另一列中的条件从 Pandas 数据框中提取值

[英]Extract Value From Pandas Dataframe Based On Condition in Another Column

我正在尝试开发一些在发电厂启动时提取电价的代码。 举个例子,参考下面的数据框。

data = {
  'Power_Price':  [10, 11,15, 33, 50, 10, 12, 20, 17],
  'Plant_Ops_1': [0, 0, 10, 10, 10, 0, 0, 10, 10],
  'Plant_Ops_2': [0, 0, 0, 50, 50, 0, 0, 0, 0]
}

df = pd.DataFrame (data, columns = ['Power_Price','Plant_Ops_1','Plant_Ops_2'])

基于此,我的目标是开发一些代码,当工厂操作列从 0 转换为大于 0 的数字时(即当发电厂启动时),该代码将存储在数据帧中的电价。 对于上面的数据,输出看起来类似于:

data_out = {
  'Plant': ['Plant_Ops_1', 'Plant_Ops_1', 'Plant_Ops_2'],
  'Power_price': [15, 20, 33]
}

df_out = pd.DataFrame (data_out, columns = ['Plant','Power_price'])

希望这是有道理的。 当然,欢迎您提供任何建议或指导。

你可以这样做:

df = df.melt(id_vars='Power_Price')

df[(df['value'] > df['value'].shift()) & (df['variable'] == df['variable'].shift())]

    Power_Price     variable  value
2            15  Plant_Ops_1     10
7            20  Plant_Ops_1     10
12           33  Plant_Ops_2     50

我希望我已经理解了你的问题:

df = df.melt(id_vars="Power_Price")
x = df["value"].eq(0)
x = df.groupby((x != x.shift()).cumsum()).head(1)
x = x[x["value"] > 0].rename(columns={"variable": "Plant"})[
    ["Plant", "Power_Price"]
]
print(x)

印刷:

          Plant  Power_Price
2   Plant_Ops_1           15
7   Plant_Ops_1           20
12  Plant_Ops_2           33

DataFrame.melt与过滤器行一起使用, DataFrame.melt移位等于0并且在boolean indexing也大于0

df = df.melt('Power_Price', var_name='Plant')

df = df[df.groupby('Plant')['value'].shift().eq(0) & df['value'].gt(0)].drop('value',axis=1)
print (df)
    Power_Price        Plant
2            15  Plant_Ops_1
7            20  Plant_Ops_1
12           33  Plant_Ops_2

如有必要,最后更改列的顺序:

df = df[["Plant", "Power_Price"]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM