如何用逗号分割字符串并插入 pandas 数据框

How to split strings by the commas and insert into a pandas dataframe

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

58、冥王星 172、乌诺 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)58ML/Y在梨区 (乙) 苹果地区64 ML/Y

是纯文本

必须努力为您找出更简单的解决方案。使用 \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)]

这是我的解决方案

s = "58, pluto 172, uno 5, peaches"
temp = s.split() # ['58,', 'pluto', '172,', 'uno', '5,', 'peaches']
amount = temp[::2] #['58,', '172,', '5,']
fruit = temp[1::2] # ['pluto', 'uno', 'peaches']
df['amount'] = amount
df['fruit'] = fruit

您可以继续删除逗号并将类型从字符串更改为整数