Rows 是一个专门用于操作表格的第三方Python模块。

只要通过 Rows 读取 csv 文件,她就能生成可以被计算的 Python 对象。

相比于 pandas 的 pd.read_csv, 我认为 Rows 的优势在于其易于理解的计算语法和各种方便的导出和转换语法。它能非常方便地提取pdf中的文字、将csv转换为sqlite文件、合并csv等,还能对csv文件执行sql语法,还是比较强大的。

当然,它的影响力肯定没有 Pandas 大,不过了解一下吧,技多不压身。

1.准备

开始之前,你要确保Python和pip已经成功安装在电脑上,如果没有,请访问这篇文章:超详细Python安装指南 进行安装。

(可选1) 如果你用Python的目的是数据分析,可以直接安装Anaconda:Python数据分析与挖掘好帮手—Anaconda,它内置了Python和pip.

(可选2) 此外,推荐大家用VSCode编辑器来编写小型Python项目:Python 编程的最好搭档—VSCode 详细指南

Windows环境下打开Cmd(开始—运行—CMD),苹果系统环境下请打开Terminal(command+空格输入Terminal),输入命令安装依赖:

pip install rows

2.Rows 基本使用

通过下面这个小示例,你就能知道Rows的基本使用方法。

假设我们有这样的一个csv表格数据:

state,city,inhabitants,area
AC,Acrelândia,12538,1807.92
AC,Assis Brasil,6072,4974.18
AC,Brasiléia,21398,3916.5
AC,Bujari,8471,3034.87
AC,Capixaba,8798,1702.58
[...]
RJ,Angra dos Reis,169511,825.09
RJ,Aperibé,10213,94.64
RJ,Araruama,112008,638.02
RJ,Areal,11423,110.92
RJ,Armação dos Búzios,27560,70.28
[...]

如果我们想要找出 state 为 RJ 并且人口大于 500000 的城市,只需要这么做:

import rows

cities = rows.import_from_csv("data/brazilian-cities.csv")
rio_biggest_cities = [
    city for city in cities
    if city.state == "RJ" and city.inhabitants > 500000
]
for city in rio_biggest_cities:
    density = city.inhabitants / city.area
    print(f"{city.city} ({density:5.2f} ppl/km²)")

和 Pandas 很像,但是语法比 Pandas 简单,整个模块也比 Pandas 轻量。

如果你想要自己新建一个”表格”, 你可以这么写:

from collections import OrderedDict
from rows import fields, Table


country_fields = OrderedDict([
    ("name", fields.TextField),
    ("population", fields.IntegerField),
])

countries = Table(fields=country_fields)
countries.append({"name": "Argentina", "population": "45101781"})
countries.append({"name": "Brazil", "population": "212392717"})
countries.append({"name": "Colombia", "population": "49849818"})
countries.append({"name": "Ecuador", "population": "17100444"})
countries.append({"name": "Peru", "population": "32933835"})

然后你可以迭代它:

for country in countries:
    print(country)
# Result:
#     Row(name='Argentina', population=45101781)
#     Row(name='Brazil', population=212392717)
#     Row(name='Colombia', population=49849818)
#     Row(name='Ecuador', population=17100444)
#     Row(name='Peru', population=32933835)
# "Row" is a namedtuple created from `country_fields`

# We've added population as a string, the library automatically converted to
# integer so we can also sum:
countries_population = sum(country.population for country in countries)
print(countries_population)  # prints 357378595

还可以将此表导出为 CSV 或任何其他支持的格式:

# 公众号:Python实用宝典
import rows
rows.export_to_csv(countries, "some-LA-countries.csv")

# html
rows.export_to_html(legislators, "some-LA-countries.csv")

从字典导入到rows对象:

import rows

data = [
    {"name": "Argentina", "population": "45101781"},
    {"name": "Brazil", "population": "212392717"},
    {"name": "Colombia", "population": "49849818"},
    {"name": "Ecuador", "population": "17100444"},
    {"name": "Peru", "population": "32933835"},
    {"name": "Guyana", },  # Missing "population", will fill with `None`
]
table = rows.import_from_dicts(data)
print(table[-1])  # Can use indexes
# Result:
#     Row(name='Guyana', population=None)

3.命令行工具

除了写Python代码外,你还可以直接使用Rows的命令行工具,下面介绍几个可能会经常被用到的工具。

读取pdf文件内的文字并保存为文件:

# 需要提前安装: pip install rows[pdf]
URL="http://www.imprensaoficial.rr.gov.br/app/_edicoes/2018/01/doe-20180131.pdf"
rows pdf-to-text $URL result.txt  # 保存到文件 显示进度条
rows pdf-to-text --quiet $URL result.txt  # 保存到文件 不显示进度条
rows pdf-to-text --pages=1,2,3 $URL # 输出三页到终端
rows pdf-to-text --pages=1-3 $URL # 输出三页到终端(使用 - 范围符)

将csv转化为sqlite:

rows csv2sqlite \
     --dialect=excel \
     --input-encoding=latin1 \
     file1.csv file2.csv \
     result.sqlite

合并多个csv文件:

rows csv-merge \
     file1.csv file2.csv.bz2 file3.csv.xz \
     result.csv.gz

对csv执行sql搜索:

# needs: pip install rows[html]
rows query \
    "SELECT * FROM table1 WHERE inhabitants > 1000000" \
    data/brazilian-cities.csv \
    --output=data/result.html

其他更多功能,请见Rows官方文档:

http://turicas.info/rows

我们的文章到此就结束啦,如果你喜欢今天的 Python 教程,请持续关注Python实用宝典。

有任何问题,可以在公众号后台回复:加群,回答相应验证信息,进入互助群询问。

原创不易,希望你能在下面点个赞和在看支持我继续创作,谢谢!


​Python实用宝典 ( pythondict.com )
不只是一个宝典
欢迎关注公众号:Python实用宝典

Pandas 性能优化
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。