首页 > 解决方案 > 从python中的数据框中列出两列的python对

问题描述

我有熊猫数据框

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

我需要从这样的字符串中获取:

(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);

最后应该是分号。

就我而言,答案应该是:

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

我应该如何解决我的问题?

标签: pythonpandaslistdataframeggpairs

解决方案


如果我正确理解了这个问题 - 您想应用以下转换:

您可以使用 zip 作为元素元组同时迭代列“x”和列“y”的每个元素。您可以连接这些元素,使它们成为字符串并将其包装在括号中以获得所需的逐行输出。然后将所有这些存储在一个更大的列表中,并将该更大的列表转换为用逗号分隔的字符串,并在末尾添加一个分号。

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);'

推荐阅读