Skip to content

Instantly share code, notes, and snippets.

@pllim
Created November 29, 2016 14:59
Show Gist options
  • Save pllim/46288d2db5e21a1c21ac5f424077cac5 to your computer and use it in GitHub Desktop.
Save pllim/46288d2db5e21a1c21ac5f424077cac5 to your computer and use it in GitHub Desktop.
Custom converter for Massimo
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"from astropy.io import ascii"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"filename = 'zspec.txt' # Replace this with actual filename"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Define a custom converter.\n",
"# This is just quick proof of concept, optimize as needed.\n",
"def myconv(arr):\n",
" \"\"\"Replace D with E for each row in column.\"\"\"\n",
" arr = [x.replace('D', 'E') for x in arr]\n",
" return np.array(arr, dtype='float64')"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Tell reader to apply custom converters to columns of interest.\n",
"converters = {'col2': [(myconv, ascii.core.FloatType)],\n",
" 'col3': [(myconv, ascii.core.FloatType)]}"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Read the file as you did, but with custom converters.\n",
"data = ascii.read(filename, format='fixed_width_no_header',\n",
" names=('wl_A', '10_FL_DF', '10_BL_DF','other'),\n",
" col_starts=(0, 13, 25, 37), col_ends=(12, 24, 36, 137),\n",
" converters=converters)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Delete the useless column (so I can print it nicely)\n",
"del data['other']"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"wl_A 10_FL_DF 10_BL_DF\n",
"---- -------- --------\n",
" 1.0 -89.0947 -89.0947\n",
" 1.0 -89.0947 -89.0947\n"
]
}
],
"source": [
"data.pprint()"
]
}
],
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@mrobberto
Copy link

just perfect!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment