extracting rows from CSV file based on specific keywords

后端 未结 2 434

I have created a code to help me retrieving the data from csv file

  import re
keywords = {\"metal\", \"energy\", \"team\", \"sheet\", \"solar\" \"finan         


        
2条回答
  •  情歌与酒
    2021-01-29 05:53

    Try this, looping in a dataframe and write back a new dataframe to a csv file.

    import pandas as pd
    
    keywords = {"metal", "energy", "team", "sheet", "solar", "financial", 
            "transportation", "electrical", "scientists",
            "electronic", "workers"}  # all your keywords
    
    df = pd.read_csv("2006-data-8-8-2016.csv", sep=",")
    
    listMatchPosition = []
    listMatchDescription = []
    
    for i in range(len(df.index)):
        if any(x in df['position'][i] or x in df['Job description'][i] for x in keywords):
            listMatchPosition.append(df['position'][i])
            listMatchDescription.append(df['Job description'][i])
    
    
    output = pd.DataFrame({'position':listMatchPosition, 'Job description':listMatchDescription})
    output.to_csv("new_data.csv", index=False)
    

    EDIT: If you have many columns to add, the modified following code will do the job.

    df = pd.read_csv("2006-data-8-8-2016.csv", sep=",")
    
    output = pd.DataFrame(columns=df.columns)
    
    for i in range(len(df.index)):
        if any(x in df['position'][i] or x in df['Job description'][i] for x in keywords):
        output.loc[len(output)] = [df[j][i] for j in df.columns]
    
    output.to_csv("new_data.csv", index=False)
    

提交回复
热议问题