gpt4 book ai didi

python - 如何查看列元素是否在后面的行中交换

转载 作者:太空狗 更新时间:2023-10-30 02:52:37 25 4
gpt4 key购买 nike

我刚刚被要求帮忙解决这个问题,但我不确定我能否想出一段运行速度相当快的代码。

有两列数据:第一列是发起与某人联系的社交媒体用户的用户ID号;第二列是他们开始联系的人的用户 ID。此外,假设行是按时间排序的。

我希望在以后查看所有“关注”其关注者的人的用户 ID。这是我到目前为止所拥有的,而且速度很慢。如果没有 for 循环,我该怎么做?

def myFun2(num):
N = df.shape[0]
init_follower = df['follower'][num]
init_followee = df['followee'][num]
for i in range(num+1,N):
a = init_followee == df['follower'][i]
b = init_follower == df['followee'][i]
if a and b:
return i

df = pd.DataFrame({'follower' : ['a', 'a', 'b'], 'followee' : ['b', 'c', 'a']})

# prints 2 because that's the row where a follows back b
for i in range(df.shape[0]):
print(myFun2(i))

最佳答案

这是一种方法。给定一个数据框 df:

df = pd.DataFrame(columns = ['follower', 'followee'])
df.loc[0] = [123, 111]
df.loc[1] = [123, 150]
df.loc[2] = [145, 123]
df.loc[3] = [150, 123]

df

follower followee
0 123 111
1 123 150
2 145 123
3 150 123

“我希望看到所有“关注”他们的粉丝的人的用户 ID...”

使用 merge 进行“自内连接”,将左表的 followee 与右表的 follower 相匹配。现在,当您对左表的 follower 与右表的 followee 相同的所有行进行子集化时,您实际上得到了想要的结果:

a = df.merge(df, left_on = 'followee', right_on = 'follower')
b = a[a['follower_x'] == a['followee_y']][['follower_x', 'followee_x']].\
reset_index().rename(columns = {'index' : 'timestamp', 'follower_x' : 'follower', 'followee_x' : 'followee'})

“...稍后”

假设你的行是按时间排序的,得到后来成为followers的followees;

b['grp'] = b[['follower', 'followee']].apply(lambda x: str(np.sort(x.tolist())), axis = 1)
b['rank'] = b.groupby('grp')['timestamp'].apply(lambda x: x.rank(ascending = False))
b[b['rank'] == 1]['follower']

输出:

1    150

编辑:

对于您提供的数据框:

输出:

1    b

关于python - 如何查看列元素是否在后面的行中交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52656929/

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