Change language

Collapse multiple columns in pandas

|

To collapse multiple columns in Pandas, follow these steps:

Step # 1: Download NumPy and Pandas. 
Step # 2: Generate some random data and use it to create a Pandas dataframe. 
Step # 3: Convert multiple lists into one data frame by creating a dictionary for each named list. 
Step # 4: Then use the Pandas info frame in the dict. The data frame with data columns and a column for names is ready. 
Step # 5: Specify which columns should be collapsed. This can be done by specifying the mapping as a dictionary, where the keys are the names of the columns to be concatenated or collapsed, and the values ​​— the names of the resulting column.

Example 1:

# Python program collapse
# multiple columns with pandas

import pandas as pd

 
# sample data

n = 3

Sample_1 = [ 57 , 51 , 6 ]

Sample_2 = [ 92 , 16 , 19 ]

Sample_3 = [ 15 , 93 , 71 ]

Sample_4 = [ 28 , 73 , 31 ]

  

sample_id = zip ([ "S" ] * n, list ( range ( 1 , n + 1 )))

 

s_names = [’’ .join ([w [ 0 ], str (w [ 1 ])]) for w in sample_id]

 

d = { ’s_names’ : s_names, ’ Sample_1’ : Sample_1, 

  ’ Sample_2’ : Sample_2, ’ Sample_3’ : Sample_3,

’Sample_4’ : Sample_4}

 

df_1 = pd.DataFrame (d)

 

mapping = { ’Sample_1’ : ’Result_1’ ,

  ’Sample_2’ : ’ Result_1’

  ’ Sample_3’ : ’Result_2’

’Sample_4’ : ’Result_2’ }

 

df = df_1.set_index ( ’s_names’ ). groupby (mapping, axis = 1 ). sum ()

  

df.reset_index (level = 0 )

Output:

Example 2:

# Python program collapse
# multiple columns with pandas

import pandas as pd

df = pd.DataFrame ({ ’First’ : [ ’Manan’ , ’Raghav’ , ’Sunny’ ],

  ’ Last’ : [ ’ Goel’ , ’Sharma’ , ’Chawla’ ],

’Age’ : [ 12 , 24 , 56 ]})

  

mapping = { ’First’ : ’Full Name’ , ’ Last’ : ’Full Name’ }

  

df = df.set_index ( ’Age’ ) .groupby (mapping, axis = 1 ). sum ()

 

df.reset_index (level = 0 )

Exit:

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically