繁体   English   中英

从 python 中的 dataframe 中列出两列 python 对的列表

[英]Make a list of python pairs of two columns from dataframe in python

我有 pandas dataframe

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”的每个元素。 您可以连接这些元素,使它们成为一个字符串并将其包装在括号中以获得所需的逐行 output。 然后将所有这些存储在一个更大的列表中,并将该更大的列表转换为用逗号分隔的字符串,并在末尾添加一个分号。

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,e),(b,f),(c,g),(d,h);'
'''

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

转换为元组。

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

如果要去除括号和空格:

import re
s_new = re.sub(r'[\[\] ]', '', s)
  • Cameron Riddell答案是最快的测试,400k 行为 337 毫秒。
  • 我使用带有.map(tuple)的列表理解的解决方案是第二快的,400k 行为 391 毫秒

样本数据

import pandas as pd

# test data
df_1 = pd.DataFrame({'x': ['a', 'b', 'c', 'd'], 'y': ['e', 'f', 'g', '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()相对较慢。
  • 使用整个 dataframe,或使用.loc指定列,使用.sum(axis=1) , map 总和到一个tuple ,和str .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, e),(b, f),(c, g),(d, h);'

%%timeit

# sample data with 400k rows
df_1 = pd.DataFrame({'x': ['a', 'b', 'c', 'd'], 'y': ['e', 'f', 'g', '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)>

功能

def cameron(df_1):
    
    all_pairs = []

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

    return ",".join(all_pairs) + ";"


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

    return ans[:-1] + ';'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM