Py学习  »  Python

Python Dataframe从行的每个列表中减去一个值

Mainland • 3 年前 • 1353 次点击  

我有一个数据框架,由列表作为元素组成。我想从每个列表中减去一个值,然后创建一个新列。 我的代码:

df = pd.DataFrame({'A':[[1,2],[4,5,6]]})
df
           A
0     [1, 2]
1  [4, 5, 6]

# lets substract 1 from each list
val = 1
df['A_new'] = df['A'].apply(lambda x:[a-b for a,b in zip(x[0],[val]*len(x[0]))],axis=1)

目前的解决方案:

IndexError: index 3 is out of bounds for axis 0 with size 2

预期解决方案:

df
           A      A_new
0     [1, 2]     [0, 1]
1  [4, 5, 6]  [3, 4, 5]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133405
 
1353 次点击  
文章 [ 4 ]  |  最新文章 3 年前