[英]Pandas dataframe: Sum of column values where values are list
There is a sample of dataset.有一个数据集样本。
Here each value of the columns is an integer list.这里列的每个值都是一个整数列表。 The highlighted row is the sum of corresponding column's list.
突出显示的行是相应列列表的总和。 Meaning, the highlighted row of column 'day1' is the sum of all lists in 'Day1' column and so on for the other columns.
意思是,“day1”列的突出显示行是“Day1”列中所有列表的总和,其他列依此类推。 I have tried with sum() with axis but seems like it isnt working for list.
我试过 sum() 和轴,但似乎它不适用于列表。
after getting the sum lists, it has to be assigned in a new dataframe with same number of column.Example in picture below,获得总和列表后,必须在具有相同列数的新数据框中分配它。下图中的示例,
Any hints of algorithm, links, help is appreciated.Thanks.任何算法提示、链接、帮助表示赞赏。谢谢。
You can convert your DataFrame to a NumPy array, like this: df.to_numpy()
您可以将 DataFrame 转换为 NumPy 数组,如下所示:
df.to_numpy()
And after receive something like:在收到类似的东西后:
a = np.random.randint(5, size=(4, 2, 5))
Each block here it is your column:这里的每个块都是您的专栏:
array([[[2, 4, 1, 1, 1],
[4, 0, 1, 4, 0]],
[[1, 2, 4, 4, 3],
[0, 1, 4, 4, 0]],
[[0, 0, 0, 0, 2],
[3, 0, 4, 2, 2]],
[[2, 0, 3, 1, 0],
[1, 1, 3, 3, 1]]])
Then sum it with axis:然后将其与轴相加:
np.sum(a, axis=1)
yields:产量:
array([[6, 4, 2, 5, 1],
[1, 3, 8, 8, 3],
[3, 0, 4, 2, 4],
[3, 1, 6, 4, 1]])
Prepare to create DataFrame准备创建 DataFrame
dd = {f'Day{n}':np.array2string(i, separator=',')
for n,i in enumerate(list(np.sum(ar, axis=1)), start=1)}
Create df
:创建
df
:
df = pd.DataFrame(list(dd.values()), index=dd.keys()).T
yields:产量:
Day1 Day2 Day3 Day4
0 [6,4,2,5,1] [1,3,8,8,3] [3,0,4,2,4] [3,1,6,4,1]
Hope you can get all the sum values by values.tolist() and converting them in to int values as follows.希望您可以通过 values.tolist() 获取所有总和值并将它们转换为 int 值,如下所示。 Tried a sample and it shows the result as in the image.
尝试了一个示例,它显示了图像中的结果。
import pandas as pd
df = pd.read_csv("data.csv")
dl = df.values.tolist()
i = 0
for column in df:
ilist = [sum([int(s) for s in l[i].split(',')]) for l in dl]
i = i+1
print(column, " - ", sum(ilist))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.