How to set to the column list with the number of elements equal to the number of elements in the list on another column Here is the df
t1 t2
[1,2] NaN
[1] NaN
[1,2,3]NaN
I want to get
t1 t2
[1,2] [0,0]
[1] [0]
[1,2,3][0,0,0]
Here is my code
df_1['t2'][df_1['t2'].isnull() & df_1['t1'].notnull()] = [0 for i in df_1['t1']]
But it somehow doesn't return lists, only integer number
CodePudding user response:
You can do it like this:
df['t2'] = df['t1'].apply(lambda x: [0]*len(x))
t1 t2
0 [1, 2] [0, 0]
1 [1] [0]
2 [1, 2, 3] [0, 0, 0]
CodePudding user response:
Assign mask to variable for each side of assignement and then use apply
for replace values of lists (with mask for replace NaN if non NaN in t1
):
import ast
#if possible strings repr of lists
#df_1['t1'] = df_1['t1'].apply(ast.literal_eval)
mask = df_1['t2'].isnull() & df_1['t1'].notnull()
df_1.loc[mask, 't2'] = df_1.loc[mask, 't1'].apply(lambda x: [0 for _ in x])
print (df_1)
t1 t2
0 [1, 2] [0, 0]
1 [1] [0]
2 [1, 2, 3] [0, 0, 0]
Alternative with np.repeat
:
mask = df_1['t2'].isnull() & df_1['t1'].notnull()
df_1.loc[mask, 't2'] = df_1.loc[mask, 't1'].apply(lambda x: np.repeat(0, len(x)))
print (df_1)
t1 t2
0 [1, 2] [0, 0]
1 [1] [0]
2 [1, 2, 3] [0, 0, 0]
CodePudding user response:
Or: (this works on 2d array)
>>> df['t2'] = df['t1'].apply(lambda x : np.where(x != 0, 0, x))
>>> df
t1 t2
0 [[1, 2], [3, 4]] [[0, 0], [0, 0]]
1 [1] [0]
2 [1, 2, 3] [0, 0, 0]