gpt4 book ai didi

python - Pandas 嵌套循环,其中一行与特定值匹配

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:22 25 4
gpt4 key购买 nike

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

例如,假设我有一个包含“日期”、“名称”和“电影”的数据框。可能有很多用户和电影。我希望所有叫约翰的人都看过和叫艾丽西亚的人以前看过的同一部电影。输入数据框可以是:

                 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 执行此操作的方法。

有什么帮助吗?

最佳答案

这是一种方法。假设您有以下数据框:

     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

IIUC 正确的解决方案不应包含第 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

您现在可以做的是GroupBy电影,并申请 cumsum在组上,因此只有第一个 True 之后的行也会变为 True:

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

最后在原始数据帧上使用 bool 索引来选择感兴趣的行。

关于python - Pandas 嵌套循环,其中一行与特定值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54215104/

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