将数据框列拆分为相等的部分

时间:2017-08-09 23:05:35

标签: python pandas

我想将此专栏分为三个部分:城市,州,邮政编码。我正在考虑这样的事情:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html。但是,我认为专栏需要先成为一个系列?任何帮助都会很棒。

import pandas as pd
suite_list
hospital_list =pd.DataFrame(suite_list, columns=['name', 'address_1', 'address_2', 'city_state_zip', 'phone'])

city_state_zip示例= Sahuarita,AZ,85629。我希望'Sahuarite','AZ','85629'在DataFrame中显示为单独的列。

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情,

df = pd.DataFrame({'Name' : ('john','doe','smith'), 'address_1' : (105,305,505), 'address_2' : ('path','lane','route'),\
           'city_state_zip': ('Sahuarita, AZ, 85629', 'Sahuarita1, AZ1, 75629', 'Sahuarita2, AZ2, 65629')})

df

        Name    address_1   address_2   city_state_zip
0        john   105             path    Sahuarita, AZ, 85629
1        doe    305             lane    Sahuarita1, AZ1, 75629
2        smith  505             route   Sahuarita2, AZ2, 65629

然后尝试,

df["col1"],df["col2"],df["col3"] = zip(*df["city_state_zip"].str.split().tolist())

输出df将是

       Name address_1   address_2   city_state_zip      col1     col2     col3
    0   john    105     path    Sahuarita, AZ,85629     Sahuarita   AZ     85629
    1   doe 3   05      lane    Sahuarita1, AZ1,5629    Sahuarita1  AZ1    75629
    2   smith   505     route   Sahuarita2, AZ2,65629   Sahuarita2  AZ2    65629

这应该是你在寻找什么。