简体   繁体   中英

replace empty list with values in another column in pandas dataframe

I am trying to replace list of values in one column with another column, below is data and script I am using

old = [[51, 1], 
          [52, 1], 
          [53, -1], 
          [], 
          [54, 0], 
          [55, 0], 
          [52, 0], 
          [], 
          [52, 0], 
          [54, -1]]

import pandas as pd
df = pd.DataFrame(columns=['old','new'])     
df["old"]=old

new = [[51, 1], 
          [52, 1], 
          [53, -1], 
          [54, -2], 
          [54, 0], 
          [55, 0], 
          [52, 0], 
          [55. -3], 
          [52, 0], 
          [54, -1]]

df["new"]=new

for index, row in df.iterrows():
    if ((df["old"][index])==[]) :
        df.old[index] = df.new[index]

Is there any better way than using for loop , actually in my script there are too many loops so i want to avoid using for loop for few data manipulation If anyone knows that will be great help

You can use Series.mask :

# df['old'] = df['old'].mask(df['old'].str.len() == 0, df['new'])
df['old'].mask(df['old'].str.len() == 0, df['new'])

0     [51, 1]
1     [52, 1]
2    [53, -1]
3    [54, -2]
4     [54, 0]
5     [55, 0]
6     [52, 0]
7      [52.0]
8     [52, 0]
9    [54, -1]
Name: old, dtype: object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM