Merge two dataframes with same dimensions (mxn) and column/index names into a new (3D) data frame where each column is divided into two subcolumns

huangapple go评论67阅读模式
英文:

Merge two dataframes with same dimensions (mxn) and column/index names into a new (3D) data frame where each column is divided into two subcolumns

问题

我有两个具有相同列/索引名称的数据框(A和B)。我想将它们合并成一个新的数据框,其中每个列都分为两个子列(A和B)。

英文:

I have two dataframes (A and B) with same column/index names. I want to merge them into a new dataframe where each column is divided into two subcolumns (A and B).

答案1

得分: 1

使用concat函数,通过参数keys在列上创建多重索引:

np.random.seed(2023)

A = pd.DataFrame(np.random.randint(10, size=(3,3)), columns=list('abc'))
B = pd.DataFrame(np.random.randint(10, size=(3,3)), columns=list('abc'))

df = pd.concat([A, B], axis=1, keys=('A','B'))
print (df)

输出结果:

   A        B
   a  b  c  a  b  c
0  7  9  6  5  0  6
1  7  1  3  1  5  7
2  4  4  6  5  8  2
英文:

Use concat for MultiIndex in columns by parameter keys:

np.random.seed(2023)

A = pd.DataFrame(np.random.randint(10, size=(3,3)), columns=list('abc'))
B = pd.DataFrame(np.random.randint(10, size=(3,3)), columns=list('abc'))

df = pd.concat([A, B], axis=1, keys=('A','B'))
print (df)

Output:

   A        B
   a  b  c  a  b  c
0  7  9  6  5  0  6
1  7  1  3  1  5  7
2  4  4  6  5  8  2

huangapple
  • 本文由 发表于 2023年6月8日 18:14:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定