Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filling a column values with max value in pandas

Tags:

python

pandas

I have some data like this:

pd.DataFrame({'code': ['a', 'a', 'a', 'b', 'b', 'c'],
                      'value': [1,2,3, 4, 2, 1] })



+-------+------+-------+
| index | code | value |
+-------+------+-------+
| 0     | a    | 1     |
+-------+------+-------+
| 1     | a    | 2     |
+-------+------+-------+
| 2     | a    | 3     |
+-------+------+-------+
| 3     | b    | 4     |
+-------+------+-------+
| 4     | b    | 2     |
+-------+------+-------+
| 5     | c    | 1     |
+-------+------+-------+

i want add a column that contain the max value of each code :

| index | code | value | max |
|-------|------|-------|-----|
| 0     | a    | 1     | 3   |
| 1     | a    | 2     | 3   |
| 2     | a    | 3     | 3   |
| 3     | b    | 4     | 4   |
| 4     | b    | 2     | 4   |
| 5     | c    | 1     | 1   |

is there any way to do this with pandas?

like image 396
Tavakoli Avatar asked Aug 26 '18 07:08

Tavakoli


People also ask

How do I get the maximum value of a column name?

To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value.

How do you use Max in pandas?

Pandas DataFrame max() Method The max() method returns a Series with the maximum value of each column. By specifying the column axis ( axis='columns' ), the max() method searches column-wise and returns the maximum value for each row.


2 Answers

Use GroupBy.transform for new column of aggregated values:

df['max'] = df.groupby('code')['value'].transform('max')
like image 180
jezrael Avatar answered Oct 08 '22 12:10

jezrael


You can try this as well.

df["max"] = df.code.apply(lambda i : max(df.loc[df["code"] == i]["value"]))
like image 1
Raviteja Ainampudi Avatar answered Oct 08 '22 14:10

Raviteja Ainampudi