Showing posts with label pandas. Show all posts
Showing posts with label pandas. Show all posts

Monday, August 13, 2018

Curious memory consumption of pandas.unique()

Leave a Comment

While profiling the memory consumption of my algorithm, I was surprised that sometimes for smaller inputs more memory was needed.

It all boils down to the following usage of pandas.unique():

import numpy as np import pandas as pd import sys  N=int(sys.argv[1])  a=np.arange(N, dtype=np.int64) b=pd.unique(a) 

with N=6*10^7 it needs 3.7GB peak memory, but with N=8*10^7 "only" 3GB.

Scanning different input-size yields the following graph:

enter image description here

Out of curiosity and for self-education: How can the counterintuitive behavior (i.e. more memory for smaller input size) around N=5*10^7, N=1.3*10^7 be explained?


Here are the scripts for producing the memory consumption graph on Linux:

pandas_unique_test.py:

import numpy as np import pandas as pd import sys  N=int(sys.argv[1])     a=np.arange(N, dtype=np.int64) b=pd.unique(a) 

show_memory.py:

import sys import matplotlib.pyplot as plt    ns=[] mems=[] for line in sys.stdin.readlines():     n,mem = map(int, line.strip().split(" "))     ns.append(n)     mems.append(mem) plt.plot(ns, mems, label='peak-memory') plt.xlabel('n') plt.ylabel('peak memory in KB') ymin, ymax = plt.ylim() plt.ylim(0,ymax) plt.legend() plt.show() 

run_perf_test.sh:

WRAPPER="/usr/bin/time -f%M" #peak memory in Kb N=1000000 while [ $N -lt 100000000 ] do    printf "$N "    $WRAPPER python pandas_unique_test.py $N    N=`expr $N + 1000000` done  

And now:

sh run_perf_tests.sh  2>&1 | python show_memory.py 

1 Answers

Answers 1

Let's see...

pandas.unique says it's a "hash-table based unique".

It calls this function to acquire the correct hash table implementation for your data, namely htable.Int64HashTable.

The hash table is initialized with size_hint = the length of your value vector. That means kh_resize_DTYPE(table, size_hint) gets called.

Those functions are defined (templated) here in khash.h.

It seems to allocate (size_hint >> 5) * 4 + (size_hint) * 8 * 2 bytes of memory for the buckets (maybe more, maybe less, I might be off here).

Then, HashTable.unique() is called.

It allocates an empty Int64Vector, which seem to quadruple their size whenever they get filled, starting from 128.

It then iterates over your values, figuring out whether they're in the hash table; if not, they get added to both the hash table and the vector. (This is where the vector may grow; the hash table shouldn't need to grow due to the size hint.)

Finally, a NumPy ndarray is made to point at the vector.

So uh, I think you're seeing the vector size quadrupling at certain thresholds (which should be, if my late-night math stands,

>>> [2 ** (2 * i - 1) for i in range(4, 20)] [     128,     512,     2048,     8192,     32768,     131072,     524288,     2097152,     8388608,     33554432,     134217728,     536870912,     2147483648,     8589934592,     34359738368,     137438953472,     ..., ] 

Hope this sheds some light at things :)

Read More

Monday, July 30, 2018

How to forecast using the Tensorflow model?

Leave a Comment

I have created tensorflow program in order to for the close prices of the forex. I have successfully created the predcitions but failed understand the way to forecast the values for the future. See the following is my prediction function:

test_pred_list = []  def testAndforecast(xTest1,yTest1): #     test_pred_list = 0     truncated_backprop_length = 3     with tf.Session() as sess:     #     train_writer = tf.summary.FileWriter('logs', sess.graph)         tf.global_variables_initializer().run()         counter = 0 #         saver.restore(sess, "models\\model2298.ckpt")         try:             with open ("Checkpointcounter.txt","r") as file:                 value = file.read()         except FileNotFoundError:             print("First Time Running Training!....")           if(tf.train.checkpoint_exists("models\\model"+value+".ckpt")):             saver.restore(sess, "models\\model"+value+".ckpt")             print("models\\model"+value+".ckpt Session Loaded for Testing")         for test_idx in range(len(xTest1) - truncated_backprop_length):              testBatchX = xTest1[test_idx:test_idx+truncated_backprop_length,:].reshape((1,truncated_backprop_length,num_features))                     testBatchY = yTest1[test_idx:test_idx+truncated_backprop_length].reshape((1,truncated_backprop_length,1))               #_current_state = np.zeros((batch_size,state_size))             feed = {batchX_placeholder : testBatchX,                 batchY_placeholder : testBatchY}              #Test_pred contains 'window_size' predictions, we want the last one             _last_state,_last_label,test_pred = sess.run([last_state,last_label,prediction],feed_dict=feed)             test_pred_list.append(test_pred[-1][-1]) #The last one 

Here is the complete jupyter and datasets for test and train:
My repository with code.

Kindly, help me how I can forecast the close values for the future. Please do not share something related to predictions as I have tried. Kindly, let me know something that will forecast without any support just on the basis of training what I have given.

I hope to hear soon.

1 Answers

Answers 1

If I understand your question correctly, by forecasting you mean predicting multiple closing prices in future (for example next 5 closing prices from current state). I went through your jupyter notebook. In short, you can not easily do that.

Right now your code takes the last three positions defined by multiple futures (open/low/high/close prices and some indicators values). Based on that you predict next closing price. If you would like to predict even further position, you would have to create an "artificial" position based on the predicted closing price. Here you can approximate that open price is same as previous closing, but you can only guess high and low prices. Then you would calculate other futures/values (from indicators) and use this position with previous two to predict next closing price. You can continue like this for future steps.

The issue is in the open/low/high prices because you can only approximate them. You could remove them from data, retrain the model, and make predictions without them, but they may be necessary for indicators calculations.


I somehow compressed your code here to show the approach of predicting all OHLC prices:

# Data xTrain = datasetTrain[     ["open", "high", "low", "close", "k",      "d", "atr", "macdmain", "macdsgnal",      "bbup", "bbmid", "bblow"]].as_matrix() yTrain = datasetTrain[["open", "high", "low", "close"]].as_matrix()  # Settings batch_size = 1 num_batches = 1000 truncated_backprop_length = 3 state_size = 12  num_features = 12 num_classes = 4  # Graph batchX_placeholder = tf.placeholder(     dtype=tf.float32,     shape=[None, truncated_backprop_length, num_features],     name='data_ph') batchY_placeholder = tf.placeholder(     dtype=tf.float32,     shape=[None, num_classes],     name='target_ph')   cell = tf.contrib.rnn.BasicRNNCell(num_units=state_size) states_series, current_state = tf.nn.dynamic_rnn(     cell=cell,     inputs=batchX_placeholder,     dtype=tf.float32)  states_series = tf.transpose(states_series, [1,0,2])  last_state = tf.gather(     params=states_series,     indices=states_series.get_shape()[0]-1)  weight = tf.Variable(tf.truncated_normal([state_size, num_classes])) bias = tf.Variable(tf.constant(0.1, shape=[num_classes]))  prediction = tf.matmul(last_state, weight) + bias   loss = tf.reduce_mean(tf.squared_difference(last_label, prediction)) train_step = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)  # Training for batch_idx in range(num_batches):     start_idx = batch_idx     end_idx = start_idx + truncated_backprop_length       batchX = xTrain[start_idx:end_idx,:].reshape(batch_size, truncated_backprop_length, num_features)     batchY = yTrain[end_idx].reshape(batch_size, truncated_backprop_length, num_classes)       feed = {batchX_placeholder: batchX, batchY_placeholder: batchY}      _loss, _train_step, _pred, _last_label,_prediction = sess.run(         fetches=[loss, train_step, prediction, last_label, prediction],         feed_dict=feed) 

I think it is not important to write the whole code plus I don't know how are the indicators calculated. Also you should change way of data feeding because right now it only works with batches os size 1.

Read More

Monday, July 16, 2018

DataFrame - table in table from nested dictionary

Leave a Comment

I use python 3.

This is my data structure:

dictionary = {     'HexaPlex x50': {         'Vendor': 'Dell  Inc.',         'BIOS Version': '12.72.9',         'Newest BIOS': '12.73.9',         'Against M & S': 'Yes',         'W10 Support': 'Yes',         'Computers': {             'someName001': '12.72.9',             'someName002': '12.73.9',             'someName003': '12.73.9'         },         'Mapped Category': ['SomeOtherCategory']     },     ... } 

I have managed to create a table that displays columns created from keys of the first nested dictionary (which starts with 'Vendor'). The row name is 'HexaPlex x50'. One of the columns contains computers with a number, i.e. the nested dictionary:

{'someName001': '12.72.9',  'someName002': '12.73.9',  'someName003': '12.73.9'} 

I would like to be able to have the key values pairs inside the table in the cell under column 'Computers', in effect a nested table.

ATM it looks like this:

Screenshot of current table display

The table should look somewhat like this

Screenshot of preferred table with one dictionary entry per row

How can I achieve this?

Further, I would like to color the numbers or the cell that has a lower BIOS version than the newest one.

I also face the problem that in one case the dictionary that contains the computers is so large that it gets abbreviated even though I have set pd.set_option('display.max_colwidth', -1). This looks like so:

Close-up of dictionary string

1 Answers

Answers 1

As already emphasized in the comments, pandas does not support "sub-dataframes". For the sake of KISS, I would recommend duplicating those rows (or to manage two separate tables... if really necessary).

The answers in the question you referred to (parsing a dictionary in a pandas dataframe cell into new row cells (new columns)) result in new (frame-wide) columns for each (row-local) "computer name". I doubt that this is what you aim for, considering your domain model.


The abbreviation of pandas can be circumvented by using another output engine, e.g. tabulate (Pretty Printing a pandas dataframe):

