'why numpy place is not replacing empty strings
Hello i have an dataframe as shown below
daf = pd.DataFrame({'A':[10,np.nan,20,np.nan,30]})
daf['B'] = ''
the above code has created a data frame with column B having empty strings
A B
0 10.0
1 NaN
2 20.0
3 NaN
4 30.0
the problem here is i need to replace column with all empty strings,(note here entire column should be empty) with values provided with numpy place last argument here it is 1
so i used following code
np.place(daf.to_numpy(),((daf[['A','B']] == '').all() & (daf[['A','B']] == '')).to_numpy(),[1])
which did nothing it gave same output
A B
0 10.0
1 NaN
2 20.0
3 NaN
4 30.0
but when i assign daf['B'] = np.nan the code seems to work fine by checking if entire column is null, then replace it with 1
here is the data frame
A B
0 10.0 NaN
1 NaN NaN
2 20.0 NaN
3 NaN NaN
4 30.0 NaN
replace where those nan with 1 where the entire column is nan
np.place(daf.to_numpy(),(daf[['A','B']].isnull() & daf[['A','B']].isnull().all()).to_numpy(),[1])
which gave correct output
A B
0 10.0 1.0
1 NaN 1.0
2 20.0 1.0
3 NaN 1.0
4 30.0 1.0
can some one tell me how to work with empty strings replacing , and give a reason why its not working with empty string as input
Solution 1:[1]
If I'm understanding your question correctly, you're wanting to replace a column with empty strings with a column of 1s. This can be done with pandas.replace()
daf.replace('', 1.0)
A B
0 10.0 1.0
1 NaN 1.0
2 20.0 1.0
3 NaN 1.0
4 30.0 1.0
This function also works with regex if you want to be more granular with the replacement.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jon Bown |
