0

I have dataframe like this.

 df['category'] 
0    None
1    None
2    None
3    None
Name: category, dtype: object

I want applying the below code and splitting them to 2 columns as level1 and level2

Code

if df['category'] is None:
    riskc = pd.DataFrame(columns=['Level1', 'Level2'])
else:
    riskc=df['category'].str.split(',', expand=True).melt()['value']\
          .str.split(':', expand=True).rename(columns={0:'Level1', 1:'Level2'})

Current Output

riskc

    Level1
0   None
1   None
2   None
3   None

Expected Output

riskc

    Level1      Level2
0   None        None
0   None        None
1   None        None
2   None        None
3   None        None

What is wrong in my code

1 Answer 1

1

To check if df['category'] contains all Nones, you need to use:

if df['category'].isna().all():
    riskc = pd.DataFrame(columns=['Level1', 'Level2'])
Sign up to request clarification or add additional context in comments.

2 Comments

Works, what was the mistake I made
You are comparing df['category'] to None but df['category'](even when all of its elements are None) is a Series and not a None.

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.