[英]Append inner 0 & 1st index to all elements in 2nd index two-dimensional List of Lists - python
Hello new to python here... wondering what the best way is to solve a problem like this.你好,这里是 python 的新手......想知道解决这样的问题的最佳方法是什么。
I have a 2d array that look something like this:我有一个看起来像这样的二维数组:
a = [['October 17', 'Manhattan', '10024, 10025, 10026'],
['October 17', 'Queen', '11360, 11362, 11365, 11368']]
Would like to iterate over this to create a new list or data frame that looks like the following:想迭代这个以创建一个新的列表或数据框,如下所示:
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
Any insight would be greatly appreciated.任何见解将不胜感激。
Thank you.谢谢你。
You may need to iterate over the values, and for each iterate over the several indices you have您可能需要迭代这些值,并且每次迭代您拥有的几个索引
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'])
To obtain获得
[[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
Azro's answer is great, but here's a way to solve this problem that is more explicit (if you're truly new to Python, this approach might be more clear so you can understand what is happening — it doesn't rely on nested list comprehension.) 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.