Reputation: 29
I have one data frame containing two entirely different data sets. The data sets are separated by two rows of all NAN values.
I have provided a sample of the data frame below.
+----+--------------------------------+-------------+-----+-----+-----+-----+-----+-----+------------+-----+--------+-----+
| 13 | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | Total Fees | NaN | 653 | NaN |
+----+--------------------------------+-------------+-----+-----+-----+-----+-----+-----+------------+-----+--------+-----+
| 14 | Expenses\nDate Description ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
+----+--------------------------------+-------------+-----+-----+-----+-----+-----+-----+------------+-----+--------+-----+
| 15 | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
+----+--------------------------------+-------------+-----+-----+-----+-----+-----+-----+------------+-----+--------+-----+
| 16 | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
+----+--------------------------------+-------------+-----+-----+-----+-----+-----+-----+------------+-----+--------+-----+
| 17 | Date | Description | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | Amount | NaN |
+----+--------------------------------+-------------+-----+-----+-----+-----+-----+-----+------------+-----+--------+-----+
Row 14 is the last row of the first data set, and row 17 is the first row of the second data set.
I would like to end up with two data frames where the first ends at row 14 above and the second starts at row 17 above.
I have tried to split them like this:
key = df.isnull().all(1)
dftopdata = df[:key]
dfbottomdata = df[key:]
When I run the code, I get an error saying, "cannot do slice indexing on class 'pandas.core.indexes.range.RangeIndex' with these indexers"
Upvotes: 0
Views: 89
Reputation: 10960
Capture all dataframes by NaN
rows split
is_row_nan = df.isnull().all(1)
is_two_row_nan = (is_row_nan & is_row_nan.shift(1))
dfs = [g for _, g in df.groupby(is_two_row_nan.cumsum())]
Sample input
df = pd.DataFrame(np.random.choice((1, np.nan), (10, 2)))
0 1
0 1.0 NaN
1 NaN 1.0
2 NaN NaN
3 NaN NaN
4 1.0 NaN
5 NaN NaN
6 NaN 1.0
7 1.0 NaN
8 1.0 1.0
9 NaN 1.0
Output
dfs[0]
0 1
0 1.0 NaN
1 NaN 1.0
2 NaN NaN
dfs[1]
0 1
3 NaN NaN
4 1.0 NaN
5 NaN NaN
6 NaN 1.0
7 1.0 NaN
8 1.0 1.0
9 NaN 1.0
Upvotes: 2