简体   繁体   中英

Columns with Continuous Values into Rows, Long in Pandas/Python

My data has info by sales information for people n amount of times. I need the data long row wise and all the different sales activities into one column.

How data looks like:

Name   Loc    sales_call    sales_meet    sales_email
A      Region  2             2             2
B      Local   1             2             2

How I need it to look like:

Name  Loc    sales_activity
A     Region  call
A     Region  call
A     Region  meet
A     Region  meet
A     Region  email
A     Region  email
B     Local   call
B     Local   meet
B     Local   meet
B     Local   email
B     Local   email

After flattening your dataframe, the index is your final output and the values are the number of times you need to repeat each row:

df1 = (df.set_index(['Name', 'Loc']).rename(columns=lambda x: x.split('_')[1])
         .rename_axis(columns='sales_activity').stack())
out = df1.index.repeat(df1).to_frame(index=False)

Output:

>>> out
   Name     Loc sales_activity
0     A  Region           call
1     A  Region           call
2     A  Region           meet
3     A  Region           meet
4     A  Region          email
5     A  Region          email
6     B   Local           call
7     B   Local           meet
8     B   Local           meet
9     B   Local          email
10    B   Local          email

>>> df1
Name  Loc     sales_activity
A     Region  call              2
              meet              2
              email             2
B     Local   call              1
              meet              2
              email             2
dtype: int64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM