Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign same random value to A-B , B-A pairs in python Dataframe

I have a Dataframe like

 Sou  Des
  1    3
  1    4
  2    3
  2    4
  3    1
  3    2
  4    1
  4    2

I need to assign random value for each pair between 0 and 1 but have to assign the same random value for both similar pairs like "1-3", "3-1" and other pairs. I'm expecting a result dataframe like

 Sou  Des   Val
  1    3    0.1
  1    4    0.6
  2    3    0.9
  2    4    0.5
  3    1    0.1
  3    2    0.9
  4    1    0.6
  4    2    0.5

How to assign same random value similar pairs like "A-B" and "B-A" in python pandas .

like image 750
kumaran ragunathan Avatar asked Feb 25 '18 00:02

kumaran ragunathan


2 Answers

Let's create first a sorted by axis=1 helper DF:

In [304]: x = pd.DataFrame(np.sort(df, axis=1), df.index, df.columns)

In [305]: x
Out[305]:
   Sou  Des
0    1    3
1    1    4
2    2    3
3    2    4
4    1    3
5    2    3
6    1    4
7    2    4

now we can group by its columns:

In [306]: df['Val'] = (x.assign(c=1)
                        .groupby(x.columns.tolist())
                        .transform(lambda x: np.random.rand(1)))

In [307]: df
Out[307]:
   Sou  Des       Val
0    1    3  0.989035
1    1    4  0.918397
2    2    3  0.463653
3    2    4  0.313669
4    3    1  0.989035
5    3    2  0.463653
6    4    1  0.918397
7    4    2  0.313669
like image 175
MaxU - stop WAR against UA Avatar answered Oct 01 '22 05:10

MaxU - stop WAR against UA


This is new way

s=pd.crosstab(df.Sou,df.Des)

b = np.random.random_integers(-2000,2000,size=(len(s),len(s)))
sy = (b + b.T)/2

s.mul(sy).replace(0,np.nan).stack().reset_index()

Out[292]: 
   Sou  Des       0
0    1    3   -60.0
1    1    4  -867.0
2    2    3   269.0
3    2    4  1152.0
4    3    1   -60.0
5    3    2   269.0
6    4    1  -867.0
7    4    2  1152.0
like image 43
BENY Avatar answered Oct 01 '22 06:10

BENY