Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Swap values in multiple dataframes

I have a DataFrame like this

id  val1   val2
0    A      B
1    B      B
2    A      A
3    A      A

And I would like swap values such as:

id  val1   val2
0    B      A
1    A      A
2    B      B
3    B      B

I need to consider that the df could have other columns that I would like to keep unchanged.

like image 239
EGM8686 Avatar asked Oct 24 '18 16:10

EGM8686


2 Answers

You can use pd.DataFrame.applymap with a dictionary:

d = {'B': 'A', 'A': 'B'}

df = df.applymap(d.get).fillna(df)

print(df)

  id val1 val2
0  0    B    A
1  1    A    A
2  2    B    B
3  3    B    B

For performance, in particular memory usage, you may wish to use categorical data:

for col in df.columns[1:]:
    df[col] = df[col].astype('category')
    df[col] = df[col].cat.rename_categories(d)
like image 191
jpp Avatar answered Nov 14 '22 12:11

jpp


Try stacking, mapping, and then unstacking:

df[['val1', 'val2']] = (
    df[['val1', 'val2']].stack().map({'B': 'A', 'A': 'B'}).unstack())

df
   id val1 val2
0   0    B    A
1   1    A    A
2   2    B    B
3   3    B    B

For a (much) faster solution, use a nested list comprehension.

mapping = {'B': 'A', 'A': 'B'}
df[['val1', 'val2']] = [
    [mapping.get(x, x) for x in row] for row in df[['val1', 'val2']].values]

df
   id val1 val2
0   0    B    A
1   1    A    A
2   2    B    B
3   3    B    B
like image 34
cs95 Avatar answered Nov 14 '22 13:11

cs95