本文介绍了如何将列添加到由另一列的n个前一个值的数组构成的Pandas数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很喜欢蟒蛇和熊猫。我不知道如何以优雅的方式解决以下问题。



假设我们有一个简单的熊猫数据框。 >

  import numpy as np 
import pandas as pd
from pandas import DataFrame,Series
df = pd .DataFrame(np.arange(0,60,10),columns = ['Value'])


现在设置一个变量,例如:

  n = 3 

目标是添加一列到df,由n个前面值的数组组成,如下所示:





下一步可能是设置NaNs为零。



有没有一个聪明的方法呢?



提前谢谢你的帮助,



吉尔伯特

解决方案

我们可以使用 df.shift 以生成偏移列和列表解析,将它们分组在一起,然后 map 生成列表列表数据框。然而,生成的列表列表将需要先转移到原始 df ,以便我们有一个对应于正确行的值的列表。

  df [ b] = np.array(map(list,[df [a]。shift(x)for x in range(1,4)]))T.tolist()

输入:

  a 
0 1
1 2
2 3
3 4

输出:

  ab 
0 1 [nan,nan,nan]
1 2 [ nan,nan]
2 3 [2.0,1.0,nan]
3 4 [3.0,2.0,1.0]


I am new to python and pandas. I don't know how to solve the following problem in an elegant way.

Let's say we have a simple pandas dataframe.

import numpy as np
import pandas as pd
from pandas import DataFrame, Series
df = pd.DataFrame(np.arange(0,60,10), columns=['Value'])

Now set a variable, e.g.:

n = 3

The goal is to add a column to df, made of arrays of the n-preceding values, as following:

The next step could be to set NaNs to zero.

Is there a smart way to do this?

Thank you in advance for your help,

Gilbert

解决方案

We can use a df.shift to generate the offset columns and a list comprehension to group them together then map to generate a list of lists for the dataframe. However, the list of lists generated will need to be transposed first before assigning it to the original df so that we have an list of values corresponding to the correct row.

df["b"] =np.array(map(list,[df["a"].shift(x) for x in range(1,4)])).T.tolist()

Input:

   a
0  1
1  2
2  3
3  4

Output:

   a                b
0  1  [nan, nan, nan]
1  2  [1.0, nan, nan]
2  3  [2.0, 1.0, nan]
3  4  [3.0, 2.0, 1.0]

这篇关于如何将列添加到由另一列的n个前一个值的数组构成的Pandas数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:20