【问题标题】:How to get Specific Cell Value from CSV With Respect To Row And Column Value using python如何使用 python 从 CSV 中获取特定的单元格值与行和列值有关
【发布时间】:2018-09-24 19:06:58
【问题描述】:

样本数据:

user,hotel_name,city,review

adam,hotel1,chennai,"Wow, what charm! As a Travel Agent.

john,hotel2,pune,Great location for sporting events.

mike,hotel3,mumbai,Its the best of the best.

george,hotel4,delhi,Ok hotel in a bad location.

大家好,

我想从 csv 文件中打印出 mike 给出的 review。我是 python 新手,有人可以帮助我吗?

【问题讨论】:

  • 你试过了吗?

标签: python pandas csv anaconda data-science


【解决方案1】:

假设您的 csv 在名为 data.csv 的文件中,并且您在同一目录中运行脚本。

然后你会做这样的事情:

import pandas as pd              # bring in pandas

df = pd.read_csv('data.csv')     # load data
print(df[df['user'] == 'mike'])  # add a mask for mike and print row

【讨论】:

  • df.loc[df['user'] == 'mike','review']
【解决方案2】:

两种方式,首先是 Python:

import csv

with open('file.csv', 'r') as fin:
    reader = csv.reader(fin)
    for line in reader:
        if line[0] == 'mike':
            print line[3]
            break

现在使用 Bash:

grep "mike" file.csv | cut -d, -f4

Its the best of the best.

【讨论】:

  • 如果有另一行有用户迈克它只打印第一个评论
  • 如果有不止一行用户是'mike',请删除break
  • 我期望的完美输出:)
猜你喜欢
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 2019-05-20
  • 2019-02-25
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多