{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 5. Joining Tables\n", "\n", "This is the fifth in a series of notebooks related to astronomy data.\n", "\n", "As a continuing example, we will replicate part of the analysis in a recent paper, \"[Off the beaten path: Gaia reveals GD-1 stars outside of the main stream](https://arxiv.org/abs/1805.00425)\" by Adrian M. Price-Whelan and Ana Bonaca.\n", "\n", "Picking up where we left off, the next step in the analysis is to select candidate stars based on photometry data.\n", "The following figure from the paper is a color-magnitude diagram for the stars selected based on proper motion:\n", "\n", "\n", "\n", "In red is a [stellar isochrone](https://en.wikipedia.org/wiki/Stellar_isochrone), showing where we expect the stars in GD-1 to fall based on the metallicity and age of their original globular cluster. \n", "\n", "By selecting stars in the shaded area, we can further distinguish the main sequence of GD-1 from younger background stars." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Outline\n", "\n", "Here are the steps in this notebook:\n", "\n", "1. We'll reload the candidate stars we identified in the previous notebook.\n", "\n", "2. Then we'll run a query on the Gaia server that uploads the table of candidates and uses a `JOIN` operation to select photometry data for the candidate stars.\n", "\n", "3. We'll write the results to a file for use in the next notebook.\n", "\n", "After completing this lesson, you should be able to\n", "\n", "* Upload a table to the Gaia server.\n", "\n", "* Write ADQL queries involving `JOIN` operations." ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "## Installing libraries\n", "\n", "If you are running this notebook on Colab, you can run the following cell to install the libraries we'll use.\n", "\n", "If you are running this notebook on your own computer, you might have to install these libraries yourself. See the instructions in the preface." ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "tags": [] }, "outputs": [], "source": [ "# If we're running on Colab, install libraries\n", "\n", "import sys\n", "IN_COLAB = 'google.colab' in sys.modules\n", "\n", "if IN_COLAB:\n", " !pip install astroquery" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Getting photometry data\n", "\n", "The Gaia dataset contains some photometry data, including the variable `bp_rp`, which contains BP-RP color (the difference in mean flux between the BP and RP bands).\n", "We use this variable to select stars with `bp_rp` between -0.75 and 2, which excludes many class M dwarf stars.\n", "\n", "Now, to select stars with the age and metal richness we expect in GD-1, we will use `g-i` color and apparent `g`-band magnitude, which are available from the Pan-STARRS survey." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Conveniently, the Gaia server provides data from Pan-STARRS as a table in the same database we have been using, so we can access it by making ADQL queries.\n", "\n", "In general, choosing a star from the Gaia catalog and finding the corresponding star in the Pan-STARRS catalog is not easy. This kind of cross matching is not always possible, because a star might appear in one catalog and not the other. And even when both stars are present, there might not be a clear one-to-one relationship between stars in the two catalogs.\n", "\n", "Fortunately, smart people have worked on this problem, and the Gaia database includes cross-matching tables that suggest a best neighbor in the Pan-STARRS catalog for many stars in the Gaia catalog.\n", "\n", "[This document describes the cross matching process](https://gea.esac.esa.int/archive/documentation/GDR2/Catalogue_consolidation/chap_cu9val_cu9val/ssec_cu9xma/sssec_cu9xma_extcat.html). Briefly, it uses a cone search to find possible matches in approximately the right position, then uses attributes like color and magnitude to choose pairs of observations most likely to be the same star." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The best neighbor table\n", "\n", "So the hard part of cross-matching has been done for us. Using the results is a little tricky, but it gives us a chance to learn about one of the most important tools for working with databases: \"joining\" tables.\n", "\n", "In general, a \"join\" is an operation where you match up records from one table with records from another table using as a \"key\" a piece of information that is common to both tables, usually some kind of ID code.\n", "\n", "In this example:\n", "\n", "* Stars in the Gaia dataset are identified by `source_id`.\n", "\n", "* Stars in the Pan-STARRS dataset are identified by `obj_id`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For each candidate star we have selected so far, we have the `source_id`; the goal is to find the `obj_id` for the same star (we hope) in the Pan-STARRS catalog.\n", "\n", "To do that we will:\n", "\n", "1. Use the `JOIN` operator to look up each `source_id` in the `panstarrs1_best_neighbour` table, which contains the `obj_id` of the best match for each star in the Gaia catalog; then\n", "\n", "2. Use the `JOIN` operator again to look up each `obj_id` in the `panstarrs1_original_valid` table, which contains the Pan-STARRS photometry data we want.\n", "\n", "Before we get to the `JOIN` operation, let's explore these tables.\n", "Here's the metadata for `panstarrs1_best_neighbour`." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "from astroquery.gaia import Gaia\n", "\n", "meta = Gaia.load_table('gaiadr2.panstarrs1_best_neighbour')" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "print(meta)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And here are the columns." ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "for column in meta.columns:\n", " print(column.name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's the [documentation for these variables](https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/sec_dm_crossmatches/ssec_dm_panstarrs1_best_neighbour.html) .\n", "\n", "The ones we'll use are:\n", "\n", "* `source_id`, which we will match up with `source_id` in the Gaia table.\n", "\n", "* `number_of_neighbours`, which indicates how many sources in Pan-STARRS are matched with this source in Gaia.\n", "\n", "* `number_of_mates`, which indicates the number of *other* sources in Gaia that are matched with the same source in Pan-STARRS.\n", "\n", "* `original_ext_source_id`, which we will match up with `obj_id` in the Pan-STARRS table.\n", "\n", "Ideally, `number_of_neighbours` should be 1 and `number_of_mates` should be 0; in that case, there is a one-to-one match between the source in Gaia and the corresponding source in Pan-STARRS.\n", "\n", "Here's a query that selects these columns and returns the first 5 rows." ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "query = \"\"\"SELECT \n", "TOP 5\n", "source_id, number_of_neighbours, number_of_mates, original_ext_source_id\n", "FROM gaiadr2.panstarrs1_best_neighbour\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "job = Gaia.launch_job_async(query=query)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "scrolled": true }, "outputs": [], "source": [ "results = job.get_results()\n", "results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The Pan-STARRS table\n", "\n", "Here's the metadata for the table that contains the Pan-STARRS data." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "meta = Gaia.load_table('gaiadr2.panstarrs1_original_valid')" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "print(meta)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And here are the columns." ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "for column in meta.columns:\n", " print(column.name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's the [documentation for these variables]() .\n", "\n", "The ones we'll use are:\n", "\n", "* `obj_id`, which we will match up with `original_ext_source_id` in the best neighbor table.\n", "\n", "* `g_mean_psf_mag`, which contains mean magnitude from the `i` filter.\n", "\n", "* `i_mean_psf_mag`, which contains mean magnitude from the `i` filter.\n", "\n", "Here's a query that selects these variables and returns the first 5 rows." ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "query = \"\"\"SELECT \n", "TOP 5\n", "obj_id, g_mean_psf_mag, i_mean_psf_mag \n", "FROM gaiadr2.panstarrs1_original_valid\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "job = Gaia.launch_job_async(query=query)" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "scrolled": true }, "outputs": [], "source": [ "results = job.get_results()\n", "results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following figure shows how these tables are related.\n", "\n", "* The orange circles and arrows represent the first `JOIN` operation, which takes each `source_id` in the Gaia table and finds the same value of `source_id` in the best neighbor table.\n", "\n", "* The blue circles and arrows represent the second `JOIN` operation, which takes each `original_ext_source_id` in the Gaia table and finds the same value of `obj_id` in the best neighbor table.\n", "\n", "There's no guarantee that the corresponding rows of these tables are in the same order, so the `JOIN` operation involves some searching.\n", "However, ADQL/SQL databases are implemented in a way that makes this kind of source efficient.\n", "If you are curious, you can [read more about it](https://chartio.com/learn/databases/how-does-indexing-work/)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Joining tables\n", "\n", "Now let's get to the details of performing a `JOIN` operation.\n", "As a starting place, let's go all the way back to the cone search from Lesson 2." ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "query_cone = \"\"\"SELECT \n", "TOP 10 \n", "source_id\n", "FROM gaiadr2.gaia_source\n", "WHERE 1=CONTAINS(\n", " POINT(ra, dec),\n", " CIRCLE(88.8, 7.4, 0.08333333))\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And let's run it, to make sure we have a working query to build on." ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "from astroquery.gaia import Gaia\n", "\n", "job = Gaia.launch_job_async(query=query_cone)" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "scrolled": true }, "outputs": [], "source": [ "results = job.get_results()\n", "results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can start adding features.\n", "First, let's replace `source_id` with a format specifier, `columns`: " ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "query_base = \"\"\"SELECT \n", "{columns}\n", "FROM gaiadr2.gaia_source\n", "WHERE 1=CONTAINS(\n", " POINT(ra, dec),\n", " CIRCLE(88.8, 7.4, 0.08333333))\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here are the columns we want from the Gaia table, again. " ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [], "source": [ "columns = 'source_id, ra, dec, pmra, pmdec'\n", "\n", "query = query_base.format(columns=columns)\n", "print(query)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And let's run the query again." ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "job = Gaia.launch_job_async(query=query)" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "scrolled": true }, "outputs": [], "source": [ "results = job.get_results()\n", "results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adding the best neighbor table\n", "\n", "Now we're ready for the first join.\n", "The join operation requires two clauses:\n", "\n", "* `JOIN` specifies the name of the table we want to join with, and\n", "\n", "* `ON` specifies how we'll match up rows between the tables.\n", "\n", "In this example, we join with `gaiadr2.panstarrs1_best_neighbour AS best`, which means we can refer to the best neighbor table with the abbreviated name `best`.\n", "\n", "And the `ON` clause indicates that we'll match up the `source_id` column from the Gaia table with the `source_id` column from the best neighbor table. " ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "query_base = \"\"\"SELECT \n", "{columns}\n", "FROM gaiadr2.gaia_source AS gaia\n", "JOIN gaiadr2.panstarrs1_best_neighbour AS best\n", " ON gaia.source_id = best.source_id\n", "WHERE 1=CONTAINS(\n", " POINT(gaia.ra, gaia.dec),\n", " CIRCLE(88.8, 7.4, 0.08333333))\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**SQL detail:** In this example, the `ON` column has the same name in both tables, so we could replace the `ON` clause with a simpler [`USING` clause](https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljusing.html):\n", "\n", "```\n", "USING(source_id)\n", "```\n", "\n", "Now that there's more than one table involved, we can't use simple column names any more; we have to use **qualified column names**.\n", "In other words, we have to specify which table each column is in.\n", "Here's the complete query, including the columns we want from the Gaia and best neighbor tables." ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "column_list = ['gaia.source_id',\n", " 'gaia.ra',\n", " 'gaia.dec',\n", " 'gaia.pmra',\n", " 'gaia.pmdec',\n", " 'best.best_neighbour_multiplicity',\n", " 'best.number_of_mates',\n", " ]\n", "columns = ', '.join(column_list)\n", "\n", "query = query_base.format(columns=columns)\n", "print(query)" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "job = Gaia.launch_job_async(query=query)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "scrolled": true }, "outputs": [], "source": [ "results = job.get_results()\n", "results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that this result has fewer rows than the previous result.\n", "That's because there are sources in the Gaia table with no corresponding source in the Pan-STARRS table.\n", "\n", "By default, the result of the join only includes rows where the same `source_id` appears in both tables.\n", "This default is called an \"inner\" join because the results include only the intersection of the two tables.\n", "[You can read about the other kinds of join here](https://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adding the Pan-STARRS table\n", "\n", "### Exercise\n", "\n", "Now we're ready to bring in the Pan-STARRS table. Starting with the previous query, add a second `JOIN` clause that joins with `gaiadr2.panstarrs1_original_valid`, gives it the abbreviated name `ps`, and matches `original_ext_source_id` from the best neighbor table with `obj_id` from the Pan-STARRS table.\n", "\n", "Add `g_mean_psf_mag` and `i_mean_psf_mag` to the column list, and run the query.\n", "The result should contain 490 rows and 9 columns." ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Selecting by coordinates and proper motion\n", "\n", "Now let's bring in the `WHERE` clause from the previous lesson, which selects sources based on parallax, BP-RP color, sky coordinates, and proper motion.\n", "\n", "Here's `query6_base` from the previous lesson." ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [], "source": [ "query6_base = \"\"\"SELECT \n", "{columns}\n", "FROM gaiadr2.gaia_source\n", "WHERE parallax < 1\n", " AND bp_rp BETWEEN -0.75 AND 2 \n", " AND 1 = CONTAINS(POINT(ra, dec), \n", " POLYGON({point_list}))\n", " AND 1 = CONTAINS(POINT(pmra, pmdec),\n", " POLYGON({pm_point_list}))\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's reload the Pandas `Series` that contains `point_list` and `pm_point_list`." ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "\n", "filename = 'gd1_data.hdf'\n", "point_series = pd.read_hdf(filename, 'point_series')\n", "point_series" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can assemble the query." ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [], "source": [ "columns = 'source_id, ra, dec, pmra, pmdec'\n", "\n", "query6 = query6_base.format(columns=columns,\n", " point_list=point_series['point_list'],\n", " pm_point_list=point_series['pm_point_list'])\n", "\n", "print(query6)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Again, let's run it to make sure we are starting with a working query." ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [], "source": [ "job = Gaia.launch_job_async(query=query6)" ] }, { "cell_type": "code", "execution_count": 57, "metadata": { "scrolled": true }, "outputs": [], "source": [ "results = job.get_results()\n", "results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise\n", "\n", "Create a new query base called `query7_base` that combines the `WHERE` clauses from the previous query with the `JOIN` clauses for the best neighbor and Pan-STARRS tables.\n", "Format the query base using the column names in `column_list`, and call the result `query7`.\n", "\n", "Hint: Make sure you use qualified column names everywhere!\n", "\n", "Run your query and download the results. The table you get should have 3725 rows and 9 columns." ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Checking the match\n", "\n", "To get more information about the matching process, we can inspect `best_neighbour_multiplicity`, which indicates for each star in Gaia how many stars in Pan-STARRS are equally likely matches." ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "results['best_neighbour_multiplicity']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It looks like most of the values are `1`, which is good; that means that for each candidate star we have identified exactly one source in Pan-STARRS that is likely to be the same star.\n", "\n", "To check whether there are any values other than `1`, we can convert this column to a Pandas `Series` and use `describe`, which we saw in in Lesson 3." ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "\n", "multiplicity = pd.Series(results['best_neighbour_multiplicity'])\n", "multiplicity.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In fact, `1` is the only value in the `Series`, so every candidate star has a single best match.\n", "\n", "Similarly, `number_of_mates` indicates the number of *other* stars in Gaia that match with the same star in Pan-STARRS." ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [], "source": [ "mates = pd.Series(results['number_of_mates'])\n", "mates.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All values in this column are `0`, which means that for each match we found in Pan-STARRS, there are no other stars in Gaia that also match. \n", "\n", "**Detail:** The table also contains `number_of_neighbors` which is the number of stars in Pan-STARRS that match in terms of position, before using other criteria to choose the most likely match. But we are more interested in the final match, using both criteria." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Transforming coordinates\n", "\n", "Here's the function we've used to transform the results from ICRS to GD-1 coordinates." ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [], "source": [ "import astropy.units as u\n", "from astropy.coordinates import SkyCoord\n", "from gala.coordinates import GD1Koposov10\n", "from gala.coordinates import reflex_correct\n", "\n", "def make_dataframe(table):\n", " \"\"\"Transform coordinates from ICRS to GD-1 frame.\n", " \n", " table: Astropy Table\n", " \n", " returns: Pandas DataFrame\n", " \"\"\"\n", " skycoord = SkyCoord(\n", " ra=table['ra'], \n", " dec=table['dec'],\n", " pm_ra_cosdec=table['pmra'],\n", " pm_dec=table['pmdec'], \n", " distance=8*u.kpc, \n", " radial_velocity=0*u.km/u.s)\n", "\n", " gd1_frame = GD1Koposov10()\n", " transformed = skycoord.transform_to(gd1_frame)\n", " skycoord_gd1 = reflex_correct(transformed)\n", "\n", " df = table.to_pandas()\n", " df['phi1'] = skycoord_gd1.phi1\n", " df['phi2'] = skycoord_gd1.phi2\n", " df['pm_phi1'] = skycoord_gd1.pm_phi1_cosphi2\n", " df['pm_phi2'] = skycoord_gd1.pm_phi2\n", " return df" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now can transform the result from the last query." ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ "candidate_df = make_dataframe(results)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And see how it looks." ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "x = candidate_df['phi1']\n", "y = candidate_df['phi2']\n", "plt.plot(x, y, 'ko', markersize=0.5, alpha=0.5)\n", "\n", "plt.xlabel('phi1 (degree GD1)')\n", "plt.ylabel('phi2 (degree GD1)');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result is similar to what we saw in the previous lesson, except that have fewer stars now, because we did not find photometry data for all of the candidate sources." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Saving the DataFrame\n", "\n", "Let's save this `DataFrame` so we can pick up where we left off without running this query again.\n", "The HDF file should already exist, so we'll add `candidate_df` to it." ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [], "source": [ "filename = 'gd1_data.hdf'\n", "\n", "candidate_df.to_hdf(filename, 'candidate_df')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use `getsize` to confirm that the file exists and check the size:" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [], "source": [ "from os.path import getsize\n", "\n", "MB = 1024 * 1024\n", "getsize(filename) / MB" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary\n", "\n", "In this notebook, we used database `JOIN` operations to select photometry data for the stars we've identified as candidates to be in GD-1.\n", "\n", "In the next notebook, we'll use this data for a second round of selection, identifying stars that have photometry data consistent with GD-1.\n", "\n", "But before you go on, you might be interested in another file format, CSV." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## CSV\n", "\n", "Pandas can write a variety of other formats, [which you can read about here](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html).\n", "We won't cover all of them, but one other important one is [CSV](https://en.wikipedia.org/wiki/Comma-separated_values), which stands for \"comma-separated values\".\n", "\n", "CSV is a plain-text format that can be read and written by pretty much any tool that works with data. In that sense, it is the \"least common denominator\" of data formats.\n", "\n", "However, it has an important limitation: some information about the data gets lost in translation, notably the data types. If you read a CSV file from someone else, you might need some additional information to make sure you are getting it right.\n", "\n", "Also, CSV files tend to be big, and slow to read and write.\n", "\n", "With those caveats, here's how to write one:" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [], "source": [ "candidate_df.to_csv('gd1_data.csv')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can check the file size like this:" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [], "source": [ "getsize('gd1_data.csv') / MB" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see the first few lines like this:" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [], "source": [ "def head(filename, n=3):\n", " \"\"\"Print the first `n` lines of a file.\"\"\"\n", " with open(filename) as fp:\n", " for i in range(n):\n", " print(next(fp))" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [], "source": [ "head('gd1_data.csv')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The CSV file contains the names of the columns, but not the data types.\n", "\n", "We can read the CSV file back like this:" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [], "source": [ "read_back_csv = pd.read_csv('gd1_data.csv')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's compare the first few rows of `candidate_df` and `read_back_csv`" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [], "source": [ "candidate_df.head(3)" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [], "source": [ "read_back_csv.head(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that the index in `candidate_df` has become an unnamed column in `read_back_csv`. The Pandas functions for writing and reading CSV files provide options to avoid that problem, but this is an example of the kind of thing that can go wrong with CSV files." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Best practices\n", "\n", "* Use `JOIN` operations to combine data from multiple tables in a databased, using some kind of identifier to match up records from one table with records from another.\n", "\n", "* This is another example of a practice we saw in the previous notebook, moving the computation to the data.\n", "\n", "* For most applications, saving data in FITS or HDF5 is better than CSV. FITS and HDF5 are binary formats, so the files are usually smaller, and they store metadata, so you don't lose anything when you read the file back.\n", "\n", "* On the other hand, CSV is a \"least common denominator\" format; that is, it can be read by practically any application that works with data." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "celltoolbar": "Tags", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" } }, "nbformat": 4, "nbformat_minor": 4 }