我已經列名保存在一個列表:如何總結的值在特定列
col_names = ["Col1","Col5",...]
現在我想創建一個新列「總」,併爲每行總結列的值col_names
。
我應該使用循環還是有任何功能,這項工作?
我已經列名保存在一個列表:如何總結的值在特定列
col_names = ["Col1","Col5",...]
現在我想創建一個新列「總」,併爲每行總結列的值col_names
。
我應該使用循環還是有任何功能,這項工作?
可以使用列的列表索引到一個數據幀,然後跨列總結(軸= 1):
>>> df = pd.DataFrame(np.random.randint(0, 10, (5,5)), columns=["Col{}".format(i) for i in range(1,6)])
>>> df
Col1 Col2 Col3 Col4 Col5
0 4 7 3 5 6
1 2 1 3 7 9
2 4 7 8 0 1
3 0 4 1 1 3
4 5 8 1 5 7
>>> col_names = ["Col1", "Col5"]
>>> df[col_names]
Col1 Col5
0 4 6
1 2 9
2 4 1
3 0 3
4 5 7
>>> df["Total"] = df[col_names].sum(axis=1)
>>> df
Col1 Col2 Col3 Col4 Col5 Total
0 4 7 3 5 6 10
1 2 1 3 7 9 11
2 4 7 8 0 1 5
3 0 4 1 1 3 3
4 5 8 1 5 7 12
實施例:
m = [[1,2,3],
[4,5,6],
[7,8,9],
]
new_n = []
for c in m:
new_n.append(c + [sum(c)])
print new_n
輸出:
[[1, 2, 3, 6], [4, 5, 6, 15], [7, 8, 9, 24]]
你想在哪裏做廣告? – inetphantom