Python Pandas: How To Replace Values In A Dataframe Based On Another Array In Conditional Base
I have a DataFrame as follows. Both columns have Member_ID which indicates which Member_ID connected with other Member_ID col1 col2 1 3 1 4 1 5 2
Solution 1:
we can stack
, map
and unstack
:
In [9]: d1.stack().map(d2.set_index('member_ID')['Label']).unstack()
Out[9]:
col1 col2
0 a1 a3
1 a1 b4
2 a1 b5
3 b2 a3
4 b2 b4
5 a3 a1
6 a3 b2
7 a3 b5
8 b4 a1
9 b4 b2
10 b5 a1
11 b5 a3
Solution 2:
Or you can try this
df2.set_index('member_ID',inplace=True)
df1.apply(lambda x: x.map(df2['Label']))
col1 col2
0 a1 a3
1 a1 b4
2 a1 b5
3 b2 a3
4 b2 b4
5 a3 a1
6 a3 b2
7 a3 b5
8 b4 a1
9 b4 b2
10 b5 a1
11 b5 a3
Solution 3:
You can use pd.DataFrame.replace
using a pd.Series
in a dictionary context.
d1.replace(d2.set_index('member_ID').Label)
col1 col2
0 a1 a3
1 a1 b4
2 a1 b5
3 b2 a3
4 b2 b4
5 a3 a1
6 a3 b2
7 a3 b5
8 b4 a1
9 b4 b2
10 b5 a1
11 b5 a3
Post a Comment for "Python Pandas: How To Replace Values In A Dataframe Based On Another Array In Conditional Base"