[英]Subtract each row of specific column from dataframe and add to the list -python
I'm trying to subtract each ow of column A from DataFrame aa and add those to the list.我正在尝试从 DataFrame aa 中减去 A 列的每一行并将它们添加到列表中。
a = pd.DataFrame(np.random.randint(1,10,(5,4)),columns=['A','B','C','D'])
list=[]
a = pd.DataFrame(np.random.randint(1,10,(5,4)),columns=['A','B','C','D'])
list=[]
I am so sorry for this such a basic question but I can't find the solution.对于这样一个基本问题,我感到很抱歉,但我找不到解决方案。
Edit: Just realized you only wanted to extract a column from a DataFrame
as a list.编辑:刚刚意识到您只想从DataFrame
提取一列作为列表。 In that case, like @arkhadiusz commented, you can just use:在这种情况下,就像@arkhadiusz 评论的那样,您可以使用:
a.A.to_list()
Note that this won't remove the column from your DataFrame
.请注意,这不会从您的DataFrame
删除该列。 If you'd like to completely remove it from your DataFrame
, you can use:如果您想从DataFrame
完全删除它,您可以使用:
a.pop('A').to_list()
Assuming you want to subtract a constant value from each element in a column of your DataFrame
, you can try something like this:假设您想从DataFrame
列中的每个元素中减去一个常量值,您可以尝试以下操作:
x = 0.5 # some constant value you want to subtract
[val1 - val2 for val1, val2 in zip(a.A.to_list(), [x] * a.shape[0])]
Or if you want to subtract different values for each element, you can try:或者,如果您想为每个元素减去不同的值,您可以尝试:
x = [1, 2, 3, 4, 5]
[val1 - val2 for val1, val2 in zip(a.A.to_list(), x)]
If I understand correctly, you want this:如果我理解正确,你想要这个:
To get a numpy array:要获得一个 numpy 数组:
lst = a[["B","C","D"]].subtract(a["A"], axis=0).values
To get a 2d list:要获得二维列表:
lst = a[["B","C","D"]].subtract(a["A"], axis=0).values.T.tolist()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.