# standard pandas output        Vendor BIOS Version Newest BIOS Against M & S W10 Support     Computer Location      ...          Category4     Category5     Category6     Category7     Category8     Category9     Category0 0  Dell  Inc.      12.72.9     12.73.9           Yes         Yes  someName001  12.72.9      ...       SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory 1  Dell  Inc.      12.72.9     12.73.9           Yes         Yes  someName002  12.73.9      ...       SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory 2  Dell  Inc.      12.73.9     12.73.9           Yes         Yes  someName003  12.73.9      ...       SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  [3 rows x 17 columns]  # tabulate psql (with headers) +----+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+ |    | Vendor     | BIOS Version   | Newest BIOS   | Against M & S   | W10 Support   | Computer    | Location   | Category1    | Category2    | Category3    | Category4    | Category5    | Category6    | Category7    | Category8    | Category9    | Category0    | |----+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------| |  0 | Dell  Inc. | 12.72.9        | 12.73.9       | Yes             | Yes           | someName001 | 12.72.9    | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | |  1 | Dell  Inc. | 12.72.9        | 12.73.9       | Yes             | Yes           | someName002 | 12.73.9    | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | |  2 | Dell  Inc. | 12.73.9        | 12.73.9       | Yes             | Yes           | someName003 | 12.73.9    | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | +----+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+  # tabulate psql +---+------------+---------+---------+-----+-----+-------------+---------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+ | 0 | Dell  Inc. | 12.72.9 | 12.73.9 | Yes | Yes | someName001 | 12.72.9 | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | | 1 | Dell  Inc. | 12.72.9 | 12.73.9 | Yes | Yes | someName002 | 12.73.9 | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | | 2 | Dell  Inc. | 12.73.9 | 12.73.9 | Yes | Yes | someName003 | 12.73.9 | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | +---+------------+---------+---------+-----+-----+-------------+---------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+  # tabulate plain     Vendor      BIOS Version    Newest BIOS    Against M & S    W10 Support    Computer     Location    Category1     Category2     Category3     Category4     Category5     Category6     Category7     Category8     Category9     Category0  0  Dell  Inc.  12.72.9         12.73.9        Yes              Yes            someName001  12.72.9     SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  1  Dell  Inc.  12.72.9         12.73.9        Yes              Yes            someName002  12.73.9     SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  2  Dell  Inc.  12.73.9         12.73.9        Yes              Yes            someName003  12.73.9     SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory 

You could also use some groupBy(..).apply(..) + string magic to produce a string representation which simply hides the duplicates:

# tabulate + merge manually +----+--------------+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+ |    | Type         | Vendor     | BIOS Version   | Newest BIOS   | Against M & S   | W10 Support   | Computer    | Location   | Category1    | Category2    | |----+--------------+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------| |  0 | HexaPlex x50 | Dell  Inc. | 12.72.9        | 12.73.9       | Yes             | Yes           | someName001 | 12.72.9    | SomeCategory | SomeCategory | |    |              |            | 12.72.9        |               |                 |               | someName002 | 12.73.9    |              |              | |    |              |            | 12.73.9        |               |                 |               | someName003 | 12.73.9    |              |              | +----+--------------+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+ 

Styled output can be generated via the new Styling API which is still provisional and under development:

styled pandas output with some cells highlighted in red

Again, you can use some logic to 'merge' consecutively redundant values in a column (quick example, I assume some more effort could result in much nicer output):

styled pandas output with some cells highlighted in red and some hidden


Code for the above examples

import pandas as pd from tabulate import tabulate import functools  def pprint(df, headers=True, fmt='psql'):     # https://stackoverflow.com/questions/18528533/pretty-printing-a-pandas-dataframe     print(tabulate(df, headers='keys' if headers else '', tablefmt=fmt))  df = pd.DataFrame({         'Type': ['HexaPlex x50'] * 3,         'Vendor': ['Dell  Inc.'] * 3,         'BIOS Version': ['12.72.9', '12.72.9', '12.73.9'],         'Newest BIOS': ['12.73.9'] * 3,         'Against M & S': ['Yes'] * 3,         'W10 Support': ['Yes'] * 3,         'Computer': ['someName001', 'someName002', 'someName003'],         'Location': ['12.72.9', '12.73.9', '12.73.9'],         'Category1': ['SomeCategory'] * 3,         'Category2': ['SomeCategory'] * 3,         'Category3': ['SomeCategory'] * 3,         'Category4': ['SomeCategory'] * 3,         'Category5': ['SomeCategory'] * 3,         'Category6': ['SomeCategory'] * 3,         'Category7': ['SomeCategory'] * 3,         'Category8': ['SomeCategory'] * 3,         'Category9': ['SomeCategory'] * 3,         'Category0': ['SomeCategory'] * 3,     })  print("# standard pandas print") print(df)  print("\n# tabulate tablefmt=psql (with headers)") pprint(df) print("\n# tabulate tablefmt=psql") pprint(df, headers=False) print("\n# tabulate tablefmt=plain") pprint(df, fmt='plain')  def merge_cells_for_print(rows, ls='\n'):     result = pd.DataFrame()     for col in rows.columns:         vals = rows[col].values         if all([val == vals[0] for val in vals]):             result[col] = [vals[0]]         else:             result[col] = [ls.join(vals)]     return result  print("\n# tabulate + merge manually") pprint(df.groupby('Type').apply(merge_cells_for_print).reset_index(drop=True))  # https://pandas.pydata.org/pandas-docs/stable/style.html # https://pandas.pydata.org/pandas-docs/version/0.22.0/generated/pandas.io.formats.style.Styler.apply.html#pandas.io.formats.style.Styler.apply  def highlight_lower(ref, col):     return [f'color: {"red" if hgl else ""}' for hgl in col < ref]  def merge_duplicates(col):     vals = col.values     return [''] + ['color: transparent' if curr == pred else ''  for pred, curr in zip(vals[1:], vals)]  with open('only_red.html', 'w+') as f:     style = df.style     style = style.apply(functools.partial(highlight_lower, df['Newest BIOS']),                         subset=['BIOS Version'])     f.write(style.render())  with open('red_and_merged.html', 'w+') as f:     style = df.style     style = style.apply(functools.partial(highlight_lower, df['Newest BIOS']),                         subset=['BIOS Version'])     style = style.apply(merge_duplicates)     f.write(style.render()) 
Read More

Saturday, July 14, 2018

Best way to process a click stream to create features in Pandas

Leave a Comment

I am processing a dataframe with a click-stream and I'm extracting features for each user in the click-stream to be used in a Machine Learning project.

The dataframe is something like this:

data = pd.DataFrame({'id':['A01','B01','A01','C01','A01','B01','A01'],                      'event':['search','search','buy','home','cancel','home','search'],                      'date':['2018-01-01','2018-01-01','2018-01-02','2018-01-03','2018-01-04','2018-01-04','2018-01-06'],                      'product':['tablet','dvd','tablet','tablet','tablet','book','book'],                      'price': [103,2,203,103,203,21,21]}) data['date'] = pd.to_datetime(data['date']) 

Since I have to create features for each user I'm using a groupby/apply with a custom function like:

featurized = data.groupby('id').apply(featurize) 

Create user features will take a chunk of the dataframe and create many (hundreds) of features. The whole process is just too slow so I'm looking for a recommendation to do this more effciently.

An example of the function used to create features:

def featurize(group):     features = dict()      # Userid     features['id'] = group['id'].max()     # Feature 1: Number of search events     features['number_of_search_events'] = (group['event']=='search').sum()     # Feature 2: Number of tablets     features['number_of_tablets'] = (group['product']=='tablet').sum()     # Feature 3: Total time     features['total_time'] = (group['date'].max() - group['date'].min()) / np.timedelta64(1,'D')     # Feature 4: Total number of events     features['events'] = len(group)     # Histogram of products examined     product_counts = group['product'].value_counts()     # Feature 5 max events for a product     features['max_product_events'] = product_counts.max()     # Feature 6 min events for a product     features['min_product_events'] = product_counts.min()     # Feature 7 avg events for a product     features['mean_product_events'] = product_counts.mean()     # Feature 8 std events for a product     features['std_product_events'] = product_counts.std()     # Feature 9 total price for tablet products     features['tablet_price_sum'] = group.loc[group['product']=='tablet','price'].sum()     # Feature 10 max price for tablet products     features['tablet_price_max'] = group.loc[group['product']=='tablet','price'].max()     # Feature 11 min price for tablet products     features['tablet_price_min'] = group.loc[group['product']=='tablet','price'].min()     # Feature 12 mean price for tablet products     features['tablet_price_mean'] = group.loc[group['product']=='tablet','price'].mean()     # Feature 13 std price for tablet products     features['tablet_price_std'] = group.loc[group['product']=='tablet','price'].std()     return pd.Series(features) 

One potential problem is that each feature potentially scans the whole chunk so if I have 100 features I scan the chunk 100 times instead of just one.

For example a feature can be the number of "tablet" events the user has, other can be the number of "home" events, other can be the average time difference between "search" events, then average time difference between "search" events for "tablets", etc etc. Each feature can be coded as a function that takes a chunk (df) and creates the feature but when we have 100s of features each is scanning the whole chunk when a single linear scan would suffice. The problem is the code would get ugly if I do a manual for loop over each record in the chunk and code all the features in the loop.

Questions:

  1. If I have to process a dataframe hundreds of times, is there a way to abstract this in a single scan that will create all the needed features?

  2. Is there a speed improvement over the groupby/apply approach I'm currently using?

2 Answers

Answers 1

Disclaimer: the following answer does not properly answer the above question. Just leaving it here for the sake of work invested. Maybe there will be some use for it at some point.

  1. parallelism (e.g. Parallelize apply after pandas groupby; see code below)
  2. use a cache if you run the calculations multiple times (e.g. HDFStore)
  3. avoid string operations; use native types which can be efficiently represented in numpy
  4. if you really need strings, use categorical columns (given they represent categorical data..)
  5. if the frames are really big, consider using chunks (e.g. "Large data" work flows using pandas)
  6. use cython for further (potentially drastical) enhancements
  7. re-use dataframe selections (e.g. group.loc[group['product']=='tablet','price'])

As for (1), given your code from above, I could produce speedups of up to 43% (i7-7700HQ CPU, 16GB RAM).

Timings

