Dou*_*ger 16 python string dataframe pandas
list
在应用str.findall()
到pandas数据帧的列之后,我想出了方括号中的值(更像是a ).如何拆下方括号?
print df
id value
1 [63]
2 [65]
3 [64]
4 [53]
5 [13]
6 [34]
Run Code Online (Sandbox Code Playgroud)
jez*_*ael 24
如果列中的值value
具有类型list
,请使用:
df['value'] = df['value'].str[0]
Run Code Online (Sandbox Code Playgroud)
要么:
df['value'] = df['value'].str.get(0)
Run Code Online (Sandbox Code Playgroud)
文件.
样品:
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
Run Code Online (Sandbox Code Playgroud)
如果strings
使用str.strip
然后转换为数字astype
:
df['value'] = df['value'].str.strip('[]').astype(int)
Run Code Online (Sandbox Code Playgroud)
样品:
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
Run Code Online (Sandbox Code Playgroud)
如果字符串我们也可以使用 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
Run Code Online (Sandbox Code Playgroud)