Combining rows of a dataframe base on the values of a column

Viewed 36

enter image description here

How can I combine the Percentage Total Production that are less than 20% into 1 row and label that as 'Others'

so i should only get 'Other': 78.43%, India: 21.561239% The results should be in a dataframe in this format

2 Answers

You can concatenate a row that is the sum of all rows where the percentage is < 20, and all the remaining rows:

mask = df['Percentage_Total_Production'] < 20
new_row = pd.DataFrame([df[mask].sum(axis=0)], index=['other'])

pd.concat([new_row, df[~mask]], axis=0)

Create a new column to mask the data. Taking into account if the percentage is < 0.2:

df["New Index"] = np.where(df["Percentage_Total_Production"] < 0.2, "Other", df["Percentage_Total_Production"].index)

And then, apply a .groupby() transformation:

df.groupby("New Index").sum()
Related