将以空格分隔的列表压缩为元组

2024-09-29 00:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧df,其中一列名为columnList作为str

"1 2,7 8,10 7"

然后我将它们转换为一个列表,如图所示:

[1 2,7 8,10 7]

我想将列表中的值转换为元组:

[(1,2),(7,8),(10,7)]

当前代码:

temp = df['columnList'].str.split(',')
result = list(zip(temp[::2], temp[1::2]))
print(result)

我得到了一张空名单

df看起来像这样:

column1    columnList
  YY      1 2,7 8,10 7

名称:df,数据类型:object


Tags: 数据代码df列表resultziptemplist
3条回答

您可以在拆分字符后将其映射为整数,然后将映射对象转换为元组:

temp = df['columnList'].str.split(',')
result = [tuple(map(int, num.split())) for num in temp]
print(result)
# [(1, 2), (7, 8), (10, 7)]

这里不需要使用zip,只需迭代列表,拆分每个元素并将其存储为元组

l = [ '1 2', '7 8', '10 7']
[tuple(int(i) for i in numbers.split()) for numbers in l]

#[(1, 2), (7, 8), (10, 7)]

试试这个

df.columnsList.apply(lambda x : 
        [tuple(map(int, x.split())) for x in "1 2, 7 8, 10 7".split(",")])

产出

0    [(1, 2), (7, 8), (10, 7)]
Name: columnsList, dtype: object

相关问题 更多 >