2016-07-01 75 views
10

Mi sono avvicinato con valori in parentesi quadra (più simile a list) dopo aver applicato str.findall() alla colonna di un dataframe panda. Come posso rimuovere la parentesi quadra?Come rimuovere la parentesi quadra da pandas dataframe

print df 

id  value     
1  [63]   
2  [65]  
3  [64]   
4  [53]  
5  [13]  
6  [34] 
+2

quali sono i contenuti di quella colonna, è questo una stringa ''[63]'' o una lista '[63]'? – EdChum

risposta

14

Se valori nella colonna value hanno tipo list, uso:

df['value'] = df['value'].str[0] 

Oppure:

df['value'] = df['value'].str.get(0) 

Docs.

Esempio:

df = pd.DataFrame({'value':[[63],[65],[64]]}) 
print (df) 
    value 
0 [63] 
1 [65] 
2 [64] 

#check type if index 0 exist 
print (type(df.loc[0, 'value'])) 
<class 'list'> 

#check type generally, index can be `DatetimeIndex`, `FloatIndex`... 
print (type(df.loc[df.index[0], 'value'])) 
<class 'list'> 

df['value'] = df['value'].str.get(0) 
print (df) 
    value 
0  63 
1  65 
2  64 

Se strings uso str.strip e poi convertire numerico da astype:

df['value'] = df['value'].str.strip('[]').astype(int) 

Esempio:

df = pd.DataFrame({'value':['[63]','[65]','[64]']}) 
print (df) 
    value 
0 [63] 
1 [65] 
2 [64] 

#check type if index 0 exist 
print (type(df.loc[0, 'value'])) 
<class 'str'> 

#check type generally, index can be `DatetimeIndex`, `FloatIndex`... 
print (type(df.loc[df.index[0], 'value'])) 
<class 'str'> 


df['value'] = df['value'].str.strip('[]').astype(int) 
print (df) 
    value 
0 63 
1 65 
2 64 
+1

'df ['valore']. Dtype' ha dato' dtype ('O') ' – DougKruger

+0

E che tipo' (df.ix [0, 'valore']) '? – jezrael

+0

è possibile avere risultato come 'dtype: float64'? – DougKruger