我有两个具有相同形状、索引和列的 pandas 数据框 A,B
。 A
的每个元素都是形状为 (n,1)
的 np.ndarray
,B
的每个元素是一个浮点值。现在我想高效将B
元素逐个附加到A
。一个最小的例子:
index = ['fst', 'scd']
column = ['a','b']
A
Out[23]:
a b
fst [1, 2] [1, 4]
scd [3, 4] [3, 2]
B
Out[24]:
a b
fst 0.392414 0.641136
scd 0.264117 1.644251
resulting_df = pd.DataFrame([[np.append(A.loc[i,j], B.loc[i,j]) for i in index] for j in column], columns=column, index=index)
resulting_df
Out[27]:
a b
fst [1.0, 2.0, 0.392414377685] [3.0, 4.0, 0.264117463613]
scd [1.0, 4.0, 0.641136433253] [3.0, 2.0, 1.64425062851]
有类似pd.DataFrame.applymap
的东西吗?可以在两个而不是一个 pandas 数据帧之间按元素进行操作?
最佳答案
您可以使用 applymap 将 df2 中的元素转换为列表,然后只需普通加法即可组合列表,即
index = ['fst', 'scd']
column = ['a','b']
A = pd.DataFrame([[[1, 2],[1, 4]],[[3, 4],[3, 2]]],index,column)
B = pd.DataFrame([[0.392414,0.264117],[ 0.641136 , 1.644251]],index,column)
选项 1:
n = B.applymap(lambda y: [y])
ndf = A.apply(lambda x : x+n[x.name])
选项 2:
使用 pd.concat
了解其工作原理检查 here即
pd.concat([A,B]).groupby(level=0).apply(lambda g: pd.Series({i: np.hstack(g[i].values) for i in A.columns}))
为了使当前方法给出正确的输出,请移动循环,即
pd.DataFrame([[np.append(A.loc[i,j], B.loc[i,j]) for j in A.columns] for i in A.index], columns=A.columns, index=A.index)
输出:
a b fst [1.0, 2.0, 0.392414] [1.0, 4.0, 0.264117] scd [3.0, 4.0, 0.641136] [3.0, 2.0, 1.644251]
关于python - pandas dataframe如何进行 "elementwise"串联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46580327/