【问题标题】:Combining two series into one with mismatching indicies将两个系列合并为一个索引不匹配的系列
【发布时间】:2019-05-31 13:41:15
【问题描述】:

我正在尝试将两个索引不匹配的系列合并为一个,我想知道最佳实践是什么。

我尝试了 combine_first 但我遇到了一个问题,将系列 [0, 24, ...] 与系列 [1, 25, ...] 组合应该给出一个带有索引 [0, 1, 24 的系列, 25, ...] 但我得到的是 [0, 12, 24, 36, ...]

for row in all_rows:
    base_col = base_col.combine_first(row)

我只想将具有互斥索引的两个系列组合成一个系列,其中包含两个索引的正确排序顺序。有点像拉链。

【问题讨论】:

  • 你觉得 align 或 pd.concat 更有用吗?
  • 两者都很棒:)

标签: python pandas sorting series


【解决方案1】:

您可以使用pd.concat 后跟sort_index

s1 = pd.Series([1, 2, 3, 4], index=[0, 24, 30, 40])
s2 = pd.Series([5, 6, 7, 8], index=[1, 25, 35, 38])

s = pd.concat([s1, s2]).sort_index()

print(s)

0     1
1     5
24    2
25    6
30    3
35    7
38    8
40    4
dtype: int64

【讨论】:

  • 借用你的设置 :-)
【解决方案2】:

使用align

sum(s1.align(s2,fill_value=0))
0     1.0
1     5.0
24    2.0
25    6.0
30    3.0
35    7.0
38    8.0
40    4.0
dtype: float64

【讨论】:

  • align 一种很少使用的 pandas 方法。但是,这是一个很好的例子。
猜你喜欢
  • 2021-05-30
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 2023-01-20
  • 2018-09-17
  • 1970-01-01
  • 2020-09-15
相关资源
最近更新 更多