【问题标题】:How to add data to pandas.DataFrame without recreating the instance如何在不重新创建实例的情况下将数据添加到 pandas.DataFrame
【发布时间】:2019-10-07 23:01:56
【问题描述】:

我正在尝试为 pandas 开发自定义数据框访问器,但遇到了我不知道如何解决的问题。

我的访问器应该从自定义源加载数据,我打算将这些值分配给调用访问器的DataFrame。但是当我将新创建的数据框分配给数据框实例时,我没有得到任何反应。

我认为这是因为我正在创建数据帧的新实例而不是重用旧实例。

有什么优雅的方法可以保存数据帧实例并在那里加载信息吗?

这是我现在处理的代码:

import pandas
import numpy


@pandas.api.extensions.register_dataframe_accessor("test")
class TestAccessor:
    def __init__(self, obj: pandas.DataFrame) -> None:
        self.data = obj

    def read(self) -> None:
        # Creates dataframe with three columns `X, Y, Z`
        self.data = pandas.DataFrame(numpy.random.randint(0,100,size=(100, 3)), columns=list('XYZ'))


# Creates dataframe with three columns `A, B, C`
data = pandas.DataFrame(numpy.random.randint(0,100,size=(100, 3)), columns=list('ABC'))

# Suppose to load dataframe with columns `X, Y, Z`
data.test.read()

# Will show dataframe with columns `A, B, C`
print (data)

有没有办法解决这个问题?解决这个问题的最佳方法是什么?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    请注意,确定这在实践中是否真的很有意义,但这里有一个解决方案可以在您的示例中实现您想要的:将所有现有列删除并分配新列:

    import pandas
    import numpy
    
    @pandas.api.extensions.register_dataframe_accessor("test")
    class TestAccessor:
        def __init__(self, obj: pandas.DataFrame) -> None:
            self.data = obj
    
        def read(self) -> None:
            # Creates dataframe with three columns `X, Y, Z`
            self.data.drop(columns=self.data.columns, inplace=True)
            new = pandas.DataFrame(numpy.random.randint(0,100,size=(100, 3)), columns=list('XYZ'))
            self.data[new.columns] = new
    
    # Creates dataframe with three columns `A, B, C`
    data = pandas.DataFrame(numpy.random.randint(0,100,size=(100, 3)), columns=list('ABC'))
    
    # Suppose to load dataframe with columns `X, Y, Z`
    data.test.read()
    
    # Now shows dataframe with columns `X, Y, Z`
    print (data)
    

    输出:

         X   Y   Z
    0   30  86  16
    1   33  93  33
    2   43  62  95
    3   24  74   5
    4   52  68  95
    ..  ..  ..  ..
    95  89  54  90
    96  35  78  20
    97  68  11  17
    98  29  68  44
    99  33  73  11
    
    [100 rows x 3 columns]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-15
      • 2018-09-12
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多