如何从熊猫数据框中删除方括号

新手上路,请多包涵

在将 str.findall() 应用于 pandas 数据框的列后,我想出了方括号中的值(更像是 list )。如何删除方括号?

 print df

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

原文由 DougKruger 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

如果列中的值 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

原文由 jezrael 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果是字符串,我们也可以使用 string.replace 方法

import pandas as pd

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

print(df)
  value
0  [63]
1  [65]
2  [64]

df['value'] =  df['value'].apply(lambda x: x.replace('[','').replace(']',''))

#convert the string columns to int
df['value'] = df['value'].astype(int)

#output
print(df)

   value
0     63
1     65
2     64

print(df.dtypes)
value    int32
dtype: object

原文由 qaiser 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题