包含与特定值匹配的行的嵌套循环

2024-06-26 13:44:50 发布

您现在位置:Python中文网/ 问答频道 /正文

给定与某些特定值匹配的行,迭代数据帧其余部分的最快方法是什么

例如,假设我有一个带有“Date”、“Name”和“Movie”的数据帧。可能有很多用户和电影。我要所有看过同一部电影的叫约翰的人,就像以前看过艾丽西亚的人一样。 输入数据帧可以是:

                 date       name              movie
0 2018-01-16 10:33:59     Alicia            Titanic
1 2018-01-17 08:49:13   Chandler             Avatar
2 2018-01-18 09:29:09      Luigi              Glass
3 2018-01-19 09:45:27     Alicia           Die Hard
4 2018-01-20 10:08:05    Bouchra       Pulp Fiction
5 2018-01-26 10:21:47     Bariza              Glass
6 2018-01-27 10:15:32      Peggy         Bumbleblee
7 2018-01-20 10:08:05       John            Titanic
8 2018-01-26 10:21:47     Bariza              Glass
9 2018-01-27 10:15:32       John            Titanic

结果应该是:

                 date       name              movie
0 2018-01-16 10:33:59     Alicia            Titanic
7 2018-01-20 10:08:05       John            Titanic
9 2018-01-27 10:15:32       John            Titanic

目前,我正在做以下工作:

alicias = df[df['Name'] == 'Alicia']

df_res = pd.DataFrame(columns=df.columns)
for i in alicias.index:
    df_res = df_res.append(alicias.loc[i], sort=False)

    df_johns = df[(df['Date'] > alicias['Date'][i])
                 &(df['Name'] == 'John')
                 &(df['Movie'] == alicias['Movie'][i)]

    df_res = df_res.append(df_johns, sort=False)

它工作,但这是非常缓慢的。我也可以使用更快的groupby,但我希望结果保留初始行(示例中带有'Alicia'的行),我找不到使用groupby的方法。

有什么帮助吗


Tags: 数据方法namedfdate电影resmovie
1条回答
网友
1楼 · 发布于 2024-06-26 13:44:50

这里有一个方法。假设您有以下数据帧:

     date      user    movie
0  2018-01-02  Alicia  Titanic
1  2018-01-13    John  Titanic
2  2018-01-22    John  Titanic
3  2018-04-02    John   Avatar
4  2018-04-05  Alicia   Avatar
5  2018-05-19    John   Avatar

正确的解决方案不应该包含第3行,因为Alicia还没有看到Avatar。所以你可以:

df[df.user.eq('Alicia').groupby(df.movie).cumsum()]

     date       user    movie
0  2018-01-02  Alicia  Titanic
1  2018-01-13    John  Titanic
2  2018-01-22    John  Titanic
4  2018-04-05  Alicia   Avatar
5  2018-05-19    John   Avatar

说明:

下面返回True,其中userAlicia

df.user.eq('Alicia')

0     True
1    False
2    False
3    False
4     True
5    False
Name: user, dtype: bool

您现在可以做的是^{}电影,并在组上应用^{},因此只有第一个True之后的行也将变成True

0     True
1     True
2     True
3    False
4     True
5     True
Name: user, dtype: bool

最后在原始数据帧上使用boolean indexation,以便选择感兴趣的行

相关问题 更多 >