![](/img/trans.png)
[英]Pandas - split column with dtype object (string) to dtype list by specifying delimiter
[英]Splitting dataframe column where the dtype is Object but inside it there is list , how to split?
我有 dataframe 列名为 teams 的列,其 dtype 为“O”(str),但里面有列表:例如:“['Australia','Sri Lanka']” 现在我想将这两个团队名称分成两个栏目,怎么办?
让我们以这两种类型的 object 列为例。
df = pd.DataFrame({'list_col':[['Aaaaa','Bbbbb'],['Scott','Boston']],
'str_col':["[Ccccc,Ddddd]","[Scott,Boston]"]})
print(df)
Output:
list_col str_col
0 [Aaaaa, Bbbbb] [Ccccc,Ddddd]
1 [Scott, Boston] [Scott,Boston]
使用 df.info():
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 list_col 2 non-null object
1 str_col 2 non-null object
dtypes: object(2)
memory usage: 160.0+ bytes
两者看起来一样,现在:
type(df.iloc[0,0])
返回列表
type(df.iloc[0,1])
返回 str
让我们像这样分开:
df['str_col'].str.strip('\[|\]').str.split(',',expand=True)
0 1
0 Ccccc Ddddd
1 Scott Boston
或者像这样:
dfe = df[['list_col']].explode('list_col')
dfe.set_index(dfe.groupby(level=0).cumcount(), append=True)['list_col'].unstack()
0 1
0 Aaaaa Bbbbb
1 Scott Boston
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.