Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

pandas - How to create column pairs in Python?

I have dataframe as below. I want to create a column like this:

 d={
        'customer' :['abadia dos dourados','abadiania','abaete'],
        'seller':['montenegro','rio de janeiro','bauru']
    }
    
df=pd.DataFrame(d, columns=['customer','seller'])

Expected result like this:

enter image description here

I am using this code. But it doesnot seem same.

cols = ['customer','seller']
df['City_Pairs'] = df[cols].apply(lambda x:','.join([str(x) for x in zip(x.values)]), axis=1)

My output:

enter image description here

question from:https://stackoverflow.com/questions/65640996/how-to-create-column-pairs-in-python

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

1 Answer

0 votes
by (71.8m points)

It's just the way you are constructing your concatenated string. I've used an f-string

df['City_Pairs'] = df.apply(lambda r: f"({r['customer']},{r['seller']})", axis=1)

output

            customer          seller                        City_Pairs
 abadia dos dourados      montenegro  (abadia dos dourados,montenegro)
           abadiania  rio de janeiro        (abadiania,rio de janeiro)
              abaete           bauru                    (abaete,bauru)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...