gpt4 book ai didi

python - 将 Pandas 数据框中的一行复制到另一行的多行中

转载 作者:太空宇宙 更新时间:2023-11-04 02:43:59 27 4
gpt4 key购买 nike

我有 2 个具有相同列的 Pandas 数据框(df1 和 df2),我试图将 1 行从 df1 复制到 df2 的多行。 df2是一个多索引数据框,第一个索引对应df1的索引值,第二个索引为整数值。

它们是这样定义的:

df1 = pd.DataFrame(index=['one', 'two', 'three'], columns=['c1', 'c2', 'c3', 'c4'], data=np.random.random((3, 4)))

index = pd.MultiIndex.from_arrays([['one', 'one', 'two', 'two', 'two', 'three'], [0, 1, 0, 1, 2, 0]])
df2 = pd.DataFrame(index=index, columns=['c1', 'c2', 'c3', 'c4'])

它们长什么样子:

In : df1
Out:
c1 c2 c3 c4
one 0.158366 0.843546 0.810493 0.925164
two 0.880147 0.464835 0.416196 0.389786
three 0.138132 0.061891 0.320366 0.727997


In : df2
Out:
c1 c2 c3 c4
one 0 NaN NaN NaN NaN
1 NaN NaN NaN NaN
two 0 NaN NaN NaN NaN
1 NaN NaN NaN NaN
2 NaN NaN NaN NaN
three 0 NaN NaN NaN NaN

下面是我如何设法将数据从 df1 复制到 df2:

for index, data in df1.iterrows():
num = len(df2.loc[index])
for i in range(num):
df2.loc[(index, i)] = df1.loc[index]

结果:

In : df2
Out:
c1 c2 c3 c4
one 0 0.158366 0.843546 0.810493 0.925164
1 0.158366 0.843546 0.810493 0.925164
two 0 0.880147 0.464835 0.416196 0.389786
1 0.880147 0.464835 0.416196 0.389786
2 0.880147 0.464835 0.416196 0.389786
three 0 0.138132 0.0618906 0.320366 0.727997

知道如何更有效地做到这一点吗?

最佳答案

您可以使用 DataFrame.align , 在元组中返回 DataFrames ,所以添加 [1] 来选择第二个:

np.random.seed(23)
df1 = pd.DataFrame(index=['one', 'two', 'three'], columns=['c1', 'c2', 'c3', 'c4'], data=np.random.random((3, 4)))

index = pd.MultiIndex.from_arrays([['one', 'one', 'two', 'two', 'two', 'three'], [0, 1, 0, 1, 2, 0]])
df2 = pd.DataFrame(index=index, columns=['c1', 'c2', 'c3', 'c4'])

print (df1)
c1 c2 c3 c4
one 0.517298 0.946963 0.765460 0.282396
two 0.221045 0.686222 0.167139 0.392442
three 0.618052 0.411930 0.002465 0.884032


df3 = df2.align(df1, level=0)[1]
print (df3)
c1 c2 c3 c4
one 0 0.517298 0.946963 0.765460 0.282396
1 0.517298 0.946963 0.765460 0.282396
two 0 0.221045 0.686222 0.167139 0.392442
1 0.221045 0.686222 0.167139 0.392442
2 0.221045 0.686222 0.167139 0.392442
three 0 0.618052 0.411930 0.002465 0.884032

关于python - 将 Pandas 数据框中的一行复制到另一行的多行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674507/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com