Pandas 列表列,为每个列表附加一个新列
Posted
技术标签:
【中文标题】Pandas 列表列,为每个列表附加一个新列【英文标题】:Pandas column of lists, append a new column to each list 【发布时间】:2021-04-10 18:12:24 【问题描述】:例如,我得到了一个 pd.Series 列表,如下所示
test = pd.Series([[1, 0, 0, 0],[0, 1, 0, 0],[0, 1, 0, 0],[0, 0, 0, 1],[1, 0, 0, 0]])
print(test)
0 [1, 0, 0, 0]
1 [0, 1, 0, 0]
2 [0, 1, 0, 0]
3 [0, 0, 0, 1]
4 [1, 0, 0, 0]
我想要做的是,我想将每个元素的(索引 + 1)添加到每个列表中,比如
0 [1, 0, 0, 0, 1]
1 [0, 1, 0, 0, 2]
2 [0, 1, 0, 0, 3]
3 [0, 0, 0, 1, 4]
4 [1, 0, 0, 0, 5]
我怎样才能做到这一点?
【问题讨论】:
【参考方案1】:test = pd.Series([[1, 0, 0, 0],[0, 1, 0, 0],[0, 1, 0, 0],
[0, 0, 0, 1],[1, 0, 0, 0]])
b=0
for a in test:
b+=1
a.append(b)
print(test)
会给
0 [1, 0, 0, 0, 1]
1 [0, 1, 0, 0, 2]
2 [0, 1, 0, 0, 3]
3 [0, 0, 0, 1, 4]
4 [1, 0, 0, 0, 5]
【讨论】:
【参考方案2】:您可以尝试将此pd.Series
与list
理解一起使用:
import pandas as pd
test = pd.Series([[1, 0, 0, 0],[0, 1, 0, 0],[0, 1, 0, 0],[0, 0, 0, 1],[1, 0, 0, 0]])
print(test + pd.Series([[i + 1] for i in test.index]))
输出:
0 [1, 0, 0, 0, 1]
1 [0, 1, 0, 0, 2]
2 [0, 1, 0, 0, 3]
3 [0, 0, 0, 1, 4]
4 [1, 0, 0, 0, 5]
dtype: object
【讨论】:
我已经投票了,但似乎当我运行“pd.Series([[i + 1] for i in test.index])”时,它返回错误“TypeError: 'builtin_function_or_method '对象不可迭代" @NicolasH 试试:print(test + pd.Series([[i + 1] for i in test.index()]))
【参考方案3】:
np.column_stack
将索引堆叠到现有列表分配回原地测试:
test[:] = np.column_stack([test.tolist(), test.index + 1]).tolist()
test
0 [1, 0, 0, 0, 1]
1 [0, 1, 0, 0, 2]
2 [0, 1, 0, 0, 3]
3 [0, 0, 0, 1, 4]
4 [1, 0, 0, 0, 5]
dtype: object
在这里,Series 被转换为列表列表,然后与 (index + 1) 连接。分配回来时,您需要使用列表列表,因为如果您要分配 numpy 数组,pandas 不明白您想要一列列表。
Series.map
和 itertools.count
另一种选择,使用 itertools 玩得开心:
from itertools import count
c = count(1)
test.map(lambda l: [*l, next(c)])
0 [1, 0, 0, 0, 1]
1 [0, 1, 0, 0, 2]
2 [0, 1, 0, 0, 3]
3 [0, 0, 0, 1, 4]
4 [1, 0, 0, 0, 5]
dtype: object
【讨论】:
以上是关于Pandas 列表列,为每个列表附加一个新列的主要内容,如果未能解决你的问题,请参考以下文章