我需要,当 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
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