0

I have a data frame with a column message, and I want to create a column media such that if for index x, df.ix[x][message]=="<Media omitted>" ,then I want df.ix[x][media] = 1

for example for the dataframe:

index    message
1        hello
2        <Media omitted>
3        hello
4        <Media omitted>

I would get:

index    message          media
1        hello             0
2        <Media omitted>   1
3        hello             0
4        <Media omitted>   1

I tried to do so only by using a loop, but I'm sure there is a smarter and faster way.

2 Answers 2

1

Try this:

df['media'] = (df['message'] == '<Media omitted>').astype(int)

Explanation

  • df['message'] == '<Media omitted>' creates a Boolean series.
  • astype(int) casts the Boolean series as integer type for display purposes.
Sign up to request clarification or add additional context in comments.

2 Comments

If I want to the same for 2 different string values? like for '<Media omitted>' and thisstringtoo ? I tried with an or operator, but it didn't work.
Try using isin: df['media'] = (df['message'].isin({'<Media omitted>', 'thisstringtoo'}).astype(int)
1

I think you need convert boolean mask to int by astype:

df['media'] = (df['message'] == '<Media omitted>').astype(int)
#very similar alternative
#df['media'] = df['message'].eq('<Media omitted>').astype(int)
print (df)
               message  media
index                        
1                hello      0
2      <Media omitted>      1
3                hello      0
4      <Media omitted>      1

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.