首页 > 解决方案 > 如何用逗号分割字符串并插入熊猫数据框

问题描述

我有一个带有 for 循环的函数,它返回一堆字符串,例如:

58, 冥王星 172, uno 5, 桃子

如何在 pandas 数据框中的一列中获取字符串的第一部分(数字),在第二列中获取第二部分(水果)。列应命名为“金额”和“水果”。

这是到目前为止的代码:

regex = r"(\d+)( ML/year )(in the |the )([\w \/\(\)]+)"
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))

我正在使用 re 从一大块文本中过滤掉我需要的数据,但现在它只是打印到控制台,我需要它进入数据框。

本质上,该代码中的最后一个打印语句需要更改,因此我插入数据帧而不是打印。

最终文本的示例是:

(a)梨区 58 ML/Y (b) 苹果区 64 ML/Y

它是纯文本

标签: pythonpandasdataframere

解决方案


必须努力为您找出一个更简单的解决方案。使用 \W 正则表达式从字符串中删除 ()\。

如果你的字符串的模式总是

(x)## ML/Y in the fruit region (y) ## ML/Y in the fruit region

然后使用此代码。它将从列表中删除 ( ) \ 并为您提供更简单的列表。使用列表中的第 3、第 8、第 13 和第 18 位来获得您想要的。

import pandas as pd
import re

finalText = '(a)58 ML/Y in the pear region (b) 64 ML/Y in the apple region'

df = pd.DataFrame(data=None, columns=['amount','fruit'])

for line in finalText.splitlines():
    matches = re.split(r'\W',line)
    df.loc[len(df)] = [matches[2],matches[7]]
    df.loc[len(df)] = [matches[12],matches[17]]

print(df)

输出结果为:

  amount  fruit
0     58   pear
1     64  apple

另一种方法是使用 findall。

for line in finalText.splitlines():
    print (line)
    m = re.findall(r'\w+',line)
    print (m)
    matches = re.findall(r'\w+',line)
    df.loc[len(df)] = [matches[1],matches[6]]
    df.loc[len(df)] = [matches[9],matches[14]]

print(df)

结果与上述相同

  amount  fruit
0     58   pear
1     64  apple

旧代码

试试这个,让我知道它是否有效。

import pandas as pd

df = pd.DataFrame(data=None, columns=['amount','fruit'])

regex = r"(\d+)( ML/year )(in the |the )([\w \/\(\)]+)"
for line in finalText.splitlines():
    matches = re.finditer(pattern, line)

    for matchNum, match in enumerate(matches, start=1):
        df[matchNum] = [match.group(1) , match.group(4)]

推荐阅读