【发布时间】:2020-02-27 07:26:34
【问题描述】:
数据框
我有很多项目的数据框。
项目由代码“类型”和重量标识。
最后一列表示数量。
|-|------|------|---------|
| | type |weight|quantity |
|-|------|------|---------|
|0|100010| 3 | 456 |
|1|100010| 1 | 159 |
|2|100010| 5 | 735 |
|3|100024| 3 | 153 |
|4|100024| 7 | 175 |
|5|100024| 1 | 759 |
|-|------|------|---------|
兼容性规则
如果满足以下条件,给定项目“A”与其他项目“兼容”:
- 是同一类型
- 其他物品的重量等于或小于物品“A”的重量
预期的结果
我想为每一行添加一个“兼容数量”列,计算有多少项目是兼容的。
|-|------|------|---------|---------------------|
| | type |weight|quantity | compatible quantity |
|-|------|------|---------|---------------------|
|0|100010| 3 | 456 | 615 | 456 + 159
|1|100010| 1 | 159 | 159 | 159 only (the lightest items)
|2|100010| 5 | 735 | 1350 | 735 + 159 + 456 (the heaviest)
|3|100024| 3 | 153 | 912 | 153 + 759
|4|100024| 7 | 175 | 1087 | ...
|5|100024| 1 | 759 | 759 | ...
|-|------|------|---------|---------------------|
我想避免使用 For 循环来得到这个结果。 (数据框很大)。
我的代码使用 For 循环
import pandas as pd
df = pd.DataFrame([[100010, 3, 456],[100010, 1, 159],[100010, 5, 735], [100024, 3, 153], [100024, 7, 175], [100024, 1, 759]],columns = ["type", "weight", "quantity"])
print(df)
for inc in range(df["type"].count()):
the_type = df["type"].iloc[inc]
the_weight = df["weight"].iloc[inc]
the_quantity = df["quantity"].iloc[inc]
df.at[inc,"quantity_compatible"] = df.loc[(df["type"] == the_type) & (df["weight"] <= the_weight),"quantity"].sum()
print(df)
一些可能的想法
- “应用”或“转换”有用吗?
- 可以在 loc 中使用 loc 吗?
【问题讨论】:
标签: pandas dataframe pandas-groupby