2017-05-25 73 views
2

我有一個數據框有很多'?'的實例。在不同的行中。列的數據類型是「對象」。 現在我想要替換所有'?'與0. 我該怎麼做?如何替換數據框中某個字符的所有實例?

+0

與此類似:https://stackoverflow.com/questions/29271549/replace-all-occurrences-of-a -string功能於一個數據幀 –

回答

3

考慮數據幀df

df = pd.DataFrame([['?', 1], [2, '?']]) 

print(df) 

    0 1 
0 ? 1 
1 2 ? 

replace

df.replace('?', 0) 

    0 1 
0 0 1 
1 2 0 

maskwhere

df.mask(df == '?', 0) 
# df.where(df != '?', 0) 

    0 1 
0 0 1 
1 2 0 

但是,想象你的數據框在更長的字符串中有?

df = pd.DataFrame([['a?', 1], [2, '?b']]) 

print(df) 

    0 1 
0 a? 1 
1 2 ?b 

replaceregex=True

df.replace('\?', '0', regex=True) 

    0 1 
0 a0 1 
1 2 0b 
2

我覺得更好的是replacestring0,因爲否則得到的混合類型 - 數字與字符串和一些大熊貓功能可以失敗:

df.replace('?', '0') 

另外如果需要更換多個?一個0添加+用於匹配一個或多個值:

df = pd.DataFrame([['a???', '?'], ['s?', '???b']]) 
print(df) 
     0  1 
0 a???  ? 
1 s? ???b 

df = df.replace('\?+', '0', regex=True) 
print (df) 
    0 1 
0 a0 0 
1 s0 0b 

df = df.replace('[?]+', '0', regex=True) 
print (df) 
    0 1 
0 a0 0 
1 s0 0b 
相關問題