Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert selected column with index to a list of tuples in pandas

Tags:

python

pandas

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)]
like image 282
The Rookie Avatar asked May 03 '20 13:05

The Rookie


People also ask

How do I turn a column into a list in pandas?

values. tolist() you can convert pandas DataFrame Column to List. df['Courses'] returns the DataFrame column as a Series and then use values. tolist() to convert the column values to list.

How do you convert the index of a DataFrame to a list in Python?

tolist() function return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period). Example #1: Use Index. tolist() function to convert the index into a list.

How do I convert a column to an index in pandas?

Pandas – Set Column as Index To set a column as index for a DataFrame, use DataFrame. set_index() function, with the column name passed as argument. You can also setup MultiIndex with multiple columns in the index. In this case, pass the array of column names required for index, to set_index() method.

How do you convert a list of tuples into a DataFrame pandas?

To convert a Python tuple to DataFrame, use the pd. DataFrame() constructor that accepts a tuple as an argument and it returns a DataFrame.


Video Answer


1 Answers

We can do zip

list(zip(df.index,df.Cost))
[('Store 1', 22.5), ('Store 1', 2.5), ('Store 2', 5.0)]
like image 141
BENY Avatar answered Oct 15 '22 16:10

BENY