如何将match.group()文本放入熊猫数据框?

时间:2020-09-10 05:52:15

标签: python regex pandas re

我正在使用re来过滤一堆文本以获取所需的信息。现在,我可以使用match.group()在文本的每一行中打印出我需要的两条信息。

match.group(1)是数字,而match.group(4)是字符串。对于每一行(通过for循环迭代),我需要将match.group(1)添加到数据帧中的一列,并将match.group(4)添加到另一列。

这是代码(将底部的print语句替换为将每个元素添加到数据框中的代码):

finalText = re.search(r'19\s+domestic and stock rights(.*?)20\s+native title rights', rawText, flags=re.S | re.I).group(

pattern = re.compile('(\d+)( ML/year )(in the |the )([\w \/\(\)]+)')

df = pd.DataFrame()

for line in finalText.splitlines():
    matches = re.finditer(pattern, line)

    for matchNum, match in enumerate(matches, start=1):
    print (match.group(1) +","+ match.group(4))

和Mathc match.group(1)是一个数字,match.group(4)是一个位置,因此数据框的示例为:

Water Usage    Town
55             York
718            Holst
7              Poke

2 个答案:

答案 0 :(得分:1)

如果要添加到新的DF,则:

您首先在循环外启动新的DF:

new_df = pd.dataframe(columns=['match1','match4'])

并在循环内:

row = [match.group(1), match.group(4)]
new_df.loc[len(new_df)] = row

如果是现有DF,请在最后两个行代码中用df替换new_df

答案 1 :(得分:0)

创建元组列表并传递给DataFrame构造函数:

out = []
for line in finalText.splitlines():
    matches = re.finditer(pattern, line)

    for matchNum, match in enumerate(matches, start=1):
        out.append((match.group(1), match.group(4)))
        
df = pd.DataFrame(out, columns=['Water Usage','Town'])
print(df)