简体   繁体   English

在 pandas python 中填充来自其他数据帧的数据帧值

[英]Fill the dataframe values from other dataframe in pandas python

I have 2 dataframes df1 and df2.我有 2 个数据框 df1 和 df2。 df1 is filled with values and df2 is empty. df1 填充有值,而 df2 为空。

df1 and df2, as it can be seen, both dataframes's index and columns will always be same, just difference is df1 doesn't contain duplicate values of columns and indexes but df2 does contain. df1 和 df2,可以看出,数据帧的索引和列将始终相同,只是不同之处在于 df1 不包含列和索引的重复值,但 df2 确实包含。

How to fill values in df2 from df1, so that it also considers the combination of index and columns?如何从 df1 填充 df2 中的值,以便它也考虑索引和列的组合?

在此处输入图像描述

df1 = pd.DataFrame({'Ind':pd.Series([1,2,3,4]),1:pd.Series([1,0.2,0.2,0.8])
                    ,2:pd.Series([0.2,1,0.2,0.8]),3:pd.Series([0.2,0.2,1,0.8])
                    ,4:pd.Series([0.8,0.8,0.8,1])})
df1 = df1.set_index(['Ind'])

df2 = pd.DataFrame(columns = [1,1,2,2,3,4], index=[1,1,2,2,3,4])

IIUC, you want to update : IIUC,您要update

df2.update(df1)
print(df2)

     1    1    2    2    3    4
1  1.0  1.0  0.2  0.2  0.2  0.8
1  1.0  1.0  0.2  0.2  0.2  0.8
2  0.2  0.2  1.0  1.0  0.2  0.8
2  0.2  0.2  1.0  1.0  0.2  0.8
3  0.2  0.2  0.2  0.2  1.0  0.8
4  0.8  0.8  0.8  0.8  0.8  1.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM