{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Pandas\n", "\n", "We want to be able to load the following csv file which quotation marks and additional commas:\n", "\n", "eg. \n", "\n", "`\"\",\"\",\"\"BSF\" code - Intermittant, see notes\",\"\"`\n", "\n", "should result in\n", "\n", " 0 1 2 3\n", " 0 , , \"BSF\" code - Intermittant, see notes, \n", " \n", "Let's fist make our data:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [], "source": [ "with open(\"file.csv\", 'w') as f:\n", " f.write(\"\\\"0\\\",\\\"1\\\",\\\"2\\\",\\\"3\\\"\\n\\\"\\\",\\\"\\\",\\\"\\\"BSF\\\" code - Intermittant, see notes\\\",\\\"\\\"\")" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\"0\",\"1\",\"2\",\"3\"\r\n", "\"\",\"\",\"\"BSF\" code - Intermittant, see notes\",\"\"" ] } ], "source": [ "!cat file.csv" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import pandas as pd" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Elzell's answer](http://stackoverflow.com/a/34043973/4244912):" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before stripping:\n", " \"0\" \"1\" \"2\" \"3\"\n", "0 \"\" \"\" \"\"BSF\" code - Intermittant, see notes\" \"\"\n", "\n", "After stripping:\n", " \"0\" \"1\" \"2\" \"3\"\n", "0 \"BSF\" code - Intermittant, see notes \n" ] } ], "source": [ "data = pd.read_csv(\"file.csv\",sep=r'(?<=\"),(?=\")',quotechar='\"', engine = 'python')\n", "print(\"Before stripping:\\n\",data)\n", "data = data.applymap(lambda s:s[1:-1])\n", "print(\"\\nAfter stripping:\\n\",data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This seems to work pretty well." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now I think the answer lies in considering `\",\"` to be the delimiter" ] } ], "metadata": { "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.5.0" } }, "nbformat": 4, "nbformat_minor": 0 }