2016-11-27 4 views
1

Ich habe eine Pandas DataFrame df. Ich möchte (ein Leerzeichen nach ↑) mit + und (ein Leerzeichen nach ↓) mit - ersetzen. Beispiel: df.a[0] (Werte ↑ 0.69%) durch +0.69% ersetzen.Pandas DataFrame Replace() mit Regex

df['last_month'] = df['last_month'].replace(r"↑ ","") ist nicht richtig. Warum?

data = [{"a":"↑ 0.69%","b":"↓ 9.93%"},{"a":"↓ 0.46%","b":"↑ 3.3%"},{"a":"↓ 0.78%","b":"↓ 3.43%"}] 
df = pd.DataFrame(data) 
df 

    a   b 
0 ↑ 0.69% ↓ 9.93% 
1 ↓ 0.46% ↑ 3.3% 
2 ↓ 0.78% ↓ 3.43% 

In meinen Rohdaten, ist ein Unicode, so dass es nicht funktioniert hat. In den Demo-Daten ist ein Str (Bytes), so funktioniert df['last_month'] = df['last_month'].replace(r"↑ ","") tatsächlich wie MaxUs. Aber wie wird ersetzt, wenn DataFrame-Werte Unicode sind?

+0

nicht richtig? kannst du ein [mcve] erstellen? und dies ist keine Regex das ist String Ersetzung. –

+0

könnten Sie einen __reproduzierbaren__ Datensatz hochladen? – MaxU

Antwort

4

IIUC:

In [28]: df.replace(['↑\s*', '↓\s*'], ['+', '-'], regex=True) 
Out[28]: 
     a  b 
0 +0.69% -9.93% 
1 -0.46% +3.3% 
2 -0.78% -3.43% 

Für Python 2x:

In [80]: %paste 
data = [{"a":u"↑ 0.69%","b":u"↓ 9.93%"},{"a":u"↓ 0.46%","b":u"↑ 3.3%"},{"a":u"↓ 0.78%","b":u"↓ 3.43%"}] 
df = pd.DataFrame(data) 
df 
## -- End pasted text -- 
Out[80]: 
     a  b 
0 ↑ 0.69% ↓ 9.93% 
1 ↓ 0.46% ↑ 3.3% 
2 ↓ 0.78% ↓ 3.43% 

In [81]: %paste 
df = df.replace([u'↑\s*', u'↓\s*'], [u'+', u'-'], regex=True) 
print(df) 
## -- End pasted text -- 
     a  b 
0 +0.69% -9.93% 
1 -0.46% +3.3% 
2 -0.78% -3.43% 
+0

'df.replace (['↑ \ s *', '↓ \ s *'], ['+', '-'], regex = Wahr)' funktioniert wenn '↑' ein Byte aber kein Unicode ist? Was, wenn '↑' ein Unicode ist? –

+0

@runningman, verwenden Sie Python 2x oder Python 3x? – MaxU

+0

Ich benutze Python 2.7.12 @ MaxU –

2

Sie können stack dann unstack mit dem str Accessor.

df.stack().str.replace("↑ ","+").str.replace("↓ ", "-").unstack() 

enter image description here

0

Ich habe es, df.replace([u'↑ ', u'↓ '], [u'+', u'-'], regex=True) funktioniert.