将数据框列拆分为新的4列

2024-10-04 07:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个熊猫df,我想把地址列(最后一个)分为4个新列streename+num、zipcode、City和land

试验

 ID           Address
1.10065e+08  Bachgasse 39 \n69502 Hemsbach \nDeutschland
2.34115e+08  Am Friedensplatz 3\n68165 Mannheim\nDeutschland
2.36743e+08  Am Friedensplatz 3\n68165 Mannheim\nDeutschland
2.24763e+08  Am Friedensplatz 3\n68165 Mannheim\nDeutschland
2.26209e+08  Am Friedensplatz 3\n68165 Mannheim
2.2621e+08   Am Friedensplatz 3\n68165 Mannheim
2.35501e+08  Herman-BurcharStrasse 1\n7265 Davos Wolfgang\n...
2.31895e+08  Via Nova 37\n7017 Flims Dorf\nSchweiz
2.3611e+08   Neu-Isenburg\nDeutschland
2.40194e+08  Herman-BurcharStrasse 1\n7265 Davos Wolfgang\n. 

我想得到这个输出

   ID           Street zipcode   city         country
1.10065e+08  Bachgasse39        69502 Hemsbach Deutschland
2.34115e+08  Am Friedensplatz3 68165 Mannheim  Deutschland
2.36743e+08  Am Friedensplatz3 68165 Mannheim  Deutschland
2.24763e+08  Am Friedensplatz3 68165 Mannheim  Deutschland
2.26209e+08  Am Friedensplatz3 68165 Mannheim  Nan
2.2621e+08   Am Friedensplatz3 68165 Mannheim  Nan
....          .......          .....  ....      ....
....          ......           ...... ....     ......

我尝试过这种方法来解决这个问题,但不适用于我:

(A、B、C、D)是(街道名称+num、Zipcode…)的列名

pd.DataFrame(test['Firmen Adresse Geschäftlich'].str.split(r"\n",1).tolist(),columns = ['A','B','C'])

但我有一个错误:

TypeError:类型为“float”的对象没有len()

这里还有提示:

enter image description here

我想这样: enter image description here

enter image description here

我的数据框中有以下地址模式: enter image description here

enter image description here

enter image description here


Tags: id地址amnumzipcodehermanmannheimdeutschland
1条回答
网友
1楼 · 发布于 2024-10-04 07:29:48

如果列Firmen Adresse Geschäftlich是字符串,可以尝试以下操作:

df1=pd.DataFrame(test['Firmen Adresse 
        Geschäftlich'].str.split(r"\n").tolist(),columns = ['street 
        no.','zip','Land'],index=test['ID'])

df1[['zip','Stadt']]=pd.DataFrame(df1['zip'].str.strip().str.split(' 
   ').tolist(),index = df1.index)

日期集较小的输出如下所示:

           street no.    zip         Land     Stadt
ID                                                  
1        Bachgasse 39   69502  Deutschland  Hemsbach
2   Am Friedensplatz 3  68165  Deutschland  Mannheim

相关问题 更多 >