简体   繁体   English

将一个数据框的所有重复列值添加到 Pandas 中的另一个数据框

[英]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.indexDataFrame.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.

相关问题 通过熊猫数据框中的列中的重复值进行汇总 - Aggregate by repeated values in a column in a data frame in pandas 如何根据其他行值添加 pandas 数据框列 - How to add pandas data frame column based on other rows values 如何将 91 添加到 pandas 数据帧的列中的所有值? - How to add 91 to all the values in a column of a pandas data frame? 更改Pandas数据框中的一列中的所有值 - Changing all values in one column of Pandas data frame 如何使用 pandas 数据框将数据框的每一列值添加到一张一张的新工作表中 - How to add each column of a data frame values in one by one new sheets using pandas data frame 根据 pandas 数据帧中的其他列值组合列值 - Combine column values based on the other column values in pandas data frame Pandas 数据框 - 将前一列中与特定条件匹配的所有值相加并将其添加到新列中 - Pandas Data Frame - Sum all the values in a previous column which match a specific condition and add it to a new column 向数据框中添加新行,其中一列保持不变,而另一列更改值 - Add new rows to data frame, where one column stays the same while other column changes values 根据其他数据框列值过滤熊猫数据框 - Filter pandas Data Frame Based on other Dataframe Column Values 一个单元格的字符串值在 pandas 数据帧的其他列中重复了多少次? - How many time a string value of a cell is repeated in other column of pandas data frame?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM