20171020-1430 - 20171020-1500: 30 minutes
Here we handle the case of applying a custom filter on the rows of a Pandas DataFrame, even when the DataFrame is empty.
import numpy as np
import pandas as pd
t = pd.DataFrame(np.random.rand(5, 2), columns=['x', 'y'])
t
# Apply custom filter
def filter_row(row):
return row['x'] > 0.5
t[t.apply(filter_row, axis=1)]
Note that the above will raise an exception if the DataFrame is originally empty. You can handle the empty DataFrame by calling DataFrame.apply
with reduce=True
.
# Apply custom filter even when original DataFrame is empty
import pandas as pd
def filter_row(row):
return row['x'] > 1
t = pd.DataFrame(columns=['x', 'y'])
t = t[t.apply(filter_row, axis=1, reduce=True)]
print(t)