gpt4 book ai didi

python - 合并列名在列表中的 Pandas 列中的列表

转载 作者:太空宇宙 更新时间:2023-11-04 07:56:13 24 4
gpt4 key购买 nike

我有三个 Pandas 列,其中元素是 list。为了组合这些列表,我可以通过显式写列的名称和 + 将它们放在一起

df = pd.DataFrame({'allmz':([[1,2,3],[2,4,5],[2,5,5],[2,3,5],[1,4,5]]),'allint':([[11,31,31],[21,41,51],[41,51,51],[11,31,51],[1,51,11]]), 'allx':([[6,7,3],[2,4,5],[2,5,5],[2,9,5],[3,4,5]])})
df['new'] = df['allmz'] + df['allint'] + df['allint']
print df

allint allmz allx new
0 [11, 31, 31] [1, 2, 3] [6, 7, 3] [1, 2, 3, 11, 31, 31, 11, 31, 31]
1 [21, 41, 51] [2, 4, 5] [2, 4, 5] [2, 4, 5, 21, 41, 51, 21, 41, 51]
2 [41, 51, 51] [2, 5, 5] [2, 5, 5] [2, 5, 5, 41, 51, 51, 41, 51, 51]
3 [11, 31, 51] [2, 3, 5] [2, 9, 5] [2, 3, 5, 11, 31, 51, 11, 31, 51]
4 [1, 51, 11] [1, 4, 5] [3, 4, 5] [1, 4, 5, 1, 51, 11, 1, 51, 11]

但是,如果我有太多的列名来写每个列名,有没有办法通过循环(或不循环)列名列表来做到这一点:columns = ['allmz','allint','allx'] 代替?

最佳答案

选项 1
在列上切片并沿第一个轴调用 sum

df['new'] = df[['allmz','allint','allx']].sum(axis=1)

df
allint allmz allx new
0 [11, 31, 31] [1, 2, 3] [6, 7, 3] [1, 2, 3, 11, 31, 31, 6, 7, 3]
1 [21, 41, 51] [2, 4, 5] [2, 4, 5] [2, 4, 5, 21, 41, 51, 2, 4, 5]
2 [41, 51, 51] [2, 5, 5] [2, 5, 5] [2, 5, 5, 41, 51, 51, 2, 5, 5]
3 [11, 31, 51] [2, 3, 5] [2, 9, 5] [2, 3, 5, 11, 31, 51, 2, 9, 5]
4 [1, 51, 11] [1, 4, 5] [3, 4, 5] [1, 4, 5, 1, 51, 11, 3, 4, 5]

选项 2
np.concatenate 的另一种选择:

v = df[['allmz','allint','allx']].values.tolist()
df['new'] = np.concatenate(v, axis=0).reshape(len(df), -1).tolist()

df

allint allmz allx new
0 [11, 31, 31] [1, 2, 3] [6, 7, 3] [1, 2, 3, 11, 31, 31, 6, 7, 3]
1 [21, 41, 51] [2, 4, 5] [2, 4, 5] [2, 4, 5, 21, 41, 51, 2, 4, 5]
2 [41, 51, 51] [2, 5, 5] [2, 5, 5] [2, 5, 5, 41, 51, 51, 2, 5, 5]
3 [11, 31, 51] [2, 3, 5] [2, 9, 5] [2, 3, 5, 11, 31, 51, 2, 9, 5]
4 [1, 51, 11] [1, 4, 5] [3, 4, 5] [1, 4, 5, 1, 51, 11, 3, 4, 5]

关于python - 合并列名在列表中的 Pandas 列中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48366076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com