熊猫基于100创建系列

时间:2018-02-12 07:12:47

标签: python pandas

我需要根据100的起始值创建和索引。

我可以做一个循环,这确实有效,但我知道有一种更好的方法可以在一行代码中完成。

所以我有一系列的百分比变化如下:

df['pct_chg'] = [0, 1.5, 0.4, 2.1, -3.1, 2.4, -0.8 ]

需要让它成为:

df['uv_acct']=[ 100.0, 101.5, 101.9, 104.0, 100.8, 103.2, 102.4 ]

所以公式是:

uv_acct  = uv_acct[-1] * (1 + (pct_chg/100) )

一个转折是索引设置为日期。

这确实有效,但我知道这不是最有效的方法。

for x in range ( len ( df ) ):

    # first month - starting index value
    if x == 0:
        df [ 'uv_acct' ] =  100 
    else:
        df [ 'uv_acct' ] = df [ 'uv_acct' ].iloc [ x - 1 ] * (1 + df [ 'pct_acct' ].iloc [ x ])

在初始值为100时创建此类索引的最佳方法是什么?

谢谢。欢呼声。

1 个答案:

答案 0 :(得分:1)

您可以尝试np.cumprod

ERROR in ./src/main.js
Module build failed: Error: Couldn't find preset "stage-2" relative to directory "/Users/Desktop/Project/2018-02e_admin_site/src"
    at /Users/Desktop/Project/2018-02-12/vue_admin_site/node_modules/babel-core/lib/transformation/file/options/-manager.js:293:19
    at Array.map (<anonymous>)
    at OptionManager.resolvePresets (/Users/luowensheng/Desktop/QIYUN/Project/2018-02-12/vue_admin_site/node_modules/babel-core/lisformation/file/options/option-manager.js:275:20)
    at OptionManager.mergePresets (/Users/Desktop/Project/2018-02-12/vue_admin_site/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
    at OptionManager.mergeOptions (/Users/Desktop//2018-02-12/vue_admin_site/node_modules/babel-core/lib/ormation/file/options/option-manager.js:249:14)
    at OptionManager.init (/Users/Desktop/Project/2018-02-12/vue_admin_site/node_modules/babel-core/lib/transfor/file/options/option-manager.js:368:12)
.....
@ multi (webpack)-dev-server/client?http://0.0.0.0:8080 webpack/hot/dev-server ./src/vendors

输出:

import numpy as np

pct_chg = np.array([0, 1.5, 0.4, 2.1, -3.1, 2.4, -0.8])
uv_acct = 100 * np.cumprod(1 + pct_chg / 100)