[英]Python Pandas non equal join
Have table有桌
import pandas as pd
import numpy as np
list_1=[['Steven',np.nan,'C1'],
['Michael',np.nan,'C2'],
['Robert',np.nan,'C3'],
['Buchanan',np.nan,'C1'],
['Suyama',np.nan,'C2'],
['King',np.nan,'C3']]
labels=['first_name','last_name','class']
df=pd.DataFrame(list_1,columns=labels)
df
OUT出去
first_name last_name class
0 Steven NaN C1
1 Michael NaN C2
2 Robert NaN C3
3 Buchanan NaN C1
4 Suyama NaN C2
5 King NaN C3
Need:需要:
first_name last_name
Steven Buchanan
Michael Suyama
Robert King
so i need make non equal join equivalent SQL query :所以我需要进行非等连接等效 SQL 查询:
;with cte as
(
SELECT first_name,
class,
ROW_NUMBER() OVER (partition by class ORDER BY first_name) as rn
FROM students
)
select c_fn.first_name,
c_ln.first_name
from cte c_fn join cte c_ln on c_fn.class=c_ln.class and c_ln.rn< c_fn.rn
or as SQL query:或作为 SQL 查询:
;with cte as
(
SELECT first_name,
last_name,
ROW_NUMBER() OVER ( ORDER BY (select null)) as rn
FROM students
)
select fn.first_name,
ln.first_name as last_name
from cte fn join cte ln on ln.rn=fn.rn+3
The problem in PANDAS is that NON EQUAL SELF JOIN cannot be done with MERGE. PANDAS 中的问题是非等价自联接不能用 MERGE 来完成。 And I can't find another way.....
而且我找不到其他方法......
We can solve this in pandas in a smarter way by using groupby
with agg
and joining the strings.我们可以通过使用
groupby
和agg
并连接字符串以更智能的方式在 Pandas 中解决这个问题。 Then we split
them to columns:然后我们
split
它们split
为列:
dfn = df.groupby('class').agg(' '.join)['first_name'].str.split(' ', expand=True)
dfn.columns = [df.columns[:2]]
dfn = dfn.reset_index(drop=True)
first_name last_name
0 Steven Buchanan
1 Michael Suyama
2 Robert King
You could set the index to 'class' and select the individual names:您可以将索引设置为 'class' 并选择各个名称:
df = df.setIndex('class')
first_name = df.loc["C1", "first_name"].values[0]
last_name = df.loc["C1", "last_name"].values[1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.