pandas DataFrame,我如何将一个列分成两个 [英] Pandas DataFrame, how do i split a column into two

查看:2564
本文介绍了 pandas DataFrame,我如何将一个列分成两个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列数据框,我想把它分成两列,一列为' fips',另一列为$ code>'row'



我的datFrame df如下所示

 
0 00000美国
1 01000阿拉巴马
2 01001奥古斯塔县,AL
3 01003 Baldwin县,AL
4 01005 Barbour County,AL

我是新来的python,不明白如何使用 df.row.str [:] 将帮助我实现分裂行单元格的目标。我可以使用 df ['fips'] = hello 添加一个新的列,并用你的方式填充它。有任何想法吗?

  fips row 
0 00000美国
1 01000 ALABAMA
2 01001 Autauga县, AL
3 01003 Baldwin County,AL
4 01005 Barbour County,AL


解决方案

可能有更好的方法,但这是一种方法:

 在[34 ]:进口大熊猫为pd 

在[35]中:df
出[35]:

0 00000美国
1 01000 ALABAMA
2 01001 Autauga县,AL
3 01003 Baldwin县,AL
4 01005 Barbour县,AL

在[36]中:df = pd.DataFrame(df。 row.str.split('',1).tolist(),
columns = ['flips','row'])

在[37]中:df
出[37]:
翻转行
0 00000美国
1 01000阿拉巴马
2 01001奥克塔加县,AL
3 01003 Baldwin县,AL
4 01005 Barbour County,AL


I have a data frame with one column and i'd like to split it into two columns, with one column header as 'fips' and the other 'row'

My datFrame df looks like this currently

          row
0    00000 UNITED STATES
1    01000 ALABAMA
2    01001 Autauga County, AL
3    01003 Baldwin County, AL
4    01005 Barbour County, AL

I am new to python and do not understand how using df.row.str[:] would help me achieve my goal of splitting the row cell. I can use df['fips'] = hello to add a new column and populate it with hello. Any ideas?

         fips       row
0    00000 UNITED STATES
1    01000 ALABAMA 
2    01001 Autauga County, AL
3    01003 Baldwin County, AL
4    01005 Barbour County, AL

解决方案

There might be a better way, but this here's one approach:

In [34]: import pandas as pd

In [35]: df
Out[35]: 
                        row
0       00000 UNITED STATES
1             01000 ALABAMA
2  01001 Autauga County, AL
3  01003 Baldwin County, AL
4  01005 Barbour County, AL

In [36]: df = pd.DataFrame(df.row.str.split(' ',1).tolist(),
                                   columns = ['flips','row'])

In [37]: df
Out[37]: 
   flips                 row
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

这篇关于 pandas DataFrame,我如何将一个列分成两个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