将For Loop的值插入Pandas列

时间:2016-09-14 19:20:50

标签: pandas python-3.4

我试图从正则表达式得到的结果,即

['11J']
['4C']
['5,']
[]
['04 ', '05 ', '48T']

并将这些值存储在现有pandas数据帧的新列(即Apt)中。

样本数据(Excel文件)

index  id           apt     address           job description
0     122092476     207     EAST 74 STREET    blah blah 11J blah               
1     122096043     2092    8TH AVENUE        blah 4C blah blah

代码

import pandas as pd
import re

df = pd.read_excel('/Users/abc/Desktop/Apartment.xlsx', sheetname=0)
df['Apt'] = 'None'
top5 = df.head()
t5jobs = top5['Job Description']    

d = []

for index, job in enumerate(t5jobs):
    result = re.findall(r'\d\d\D', job) or re.findall(r'\d\D', job) or re.findall(r'PH\D', job)

#print(str(result))
d.append(str(result))

df2 = pd.DataFrame([[d]], columns=list('Apt'))
df.append(df2)

我收到此错误:

AssertionError: 3 columns passed, passed data had 1 columns

如何在Apt列中插入这些值(覆盖无)?

期望的输出:

index  id           apt     address           job description         apt 
 0     122092476     207     EAST 74 STREET    blah blah 11J blah      11J         
 1     122096043     2092    8TH AVENUE        blah 4C blah blah        4C

1 个答案:

答案 0 :(得分:2)

试试这个(对于pandas 0.18.0 +):

In [11]: df['Apt'] = df['job description'].str.extract(r'\b(\d{1,2}\D)\b', expand=True)

In [12]: df
Out[12]:
              id   apt         address     job description  Apt
index
0      122092476   207  EAST 74 STREET  blah blah 11J blah  11J
1      122096043  2092      8TH AVENUE   blah 4C blah blah   4C

用于pandas版本< 0.18.0:

df['Apt'] = df['job description'].str.extract(r'\b(\d{1,2}\D)\b')