【问题标题】:How to loop through a series and create a new series based on values from the original series?如何循环一个系列并根据原始系列的值创建一个新系列?
【发布时间】:2021-10-09 02:23:37
【问题描述】:

我正在尝试创建一个新系列,该系列使用一系列两列中的条目。 每列包含一个上限和下限,我想为新系列的每个条目创建一个数组。

系列 =

lower upper
0 20.20 56.20
1 10.00 77.70

我想要的是使用以下代码:

np.linsapce(lower,upper,5) 

这将创建一个由 5 个点组成的数组,从小数到大数。新系列看起来像:

range
0 [20.2, 25.34285714, 30.48571429... 56.2]
1 [10., 19.67142857, 29.34285714... 77.7]

【问题讨论】:

  • 一系列两列实际上是一个DataFrame。

标签: python pandas numpy series linspace


【解决方案1】:

使用apply:

df['range'] = df.apply(lambda x: np.linspace(x['lower'], x['upper'], 5), axis=1)
>>> df
   lower   upper                                            range

0    20.2   56.2                   [20.2, 29.2, 38.2, 47.2, 56.2]
1    10.0   77.7  [10.0, 26.925, 43.85, 60.775000000000006, 77.7]

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 2018-12-20
    • 2020-09-15
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2016-11-25
    相关资源
    最近更新 更多