简体   繁体   English

连接两个索引长度不同的 Pandas DataFrame 列

[英]Concat two Pandas DataFrame column with different length of index

How do I add a merge columns of Pandas dataframe to another dataframe while the new columns of data has less rows?如何将 Pandas dataframe 的合并列添加到另一个 dataframe 而新数据列的行数较少? Specifically I need to new column of data to be filled with NaN at the first few rows in the merged DataFrame instead of the last few rows.具体来说,我需要在合并的 DataFrame 而不是最后几行的前几行用 NaN 填充新的数据列。 Please refer to the picture.请参考图片。 Thanks.谢谢。

在此处输入图像描述

Use:利用:

df1 = pd.DataFrame({
        'A':list('abcdef'),
        'B':[4,5,4,5,5,4],
})

df2 = pd.DataFrame({
        'SMA':list('rty')
})

df3 = df1.join(df2.set_index(df1.index[-len(df2):]))

Or:或者:

df3 = pd.concat([df1, df2.set_index(df1.index[-len(df2):])], axis=1)
print (df3)
   A  B  SMA
0  a  4  NaN
1  b  5  NaN
2  c  4  NaN
3  d  5    r
4  e  5    t
5  f  4    y

How it working:它是如何工作的:

First is selected index in df1 by length of df2 from back:首先是从后面按df2的长度在df1中选择的索引:

print (df1.index[-len(df2):])
RangeIndex(start=3, stop=6, step=1)

And then is overwrite existing values by DataFrame.set_index :然后用DataFrame.set_index覆盖现有值:

print (df2.set_index(df1.index[-len(df2):]))
  SMA
3   r
4   t
5   y

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

相关问题 pandas concat DataFrame对不同的索引 - pandas concat DataFrame on different Index Pandas:将系列添加到数据框作为列(相同的索引,不同的长度) - Pandas: Add series to dataframe as a column (same index, different length) 如何合并格式相同但长度索引不同的两个熊猫数据框 - how to combine two pandas dataframe with same format but different length index Pandas Concat不同大小的DataFrame到列的结尾 - Pandas Concat Different Sized DataFrame to End of Column 将多个pandas数据帧列与另一个具有不同长度和索引的数据帧的一列进行比较 - compare multiple columns of pandas dataframe with one column of another dataframe having different length and index 比较 Pandas Dataframe 中不同长度的两个列表 - Compare two lists in Pandas Dataframe with different length 如何创建新的 pandas 列,其中列表值 ==df 索引但列表的长度与原始 dataframe 的长度不同 - how to create new pandas column where list value ==df index but list is a different length to orignal dataframe 当index相同时,DataFrame会连接不同的列值 - DataFrame concat different column values when index are the same Pandas 在不同长度的列上合并两个数据帧 - Pandas merge two dataframes on column with different length 连接或合并两个 dataframe pandas - Concat, or merge two dataframe pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM