Reputation: 458
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']
Upvotes: 1
Views: 127
Reputation: 2479
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.
Upvotes: 2
Reputation: 61
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)
Upvotes: 2
Reputation: 862396
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 []
Upvotes: 2
Reputation: 670
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 []
Upvotes: 1
Reputation: 150725
If you want to replace only ' '
try:
df.loc[df['X']=='', 'X'] = 0
Upvotes: 1