Python 如何从数据框中删除方括号
在将Python 如何从数据框中删除方括号,python,string,pandas,dataframe,Python,String,Pandas,Dataframe,在将str.findall()应用于数据帧的列之后,我得到了方括号中的值(更像是列表)。如何卸下方形支架 print df id value 1 [63] 2 [65] 3 [64] 4 [53] 5 [13] 6 [34] 如果列value中的值具有类型list,请使用: df['value'] = df['val
str.findall()
应用于数据帧的列之后,我得到了方括号中的值(更像是列表)。如何卸下方形支架
print df
id value
1 [63]
2 [65]
3 [64]
4 [53]
5 [13]
6 [34]
如果列value
中的值具有类型list
,请使用:
df['value'] = df['value'].str[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
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
样本:
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
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
df=pd.DataFrame({'value':['[63]','[65]','[64]})
打印(df)
价值
0 [63]
1 [65]
2 [64]
#如果索引0存在,请检查类型
打印(类型(df.loc[0,'值']))
#检查类型通常,索引可以是“DatetimeIndex”、“FloatIndex”。。。
打印(类型(df.loc[df.index[0],'value']))
df['value']=df['value'].str.strip('[]').astype(int)
打印(df)
价值
0 63
1 65
2 64
如果是string,我们也可以使用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
该列的内容是什么,这是一个字符串'[63]
还是一个列表[63]
?df['value'].dtype
给出了dtype('O')
和什么类型(df.ix[0,'value'])
?结果是否可能是dtype:float64
?@separ1-是的df['value'].str.get(0)
或df['value'].str[0]
表示给出列表的第一个值。如果需要al值,则需要df1=pd.DataFrame(df['value'].values.tolist())
当我有[63,23]
(列表中的2个值)而不是[63]时该怎么办?