gpt4 book ai didi

python - 基于列值的 Pandas DataFrame 操作

转载 作者:太空宇宙 更新时间:2023-11-04 05:50:30 24 4
gpt4 key购买 nike

假设我有一个 Pandas Dataframe,格式如下,基于“Dict of Dicts”组列表(也在下面)......

ITEMS={
“Item_group1”:{‘Stuff’:’Some stuf’
‘More Stuff’:’Extra Stuff’
Group:[[Iteration1, 18, 25,0], [Iteration1, 43, 67,1], [Iteration1, 87, 76,1],
[Iteration2, 45, 29,0], [Iteration2, 44, 77,1], [Iteration2, 43, 74,0]],

}
“Item_group2”:{‘Stuff’:’Some stuf’
‘More Stuff’:’Extra Stuff’
Group:[[Iteration1, 75, 564,0], [Iteration1, 21, 87,1], [Iteration1, 7, 5,1],
[Iteration2, 54, 24,0], [Iteration2, 7, 45,1], [Iteration2, 45, 745,0]],
}

以下格式的DataFrame……

Iteration   Value1  Value2  Feature Active
Iteration1 18 25 0
Iteration1 3 67 1
Iteration1 87 76 1
Iteration2 45 29 0
Iteration2 44 7 1
Iteration2 43 74 0

我将如何根据“Feature Active”== 1 来分离和计算每次迭代的平均值,并忽略任何“Feature Active”==0 条目?

我有以下代码来计算 Value1 和 Value2 在将“Iteration”和“Feature Active”作为键分开后的每次迭代统计数据,但它显示“Feature Active”==0,我并不关心。

FeatureAvgs = Item_group1_DF.groupby(['Iteration’,’Feature Active'])
print np.round(FeatureAvgs[['Value1','Value2']].describe(), decimals=1)

产生以下输出……(忽略实际数字,这是从另一个数据框中获取的)

Iteration   Feature Enabled
Iteration1 0 count 3672.0 3672.0
mean -1352.5 0.0
std 220.5 0.0
min -1920.0 0.0
25% -1507.2 0.0
50% -1267.0 0.0
75% -1184.0 0.0
max -785.0 0.0
1 count 580.0 580.0
mean -1368.6 -1394.5
std 151.5 157.7
min -1788.0 -1805.0
25% -1454.2 -1490.2
50% -1335.5 -1361.0
75% -1270.0 -1291.0
max -1045.0 -1033.0
Iteration2 0 count 20612.0 20612.0
mean -1073.5 0.0
std 142.3 0.0
min -1730.0 0.0
25% -1088.0 0.0
50% -1036.0 0.0
75% -1005.0 0.0
max -805.0 0.0
1 count 14718.0 14718.0
mean -1113.6 -1161.1
std 129.3 134.9
min -1773.0 -1818.0
25% -1151.0 -1214.0
50% -1095.0 -1122.0
75% -1043.0 -1075.0
max -832.0 -897.0

但我只是在该功能处于事件状态 (==1) 时的平均值之后。很抱歉问了这么长的问题,但我是 Pandas 的新手,并且仍在阅读文档

最佳答案

您可以先过滤初始 df,而不是过滤 groupby 对象:

FeatureAvgs = Item_group1_DF[item_group1_DF['Feature Enabled'] == 1].groupby(['Iteration’,’Feature Active'])[['Value1','Value2']].mean()

也没有必要使用 describe如果你只想要 mean只需使用 mean ,顺便说一句,您可以访问 mean describe 的结果列通过使用:

print np.round(FeatureAvgs[['Value1','Value2']].describe()['mean'], decimals=1)

关于python - 基于列值的 Pandas DataFrame 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30505591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com