Groupby 多列并获得其他两列的总和,同时保持每隔一列的第一次出现
Groupby multiple columns and get the sum of two other columns while keeping the first occurrence of every other column
我会尽量切题。所以我有一个包含 100 列的 df,我想对其中两列进行分组,同时获得另外两列的总和。就此而言,我已经使用了 groupby + agg 函数。问题是,在这样做的同时,我仍然想保留剩余的 96 列,因此我想保留这 96 列中每个值的第一次出现。为此,我在考虑诸如删除重复项和保留 = 'first'.
我搜索了一种可以一次完成该操作的方法,但此时我愿意听取您可能提出的任何建议。
注意:出于某种原因,我没有包含示例 df 和所需的输出,因为我想根据建议自己尝试,我并不是想直接从某人那里获得解决方案。
提前致谢,
我认为对 groupby 对象使用两个单独的操作并在之后加入它们比 one-liner 更清晰。这是一个最小的例子,在 1 列上分组:
df = pd.DataFrame(
[
("bird", "Falconiformes", 389.0, 5.5, 1),
("bird", "Psittaciformes", 24.0, 4.5, 2),
("mammal", "Carnivora", 80.2, 33.3, 1),
("mammal", "Primates", np.nan, 33.7, 2),
("mammal", "Carnivora", 58, 23, 3),
],
index=["falcon", "parrot", "lion", "monkey", "leopard"],
columns=("class", "family", "max_speed", "height", "order"),
)
print(df, "\n")
grouped = df.groupby('class')
df_sum = grouped[['max_speed', 'height']].agg(sum)
df_first = grouped['order'].first()
df_out = pd.concat([df_sum, df_first], axis=1)
print(df_out)
输出:
class family max_speed height order
falcon bird Falconiformes 389.0 5.5 1
parrot bird Psittaciformes 24.0 4.5 2
lion mammal Carnivora 80.2 33.3 1
monkey mammal Primates NaN 33.7 2
leopard mammal Carnivora 58.0 23.0 3
max_speed height order
class
bird 413.0 10.0 1
mammal 138.2 90.0 1
我会尽量切题。所以我有一个包含 100 列的 df,我想对其中两列进行分组,同时获得另外两列的总和。就此而言,我已经使用了 groupby + agg 函数。问题是,在这样做的同时,我仍然想保留剩余的 96 列,因此我想保留这 96 列中每个值的第一次出现。为此,我在考虑诸如删除重复项和保留 = 'first'.
我搜索了一种可以一次完成该操作的方法,但此时我愿意听取您可能提出的任何建议。
注意:出于某种原因,我没有包含示例 df 和所需的输出,因为我想根据建议自己尝试,我并不是想直接从某人那里获得解决方案。
提前致谢,
我认为对 groupby 对象使用两个单独的操作并在之后加入它们比 one-liner 更清晰。这是一个最小的例子,在 1 列上分组:
df = pd.DataFrame(
[
("bird", "Falconiformes", 389.0, 5.5, 1),
("bird", "Psittaciformes", 24.0, 4.5, 2),
("mammal", "Carnivora", 80.2, 33.3, 1),
("mammal", "Primates", np.nan, 33.7, 2),
("mammal", "Carnivora", 58, 23, 3),
],
index=["falcon", "parrot", "lion", "monkey", "leopard"],
columns=("class", "family", "max_speed", "height", "order"),
)
print(df, "\n")
grouped = df.groupby('class')
df_sum = grouped[['max_speed', 'height']].agg(sum)
df_first = grouped['order'].first()
df_out = pd.concat([df_sum, df_first], axis=1)
print(df_out)
输出:
class family max_speed height order
falcon bird Falconiformes 389.0 5.5 1
parrot bird Psittaciformes 24.0 4.5 2
lion mammal Carnivora 80.2 33.3 1
monkey mammal Primates NaN 33.7 2
leopard mammal Carnivora 58.0 23.0 3
max_speed height order
class
bird 413.0 10.0 1
mammal 138.2 90.0 1