Reputation: 307
I want to use some function that requires to concat two dataframe. Here is the example:
import numpy as np
import pandas as pd
data1 = np.array([['','Col1','Col2'],['1',1,2],['2',3,4]])
data1=pd.DataFrame(data=data1[1:,1:],index=data1[1:,0],columns=data1[0,1:])
data2=np.array([['','Col1','Col2'],['1',5,6],['2',7,8]])
data2=pd.DataFrame(data=data2[1:,1:],index=data2[1:,0],columns=data2[0,1:])
X=pd.concat([data1,data2],0)
X_transformed=func(X)
Now I want to unconcat X_transformed back into the original data1 and data2. Is there a way to do so?
Upvotes: 1
Views: 274
Reputation: 862581
You can add parameter keys
to concat
for distinguish each DataFrame and then select by loc
:
X=pd.concat([data1,data2],0, keys=[0,1])
print (X)
Col1 Col2
0 1 1 2
2 3 4
1 1 5 6
2 7 8
data11 = X.loc[0]
data22 = X.loc[1]
print (data11)
Col1 Col2
1 1 2
2 3 4
print (data22)
Col1 Col2
1 5 6
2 7 8
EDIT:
More general solution:
data3=data2.iloc[[0]].rename({'1':'10'})
dfs = [data1,data2,data3]
X=pd.concat(dfs, keys=np.arange(len(dfs)))
print (X)
Col1 Col2
0 1 1 2
2 3 4
1 1 5 6
2 7 8
2 10 5 6
print (X.xs(0))
Col1 Col2
1 1 2
2 3 4
print (X.xs(1))
Col1 Col2
1 5 6
2 7 8
print (X.xs(2))
Col1 Col2
10 5 6
Upvotes: 2
Reputation: 57033
X_transformed.iloc[:data1.shape[0]]
is the first dataframe. X_transformed.iloc[data1.shape[0]:]
is the second one.
Upvotes: 0