代码之家  ›  专栏  ›  技术社区  ›  proximacentauri

将具有一列的数据附加到现有数据帧

  •  1
  • proximacentauri  · 技术社区  · 6 年前

    我想在数据框中添加一个数据列表,这样列表就会出现在列中,例如:

    #Existing dataframe:
    [A, 20150901, 20150902
     1  4  5
     4  2  7]
    
    #list of data to append to column A:
    data = [8,9,4]
    
    #Required dataframe
    [A, 20150901, 20150902
     1  4  5
     4  2  7
     8, 0  0
     9  0  0
     4  0  0]
    

    df_new = df.copy(deep=True)
    #I am copying and deleting data as column names are type Timestamp and easier to reuse them
    df_new.drop(df_new.index, inplace=True)
    for item in data_list:
        df_new = df_new.append([{'A':item}], ignore_index=True)
    df_new.fillna(0, inplace=True) 
    df = pd.concat([df, df_new],  axis=0, ignore_index=True)   
    

    但是在一个循环中这样做是低效的,而且我得到一个警告:

    Passing list-likes to .loc or [] with any missing label will raise
    KeyError in the future, you can use .reindex() as an alternative.
    

    3 回复  |  直到 6 年前
        1
  •  4
  •   jezrael    6 年前

    我想我们需要 concat 带列的新数据帧 A ,那么 reindex 如果希望列的顺序相同,最后用替换缺少的值 fillna :

    data = [8,9,4]
    df_new = pd.DataFrame({'A':data})
    
    df = (pd.concat([df, df_new], ignore_index=True)
            .reindex(columns=df.columns)
            .fillna(0, downcast='infer'))
    print (df)
       A  20150901  20150902
    0  1         4         5
    1  4         2         7
    2  8         0         0
    3  9         0         0
    4  4         0         0
    
        2
  •  0
  •   Chandu    6 年前

    df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
    df2 = pd.DataFrame({'A':[8,9,4]})
    df.append(df2).fillna(0)
    
        A    B
    0   1   2.0
    1   3   4.0
    0   8   0.0
    1   9   0.0
    2   4   0.0
    
        3
  •  0
  •   FdMon    6 年前

    也许你可以这样做:

    new = pd.DataFrame(np.zeros((3, 3))) #Create a new zero dataframe:
    new[0]=[8,9,4] #add values
    existed_dataframe.append(new) #and merge both dataframes