In the following example, pandas.Dataframe.groupby() works the same whether or not the date() method of the timestamp is explicitly called. Why? I expected the explicit call to be required.
import pandas as pd
def return_date_method(timestamp):
return timestamp.date
def call_date_method(timestamp):
return timestamp.date()
df = pd.DataFrame(range(4),
index=pd.date_range('2022', freq='12h', periods=4))
print(f'Using Pandas version {pd.__version__}')
print(df)
print()
print('return_date_method(df.index[0]) returns', return_date_method(df.index[0]))
print('call_date_method(df.index[0]) returns', call_date_method(df.index[0]))
print()
print(df.groupby(return_date_method).groups)
print()
print(df.groupby(call_date_method).groups)
Output:
Using Pandas version 0.25.3
0
2022-01-01 00:00:00 0
2022-01-01 12:00:00 1
2022-01-02 00:00:00 2
2022-01-02 12:00:00 3
return_date_method(df.index[0]) returns <built-in method date of Timestamp object at 0x00000233478574C8>
call_date_method(df.index[0]) returns 2022-01-01
{datetime.date(2022, 1, 1): DatetimeIndex(['2022-01-01 00:00:00', '2022-01-01 12:00:00'], dtype='datetime64[ns]', freq='12H'), datetime.date(2022, 1, 2): DatetimeIndex(['2022-01-02 00:00:00', '2022-01-02 12:00:00'], dtype='datetime64[ns]', freq='12H')}
{datetime.date(2022, 1, 1): DatetimeIndex(['2022-01-01 00:00:00', '2022-01-01 12:00:00'], dtype='datetime64[ns]', freq='12H'), datetime.date(2022, 1, 2): DatetimeIndex(['2022-01-02 00:00:00', '2022-01-02 12:00:00'], dtype='datetime64[ns]', freq='12H')}
This example shows that the behavior is different when using str.isalpha().
def return_isalpha_method(string):
return string.isalpha
def call_isalpha_method(string):
return string.isalpha()
df2 = pd.DataFrame(range(4), index=list('1a2b'))
print(df2)
print()
print(df2.groupby(call_isalpha_method).groups)
print()
try:
print(df2.groupby(return_isalpha_method).groups)
except TypeError as exception:
print('TypeError:', exception)
Output:
0
1 0
a 1
2 2
b 3
{False: Index(['1', '2'], dtype='object'), True: Index(['a', 'b'], dtype='object')}
TypeError: '<' not supported between instances of 'builtin_function_or_method' and 'builtin_function_or_method'