你好,这里是python的新手……想知道解决这样的问题最好的方法是什么。
我有一个二维数组,看起来像这样:
a = [['October 17', 'Manhattan', '10024, 10025, 10026'],
['October 17', 'Queen', '11360, 11362, 11365, 11368']]我想通过迭代来创建一个新的列表或数据框,如下所示:
10024, October 17, Manhattan
10025, October 17, Manhattan
10026, October 17, Manhattan
11360, October 17, Queens
11362, October 17, Queens
11365, October 17, Queens
11368, October 17, Queens任何见解都将不胜感激。
谢谢。
发布于 2020-03-03 04:12:16
您可能需要迭代这些值,对于每个值,还需要迭代您拥有的几个索引
values = [['October 17', 'Manhattan', '10024, 10025, 10026'],
['October 17', 'Queens', '11360, 11362, 11365, 11368']]
result = [[int(idx), row[0], row[1]]
for row in values
for idx in row[2].split(',')]
df = DataFrame(result, columns=['idx', 'date', 'place'])要获得
[[10024, 'October 17', 'Manhattan'], [10025, 'October 17', 'Manhattan'],
[10026, 'October 17', 'Manhattan'], [11360, 'October 17', 'Queens'],
[11362, 'October 17', 'Queens'], [11365, 'October 17', 'Queens'],
[11368, 'October 17', 'Queens']]
idx date place
0 10024 October 17 Manhattan
1 10025 October 17 Manhattan
2 10026 October 17 Manhattan
3 11360 October 17 Queens
4 11362 October 17 Queens
5 11365 October 17 Queens
6 11368 October 17 Queens发布于 2020-03-03 05:42:23
Azro的答案很好,但这里有一种更明确的方法来解决这个问题(如果您是Python的新手,这种方法可能会更清楚,这样您就可以理解发生了什么-它不依赖于嵌套列表理解)。
a = [['October 17', 'Manhattan', '10024, 10025, 10026'],
['October 17', 'Queen', '11360, 11362, 11365, 11368']]
# initialize an empty list to put our reformatted data into
final_result = []
for inner_list in a:
# get the first two items
first_item = inner_list[0]
second_item = inner_list[1]
# split the third list item, and remove trailing and leading whitespace
remaining_data = [x.strip() for x in inner_list[2].split(',')]
# iterate over the remaining data
for item in remaining_data:
# first, create a new sublist containing our first two items
new_entry = [item, first_item, second_item]
# add our new_entry into the final result list
final_result.append(new_entry)
print(final_result)https://stackoverflow.com/questions/60495859
复制相似问题