gpt4 book ai didi

python - 如何根据索引位置过滤一组行?

转载 作者:行者123 更新时间:2023-12-03 18:05:12 26 4
gpt4 key购买 nike

我被困在如何根据索引位置过滤出一组行。为了更清楚,让我们有一个虚拟问题,假设我有一个用户具有多个配置文件的数据框,例如在 df1 中,我有三个用户 John、Johnny 和 Ben 具有多个配置文件..

df1 = pd.DataFrame({"user": ["Peter (1)", "Peter (2)", "Peter (3)","John (1)","John (2)","John (3)","Johnny (1)","Johnny (2)"], "value": [1, 3, 3, 1, 6, 3, 4, 1]}, )
我根据值对 df1 进行排序并重新索引它 df1=df1.sort_values(by='value', ascending=False) df1.index=[0, 1, 2, 3, 4, 5, 6, 7]df1 看起来像这样
enter image description here
现在我被困在如何为具有第一个索引值的用户(在本例中为 John)过滤掉行,让我们说新数据帧 df2,以及将第二个索引用户(在本例中为 Johnny)的行过滤到新数据帧 df3
预期的 df2 应该是这样的
enter image description here
df3 应该如下所示
enter image description here

最佳答案

对数据框进行排序后,您可以使用 str.split 拆分 user 中的字符串创建分组的列 key ,然后 group此分组键和每个子组的数据帧 user创建 user 的映射-> dataframe里面dict理解:

key = df1['user'].str.split().str[0]
dct = {user:grp.reset_index(drop=True) for user, grp in df1.groupby(key)}
现在访问对应于 user 的数据帧我们可以简单地在字典中查找:
>>> dct['John']

user value
0 John (2) 6
1 John (3) 3
2 John (1) 1

>>> dct['Peter']

user value
0 Peter (2) 3
1 Peter (3) 3
2 Peter (1) 1

>>> dct['Johnny']

user value
0 Johnny (1) 4
1 Johnny (2) 1

关于python - 如何根据索引位置过滤一组行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66289956/

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