Pandas 合并特定索引的数据帧

问题描述 投票:0回答:1

我有两个 pandas 数据框:

x_轴:

索引 日期
1 2023年1月1日
2 2023年2月1日
3 2023年3月1日
4 2023 年 4 月 1 日
5 2023年5月1日
6 2023年6月1日
7 2023年7月1日
8 2023年8月1日
9 2023年9月1日

df:

索引 快照日期 一些_数据
1 2023年3月1日 12
2 2023 年 4 月 1 日 85
3 2023年5月1日 46
4 2023年6月1日 74285
5 0 427
6 0 452

我想得到这样的合并/连接:

所需_df:

索引 日期 index_y 快照日期 一些_数据
1 2023年1月1日
2 2023年2月1日
3 2023年3月1日 1 2023年3月1日 12
4 2023 年 4 月 1 日 2 2023 年 4 月 1 日 85
5 2023年5月1日 3 2023年5月1日 46
6 2023年6月1日 4 2023年6月1日 74285
7 2023年7月1日 5 0 427
8 2023年8月1日 6 0 452
9 2023年9月1日

基本上,我想在 datesnap_date 的第一场比赛中将 df 连接到 x_axis,但我不想加入日期,因为 index_y 5 和 6 也应该包含在 中想要的_df。 更多信息:

  • snap_date 始终是 date
  • 的子集
  • snap_datedate 都是均匀间隔、排序、唯一的并且没有 NAN。基本上是熊猫约会系列。

已经谢谢你了!

python pandas dataframe join concatenation
1个回答
0
投票

您可以使用自定义

join

# identify first date
first_date = df['snap_date'].iloc[0]
# and it's first index
first_index = next(iter(x_axis.index[x_axis['date'].eq(first_date)]))

# set the index of x_axis and join
out = x_axis.join(df.set_axis(x_axis.index[first_index:first_index+len(df)]),
                  rsuffix='_y')

输出:

   index        date  index_y   snap_date  some_data
0      1  01-01-2023      NaN         NaN        NaN
1      2  02-01-2023      NaN         NaN        NaN
2      3  03-01-2023      1.0  03-01-2023       12.0
3      4  04-01-2023      2.0  04-01-2023       85.0
4      5  05-01-2023      3.0  05-01-2023       46.0
5      6  06-01-2023      4.0  06-01-2023    74285.0
6      7  07-01-2023      5.0           0      427.0
7      8  08-01-2023      6.0           0      452.0
8      9  09-01-2023      NaN         NaN        NaN
© www.soinside.com 2019 - 2024. All rights reserved.