且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Pandas中将元组中的字符串拆分为列

更新时间:2022-12-12 10:15:09

在另一种情况下,假设它是看起来像元组的字符串:

And for the other case, assuming it are strings that look like tuples:

In [74]: df['stats'].str[1:-1].str.split(',', expand=True).astype(float)
Out[74]:
          0         1         2         3         4
0 -0.009242  0.410000 -0.742016  0.003683  0.002517
1  0.041154  0.318231  0.758717  0.002640  0.010654
2 -0.014435  0.168438 -0.808703  0.000817  0.003166
3  0.034346  0.288731  0.950845  0.000001  0.003373
4  0.009052  0.151031  0.670257  0.012179  0.003022
5 -0.004797  0.171615 -0.552879  0.050032  0.002180

(注意:对于较早版本的熊猫(return_type='frame'而不是expand关键字)

(note: for older versions of pandas (< 0.16.1), you need to use return_type='frame' instead of the expand keyword)

顺便说一句,如果它是元组而不是字符串,则可以简单地执行以下操作:

By the way, if it are tuples and not strings, you can simply do the following:

pd.DataFrame(df['stats'].tolist(), index=df.index)