Category: Allgemein

  • Accessing elements in Python dataframe

    A dataframe in Python can be compared to a table in a database. I also get idea that database functionalities are translated into functions that can be found in dataframes. It is also true that a database table can be quickly read into a dataframe. See:

    con = pyodbc.connect('DSN=AzureSQL;UID=tomvanmaanen;PWD=*******')
    cur = con.cursor()
    sql = 'SELECT * FROM AXYWARE.DEELNEMERS_CSV'
    df = pd.read_sql(sql, con)

    So, we have a table in a database (AXYWARE.DEELNEMERS_CSV) that is read in a dataframe in just 4 lines of code.

    More or less the same holds for propagating the dataframe into a table:

    from sqlalchemy import create_engine
    engine = create_engine("mssql+pyodbc://tomvanmaanen:*******!@AzureSQL")
    ff.to_sql('Tax_Exception__c', schema='RAPPORTAGE', con = engine, chunksize=100, method='multi', index=False, if_exists='replace')

    Just 3 lines of code, including importing a library to propagate a dataframe (ff) to a table (Tax_Exception__c).

    To access an element within a dataframe, we may either use the labels or the position. So we may use a label approach:

    df.loc[:,"FirstName"] to derive a column or df.loc[3,"FirstName"] to access a element

    Or we may use the positions:

    df.iloc[:,3] to derive a column or df.loc[3,4] to access a element

    In most cases, the label to identify a row is the same number that is used to identify a position. So:

    df.iloc[3] equals df.loc[3]
    

    However, the philosophy is different. With iloc we address a position. With loc, we address a label. As the label equals the position, the code is equal.

    It is also possible to use this type of coding to update a certain slice of your data frame:

    df.loc[(df['BRPStreetName__c'] == 'Waterlelie') & (df['BRPCityName__c'] == 'GOUDA'),'LastName'] = 'testName'

    Somehow, the ‘loc’ method seems to refer to the same memory position as the original dataframe. this then means that if a slice of the dataframe is referred to by .loc, we may change the content.

  • Copying data from Salesforce to SQL Server

    It can be handy to copy data from Salesforce to SQL Server if one would like to analyse the data. After all, the query language in Salesforce is not easy to use, whereas SQL Server allows easy access to data, good analytical possibilities and rapid response time.

    Currently, Python is my favorite tool. It allows to achieve great results with a minimum of effort.

    The Python code to do so is:

    from simple_salesforce import Salesforce
    import pandas as pd
    import pyodbc
    from sqlalchemy import create_engine
    sf = Salesforce(username='tom', password='wacht', security_token='abc')
    stmt = "SELECT field1, field2 FROM Table"
    queryOutput = sf.query_all(stmt)
    ff = pd.DataFrame(queryOutput['records'])
    if ff.empty==False:
      ff.drop(ff.columns[0], axis=1, inplace=True)
      nmbrRows = ff.shape[0]
      print("Number of rows in Salesforce "+ str(nmbrRows))
    else:
      print('No records in Salesforce')
    engine = create_engine("mssql+pyodbc://user:psw@dsn")
    ff.to_sql('Table', schema='dbo', con = engine, chunksize=100, method='multi', index=False, if_exists='replace')
  • Using Python to send http commands

    I now play with Python to communicate with HTTP servers. The idea that signals are sent to a server and the answer is subsequently analysed. My first attempt is shown below:

    import urllib3
    http = urllib3.PoolManager()
    resp = http.request('GET', 'https://archief.van-maanen.com/')
    print(resp.data)
    print(resp.status)
     

    the output can be seen as a series of symbols that can be stored in an html file that can be read with any Internet browser.

  • CRUD on Salesforce with Python

    I wrote four programmes in Python that enable us to maintain tables in Salesforce. The four functionalities are: creating data, reading data, updating data and deleting data.

    The programmes

    The programmes are stored in accompanying zip file. The programmes follow more or less the same logic. The first part is getting access to the system. Then a job is opened. Subsequently, data are added or modified. Finally, the job is closed.

  • SOQL / Querying salesforce

    Salesforce is a CRM tool that allows monitoring customer contacts. It also allows following leads. For back ground technicians, it is interesting to know that it is possible to query the data. The structure of the query language resembles a bit SQL. The structure “select fields from table”may sound familiar to our ears. However SOQL misses a join. Instead a different concept is provided. This can be shown with two examples:

    SELECT lastname, BSN__c, (select Start_date_participation__c from Participations__r) FROM Contact where Lastname = 'Bont'
    
    Select Id, Start_date_participation__c, End_date_participation__c, (select EntitlementType_Ent__c from Entitlements__r) from Participation__c where Id = 'a0Q6E0000078949UAA'

    The structure is as follows. We recognise that within the field list, a separate sub query is formulated that uses the relationship name after the key word “from”, In the examples above, relations are called Participations__r and Entitlements__r. From that relation name, the query engine knows how to the link the data from the parent table with data from the child table. The child table is not shown – in stead the relationship is used.

  • New script to set up user on SQL Server

    Herewith, I provide another script to set up a user in the SQL Server environment. The idea is that a role is created on the database. The user that is subsequently created is then added as a member to that role.

    First, the login is created. It is created on the master database.

    CREATE LOGIN kijker_Stagingzone WITH PASSWORD='****'
    GO
    CREATE USER kijker_Stagingzone FOR LOGIN kijker_Stagingzone WITH DEFAULT_SCHEMA=[dbo]
    GO

    Then the role is created on the database.

    CREATE ROLE db_Kijken_Stagingzone AUTHORIZATION [dbo]
    GO
    GRANT 
        SELECT
    ON SCHEMA::STAGINGZONE
        TO db_Kijken_Stagingzone
    GO

    Subsequently, a user is created and the user is added as a member to that role.

    CREATE USER kijker_Stagingzone
        FOR LOGIN kijker_Stagingzone
        WITH DEFAULT_SCHEMA = STAGINGZONE
    GO
    EXEC sp_addrolemember N'db_Kijken_Stagingzone', N'kijker_Stagingzone'
    GO

    see for the latest addition:

    use master

    drop user edgar

    CREATE LOGIN edgar WITH PASSWORD=”
    GO
    CREATE USER edgar FOR LOGIN edgar WITH DEFAULT_SCHEMA=[dbo]
    GO

    use sqlservertomvanmaanen
    drop user edgar

    CREATE USER edgar
    FOR LOGIN edgar
    WITH DEFAULT_SCHEMA = STAGINGZONE
    GO
    EXEC sp_addrolemember N’db_Lezer’, N’edgar’
    GO

  • Joining in Pandas

    Python has Pandas its tool to handle matrices, also known as dataframes in Pyhon speak. It is possible to join dataframes, much like joining tables. I found a nice example on the internet with several possible choices.

    As a first step, two dataframes were declared:

    import pandas as pd

    The first dataframe:

    customer=pd.DataFrame({
    'id':[1,2,3,4,5,6,7,8,9],
    'name':['Olivia','Aditya','Cory','Isabell','Dominic','Tyler','Samuel','Daniel','Jeremy'],
    'age':[20,25,15,10,30,65,35,18,23],
    'Product_ID':[101,0,106,0,103,104,0,0,107],
    'Purchased_Product':['Watch','NA','Oil','NA','Shoes','Smartphone','NA','NA','Laptop'],
    'City':['Mumbai','Delhi','Bangalore','Chennai','Chennai','Delhi','Kolkata','Delhi','Mumbai']
    })

    The second dataframe:

    product=pd.DataFrame({
    'Product_ID':[101,102,103,104,105,106,107],
    'Product_name':['Watch','Bag','Shoes','Smartphone','Books','Oil','Laptop'],
    'Category':['Fashion','Fashion','Fashion','Electronics','Study','Grocery','Electronics'],
    'Price':[299.0,1350.50,2999.0,14999.0,145.0,110.0,79999.0],
    'Seller_City':['Delhi','Mumbai','Chennai','Kolkata','Delhi','Chennai','Bengalore']
    })

    The inner join:

    ff_inner = pd.merge(product,customer,on= 'Product_ID')

    An outer join

    ff_outer = pd.merge(product,customer,left_on='Product_ID',right_on='Product_ID',how='outer',indicator=True)

    The left join is as follows:

    ff_left = pd.merge(product,customer,left_on=['Product_ID','Seller_City'],right_on=['Product_ID','City'],how='left')
  • Granting privs in SQL Server

    Granting privs in SQL Server is done in three steps. As first step, one must create a login to the SQL Server. This can be seen as getting the entrance to the data fort.

    CREATE LOGIN lezer
    WITH PASSWORD = 'password'
    GO

    One must then get entrance to the database. One must create a user who has access to the system files that steer the database.

    use master
    CREATE USER lezer
    FOR LOGIN lezer
    WITH DEFAULT_SCHEMA =dbo

    Subsequently, a user is created on the database itsself.

    use [sqlservertomvanmaanen]
    CREATE USER lezer
    FOR LOGIN lezer
    WITH DEFAULT_SCHEMA =dbo

    Then a role is created that provides a pattern of privs that is given to a user. A user is then added as a member to that role.

    CREATE ROLE [db_Lezer]
    ALTER ROLE [db_Lezer] ADD MEMBER lezer

    Finally, privs are granted to the role.

    GRANT CREATE FUNCTION TO [db_Lezer]
    GRANT CREATE PROCEDURE TO [db_Lezer]
    GRANT CREATE SCHEMA TO [db_Lezer]
    GRANT CREATE SYNONYM TO [db_Lezer]
    GRANT CREATE TABLE TO [db_Lezer]
    GRANT CREATE VIEW TO [db_Lezer]
    GRANT DELETE TO [db_Lezer]
    GRANT EXECUTE TO [db_Lezer]
    GRANT INSERT TO [db_Lezer]
    GRANT REFERENCES TO [db_Lezer]
    GRANT SELECT TO [db_Lezer]
    GRANT SHOWPLAN TO [db_Lezer]
    GRANT UPDATE TO [db_Lezer]
  • Dates in SQL server

    SQL Server is has several possibilities to calculate elapsed time (such as age). Two approaches are possible. The first idea is to calculate the number of hours and divide this by the number of hours in a year. The other possibility is to make a distinction between the number of a day in a month as compared between the first date and the last date.

    Let me first declare a first date. Let us think of a date of birth.

    DECLARE @dob date
    SET @dob='2001-01-22'

    Then the last date is declared.

    DECLARE @ref date
    SET @ref='2021-01-21'

    Another last date is declared whereby the first day in a month is taken.

    DECLARE @ref1 date
    SET @ref1=convert(date,convert(char(8),DATEPART(YEAR,@ref)10000+datepart(month,@ref)100+1),112)

    The first calculation provides an age.

    SELECT floor(DATEDIFF(hour,@dob,@ref)/8765.82) AS AgeYears

    The second calculation provides another calculation of an age.

    select CASE WHEN DATEPART(DAY, @ref) < DATEPART(DAY ,@dob)
    THEN DATEDIFF(YEAR, @dob, @ref) - 1
    ELSE DATEDIFF(YEAR, @dob, @ref)
    END as "Leeftijd"

    Then the difference is calculated between the date of birth and a first day in a month.

    select DATEDIFF(YEAR, @dob, @ref1) as "Leeftijd_Eerste_Maand"

  • Adding data to Salesforce

    Below, I provide a simple Python programme which allows to add data from an external table to Salesforce. The programme uses simple_salesforce as a library. In the first few lines, the necessary libraries are imported.

    from simple_salesforce import Salesforce
    import pyodbc
    import pandas as pd

    Then the connection to Salesforce is created.

    sf = Salesforce(username='datamigrationuser@pension4you.nl.pensiond2', password='password', security_token='security',domain='test')

    Whatever is found in Salesforce is subsequently removed:

    queryOutput = sf.query_all("Select Id, code__c, beschrijving__c from SALESFORCEBAK__C")
    queryOutputDF = pd.DataFrame(queryOutput['records'])
    print('Number of rows in salesforce NW',queryOutputDF.shape)
    for i in range(queryOutputDF.shape[0]):
    rec = sf.SALESFORCEBAK__C.delete(str(queryOutputDF.iloc[i,1]))
    if rec != 204:
    print(rec)

    Records from an external table are read.

    conn = pyodbc.connect('DSN=AzureSQL;UID=tomvanmaanen;PWD=password')
    cursor = conn.cursor()
    sql = 'SELECT top(100) [code__c],[beschrijving__c] FROM [KONTROLE].[SALESFORCEBAK__C]'
    df = pd.read_sql(sql, conn)
    cursor.close()

    The data are then added to Salesforce.

    for i in range(df.shape[0]):
    hx1 = str(df.iloc[i,0])
    hx2 = df.iloc[i,1]
    rec = sf.SALESFORCEBAK__C.create({'code__c' : hx1, 'beschrijving__c' : hx2 })
    if rec['success'] != True:
    print(rec)

    The programme terminates with a check on the number of records that are found in the table.

    queryOutput = sf.query_all("Select count(Id) from SALESFORCEBAK__C")
    queryOutputDF = pd.DataFrame(queryOutput['records'])
    print('Number of rows in salesforce NW ',queryOutputDF.iloc[0,1],' <<<<')