简体   繁体   中英

How to select a specific part in a .csv file on multiple lines? (Python3)

I'm making this example up for the sake of explaining the problem. If I have a .csv file as follows:

alfa, bravo, Charlie, 1.31
Dragonball, manga, anime, 3.11
delta, Omega, cookie, 3.13
Dragonball, stan, lee, 1.13

How can I pick up the fourth part of each line which has "Dragonball" as the first part? If the list goes on further, and I do not know which lines have the "Dragonball" as the first part.

I have tried:

list = []
for line in file:
    line = line.rstrip()
    part = line.split(",")
    if part[0] == Dragonball:
        list.append(part[3])

Expected output:

list = [3.11, 1.13]

You can do it easily using pandas :

import pandas as pd

df = pd.read_csv("path to your csv file")

print(list(df[df[0]=='Dragonball'][3]))

Output:

[3.11, 1.13]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM