在附加到现有df的pandas中,没有更改df的id?

时间:2018-03-14 07:11:34

标签: python python-2.7 pandas dataframe

我有一个数据框df1,其中包含一些文本和数字作为列。 我用数据创建了新行,并使用pandas附加到df1,如下所示。结果df的id正在改变。 有没有办法主df1的id没有改变,并附加到现有的df,而不改变df的id?

我的代码是:

import cStringIO as io
import pandas as pd

def test():
    text_data = """bcd  11  
    abc  12  
    def  13
    ghi  14"""

    df = pd.read_csv(io.StringIO(text_data), header=None, sep="\s+", names=["txt", "num"])
    df2 = pd.DataFrame([["pqr", 1]], columns=["txt", "num"])
    print "id is =",id(df), "\n" ,df
    df = pd.concat([df, df2])
    print "id is =", id(df), "\n", df

if __name__ == '__main__':
    test()

1 个答案:

答案 0 :(得分:1)

如果仅追加一行并使用setting with enlargement,则可以使用concatappend获取新的DataFrame对象(不同id s) :

from pandas.compat import StringIO

def test():
    text_data = """bcd  11  
    abc  12  
    def  13
    ghi  14"""

    df = pd.read_csv(StringIO(text_data), header=None, sep="\s+", names=["txt", "num"])
    df2 = pd.DataFrame([["pqr", 1]], columns=["txt", "num"])
    print ("id is =",id(df), "\n" ,df)
    df.loc[len(df.index)] = df2.iloc[0]
    print ("id is =", id(df), "\n", df)

test()

id is = 243587168 
    txt  num
0  bcd   11
1  abc   12
2  def   13
3  ghi   14
id is = 243587168 
    txt  num
0  bcd   11
1  abc   12
2  def   13
3  ghi   14
4  pqr    1