2

I want to split a DataFrame based on if a row contains a certain string "Customer" and all subsequent rows until another row that contains "Customer", i.e.

c_name       |   cost   | p_date
Customer: xx |          | 
hat          |    12    |   1/1/2018
bat          |    13    |   2/3/2018
Customer: xy |          |
mat          |    14    |   1/2/2018

to DF1

c_name       |   cost   | p_date
Customer: xx |          | 
hat          |    12    |   1/1/2018
bat          |    13    |   2/3/2018

DF2

c_name       |   cost   | p_date
Customer: xy |          |
mat          |    14    |   1/2/2018

I know I can get where to split the DataFrame based on df.c_name.str.contains('Customer'), but how do I use that to split the DataFrame?

0

1 Answer 1

5

str.contains + groupby

m = df.c_name.str.contains('Customer').cumsum()
d = {f'df{i}': g for i, g in df.groupby(m)}

for k, v in d.items():
    print(k)
    print(v, end='\n\n')

df1
         c_name  cost    p_date
0  Customer: xx   NaN       NaN
1           hat  12.0  1/1/2018
2           bat  13.0  2/3/2018

df2
         c_name  cost    p_date
3  Customer: xy   NaN       NaN
4           mat  14.0  1/2/2018

To access the individual DataFrames, simply use d['df1'], etc...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.