gpt4 book ai didi

python - Pandas - 选择列值出现 `n`次的行

转载 作者:行者123 更新时间:2023-12-02 01:27:51 25 4
gpt4 key购买 nike

我正在尝试从 df 本身出现 n 次的 df 的所有条目中检索随机 df 条目,但我面临一些问题。这是我正在使用的代码,其中 n = 2。


d = {
"letters": ["a", "b", "c", "a", "b", "a", "d", "d"],
"one": [1, 1, 1, 1, 1, 1, 1, 1],
"two": [2, 2, 2, 2, 2, 2, 2, 2],
}
df = pd.DataFrame(d)
s = df["letters"].value_counts()
df2 = df.loc[np.where(s.to_numpy() == 2)]
rand = df2.sample(n=1, random_state = 2)

乍一看,这看起来没问题,但检查 df2 会返回 df2["letters"] 有两个条目:“b”和“c”,并且显然“c”在原始 df 中没有出现两次。

我猜这个错误应该是我定义“只查看出现n次的条目,但我无法全神贯注”这一概念的方式。

这是怎么回事?我该如何解决这个问题?

最佳答案

使用Series.map按原始列字母进行过滤:

s = df["letters"].value_counts()
df2 = df[df["letters"].map(s) == 2]

print (df2)
letters one two
1 b 1 2
4 b 1 2
6 d 1 2
7 d 1 2

然后,如果需要每个字母使用随机行:

rand = df2.groupby('letters').sample(n=1, random_state = 2)
print (rand)
letters one two
4 b 1 2
6 d 1 2

关于python - Pandas - 选择列值出现 `n`次的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74028544/

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