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

试试这个:

import pandas as pd

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

ans = ""
for i in range(df_1.shape[0]):
    ans += '(' + df_1['x'][i] + ',' + df_1['y'][i] + '),'
    
ans = ans[:-1] + ';'

ans
'''
'(a,h);'
'''

这是一个非常粗略的方法,但它有效:)

,

转换为元组。

s = ''.join(str([tuple(t) for _,t in df_1.iterrows()])) + ';'

如果你想去掉括号和空格:

import re
s_new = re.sub(r'[\[\] ]','',s)
,
  • 来自 answerCameron Riddell 是最快的测试,40 万行的时间为 337 毫秒。
  • 我使用带有 .map(tuple) 的列表理解的解决方案是第二快的,40 万行需要 391 毫秒

样本数据

import pandas as pd

# test data
df_1 = pd.DataFrame({'x': ['a','y': ['e','h']})
  • 这两个选项比使用 .to_string() 更快
','.join([f'{v}' for v in (df_1.x + df_1.y).map(tuple).values]) + ';'

','.join([f'{v}' for v in (df_1.sum(axis=1)).map(tuple).values]) + ';'
  • 我最初的假设是这两个选项最快,因为它们不使用循环或列表推导式,但显然 .to_string() 相对较慢。
  • 无论是使用整个数据框,还是使用 .loc 指定列,使用 .sum(axis=1),将总和映射到 tuple,并使用 {{} 输出到 str 1}}。
    • 结果为 .to_string(index=False),因此 '(a,e)\n(b,f)\n(c,g)\n(d,h)' 替换为 \n
,
# use .loc to specify specific columns
df_1.loc[:,['x','y']].sum(axis=1).map(tuple).to_string(index=False).replace('\n',',') + ';'

# use this option to sum all columns
df_1.sum(axis=1).map(tuple).to_string(index=False).replace('\n',') + ';'

# resulting output of each '(a,h);'

%%timeit

功能

# sample data with 400k rows
df_1 = pd.DataFrame({'x': ['a','h']})
df = pd.concat([df_1] * 100000).reset_index(drop=True)

# Cameron
%%timeit -r1 -n1 -q -o
cameron(df)
[out]:
<TimeitResult : 337 ms ± 0 ns per loop (mean ± std. dev. of 1 run,1 loop each)>

# Trenton
%%timeit -r1 -n1 -q -o
','.join([f'{v}' for v in (df.sum(axis=1)).map(tuple).values]) + ';'
[out]:
<TimeitResult : 391 ms ± 0 ns per loop (mean ± std. dev. of 1 run,1 loop each)>

# xxdil
%%timeit -r1 -n1 -q -o
xxdil(df)
[out]:
<TimeitResult : 5.36 s ± 0 ns per loop (mean ± std. dev. of 1 run,1 loop each)>

# ifly6
%%timeit -r1 -n1 -q -o
re.sub(r'[\[\] ]',''.join(str([tuple(t) for _,t in df.iterrows()])) + ';')
[out]:
<TimeitResult : 34.8 s ± 0 ns per loop (mean ± std. dev. of 1 run,1 loop each)>

# Trenton
%%timeit -r1 -n1 -q -o
df.sum(axis=1).map(tuple).to_string(index=False).replace('\n',') + ';'
[out]:
<TimeitResult : 49.6 s ± 0 ns per loop (mean ± std. dev. of 1 run,1 loop each)>