2

i am using below formula to get value count froma. column in a dataframe:

new_data = df['item'].value_counts()

which give me below result

Apples                    3
Green bananas             2
Bananas                   1
Oranges                   1

what i want is to get output for every item count in in new column like the below excel example

example

Any help or guidance is appreciated. Thank you

3 Answers 3

4

Use Series.map for your solution:

new_data = df['item'].value_counts()
df['Occurence'] = df['item'].map(new_data)

One row solution:

df['Occurence'] = df['item'].map(df['item'].value_counts())

If there is multiple columns:

cols = ['item','item1']
for c in cols:
    df[f'Occurence_{c}'] = df[c].map(df[c].value_counts())

 df.loc[len(df), cols] = df[cols].sum()

Or:

df = df.join(df[cols].apply(lambda x: x.map(x.value_counts())).add_prefix('Occurence_'))
Sign up to request clarification or add additional context in comments.

7 Comments

i have more then one column to do the same thing with different item headers how can i do it?
@Zac - Do you think df['Occurence1'] = df['item1'].map(df['item1'].value_counts()) ?
okday so i have to do same code for every column
Thank you so much,now last question. How can i sum every row cols occurance and total it in new column
@Zac - You can add ` df.loc[len(df), cols] = df[cols].sum()`, added to answer.
|
2

Try with transform

df['new'] = df.groupby('item')['item'].transform('count')

Comments

1

Or by the index:

df.set_index('item').assign(count=df['item'].value_counts()).reset_index()

Since column assigning corresponds to the index, this way would do it.

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.