1

If I have a pandas dataframe like this

d = {'id': {0: 0, 1: 1, 2: 2.0, 3: 3},
 'lst': {0: [1, 2], 1: [0], 2: [1, 2, 3], 3: np.nan}}
df = pd.DataFrame(d)
print(df)

    id        lst
0  0.0     [1, 2]
1  1.0        [0]
2  2.0  [1, 2, 3]
3  3.0        NaN

How can I add 1 to each element of the lists, Nan will remain to be Nan. So the output should be like this:

    id        lst
0  0.0     [2, 3]
1  1.0        [1]
2  2.0  [2, 3, 4]
3  3.0        NaN

Thanks!

4 Answers 4

2

IIUC, try mapping to numpy array and add 1 else you can use apply and add 1:

df['lst'] = df['lst'].map(np.array).add(1)
Sign up to request clarification or add additional context in comments.

Comments

2

You could use map() with list comprehensions and na_action parameter

df['lst'].map(lambda x: [i+1 for i in x],na_action='ignore')

Output:

0       [2, 3]
1          [1]
2    [2, 3, 4]
3          NaN

Comments

2

Using a classical list comprehension:

df['lst'] = [[x+1 for x in l] if isinstance(l, list) else l
             for l in df['lst']]

Output:

    id        lst
0  0.0     [2, 3]
1  1.0        [1]
2  2.0  [2, 3, 4]
3  3.0        NaN

Comments

2

One option is to convert the nested list column to an AwkwardDtype, and subsequently apply vectorized operations on the column:

# pip install awkward-pandas
import awkward-pandas as akpd

In [61]: df.astype({"lst":akpd.AwkwardDtype()}).assign(lst = lambda f: f.lst + 1)
Out[61]: 
    id        lst
0  0.0     [2, 3]
1  1.0        [1]
2  2.0  [2, 3, 4]
3  3.0        NaN

For this however, you can just use @anky's solution, since there isnt much complexity to the nested list.

1 Comment

You always have nice lib suggestions ;)

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.