python - 从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);
我应该如何解决我的问题?
解决方案
如果我正确理解了这个问题 - 您想应用以下转换:
您可以使用 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);'
推荐阅读
- android - 在 Android 中放大 Auth,无法访问管理查询 API
- swift - 如果允许重复点赞,在新的点赞条目替换旧点赞且不计入点赞数的情况下,如何将点赞数加 1?
- android - 如何将字符串从应用程序传递到另一个应用程序?
- solr - 如何授权一个 solr 用户使用 solr 7 的一个核心
- java - java中线程“main”中的异常。非常简单的代码,在它没有问题之前
- python - python Tkinter清除输出文本的某些标签
- arrays - Oracle如何在json数组列中查找包含某些值的行
- r - format() - 从星期一开始的几周?
- html - 使用 unpkg 在 html 中重用 Vue 组件
- javascript - React 状态从另一个状态变量(React Select)更新所有先前的元素