Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

python - Pandas: How to combine several rows with the same column value and create a new Dataframe which covers all possibilities?

There exists a DataFrame like this:

id name age
0x0 Hans 32
0x0 Peter 21
0x1 Jan 42
0x1 Simon 25
0x1 Klaus 51
0x1 Franz 72

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Core python itertools combinations is the solution. merge() to get the age

import itertools
df = pd.read_csv(io.StringIO("""id  name    age
0x0 Hans    32
0x0 Peter   21
0x1 Jan 42
0x1 Simon   25
0x1 Klaus   51
0x1 Franz   72"""), sep="")

df1 = (
df
    .groupby(["id"])["name"]
    .apply(lambda x: pd.DataFrame(itertools.combinations(list(x),2)))
    .reset_index()
    .merge(df, left_on=["id",0], right_on=["id","name"])
    .merge(df, left_on=["id",1], right_on=["id","name"], suffixes=("0","1"))
    .drop(columns=["level_1",0,1])
)

output

  id  name0  age0  name1  age1
 0x0   Hans    32  Peter    21
 0x1    Jan    42  Simon    25
 0x1    Jan    42  Klaus    51
 0x1  Simon    25  Klaus    51
 0x1    Jan    42  Franz    72
 0x1  Simon    25  Franz    72
 0x1  Klaus    51  Franz    72

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...