簡體   English   中英

有沒有辦法替換熊貓數據框中的所有子字符串?

[英]Is there a way to replace all substrings in a pandas dataframe?

我正在嘗試從我的數據[xReturn]清除[xReturn]所有實例並將其替換為空格( )。 但是,當我嘗試下面的代碼時,它只會刪除[xReturn]的值,而不會刪除其他值。 例如"abcde[xReturn]fghij"保持不變,而"[xReturn]"變成 . 我試過設置regex=True但這也不起作用。 它刪除[xReturn]中任何字符的任何實例。 我希望"abcde[xReturn]fghij"變成"abcdefghij" 有沒有辦法使用df.replace()做到這一點?

我的代碼:

df = df.replace('[xReturn]', ' ')

您可以使用:

df['column_name'] = df['column_name'].str.replace('[xReturn]', ' ', regex=False)

str允許您使用矢量化字符串函數,因為您想對字符串內容執行replace()操作,而不是對數據幀本身。

編輯如果要對所有str列執行操作,您可以執行以下操作:

for c in df.select_dtypes(include='object').columns:
    df[c] = df[c].str.replace('[xReturn]', ' ', regex=False)

嘗試:

df = df.astype(str).replace("\[xReturn\]", "", regex=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM