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!
CodePudding user response:
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)
CodePudding user response:
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
CodePudding user response:
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