Skip to content

pandas: Gestire le stringhe (sostituzione, strip, conversione di casi, ecc.)

Python

È possibile utilizzare vari metodi con la funzione di accesso stringa (str.xxx()) per gestire (sostituire, rimuovere, ecc.) stringhe di pandas.Series (= una colonna o una riga di pandas.DataFrame).

Ad esempio, sono disponibili i seguenti metodi. Puoi applicare gli stessi metodi per le stringhe Python standard (str) a tutti gli elementi di pandas.Series.

  • Sostituisci ogni stringa in pandas.Series
  • Spoglia ogni stringa in panda.Serie
    • str.striscia()
    • str.lstrip()
    • str.rstrip()
  • Converti il ​​caso di ogni stringa in pandas.Series
    • str.inferiore()
    • str.upper()
    • str.capitalize()
    • str.titolo()

Sostituisci ogni stringa in pandas.Series

str.replace()

import pandas as pd

s = pd.Series([' a-a-x ', ' b-x-b ', ' x-c-c '])
print(s)
# 0     a-a-x 
# 1     b-x-b 
# 2     x-c-c 
# dtype: object

s_new = s.str.replace('x', 'z')
print(s_new)
# 0     a-a-z 
# 1     b-z-b 
# 2     z-c-c 
# dtype: object

Per aggiornare una colonna in pandas.DataFrame, assegna la nuova colonna alla colonna originale. Lo stesso vale per altri metodi.

df = pd.DataFrame([[' a-a-x-1 ', ' a-a-x-2 '],
                   [' b-x-b-1 ', ' b-x-b-2 '],
                   [' x-c-c-1 ', ' x-c-c-2 ']],
                  columns=['col1', 'col2'])
print(df)
#         col1       col2
# 0   a-a-x-1    a-a-x-2 
# 1   b-x-b-1    b-x-b-2 
# 2   x-c-c-1    x-c-c-2 

df['col1'] = df['col1'].str.replace('x', 'z')
print(df)
#         col1       col2
# 0   a-a-z-1    a-a-x-2 
# 1   b-z-b-1    b-x-b-2 
# 2   z-c-c-1    x-c-c-2 

Se si desidera non sostituire una sottostringa ma l’elemento stesso, utilizzare il metodo replace() di pandas.DataFrame o pandas.Series.

Spoglia ogni stringa in panda.Serie

str.striscia()

Per impostazione predefinita, gli spazi vuoti alle estremità sinistra e destra (= spazi vuoti iniziali e finali) vengono rimossi.

s_new = s.str.strip()
print(s_new)
# 0    a-a-x
# 1    b-x-b
# 2    x-c-c
# dtype: object

È possibile specificare i caratteri da rimuovere. I caratteri nella stringa specificata vengono rimossi. Lo stesso vale per str.lstrip() e str.rstrip().

s_new = s.str.strip(' x')
print(s_new)
# 0     a-a-
# 1    b-x-b
# 2     -c-c
# dtype: object

Per panda.DataFrame:

df['col1'] = df['col1'].str.strip()
print(df)
#       col1       col2
# 0  a-a-z-1   a-a-x-2 
# 1  b-z-b-1   b-x-b-2 
# 2  z-c-c-1   x-c-c-2 

str.lstrip()

str.lstrip() rimuove solo i caratteri sul lato sinistro.

s_new = s.str.lstrip()
print(s_new)
# 0    a-a-x 
# 1    b-x-b 
# 2    x-c-c 
# dtype: object

str.rstrip()

str.rstrip() rimuove solo i caratteri sul lato destro.

s_new = s.str.rstrip()
print(s_new)
# 0     a-a-x
# 1     b-x-b
# 2     x-c-c
# dtype: object

Converti il ​​caso di ogni stringa in pandas.Series

Il seguente pandas.DataFrame viene utilizzato come esempio.

s = pd.Series(['Hello World', 'hello world', 'HELLO WORLD'])
print(s)
# 0    Hello World
# 1    hello world
# 2    HELLO WORLD
# dtype: object

str.inferiore()

s_new = s.str.lower()
print(s_new)
# 0    hello world
# 1    hello world
# 2    hello world
# dtype: object

str.upper()

s_new = s.str.upper()
print(s_new)
# 0    HELLO WORLD
# 1    HELLO WORLD
# 2    HELLO WORLD
# dtype: object

str.capitalize()

s_new = s.str.capitalize()
print(s_new)
# 0    Hello world
# 1    Hello world
# 2    Hello world
# dtype: object

str.titolo()

s_new = s.str.title()
print(s_new)
# 0    Hello World
# 1    Hello World
# 2    Hello World
# dtype: object