【问题标题】:Appending a row to a pandas dataframe将一行附加到熊猫数据框
【发布时间】:2019-10-22 13:57:42
【问题描述】:

我有以下代码:

def randFunc(data,x,y,w,h,n): #(this has problems)
    df = pd.DataFrame({"X":[], 
                         "Y":[]}) 
    for i in range(n):
        for j in range(n):
            data1 = filterbox(data,x,y,w,h,i,j,n)
            if data1.empty:
                data1 = data1.sample()
                print(data1)
                df.append(data1)
            else:
                sus = data1.sample()
                df.append(sus)
    return df
    """gets a list of random points in each subinterval in a list"""

因为 data1 是数据框中的一行,sus 也是如此。但是,由于某种原因,当我附加到 df 时,df 中没有显示新值。为什么会这样,我该如何解决? 谢谢

【问题讨论】:

    标签: python pandas dataframe append rows


    【解决方案1】:

    DataFrame.append 返回一个新的数据框

    import pandas as pd
    
    df = pd.DataFrame([[1,2,3]])
    # you probably want to ignore_index so that you have unique indexes
    df2 = df.append([[4,5,6]],ignore_index=True)
    print("DF is unchanged:")
    print(df)
    
    print("DF2 has the new DataFrame:")
    print(df2)
    
    #this is just a convience wrapper for pandas.concat
    df3 = pd.concat([df2,[[4,4,4]]],ignore_index=True)
    print("DF3")
    print(df3)
    

    【讨论】:

    • 非常感谢,您为我节省了很多时间。
    猜你喜欢
    • 2018-02-08
    • 2017-06-13
    • 2014-01-03
    • 1970-01-01
    • 2019-01-14
    • 2021-12-22
    • 2022-01-06
    • 2023-02-01
    相关资源
    最近更新 更多