Necesito reemplazar los valores específicos en cada fila de pandas df con otro valor. Mis datos se ven así:
time log
1 whats the weather look like today
2 what is the weather look like today
3 whats for lunch
4 what’s for lunch
Necesito reemplazar el whats
ser what is
y what’s
ser what is
también. La salida deseada:
time log
1 what is the weather look like today
2 what is the weather look like today
3 what is for lunch
4 what is for lunch
Yo he tratado:
new_df = df.log.str.replace("^whats", "what is").str.replace("^what’s", "what is")
Esto se solucionó, whats
pero no el otro caso y el resultado no es un pandas df y necesito que sea pandas df.
Lo que está obteniendo es una serie Pandas, si desea obtener un DataFrame, solo use
new_df = pd.DataFrame(df.log.str.replace("^whats", "what is").str.replace("^what’s", "what is"))
Y como señaló @Quang Hoang, puede buscar usando los pandas O y buscar whats
o what’s
:
new_df = pd.DataFrame(df.log.str.replace("^whats|what’s", "what is"))
Código completo:
import pandas as pd
df = pd.DataFrame({"time": [1,2,3,4],
"log": ['whats the weather look like today', 'what is the weather look like today', 'whats for lunch', 'what’s for lunch']
})
new_df = pd.DataFrame(df.log.str.replace("^whats", "what is").str.replace("^what’s", "what is"))
y los resultados son:
print(df)
time log
0 1 whats the weather look like today
1 2 what is the weather look like today
2 3 whats for lunch
3 4 what’s for lunch
print(new_df)
log
0 what is the weather look like today
1 what is the weather look like today
2 what is for lunch
3 what is for lunch
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras