Dealing with legacy code contains ‘xrange’ in Python 2.7

Python 3.x has been around since 2008 but 2.7.x is still around and continues used in current development. While doing machine learning, one of the most used function is ‘xrange’ in loops. But ‘xrange’ has been replaced with ‘range’ in 3.x. Here is a good practice for writing code that’s compatible with both Python 2 and 3.x.



except NameError:

xrange = range

For Python 2.7 die-hard fans switching to 3.x, you can define ‘xrange’ as following:

def xrange(x):

return iter(range(x))



Understand blockchain with Simply Python Code

Everybody knows Bitcoin now but not everyone knows how blockchain technology works. The blockchain is like a distributed ledger which is a consensus of replicated, shared and synchronized digital data geographically spread across multiple sites and there is no centralized data storage. This is different from centralized and decentralized storage. See illustration image here:


In another word, blockchain is a public data storage where every new data is stored in a ‘block’ container and inserted into an immutable chain with past data. In terms of bitcoin or other coins, these data are a series of the transaction record. Of course, the data stored here can be anything. The blockchain technology is supposed to be more secure and hack-proof since the computation resources required to hack it is unimaginable.

Here, I’ll show a simple Python code to demonstrate how blockchain works:

The code structure is like this shown in Eclipse:

Screen Shot 2017-12-10 at 12.34.35 PM

The Python code is shown below:Screen Shot 2017-12-10 at 12.35.57 PMScreen Shot 2017-12-10 at 12.35.40 PMScreen Shot 2017-12-10 at 12.35.49 PM

Let’s look at the blockchain created:

Screen Shot 2017-12-10 at 12.39.43 PM.png

As seen in the code, each block contains the hash of the previous block. And this makes it’s hard to modify the blockchain. In practice, there are other restriction to make each new block harder to generate. For example, you can restrict new block to all start with nth zero in the new hash. The more leading zero will make it harder to generate a new block. The way it is distributed requires that a new legitimate block need to be voted ‘valid’ by at least 51% of public storage holder.



How to clear all in python Spyder workspace

While doing data analysis, sometimes we want clear everything in current workspace to have a fresh environment. It is similar to Matlab’s ‘clear all’ function. Here is how the function looks like (

def clear_all():
“””Clears all the variables from the workspace of the spyder application.”””
gl = globals().copy()
for var in gl:
if var[0] == ‘_’: continue
if ‘func’ in str(globals()[var]): continue
if ‘module’ in str(globals()[var]): continue

del globals()[var]
if __name__ == “__main__”:

Converting local time to UTC and vice verse in Python

When dealing with global data time series, we often encounter data in different time zones. Here I’ll share with the python scripts that created to address this issue:

  1. Converting from local to UTC

# e.g. local_to_utc(t.timetuple())

import time,calendar
import datetime

def local_to_utc(t_tuple):
secs = time.mktime(t_tuple)
utcStruct = time.gmtime(secs)
return datetime.datetime(*utcStruct[:6])

2. Converting from UTC to local time

# e.g.: utc_to_local(t.timetuple()):

import time
import calendar
import datetime
def utc_to_local(t_tuple):
secs = calendar.timegm(t_tuple)
localStruct = time.localtime(secs)
return datetime.datetime(*localStruct[:6])

Pandas– ValueError: If using all scalar values, you must pass an index

For Python users, we all know that it is very convenient to create a data frame from a dictionary. For example:

df = pd.DataFrame({‘Key’:[‘a’,’b’,’c’,’d’], ‘Value’:[1,2,3,4]})

It works beautifully when the values is a list/dict with multiple columns. However, you may encounter into syntax errors ValueError: If using all scalar values, you must pass an index” when you try to convert the following dictionary to a data frame.

dict_test = {


‘pulled pork’:’pig’,

‘pastrami’: ‘cow’,

‘honey ham’:’pip’,

‘nova lox’: ‘salmon’


df = pd.DataFrame.from_dict(dict_test)

Why is that?

While pandas create data frame from a dictionary, it is expecting its value to be a list or dict. If you give it a scalar, you’ll also need to supply index. In this example, the values are ‘pig’ instead of [‘pig’].

How to fix it:

  1. Change the data to:

dict_test = {


‘pulled pork’:[‘pig’],

‘pastrami’: [‘cow’],

‘honey ham’:[‘pip’],

‘nova lox’: [‘salmon’]


2. Get the list items from the dictionary and add ‘list’ for Python 3.x.

pd.DataFrame.from_dict(list(dict_test.items()), columns = [‘food’,’animal’])

3. Specify the orientation with ‘index’.

pd.DataFrame.from_dict(dict_test, orient = ‘index’)

4. Pass the Series constructor instead:

s = pd.Series(dict_test, name = ‘animal’) = ‘Food’

df = pd.DataFrame(s)

Dealing with non-ASCII characters in R and Python

While dealing with an online dataset, especially global data, we’ll encounter non-ASCII characters very frequently. In this post,  I’ll take dealing with Chinese character as an example to show how to address this issue in R and Python.

In R:

Sys.getlocale()  #First get the system locale setting
Sys.setlocale(category = "LC_ALL", locale = "chs")  #cht for traditional chinese
print("测试")  # means test in chinese

# While reading data with non-ASCII files
data <- read.csv('file.csv',encoding = 'UTF-8')

Publish Shiny App with foreign languages.

Here are the tips when dealing with Shiny App that contains non-ASCII characters:

  1. Save the scripts with ‘save with Encoding’ –> choose ‘UTF-8’
  2. While dealing with I/O, add option encoding=’UTF-8′
  3. Publishing shiny app with say Chinese characters, do the following:
  • temp.enc <- options()$encoding
  • options(encoding=’UTF-8′)
  • deployApp(appDir=”your app’s root directory”)

Try not using options(‘UTF-8’) in the script, this will cause all I/O to be UTF-8.


In Python

In your python code, just add the following to your python script and save it.

# -*- coding: utf-8 -*-
print (u"你好".encode('utf-8'))

A quick hack for creating a series of template feature names in Python

Let’s say that I want to create a bunch of feature names with the format of ‘model_pow_1′,’model_pow_2′,’model_pow_3’ and to the Nth variable. It’s very easy to do so in R with just paste and seq function (e.g. paste(‘pow’,seq(1,5))). In python,  we can use list apprehension to accomplish the same thing but pay attention to the format tweak.

ind = [‘model_pow_%d’%i for i in range(1,10)]

Another way to do is using character concatenation.

ind=[‘model_pow_’+str(i) for  i in range(1,10)]