【问题标题】:Merge pandas series with different index (align on one index)合并具有不同索引的熊猫系列(对齐一个索引)
【发布时间】:2018-09-17 04:25:12
【问题描述】:

我有来自不同熊猫系列的结果,最终形成 1x1 系列。现在我想将它们全部合并到一个 1xN 行。它们中的每一个都可以有不同的索引。

我可以为它们中的每一个重置索引并创建一个新的数据框。但是,我想知道是否有比这更快/更简单的方法。

edit1:添加数据和所需的输出样本

A
326    0.005077
dtype: float64

date
4300   2011-01-18 16:00:00
Name: datetime, dtype: datetime64[ns]

B
5    0.004077
dtype: float64

我想要类似的东西:

Index                    A            B
2011-01-18 16:00:00    0.005077     0.004077

我想要这个的原因:程序运行一个循环并返回多个上述 1xN 行,如果日期不同,我想将这些行相互附加,或者如果日期(索引)相同,则将值相加(可以如下所示完成:Loop: Results to be updated via += if on the same date, otherwise write next line

edit2:抱歉,我的代码中有一些例外情况,我必须设置某些系列对象 = 0。有什么方法可以将它包含在下面的一个衬里中,还是我需要将 pd.series 从我的零中取出?

【问题讨论】:

  • 可以添加数据样本和预期输出吗?
  • 你认为另一个C 系列与0 吗?然后df = pd.DataFrame([np.concatenate([A, B, C])], columns=['A','B', 'C'], index=date) should working nice print (df)
  • 答案已编辑。
  • 嗯,所以 C 有时应该是 one value Series 有时是标量?
  • 或更具体的C = C if isinstance(C, pd.Series) else pd.Series([C])

标签: python pandas indexing merge


【解决方案1】:

我认为需要:

A = pd.Series([0.005077], index=[326])
date = pd.Series(['2011-01-18 16:00:00'], index=[4300])
B = pd.Series([ 0.004077], index=[5])

df = pd.DataFrame([np.concatenate([A, B])], columns=['A','B'], index=date)
print (df)
                            A         B
2011-01-18 16:00:00  0.005077  0.004077

编辑:

对于标量是必要的,创建一个项目列表:

A = pd.Series([0.005077], index=[326])
date = pd.Series(['2011-01-18 16:00:00'], index=[4300])
B = pd.Series([ 0.004077], index=[5])
C = 0

df = pd.DataFrame([np.concatenate([A, B, [C] ])], columns=['A','B','C'], index=date)
print (df)
                            A         B    C
2011-01-18 16:00:00  0.005077  0.004077  0.0

【讨论】:

  • 结果 df 为 Nx1。只是一个建议。
  • 谢谢,jezrael 和 Rao Sahab。对我来说是这样吗:df = pd.concat([A, B]).to_frame([date]).T?
  • @jezrael 你能添加设置索引以满足他的要求吗
  • @eternity1 - 也适合你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 2017-01-31
  • 2018-12-25
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
相关资源
最近更新 更多