Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

pandas - Make a list of python pairs of two columns from dataframe in python

I have pandas dataframe

df_1 = pd.DataFrame({'x' : [a, b, c, d], 'y' : [e, f, g, h]})

I need to get from string like this:

(first_element_from_first_row,first_element_from_second_row),
(second_element_from_first_row,second_element_from_second_row),
................................................................
(last_element_from_first_row,last_element_from_second_row);

at the end should be semicolon.

in my case the answer should be:

(a,e),(b,f),(c,g),(d,h);

How should I solve my problem?


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

1 Answer

0 votes
by (71.8m points)

If I understand the question correctly- you want to apply the following transformation:

you can use zip to iterate over each element of column "x" and column "y" at the same time as a tuple of elements. You can join those elements so that they are a string and wrap that in parentheses to get the desired row-wise output. Then you store all of those in a larger list and turn that larger list into a string separated by commas, and add a semicolon at the end.

all_pairs = []

for pair in zip(df_1["x"], df_1["y"]):
    pair_str = "({})".format(",".join(pair))
    all_pairs.append(pair_str)

final_str = ",".join(all_pairs) + ";"

print(final_str)
'(a,e),(b,f),(c,g),(d,h);'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...