Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
362,500
45,111,589
Dropping NaN rows doesn't work in pandas
<p>I have a file with about 7k rows and 4 columns. A lot of the cells are empty and I have tried to drop them using a number of pandas functions but nothing seems to work. Functions I have tried and the code are below:</p> <p>What I have tried:</p> <pre><code>df = df.dropna(thresh=2) </code></pre> <p>and</p> <pre>...
<p><code>dropna</code> is not an inplace operation, you need to reassign it back to the variable or use the <code>inplace</code> parameter set to True.</p> <pre><code>df = df.dropna(axis=0, how='all') </code></pre> <p>or </p> <pre><code>df.dropna(axis=0, how='all', inplace=True) </code></pre> <h1>Edit</h1> <p>Jay ...
python|pandas
2
362,501
44,892,700
python matrix when both row and column size are large
<p>I want to create a 2D matrix in python when number of rows and columns are equal and it is around 231000. Most of the cell entries would be zero. Some [i][j] entries would be non-zero.</p> <p>The reason for creating this matrix is to apply SVD and get [U S V] matrices with rank of say 30. </p> <p>Can anyone provi...
<p>I think this is a duplicate question, but I'll answer this anyways.</p> <p>There are several libraries in python aimed at dealing with <em>partial</em> svds on very sparse matrices. </p> <p>My personal preference is <code>scipy.sparse.linalg.svds</code>, a <a href="https://en.wikipedia.org/wiki/ARPACK" rel="nofoll...
python|pandas
1
362,502
45,220,247
Pandas Excel Writer using Openpyxl with existing workbook
<p>I have code from a while ago that I am re-using for a new task. The task is to write a new DataFrame into a new sheet, into an existing excel file. But there is one part of the code that I do not understand, but it just makes the code "work".</p> <p>working:</p> <pre><code>from openpyxl import load_workbook import...
<p>In the source code of ExcelWriter, with openpyxl, it initializes empty workbook and delete all sheets. That's why you need to add it explicitly</p> <pre><code>class _OpenpyxlWriter(ExcelWriter): engine = 'openpyxl' supported_extensions = ('.xlsx', '.xlsm') def __init__(self, path, engine=None, **engine...
python|excel|pandas|openpyxl|xlsxwriter
2
362,503
44,865,023
How can I create a circular mask for a numpy array?
<p>I am trying to circular mask an image in Python. I found some example code on the web, but I'm not sure how to change the maths to get my circle in the correct place.</p> <p>I have an image <code>image_data</code> of type <code>numpy.ndarray</code> with shape <code>(3725, 4797, 3)</code>:</p> <pre><code>total_rows...
<p>The algorithm you got online is partly wrong, at least for your purposes. If we have the following image, we want it masked like so:</p> <p><a href="https://i.stack.imgur.com/Tr5bL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Tr5bL.png" alt="Image to mask"></a> <a href="https://i.stack.imgur.com/Hcsl9....
python|arrays|numpy|image-processing
86
362,504
45,086,121
Assigning values when two dfs have different indexes
<p>I have two dfs that look like this:</p> <pre><code>Symbol Sector Sub-industry Company Weight SectorSymbol Ticker MMM Industrials Conglomerates MCompany 0.602676 XLI ABT Health Care Equipment Abbott Lab 0.401900 XLV ABBV Health Care Pharmaceuticals AbbVie Inc 0...
<p>1) Create a dictionary mapping symbols to sector symbols.</p> <p>2) Use a list comprehension to get an ordered mapping of all sector symbols for the relevant symbols. Use <code>get</code> on the dictionary to allow for unmapped securities (see comments below).</p> <p>3) Use <code>groupby</code> on the sector symb...
python|pandas|dataframe
1
362,505
45,070,959
AtributeError: 'module' object has no attribute 'plt' - Seaborn
<p>I'm very new with these libraries and i'm having troubles while plotting this:</p> <pre><code>import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np import random df5 = pd.read_csv('../../../../datos/tiempos-exacto-variando-n-m0.csv', sep=', ', engine='python') print(df5) df5[...
<p><code>sns.plt.show()</code> works fine for me using seaborn 0.7.1. Could be that this is different in other versions. However, if you anyways <code>import matplotlib.pyplot as plt</code> you may as well simply use <code>plt.show()</code>, as <code>sns.plt.show()</code> is only working because <code>pyplot</code> is ...
python|pandas|matplotlib|seaborn
36
362,506
45,107,956
How to get Python to open a file that I have just created?
<p>So I am outputting a CSV using Python and Pandas, based on a certain criteria I have. Once building the the CSV file, I'd like to run a command that has Python open the CSV file in Excel. </p> <p>Would something like this people possible?</p>
<p>If you know the location of your Excel executable:</p> <pre><code>import subprocess subprocess.call(("path/to/Excel.exe", "path/to/your.csv")) </code></pre> <p>If you don't know the location (but Excel is set as default app for <code>.csv</code> files) it depends on the OS you're using, but since you want Excel I...
python|file|csv|pandas
3
362,507
57,120,555
decode TFRecord fail. Expected image (JPEG, PNG, or GIF), got unknown format starting with '\257\
<p>I encoded some images to TFRecords as an example and then try to decode them. However, there is a bug during the decode process and I really cannot fix it.</p> <p>InvalidArgumentError: Expected image (JPEG, PNG, or GIF), got unknown format starting with '\257\222\244\257\222\244\260\223\245\260\223\245\262\225\247\...
<p>I can use tf.io.decode_raw() to decode the TFRecords and then use tf.reshape() to get the original image. While still don't know when to use tf.io.decode_raw() and when to use tf.io.decode_jpeg().</p>
image|tensorflow|deep-learning|computer-vision|tfrecord
0
362,508
57,273,221
Convert the month difference into integer
<p>The dataset with datetime columns as below, I converted to the period as month and calculated the difference. I would like to convert the output as an integer, but failed to do it.</p> <pre><code>ID StartDate CurrentDate a 2019-03-05 2019-06-18 b 2019-02-05 2019-07-20 c 2019-01-23 2019-07-2...
<p>Let's have some fun with pandas.tseries.offsets:</p> <p>Using your code, you can get the number of offsets, n, by using the <code>apply</code> to retreive this attribute from the pandas.tseries.offsets object like this:</p> <pre><code>df['start_month_year'] = df['StartDate'].dt.to_period('M') df['current_month_yea...
python-3.x|pandas|datetime
2
362,509
57,254,669
Understanding fit_generator (steps_per_epoch), validation_steps, evaluate_generator (Steps) & predict_generator (steps)
<p>I am new in using keras for my project. I have been working with <code>generator</code> in my model. </p> <p>I am literally confused what value should i input </p> <blockquote> <p>1) In fit_generator : steps_per_epoch &amp; validation_steps ? </p> <p>2) evaluate_generator : steps ? </p> <p>3) predict_g...
<p>Steps are not a parameter that you "choose", you can compute it as:</p> <pre><code>steps = number of samples / batch size </code></pre> <p>So here the only parameter that you are free to choose is the batch size, which is chosen to a value where the model does not run out of memory while training. Typical values a...
python|tensorflow|keras|generator
2
362,510
57,265,099
How can I get the Hours from the column created_time of sample dataframe and get count of it as another dataframe
<p>sample dataframe(df) having following columns:</p> <pre><code> id created_time faid 0 21 2019-06-17 07:06:45 FF1854155 1 54 2019-04-12 08:06:03 FF30232 2 88 2019-04-20 05:36:03 FF1855531251 3 154 2019-04-26 07:09:22 FF8145292 4 ...
<p>try calculating hours from created_time.</p> <p>groupby hour and count it</p> <pre><code>df['hour'] = pd.to_datetime(df['created_time']).dt.hour res = df.groupby(['hour'],as_index=False)['faid'].count().rename(columns={"faid":"count"}) </code></pre> <pre><code>hour count 07 2 08 2 </code></pre>
pandas|pandas-groupby
1
362,511
57,267,088
How to define tf.layer.dense in a for loop for creating dynamics number of hidden layers and hidden unit?
<p>I am looking for a way where we can use tensorflow API to create a neural network with the number of layer and hidden units as user defined.</p> <p>Lets say I have a neural network like this</p> <pre><code>hidden1 = tf.layers.dense(inp, units=32, kernel_initializer=tf.initializers.he_uniform(),activation=tf.nn.re...
<p>You can do it like this:</p> <pre class="lang-py prettyprint-override"><code>from keras.layers import Dense, BatchNormalization, Dropout from keras.layers.advanced_activations import ReLU from keras.models import Model # Define the number of units per hidden layer layer_widths = [128, 64, 32] # Set up input laye...
python|tensorflow
2
362,512
57,199,248
(memory-)efficient operations between arbitrary columns of numpy array
<p>I have a large 2D numpy array. I would like to be able to efficiently run row-wise operations on subsets of the columns, without copying the data.</p> <p>In what follows, <code>a = np.arange(1000000).reshape(1000, 10000)</code> and <code>columns = np.arange(1, 1000, 2)</code>. For reference,</p> <pre><code>In [4]...
<p>On this one <code>pythran</code> seems a bit faster than <code>numba</code> at least on my rig:</p> <pre><code>import numpy as np #pythran export col_sum(float[:,:], int[:]) #pythran export col_sum(int[:,:], int[:]) def col_sum(data, idx): return data.T[idx].sum(0) </code></pre> <p>Compile with <code>pythran...
python|arrays|numpy|cython
3
362,513
57,250,721
Extract minimum values only in a dataframe
<p>I have the following dataframe:</p> <pre><code>Quantity_Limit Cost Wholesaler_Code 2 9.2 1 2 9.4 1 2 7.1 2 4 10.2 1 4 4.1 2 4 2.1 3 </code></pre> <p>And I would like to create the following d...
<p>You can use <code>transform</code> to create a column with the minimum values and filter based on those.</p> <pre><code>df["min_cost"] = df.groupby(["Quantity_Limit"])["Cost"].min() df[df["Cost"] == df["min_cost"]] </code></pre>
python|pandas
2
362,514
57,074,704
Fill Empty Panda Dataframe Using Loop Method
<p>I am currently working with some telematics data where the trip id is missing. Trip id is unique. 1 trip id contains multiple of rows of data consisting i.e gps coordinate, temp, voltage, rpm, timestamp, engine status (on or off). The data pattern indicate time of engine status on and off, can be cluster as a unique...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>series.eq()</code></a> to check for <code>OFF</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>series....
pandas|loops
3
362,515
56,901,107
Join two DataFrames by index and columns
<p>I'm trying to join two <code>DataFrames</code> by index that can contain columns in common and I only want to add one to the other if that specific value is <code>NaN</code> or doesn't exist. I'm using the pandas example, so I've got:</p> <pre><code>df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], ...
<p>This is a good use case for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>combine_first</code></a>, where the row and column indices of the resulting dataframe will be the union of the two, i.e in the absence of an index in on...
python|pandas
4
362,516
57,056,304
How to fix ‘TypeError: a bytes-like object is required, not 'str'’ error in tts python code
<p>I want to train LJSpeech data with convolutional networks on my own. I've recently found auseful code on web. I set everything done, but just before the process of training (like a loading box shows up) i'm getting a type error. I have tried search for it on web, but nothing familiar came up. So i want to share the ...
<p>Try replacing</p> <pre><code>mel = "mels/{}".format(fname.replace("wav", "npy")) mag = "mags/{}".format(fname.replace("wav", "npy")) </code></pre> <p>with</p> <pre><code>mel = "mels/{}".format(fname.decode("utf-8").replace("wav", "npy")) mag = "mags/{}".format(fname.decode("utf-8").replace("wav", "npy")) </code><...
python|tensorflow|text-to-speech
0
362,517
56,941,860
Tensorflow Python: Method for multi-class labels
<p>I am using the Abalone Dataset (<a href="https://archive.ics.uci.edu/ml/datasets/Abalone" rel="nofollow noreferrer">https://archive.ics.uci.edu/ml/datasets/Abalone</a>) and it has data of certain abalones, with features such as sex, diameter, length, and weight. I want to be able to use the diameter, length, and wei...
<p><strong>try this</strong></p> <pre><code>from sklearn.preprocessing import OneHotEncoder sex_label = abalone_dataframe['sex'].values sex_label_onehot = OneHotEncoder(sparse=False).fit_transform(sex_label .reshape(-1,1)) </code></pre>
python|tensorflow
0
362,518
56,898,069
How to use tensorflow-hub module with tensorflow-dataset api
<p>I want to use Tensorflow Dataset api to initialize my dataset using tensorflow Hub. I want to use dataset.map function to convert my text data into embedding. My Tensorflow version is 1.14.</p> <p>Since I used elmo v2 modlule which converts bunch of sentences array into their word embeddings, I used the following c...
<p>Unfortunately this is not supported in TensorFlow 1.x</p> <p>It is, however, supported in TensorFlow 2.0 so if you can upgrade to tensorflow 2 and choose from the available text embedding modules for tf 2 (current list <a href="https://tfhub.dev/google/tf2-preview/nnlm-en-dim128/1" rel="nofollow noreferrer">here</a...
python|tensorflow|tensorflow-datasets|tensorflow-hub
2
362,519
57,146,985
Selecting values with Pandas multiindex using lists of tuples
<p>I have a DataFrame with a MultiIndex with 3 levels:</p> <pre><code>id foo bar col1 0 1 a -0.225873 2 a -0.275865 2 b -1.324766 3 1 a -0.607122 2 a -1.465992 2 b -1.582276 3 b -0.718533 7 1 a -1.904252 2 a 0.588496 2 b -1.057...
<p>The list of tuples is not the problem. The fact that each tuple does not correspond to a <em>single index</em> is the problem (Since a <code>list</code> isn't a valid <code>key</code>). If you want to index a Dataframe like this, you need to expand the lists inside each tuple to their own entries.</p> <hr> <p>De...
pandas|pandas-groupby
1
362,520
56,996,420
Python - Trouble pulling data from multiple excel files in folder
<p>I am trying to write a script that will open/look through every excel workbook inside a folder, pull specific values from each of those workbooks, and then paste those values into a new csv. </p> <p>My script (see below), and all 49 workbooks are located in the following path: C:\Users\user.name\Desktop\Excel Test....
<p>There could be a couple of problems. It may be trying to open non-excel files in the directory. After your os.listdir() call, try to filter for excel files only. </p> <p>Or your excel file may be formatted incorrectly. </p>
python|pandas
0
362,521
56,921,796
requestAnimFrame is executed multiple times
<p>I have an emotion detection running with openCV.js for the face detection and tensorflow.js for the emotion classification. When I start the emotion detection I call the requestAnimFrame(myProcessingLogic) function and pass my detection logic to the callback parameter. My processing logic calls the requestAnimFrame(...
<p>Found the bug myself. It had nothing to do with the code posted above. On each start of the emotion tracking I was adding an EventListener to the video element. The EventListener on the other hand executed startVideoProcessing. Since those eventlistener stack on each other they were executed multiple times. </p> <p...
javascript|opencv|requestanimationframe|tensorflow.js|cancelanimationframe
0
362,522
56,992,430
TensorFlow: multithreaded unbatching of datasets
<p>I am using TensorFlow 2.0 beta. I have a TensorFlow <code>Dataset</code> where each element is a batch of feature columns: a tuple of tensors where each has the values of a particular feature for <code>batch_size</code> records. I need to flatten these records for serialization as <code>TFRecords</code>, which I wou...
<p>Here is the version that I ultimately found, using <code>interleave</code> with <code>from_tensor_slices</code>:</p> <pre><code>batch_size = 100 num_batches = 10 num_threads = 4 input_data = (tf.constant(['text_data']), tf.constant(13)) ds = tf.data.Dataset.from_tensors(input_data).repeat(batch_size * num_batches) ...
tensorflow|tensorflow-datasets|tensorflow2.0
0
362,523
56,918,377
Pandas not working with linear regression
<p>I am trying to run a regression some data from a dataframe, but I keep getting this weird shape error. Any idea what is wrong?</p> <pre><code>import pandas as pd import io import requests import statsmodels.api as sm # Read in a dataset url="https://raw.githubusercontent.com/jldbc/coffee-quality-database/master/d...
<p>You have your <code>X</code> and <code>y</code> terms in the wrong order in your <code>sm.OLS</code> command:</p> <pre><code>import pandas as pd import io import requests import statsmodels.api as sm # Read in a dataset url="https://raw.githubusercontent.com/jldbc/coffee-quality-database/master/data/arabica_data_...
python|pandas|regression|linear-regression|statsmodels
0
362,524
56,923,731
converting dataframe column from object to date not datetime
<p>I am using python version 3.7.</p> <p>I have a dataframe, df that contains one column called TDate.</p> <p>The column looks like below.</p> <pre><code> 2019-01-01 00:00:00 2019-01-02 00:00:00 2019-01-03 00:00:00 2019-01-04 00:00:00 </code></pre> <p>When I do df.dtypes it tell me the column is of type object.<...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>Series.dt.floor</code></a> for remove time information from column (or better it is set to default <code>00:00:00</code> value in each datetime):</p> <pre><code>myDates = pd.to_datetim...
python|pandas|dataframe
2
362,525
57,022,175
Boolean intersection based on connected neighborhood - NumPy / Python
<p>Having these two arrays:</p> <pre><code>import numpy as np arr1 = np.array([[0,0,0,0,1,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,1,0,0,1,0], [0,0,0,0,0,0]], dtype=bool) arr2 = np.array([[0,1,1,0,0,0], [0,1,1,0,0,0], [...
<p><strong>Approach #1</strong></p> <p>We can use image-processing based labeling function to label the image based on connected-ness and then use masking to get our desired output. To do the labeling, we can use <a href="https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.label" rel="nofollow n...
python|numpy|image-processing|boolean|intersection
2
362,526
56,968,815
Trying to get the first item in a list within a panda dataframe
<p>I am a newbie to Python and Pandas and am trying to resolve an issue.</p> <p>I have a pandas dataframe which contains a column, where the column data is a string, with values separated by a hyphen,</p> <pre><code>import pandas as pd data = [['item 1 - item 2 - item 3'],['item 4 - item 5 - item 6 '],['item 7 - i...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a>, get first value of lists by indexing and last call <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.strip.html" rel="no...
python|pandas|dataframe
1
362,527
57,157,616
Turn an hourly temperature table into a single time series in pandas?
<p>I have a pandas data frame with the following customer data from a 24 hour shopping location: </p> <pre><code>Date #Cust at 00:00 Items/Cust at 00:00 Ttl Items at 00:00 #Cust at 01:00 Items/Cust at 01:00 Ttl Items at 01:00 ....#Cust at 23:00 Items/Cust at 23:00 Ttl Items at 23:00 1/1/2018 2 ...
<p>You can create index by columns without <code>at</code> first by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a>, then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Serie...
python|pandas
1
362,528
57,079,522
SettingWithCopyWarning when using .str on pandas
<p>I am trying to apply a .str[] to a pandas data from so I can get specific characters from a string but I get a "SettingWithCopyWarning" error.</p> <pre><code>import pandas as pd df_temp = pd.read_csv("C:\\Users\\Bill-PC\\PycharmProjects\\QC Data\\Testing\\10 PP 1 2 again.txt", sep="\t", low_memory=False) df_temp ...
<p>By the way this is not an error it is just a warning but try this I hope warning would not be shown</p> <pre><code>df.loc[:,"City"] = df['City'].str[-1:] </code></pre>
python|pandas
0
362,529
57,221,459
Using input parameters of defined function inside apply function
<p>Maybe a very naive question, but I am stuck in this: pandas.DataFrame.apply has a possibility to put inside a function.</p> <pre><code># define function for further usage def get_string(df): string_input = [] for id, field in enumerate(df.index): string_input.append('&lt;field id="{0...
<p>You are confusing between <code>df</code> the global variable and <code>df</code> the local variable.</p> <p>The <code>get_string</code> function defines input variable called <code>df</code> and this will overshadow any variable of the same name from higher scopes. The <code>df</code> that <code>get_string</code> ...
python|pandas|apply
1
362,530
57,071,035
Compare the example of Pytorch and Keras on Cifar10 data
<p>I use CIFAR10 dataset to learn how to code using Keras and PyTorch.</p> <p>The environment is <strong>Python 3.6.7, Torch 1.0.0, Keras 2.2.4, Tensorflow 1.14.0</strong>. I use the <strong>same batch size, number of epochs, learning rate and optimizer</strong>. I use <strong>DenseNet121</strong> as the model.</p> <...
<p>You are not supposed to softmax the model output before you pass it to <code>CrossEntropyLoss</code>. Per the documentation:</p> <blockquote> <p>This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class.</p> <p>...</p> <p>The input is expected to contain raw, unnormalized scores for e...
tensorflow|keras|pytorch
1
362,531
57,227,597
How to extend dataframe to length of list?
<p>I'm using a code to update my column using a list. It works as long as the list length shorter than the df index, since I'm using a workaround code by updating the column by using pd.series. Here's what I mean below. </p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = [ ['a' , 'Hell...
<pre><code>col = 'ColB' temp = list(df[col].dropna()) df = df.drop(columns= col ) temp.append('Sup') temp.append('Chao') pd.concat([df, pd.DataFrame(temp).rename(columns ={0:'ColB'})], axis=1 ) ColA ColB 0 a Hello 1 b Hi There 2 c Hola 3 d Sup 4 NaN Chao </code></pre> <p>This is probably ineffic...
python|pandas|dataframe|series
0
362,532
56,882,617
Python returns NaN value list as column values
<p>I want to read a column from excel file using pandas in python. But it returns NaN list.</p> <p><a href="https://i.stack.imgur.com/ZhVjo.png" rel="nofollow noreferrer">This is the code I used</a></p> <pre><code>from pandas import DataFrame import pandas as pd data = pd.read_excel (r'D:\Pandas\1 (179).xlsx') df ...
<p>Your excel file does not start with the first line, there are several description in it before.</p> <p>You need to skip some rows:</p> <pre><code>df = pd.read_excel(r'D:\Pandas\1 (179).xlsx',skiprows=5) </code></pre> <p>see the documentation for more adjustments: <a href="https://pandas.pydata.org/pandas-docs/sta...
python|excel|python-3.x|pandas
1
362,533
56,907,470
Copying dataframes through variables vs copying through variables for columns
<p>I have been playing with python and understanding the concept of copying a dataframe through the .copy function as opposed to just reassigning it to a variable.</p> <p>Let's say we have the following data frame: dfx:</p> <pre><code> Name Score1 Score2 Score3 Score4 0 Jack 10 Perfect...
<p>You are referencing <code>dfx3</code> and <code>dfx</code> to one DataFrame, if you want to do manipulations on <code>dfx3</code>with columns similar to that <code>dfx</code>'s then you should make a copy of <code>dfx</code> on <code>dfx3</code> not reference them both to the same DataFrame. </p> <pre><code>dfx3 = ...
python|python-3.x|pandas|dataframe
0
362,534
57,087,708
Facing an Error while creating a new column
<p>Original dataframe :</p> <pre><code>df.head() &gt; beer_beerid review_profilename review_overall 0 48215 stcules 3.0 1 52159 oline73 3.0 2 52159 alpinebryant 3.0 3 52159 rawthar 4.0 4 ...
<p>Here's the solution. </p> <pre><code>df['beer_review_count'] = df.groupby('beer_beerid')['beer_beerid'].transform('count') </code></pre> <p>It works fine by using <strong>transform()</strong></p> <pre><code>beer_beerid profilename overall beer_review_count 0 48215 stcules 3.0 1 1 ...
python|pandas
0
362,535
57,203,726
Pandas sort columns by name
<p>I have the following dataframe, where I would like to sort the columns according to the name. </p> <pre><code>1 | 13_1 | 13_10| 13_2 | 2 | 3 9 | 31 | 2 | 1 | 3 | 4 </code></pre> <p>I am trying to sort the columns in the following way:</p> <pre><code>1 | 2 | 3 | 13_1 | 13_2 | 13_10 9 | 3 | 4...
<h3><a href="https://pypi.org/project/natsort/" rel="nofollow noreferrer"><code>natsort</code></a></h3> <pre><code>from natsort import natsorted df = df.reindex(natsorted(df.columns), axis=1) # 1 2 3 13_1 13_2 13_10 #0 9 3 4 31 1 2 </code></pre>
python|pandas
7
362,536
56,891,456
timedelta64[ns] -> FutureWarning: Passing timedelta64-dtype data is deprecated, will raise a TypeError in a future version
<p>Assuming <code>df['time']</code> is from type <code>timedelta64[ns]</code> and <code>df['a']</code> as well as <code>df['b']</code> are from type <code>float64</code>, the two series can be plotted like this:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt fig, axs = plt.subplots(2, sharex=True) ...
<p>I faced the same issue when reading time data from SQL using pandas. These 2 lines solved my problem. I tried to find another direct solution without success. </p> <pre><code>time_values = df['time'].apply(lambda x: np.nan if pd.isnull(x) else str(x)[-8:]) time_values = pd.to_datetime(time_values, format='%H:%M:%S'...
python|python-3.x|pandas|matplotlib|plot
1
362,537
56,888,436
Unique non-zero elements in a tensorflow tensor
<p>Say I have a tensorflow tensor <code>A</code>, i would like to know if there is a one-liner to find all unique values in <code>A</code> except <code>0</code> (or more realistically, a short way to do so). It would be quite similar the more pythonic :</p> <pre><code>import numpy as np A = np.array([2,2,2,0,1,3,3]) ...
<p>In TensorFlow you would do that like this:</p> <pre><code>import tensorflow as tf with tf.Graph().as_default(), tf.Session() as sess: data = tf.placeholder(tf.int32, [None]) data_unique, _ = tf.unique(data) data_unique_nonzero = tf.boolean_mask(data_unique, tf.not_equal(data_unique, 0)) print(sess....
python|tensorflow
1
362,538
57,170,178
how to use .to_csv to write data to tsv file without combining everything in one column?
<p>I try to copy some data from a .xlsx file to a .tsv file, but when I use to_csv it combined everything in one column. </p> <p>I tried this </p> <pre><code>times = pd.read_excel(“timing.xlsx", 'Sheet1', index = False, delimiter='\t') with open('example.tsv', 'wt') as out_file: tsv_writer = csv.writer(out_fil...
<p>Pass sep=‘\t’ parameter in .to_csv</p>
python|pandas
0
362,539
56,951,733
Setting calculated value for column for each group in a dataframe
<p>I have dataframe where I need to group by column x and change all the values of column a in every group to a calculated, but constant value for each group. </p> <p>I start with a dataframe like this:</p> <pre><code>x | a | b ------+------+----- a | -1 | ... b | -1 | ... c | -1 | ....
<p>What you want to do is </p> <pre><code>df['a'] = p[df.groupby('x').ngroup() % len(p)] # TypeError here </code></pre> <p>Unfortunately, you cannot directly broadcast to a Python list so this will raise a </p> <pre><code>TypeError: list indices must be integers or slices, not Series </code></pre> <p>But numpy nda...
python|pandas|pandas-groupby
1
362,540
57,152,041
array concatenation giving error in python
<p>I have two arrays</p> <pre><code>array_1.shape #(961,300) array_2.shape #(961,9) </code></pre> <p>when I am concatenating the whole arrays I am not getting any error:</p> <pre><code> np.column_stack((array_1,array_2)) </code></pre> <p>but when I am concatenating the first element of each, I am getting the erro...
<p>using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html" rel="nofollow noreferrer">np.hstack</a> instead will prevent this error, and it will give you the intended (309,)-shaped output</p>
python|arrays|pandas|numpy
1
362,541
57,137,860
Shorter way of boolean indexing in pandas (Series and DataFrame)?
<p>I want to know if there is a shorter way for boolean indexing in pandas? Nowadays I make like that:</p> <pre class="lang-py prettyprint-override"><code>s = pd.Series(...) s[s&gt;0] </code></pre> <p>But it becomes cumbersome when the variable has a long name or if I do not have the Series/DataFrame stored in a vari...
<p>Let us do <code>loc</code></p> <p>For <code>Series</code></p> <pre><code>s.loc[lambda x : x &gt;0] </code></pre> <p>For <code>DataFrame</code></p> <pre><code>df.loc[lambda x : x['code']&gt;0] </code></pre>
python|pandas
2
362,542
57,208,488
Convert lower triangle half to Symmertic matrix using numpy
<p>I have a matrix which has to be transformed to a symmetric matrix using python numpy.</p> <p>Apparently, using the following code in am able to transform to symmetric matrix .. this work fine for small matrix but for a large 150 * 151</p> <pre><code> I get the following error...operands could not be broadcast tog...
<p>You don't have a square matrix. 150 x 151 is not a square matrix! The reason it worked for smaller example because it was a square matrix (3 x 3). The example on which you are trying to work is not a square matrix. Please there is a transpose operator in the code (see below towards right). </p> <pre class="lang-py ...
python|numpy|data-science
1
362,543
57,171,899
Faster way to flatten list in Pandas Dataframe
<p>I have a dataframe below:</p> <pre><code>import pandas df = pandas.DataFrame({"terms" : [[['the', 'boy', 'and', 'the goat'],['a', 'girl', 'and', 'the cat']], [['fish', 'boy', 'with', 'the dog'],['when', 'girl', 'find', 'the mouse'], ['if', 'dog', 'see', 'the cat']]]}) </code></pre> <p>My desired outcome is as foll...
<p>This is certainly no way to avoid loops here, at least not implicitely. Pandas is not created to handle <code>list</code> objects as elements, it deals magnificently with numeric data, and pretty well with strings. In any case, your fundamental problem is that you are using <code>pd.Dataframe.append</code> in a loop...
python|pandas|list|dataframe|flatten
3
362,544
57,184,551
Assigning string to variable in conditional gives error
<p>I want to have a dynamic marker type for my scatter plot. So, I have something like this:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt x = pd.DataFrame(np.random.randint(20,40,size=(5,1))) y = pd.DataFrame(np.random.randint(24,26,size=(5,1))) if x &lt;= 30: marker_type = '...
<p>if you make you if loop as below, this error will disappear.</p> <pre><code>if x &lt;= 30: marker_type = 'o' fill_type = 'full' label_type = "var &lt;= 30" else: pass if x &gt; 30 and symbols_x &lt;= 40: marker_type = 'o' fill_type = 'none' label_type = "30 &lt; var &lt;= 40" else: ...
python|pandas|matplotlib
0
362,545
56,928,253
Value of one column based on first max in second column after groupby
<p>I have a dataframe as below, where I do a groupby on <code>Itr</code> and <code>Type</code>:</p> <ul> <li>How do I get the value in <code>Start</code> for the row in each group where <code>Values</code> column is max?</li> <li><strong>I only want the first max; there are multiple rows where <code>Values</code> is m...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> if need new columns in original <code>DataFrame</code>:</p> <pre><code>g = df.groupby(['Itr','Type']) df['max_val'] = g['Val...
python|pandas|pandas-groupby
3
362,546
45,888,400
Using tf.name_scope in Tensorboard with Tensorflow Estimator
<p>I have some code to calculate performance metrics within my <code>Estimator</code> model_fn written in a function that returns a dictionary of metrics</p> <pre><code>def __model_eval_metrics(self, classes, labels, mode): if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL: retur...
<p>I solved this by using the same "folder" prefix for the metric name (eval) as the name scope for summary (train):</p> <pre><code>r2 = metrics_r2(labels, predictions) metrics = {'metrics/r2': r2} with tf.name_scope('metrics'): tf.summary.scalar('r2', r2[1]) if mode == tf.estimator.ModeKeys.EVAL: return tf.e...
tensorflow|tensorboard
1
362,547
45,770,810
Creating a confusion matrix in python
<p>I am having issues creating a confusion matrix in python. I currently have the following csv file with a table organized in two columns as presented:</p> <pre><code>---------- Letter | Code A | ["13.45", "16.59", "12.28"] B | ["13.45", "18.20"] C | ["13.45", "18.20", "19.30"] </code><...
<p>You could use <code>apply</code> and <code>set</code> <code>intersection</code></p> <p>For individual column </p> <pre><code>In [607]: A = df.query('letter == "A"').code.item() In [608]: df.code.apply(lambda x: len(set(x).intersection(A))) / len(A) Out[608]: 0 1.000000 1 0.333333 2 0.333333 Name: code, d...
python|pandas
0
362,548
46,136,952
How faster is tensorflow-gpu with AVX and AVX2 compared with it without AVX and AVX2?
<p>How faster is <code>tensorflow-gpu</code> with AVX and AVX2 compared with it without AVX and AVX2?</p> <p>I tried to find an answer using Google but with no success. It's hard to recompile <code>tensorflow-gpu</code> for Windows. So, I want to know if it worth it.</p>
<p>If your computation is one giant matmul on CPU, you will get 3x speed-up on Xeon V3 (see benchmark <a href="https://github.com/tensorflow/tensorflow/issues/7257#issuecomment-277456370" rel="noreferrer">here</a>). But it's also possible to see no speed-up, presumably because there's not enough time spent in high arit...
performance|tensorflow
12
362,549
46,040,487
Python performance improvements and coding style
<p><strong>Question</strong></p> <p>Let's assume the following sparse table is given indicating the listing of a security on an index.</p> <pre><code>identifier from thru AAPL 1964-03-31 -- ABT 1999-01-03 2003-12-31 ABT 2005-12-31 -- AEP 1992-01-15 2017-08-31 KO ...
<pre><code># Ensure dates are Pandas timestamps. df['from'] = pd.DatetimeIndex(df['from']) df['thru'] = pd.DatetimeIndex(df['thru'].replace('--', np.nan)) # Get sorted list of all unique dates and create index for full range. dates = sorted(set(df['from'].tolist() + df['thru'].dropna().tolist())) dti = pd.DatetimeInde...
python|performance|pandas
2
362,550
45,796,741
Number of business days between DateTimeIndex and columns of dates
<p>I have a dataframe of dates with a DateTimeIndex like this:</p> <pre><code>pd.DataFrame(['01-20-2017']*len(pd.date_range('01-01-2017', '01-30-2017')), columns=['Dates'], index=pd.date_range('01-01-2017', '01-30-2017')) </code></pre> <p>I would like to add a column that counts the difference in BUSINESS DAYS betwee...
<p>use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.busday_count.html" rel="nofollow noreferrer">np.busday_count()</a> </p> <pre><code>df = pd.DataFrame({'begin' : pd.date_range('01-01-2017', '01-30-2017'), 'end' : ['01-20-2017']*len(pd.date_range('01-01-2017', '01-30-2017'))}) df['begin'] = p...
pandas|datetimeindex
1
362,551
45,965,741
Python Regression of Categorical data with interactions
<p>I have found how people do linear regressions on Python using sklearn and doing <code>reg.fit()</code> with their data, but this only lets you do it if you're looking for a regression like <code>y = Ax1 + Bx2 +Cx3</code> etc</p> <p>But what if I had categorical data that had some sort of interactions such that I w...
<p>To take care of the interactions between input features such as x1, x2 and x3, the common practice is to create polynomial features such as x1^3, x1^2*x2 + x1*x2*x3 + ... + x3^3. For example, in your case, your equation for y would look like the following:</p> <pre><code>y = A*x1^3 + B*x2^3 + C*x3^3 + D*x1^2*x2 + E...
python|pandas|scikit-learn|linear-regression|non-linear-regression
1
362,552
46,167,824
How to perform linear correlation on a data set and return the column name which has the most correlation?
<p>I am working on a data set which has the closing prices of a stock.</p> <pre><code>'GOOG' : [ 742.66, 738.40, 738.22, 741.16, 739.98, 747.28, 746.22, 741.80, 745.33, 741.29, 742.83, 750.50 ], 'FB' : [ 108.40, 107.92, 109.64, 112.22, 109.57, 113.82, 114.03, 112.24, ...
<p>You could use pandas <em>corr</em> function by converting your dictionary into a dataframe. This function returns the correlation matrix for the numeric columns in your dataframe.</p> <pre><code>import pandas as pd prices = { 'GOOG' : [ 742.66, 738.40, 738.22, 741.16, 739.98, 747.28, 746.22, 74...
python|python-3.x|numpy|vector|correlation
2
362,553
46,056,648
Save model checkpoint only when model shows improvement in TensorFlow
<p>Do you know if there is a way to chose which model is saved when using Estimator wrapped in an experiment? Because every 'save_checkpoints_steps', the model is saved but this model is not necessarily the best.</p> <pre class="lang-py prettyprint-override"><code>def model_fn(features, labels, mode, params): predi...
<p>Checkpoints are saved for the event that your training process is interrupted. If you don't have checkpoints you will need to restart from scratch. This is a big issue for big models that take weeks to train.</p> <p>Once your training is done and you are satisfied with your model (in your words, "it is the best"), ...
python|tensorflow|save
2
362,554
45,912,419
KeyError when trying to access a newly assigned column in a pandas dataframe
<p>None of the solution on KeyError posts addressed my problem hence this question:</p> <p>I have the following column in a Pandas DataFrame:</p> <pre><code>df['EventDate'] 0 26-12-2016 1 23-12-2016 2 16-12-2016 3 15-12-2016 4 11-12-2016 5 10-12-2016 6 07-12-2016 </co...
<p>The fundamental misunderstanding here is that you think doing </p> <pre><code>df.year = ... </code></pre> <p>Creates a column called <code>year</code> in <code>df</code>, but this is <em>not</em> true! Observe:</p> <pre><code>print(df) Col1 0 26-12-2016 1 23-12-2016 2 16-12-2016 3 15-12-2016 4 11-1...
python|pandas|dataframe|keyerror
3
362,555
46,120,619
How to write a 3 channel image into a tiff file?
<p>I don't find any clear explanation of how to make a 3 channel image with tifffile. I tried (all values are between 0 and 1)</p> <pre><code>image = [(0.5,0.2145,0), (1,0.214568,0.324586).... ] side = int(len(image)**(1/2)) R,G,B = zip(*image) R = np.array(R).reshape((side,side)) G = np.array(G).reshape((side,side)) ...
<p>I emailed Christoph Gohlke, the developer of Tifffile.py and heres his answer</p> <pre><code>E.g. tifffile.imsave('rgb.tif', numpy.zeros((256, 256, 3), 'uint16')) </code></pre> <p>For some reason it didn't work using a (n,n,3) shape worked perfectly (3,n,n) shaped numpy array instead. Note : the RGB values are int...
python|numpy|tiff
1
362,556
45,747,823
Is there any way to install pandas on pypy2-v5.8.0-win32?
<p>Windows 7 64bit.I had install numpy 1.10.0 successfully via.<br/><code>pypy -m pip install git+https://bitbucket.org/pypy/numpy.git</code><br/> Then,I tried three method(pip+git,pip,easy_install) to install pandas,however,<strong>all failed,why</strong>?</p> <p><strong>method</strong>:<br/><code>pip install git+htt...
<ol> <li>We no longer recommend using <a href="https://bitbucket.org/pypy/numpy.git" rel="nofollow noreferrer">https://bitbucket.org/pypy/numpy.git</a>, as documented <a href="https://pypy.org/download.html#installing-numpy" rel="nofollow noreferrer">here</a> we now recommend using the upstream standard numpy repo.</l...
pandas|pypy
0
362,557
46,144,058
Python - Filter DataFrame by flexible length dict
<p>I got a DataFrame like this:</p> <pre><code> A B C 1 1 3 5 2 1 3 6 3 2 4 7 4 2 4 8 </code></pre> <p>I know I can filter fixed column as below:</p> <pre><code>df[df[A]==1 &amp; df[B]==3] </code></pre> <blockquote> <p>But if I want to filter the DataFrame by flexible length of dict:</p> <pr...
<p>If your dictionary has its values in a list then you can pass it to the DataFrame <code>isin</code> method.</p> <pre><code>d = {'A':[1], 'B':[3], 'C':[5]} df[df.isin(d)[list(d.keys())].all(axis=1)] A B C 1 1 3 5 </code></pre> <p>If you have lots of items in your dictionary, you can automate the conversion...
python|pandas|dictionary|dataframe
2
362,558
45,872,933
Extract text enclosed between a delimiter and store it as a list in a separate column
<p>I have a <code>Panda</code> dataframe with a text column in the format below. There are some values/text meshed in between <code>##</code>. I want to find such text which are present between <code>##</code> and extract them in a separate column as a list.</p> <pre><code>##fare_curr.currency####based_fare_90d.price#...
<p>Given this df</p> <pre><code>df = pd.DataFrame({'data': ['##fare_curr.currency####based_fare_90d.price##', 'htt://www.abcd.lol/abcd-Search?\ from:##based_best_flight_fare_90d.air##,to:##mbased_90d.water##,departure:# #mbased_90d.date_1##TANYT&amp;pas=ch:0Y&amp;mode=search']}) </code></pre> <p>You can get desired r...
python|pandas
1
362,559
45,968,880
How to extract formatted cells and their corresponding rows in Excel
<p>SO, my problem is as follows:</p> <p>Using this script written below, I have successfully formatted certain cells in the extracted excel sheet. It is intended to accept any excel file as long as it is entered correctly and is in the same format (which for my purposes will always be in the same format).</p> <p>My n...
<p>The loop you wrote is incorrect. That's because <code>df==format1</code> is equivalent to the boolean <code>True</code>. If you want to print <code>i</code> only when some condition holds, do:</p> <pre><code>upperBound = 1000 for i in range(upperBound): if df==format1: print(i) </code></pre>
excel|pandas|xlsxwriter
0
362,560
46,090,981
python - ValueError: time data does not match format
<p>I downloaded my CSV file TSLA.csv from <a href="https://finance.yahoo.com/quote/TSLA/history?period1=1277762400&amp;period2=1504735200&amp;interval=1d&amp;filter=history&amp;frequency=1d" rel="nofollow noreferrer">here</a>. It has a header line and 7 columns, first of which is date, the others are floats and ints.</...
<p>Okay, I believe the problem is here:</p> <p>Have a look again at the error, it says <code>"['2010-06-29" does not match data format</code>. That is because you are not trying to parse the date alone, look at the double quotes that surround the date.</p> <p>You are trying to parse:</p> <pre><code>['2010-06-29 </c...
python|csv|numpy|date-conversion
2
362,561
46,101,897
Removing characters from a dataframe column
<p>Below is the code for extracting the matching values from Category List and dataset.</p> <pre><code>matches= token.apply(lambda x: pd.Series(x).str.extractall("|".join(["({})".format(cat) for cat in Categories.HealthCare]))) match_list= [[m for m in match.values.ravel() if isinstance(m, str)] for match in matches] ...
<p>You can call <code>.str.replace</code>:</p> <pre><code>match_df['HealthCare'] = match_df['HealthCare']\ .astype(str).str.replace(r"[\[\]']", '') </code></pre>
python|regex|python-3.x|pandas|dataframe
1
362,562
45,804,810
memory error while reading csv file from s3 using pandas & boto3. Error in `python': free(): invalid pointer:
<p>I am trying to read a 1.5 GB file from s3 using pandas &amp; boto3 Today I had to pivot a 36 GB deep file into a wide file (1.5 GB) . I wrote the 1.5 GB file to local and checked if everything was alright using pandas.read_csv(). It read without any issues.</p> <p>But after copying to s3 while reading using boto3 t...
<p>The reason you see this error on EC2/S3 but not locally may be due to the C environment on the VM instance you're using. Your local machine may just have a more compatible C setup than whatever came bundled on your VM.</p> <p>To fix the issue, consider setting <code>engine='python'</code> or <code>low_memory=True</...
python|pandas|csv|amazon-s3|boto3
1
362,563
46,112,077
Scipy sparse matrix multiplication much slower than numpy array
<p>I have constructed the following case to test one-dimensional sparse matrix multiplication vs numpy arrays.</p> <pre><code>from scipy.sparse import csc_matrix sp = csc_matrix((1, 36710)) sp[0,4162] = 0.2335 sp[0,21274] = 0.1367 sp[0,27322] = 0.261 sp[0,27451] = 0.9266 %timeit sp.dot(sp.T) arr = sp.toarray()[0] %ti...
<p>In hpaulj's answer, M*M is not a matrix multiplication -- it's just an element-wise multiplication. This is why M*M is much faster than matrix multiplication. So in all case matrix multiplication is much slower for csr matrix.</p>
numpy|scipy|sparse-matrix
2
362,564
46,102,485
How to append a string from dictionary?
<pre><code>X = corpus.get("Andrew Shapiro") testsite_array = [] with X as my_file: for line in my_file: testsite_array.append(line) </code></pre> <p>where corpus is a dictonary and Andrew Shapiro is an item in it. It gives me following error.</p> <pre><code> File "C:/Users/Vrushab PC/Downloads/Disser...
<p>In order to use the with statement, the object, X in this case, the object must have implemented the <strong>enter</strong> method and <strong>exit</strong> method. The whole point is that it allow for the object to clean it's self up even in the case of an exception. Think try:except:finally done much more cleanly....
python|pandas|numpy
0
362,565
45,900,449
Keras model.predict always 0
<p>I am using keras applications for transfer learning with resnet 50 and inception v3 but when predicting always get <code>[[ 0.]]</code> </p> <p>The below code is for a binary classification problem. I have also tried vgg19 and vgg16 but they work fine, its just resnet and inception. The dataset is a 50/50 split. ...
<p>I was running into similar problem. You are scaling all the RGB values from 0-255 to 0-1 during training.</p> <p>Thse same should be done at the time of prediction. Try <code>x = img_to_array(img) x = x/255</code></p>
python|tensorflow|keras|conv-neural-network|resnet
11
362,566
45,907,088
Comparing NumPy arange and custom range function for producing ranges with decimal increments
<p>Here's a custom function that allows stepping through decimal increments:</p> <pre><code>def my_range(start, stop, step): i = start while i &lt; stop: yield i i += step </code></pre> <p>It works like this:</p> <pre><code>out = list(my_range(0, 1, 0.1)) print(out) [0, 0.1, 0.2, 0.300000000...
<p>The difference in endpoints is because NumPy calculates the length up front instead of ad hoc, because it needs to preallocate the array. You can see this in the <a href="https://github.com/numpy/numpy/blob/dfc3eba72841e95fe2be44e1194dc5f77a1e2ec2/numpy/core/src/multiarray/ctors.c#L3007" rel="noreferrer"><code>_calc...
python|arrays|numpy|range
10
362,567
45,844,799
Filter numpy array if elements in subarrays are repeated position-wise in the other subarrays
<p>Unluckily it is terribly similar to: <a href="https://stackoverflow.com/questions/45841160/filter-a-numpy-array-if-any-list-within-it-contains-at-least-one-value-of-a-prev/45841462?noredirect=1#comment78646997_45841462">Filter a numpy array if any list within it contains at least one value of a previous row</a> whic...
<h2>Edit:</h2> <p>My initial solution doesn't consistently produce the result you're looking for, example at bottom.</p> <p>So here's an alternative solution, which actually iterates through the rows as seems necessary:</p> <pre><code>ar = b.copy() new_rows = [] while ar.shape[0]: new_rows.append(ar[0]) ar =...
python|arrays|numpy
2
362,568
45,973,339
Sandwich the data cell with 0 value in Python with pandas
<p>My dataset has this format (the first row is header)</p> <pre><code>0 1 2 3 4 5 6 7 8 9 10 Nan 6 5 8 9 2 Nan Nan Nan Nan Nan Nan 3 8 Nan Nan Nan Nan Nan Nan Nan Nan Nan 5 9 2 4 Nan Nan Nan Nan Nan Nan </code></pre> <p>I want to insert 0 ...
<p>One way to do this, if your list of values doesn't have a NaN in the middle, is to use <code>T</code> and <code>fillna</code> with a <code>limit=2</code>:</p> <pre><code>df1 = df.replace('Nan',np.nan) #Make sure those Nan are really np.nan df1.T.fillna(0,limit=2).T </code></pre> <p>Output:</p> <pre><code> 0 1 ...
python|database|pandas
4
362,569
46,009,662
Can I do str manipulation like this in pandas?
<p>I have used pandas to get my data looking like the dict in the code below.</p> <p>I want to find all the salsa types, and put them in a dict with number of items with that salsa type being the dictionary value.</p> <p>Here it is in Python. Is there a way to do a thing like this in Pandas? Or is this task where I...
<p>This can be done without using for loops one of the way is creating a separated df by <code>stacking</code> the columns and then <code>replacing the values</code> after that <code>dropping the values</code> which do not contain <code>alsa</code>. Then finally using <code>value_counts</code> to get the frequency. </p...
python|pandas
1
362,570
46,063,428
Filling a pandas dataframe with repeating values
<p>I have this code in R</p> <pre><code>a &lt;- c(NA) a&lt;- matrix(c(a), nrow = 80) a&lt;-as.data.frame(a) a[ c(T,F,F,F), ] &lt;- "aaa" a[ c(F,T,F,F), ] &lt;- "bbb" a[ c(F,F,T,F), ] &lt;- "ccc" a[ c(F,F,F,T), ] &lt;- "ddd" </code></pre> <p>How can I replicate it in python as a pandas data frame?</p> <pre><code>str...
<p>You could use <code>np.tile</code> and construct a series.</p> <pre><code>import pandas as pd import numpy as np s = pd.Series(np.tile(['aaa', 'bbb', 'ccc', 'ddd'], 20) ) print(s.shape) # size - 80 rows (80,) print(s.head(10)) # shows only the first 10 rows 0 aaa 1 bbb 2 ccc 3 ddd 4 aaa 5 bbb 6...
python|pandas|dataframe|repeat
6
362,571
23,222,442
Drop columns from pandas dataframe, regardless of whether ALL column names are present
<p>I would like to use <code>df.drop(drop_list, axis=1)</code> to remove a number of columns from my data frame, however if an entry from <code>drop_list</code> is not present in <code>df.columns.tolist()</code>, the command fails, how can I prevent this from happening?</p>
<pre><code>df.drop(set(drop_list) &amp; set(df.columns), axis=1) </code></pre>
python|filter|pandas|dataframe
3
362,572
23,268,605
Grouping indices of unique elements in numpy
<p>I have many large (>100,000,000) lists of integers that contain many duplicates. I want to get the indices where each of the element occur. Currently I am doing something like this:</p> <pre><code>import numpy as np from collections import defaultdict a = np.array([1, 2, 6, 4, 2, 3, 2]) d=defaultdict(list) for i,e...
<p>This is very similar to what was asked <a href="https://stackoverflow.com/questions/23159791/find-the-indices-of-non-zero-elements-and-group-by-values">here</a>, so what follows is an adaptation of my answer there. The simplest way to vectorize this is to use sorting. The following code borrows a lot from the implem...
python|python-2.7|numpy
10
362,573
23,138,112
VTK to Matplotlib using Numpy
<p>I want to extract some data (e.g. scalars) from a <strong>VTK</strong> file along with their coordinates on the grid then process it in <strong>Matplotlib</strong>. The problem is I dont know how to grab the point/cell data from the VTK file (by giving the name of the scalar, for instance) and load them into a <str...
<p>I finally figured a way (maybe not the optimal) that does the job. The example here is contour plotting a temperature field extracted from a vtk file:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.cm as cm from scipy.interpolate import griddata import numpy as np import vtk from vtk.util.numpy_su...
python|arrays|numpy|matplotlib|vtk
11
362,574
23,345,577
Updating a dataframe with boolean sub-indexing
<p>Say I have a dataframe, and I want to replace any entries higher than 1 with 1. The dataframe has several dtypes (strings, numbers and dates) so:</p> <pre><code>df.gt(1.2) </code></pre> <p>returns:</p> <pre><code>AttributeError: 'float' object has no attribute 'view' </code></pre> <p>If I do:</p> <pre><code>df[...
<p>you could always do something like this.</p> <pre><code>df.update((df[cols] &gt; 1.2).replace((True, False), (1, np.nan)) </code></pre>
python|pandas
2
362,575
23,037,548
Change main plot legend label text
<p>So far I have been able to label the subplots just fine but I'm having an issue with the main one.</p> <p>Here's the relevant part of my code:</p> <pre><code>data_BS_P = data[channels[0]] data_BS_R = data[channels[1]] data_BS_Y = data[channels[2]] plot_BS_P = data_BS_P.plot() #data_BS_P is a pandas dataframe axBS ...
<p>Another way:</p> <pre><code>ax.legend(labels=mylabels) </code></pre>
python|matplotlib|pandas|label|legend
91
362,576
23,055,793
How to generate group based columns faster?
<p>I'd like to create a column for my dataframe that is based on anther column. For example, I have a dataframe like this: </p> <pre><code> Content Date ID Bob birthday 2010.03.01 Bob school 2010.04.01 Tom shopping 2010.02.01 Tom work 2010.09.01 Tom holiday 2010.10.0...
<p>See this issue here: <a href="https://github.com/pydata/pandas/issues/6496" rel="nofollow">https://github.com/pydata/pandas/issues/6496</a>.</p> <p>These are equivalent, but 2nd is faster</p> <pre><code>In [41]: %timeit grp.transform(np.size) 1 loops, best of 3: 442 ms per loop In [40]: %timeit pd.concat([ Series...
python|pandas
1
362,577
23,334,211
Converting CSV file to HDF5 using pandas
<p>When i use pandas to convert csv files to hdf5 files the resulting file is extremely large. For example a test csv file (23 columns, 1.3 million rows) of 170Mb results in an hdf5 file of 2Gb. However if pandas is bypassed and the hdf5 file is directly written (using pytables) it is only 20Mb. In the following code (...
<p><a href="http://pandas-docs.github.io/pandas-docs-travis/io.html#io-perf" rel="nofollow">Here's</a> an informal comparison of times/sizes for various IO method</p> <p>Using 0.13.1 on 64-bit linux</p> <p>Setup</p> <pre><code>In [3]: N = 1000000 In [4]: df = DataFrame(dict([ ("int{0}".format(i),np.random.randint(0...
python|pandas|hdf5
2
362,578
35,366,970
Theano.function equivalent in Tensorflow
<p>I am wondering if there is any equivalent to </p> <pre class="lang-none prettyprint-override"><code>theano.function(inputs=[x,y], # list of input variables outputs=..., # what values to be returned updates=..., # “state” values to be modified givens=..., # substitutions to the graph) </code></pre> <p>in TensorFlo...
<p>The <code>run</code> method on the <a href="https://www.tensorflow.org/versions/v0.6.0/api_docs/python/client.html#Session" rel="noreferrer"><code>tf.Session</code></a> class is quite close to <code>theano.function</code>. Its <code>fetches</code> and <code>feed_dict</code> arguments are moral equivalents of <code>o...
python|numpy|theano|tensorflow
5
362,579
35,489,990
Converting list of tuples with varying number of elements into columns in a Pandas Dataframe
<p>This is my first post. I am coding a combinatorial algorithm for an engineering project at University. I am using Python and Pandas..</p> <p>I have a Pandas dataframe with several columns, one of which is a list of over 20k tuples.<br> The number of elements per tuple vary from <code>1</code> to <code>6.</code> i.e...
<p>You can use a list comprehension to expand your tuples. Given several lists, you can add them together. For example, ['apple'] + ['pear'] = ['apple', 'pear']. And ['apple'] * 2 = ['apple', 'apple'].</p> <p>The same principle applies to tuples, so (10, 20) + (0,) * 4 = (10, 20, 0, 0, 0, 0). The tuples are thus ex...
python|pandas
0
362,580
35,747,837
pandas - different dtype column before/after reading a file
<p>I'm referring to <a href="https://stackoverflow.com/questions/35746039/pandas-get-nested-string-values-from-arrays">this</a> question since I'm facing with a weird behaviour of column types before and after reading the same dataframe from a .csv. Starting from:</p> <pre><code>In [137]: df Out[137]: node1 node...
<p>You might want to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_pickle.html" rel="nofollow">pickle IO</a>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a': [['a', 'b']]}) df.a.dtype df.to_pickle('stuff.pkl.bin') &gt;&gt;&gt; pd.read_pickle('stuff.pkl.bin').a 0 [a, b] Na...
python|pandas
2
362,581
35,503,669
NAN values considered strings in python
<p>I am writing the code for a small application in python and i realize that i get errors in my import data functions when the files (txt, dat, csv ...) contain missing values written like NAN or "NAN" in some of the data, while there is no problem by importing the data if these values are written as nan or NaN.</p> ...
<p>You could add your variables which you'd like to interpret as <code>NaN</code> to <code>na_values</code> argument of the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>pd.read_csv</code></a>:</p> <pre><code>df = pd.read_csv('your_file.csv', na_va...
python|pandas|nan
7
362,582
35,655,671
Plotting DataFrame with column in all subplots
<p>Consider that I have a pandas DataFrame with 3 columns. I would to plot two of these columns as separate subplots and the other one should appear on both the other subplots.</p> <p>To explain better, consider the example</p> <pre><code>x = np.linspace(0,10,5) y1 = 2*x y2 = 3*x y3 = 4*x df = pd.DataFrame(index=x, ...
<p>Like this</p> <pre><code>ax = df[[1,2]].plot(subplots=True, layout=(1,2), ylim=[0,40]) for axe in ax[0]: axe.plot(df.index, df[0]) </code></pre> <p><a href="https://i.stack.imgur.com/cEq6x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cEq6x.png" alt="enter image description here"></a></p>
python|pandas|matplotlib|plot
7
362,583
35,682,758
PTB rnn model one PTBModel object instead of three
<p>in the PTB rnn model, three PTBModel objects are created, namely m, mvalid and mtest: </p> <pre><code>with tf.Graph().as_default(), tf.Session() as session: initializer = tf.random_uniform_initializer(-config.init_scale, config.init_scale) with tf.variable_scope("mod...
<p>Yes, these three objects live in the same graph.</p> <p>The placeholders are different and you need to use the correct one if you want to evaluate particular part of the graph.</p> <p>It would in theory be possible but it is not as trivial. E.g. you could have a training graph unrolled for 20 steps but use only a ...
tensorflow
0
362,584
35,566,368
Inequality joins in Pandas?
<p>I usually use Dataframe.merge to combine dataframes in pandas. From my understanding, this only works on equality joins. What is the idiomatic way to join two dataframes using other types of checks (e.g. inequality)?</p>
<p>merge() is fairly limited. You can accomplish more complex joins using pandasql.sqldf. You can write pretty much any sql query and refer to your existing dataframes as table names in the sql statements.<br> <a href="https://github.com/yhat/pandasql/" rel="noreferrer">https://github.com/yhat/pandasql/</a> A known b...
python|join|pandas|merge|dataframe
9
362,585
35,727,956
python mean of list of lists
<p>I want to find the means of all the negative numbers from a list that has a mix of positive and negative numbers. I can find the mean of the lists as </p> <pre><code>import numpy as np listA = [ [2,3,-7,-4] , [-2,3,4,-5] , [-5,-6,-8,2] , [9,5,13,2] ] listofmeans = [np.mean(i) for i in listA ] </code></pre> <p>I ...
<p>You could use the following:</p> <pre><code>listA = [[2,3,-7,-4], [-2,3,4,-5], [-5,-6,-8,2], [9,5,13,2]] means = [np.mean([el for el in sublist if el &lt; 0] or 0) for sublist in listA] print(means) </code></pre> <p><strong>Output</strong></p> <pre><code>[-5.5, -3.5, -6.3333, 0.0] </code></pre> <p>If none of the...
python|list|numpy|list-comprehension
5
362,586
35,714,832
TensorFlow shuffle_batch not working
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf sess = tf.Session() def add_to_batch(image): print('Adding to batch') image_batch = tf.train.shuffle_batch([image],batch_size=5,capacity=11,min_after_dequeue=1,num_threads=1) # Add to summary tf.image_summary('images',image_batch...
<p>It looks like the problem arises because the statement</p> <pre><code>tf.train.start_queue_runners(sess=sess) </code></pre> <p>...executes before any queue runners have been created. If you move this line after <code>images = get_batch()</code>, your program should work.</p> <p>What is the problem here? The <a hr...
tensorflow
7
362,587
35,556,799
Numpy vectorized summation with variable number of factors
<p>I am currently computing a function that contains a summation over an index. The index is between 0 and the integer part of T; ideally I would like to be able to compute this summation quickly for several values of T. In a real-life case, most of the values of T are small, but a small percentage can be one or two o...
<p>Looking at your <code>j</code>, for each column it has numbers going from <code>1</code> to <code>N</code>, where <code>N</code> is being decided based on each <code>T</code> element. Then, you are summing along each column, which is the same as summing until <code>N</code> because rest of the elements are zeros any...
python|arrays|performance|numpy|vectorization
2
362,588
35,500,425
Using Panda's groupby just to drop repeated items
<p>I'm sure this is a basic question, but I am unable to find the correct path here.</p> <p>Let's suppose a dataframe like this, telling how many fruits each person eats per week:</p> <pre><code> Name Fruit Amount 1 Jack Lemon 3 2 Mary Banana 6 3 Sophie Lemon 1 4 Sophie Cherry 10 5 ...
<p>If you just want some row, you can use a combination of <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow"><code>groupby</code>-<code>first()</code></a> + <code>reset_index</code> - it will retain the first row per group:</p> <pre><code>impo...
python|pandas
4
362,589
35,485,675
How to create a vector of Matrices in python
<p>In my code i have calculated multiple flow map with respect to time and want to store in one list. This is what i want to do in may code</p> <p><a href="https://i.stack.imgur.com/xPOOo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xPOOo.png" alt="enter image description here"></a></p>
<p>Before entering your time loop, create an empty list:</p> <pre><code>listOfFlowMaps = [] </code></pre> <p>Then, after creating your flow map:</p> <pre><code>flowmap = np.array([...]) # your flow map listOfFlowMaps.append(flowmap) # add the flow map to the list </code></pre>
python|opencv|numpy|scipy
2
362,590
35,657,516
pandas: FloatingPointError with np.seterr(all='raise') and missing data
<p>I'm getting a FloatingPointError when I want to look at data involving missing data.</p> <pre><code>import numpy as np import pandas as pd np.seterr(all='raise') s = pd.Series([np.nan,np.nan,np.nan],index=[1,2,3]); print(s); print(s.head()) </code></pre> <p>I'm on the newest version of <code>pandas</code>, instal...
<p>Whenever you <code>import pandas</code>, all numpy errors are set to be ignore. This is currently undocumented behavior.</p> <p>This is done in <a href="https://github.com/pydata/pandas/blob/master/pandas/compat/numpy_compat.py" rel="noreferrer">pandas/compat/numpy_compat.py</a></p> <pre><code># TODO: HACK for Num...
python|numpy|pandas|anaconda
5
362,591
11,895,233
Pythonpath is still ignored and unable to install locally with pip
<p>I'm finding that my pythonpath environment variable is ignored. I'm using python 2.6 on ubuntu. I have in my <code>.bashrc</code> the following:</p> <p><code>export PTYHONPATH=/my/home/mylibs/lib/python2.6/site-packages/:$PYTHONPATH</code></p> <p>Then I install a new version of <code>numpy</code> using:</p> <p><c...
<p>Ok, Python will use the first package it finds. The PYTHONPATH gets appended to sys.path, after the system one. So it will normally find the system one first. But the "official" per-user packages directory seems to be placed before that. So create your personal site-packages directory:</p> <pre><code>mkdir -p $HOME...
python|numpy|pip|setuptools|distutils
2
362,592
11,941,492
Selecting rows from a Pandas dataframe with a compound (hierarchical) index
<p>I'm suspicious that this is trivial, but I yet to discover the incantation that will let me select rows from a Pandas dataframe based on the values of a hierarchical key. So, for example, imagine we have the following dataframe:</p> <pre><code>import pandas df = pandas.DataFrame({'group1': ['a','a','a','b','b','b']...
<p>Try using <code>xs</code> to be very precise:</p> <pre><code>In [5]: df.xs('a', level=0) Out[5]: value1 value2 group2 c 1.1 7.1 c 2.0 8.0 d 3.0 9.0 In [6]: df.xs('c', level='group2') Out[6]: value1 value2 group1 a 1...
python|pandas|dataframe|multi-index
50
362,593
11,615,664
Multivariate normal density in Python?
<p>Is there any python package that allows the efficient computation of the PDF (probability density function) of a <a href="https://en.wikipedia.org/wiki/Multivariate_normal_distribution" rel="noreferrer">multivariate normal distribution</a>?</p> <p>It doesn't seem to be included in Numpy/Scipy, and surprisingly a Goo...
<p>The multivariate normal is now available on <code>SciPy 0.14.0.dev-16fc0af</code>:</p> <pre><code>from scipy.stats import multivariate_normal var = multivariate_normal(mean=[0,0], cov=[[1,0],[0,1]]) var.pdf([1,0]) </code></pre>
python|numpy|scipy|probability
91
362,594
28,837,057
Pandas - Writing an excel file containing unicode - IllegalCharacterError
<p>I have the following code:</p> <pre><code>import pandas as pd x = [u'string with some unicode: \x16'] df = pd.DataFrame(x) </code></pre> <p>If I try to write this dataframe as an excel file:</p> <pre><code>df.to_excel("test.xlsx") </code></pre> <p>Or, if I try to write this dataframe as an excel file, with utf-...
<p>The same problem happened to me. I solved it as follows:</p> <p>First, install python package xlsxwriter:</p> <pre><code>pip install xlsxwriter </code></pre> <p>Second, replace the default engine 'openpyxl' with 'xlsxwriter':</p> <pre><code>df.to_excel("test.xlsx", engine='xlsxwriter') </code></pre>
python|unicode|pandas|export-to-excel
56
362,595
28,462,144
Python version of Matlab Signal Toolbox's tfestimate()?
<p>Is there a Python version of Matlab's tfestimate()? I have looked into the control toolbox but it only offers linear transfer functions.</p>
<p>As shown in the 'more about' section of the <a href="http://it.mathworks.com/help/signal/ref/tfestimate.html" rel="noreferrer">help of tfestimate</a>, the transfer function is calculated more or less as <code>Txy = Pyx / Pxx</code>, so by dividing the cross-spectral-density between <code>y</code> and <code>x</code> ...
python|matlab|numpy|scipy
13
362,596
28,822,345
How do you merge two Pandas dataframes with different column index levels?
<p>I want to concatenate two dataframes with same indices but different column-levels. One dataframe has a hierarchical index, the other on doesnt.</p> <pre><code>print df1 A_1 A_2 A_3 ..... Value_V Value_y Value_V Value_y Value_V Value_y in...
<p>Perhaps use good ole assignment:</p> <pre><code>df3 = df1.copy() df3[df2.columns] = df2 </code></pre> <p>yields</p> <pre><code> A_1 A_2 A_3 PV Estimate Value_V Value_y Value_V Value_y Value_V Value_y instance200 50 0 ...
python|pandas
12
362,597
28,462,026
Explain {isinstance} in iPython prun output?
<p>I'm trying to profile a few lines of Pandas code, and when I run %prun i'm finding most of my time is taken by {isinstance}. This seems to happen a lot -- can anyone suggest what that means and, for bonus points, suggest a way to avoid it?</p> <p>This isn't meant to be application specific, but here's a thinned out...
<p><code>isinstance</code>, <code>len</code> and <code>getattr</code> are just the built-in functions. There are a <em>huge</em> number of calls to the <a href="https://docs.python.org/2/library/functions.html#isinstance" rel="nofollow"><code>isinstance()</code> function</a> here; it is not that the call itself takes a...
python|pandas|ipython
2
362,598
28,687,490
Python 'in' function , pandas dataframe wrongly populated
<pre><code>from collections import defaultdict import csv from bs4 import BeautifulSoup import urllib2 import pandas as pd import re text = open("/Users/dynajose/Desktop/PlayList.rtf").read() songDom = BeautifulSoup(text) data=defaultdict(list) musicData=defaultdict(list) f_music = songDom.find_all("div", {"class" ...
<p>Looks like your <code>page_verified</code> variable is actually a list, that's why your check returns false.</p> <p>Example :</p> <pre><code>l = ['ab'] 'a' in l False </code></pre> <p>If the list returned is always containing one element, just do </p> <pre><code>if check in page_verified[0]: </code></pre> <p>if...
python|pandas|beautifulsoup|dataframe
1
362,599
28,847,494
Can not install numexpr (and hence pytables) on windows 7, dll load failing for interpreter.pyd even though it is present
<p>I installed numexpr and pytable using .whl. Installation looked fine but dll import failure keeps coming. Here are the installation details.</p> <pre><code>PS E:\&gt; pip install --use-wheel --no-index --find-links=.\ numexpr-2.4-cp27-none-win32.whl Ignoring indexes: https://pypi.python.org/simple Processing e:\num...
<p>I had a very similar problem and after a couple of hours, I was able to fix it. I'm sharing my fix and hope it may help someone else like me.</p> <p>Go to the site below:</p> <p><a href="https://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow noreferrer">https://www.lfd.uci.edu/~gohlke/pythonlibs/</a></p> <p>T...
python|dll|pandas|pytables|numexpr
2