如何从数据帧列中提取特定值并将其放入另一列?

2024-06-28 11:09:46 发布

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

我有一个由一列字符串组成的数据帧。我想从一列中提取地点、日期和比赛号码

数据帧:

- S.no.            FileName
- 0.     Albany17NOV19sectionalRace1.csv
- 1.     Albany22NOV19sectionalRace4.csv
- 2.     New York1NOV19sectionalRace7.csv
- 3.     Aquis Park Gold Coast27NOV19sectionalRace2.csv 

所需数据帧:

- S.no.   Place                     Date     Racenumber
- 0.     Albany                    17NOV19    Race1
- 1.     Albany                    22NOV19    Race4
- 2.     New York                  1NOV19     Race7
- 3.     Aquis park Gold Coast     27NOV19    Race2

Tags: csv数据no字符串parknewfilename号码
3条回答

虽然没有其他答案那么好,但它仍然完成了任务:

extract_info = {
    'Date': lambda x: x.str.findall('\d.+?\d{2}').str[0],
    'Place': lambda x: x.str.findall('^.+?(?=\d)').str[0],
    'Racenumber': lambda x: x.str.findall('Race\d+').str[0]}

df = df.FileName.agg(extract_info.values())
df.columns = extract_info.keys()

print(df)

      Date                  Place Racenumber
0  17NOV19                 Albany      Race1
1  22NOV19                 Albany      Race4
2   1NOV19               New York      Race7
3  27NOV19  Aquis Park Gold Coast      Race2

正则表达式函数应完成以下工作:

import re


def split_string_to_groups(s: str):
    temp = re.compile("([a-zA-Z\s]+)([0-9]+[a-zA-Z]+[0-9]+)(sectional)(Race[0-9]+)(\.csv)")
    res = temp.match(s).groups()
    return res

print(split_string_to_groups("Albany17NOV19sectionalRace1.csv"))
print(split_string_to_groups("Aquis Park Gold Coast27NOV19sectionalRace2.csv"))

输出:

('Albany', '17NOV19', 'sectional', 'Race1', '.csv')
('Aquis Park Gold Coast', '27NOV19', 'sectional', 'Race2', '.csv')

被分割

  1. digit后接Nondigitdigit,即17NOV19

  1. sectional

3特殊字符.

拆分后,删除所有没有作为值的行以及任何其他不需要的行。如果需要,可以重命名列

    df=df.FileName.str.split('(\d+\D+\d+)|(sectional)|(\.)', expand=True).dropna(1).drop(columns=[4,6,11,12])
print(df)
        

          

                    0        1      8
0                 Albany  17NOV19  Race1
1                 Albany  22NOV19  Race4
2               New York   1NOV19  Race7
3  Aquis Park Gold Coast  27NOV19  Race2

相关问题 更多 >