So I wanted to create a module for my own projects and wanted to use methods. For example I wanted to do:
from mymodule import *
df = pd.DataFrame(np.random.randn(4,4))
df.mymethod()
Thing is it seems I can't use .myfunc()
since I think I can only use methods for the classes I've created. A work around is making mymethod
a function and making it use pandas.Dataframes
as a variable:
myfunc(df)
I don't really want to do this, is there anyway to implement the first one?
Thus, the first and foremost method for creating a dataframe is by reading a csv file which is straightforward operation in Pandas. We just need to give the file path to the read_csv function. The read_csv function is highly versatile. It has several parameters that allow for modifying the csv file while reading.
You can create a new DataFrame of a specific column by using DataFrame. assign() method. The assign() method assign new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original ones.
Nice solution can be found in ffn package. What authors do:
from pandas.core.base import PandasObject
def your_fun(df):
...
PandasObject.your_fun = your_fun
After that your manual function "your_fun" becomes a method of pandas.DataFrame object and you can do something like
df.your_fun()
This method will be able to work with both DataFrame and Series objects
This topic is well documented as of Nov 2019: Extending pandas
Note that the most obvious technique - Ivan Mishalkin's monkey patching - was actually removed at some point in the official documentation... probably for good reason.
Monkey patching works fine for small projects, but there is a serious drawback for a large scale project: IDEs like Pycharm can't introspect the patched-in methods. So if one right clicks "Go to declaration", Pycharm simply says "cannot find declaration to go to". It gets old fast if you're an IDE junkie.
I confirmed that Pycharm CAN introspect both the "custom accessors" and "subclassing" methods discussed in the official documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With