Home > Enterprise >  Extracting selected columns to new DataFrame as a copy in python
Extracting selected columns to new DataFrame as a copy in python

Time:02-23

I have the following intent classification data (4 columns, 65 rows):

Columns:   intent-A   intent-B   intent-C   intent-D

records:         d1a           d1b           d1c           d1d
                      d2a           d2b           d2c           d2d

I am attempting to combine the columns into two columns to look like this (2 columns, 260 rows):

data   intent

d1a   intent-A
d1b   intent-B
d1c   intent-C
d1d   intent-D
d2a   intent-A
d2b   intent-B
d2c   intent-C
d2d   intent-D

I am using pandas DataFrame and have tried using different functions with no success (append, concat, etc.). Any help would be most appreciated!

CodePudding user response:

You can use the following code, (here df is your data frame)-

pd.DataFrame({"Date":df.values.flatten(), "intent":df.columns.tolist()*65})

CodePudding user response:

Use melt:

df.melt(value_vars=df.columns, var_name='intent', value_name='data')

     intent data
0  intent-A  d1a
1  intent-A  d2a
2  intent-B  d1b
3  intent-B  d2b
4  intent-C  d1c
5  intent-C  d2c
6  intent-D  d1d
7  intent-D  d2d
  • Related