Issue
Check the following dataset:
d = {'col1':[2,4,5,6],'col2':[8,8,6,1],'col3':[1,2,3,4],'col4':[4,4,4,4]}
df = pd.DataFrame(d,index=['Item1','Item2','Item1','Item2'])
Lets say i want to interact through the columns, and create a diff column. That gives me difference beetween col1, col2 and them another diff column that gives me col3,col4. And so on like in a window by window style. Difference columns.
d = {'col1':[2,4,5,6],'col2':[8,8,6,1],'diff_1':[-6,-4,1,5],'col3':[1,2,3,4],'col4':[4,4,4,4],'diff_2':[-3,-2,-1,0]}
df = pd.DataFrame(d,index=['Item1','Item2','Item1','Item2'])
Solution
You can check groupby
then concat
back
out = pd.concat([y.assign(**{'diff_{0}'.format(x+1): y.iloc[:,0] - y.iloc[:,1]})for x , y in df.groupby(np.arange(df.shape[1])//2,axis=1)],axis=1)
Out[166]:
col1 col2 diff_1 col3 col4 diff_2
Item1 2 8 -6 1 4 -3
Item2 4 8 -4 2 4 -2
Item1 5 6 -1 3 4 -1
Item2 6 1 5 4 4 0
Answered By - BENY
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.