Reputation: 237
This might be fairly simple but I'm trying to get the data I have in rows into a list of tuples.
I'm using pandas and have made it so that data from the spreadsheet is in a list of tuples but it will not put the data from each row in an individual tuple. My code is as follows:
import pandas as pd
spreadsheet_data = []
data = pd.read_excel("file.xlsx")
info = [(ix, k, v) for ix, row in data.iterrows() for k, v in row.items()]
spreadsheet_data.append(info)
print(spreadsheet_data)
The spreadsheet has 3 items in each row: the name of the food item, the category of the item, and the order recommendation. For example: A1 = Coca-Cola, B2 = Beverages and C2 = 1 All of this information should appear in a tuple like so: (Coca-Cola, Beverages, 1) I have about 32 rows just like this and I need the tuples for all 32 rows in a list. The code I have makes the list and makes the tuples but the data in the tuples is all over the place. Help with this would be greatly appreciated. Thank you in advance.
Upvotes: 1
Views: 1909
Reputation: 294508
pandas.DataFrame.itertuples
[*data.itertuples()]
[Pandas(Index=0, A=1, B=1, C=1, D=1, E=1),
Pandas(Index=1, A=1, B=1, C=1, D=1, E=1),
Pandas(Index=2, A=1, B=1, C=1, D=1, E=1),
Pandas(Index=3, A=1, B=1, C=1, D=1, E=1)]
Or without the index or named tuples
[*data.itertuples(index=False, name=False)]
[(1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1)]
map
and zip
[*zip(*map(data.get, data))]
[(1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1)]
data = pd.DataFrame(1, range(4), [*'ABCDE'])
data
A B C D E
0 1 1 1 1 1
1 1 1 1 1 1
2 1 1 1 1 1
3 1 1 1 1 1
Upvotes: 5