Python Replace Empty Strings in a List With Values from a Different List

Replace an empty string in a list with NaN

It is working but you are simply running it without assigning the output to any location. Change the line with:

fl[2] = ["nan" if x == '' else x for x in a]

Or maybe:

a = ["nan" if x == '' else x for x in a]

Depending on where you want to store it...

Python replace empty strings in a list with values from a different list

empty_list = [" ", " ", " "]
other_list = iter(["a", "b"])

lst = [x if x != ' ' else next(other_list, x) for x in empty_list]

print(lst)

Output

['a', 'b', ' ']

Replace the empty list to something character such as a

You can try this. -

k = [i if i.values() != [[]] else {i.keys()[0]:"a"} for i in k ]
print(k)

Result -

[{'1': 'man'},
{'8': 'a'},
{'3': 'chester'},
{'5': 'united'},
{'7': 'one'},
{'0': 'man'},
{'2': 'army'},
{'4': 'my'},
{'6': 'random'},
{'9': 'example'},
{'1': 'for'},
{'8': 'a'},
{'3': 'asking'},
{'5': 'in'},
{'7': 'stack'},
{'0': 'over'},
{'2': 'flow'},
{'4': 'expert'},
{'6': 'people'},
{'9': 'yes'}]

Python Flask - How to Convert Empty Strings to None type in list of lists

First use (two) normal for-loops

data = [['a', '', 'c'],['', '', 'f'],['g', 'h', 'i']]

new_data = []

for row in data:
new_row = []
for cell in row:
if cell == '':
cell = None
new_row.append(cell)
new_data.append(new_row)

print(new_data)

Result:

[['a', None, 'c'], [None, None, 'f'], ['g', 'h', 'i']]

And later you can try to convert it to list comprehension.

First step - convert inner for-loop into list comprehension

data = [['a', '', 'c'],['', '', 'f'],['g', 'h', 'i']]

new_data = []

for row in data:
new_row = [None if cell == '' else cell for cell in row]
new_data.append(new_row)

print(new_data)

Second step - convert outer for-loop into list comprehension

data = [['a', '', 'c'],['', '', 'f'],['g', 'h', 'i']]

new_data = [
[None if cell == '' else cell for cell in row]
for row in data
]

print(new_data)

EDIT:

You may also add your i or None but without lambda

data = [['a', '', 'c'],['', '', 'f'],['g', 'h', 'i']]

new_data = [
[cell or None for cell in row]
for row in data
]

print(new_data)

And you can write it in one line

new_data = [ [cell or None for cell in row] for row in data ]

and eventually you can use shorter names

new_data = [ [c or None for c in r] for r in data ]

EDIT:

With numpy.array you could do it simpler arr[ arr == '' ] = None

data = [['a', '', 'c'],['', '', 'f'],['g', 'h', 'i']]

import numpy as np

# convert list to array
arr = np.array(data, dtype=object)

# replace
arr[ arr == '' ] = None

# convert array to list
new_data = arr.tolist()

Something similar you could do with pandas.DataFrame

How to remove the '' (empty string) in the list of list in python?

Try the below

final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
lst = []
for e in final_list:
if any(e):
lst.append([x for x in e if x])
print(lst)

output

[['country'], ['India']]

Remove empty strings from a list of strings

I would use filter:

str_list = filter(None, str_list)
str_list = filter(bool, str_list)
str_list = filter(len, str_list)
str_list = filter(lambda item: item, str_list)

Python 3 returns an iterator from filter, so should be wrapped in a call to list()

str_list = list(filter(None, str_list))

replace empty values with a string pandas

Use ^\s*$ for replace only zero, one or multiple empty strings:

df = df.replace('^\s*$', value, regex=True)
print (df)
A B C
2000-01-01 -0.532681 foo 0
2000-01-02 1.490752 bar 1
2000-01-03 -1.387326 foo 2
2000-01-04 0.814772 baz unkown
2000-01-05 -0.222552 unkown 4
2000-01-06 -1.176781 qux unkown

Replacing various types of empty lists with np.nan

It can be done by screening for all possible empty cases. The code is as follows:

import numpy as np
import pandas as pd

df2 = pd.DataFrame({'column 1':[['97010', '97110', '97140'],[],[''],'[]']})
df2["column 1"] = df2["column 1"].astype(str).replace(["[]", "['']"], np.nan)
df2

The output is:

    column 1
0 ['97010', '97110', '97140']
1 NaN
2 NaN
3 NaN

Explanation:

Basically screen for all possible empty sequences in the replace function's first parameter and the replace them with nans.



Related Topics



Leave a reply



Submit