using joblib: 68.86841534099949s using multiprocessing: 71.53540843299925s single-threaded: 119.05010353899888s 

Code

import pandas as pd import numpy as np import time import timeit import os import joblib import multiprocessing   import pandas as pd import numpy as np import timeit import joblib import multiprocessing   def make_data():     # just some test data ...     n_users = 100     events = ['search', 'buy', 'home', 'cancel']     products = ['tablet', 'dvd', 'book']     max_price = 1000      n_duplicates = 1000     n_rows = 40000      df = pd.DataFrame({         'id': list(map(str, np.random.randint(0, n_users, n_rows))),         'event': list(map(events.__getitem__, np.random.randint(0, len(events), n_rows))),         'date': list(map(pd.to_datetime, np.random.randint(0, 100000, n_rows))),         'product': list(map(products.__getitem__, np.random.randint(0, len(products), n_rows))),         'price': np.random.random(n_rows) * max_price     })     df = pd.concat([df for _ in range(n_duplicates)])     df.to_pickle('big_df.pkl')     return df   def data():     return pd.read_pickle('big_df.pkl')   def featurize(group):     features = dict()      # Feature 1: Number of search events     features['number_of_search_events'] = (group['event'] == 'search').sum()     # Feature 2: Number of tablets     features['number_of_tablets'] = (group['product'] == 'tablet').sum()     # Feature 3: Total time     features['total_time'] = (group['date'].max() - group['date'].min()) / np.timedelta64(1, 'D')     # Feature 4: Total number of events     features['events'] = len(group)     # Histogram of products examined     product_counts = group['product'].value_counts()     # Feature 5 max events for a product     features['max_product_events'] = product_counts.max()     # Feature 6 min events for a product     features['min_product_events'] = product_counts.min()     # Feature 7 avg events for a product     features['mean_product_events'] = product_counts.mean()     # Feature 8 std events for a product     features['std_product_events'] = product_counts.std()     # Feature 9 total price for tablet products     features['tablet_price_sum'] = group.loc[group['product'] == 'tablet', 'price'].sum()     # Feature 10 max price for tablet products     features['tablet_price_max'] = group.loc[group['product'] == 'tablet', 'price'].max()     # Feature 11 min price for tablet products     features['tablet_price_min'] = group.loc[group['product'] == 'tablet', 'price'].min()     # Feature 12 mean price for tablet products     features['tablet_price_mean'] = group.loc[group['product'] == 'tablet', 'price'].mean()     # Feature 13 std price for tablet products     features['tablet_price_std'] = group.loc[group['product'] == 'tablet', 'price'].std()     return pd.DataFrame.from_records(features, index=[group['id'].max()])   # https://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby def apply_parallel_job(dfGrouped, func):     retLst = joblib.Parallel(n_jobs=multiprocessing.cpu_count())(         joblib.delayed(func)(group) for name, group in dfGrouped)     return pd.concat(retLst)   def apply_parallel_pool(dfGrouped, func):     with multiprocessing.Pool(multiprocessing.cpu_count()) as p:         ret_list = list(p.map(func, [group for name, group in dfGrouped]))     return pd.concat(ret_list)   featurized_job = lambda df: apply_parallel_job(df.groupby('id'), featurize) featurized_pol = lambda df: apply_parallel_pool(df.groupby('id'), featurize) featurized_sng = lambda df: df.groupby('id').apply(featurize)  make_data() print(timeit.timeit("featurized_job(data())", "from __main__ import featurized_job, data", number=3)) print(timeit.timeit("featurized_sng(data())", "from __main__ import featurized_sng, data", number=3)) print(timeit.timeit("featurized_pol(data())", "from __main__ import featurized_pol, data", number=3)) 

As for (7), consider the following refactorization:

Timings

original: 112.0091859719978s re-used prices: 83.85681765000118s 

Code

# [...] prices_ = group.loc[group['product'] == 'tablet', 'price'] features['tablet_price_sum'] = prices_.sum() # Feature 10 max price for tablet products features['tablet_price_max'] = prices_.max() # Feature 11 min price for tablet products features['tablet_price_min'] = prices_.min() # Feature 12 mean price for tablet products features['tablet_price_mean'] = prices_.mean() # Feature 13 std price for tablet products features['tablet_price_std'] = prices_.std() # [...] 

Answers 2

DataFrame.agg() is your friend here. You're right in that the initial method implemented iterates over the entire dataset for EACH call. So what we can do is define all of the heavy lifting that we want to do at the beginning and let pandas handle all of the internal optimizations. Typically with these libraries, there's VERY rarely a time where you can code something that would beat just using the internal libraries.

What's nice about this method is that you only have to do this heavy calculation ONCE and then you can do all of the fine tuned feature creation on the filtered dataset since it's so much faster.

This reduces runtime by 65% percent, which is quite large. And also, next time you want to get a new statistic, you can just access the result of featurize2 and not have to run the computation again.

df = make_data() # include this to be able to calculate standard deviations correctly df['price_sq'] = df['price'] ** 2.  def featurize2(df):     grouped = df.groupby(['id', 'product', 'event'])     initial = grouped.agg({'price': ['count', 'max', 'min', 'mean', 'std', 'sum', 'size'], 'date': [         'max', 'min'], 'price_sq': ['sum']}).reset_index()     return initial  def featurize3(initial):      # Features 5-8     features = initial.groupby('product').sum()['price']['count'].agg(['max', 'min', 'mean', 'std']).rename({         'max': 'max_product_events',         'min': 'min_product_events',         'mean': 'mean_product_events',         'std': 'std_product_events'     })      searches = initial[initial['event'] == 'search']['price']      # Feature 1: Number of search events     features['number_of_search_events'] = searches['count'].sum()      tablets = initial[initial['product'] == 'tablet']['price']     tablets_sq = initial[initial['product'] == 'tablet']['price_sq']      # Feature 2: Number of tablets     features['number_of_tablets'] = tablets['count'].sum()     # Feature 9 total price for tablet products     features['tablet_price_sum'] = tablets['sum'].sum()     # Feature 10 max price for tablet products     features['tablet_price_max'] = tablets['max'].max()     # Feature 11 min price for tablet products     features['tablet_price_min'] = tablets['min'].min()     # Feature 12 mean price for tablet products     features['tablet_price_mean'] = (         tablets['mean'] * tablets['count']).sum() / tablets['count'].sum()     # Feature 13 std price for tablet products     features['tablet_price_std'] = np.sqrt(tablets_sq['sum'].sum(     ) / tablets['count'].sum() - features['tablet_price_mean'] ** 2.)      # Feature 3: Total time     features['total_time'] = (initial['date']['max'].max(     ) - initial['date']['min'].min()) / np.timedelta64(1, 'D')      # Feature 4: Total number of events     features['events'] = initial['price']['count'].sum()      return features  def new_featurize(df):     initial = featurize2(df)     final = featurize3(initial)     return final  original = featurize(df) final = new_featurize(df)  for x in final.index:     print("outputs for index {} are equal: {}".format(         x, np.isclose(final[x], original[x])))  print("featurize(df): {}".format(timeit.timeit("featurize(df)",                     "from __main__ import featurize, df", number=3))) print("featurize2(df): {}".format(timeit.timeit("featurize2(df)",                     "from __main__ import featurize2, df", number=3))) print("new_featurize(df): {}".format(timeit.timeit("new_featurize(df)",                     "from __main__ import new_featurize, df", number=3)))  for x in final.index:     print("outputs for index {} are equal: {}".format(         x, np.isclose(final[x], original[x]))) 

Results

featurize(df): 76.0546050072 featurize2(df): 26.5458261967 new_featurize(df): 26.4640090466 outputs for index max_product_events are equal: [ True] outputs for index min_product_events are equal: [ True] outputs for index mean_product_events are equal: [ True] outputs for index std_product_events are equal: [ True] outputs for index number_of_search_events are equal: [ True] outputs for index number_of_tablets are equal: [ True] outputs for index tablet_price_sum are equal: [ True] outputs for index tablet_price_max are equal: [ True] outputs for index tablet_price_min are equal: [ True] outputs for index tablet_price_mean are equal: [ True] outputs for index tablet_price_std are equal: [ True] outputs for index total_time are equal: [ True] outputs for index events are equal: [ True] 
Read More

Sunday, June 3, 2018

Tricky slicing specifications on business-day datetimeindex

Leave a Comment

I have a pandas dataframe with a business-day-based DateTimeIndex. For each month that's in the index, I also have a single 'marker' day specified.

Here's a toy version of that dataframe:

# a dataframe with business dates as the index df = pd.DataFrame(list(range(91)), pd.date_range('2015-04-01', '2015-6-30'), columns=['foo']).resample('B').last()  # each month has an single, arbitrary marker day specified marker_dates = [df.index[12], df.index[33], df.index[57]] 

For each month in the index, I need to calculate average of the foo column in specific slice of rows in that month.

There are two different ways I need to be able to specify those slices:

1) m'th day to n'th day.

Example might be (2rd to 4th business day in that month). So april would be the average of 1 (apr2), 4 (apr3), and 5 (apr 6) = 3.33. May would be 33 (may 4), 34 (may 5), 35 (may 6) = 34. I don't consider the weekends/holidays that don't occur in the index as days.

2) m'th day before/after the marker date to the n'th day before/after the marker date.

Example might be "average of the slice from 1 day before the marker date to 1 day after the marker date in each month" Eg. In April, the marker date is 17Apr. Looking at the index, we want the average of apr16, apr17, and apr20.

For Example 1, I had an ugly solution that foreach month I would slice the rows of that month away, and then apply df_slice.iloc[m:n].mean()

Whenever I start doing iterative things with pandas, I always suspect I'm doing it wrong. So I imagine there is a cleaner, pythonic/vectorized way to make this result for all the months

For Example 2, I don't not know a good way to do this slice-averaging based on arbitrary dates across many months.

4 Answers

Answers 1

Use BDay() from pandas.tseries.offsets

import pandas as pd from pandas.tseries.offsets import BDay   M=2 N=4  start_date = pd.datetime(2015,4,1) end_date = pd.datetime(2015,6,30)  df = pd.DataFrame(list(range(91)), pd.date_range('2015-04-01', '2015-6-30'), columns=['foo']).resample('B').last()  # for month starts marker_dates = pd.date_range(start=start_date, end=end_date, freq='BMS')  # create IntervalIndex bins = pd.IntervalIndex.from_tuples([ (d + (M-1)*BDay(), d + (N-1)*BDay()) for d in marker_dates ], closed='both')  df.groupby(pd.cut(df.index, bins)).mean() #[2015-04-02, 2015-04-06]   3.333333 #[2015-05-04, 2015-05-06]  34.000000 #[2015-06-02, 2015-06-04]  63.000000   # any markers marker_dates = [df.index[12], df.index[33], df.index[57]]  # M Bday before, and N Bday after  bins = pd.IntervalIndex.from_tuples([ (d - M*BDay(), d + N*BDay()) for d in marker_dates ], closed='both')  df.groupby(pd.cut(df.index, bins)).mean() #[2015-04-15, 2015-04-23]  18.428571 #[2015-05-14, 2015-05-22]  48.000000 #[2015-06-17, 2015-06-25]  81.428571 

Answers 2

The most pythonic/vectorized (pandonic?) way to do this might be to use df.rolling and df.shift to generate the window over which you'll take the average, then df.reindex to select the value at the dates you've marked.

For your example (2), this could look like:

df['foo'].rolling(3).mean().shift(-1).reindex(marker_dates) Out[8]:  2015-04-17    17.333333 2015-05-18    47.000000 2015-06-19    80.333333 Name: foo, dtype: float64 

This could be wrapped in a small function:

def window_mean_at_indices(df, indices, begin=-1, end=1):     return df.rolling(1+end-begin).mean().shift(-end).reindex(indices) 

Helping to make it more clear how to apply this to situation (1):

month_starts = pd.date_range(df.index.min(), df.index.max(), freq='BMS')  month_starts Out[11]: DatetimeIndex(['2015-04-01', '2015-05-01', '2015-06-01'],                        dtype='datetime64[ns]', freq='BMS')  window_mean_at_indices(df['foo'], month_starts, begin=1, end=3) Out[12]:  2015-04-01     3.333333 2015-05-01    34.000000 2015-06-01    63.000000 Freq: BMS, Name: foo, dtype: float64 

Answers 3

For your first problem you can use grouper and iloc i.e

low = 2 high= 4  slice_mean = df.groupby(pd.Grouper(level=0,freq='m')).apply(lambda x : x.iloc[low-1:high].mean()) # or df.resample('m').apply(lambda x : x.iloc[low-1:high].mean())                foo 2015-04-30   3.333333 2015-05-31  34.000000 2015-06-30  63.000000 

For your second problem you can concat the dates and take the groupy mean per month i.e

idx = pd.np.where(df.index.isin(pd.Series(marker_dates)))[0]  #array([12, 33, 57]) temp = pd.concat([df.iloc[(idx+i)] for i in [-1,0,1]])              foo 2015-04-16   15 2015-05-15   46 2015-06-18   78 2015-04-17   18 2015-05-18   47 2015-06-19   81 2015-04-20   19 2015-05-19   48 2015-06-22   82  # Groupby mean temp.groupby(pd.Grouper(level=0,freq='m')).mean() # or temp.resample('m').mean()               foo 2015-04-30  17.333333 2015-05-31  47.000000 2015-06-30  80.333333 dtype: float64 

since the index of output aint specified in the question do let us know what the index of output be.

Answers 4

Here's what I managed to come up with:

Import pandas and setup the dataframe

import pandas as pd df = pd.DataFrame(list(range(91)), pd.date_range('2015-04-01', '2015-6-30'), columns=['foo']).resample('B') 

Start with a pure list of marker dates, since I'm guessing that what you're really starting with:

marker_dates = [     pd.to_datetime('2015-04-17', format='%Y-%m-%d'),     pd.to_datetime('2015-05-18', format='%Y-%m-%d'),     pd.to_datetime('2015-06-19', format='%Y-%m-%d') ] marker_df = pd.DataFrame([], columns=['marker', 'start', 'end', 'avg']) marker_df['marker'] = marker_dates 

For the case where you want to just test ranges, input the start and end manually here instead of calculating it. If you want to change the range you can change the arguments to shift():

marker_df['start'] = df.index.shift(-1)[df.index.isin(marker_df['marker'])] marker_df['end'] = df.index.shift(1)[df.index.isin(marker_df['marker'])] 

Finally, use DataFrame.apply() to do a row by row calculation of averages:

marker_df.apply(     lambda x: df[(x['start'] <= df.index) & (df.index <= x['end'])]['foo'].mean(),      axis=1 ) 

Which gives us this result:

      marker      start        end        avg 0 2015-04-17 2015-04-16 2015-04-20  17.000000 1 2015-05-18 2015-05-15 2015-05-19  46.666667 2 2015-06-19 2015-06-18 2015-06-22  80.000000 
Read More

Tuesday, May 1, 2018

Creating new columns given if an event happen in a window of time (future or past)

Leave a Comment

I have a pandas dataframe with the following structure:

ID    date           e_1     1    2016-02-01     False        2016-02-02     False        2016-02-03     True         2016-02-04     False       2016-02-05     False       2016-02-06     False       2016-02-07     False       2016-02-08     False       2016-02-09     False       2016-02-10     False    2    2016-02-01     False         2016-02-02     True           2016-02-03     True           2016-02-04     False             ...         ... 

I want to add several columns that encode the following: Does the e_1 is True in the following 1d, 2d, 3d, 4d, 5d, 1 month... etc?

I will like to specify the delta in time in a list. The name of the columns will be the e1_XX where XX is the delta (i.e. 1d, etc)

I tried with shift but that just moves the values. Also tried with rolling (it seems more suitable for this task):

df.groupby('ID').rolling(3).agg(???) 

But I don' t know how to pass the condition (I though in something like np.any), but I am stuck

2 Answers

Answers 1

You can using groupby with rolling apply

df.groupby('ID').e_1.apply(lambda x : x.iloc[::-1].rolling(window=3,min_periods=1).apply(any).iloc[::-1].astype(bool)) Out[51]:  ID  date       1   2016-02-01     True     2016-02-02     True     2016-02-03     True     2016-02-04    False     2016-02-05    False     2016-02-06    False     2016-02-07    False     2016-02-08    False     2016-02-09    False     2016-02-10    False 2   2016-02-01     True     2016-02-02     True     2016-02-03     True     2016-02-04    False Name: e_1, dtype: bool 

EDIT : groupby the index ID , then we have series of e_1 for each ID , and check the link for rolling , it can accept offset which means when your index is datetime ,it can using offset(3d means 3 days) to determine the window size

df.groupby('ID').e_1.apply(lambda x : x.reset_index(level=0,drop=True).rolling('3d').apply(any)) 

Answers 2

check the following code and see if it works:

# make sure date is in valid Pandas datetime format mydf['date'] = pd.to_datetime(mydf['date'], format='%Y-%m-%d')  # use date as index to make it easier in date manipulations mydf.set_index('date', inplace=True)  def flag_visits(grps, d, d_name):     """Loop through each group and extend the index to 'd' more days from        df_grp.index.max(). fill the NaN values with *False*        this is needed to retrieve the forward rolling stats when running shift(1-d)     """     for id, df_grp in grps:         # create the new index to cover all days required in calculation         idx = pd.date_range(               start = df_grp.index.min()             , end   = df_grp.index.max() + pd.DateOffset(days=d)             , freq  = 'D'         )          # set up the new column 'd_name' for the current group         mydf.loc[mydf.ID == id, 'e1_'+d_name] = (df_grp.reindex(idx, fill_value=False)                                                        .e_1.rolling(str(d)+'d', min_periods=0)                                                        .sum().gt(0)                                                        .shift(1-d)         )  # if you know the dates are continue without gap, then you might also reverse the dates, do the regular backward rolling(), and then flip it back. However, you can not do the rolling() by the number of day, only by the number of records.  def flag_visits_1(grps, d, d_name):     for id, df_grp in grps:         mydf.loc[mydf.ID == id, 'e1_'+d_name] = (df_grp.sort_index(ascending=False)                                                        .e_1.rolling(d, min_periods=0)                                                        .sum().gt(0).sort_index()         )    # d is the actual number of days used in Series.rolling(), d_name used in the column name""" for d, d_name in [ (2, '1d') , (3, '2d'), (7, '6d'), (30, '1m') ]:     mydf.groupby('ID').pipe(flag_visits, d, d_name)  # reset to the previous  mydf.reset_index(inplace=True)  print(mydf) 

Note:

  • If the next 1 day does not include today, thus when d_name == 'id', d == 1, then you can adjust the shift(1-d) to shift(-d)
  • date field must be unique for each ID, or you will not be able to set_index()
Read More

Thursday, April 26, 2018

Saving in a file an array or DataFrame together with other information

Leave a Comment

The statistical software Stata allows short text snippets to be saved within a dataset. This is accomplished either using notes and/or characteristics.

This is a feature of great value to me as it allows me to save a variety of information, ranging from reminders and to-do lists to information about how I generated the data, or even what the estimation method for a particular variable was.

I am now trying to come up with a similar functionality in Python 3.6. So far, I have looked online and consulted a number of posts, which however do not exactly address what I want to do.

A few reference posts include:

For a small NumPy array, I have concluded that a combination of the function numpy.savez() and a dictionary can store adequately all relevant information in a single file.

For example:

a = np.array([[2,4],[6,8],[10,12]]) d = {"first": 1, "second": "two", "third": 3}  np.savez(whatever_name.npz, a=a, d=d) data = np.load(whatever_name.npz)  arr = data['a'] dic = data['d'].tolist() 

However, the question remains:

Are there better ways to potentially incorporate other pieces of information in a file containing a NumPy array or a (large) Pandas DataFrame?

I am particularly interested in hearing about the particular pros and cons of any suggestions you may have with examples. The fewer dependencies, the better.

Thank you.

6 Answers

Answers 1

