简体   繁体   English

追加pandas数据框并添加自己的值(python)

[英]Appending pandas dataframe and adding its own values (python)

my dataframe looks like: 我的数据框看起来像:

hours  |  cumulative value  |  value to add
  1              1                  1
  2              2                  1
  3              3                  3
  4              6                  1

What I want is, to append this dataframe like eg: 2-times (should be up to 50-times) and add its own values. 我想要的是,像这样附加该数据帧:2次(最多50次)并添加自己的值。 It should look like: 它应该看起来像:

hours  |  cumulative value |  value to add
  1              1                 1
  2              2                 1
  3              3                 3
  4              6                 1
  #The first time 
  5              7                 1
  6              8                 1
  7              9                 3
  8              12                1
  #The second time
  9              13                1
  10             14                1
  11             15                3
  12             18                1

And so on.. 等等..

I am strugglin to find an optimal solution for that. 我努力寻找最佳解决方案。 Has anyone a good idea? 有没有个好主意?

You need to repeat value to add and then compute other columns. 您需要重复value to add ,然后计算其他列。 It is best if you make a series separately and then simply create a new dataframe. 最好是分别制作一个series ,然后简单地创建一个新的数据框。

s = pd.Series((df['value to add'].tolist()) *50)
data = pd.DataFrame({
    'hour': range(1, len(s)+1),
    'cumulative value' : s.shift().fillna(s[0]).cumsum(),
    'value to add': s
})
data.head(10)

Output: 输出:

      hour  cumulative value  value to add
0     1                 1           1.0
1     2                 2           2.0
2     3                 5           3.0
3     4                 6           6.0
4     5                 7           7.0
5     6                 8           8.0
6     7                11           9.0
7     8                12          12.0
8     9                13          13.0
9    10                14          14.0

Here's a little function that can achieve this for you on a row by row basis (keeps appending new rows to the data frame) 这是一个小功能,可以逐行为您实现此功能(保留将新行追加到数据帧的功能)

df = pd.DataFrame({'hours':[1,2,3,4],
                   'cumulative value':[1,2,3,6], 
                   'Value to add': [1,1,3,1]})


def add_row(dataframe, numtimes): #adds new row 'numtimes' many times
    for i in range(numtimes):

        # Get values to put in new row

        new_hour = dataframe['hours'].iloc[-1]+1
        new_cumulative_value = dataframe['cumulative value'].iloc[-1]+dataframe['Value to add'].iloc[-1]
        if new_hour % 3 == 0:
            new_val_to_add = 3
        else:
            new_val_to_add = 1

        #Create new row and add to DataFrame

        new_row = pd.DataFrame({'hours':[new_hour],
                                'cumulative value':[new_cumulative_value],
                                'Value to add': [new_val_to_add]},
                                index=[new_hour-1])

        dataframe = dataframe.append(new_row)

    return dataframe


df =add_row(df, 50)
new_df = pd.concat([df] * 50, ignore_index=True)
new_df["hours"] = np.arange(df.shape[0])
new_df["cumulative_value"] = df["value_to_add"].cumsum()
from functools import reduce
def repeat(df,number):
    series1 = np.tile(np.array(df['value to add']),number)
    series2 = reduce((lambda x,y: np.append(x,y+x[-1])),[np.array(df['cumulative value'] for i in range(number)])
    series3 = reduce((lambda x,y: np.append(x,y+x[-1])),[np.array(df['hours'] for i in range(number)])
    return(pd.DataFrame({'hours':series3,'cumulative value':series2,'value to add':series1})

Running this function with number =3 gives number = 3运行此函数得到

   hour  cumulative value  value to add
0     1                 1             1
1     2                 2             1
2     3                 5             3
3     4                 6             1
4     5                 7             1
5     6                 8             1
6     7                11             3
7     8                12             1
8     9                13             1
9    10                14             1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM