[英]Add all column values repeated of one data frame to other in pandas
Having two data frames:有两个数据框:
df1 = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})
a b
0 1 4
1 2 5
2 3 6
df2 = pd.DataFrame({'c':[7],'d':[8]})
c d
0 7 8
The goal is to add all df2
column values to df1
, repeated and create the following result.目标是将所有
df2
列值添加到df1
,重复并创建以下结果。 It is assumed that both data frames do not share any column names.假设两个数据框不共享任何列名。
a b c d
0 1 4 7 8
1 2 5 7 8
2 3 6 7 8
If there are strings columns names is possible use DataFrame.assign
with unpack Series
created by selecing first row of df2
:如果有字符串列名称是可能的,使用
DataFrame.assign
和通过选择df2
第一行创建的解包Series
:
df = df1.assign(**df2.iloc[0])
print (df)
a b c d
0 1 4 7 8
1 2 5 7 8
2 3 6 7 8
Another idea is repeat values by df1.index
with DataFrame.reindex
and use DataFrame.join
(here first index value of df2
is same like first index value of df1.index
):另一个想法是通过
df1.index
与DataFrame.reindex
重复值并使用DataFrame.join
(这里df2
第一个索引值与df1.index
第一个索引值df1.index
):
df = df1.join(df2.reindex(df1.index, method='ffill'))
print (df)
a b c d
0 1 4 7 8
1 2 5 7 8
2 3 6 7 8
If no missing values in original df
is possible use forward filling missing values in last step, but also are types changed to floats, thanks @Dishin H Goyan:如果原始
df
没有缺失值可能在最后一步使用前向填充缺失值,但类型也更改为浮点数,谢谢@Dishin H Goyan:
df = df1.join(df2).ffill()
print (df)
a b c d
0 1 4 7.0 8.0
1 2 5 7.0 8.0
2 3 6 7.0 8.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.