gpt4 book ai didi

python - pandas 数据框中的 un_directed id

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:29 26 4
gpt4 key购买 nike

好吧,假设我有两个数据框,如下所示:

import pandas as pd

df1 = [{'time': '2016-11-01 17:38:25',
'id1': '49466',
'id2': '6989',
'amount': '23.74'}]

df2 = [{'time': '2016-11-01 17:49:26',
'id1': '6989',
'id2': '49466',
'amount': '25.32'}]

然后我创建数据框。

b_p = pd.DataFrame(df1)

s_p = pd.DataFrame(df2)

在这些框架中我得到:

b_p: 

amount id1 id2 time
0 23.74 49466 6989 2016-11-01 17:38:25

s_p:

amount id1 id2 time
0 25.32 6989 49466 2016-11-01 17:49:26

正如您分别在 id1id2 中看到的,b_p 数据帧显示了一个连接,但在第二个数据帧中它显示了一个相反顺序的连接。我的问题是,有没有办法让它在一个 id 连接到另一个 id 时它在第二个数据帧中支持某些交换属性?就像我可以将其存储在某个地方并确保它在第二个数据框中找到它吗?我已经知道这两个 id 已被使用,因为第一个数据帧是过去的数据集,所以当我查看当前的数据集时,我已经知道这些用户之前已经有某种连接。第一次使用,长期阅读。干杯

最佳答案

我会做两件事:

  • 我会在两个数据帧中保存 id 的顺序。如果 id1 小于 id2,则为 True,否则为 False。
  • 然后将排序后的 id 保存在不同的列中['i1', 'i2']

这样,您就可以随时进行比较,而无需考虑顺序或顺序。

b_p['direction'] = b_p.id1.lt(b_p.id2)
b_p = b_p.join(
pd.DataFrame(np.sort(b_p[['id1', 'id2']].values, 1), b_p.index, ['i1', 'i2'])
)
b_p

enter image description here

s_p['direction'] = s_p.id1.lt(s_p.id2)

s_p = s_p.join(
pd.DataFrame(np.sort(s_p[['id1', 'id2']].values, 1), s_p.index, ['i1', 'i2'])
)
s_p

enter image description here

<小时/>

实验

n = 1000000
k = 1000

d1 = pd.DataFrame(np.random.randint(0, k, (n, 2)), columns=['i1', 'i2'])
d1.insert(2, 'v1', pd.Series(np.arange(n)).astype(str).__radd__('s'))

d2 = pd.DataFrame(np.random.randint(0, k, (n, 2)), columns=['i1', 'i2'])
d2.insert(2, 'x1', pd.Series(np.arange(n)).astype(str).__radd__('s'))

def track(df):
df = df.copy()
df['direction'] = df.i1.lt(df.i2)
df.loc[:, ['i1', 'i2']] = np.sort(df[['i1', 'i2']].values, 1)
return df


d1 = track(d1)
d2 = track(d2)

d3 = d2.merge(d1)
d3.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 999066 entries, 0 to 999065
Data columns (total 5 columns):
i1 999066 non-null int64
i2 999066 non-null int64
x1 999066 non-null object
direction 999066 non-null bool
v1 999066 non-null object
dtypes: bool(1), int64(2), object(2)
memory usage: 39.1+ MB

enter image description here

关于python - pandas 数据框中的 un_directed id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40479594/

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