从列值获取行中的值

时间:2018-03-30 11:34:55

标签: python python-3.x csv python-3.5

我有一个csv文件,如下所示:

----------------------------------------------------------
|Student ID |   Name   | Username | Password | Moderator |
----------------------------------------------------------    
|   0001    | Foo Bar  |   test   |   abc123  |     N    |
|   0002    |  Baz Qux |   bob    |   bcd986  |     Y    |
----------------------------------------------------------

如何从列值中连续获取值?

例如,如果我有用户名' test'我怎样才能获得'姓名'在相应的行(Foo Bar)?

3 个答案:

答案 0 :(得分:2)

使用pandas

读取csv文件
    int start = 0;
    char[] arr = { 'a', 'b', 'c', 'd', 'e', 'f'};
    int end = arr.length - 1;
    while (start <= end) {
        if (start == end) {
            System.out.print(arr[start]);
        } else {
            System.out.print(arr[start] + " " + arr[end] + " ");
        }
        start++;
        end--;
    }

从列值

中访问行中的值
import pandas as pd
# Here you can use pd.read_csv() instead
df = pd.read_clipboard(sep=',')

[OUT]:

df[df.Username == 'test']['Name']

如果您需要将结果作为字符串:

0    Foo Bar
Name: Name, dtype: object

[OUT]:

df[df.Username == 'test'].Name.values[0]

答案 1 :(得分:1)

有几种方法可以完成您的任务。 首先,正如@michaelg提出的那样,使用pandas - 它很快并且库处理得非常好。这是pandas的链接。 第二个选项将是csv module中的内置版本。在那里,您可以找到带有分隔符的scv reader的简短示例。第三种选择只是将您的.scv文件视为普通文件。例如,

with open("test.csv", "r") as f:
    data = f.readlines()
    # we skip first line because it is your header,
    # e.g. id, name, pswd, etc.
    for line in data[1:]:
        for field in line.split("|"): # place your delimiter
            # strip data of leading and trailing whitespaces 
            print(field.strip()) 

您可以使用此方法搜索相应的值。上面的代码段会生成此输出:

0001
Foo Bar
test
abc123
N

如果要按索引访问值,请使用:

with open("test.csv", "r") as f:
    data = f.readlines()
    values = [x.split("|") for x in data[1:]]

上面的代码段会为您提供list这种格式[[..], [..],..],其中values[0]是您文件的第1行,values[0][1] = "Foo Bar"名称。

答案 2 :(得分:0)

格式不是真正的csv。您可以将其重写为有用的东西并使用DictReader解析它:

import csv

def rewriteCsv(filename): 
    """Rewrite silly file into something usefull"""
    header = None
    rwfn = "mod_"+filename
    with open (filename,"r") as r, open(rwfn,"w") as w:
        for row in r:
            if row.startswith("---"):
                continue # skip it
            if not header:
                header = ','.join(x.strip() for x in row.split("|") if x.strip())
                w.write(header+'\n')
                continue

            w.write(','.join( x.strip() for x in row.strip()[1:-1].split("|") ) +"\n")
    return rwfn

def createFile(filename):
    """Create the silly file..."""
    with open(filename,"w") as f:
        f.write("""----------------------------------------------------------
|Student ID |   Name   | Username | Password | Moderator |
----------------------------------------------------------    
|   0001    | Foo Bar  |   test   |   abc123  |     N    |
|   0002    |  Baz Qux |   bob    |   bcd986  |     Y    |
----------------------------------------------------------
""")

createFile("file.txt") # create the silly one
fn = rewriteCsv("file.txt") # rewrite into something useful

with open(fn,"r") as r: 
    reader = csv.DictReader(r)
    for row in reader: # access earch ordered dict by columnname
        print(row["Student ID"], row["Name"], row["Username"])