我有一个数据框df1,其中一些文本和数字作为列。
我用数据创建了新行,并使用pandas将其追加到df1,如下所示。结果df的ID正在更改。
有没有一种方法可以更改主df1的ID,并在不更改df的ID的情况下附加到现有df?

我的代码是:

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()

最佳答案

如果仅追加一行并使用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

关于python - 在追加到现有df的 Pandas 中,没有更改df的id?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49271638/

10-12 18:32