Reputation: 55
Hello new to python here... wondering what the best way is to solve a problem like this.
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.
Upvotes: 0
Views: 118
Reputation: 700
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.)
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)
Upvotes: 0
Reputation: 54168
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
Upvotes: 1