Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list including row name, column name and the value from dataframe [duplicate]

I have the following dataframe:

    A   B   C  
A   1   3   0    
B   3   2   5     
C   0   5   4   

All I want is shown below:

my_list = [('A','A',1),('A','B',3),('A','C',0),('B','B',2),('B','C',5),('C','C',4)]

Thanks in advance!

like image 202
Phước Avatar asked May 24 '20 15:05

Phước


People also ask

How do I get a list of values from a DataFrame column?

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 I get a list of column names in a DataFrame?

To access the names of a Pandas dataframe, we can the method columns(). For example, if our dataframe is called df we just type print(df. columns) to get all the columns of the Pandas dataframe.

How do you print duplicate rows in Python?

The pandas. DataFrame. duplicated() method is used to find duplicate rows in a DataFrame. It returns a boolean series which identifies whether a row is duplicate or unique.


2 Answers

IIUC, you can do:

df.stack().reset_index().agg(tuple,1).tolist()

[('A', 'A', 1),
 ('A', 'B', 3),
 ('A', 'C', 0),
 ('B', 'A', 3),
 ('B', 'B', 2),
 ('B', 'C', 5),
 ('C', 'A', 0),
 ('C', 'B', 5),
 ('C', 'C', 4)]
like image 154
anky Avatar answered Sep 30 '22 19:09

anky


You can stack and use to_records to obtain a record array from the result:

df.stack().to_frame().to_records().tolist()
# [('A', 'A', 1), ('A', 'B', 3), ('A', 'C', 0), ('B', 'A', 3),...
like image 29
yatu Avatar answered Sep 30 '22 18:09

yatu