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