【问题标题】:Pandas find text with keyword and parenthesisPandas 查找带有关键字和括号的文本
【发布时间】:2021-12-01 08:23:24
【问题描述】:

我有一个包含以下数据的文本文件(example.txt):

parameter1
(
0
1
2
3
)

parameter2
(
4
5
5
6)

parameter3
(
2
3
)

我想使用 pandas 来提供关键字(例如,参数 2)并检索括号之间的信息。有什么办法吗?

【问题讨论】:

  • 这对熊猫有什么影响?

标签: python-3.x pandas dataframe


【解决方案1】:

这样的事情对我有用:

import pandas as pd
import numpy as np

df = pd.read_csv('exampleFile')


def findDataBetweenParenthesis( df, keyWord):
    
    headerName = df.columns[0]
    
    try:
        indexOfMatch = (df.index[(df[headerName] == keyWord)].tolist())[0]
    except:
        raise ValueError(keyWord + " not found")

    findFirstParenthesis = df[indexOfMatch:].index[df[indexOfMatch:][headerName].str.contains(r'\(')].tolist()[0]
    
    findSecondParenthesis = df[indexOfMatch:].index[df[indexOfMatch:][headerName].str.contains(r'\)')].tolist()[0]
    
    # If parenthesis are in the same line (1 2 3 4 5)
    
    if (findFirstParenthesis == findSecondParenthesis):
            
        # Read data between parenthesis
        data = df[findFirstParenthesis:findSecondParenthesis+1][headerName].str.extract(r"\((.*?)\)", expand=False)
        # split based on white space
        data = data.str.split()
        
        data = np.array(data.values[0],dtype=np.float64)
        
    else:
        data = np.zeros(findSecondParenthesis-findFirstParenthesis-1)
        i = 0
        for element in df[findFirstParenthesis+1:findSecondParenthesis].iterrows():
            data[i] = element[1][0]
            i=i+1
        
        
    return data

a = findDataBetweenParenthesis(df, "parameter1")

【讨论】:

    猜你喜欢
    • 2013-08-12
    • 2020-02-01
    • 1970-01-01
    • 2015-02-19
    • 2015-10-21
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    相关资源
    最近更新 更多