0

Here is pandas data frame format of the data source

    cinema       kiwi    restaurant         sushi
0  [2, 2, 2]  [5, 5, 5]     [2, 2, 2]  [14, 14, 14]
1  [2, 2, 2]  [2, 2, 2]     [2, 2, 2]     [2, 2, 2]
2  [1, 1, 1]  [1, 1, 1]  [10, 10, 10]     [1, 1, 1]

I would like to transform it as follow by choosing only the first value of the array

    cinema       kiwi    restaurant         sushi
0  2             5       2                  14
1  2             2       2                  2
2  1             1       10                 1

Is there any function to do that ? I was thinking about using the "apply" method but I am not sure if it the best/most straightforward way.

Thank you by advance for your comments.

1

1 Answer 1

3

The most straight-forward way is to use .applymap:

In [3]: df
Out[3]:
      cinema       kiwi    restaurant         sushi
0  [2, 2, 2]  [5, 5, 5]     [2, 2, 2]  [14, 14, 14]
1  [2, 2, 2]  [2, 2, 2]     [2, 2, 2]     [2, 2, 2]
2  [1, 1, 1]  [1, 1, 1]  [10, 10, 10]     [1, 1, 1]

In [4]: df.applymap(lambda x: x[0])
Out[4]:
   cinema  kiwi  restaurant  sushi
0       2     5           2     14
1       2     2           2      2
2       1     1          10      1
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much ! I had to tweak that a little as I have NaN values. So I am using the following : > df.applymap(lambda x: x[0] if not np.all(pd.isnull(x)) else 0)
@fixme If you need to account for NaNs too, you might use df.apply(lambda x: x.str[0], axis=0) instead.

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.