Debian Codegraph @

docs/tutorial/3_power_tools.rst

raw
1 ===========
2 Power tools
3 ===========
4
5 csvjoin: merging related data
6 =============================
7
8 One of the most common operations that we need to perform on data is "joining" it to other, related data. For instance, given a dataset about equipment supplied to counties in Nebraska, one might reasonably want to merge that with a dataset containing the population of each county. :doc:`/scripts/csvjoin` allows us to take those two datasets (equipment and population) and merge them, much like you might do with a SQL ``JOIN`` query. In order to demonstrate this, let's grab a second dataset:
9
10 .. code-block:: bash
11
12 curl -L -O https://raw.githubusercontent.com/wireservice/csvkit/master/examples/realdata/acs2012_5yr_population.csv
13
14 Now let's see what's in there:
15
16 .. code-block:: console
17
18 $ csvstat acs2012_5yr_population.csv
19 1. "fips"
20
21 Type of data: Number
22 Contains null values: False
23 Unique values: 93
24 Smallest value: 31,001
25 Largest value: 31,185
26 Sum: 2,891,649
27 Mean: 31,093
28 Median: 31,093
29 StDev: 53.981
30 Most common values: 31,001 (1x)
31 31,003 (1x)
32 31,005 (1x)
33 31,007 (1x)
34 31,009 (1x)
35
36 2. "name"
37
38 Type of data: Text
39 Contains null values: False
40 Unique values: 93
41 Longest value: 23 characters
42 Most common values: Adams County, NE (1x)
43 Antelope County, NE (1x)
44 Arthur County, NE (1x)
45 Banner County, NE (1x)
46 Blaine County, NE (1x)
47
48 3. "total_population"
49
50 Type of data: Number
51 Contains null values: False
52 Unique values: 93
53 Smallest value: 348
54 Largest value: 518,271
55 Sum: 1,827,306
56 Mean: 19,648.452
57 Median: 6,294
58 StDev: 62,501.005
59 Most common values: 31,299 (1x)
60 6,655 (1x)
61 490 (1x)
62 778 (1x)
63 584 (1x)
64
65 4. "margin_of_error"
66
67 Type of data: Number
68 Contains null values: False
69 Unique values: 15
70 Smallest value: 0
71 Largest value: 115
72 Sum: 1,800
73 Mean: 19.355
74 Median: 0
75 StDev: 37.897
76 Most common values: 0 (73x)
77 73 (2x)
78 114 (2x)
79 97 (2x)
80 99 (2x)
81
82 Row count: 93
83
84 As you can see, this data file contains population estimates for each county in Nebraska from the 2012 5-year ACS estimates. This data was retrieved from `Census Reporter <https://censusreporter.org/>`_ and reformatted slightly for this example. Let's join it to our equipment data:
85
86 .. code-block:: bash
87
88 csvjoin -c fips data.csv acs2012_5yr_population.csv > joined.csv
89
90 Since both files contain a fips column, we can use that to join the two. In our output you should see the population data appended at the end of each row of data. Let's combine this with what we've learned before to answer the question "What was the lowest population county to receive equipment?":
91
92 .. code-block:: console
93
94 $ csvcut -c county,item_name,total_population joined.csv | csvsort -c total_population | csvlook | head
95 | county | item_name | total_population |
96 | ---------- | -------------------------------------------------------------- | ---------------- |
97 | MCPHERSON | RIFLE,5.56 MILLIMETER | 348 |
98 | WHEELER | RIFLE,5.56 MILLIMETER | 725 |
99 | GREELEY | RIFLE,7.62 MILLIMETER | 2,515 |
100 | GREELEY | RIFLE,7.62 MILLIMETER | 2,515 |
101 | GREELEY | RIFLE,7.62 MILLIMETER | 2,515 |
102 | NANCE | RIFLE,5.56 MILLIMETER | 3,730 |
103 | NANCE | RIFLE,7.62 MILLIMETER | 3,730 |
104 | NANCE | RIFLE,7.62 MILLIMETER | 3,730 |
105
106 Two counties with fewer than one-thousand residents were the recipients of 5.56 millimeter assault rifles. This simple example demonstrates the power of joining datasets. Although SQL will always be a more flexible option, :doc:`/scripts/csvjoin` will often get you where you need to go faster.
107
108 csvstack: combining subsets
109 ===========================
110
111 Frequently large datasets are distributed in many small files. At some point you will probably want to merge those files for bulk analysis. :doc:`/scripts/csvstack` allows you to "stack" the rows from CSV files with the same columns (and identical column names). To demonstrate, let's imagine we've decided that Nebraska and Kansas form a "region" and that it would be useful to analyze them in a single dataset. Let's grab the Kansas data:
112
113 .. code-block:: bash
114
115 curl -L -O https://raw.githubusercontent.com/wireservice/csvkit/master/examples/realdata/ks_1033_data.csv
116
117 Back in :doc:`1_getting_started`, we had used in2csv to convert our Nebraska data from XLSX to CSV. However, we named our output `data.csv` for simplicity at the time. Now that we are going to be stacking multiple states, we should re-convert our Nebraska data using a file naming convention matching our Kansas data:
118
119 .. code-block:: bash
120
121 in2csv ne_1033_data.xlsx > ne_1033_data.csv
122
123 Now let's stack these two data files:
124
125 .. code-block:: bash
126
127 csvstack ne_1033_data.csv ks_1033_data.csv > region.csv
128
129 Using csvstat we can see that our ``region.csv`` contains both datasets:
130
131 .. code-block:: console
132
133 $ csvstat -c state,acquisition_cost region.csv
134 1. "state"
135
136 Type of data: Text
137 Contains null values: False
138 Unique values: 2
139 Longest value: 2 characters
140 Most common values: KS (1575x)
141 NE (1036x)
142
143 8. "acquisition_cost"
144
145 Type of data: Number
146 Contains null values: False
147 Unique values: 127
148 Smallest value: 0
149 Largest value: 658,000
150 Sum: 9,440,445.91
151 Mean: 3,615.644
152 Median: 138
153 StDev: 23,730.631
154 Most common values: 120 (649x)
155 499 (449x)
156 138 (311x)
157 6,800 (304x)
158 58.71 (218x)
159
160 Row count: 2611
161
162 If you supply the :code:`-g` flag then :doc:`/scripts/csvstack` can also add a "grouping column" to each row, so that you can tell which file each row came from. In this case we don't need this, but you can imagine a situation in which instead of having a ``county`` column each of this datasets had simply been named ``nebraska.csv`` and ``kansas.csv``. In that case, using a grouping column would prevent us from losing information when we stacked them.
163
164 csvsql and sql2csv: ultimate power
165 ==================================
166
167 Sometimes (almost always), the command-line isn't enough. It would be crazy to try to do all your analysis using command-line tools. Often times, the correct tool for data analysis is SQL. :doc:`/scripts/csvsql` and :doc:`/scripts/sql2csv` form a bridge that eases migrating your data into and out of a SQL database. For smaller datasets :doc:`/scripts/csvsql` can also leverage `sqlite <https://www.sqlite.org/>`_ to allow execution of ad hoc SQL queries without ever touching a database.
168
169 By default, :doc:`/scripts/csvsql` will generate a create table statement for your data. You can specify what sort of database you are using with the ``-i`` flag:
170
171 .. code-block:: bash
172
173 csvsql -i sqlite joined.csv
174
175 .. code-block:: sql
176
177 CREATE TABLE joined (
178 state VARCHAR NOT NULL,
179 county VARCHAR NOT NULL,
180 fips FLOAT NOT NULL,
181 nsn VARCHAR NOT NULL,
182 item_name VARCHAR,
183 quantity FLOAT NOT NULL,
184 ui VARCHAR NOT NULL,
185 acquisition_cost FLOAT NOT NULL,
186 total_cost FLOAT NOT NULL,
187 ship_date DATE NOT NULL,
188 federal_supply_category FLOAT NOT NULL,
189 federal_supply_category_name VARCHAR NOT NULL,
190 federal_supply_class FLOAT NOT NULL,
191 federal_supply_class_name VARCHAR NOT NULL,
192 name VARCHAR NOT NULL,
193 total_population FLOAT NOT NULL,
194 margin_of_error FLOAT NOT NULL
195 );
196
197 Here we have the sqlite "create table" statement for our joined data. You'll see that, like :doc:`/scripts/csvstat`, :doc:`/scripts/csvsql` has done its best to infer the column types.
198
199 Often you won't care about storing the SQL statements locally. You can also use :doc:`/scripts/csvsql` to create the table directly in the database on your local machine. If you add the :code:`--insert` option the data will also be imported:
200
201 .. code-block:: bash
202
203 csvsql --db sqlite:///leso.db --insert joined.csv
204
205 How can we check that our data was imported successfully? We could use the sqlite command-line interface, but rather than worry about the specifics of another tool, we can also use :doc:`/scripts/sql2csv`:
206
207 .. code-block:: bash
208
209 sql2csv --db sqlite:///leso.db --query "select * from joined"
210
211 Note that the :code:`--query` parameter to :doc:`/scripts/sql2csv` accepts any SQL query. For example, to export Douglas county from the ``joined`` table from our sqlite database, we would run:
212
213 .. code-block:: bash
214
215 sql2csv --db sqlite:///leso.db --query "select * from joined where county='DOUGLAS';" > douglas.csv
216
217 Sometimes, if you will only be running a single query, even constructing the database is a waste of time. For that case, you can actually skip the database entirely and :doc:`/scripts/csvsql` will create one in memory for you:
218
219 .. code-block:: bash
220
221 csvsql --query "select county,item_name from joined where quantity > 5;" joined.csv | csvlook
222
223 SQL queries directly on CSVs! Keep in mind when using this that you are loading the entire dataset into an in-memory SQLite database, so it is likely to be very slow for large datasets.
224
225 Summing up
226 ==========
227
228 :doc:`/scripts/csvjoin`, :doc:`/scripts/csvstack`, :doc:`/scripts/csvsql` and :doc:`/scripts/sql2csv` represent the power tools of csvkit. Using these tools can vastly simplify processes that would otherwise require moving data between other systems. But what about cases where these tools still don't cut it? What if you need to move your data onto the web or into a legacy database system? We've got a few solutions for those problems in our final section, :doc:`4_going_elsewhere`.