[Pandas-dev] Problem while deleting blank spaces of a column of a DataFrame
Reto
reto at labrat.space
Tue Apr 5 16:54:55 EDT 2022
On Tue, Apr 05, 2022 at 03:36:45PM -0400, Raul Escobar wrote:
> The .replace() method doesn't work during the process of replacing multiple
> blank spaces of a column while I'm creating an .xlsx file from a DataFrame
> in Pandas. I also tried .str.strip(), it deletes the blank spaces but it
> also deletes all the cells of the column. I also used regex=True into the
> .replace() method but it still doesn't work. Here's the code I'm using:
>
> import pandas as pd
>
> from openpyxl import Workbook
>
> book = Workbook()
>
> operacional_1100 = book.active
>
> maestro = pd.read_excel("2021 Gastos Ortodontik.xlsx", sheet_name="MAESTRO
> TR")
>
> df_ordenar = maestro.iloc[:, [0,1,2,3,4]]
This selects multiple columns
>
> df_ordenar2 = df_ordenar['Monto'].replace(' ', '')
This only selects the "Monto" column and discards the rest.
df_ordenar2 is a pd.Series with the Monto column having replaced spaces
with nothing.
> escrito = pd.ExcelWriter('prueba.xlsx')
> df_ordenar2.to_excel(escrito)
> escrito.save()
This is not needed, simply call to_excel with the filename
In [15]: import pandas as pd
In [16]: ser = pd.Series(['f.o ', 'fuz', ' blah '])
In [17]: replaced = ser.str.replace(' ', '')
In [18]: replaced
Out[18]:
0 f.o
1 fuz
2 blah
dtype: object
In [20]: ser
Out[20]:
0 f.o
1 fuz
2 blah
dtype: object
More information about the Pandas-dev
mailing list