首页 > 解决方案 > 将 DataFrame 列转换为对列表

问题描述

  col_1
A   2   
B   8    
C   4    
D   3
E   1

我想把它转换成类似的东西:

[[1,2],[3,4],...]

我尝试了一个 for 循环

def get_pair(col):
    lst = sorted(list(col))
    pairs = []
    for i in range(len(col)):
        for j in range(i+1, len(lst)):
            pair = [lst[i], lst[j]]
            pairs.append(pair)
    return pairs

在 Pandas 中有没有一种有效的方法来做到这一点?

标签: python-3.xpandas

解决方案


偶数或奇数项目的解决方案;使用 numpy

扩展@sammywemmy 提供的绝妙想法,我正在使用 numpy。以下解决方案将处理偶数或奇数:

import pandas as pd
import numpy as np

df = pd.DataFrame({'col_1':[1,2,3,4,5,6,7,8,9]})

#check length of df. If len is odd, get items upto n-1
x = len(df)
y = x if x%2 == 0 else x-1

#reshape only n-1 items if n is odd
z = np.reshape(df.col_1.to_numpy()[:y], (-1, 2)).tolist()

#if n is odd, then append nth item with None.
if x != y: z.append([df.values.tolist()[-1][0],None])

#print result
print (z)

输出将是:

[[1, 2], [3, 4], [5, 6], [7, 8], [9, None]]

如果您希望结果集如下所示:

[[1, 2], [3, 4], [5, 6], [7, 8], [9]]

然后将z.append行更改为

if x != y: z.append(df.values.tolist()[-1])

如果列表是偶数项的解决方案

假设您的 DataFrame 是一个偶数列表,您可以使用iterrows()list comprehension获得您想要的。

import pandas as pd
df = pd.DataFrame({'col_1':[1,2,3,4,5,6,7,8]})
print (df)

a = [[v['col_1'],df.iloc[i+1]['col_1']] for i,v in df.iloc[::2].iterrows()]
print (a)

这会给你:

[[1, 2], [3, 4], [5, 6], [7, 8]]

推荐阅读