gpt4 book ai didi

python - 将每列的最后 N 个正值提取到新的数据框中

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:55 24 4
gpt4 key购买 nike

我想提取每列的最后 N 个 > 0 的值,并将它们保存在新的数据框中。您能建议我一种有效的方法吗?谢谢!

最佳答案

使用字典理解通过掩码过滤 Series.gtSeries.tail ,通过 Series.reset_index 创建默认索引值使用 drop=True 并最后传递给 DataFrame 构造函数:

np.random.seed(2020)
df = pd.DataFrame(np.random.randint(-5, 5, size=(10, 3)))
print (df)
0 1 2
0 -5 3 -2
1 1 -2 -2
2 2 3 -5
3 -5 3 4
4 -2 2 -3
5 -2 1 0
6 -5 -1 3
7 1 -1 -4
8 -4 0 4
9 0 1 1

d = {c: df.loc[df[c].gt(0), c].tail(3).reset_index(drop=True) for c in df.columns}
df = pd.DataFrame(d)
print (df)
0 1 2
0 1 2 3
1 2 1 4
2 1 1 1

关于python - 将每列的最后 N 个正值提取到新的数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59715018/

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