python - 我如何删除 Pandas 中的过滤器数据(数据处理)

标签 python pandas dataframe data-munging

数据与我在 Pandas 系列:

data = ["1. stock1 (1991)",  
"3. stock13 (1993)",  
"5. stock19 (1999)",  
"89. stock105 (2001)"] # pandas Series

我需要过滤每个字符串并保存为

s.no    sdata       year  
1       stock1      1991  
3       stock13     1993  
5       stock19     1999  
89      stock105    2001 

我试过用

data = stock["Rank & Title"].str.split(".")

最佳答案

你可以试试str.extract使用正则表达式的方法:

data = ["1. stock1 (1991)",  
"3. stock13 (1993)",  
"5. stock19 (1999)",  
"89. stock105 (2001)"]

s = pd.Series(data)

s.str.extract("(?P<sno>\d+)\.\s(?P<sdata>\w+)\s\((?P<year>\d+)\)", expand=True)

# sno      sdata    year
#0  1     stock1    1991
#1  3    stock13    1993
#2  5    stock19    1999
#3  89  stock105    2001

正则表达式 上出现故障,(?P<sno>\d+)\.\s(?P<sdata>\w+)\s\((?P<year>\d+)\)可以简化为(\d+)\.\s(\w+)\s\((\d+)\)不命名捕获的组(使用 ?P<name> 完成); (\d+) , (\w+)(\d+)分别捕获 s.nostocknameyear


或者您可能只想在空白处进行拆分,然后根据实际数据的样子清理列:

(s.str.split(" ", expand=True)
  # strip period and parenthesis
 .apply(lambda col: col.str.strip(".()"))
  # rename columns
 .rename(columns={0: "s.no", 1: "sdata", 2: "year"}))

# s.no     sdata    year
#0   1    stock1    1991
#1   3   stock13    1993
#2   5   stock19    1999
#3  89  stock105    2001

关于python - 我如何删除 Pandas 中的过滤器数据(数据处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43592137/

相关文章:

python - 通过 Javascript 添加 Mongo 索引

python - 转置混合类型 DataFrame 的数据类型不正确

python - 获取数据帧中最后一个值时出现 KeyError

apache-spark - DataFrame na() 填充方法和不明确引用的问题

python - 为什么 jupyter 有时打印格式化的 DataFrame 有时打印为文本?

python - 类 : cannot use self inside the decorated function 中的装饰器

python - 车类错误

Python Pandas : classifying values in column and making a new column

python - 在多索引数据帧上应用重复序列

python - 使用 Pandas 通过键标识符转置多列