1

I am having a Python Pandas DataFrame like

>>> df
  classification like 
0         flower    1 
1         flower    0 
2         flower    0 
3      adventure    1 
4      adventure    1 

I want to create an output DataFrame like

>>> df
  classification like  liked
0         flower    1  True
1         flower    0  False
2         flower    0  False
3      adventure    1  True
4      adventure    1  True

I am "apply"ing the Python lambda function on the input DataFrame as follows:

>>> df['like'].apply(lambda x: x == 1)

But I am getting all 'False' under the 'liked' column

>>> df
  classification like  liked
0         flower    1  False
1         flower    0  False
2         flower    0  False
3      adventure    1  False
4      adventure    1  False

Any quick suggestions will be helpful.

>>> df['like'].astype(int)
0    1
1    0
2    0
3    1
4    1
Name: like, dtype: int32

@jezrael

>>> df['liked'] = df['like'].astype(bool)
>>> df
  classification like  liked
0         flower    1   True
1         flower    0   True
2         flower    0   True
3      adventure    1   True
4      adventure    1   True

@jezrael : DTypes

>>> df.dtypes
classification    object
like              object
liked               bool
dtype: object
2
  • 1
    try df['like'].astype(int) Commented Jun 29, 2018 at 13:13
  • If you can avoid apply which is a hidden loop as your needs can be vectorized. Commented Jun 29, 2018 at 13:14

1 Answer 1

4

Convert integer column to boolean:

print (type(df.loc[0, 'like']))
<class 'numpy.int64'>

df['liked'] = df['like'].astype(bool)

Or assign comparison with 1:

df['liked'] = df['like'] == 1

If 1 is string compare by string '1':

print (type(df.loc[0, 'like']))
<class 'str'>

df['liked'] = df['like'] == '1'
print (df)
  classification like  liked
0         flower    1   True
1         flower    0  False
2         flower    0  False
3      adventure    1   True
4      adventure    1   True
Sign up to request clarification or add additional context in comments.

4 Comments

When I compared using df['like'] == '1' it is working. But the problem is when I checked the data type for the 'like' column it is showing as int32
Do you check it by print (type(df.loc[0, 'like'])) ?
No I checked by df['like'].astype(int)
Here is possible check it by print (df.dtypes), it return object for string column

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.