There are many options. I will discuss only HDF5, because I have experience using this format.

Advantages: Portable (can be read outside of Python), native compression, out-of-memory capabilities, metadata support.

Disadvantages: Reliance on single low-level C API, possibility of data corruption as a single file, deleting data does not reduce size automatically.

In my experience, for performance and portability, avoid pyTables / HDFStore to store numeric data. You can instead use the intuitive interface provided by h5py.

Store an array

import h5py, numpy as np  arr = np.random.randint(0, 10, (1000, 1000))  f = h5py.File('file.h5', 'w', libver='latest')  # use 'latest' for performance  dset = f.create_dataset('array', shape=(1000, 1000), data=arr, chunks=(100, 100)                         compression='gzip', compression_opts=9) 

Compression & chunking

There are many compression choices, e.g. blosc and lzf are good choices for compression and decompression performance respectively. Note gzip is native; other compression filters may not ship by default with your HDF5 installation.

Chunking is another option which, when aligned with how you read data out-of-memory, can significantly improve performance.

Add some attributes

dset.attrs['Description'] = 'Some text snippet' dset.attrs['RowIndexArray'] = np.arange(1000) 

Store a dictionary

for k, v in d.items():     f.create_dataset('dictgroup/'+str(k), data=v) 

Out-of-memory access

dictionary = f['dictgroup'] res = dictionary['my_key'] 

There is no substitute for reading the h5py documentation, which exposes most of the C API, but you should see from the above there is a significant amount of flexibility.

Answers 2

A practical way could be to embed meta-data directly inside the Numpy array. The advantage is that, as you'd like, there's no extra dependency and it's very simple to use in the code. However, this doesn't fully answers your question, because you still need a mechanism to save the data, and I'd recommend using jpp's solution using HDF5.

To include metadata in an ndarray, there is an example in the documentation. You basically have to subclass an ndarray and add a field info or metadata or whatever.

It would give (code from the link above)

import numpy as np  class ArrayWithInfo(np.ndarray):      def __new__(cls, input_array, info=None):         # Input array is an already formed ndarray instance         # We first cast to be our class type         obj = np.asarray(input_array).view(cls)         # add the new attribute to the created instance         obj.info = info         # Finally, we must return the newly created object:         return obj      def __array_finalize__(self, obj):         # see InfoArray.__array_finalize__ for comments         if obj is None: return         self.info = getattr(obj, 'info', None) 

To save the data through numpy, you'd need to overload the write function or use another solution.

Answers 3

I agree with JPP that hdf5 storage is a good option here. The difference between his solution and mine is mine uses Pandas dataframes instead of numpy arrays. I prefer the dataframe since this allows mixed types, multi-level indexing (even datetime indexing, which is VERY important for my work), and column labeling, which helps me remember how different datasets are organized. Also, Pandas provides a slew of built-in functionalities (much like numpy). Another benefit of using Pandas is it has a hdf creator built in (i.e. pandas.DataFrame.to_hdf), which I find convenient

