python - 附加具有相同索引的 Pandas 系列的简单方法

标签 python pandas

有没有一种简单的方法可以将 pandas 系列附加到另一个系列并更新其索引?目前我有两个系列

from numpy.random import randn
from pandas import Series

a = Series(randn(5))
b = Series(randn(5))

我可以通过

b附加到a
a.append(b)

>>> 0   -0.191924
    1    0.577687
    2    0.332826
    3   -0.975678
    4   -1.536626
    0    0.828700
    1    0.636592
    2    0.376864
    3    0.890187
    4    0.226657

但是有没有比

更聪明的方法来确保我有一个连续的索引
a=Series(randn(5))
b=Series(randn(5),index=range(len(a),len(a)+len(b)))
a.append(b)  

最佳答案

一种选择是使用reset_index:

>>> a.append(b).reset_index(drop=True)
0   -0.370406
1    0.963356
2   -0.147239
3   -0.468802
4    0.057374
5   -1.113767
6    1.255247
7    1.207368
8   -0.460326
9   -0.685425
dtype: float64

为了正义,Roman Pekar最快的方法:

>>> timeit('from __main__ import np, pd, a, b; pd.Series(np.concatenate([a,b]))', number = 10000)
0.6133969540821536
>>> timeit('from __main__ import np, pd, a, b; pd.concat([a, b], ignore_index=True)', number = 10000)
1.020389742271714
>>> timeit('from __main__ import np, pd, a, b; a.append(b).reset_index(drop=True)', number = 10000)
2.2282133623128075

关于python - 附加具有相同索引的 Pandas 系列的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20400135/

相关文章:

python - TypeError:预期的二进制或 Unicode 字符串,得到 618.0

pandas - 在 Pandas 多索引 DataFrame 上扩展指数权重,其中每一天都是一个矩阵

python - 合并字符串列表和列表列表

python - 如何将参数传递给 Tornado 的 WebSocketHandler 类?

python - 我应该如何读取和使用 ~40GB csv 中的数据进行时间序列预测?

python - Pandas 将带有 unix 时间戳(以毫秒为单位)的行转换为日期时间

python - 使用Python提取csv(数据框)中的特定字符串数据

python - 从 pandas 数据框中的字符串中提取信息非常困难

python - 选择随机 Action 的 Tensorflow 代理

python - win32pdh.EnumObjectItems 调用错误