如何在python数据帧中存储列表

时间:2017-07-04 17:46:18

标签: python list dataframe

我试图创建一个数据框,其中一列是其他列的值列表,如:

   a             b  MA2  MA4
0  1   [1,NaN,NaN]  NaN  Nan
1  2   [2,1.5,NaN]  1.5  NaN
2  3   [3,2.5,NaN]  2.5  NaN
3  4   [4,3.5,2.5]  3.5  2.5
...

但我无法弄清楚如何将列b中的值设为列表。

我的测试代码是:

df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8,9]})

df["b"] = list(df["a"])

for days in [2,4]:
    labelMA  = "MA" + str(days)

    df[labelMA]   = df["a"].rolling(window =  days, center = False).mean() 
    df["b"] += list(df[labelMA])

但是这(以及我尝试的其他变体)会生成单值b列。

1 个答案:

答案 0 :(得分:2)

使用tolist()将您需要存储在列 b 中的值转换为列表列表,然后直接分配;这应该比在旅途中创建列 b 更有效:

df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8,9]})

for days in [2,4]:
    labelMA  = "MA" + str(days)
    df[labelMA] = df["a"].rolling(window =  days, center = False).mean() 
df['b'] = df.values.tolist()

df
#   a   MA2 MA4               b
#0  1   NaN NaN [1.0, nan, nan]
#1  2   1.5 NaN [2.0, 1.5, nan]
#2  3   2.5 NaN [3.0, 2.5, nan]
#3  4   3.5 2.5 [4.0, 3.5, 2.5]