Category: Allgemein

  • Adding data to a SAS dataset

    This short article describes how to add two files with data to a SAS dataset. Assume both files use the same format for the data.

    The first approach uses a more or less standard technique wereby a global variable (fileref) is created that refers to two files.

    filename gegs ('C:\Users\tomva\SynologyDrive\SAS\gegs.txt' 'C:\Users\tomva\SynologyDrive\SAS\gegs2.txt');
    data ff;
    infile gegs;
    input nummer 1-3 naam $;
    run;
    

    The second approach creates a place holder that is linked to a file variable that is loaded with different file names. Each file is read sequentially. While the SAS read procedure loops through the records, each record is written to the target SAS dataset with the output statement.

    data score45;
    infile datalines;
    length rfile $60;
    input rfile $;
    infile PH filevar=rfile end=lastobs;
    do until (lastobs);
    input nummer naam $;
    output;
    end;
    datalines;
    C:\Users\tomva\SynologyDrive\SAS\gegs.txt
    C:\Users\tomva\SynologyDrive\SAS\gegs2.txt
    ;
    run;
  • Exporting data from Teradata

    Recently, I came across the so-called fast export facility in Teradata. This facility allows you to export data from Teradata in a relative fast way. Let us look at the script:

    .LOGTABLE tom.invoer_log;  
     .logon 192.168.178.13/tom,******;
     database tom;
     .BEGIN EXPORT SESSIONS 2;  
           .EXPORT OUTFILE C:\Users\tomva\Documents\invoer.txt  
           MODE RECORD FORMAT TEXT;
           SELECT CAST(leeftijd AS CHAR(10)), 
              CAST(nummer AS CHAR(10))   
           FROM
           invoer;
        .END EXPORT;
     .logoff;
    

    The script can be evoked by “fexp < t.txt”, t.txt being the name of the script. The output then looks like:

  • Teradata BTEQ

    Teradata is a DBMS that is more or less created to handle massive amounts of data. I now work with it and this DBMS is able to handle 500 million rows in a split second. Brilliant. Teradata has a tool BTEQ that can be used to run scripts. Let us show a very simple script:

    .logon 192.168.178.13/tom,*********
     database tom;
     select * from invoer;
     .logoff

    This script can be run with the command “C:\Program Files (x86)\Teradata\Client\15.00\bin>bteq<C:\Users\tomva\Documents\s.txt”

    The output looks as:

  • SVN version controller

    Recently, I came accross the SVN version control mechanism. The idea is that we have a so-called working directory that acts as a source for a final version of some documents. Once we have a final version, the final version can be committed to another platform. This other platform can be accessed by others.

    If we have a revised version, it can be subsequently committed. This revised version can then be accessed by others to want to have the revised version.

    Let us look at the working directory. This looks like:

    The .svn folder indicates that we have a working directory that contains files that may act as a final version of a document. Let us assume for the moment that “test.txt” may be used as a document that can be committed as a final version.

    On the other hand, let us look at the platform where others may find the final version:

    The platform is a website where documents can be accessed as final versions. We may download file ” test.txt” to see the latest committed version. We also see that we have version “r2” as the latest version.

    How do we commit a next version as a final version?

    The first command is “svn update”, whereby it is indicated that test.txt is changed in the working directory.

    The second command is “svn commit -m “1234 toegevoegd””

    We then see that the file is updated.

    A new version “r3” is then shown.

  • SAS en Teradata

    Currently, I work with SAS and teradata. I notice, we have two possibilities to connect SAS to teradata. One possibility is to create a remote library. The definition is:

    libname Td_direc teradata
    tdpid ="127.0.0.1"
    user="tduser"
    password="tduser"
    database="financial";
    

    Another possibility is to create an explicit connection:

    proc sql;
    connect to teradata as td(tdpid="127.0.0.1"
    user="tduser"
    password="tduser"
    database="financial");
    create table work.dataX as
    select *
    from connection to td
    (select * from dataX);
    quit;

    This explicit connection can also be used to create a table on teradata:

    proc sql;
    connect to teradata as td(tdpid="127.0.0.1"
    user="tduser"
    password="tduser"
    database="financial");
    execute
    (create table dataY(x integer, y integer))
    by td;
    execute(commit work) by td;
    quit;
  • Getting data from an API

    Once an API is running, we may start a client. This client fires a call. This call is fired with “requests.get”. Between the brackets, we see a call that could be run from any webbrowser.

    The reponse can then be received with response.json()

    The json is very similar to a dataframe. The dataframe can then be set up by reading a row in the json and appending the row to the dataframe.

    import requests
    import pandas as pd
    doel = []
    df = pd.DataFrame(doel, columns=["Author", "FirstLine", "Index", "Year", "Title"])
    response = requests.get("http://127.0.0.1:5000/api/v1/resources/books/all")
    if (response.status_code == 200):
      print('Status code: ',response.status_code)
      data = response.json()
      for i in range(len(data)):
        rij = data[i]
        df = df.append([[]])
        df.iloc[i] = rij
    elif (response.status_code == 404) :
      print("Result not found!")
      print('Nmbr rows: ',df.shape[0],' Nmbr columns: ',df.shape[1])
  • Server App for APIs

    I found a brilliant script to handle API requests. I noticed three elements here: it contains a server process, it is able to receive a call and it is able to return results.

    The script:

    import flask
    from flask import request, jsonify
    import pyodbc
    import pandas as pd
    app = flask.Flask(name)
    app.config["DEBUG"] = True
    def dict_factory(cursor, row):
      d = {}
      for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
      return d
    @app.route('/', methods=['GET'])
    def home():
      return '''Distant Reading Archive'''
    @app.route('/api/v1/resources/books/all', methods=['GET'])
    def api_all():
      connStr =       pyodbc.connect('DSN=AzureSQL;UID=tomvanmaanen;PWD=****')
      cursor = connStr.cursor()
      data = []
      rows = cursor.execute('SELECT * FROM books;').fetchall()
      for row in rows:
        data.append([x for x in row])
      cursor.close()
      connStr.close()
      return jsonify(data)
    @app.errorhandler(404)
    def page_not_found(e):
      return "404 The resource could not be found.", 404
    @app.route('/api/v1/resources/books', methods=['GET'])
    def api_filter():
      query_parameters = request.args
      id = query_parameters.get('id')
      published = query_parameters.get('published')
      author = query_parameters.get('author')
      query = "SELECT * FROM books WHERE"
      to_filter = []
      if id:
        query += ' id=? AND'
        to_filter.append(id)
      if published:
        query += ' published=? AND'
        to_filter.append(published)
      if author:
        query += ' author=? AND'
        to_filter.append(author)
      if not (id or published or author):
        return page_not_found(404)
      query = query[:-4] + ';'
      connStr = pyodbc.connect('DSN=AzureSQL;UID=tomvanmaanen;PWD=*****')
      cursor = connStr.cursor()
      data = []
    rows = cursor.execute(query, to_filter).fetchall()
    for row in rows:
      data.append([x for x in row])
    cursor.close()
    connStr.close()
    return jsonify(data)
    app.run()

    This API can be called by two different calls:

    http://127.0.0.1:5000/api/v1/resources/books?author=Connie+Willis 

    or

     http://127.0.0.1:5000/api/v1/resources/books/all

    It can be see in the code what happens. If we call http://127.0.0.1:5000/api/v1/resources/books/all, we see that a function is used that is provided after the definition of “/api/v1/resources/books/all”. In that function, we a sql is fired that is “SELECT * FROM books;”. We see that the query results are returned as a json file.

    As it is a GET call, the results are simply returned to the client.

    If we call “127.0.0.1:5000/api/v1/resources/books?author=Connie+Willis”, we see what happens after the definition /api/v1/resources/books, in combination with some arguments. The arguments are provided after the ? mark. We see that parameter author is used. When that parameter is used, a query is used that is formulated as “SELECT * FROM books WHERE author = Connie+Willis”

    
    
  • Python using API

    A small example on using an API is provided below. I have attempted to make the programme as small as possible. It shows how the response is derived. This response is then translated into a dataframe. this dataframe is then split into keys and values.

    import requests
    import pandas as pd
    response = requests.get("http://api.open-notify.org/astros.json")
    if (response.status_code == 200):
      dataframe = pd.DataFrame.from_dict(response.json(),   orient="Index")
      ff=dataframe.iloc[2]
      w = ff[0]
      for j in range(len(w)):
        for key, value in w[j].items():
        print('key ',key,' value ',value)
    elif (response.status_code == 404) :
      print("Result not found!")
  • Python retrieve data from an API & store in a table

    This script combines many Python features, I used in the last few months.

    The idea is a file is read that contains parameters that are used is a API call. The result is then analysed and split in different data element. Finally, some data are stored in a dataframe that is subsequently read in a table.

    Reading the data is done with a method within the dataframes. The dataframe library is extensively used here. One method is “read_csv” which allows to read a csv file. While reading such a csv file, we are allowed to use parameters that describe the csv file. One parameter is the name of the file; another is the header that indicates if a header record exists or not. It is good to realise that the headers are used as column names. This implies that we may use the header to address in the column that is created with the dataframe.

    The result from that read is subsequently stored in a dataframe.

    That dataframe is then processed row by row. The row is a series that is transformed into a dictionary (key / value structure).

    This dictionary is then used as a parameter in an API call.

    See below

    import requests
     import csv
     import pyodbc
     import glob
     import pandas as pd
     import pyodbc
     from sqlalchemy import create_engine
     teller = 0
     resultaat = pd.DataFrame([['','']])
     print(resultaat.shape[0],resultaat.shape[1])
     df = pd.read_csv("C:\Users\tmaanen\documents\Cloudstation\pensioenfonds\moeilijk\c.csv", header=0, squeeze=True)
     top = len(df)
     for i in range(top):
         rij = df.iloc[i]
         dict_from_csv = rij.to_dict()
         print(dict_from_csv)
         response = requests.get('http://api.open-notify.org/iss-pass.json', params=dict_from_csv)
         dataframe = pd.DataFrame.from_dict(response.json(), orient="Index")
         ff=dataframe.iloc[0]
         for key, value in ff.items():
             print('key ',key,' value ',value)
         ff=dataframe.iloc[1] 
         for key, value in ff.items():     
              print('key ',key,' value ',value)     
               w = value     
               for key, value in w.items():         
                     print('key ',key,' value ',value)   
          ff=dataframe.iloc[2] 
          print(ff) 
          for i in range(len(ff)):     
          w = ff[i]     
          print(len(w),' ',w)     
          for i in range(len(w)):         
               w1 = w[i]         
               for key, value in w1.items():             
                   print('key ',key,' value ',value)             
                   if key == 'duration': 
                      resultaat.iloc[teller,0] = value             
                   if key == 'risetime':  
                   resultaat.iloc[teller,1] = value 
                       teller = teller + 1                 
                       resultaat =        resultaat.append(pd.DataFrame([['','']]), ignore_index=True)                  print(resultaat.shape[0],resultaat.shape[1])
     
    engine = create_engine("mssql+pyodbc://tomvanmaanen:*******@AzureSQL")
    resultaat.to_sql('nix', schema='dbo', con = engine, chunksize=100, method='multi', index=False, if_exists='replace')

    The c.csv file looks like:

    lat,lon
    5, 50
    6, 45
    -1, 50
    10,45
    15,40
  • Function in Python Dataframe

    Whenever we have a data in a dataframe, we might have the urge to change the values. Below, three situations will be investigated.

    The first situation is the situation, whereby one field will be taken into account. The first approach is a one line creation of such transformation.

    df["Birthdate"].astype(str).apply(lambda x : datetime.strptime(x, '%Y-%m-%d') if x != 'None' else '')

    The dataframe is called df. One column can be addressed as df[“column name”]. This leads to a series that must be transformed into a string. That string is then translated into a date.

    A second situation is a situation where a function is created. That function can be created with:

    def _datum(s):
      if s!= 'None':
        return datetime.strptime(s, '%Y-%m-%d')
      else:
        return ''

    That function can be used subsequently as:

    df["Date_of_Death__c"].astype(str).apply(_datum)

    A third situation is a situation where several fields are needed to create a new value. We then create a function like:

    def lange_naam(row):
    FirstName = row[4]
    LastName = row[6]
    if FirstName is not None and LastName is not None:
    if len(FirstName + LastName) > 20:
    return 'LangeNaam'
    else:
    return 'Valt wel Mee'
    else:
    return 'Zooi'

    Then can then be used as:

    df.apply(lange_naam, axis="columns")