问题 如何从pandas数据框中删除方括号


我想出了方括号中的值(更像是一个 list)申请后 str.findall() 到pandas数据帧的列。如何拆除方括号?

print df

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

7636
2017-07-01 14:03


起源

该列的内容是什么,这是一个字符串 '[63]' 或列表 [63]? - EdChum


答案:


如果列中的值 value 有类型 list, 使用:

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

要么:

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

文件

样品:

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

如果 strings 使用 str.strip 然后转换为数字 astype

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

样品:

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

16
2017-07-01 14:04



df['value'].dtype 给 dtype('O') - DougKruger
什么 type(df.ix[0, 'value']) ? - jezrael
是否有可能得到结果 dtype: float64 ? - DougKruger
是的,使用 astype: df['value'] = df['value'].str.get(0).astype(float) - jezrael
@ separ1 - 是的。 df['value'].str.get(0) 要么 df['value'].str[0] 意味着给出列表的第一价值。如果需要al值,需要 df1 = pd.DataFrame(df['value'].values.tolist()) - jezrael