如何将 pandas DataFrame 绑定到回调

问题描述 投票:0回答:1

我需要,当 pandas DataFrame 内进行一些更改时,会运行回调。

loc
方法一样改变值。

示例:

df = pd.DataFrame({'example': [0,1,2], 'example2': [3,4,5]})
def callback():
    print('it\'s a callback')
df.bind(callback)
df.loc[len(df)] = {'example3': [6,7,8]}
# it's a callback
python pandas dataframe callback
1个回答
0
投票

import pandas as pd

class CustomDataFrame(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.callback = None
    
    def bind(self, callback):
        self.callback = callback

    def _trigger_callback(self):
        if self.callback is not None:
            self.callback()

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self._trigger_callback()

# Example usage
def callback():
    print("It's a callback")

# Create the CustomDataFrame instance and bind the callback
df = CustomDataFrame({'example': [0, 1, 2], 'example2': [3, 4, 5]})
df.bind(callback)

# Add a new row with the same columns as the DataFrame
new_row = {'example': 6, 'example2': 7}
df = df.append(new_row, ignore_index=True)

df

结果:

   example  example2
0     0       3
1     1       4
2     2       5
3     6       7
© www.soinside.com 2019 - 2024. All rights reserved.