[英]Remove trailing .0 from strings of entire DataFrame
嗨,我想刪除整個 DataFrame 字符串末尾的所有“.0”,我需要它完全匹配。
讓我們舉一個例子df:
a b c
20 39.0 17-50
34.0 .016.0 001-6784532
所需的 output:
a b c
20 39 17-50
34 .016 001-6784532
我嘗試使用replace
,但由於某種原因它不起作用(我讀過可能是因為替換只替換整個字符串而不是子字符串?)。 無論哪種方式,如果有一種方法可以工作,我很想知道它,因為它適用於我的 dataframe 但我覺得它不太正確,以防萬一我有像.016.0 這樣的值,因為它也將取代第一個2個字符。
然后我用正則表達式r'\.0$'
嘗試了 sub 和 rtrim ,但我也沒有讓它工作。 我不確定是因為正則表達式還是因為這些方法不適用於整個 dataframe。 同樣使用帶有.0
的 rtrim 也不起作用,因為它也刪除了之前沒有點的零,然后 20 將變為 2。當嘗試使用正則表達式的 sub 和 rtrim 時,我收到一個錯誤,即 dataframe 沒有屬性str
,這是怎么回事可能的?
無論如何都可以在不遍歷所有列的情況下做到這一點?
謝謝!
讓我們試試DataFrame.replace
:
import pandas as pd
df = pd.DataFrame({
'a': ['20', '34.0'],
'b': ['39.0', '.016.0'],
'c': ['17-50', '001-6784532']
})
df = df.replace(r'\.0$', '', regex=True)
print(df)
如果列還不是str
,則可選DataFrame.astype
:
df = df.astype(str).replace(r'\.0$', '', regex=True)
前:
a b c
0 20 39.0 17-50
1 34.0 .016.0 001-6784532
后:
a b c
0 20 39 17-50
1 34 .016 001-6784532
rtrim
/ rstrip
在這里不起作用,因為它們不解析正則表達式,而是獲取要刪除的字符列表。 出於這個原因,他們將刪除所有0
,因為0
在要刪除的“列表”中。
有條件更換; 使用 np.where()。
df['b']=np.where(df['b'].str.contains('\.\d+\.'),df['b'].str.replace(r'\.\d+$','', regex=True), df['b'])
a b c
0 20.0 39.0 17-50
1 34.0 .016 001-6784532
也就是說,我們有.digit(s).
, 最后替換.\digit(s)
For those who are going to export the DataFrame to a CSV (or other types), you can use the parameter float_format from Pandas to eliminate all trailing zeros from the entire DataFrame.
df.to_csv(path_to_file.csv, float_format='%g')
'%g' 等格式解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.