Python将列表追加到数据框列

时间:2020-11-08 01:41:41

标签: python pandas dataframe

我有一个stata文件中的数据框,我想向其中添加一个新列,该列具有一个数字列表作为每一行的条目。一个人怎么能做到这一点?我一直在尝试分配,但是它抱怨索引大小。

我尝试启动一个新的字符串列(也尝试了整数),并尝试了类似的方法,但是没有用。

testdf['new_col'] = '0'
testdf['new_col'] = testdf['new_col'].map(lambda x : list(range(100)))

enter image description here

这是一个类似于我的玩具示例:

data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd'], 'start_val': [1,7,9,10], 'end_val' : [3,11, 12,15]}
testdf = pd.DataFrame.from_dict(data)

enter image description here

这就是我想要的:

data2 = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd'], 'start_val': [1,7,9,10], 'end_val' : [3,11, 12,15], 'list' : [[1,2,3],[7,8,9,10,11],[9,10,11,12],[10,11,12,13,14,15]]}
testdf2 = pd.DataFrame.from_dict(data2)

enter image description here

我的最终目标是在该“列表”列上使用explode来适当地复制行。

2 个答案:

答案 0 :(得分:2)

尝试以下代码:

testdf['list'] = pd.Series(np.arange(i, j) for i, j in zip(testdf['start_val'], 
                                                            testdf['end_val']+1))
testdf

输出:

   col_1 col_2  start_val  end_val                      list
0      3     a          1        3                 [1, 2, 3]
1      2     b          7       11         [7, 8, 9, 10, 11]
2      1     c          9       12           [9, 10, 11, 12]
3      0     d         10       15  [10, 11, 12, 13, 14, 15]

让我们对pd.Series构造函数和np.arange使用zip和zip来创建列表。

答案 1 :(得分:1)

如果您坚持使用Apply功能:

import pandas as pd
import numpy as np

data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd'], 'start_val': [1,7,9,10], 'end_val' : [3,11, 12,15]}

df = pd.DataFrame.from_dict(data)
df['range'] = df.apply(lambda row: np.arange(row['start_val'], row['end_val']+1), axis=1)

print(df)

输出:

   col_1 col_2  start_val  end_val                     range
0      3     a          1        3                 [1, 2, 3]
1      2     b          7       11         [7, 8, 9, 10, 11]
2      1     c          9       12           [9, 10, 11, 12]
3      0     d         10       15  [10, 11, 12, 13, 14, 15]