6

Given the dataframe below:

df = pd.DataFrame([{'Name': 'Chris', 'Item Purchased': 'Sponge', 'Cost': 22.50},
                   {'Name': 'Kevyn', 'Item Purchased': 'Kitty Litter', 'Cost': 2.50},
                   {'Name': 'Filip', 'Item Purchased': 'Spoon', 'Cost': 5.00}],
                  index=['Store 1', 'Store 1', 'Store 2'])

How do I write a script to produce the following output:

[('Store 1', 22.5), ('Store 1', 2.5), ('Store 2', 5.0)]
Georgy
  • 12,464
  • 7
  • 65
  • 73
The Rookie
  • 877
  • 8
  • 15
  • Does this answer your question? [Pandas convert dataframe to array of tuples](https://stackoverflow.com/questions/9758450/pandas-convert-dataframe-to-array-of-tuples). There are several solutions that deal with a subset of a dataframe as well. – Georgy May 09 '20 at 14:31
  • You want to sum all the costs for each store, or just transpose the dataframe? (if the data frame has 2 rows with store1, should the output have store1 2 times or just one? I recommend you to be more specific on the transformation you are expecting to perform, because the output can be achieved in many ways. – CarlosSR May 31 '20 at 08:11

3 Answers3

4

We can do zip

list(zip(df.index,df.Cost))
[('Store 1', 22.5), ('Store 1', 2.5), ('Store 2', 5.0)]
BENY
  • 317,841
  • 20
  • 164
  • 234
4

You can also use items:

list(df['Cost'].items())
#df['Cost'].to_dict().items()

[('Store 1', 22.5), ('Store 1', 2.5), ('Store 2', 5.0)]
anky
  • 74,114
  • 11
  • 41
  • 70
3

You can also use itertuples since you have an index set.

list(df[['Cost']].itertuples(name=None))
[('Store 1', 22.5), ('Store 1', 2.5), ('Store 2', 5.0)]
Umar.H
  • 22,559
  • 7
  • 39
  • 74