1

I have a data frame already which is something like

x     label     word

10      1        is
20      2        goal
15      2        left
13      0        am
9       1        are
7       0        I
6       1        hello
2       0        world

I'm trying to create another data frame which, once I have performed the operations to extract from this data frame, looks like this:

label    min    max    words
 0        2     13     I, world, am
 1        6     10     hello, are, is
 2        15    20     goal, left

The words in the words column can be in any order. They represent the words for that specific label.

I have tried using df.groupby but i don't seem to understand how it works. Can someone guide me as to what method should I be looking for?

1 Answer 1

1

Use DataFrameGroupBy.agg by dictionary of columns names and aggregated functions. Then get MultiIndex in columns, so need flatten it - here by map and join, last if necessary rename columns:

df = df.groupby('label').agg({'x':['min','max'], 'word':', '.join})
df.columns = df.columns.map('_'.join)
d = {'x_min':'min','x_max':'max','word_join':'words'}
df = df.rename(columns=d).reset_index()
print (df)
   label  min  max           words
0      0    2   13    am, I, world
1      1    6   10  is, are, hello
2      2   15   20      goal, left

If want aggregate column word to lists:

df = df.groupby('label').agg({'x':['min','max'], 'word': lambda x: x.tolist()})
df.columns = df.columns.map('_'.join)
d = {'x_min':'min','x_max':'max','word_<lambda>':'words'}
df = df.rename(columns=d).reset_index()
print (df)
   label  min  max             words
0      0    2   13    [am, I, world]
1      1    6   10  [is, are, hello]
2      2   15   20      [goal, left]
Sign up to request clarification or add additional context in comments.

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.