I am trying to switch the group number by the people of number, the table like this below
| uid | group |
| ------ | ------ |
| 355 | 1 |
| 356 | 3 |
| 357 | 4 |
| 358 | 3 |
| 359 | 5 |
| 360 | 6 |...
want to switch the number if the people in group 1 rename to group 5, if in group 3 rename to group 6... how can I able to change the value? I try to
df['group'] = df['group'][df['group'] == 1] 4
df['group'] = df['group'][df['group'] == 3] 3
but i also calculate the NAN value to the dataframe i also try to
df['group'][df['group'] == 5] = df['group'][df['group'] == 10]
by add all group by 10 from the start, but not work
CodePudding user response:
Use a mapping dictionary:
d = {1: 5, 3: 6}
df['group'] = df['group'].map(lambda x: d.get(x, x))
Or if you want to use an addition:
d = {1: 4, 3: 3}
df['group'] = df['group'].add(df['group'].map(d), fill_value=0)
output (as new column "group2" for clarity):
uid group group2
0 355 1 5
1 356 3 6
2 357 4 4
3 358 3 6
4 359 5 5
5 360 6 6
CodePudding user response:
you can use loc for this and assign the group with it
df.loc[ {your condition}, {the column that you want to update}] = {new value}
by replacing those {}, for your first example this is the code
df = pd.DataFrame({
'uid': [355,356,357,358,359,360],
'group': [1, 2, 3, 4, 5,6]
})
df.loc[df["group"]==1,"group"]=5
df.loc[df["group"]==3,"group"]=6
the output is this
uid group
0 355 5
1 356 2
2 357 6
3 358 4
4 359 5
5 360 6