When storing the dataframe to h5 you have the option of storing a dictionary of metadata as well, which can be your notes to self, or actual metadata that does not need to be stored in the dataframe (I use this for setting flags as well, e.g. {'is_agl': True, 'scale_factor': 100, 'already_corrected': False, etc.}. In this regard, there is no difference between using a numpy array and a dataframe. For the full solution see my original question and solution here.

Answers 4

jpp's answer is pretty comprehensive, just wanted to mention that as of pandas v22 parquet is very convenient and fast option with almost no drawbacks vs csv (accept perhaps the coffee break).

read parquet

write parquet

At time of writing you'll need to also

pip install pyarrow 

In terms of adding information you have the metadata which is attached to the data

import pyarrow as pa  import pyarrow.parquet as pq  import pandas as pd  import numpy as np    df = pd.DataFrame(np.random.normal(size=(1000, 10)))    tab = pa.Table.from_pandas(df)    tab = tab.replace_schema_metadata({'here' : 'it is'})    pq.write_table(tab, 'where_is_it.parq')    pq.read_table('where_is_it.parq')
which then yield a table

Pyarrow table 0: double 1: double 2: double 3: double 4: double 5: double 6: double 7: double 8: double 9: double __index_level_0__: int64 metadata -------- {b'here': b'it is'} 

To get this back to pandas:

tab.to_pandas() 

Answers 5

It's an interesting question, although very open-ended I think.

Text Snippets
For text snippets that have literal notes (as in, not code and not data), I really don't know what your use case is, but I don't see why I would deviate from using the usual with open() as f: ...

Small collections of various data pieces
Sure, your npz works. Actually what you are doing is very similar to creating a dictionary with everything you want to save and pickling that dictionary.

See here for a discussion of the differences between pickle and npz (but mainly, npz is optimized for numpy arrays).

Personally, I'd say if you are not storing Numpy arrays I would use pickle, and even implement a quick MyNotes class that is basically a dictionary to save stuff in it, with some additional functionality you may want.

Collection of large objects
For really big np.arrays or dataframes I have used before the HDF5 format. The good thing is that it is already built in into pandas and you can directly df.to_hdf5(). It does need underneath pytables -installation should be fairly painless with pip or conda- but using pytables directly can be a much bigger pain.

Again, this idea is very similar: you are creating an HDFStore, which is pretty much a big dictionary in which you can store (almost any) objects. The benefit is that the format utilizes space in a smarter way by leveraging repetition of similar values. When I was using it to store some ~2GB dataframes, it was able to reduce it by almost a full order of magnitude (~250MB).

One last player: feather
Feather is a project created by Wes McKinney and Hadley Wickham on top of the Apache Arrow framework, to persist data in a binary format that is language agnostic (and therefore you can read from R and Python). However, it is still under development, and last time I checked they didn't encourage to use it for long-term storage (since the specification may change in future versions), rather than just use it for communication between R and Python.

They both just launched Ursalabs, literally just weeks ago, that will continue growing this and similar initiatives.

Answers 6

You stated as the reasons for this question:

... it allows me to save a variety of information, ranging from reminders and to-do lists, to information about how i generated the data, or even what the estimation method for a particular variable was.

May I suggest a different paradigm than that offered by Stata? The notes and characteristics seem to be very limited and confined to just text. Instead, you should use Jupyter Notebook for your research and data analysis projects. It provides such a rich environment to document your workflow and capture details, thoughts and ideas as you are doing your analysis and research. It can easily be shared, and it's presentation-ready.

Here is a gallery of interesting Jupyter Notebooks across many industries and disciplines to showcase the many features and use cases of notebooks. It may expand your horizons beyond trying to devise a way to tag simple snippets of text to your data.

Read More

Wednesday, March 21, 2018

Feature Selection using MRMR

Leave a Comment

I found two ways to implement MRMR for feature selection in python. The source of the paper that contains the method is:

https://www.dropbox.com/s/tr7wjpc2ik5xpxs/doc.pdf?dl=0

This is my code for the dataset.

import numpy as np import pandas as pd from sklearn.datasets import make_classification  from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all"  X, y = make_classification(n_samples=10000,                            n_features=6,                            n_informative=3,                            n_classes=2,                            random_state=0,                            shuffle=False)  # Creating a dataFrame df = pd.DataFrame({'Feature 1':X[:,0],                                   'Feature 2':X[:,1],                                   'Feature 3':X[:,2],                                   'Feature 4':X[:,3],                                   'Feature 5':X[:,4],                                   'Feature 6':X[:,5],                                   'Class':y})   y_train = df['Class'] X_train = df.drop('Class', axis=1) 

Method 1: Applying MRMR using pymrmr

Contains MID and MIQ

Which is published by the author The link is https://github.com/fbrundu/pymrmr

import pymrmr  pymrmr.mRMR(df, 'MIQ',6) 

['Feature 4', 'Feature 5', 'Feature 2', 'Feature 6', 'Feature 1', 'Feature 3']

or running using the second way

pymrmr.mRMR(df, 'MID',6) 

['Feature 4', 'Feature 6', 'Feature 5', 'Feature 2', 'Feature 1', 'Feature 3']

Both these methods, on the above dataset yields this 2 output. Another author on GitHub claims that you can use his version to apply the MRMR method. However when I use it for the same dataset I have a different result.

Method 2: Applying MRMR using MIFS

Github link

https://github.com/danielhomola/mifs

import mifs  for i in range(1,11):      feat_selector = mifs.MutualInformationFeatureSelector('MRMR',k=i)     feat_selector.fit(X_train, y_train)      # call transform() on X to filter it down to selected features     X_filtered = feat_selector.transform(X_train.values)      #Create list of features     feature_name = X_train.columns[feat_selector.ranking_]       print(feature_name) 

And if you run the above iteration for all different values of i, there will come no time where both methods actually yield the same feature selection output.

What seems to be the problem here ?

1 Answers

Answers 1

You'll probably need to contact either the authors of the original paper and/or the owner of the Github repo for a final answer, but most likely the differences here come from the fact that you are comparing 3 different algorithms (despite the name).

Minimum redundancy Maximum relevance algorithms are actually a family of feature selection algorithms whose common objective is to select features that are mutually far away from each other while still having "high" correlation to the classification variable.

You can measure that objective using Mutual Information measures, but the specific method to follow(i.e. what to do with the scores computed? In what order? What other post-processing methods will be used? ...) is going to be different from one author to another - even in the paper they are actually giving you two different implementations, MIQ and MID.

So my suggestion would be to just choose the implementation you are more comfortable with (or even better, the one that produces better results in your pipeline after conducting a proper validation), and just report which specific source did you choose and why.

Read More

Thursday, March 8, 2018

How to pass nested JSON from dataframe while adding another field?

Leave a Comment

I have a dataframe that I need to pass as a nested json string into an email service provider api as a json string.

My dataframe looks like this:

email_address     first_name       last_name a@a.com            adam             apple b@b.com            bobby            banana 

The contacts in the dataframe is what I need to pass into the email service provider API, and this needs be a nested JSON string like so:

{     "import_data": [{         "email_addresses": ["hector@hector.com"],         "first_name": "Hector",         "last_name": "Smith"     }, {         "email_addresses": ["Jane@Doe.com"],         "first_name": "Jane",         "last_name": "Doe"     }, {         "email_addresses": ["Pradeep@Patel.com"],         "first_name": "Pradeep",         "last_name": "Patel"     }],     "lists": ["1234567890"] } 

I am not sure how I would create nested json string via the 'to_json' command from pandas and at the same time insert the word "import_data" as above into the json string. I know I can hard code the a column with in the dataframe for "lists" and pass that in as well. List ID will always be static.

Here is code for my API response:

headers = {      'Authorization': '',     'X-Originating-Ip': '',     'Content-Type': '',      }  update_contact = '{"import_data": [{"email_addresses": ["test@test.com"],"first_name": "test","last_name": "test"},{"email_addresses": ["Jane@Doe.com"],"first_name": "Jane","last_name": "Doe"}, {"email_addresses": ["Pradeep@Patel.com"],"first_name": "Pradeep","last_name": "Patel"}],"lists": ["1234567890"]}'  r = requests.post('url', headers=headers ,data = update_contact)  print(r.text) 

3 Answers

Answers 1

I believe the API asked for application/json, if this is really the case, you should send it like this

headers = {}  update_contact = {"import_data": [{"email_addresses": ["test@test.com"],"first_name": "test","last_name": "test"},{"email_addresses": ["Jane@Doe.com"],"first_name": "Jane","last_name": "Doe"}, {"email_addresses": ["Pradeep@Patel.com"],"first_name": "Pradeep","last_name": "Patel"}],"lists": ["1234567890"]}  r = requests.post('url', headers=headers ,json= update_contact)  print(r.text) 

Answers 2

Format the data using orient='records' of to_dict(), then just format your the dictionary to json

#converted emails to list, may not be necessary... df.email_address = df.email_address.apply(lambda x: [x])  import json  update_contact = json.dumps({'import_data':df.to_dict(orient='records'),                              'lists':["1234567890"]}) 

Answers 3

You can use json_variable.append(NewValues) so that it will append any of your data blocks into a json value. Refer to below skeleton and re-build according to your inputs.

enter code here   import json Json_List=[]  for i in Excel_data:     Newdata = {     'Name':Read_name_From_Excel(i),     'Age':Read_age_From_Excel(i),     'Email':Read_Email_From_Excel(i),     'Amount':Read_Amount_From_Excel(i)     }      Json_List.append(Newdata) 
Read More

Wednesday, March 7, 2018

How to achieve stratified K fold splitting for arbitrary number of categorical variables?

Leave a Comment

I have a dataframe of the form, df:

    cat_var_1    cat_var_2     num_var_1 0    Orange       Monkey         34 1    Banana        Cat           56 2    Orange        Dog           22 3    Banana       Monkey          6 .. 

Suppose the possible values of cat_var_1 in the dataset have the ratios- ['Orange': 0.6, 'Banana': 0.4] and the possible values of cat_var_2 have the ratios ['Monkey': 0.2, 'Cat': 0.7, 'Dog': 0.1].

How to I split the data into train, test and validation sets (60:20:20 split) such that the ratios of the categorical variables remain preserved? In practice, these variables can be of any number, not just two. Also, clearly, the exact ratios may never be achieved in practice, but we would like it to be as near as possible.

I have looked into the StratifiedKFold method from sklearn described here: how to split a dataset into training and validation set keeping ratio between classes? but this is restricted to evaluating on the basis of one categorical variable only.

Additionally, I would be grateful if you could provide the complexity of the solution you achieve.

1 Answers

Answers 1

You can pass df.cat_var_1+ "_" + df.cat_var_2 to argument y of StratifiedShuffleSplit.split():

But here is a method that use DataFrame.groupby:

import pandas as pd import numpy as np  nrows = 10000 p1 = {'Orange': 0.6, 'Banana': 0.4} p2 = {'Monkey': 0.2, 'Cat': 0.7, 'Dog': 0.1}  c1 = [key for key, val in p1.items() for i in range(int(nrows * val))] c2 = [key for key, val in p2.items() for i in range(int(nrows * val))] random.shuffle(c1) random.shuffle(c2)  df = pd.DataFrame({"c1":c1, "c2":c2, "val":np.random.randint(0, 100, nrows)})  index = [] for key, idx in df.groupby(["c1", "c2"]).groups.items():     arr = idx.values.copy()     np.random.shuffle(arr)     p1 = int(0.6 * len(arr))     p2 = int(0.8 * len(arr))     index.append(np.split(arr, [p1, p2]))  idx_train, idx_test, idx_validate = list(map(np.concatenate, zip(*index))) 
Read More

Thursday, March 1, 2018

Performance decrease for huge amount of columns. Pyspark

Leave a Comment

I met problem with processing of spark wide dataframe (about 9000 columns and sometimes more).
Task:

  1. Create wide DF via groupBy and pivot.
  2. Transform columns to vector and processing in to KMeans from pyspark.ml.

So I made extensive frame and try to create vector with VectorAssembler, cached it and trained on it KMeans.
It took about 11 minutes for assembling and 2 minutes for KMeans for 7 different count of clusters on my pc in standalone mode for frame ~500x9000. Another side this processing in pandas (pivot df, and iterate 7 clusters) takes less one minute.
Obviously I understand overhead and performance decreasing for standalone mode and caching and so on but it's really discourages me.
Could somebody explain how I can avoid this overhead?
How peoples work with wide DF instead of using vectorassembler and getting performance decreasing?
More formal question (for sof rules) sound like - How can I speed up this code?

%%time tmp = (df_states.select('ObjectPath', 'User', 'PropertyFlagValue')        .groupBy('User')        .pivot('ObjectPath')        .agg({'PropertyFlagValue':'max'})        .fillna(0)) ignore = ['User'] assembler = VectorAssembler(     inputCols=[x for x in tmp.columns if x not in ignore],     outputCol='features') Wall time: 36.7 s  print(tmp.count(), len(tmp.columns)) 552, 9378  %%time transformed = assembler.transform(tmp).select('User', 'features').cache() Wall time: 10min 45s  %%time lst_levels = [] for num in range(3, 14):     kmeans = KMeans(k=num, maxIter=50)     model = kmeans.fit(transformed)     lst_levels.append(model.computeCost(transformed)) rs = [i-j for i,j in list(zip(lst_levels, lst_levels[1:]))] for i, j in zip(rs, rs[1:]):     if i - j < j:         print(rs.index(i))         kmeans = KMeans(k=rs.index(i) + 3, maxIter=50)         model = kmeans.fit(transformed)         break  Wall time: 1min 32s 

Config:

.config("spark.sql.pivotMaxValues", "100000") \ .config("spark.sql.autoBroadcastJoinThreshold", "-1") \ .config("spark.sql.shuffle.partitions", "4") \ .config("spark.sql.inMemoryColumnarStorage.batchSize", "1000") \ 

1 Answers

Answers 1

This solution is perhaps unsatisfying, but it's true: avoid using VectorAssembler with wide data. It doesn't seem built for that use case. Try to run an equivalent computation on a long format instead.

VectorAssembler adds in a lot of info about the column types as it evaluates the data structure.

So now you have two problems. First, as just mentioned, initial processing time blows up. Second, you've introduced overhead in performing transformations because your transforming much larger monster than the original data set. See the transform function in the link to see what I'm talking about.

Read More

Wednesday, January 17, 2018

pandas .plot() x-axis tick frequency — how can I show more ticks?

Leave a Comment

I am plotting time series using pandas .plot() and want to see every month shown as an x-tick.

Here is the dataset structure data set

Here is the result of the .plot()

enter image description here

I was trying to use examples from other posts and matplotlib documentation and do something like

ax.xaxis.set_major_locator(    dates.MonthLocator(revenue_pivot.index, bymonthday=1,interval=1)) 

But that removed all the ticks :(

I also tried to pass xticks = df.index, but it has not changed anything.

What would be the rigth way to show more ticks on x-axis?

2 Answers

Answers 1

The right way to do that described here Using the x_compat parameter, it is possible to suppress automatic tick resolution adjustment

df.A.plot(x_compat=True)

Answers 2

No need to pass any args to MonthLocator. Make sure to use x_compat in the df.plot() call per @Rotkiv's answer.

import pandas as pd import numpy as np import matplotlib.pylab as plt import matplotlib.dates as mdates  df = pd.DataFrame(np.random.rand(100,2), index=pd.date_range('1-1-2018', periods=100)) ax = df.plot(x_compat=True) ax.xaxis.set_major_locator(mdates.MonthLocator()) plt.show() 
Read More

Thursday, December 28, 2017

Why are numpy functions so slow on pandas series / dataframes?

Leave a Comment

Consider a small MWE, taken from another question:

DateTime                Data 2017-11-21 18:54:31     1 2017-11-22 02:26:48     2 2017-11-22 10:19:44     3 2017-11-22 15:11:28     6 2017-11-22 23:21:58     7 2017-11-28 14:28:28    28 2017-11-28 14:36:40     0 2017-11-28 14:59:48     1 

The goal is to clip all values with an upper bound of 1. My answer uses np.clip, which works fine.

np.clip(df.Data, a_min=None, a_max=1) array([1, 1, 1, 1, 1, 1, 0, 1]) 

Or,

np.clip(df.Data.values, a_min=None, a_max=1) array([1, 1, 1, 1, 1, 1, 0, 1]) 

Both of which return the same answer. My question is about the relative performance of these two methods. Consider -

df = pd.concat([df]*1000).reset_index(drop=True)  %timeit np.clip(df.Data, a_min=None, a_max=1) 1000 loops, best of 3: 270 µs per loop  %timeit np.clip(df.Data.values, a_min=None, a_max=1) 10000 loops, best of 3: 23.4 µs per loop 

Why is there such a massive difference between the two, just by calling values on the latter? In other words...

Why are numpy functions so slow on pandas objects?

4 Answers

Answers 1

Yes, it seems like np.clip is a lot slower on pandas.Series than on numpy.ndarrays. That's correct but it's actually (at least asymptomatically) not that bad. 8000 elements is still in the regime where constant factors are major contributors in the runtime. I think this is a very important aspect to the question, so I'm visualizing this (borrowing from another answer):

# Setup  import pandas as pd import numpy as np  def on_series(s):     return np.clip(s, a_min=None, a_max=1)  def on_values_of_series(s):     return np.clip(s.values, a_min=None, a_max=1)  # Timing setup timings = {on_series: [], on_values_of_series: []} sizes = [2**i for i in range(1, 26, 2)]  # Timing for size in sizes:     func_input = pd.Series(np.random.randint(0, 30, size=size))     for func in timings:         res = %timeit -o func(func_input)         timings[func].append(res)  %matplotlib notebook  import matplotlib.pyplot as plt import numpy as np  fig, (ax1, ax2) = plt.subplots(1, 2)  for func in timings:     ax1.plot(sizes,               [time.best for time in timings[func]],               label=str(func.__name__)) ax1.set_xscale('log') ax1.set_yscale('log') ax1.set_xlabel('size') ax1.set_ylabel('time [seconds]') ax1.grid(which='both') ax1.legend()  baseline = on_values_of_series # choose one function as baseline for func in timings:     ax2.plot(sizes,               [time.best / ref.best for time, ref in zip(timings[func], timings[baseline])],               label=str(func.__name__)) ax2.set_yscale('log') ax2.set_xscale('log') ax2.set_xlabel('size') ax2.set_ylabel('time relative to {}'.format(baseline.__name__)) ax2.grid(which='both') ax2.legend()  plt.tight_layout() 

enter image description here

It's a log-log plot because I think this shows the important features more clearly. For example it shows that np.clip on a numpy.ndarray is faster but it also has a much smaller constant factor in that case. The difference for large arrays is only ~3! That's still a big difference but way less than the difference on small arrays.

However, that's still not an answer to the question where the time difference comes from.

The solution is actually quite simple: np.clip delegates to the clip method of the first argument:

>>> np.clip?? Source:    def clip(a, a_min, a_max, out=None):     """     ...     """     return _wrapfunc(a, 'clip', a_min, a_max, out=out)  >>> np.core.fromnumeric._wrapfunc?? Source:    def _wrapfunc(obj, method, *args, **kwds):     try:         return getattr(obj, method)(*args, **kwds)     # ...     except (AttributeError, TypeError):         return _wrapit(obj, method, *args, **kwds) 

The getattr line of the _wrapfunc function is the important line here, because np.ndarray.clip and pd.Series.clip are different methods, yes, completely different methods:

>>> np.ndarray.clip <method 'clip' of 'numpy.ndarray' objects> >>> pd.Series.clip <function pandas.core.generic.NDFrame.clip> 

Unfortunately is np.ndarray.clip a C-function so it's hard to profile it, however pd.Series.clip is a regular Python function so it's easy to profile. Let's use a Series of 5000 integers here:

s = pd.Series(np.random.randint(0, 100, 5000)) 

For the np.clip on the values I get the following line-profiling:

%load_ext line_profiler %lprun -f np.clip -f np.core.fromnumeric._wrapfunc np.clip(s.values, a_min=None, a_max=1)  Timer unit: 4.10256e-07 s  Total time: 2.25641e-05 s File: numpy\core\fromnumeric.py Function: clip at line 1673  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   1673                                           def clip(a, a_min, a_max, out=None):   1674                                               """   ...   1726                                               """   1727         1           55     55.0    100.0      return _wrapfunc(a, 'clip', a_min, a_max, out=out)  Total time: 1.51795e-05 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================     55                                           def _wrapfunc(obj, method, *args, **kwds):     56         1            2      2.0      5.4      try:     57         1           35     35.0     94.6          return getattr(obj, method)(*args, **kwds)     58                                                59                                               # An AttributeError occurs if the object does not have     60                                               # such a method in its class.     61                                                62                                               # A TypeError occurs if the object does have such a method     63                                               # in its class, but its signature is not identical to that     64                                               # of NumPy's. This situation has occurred in the case of     65                                               # a downstream library like 'pandas'.     66                                               except (AttributeError, TypeError):     67                                                   return _wrapit(obj, method, *args, **kwds) 

But for np.clip on the Series I get a totally different profiling result:

%lprun -f np.clip -f np.core.fromnumeric._wrapfunc -f pd.Series.clip -f pd.Series._clip_with_scalar np.clip(s, a_min=None, a_max=1)  Timer unit: 4.10256e-07 s  Total time: 0.000823794 s File: numpy\core\fromnumeric.py Function: clip at line 1673  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   1673                                           def clip(a, a_min, a_max, out=None):   1674                                               """   ...   1726                                               """   1727         1         2008   2008.0    100.0      return _wrapfunc(a, 'clip', a_min, a_max, out=out)  Total time: 0.00081846 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================     55                                           def _wrapfunc(obj, method, *args, **kwds):     56         1            2      2.0      0.1      try:     57         1         1993   1993.0     99.9          return getattr(obj, method)(*args, **kwds)     58                                                59                                               # An AttributeError occurs if the object does not have     60                                               # such a method in its class.     61                                                62                                               # A TypeError occurs if the object does have such a method     63                                               # in its class, but its signature is not identical to that     64                                               # of NumPy's. This situation has occurred in the case of     65                                               # a downstream library like 'pandas'.     66                                               except (AttributeError, TypeError):     67                                                   return _wrapit(obj, method, *args, **kwds)  Total time: 0.000804922 s File: pandas\core\generic.py Function: clip at line 4969  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4969                                               def clip(self, lower=None, upper=None, axis=None, inplace=False,   4970                                                        *args, **kwargs):   4971                                                   """   ...   5021                                                   """   5022         1           12     12.0      0.6          if isinstance(self, ABCPanel):   5023                                                       raise NotImplementedError("clip is not supported yet for panels")   5024                                              5025         1           10     10.0      0.5          inplace = validate_bool_kwarg(inplace, 'inplace')   5026                                              5027         1           69     69.0      3.5          axis = nv.validate_clip_with_axis(axis, args, kwargs)   5028                                              5029                                                   # GH 17276   5030                                                   # numpy doesn't like NaN as a clip value   5031                                                   # so ignore   5032         1          158    158.0      8.1          if np.any(pd.isnull(lower)):   5033         1            3      3.0      0.2              lower = None   5034         1           26     26.0      1.3          if np.any(pd.isnull(upper)):   5035                                                       upper = None   5036                                              5037                                                   # GH 2747 (arguments were reversed)   5038         1            1      1.0      0.1          if lower is not None and upper is not None:   5039                                                       if is_scalar(lower) and is_scalar(upper):   5040                                                           lower, upper = min(lower, upper), max(lower, upper)   5041                                              5042                                                   # fast-path for scalars   5043         1            1      1.0      0.1          if ((lower is None or (is_scalar(lower) and is_number(lower))) and   5044         1           28     28.0      1.4                  (upper is None or (is_scalar(upper) and is_number(upper)))):   5045         1         1654   1654.0     84.3              return self._clip_with_scalar(lower, upper, inplace=inplace)   5046                                              5047                                                   result = self   5048                                                   if lower is not None:   5049                                                       result = result.clip_lower(lower, axis, inplace=inplace)   5050                                                   if upper is not None:   5051                                                       if inplace:   5052                                                           result = self   5053                                                       result = result.clip_upper(upper, axis, inplace=inplace)   5054                                              5055                                                   return result  Total time: 0.000662153 s File: pandas\core\generic.py Function: _clip_with_scalar at line 4920  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4920                                               def _clip_with_scalar(self, lower, upper, inplace=False):   4921         1            2      2.0      0.1          if ((lower is not None and np.any(isna(lower))) or   4922         1           25     25.0      1.5                  (upper is not None and np.any(isna(upper)))):   4923                                                       raise ValueError("Cannot use an NA value as a clip threshold")   4924                                              4925         1           22     22.0      1.4          result = self.values   4926         1          571    571.0     35.4          mask = isna(result)   4927                                              4928         1           95     95.0      5.9          with np.errstate(all='ignore'):   4929         1            1      1.0      0.1              if upper is not None:   4930         1          141    141.0      8.7                  result = np.where(result >= upper, upper, result)   4931         1           33     33.0      2.0              if lower is not None:   4932                                                           result = np.where(result <= lower, lower, result)   4933         1           73     73.0      4.5          if np.any(mask):   4934                                                       result[mask] = np.nan   4935                                              4936         1           90     90.0      5.6          axes_dict = self._construct_axes_dict()   4937         1          558    558.0     34.6          result = self._constructor(result, **axes_dict).__finalize__(self)   4938                                              4939         1            2      2.0      0.1          if inplace:   4940                                                       self._update_inplace(result)   4941                                                   else:   4942         1            1      1.0      0.1              return result 

I stopped going into the subroutines at that point because it already highlights where the pd.Series.clip does much more work than the np.ndarray.clip. Just compare the total time of the np.clip call on the values (55 timer units) to one of the first checks in the pandas.Series.clip method, the if np.any(pd.isnull(lower)) (158 timer units). At that point the pandas method didn't even start at clipping and it already takes 3 times longer.

However several of these "overheads" become insignificant when the array is big:

s = pd.Series(np.random.randint(0, 100, 1000000))  %lprun -f np.clip -f np.core.fromnumeric._wrapfunc -f pd.Series.clip -f pd.Series._clip_with_scalar np.clip(s, a_min=None, a_max=1)  Timer unit: 4.10256e-07 s  Total time: 0.00593476 s File: numpy\core\fromnumeric.py Function: clip at line 1673  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   1673                                           def clip(a, a_min, a_max, out=None):   1674                                               """   ...   1726                                               """   1727         1        14466  14466.0    100.0      return _wrapfunc(a, 'clip', a_min, a_max, out=out)  Total time: 0.00592779 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================     55                                           def _wrapfunc(obj, method, *args, **kwds):     56         1            1      1.0      0.0      try:     57         1        14448  14448.0    100.0          return getattr(obj, method)(*args, **kwds)     58                                                59                                               # An AttributeError occurs if the object does not have     60                                               # such a method in its class.     61                                                62                                               # A TypeError occurs if the object does have such a method     63                                               # in its class, but its signature is not identical to that     64                                               # of NumPy's. This situation has occurred in the case of     65                                               # a downstream library like 'pandas'.     66                                               except (AttributeError, TypeError):     67                                                   return _wrapit(obj, method, *args, **kwds)  Total time: 0.00591302 s File: pandas\core\generic.py Function: clip at line 4969  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4969                                               def clip(self, lower=None, upper=None, axis=None, inplace=False,   4970                                                        *args, **kwargs):   4971                                                   """   ...   5021                                                   """   5022         1           17     17.0      0.1          if isinstance(self, ABCPanel):   5023                                                       raise NotImplementedError("clip is not supported yet for panels")   5024                                              5025         1           14     14.0      0.1          inplace = validate_bool_kwarg(inplace, 'inplace')   5026                                              5027         1           97     97.0      0.7          axis = nv.validate_clip_with_axis(axis, args, kwargs)   5028                                              5029                                                   # GH 17276   5030                                                   # numpy doesn't like NaN as a clip value   5031                                                   # so ignore   5032         1          125    125.0      0.9          if np.any(pd.isnull(lower)):   5033         1            2      2.0      0.0              lower = None   5034         1           30     30.0      0.2          if np.any(pd.isnull(upper)):   5035                                                       upper = None   5036                                              5037                                                   # GH 2747 (arguments were reversed)   5038         1            2      2.0      0.0          if lower is not None and upper is not None:   5039                                                       if is_scalar(lower) and is_scalar(upper):   5040                                                           lower, upper = min(lower, upper), max(lower, upper)   5041                                              5042                                                   # fast-path for scalars   5043         1            2      2.0      0.0          if ((lower is None or (is_scalar(lower) and is_number(lower))) and   5044         1           32     32.0      0.2                  (upper is None or (is_scalar(upper) and is_number(upper)))):   5045         1        14092  14092.0     97.8              return self._clip_with_scalar(lower, upper, inplace=inplace)   5046                                              5047                                                   result = self   5048                                                   if lower is not None:   5049                                                       result = result.clip_lower(lower, axis, inplace=inplace)   5050                                                   if upper is not None:   5051                                                       if inplace:   5052                                                           result = self   5053                                                       result = result.clip_upper(upper, axis, inplace=inplace)   5054                                              5055                                                   return result  Total time: 0.00575753 s File: pandas\core\generic.py Function: _clip_with_scalar at line 4920  Line #      Hits         Time  Per Hit   % Time  Line Contents ==============================================================   4920                                               def _clip_with_scalar(self, lower, upper, inplace=False):   4921         1            2      2.0      0.0          if ((lower is not None and np.any(isna(lower))) or   4922         1           28     28.0      0.2                  (upper is not None and np.any(isna(upper)))):   4923                                                       raise ValueError("Cannot use an NA value as a clip threshold")   4924                                              4925         1          120    120.0      0.9          result = self.values   4926         1         3525   3525.0     25.1          mask = isna(result)   4927                                              4928         1           86     86.0      0.6          with np.errstate(all='ignore'):   4929         1            2      2.0      0.0              if upper is not None:   4930         1         9314   9314.0     66.4                  result = np.where(result >= upper, upper, result)   4931         1           61     61.0      0.4              if lower is not None:   4932                                                           result = np.where(result <= lower, lower, result)   4933         1          283    283.0      2.0          if np.any(mask):   4934                                                       result[mask] = np.nan   4935                                              4936         1           78     78.0      0.6          axes_dict = self._construct_axes_dict()   4937         1          532    532.0      3.8          result = self._constructor(result, **axes_dict).__finalize__(self)   4938                                              4939         1            2      2.0      0.0          if inplace:   4940                                                       self._update_inplace(result)   4941                                                   else:   4942         1            1      1.0      0.0              return result 

There are still multiple function calls, for example isna and np.where, that take a significant amount of time, but overall this is at least comparable to the np.ndarray.clip time (that's in the regime where the timing difference is ~3 on my computer).

The takeaway should probably be:

  • Many NumPy functions just delegate to a method of the object passed in, so there can be huge differences when you pass in different objects.
  • Profiling, especially line-profiling, can be a great tool to find the places where the performance difference comes from.
  • Always make sure to test differently sized objects in such cases. You could be comparing constant factors that probably don't matter except if you process lots of small arrays.

Used versions:

Python 3.6.3 64-bit on Windows 10 Numpy 1.13.3 Pandas 0.21.1 

Answers 2

Just read the source code, it's clear.

def clip(a, a_min, a_max, out=None):     """a : array_like Array containing elements to clip."""     return _wrapfunc(a, 'clip', a_min, a_max, out=out)  def _wrapfunc(obj, method, *args, **kwds):     try:         return getattr(obj, method)(*args, **kwds)     #This situation has occurred in the case of     # a downstream library like 'pandas'.     except (AttributeError, TypeError):         return _wrapit(obj, method, *args, **kwds)  def _wrapit(obj, method, *args, **kwds):     try:         wrap = obj.__array_wrap__     except AttributeError:         wrap = None     result = getattr(asarray(obj), method)(*args, **kwds)     if wrap:         if not isinstance(result, mu.ndarray):             result = asarray(result)         result = wrap(result)     return result 

rectify:

after pandas v0.13.0_ahl1,pandas has it's own implement of clip.

Answers 3

There are two parts to the performance difference to be aware of here:

  • Python overhead in each library (pandas being extra helpful)
  • Difference in numeric algorithm implementation (pd.clip actually calls np.where)

Running this on a very small array should demonstrate the difference in Python overhead. For numpy, this is understandably very small, however pandas does a lot of checking (null values, more flexible argument processing, etc) before getting to the heavy number crunching. I've tried to show a rough breakdown of the stages which the two codes go through before hitting C code bedrock.

data = pd.Series(np.random.random(100)) 

When using np.clip on an ndarray, the overhead is simply the numpy wrapper function calling the object's method:

>>> %timeit np.clip(data.values, 0.2, 0.8)        # numpy wrapper, calls .clip() on the ndarray >>> %timeit data.values.clip(0.2, 0.8)            # C function call  2.22 µs ± 125 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) 1.32 µs ± 20.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 

Pandas spends more time checking for edge cases before getting to the algorithm:

>>> %timeit np.clip(data, a_min=0.2, a_max=0.8)   # numpy wrapper, calls .clip() on the Series >>> %timeit data.clip(lower=0.2, upper=0.8)       # pandas API method >>> %timeit data._clip_with_scalar(0.2, 0.8)      # lowest level python function  102 µs ± 1.54 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) 90.4 µs ± 1.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) 73.7 µs ± 805 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) 

Relative to overall time, the overhead of both libraries before hitting C code is pretty significant. For numpy, the single wrapping instruction takes as much time to execute as the numeric processing. Pandas has ~30x more overhead just in the first two layers of function calls.

To isolate what is happening at the algorithm level, we should check this on a larger array and benchmark the same functions:

>>> data = pd.Series(np.random.random(1000000))  >>> %timeit np.clip(data.values, 0.2, 0.8) >>> %timeit data.values.clip(0.2, 0.8)  2.85 ms ± 37.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 2.85 ms ± 15.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)  >>> %timeit np.clip(data, a_min=0.2, a_max=0.8) >>> %timeit data.clip(lower=0.2, upper=0.8) >>> %timeit data._clip_with_scalar(0.2, 0.8)  12.3 ms ± 135 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 12.3 ms ± 115 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 12.2 ms ± 76.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 

The python overhead in both cases is now negligible; time for wrapper functions and argument checking is small relative to the calculation time on 1 million values. However there is a 3-4x speed difference which can be attributed to numeric implementation. By investigating a bit in the source code, we see that the pandas implementation of clip actually uses np.where, not np.clip:

def clip_where(data, lower, upper):     ''' Actual implementation in pd.Series._clip_with_scalar (minus NaN handling). '''     result = data.values     result = np.where(result >= upper, upper, result)     result = np.where(result <= lower, lower, result)     return pd.Series(result)  def clip_clip(data, lower, upper):     ''' What would happen if we used ndarray.clip instead. '''     return pd.Series(data.values.clip(lower, upper)) 

The additional effort required to check each boolean condition separately before doing a conditional replace would seem to account for the speed difference. Specifying both upper and lower would result in 4 passes through the numpy array (two inequality checks and two calls to np.where). Benchmarking these two functions shows that 3-4x speed ratio:

>>> %timeit clip_clip(data, lower=0.2, upper=0.8) >>> %timeit clip_where(data, lower=0.2, upper=0.8)  11.1 ms ± 101 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 2.97 ms ± 76.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 

I'm not sure why the pandas devs went with this implementation. np.clip may be a newer API function that previously required a workaround. There is also a little more to it than I've gone into here, since pandas checks for various case before running the final algorithm, and this is only one of the implementations that may be called.

Answers 4

The reason why the performance differs is because numpy first tends to search for pandas implementation of the function using getattr than doing the same in builtin numpy functions when a pandas object is passed.

Its not the numpy over the pandas object that is slow, its the pandas version.

When you do

np.clip(pd.Series([1,2,3,4,5]),a_min=None,amax=1)   

_wrapfunc is being called :

# Code from source  def _wrapfunc(obj, method, *args, **kwds):     try:         return getattr(obj, method)(*args, **kwds) 

Due to _wrapfunc's getattr method :

getattr(pd.Series([1,2,3,4,5]),'clip')(None, 1) # Equivalent to `pd.Series([1,2,3,4,5]).clip(lower=None,upper=1)` # 0    1 # 1    1 # 2    1 # 3    1 # 4    1 # dtype: int64 

If you go through the pandas implementation there is a lot of pre checking work that is done. Its the reason why the functions which has the pandas implementation done via numpy has such difference in speed.

Not only clip, functions like cumsum,cumprod,reshape,searchsorted,transpose and much more uses pandas version of them than numpy when you pass them a pandas object.

It might appear numpy is doing the work over those objects but under the hood its the pandas function.

Read More