df = pd.DataFrame({
"Continent": list("AAABBBCCD"),
"Country": list("FGHIJKLMN"),
"Population": [90, 140, 50, 80, 80, 70, 50, 125, 50]})正如所解释的那样,我想把每一个大陆上所有国家都不到100的所有行还给我们。
Continent Country Population
0 A F 90
1 A G 140
2 A H 50
3 B I 80
4 B J 80
5 B K 70
6 C L 50
7 C M 125
8 D N 50A大陆的每一行都被移除,因为G国的人口超过100。因为国家M,C大陆的每一行都被删除了。我希望返回的DataFrame如下所示:
Continent Country Population
3 B I 80
4 B J 80
5 B K 70
8 D N 50我试过df[df["Population"] <= 100],但无法决定如何适应欧洲大陆。
发布于 2022-11-21 01:02:50
这里有一种方法
# groupby on continent
# using makes the row True/False, whether max for the group is below 100
out=df[df.groupby(['Continent'])['Population'].transform(lambda x: x.max()<100)]
outContinent Country Population
3 B I 80
4 B J 80
5 B K 70
8 D N 50发布于 2022-11-21 02:20:26
这里有另一种方法来完成它
import pandas as pd
df = pd.DataFrame({
"Continent": list("AAABBBCCD"),
"Country": list("FGHIJKLMN"),
"Population": [90, 140, 50, 80, 80, 70, 50, 125, 50]})
df.loc[df.groupby(['Continent'])['Population'].transform('max') <= 100]我通常不喜欢使用lambda,因为它是如此缓慢,但上面的答案也有效。这只是另一种选择
https://stackoverflow.com/questions/74513188
复制相似问题