0
  • original DataFrame df

      label  value
    0     a      1
    1     a      2
    2     b      3
    3     a      4
    4     b      5
    
  • ds = df.groupby('label')['value'].apply(list)

    label
    a    [1, 2, 4]
    b       [3, 5]
    
  • ds.explode() generate

      label
      a    1
      a    2
      a    4
      b    3
      b    5
    

What I need is a new column to represents the position of the item in the value column in the original list.

 label value position
 a    1      0
 a    2      1
 a    4      2
 b    3      0
 b    5      1

update:

Example above is not appropriate, suppose the original dataframe is

  label   value
0     a  [1, 2]
1     a     [2]
2     b     [3]
3     a     [4]
4     b     [5]

df.explode('value') gives

  label value
0     a     1
0     a     2
1     a     2
2     b     3
3     a     4
4     b     5

how I get

  label value position
0     a     1  0
0     a     2  1
1     a     2  0
2     b     3  0
3     a     4  0
4     b     5  0
5
  • 1
    df['position'] = df.groupby('label').cumcount() Commented Jan 5, 2021 at 3:51
  • BTW, do you really need explode? How about just df.sort_values("label")? Commented Jan 5, 2021 at 3:53
  • @Ch3steR thanks and no, I've edited my question Commented Jan 5, 2021 at 4:14
  • @ComplicatedPhenomenon Got it retracted close vote ;) Commented Jan 5, 2021 at 4:18
  • @Chris my intention is to expand the list Commented Jan 5, 2021 at 4:43

2 Answers 2

2

First, get length of list in value then apply np.arange or range on it using pd.Series.map or pd.Series.apply. Now, explode value

df['value'] = df['value'].str.len().map(np.arange)
#                                 _.map(range) # Alternative
df.explode('value')

  label value
0     a     0
0     a     1
1     a     0
2     b     0
3     a     0
4     b     0
Sign up to request clarification or add additional context in comments.

Comments

0

Lets Try:

 df['position']=df.groupby(['label'])['value'].cumcount()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.