简体   繁体   中英

How to call a specific word from csv file using python

Supposed if I have a .csv file with two columns A, B so if I call column A row 3 then how to print column B row 3 data. Please help me out as I am beginner at code.

I just want to call a input value and print same row value form next column.

This is my code:

if "Hello" in msg:

     with open('data.csv', "r") as f:
        reader = csv.reader(f)
        chat = {}

        for row in reader:
            key = row[0]
            chat[key] = row[1:]
    try:
        gotreply = chat[msg]
    except KeyError:
        gotreply = 'null'

    print(gotreply)

     if gotreply == 'null':
        print("Sorry! I didn't understand. I'm still learning.")
    else:
        print("Input Again")

Not sure what exactly you asking, but you could do

import pandas as pd

foo_df = pd.read_csv('files/example.csv')

if foo_df.A[2] == "c":
    print(foo_df.B[2])

I recommend familiarizing yourself with Pandas as an elegant way to parse data.

Example.csv:

A,B
a,b
b,c
c,d
d,e

where A and B are your column names.

pandas.read_csv() will read a.csv and put it in a Dataframe. Check out the docs and give it a go.

import pandas as pd

foo_df = pd.read_csv('/path/to/example.csv')

print(foo_df)

should return

   A  B
0  a  b
1  b  c
2  c  d
3  d  e    

From there, it should just be a matter of taking a look at the docs to retrieve what you want from the dataframe.

I'm also a beginner and this is my first post here so I'll try to help you out.

First I assume your CSV file has headers and I assume your headers are called "A" and "B".

import csv

with open('test.csv', mode='r') as csv_file:
    csv_reader = csv.reader(csv_file)
    row_count = 1
    for i in csv_reader:
        if row_count == 4:
            print(i[1])  # prints second column of third row
        row_count += 1

There's probably a more efficient way but I'm new to the game too.

When I first started I also had some doubts like that. Pandas Slicing will be of help to you.

First import Pandas module as 'pd' (import pandas as pd) as it the most used form and will be easier for you to adapt.

import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14], ['tony', 12]]
df = pd.DataFrame(data, columns = ['A', 'B'])

This will create a sample Data Frame or simple 'df':

      A     B
0   tom     10
1   nick    15
2   juli    14
3   tony    12

Using one of the most common slicers in pandas df.loc you can get the result you want:

df.loc[2,'B']

This will return column 'B' row 3 as you mentioned. Remember that in Python first index start at 0 not 1. That's why we are using '2' for row number three.

Hope this help you.

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