简体   繁体   中英

Replacing blank elements in list of pandas dataframe

Question edited for clarity:

I have a column in a pandas dataframe where each element is a list

Index      X
  1     ['1','2','3']
  2     ['4','5','6']
  3     ['']

I want it to look like the following:

Index      X
  1     ['1','2','3']
  2     ['4','5','6']
  3     ['0']

not an answer but:

in your df, I have a hard time to df.iat[0, 0]=[''] or df.iat[0, 0]=[] pandas really discourages you from using a list inside a df cell.

Use nested list comprehension for replace '' in lists to 0 :

df = pd.DataFrame({'X':[[''], ['a',''], []]})

df['X'] = [[0 if y =='' else y for y in x] for x in df['X']]
print (df)
        X
0     [0]
1  [a, 0]
2      []

Assuming your column is object type, something like this should work:

# Example of dataframe
df = pd.DataFrame({'col_1': [1,2,3], 'col_2' : [[1,2,3,4],[''],['']]})
col_1   col_2
0   1   [1, 2, 3, 4]
1   2   []
2   3   []

Using pandas.apply should do the trick for you

df["col_2"].apply(lambda x : ['0'] if x==[''] else x)

如果您只想替换' '尝试:

df.loc[df['X']=='', 'X'] = 0

You can use this peace of code:

df = pd.DataFrame({"X":[["a"], ["b"], [""], []]})
df.head()

    X
0   [a]
1   [b]
2   []
3   []

def replace_empty(X):
    for n, i in enumerate(X):
        if i == '':
            X[n] = 0
    return X

df.X = df.X.apply(lambda x: replace_empty(x))
df.head()

    X
0   [a]
1   [b]
2   [0]
3   []

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