如何添加多个熊猫数据框的每个条目。蟒蛇

时间:2020-09-09 23:26:00

标签: python pandas numpy

我正在尝试在数据框中获取一组新值并将其添加到现有值中。但是我想要的加法是1到1。因此,数据框中的第一个条目会添加到第二个数据框中的相应条目,依此类推。如果我使用的是numpy,我可以轻松地做到这一点,但是对于熊猫来说,这非常困难。我还尝试采用这些不同的数据框并计算每个相应条目的中位数。以下是我为numpy做的事情,以了解我在说什么:

import random 
import numpy as np


index = 10
Value_sums = np.zeros(index)

Vals = []

values1 = random.sample(range(100), 10)

values2 = random.sample(range(100), 10)

Value_sums = Value_sums + values1

Value_sums = Value_sums + values2

vals.append(values1)

vals.append(values2)

Out[54]: array([71., 82., 87., 59., 97., 99., 69., 50., 80., 61.])

这部分的预期结果是将每个元素加在一起,并生成另一个相同大小的数组。

vals_stacked = np.stack(vals)

Out[49]: 
[[45, 36, 20, 63, 43, 10, 38, 79, 31, 67],
 [71, 82, 87, 59, 97, 99, 69, 50, 80, 61]]

vals_median = np.nanmedian(vals_stacked, axis = 0)

Out[53]: array([58. , 59. , 53.5, 61. , 70. , 54.5, 53.5, 64.5, 55.5, 64. ])
   

对于中位数,我堆叠了所有不同的数组,并取第一个元素的中位数,然后取第二个元素的中位数,依此类推,以生成另一个相同大小的数组,但条目是中位数。 / p>

我的数据框看起来像这样。

ts[0:10]
Out[51]: 
2011-10-06 03:54:44    45427
2011-10-06 03:55:01    45742
2011-10-06 03:55:15    45844
2011-10-06 03:55:29    45800
2011-10-06 03:55:43    46023
2011-10-06 03:55:56    46484
2011-10-06 03:56:10    46966
2011-10-06 03:56:23    47768
2011-10-06 03:56:37    48286
2011-10-06 03:56:50    48205
dtype: int32

1 个答案:

答案 0 :(得分:0)

没关系。只需将数据帧转换为numpy并执行与我上面相同的操作即可。

import java.io.File;
import java.io.FileNotFoundException;

public class Array {

    public static void main(String[] args) {
        
        int[] arr = new int[10];
        int i = 0;
    
        
    
        Scanner input = new Scanner(System.in);
        
        
        try {
        
        System.out.print("Enter the file name:");
        String fileName = input.next();
        Scanner readFile = new Scanner(new File(fileName));
        while (readFile.hasNext()) {
            try {
                arr[i] = readFile.nextInt();
                i++;
            } catch (InputMismatchException e) {
                readFile.next();
            }
            
        bubbleSort(arr);
        System.out.print("Sorted Array order: " + arr);
            input.close();
                
        }}catch(FileNotFoundException e) {
            System.out.println("Error occured");
            e.printStackTrace();
        }
        
        }

    

static void bubbleSort(int[] arr) {  
    int n = arr.length;  
    int temp = 0;  
     for(int i=0; i < n; i++){  
             for(int j=1; j < (n-i); j++){  
                      if(arr[j-1] > arr[j]){   
                             temp = arr[j-1];  
                             arr[j-1] = arr[j];  
                             arr[j] = temp;  
                     }  
                      
             }  
     }  

}}