你能解釋一下嗎?
空格處理不當(測驗 C 和 E),我不明白出了什么問題。
非常感謝。
foo={'testing':['this is test A',' this is test B',' this is test C ',' this is test D',' this is test E ']}
foo=pd.DataFrame(foo,columns=['testing'])
print("Before:")
print(foo,"\n")
foo.replace(r'\s ', ' ', regex=True,inplace=True)
print("After:")
print(foo)
Before:
testing
0 this is test A
1 this is test B
2 this is test C
3 this is test D
4 this is test E
After:
testing
0 this is test A
1 this is test B
2 this is test C
3 this is test D
4 this is test E
uj5u.com熱心網友回復:
在構造資料框之前處理字典可能更容易。您還需要考慮任何字串中的前導空格。
import pandas as pd
import re
foo={'testing':['this is test A',' this is test B',' this is test C ',' this is test D',' this is test E ']}
foo['testing'] = [re.sub('\s ', ' ', s.strip()) for s in foo['testing']]
foo = pd.DataFrame(foo, columns=['testing'])
print(foo)
輸出:
testing
0 this is test A
1 this is test B
2 this is test C
3 this is test D
4 this is test E
uj5u.com熱心網友回復:
# remove leading and trailing space first; then use regex to replace space inside the strings
foo['testing'] = foo['testing'].str.strip().str.replace(r'\s ', ' ', regex=True)
print(foo)
testing
0 this is test A
1 this is test B
2 this is test C
3 this is test D
4 this is test E
uj5u.com熱心網友回復:
你可以在沒有正則運算式的情況下做到這一點:
foo["testing"] = foo["testing"].str.split().str.join(" ")
print(foo)
印刷:
testing
0 this is test A
1 this is test B
2 this is test C
3 this is test D
4 this is test E
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479782.html
