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
355,700
70,916,046
Dropping Rows that Contain a Specific String wrapped in square brackets?
<p>I'm trying to drop rows which contain strings that are wrapped in a column. I want to drop all values that contain the strings '[removed]', '[deleted]'. My df looks like this:</p> <pre><code> Comments 1 The main thing is the price appreciation of the token (this determines the gains or losses more than anything...
<p>Try this</p> <p>I have created a data frame for comments column and used my own comments but it should work for you</p> <pre><code>import pandas as pd sample_data = { 'Comments': ['first comment whatever','[deleted]','[removed]','last comments whatever']} df = pd.DataFrame(sample_data) data = df[df[&quot;Comments...
python|pandas|dataframe|data-cleaning
0
355,701
70,853,377
How can I properly graph these two datasets using Pandas in Matplotlib?
<p>I have two datasets that I am trying to plot over each other.</p> <p>The first dataset is the daily price of Dogecoin. I am using yfinance and mplfinance to chart this.</p> <p>The second dataset is a CSV file of Dogecoin wallet transactions, which has a column named &quot;Balance&quot;, that shows the Balance of the...
<p>Before you can line up the timestamps from the two data sets, there are a number of issues with the csv file that have to be cleaned up first.</p> <p>This is what the csv file looks like as you are reading it:</p> <pre class="lang-py prettyprint-override"><code>df = pd.read_csv('DSb5CvAXhXnzFoxmiMaWpgxjDF6CfMK7h2.cs...
python|pandas|matplotlib
1
355,702
70,764,969
How to know if tensorflow 2 training is going forward, is stuck or will finish?
<h1>without gpus</h1> <p>I achieve to start the training process of a simple object detection, using:</p> <ul> <li>tensorflow 2</li> <li>model_main_tf2.py</li> <li>pipeline.config: <code>BATCH_SIZE=16 NUM_CLASSES=1 NUM_STEPS=200000</code></li> <li>model_main_tf2.py parameters: <code>NUM_WORKERS=1</code></li> <li>model:...
<p>If you are using <code>TFOD</code> (<code>TensorFlow Object Detection</code>) API then you can limit the total number of steps to be performed from the <code>config</code> file. If you are using <code>SSD Mobilenet</code> trained on <code>COCO</code> dataset, then the <code>config</code> file name should be like: <a...
python|tensorflow|machine-learning|tensorflow2.0
0
355,703
70,898,729
Why is matplotlib plotting nan differently than zeros?
<p>I have 2D numpy array that I want to mask and plot. I have tried this.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt a = np.random.random((101,99)) data1 = a.copy() bound = np.percentile(data1, 80) data1[data1&lt;bound] = np.nan plt.figure() plt.imshow(data1) </code></pre> <p>Output:</p> <p><a ...
<p>As others pointed out this seems to be due to interpolation. On my machine, running your code, there was no difference between the two plots apart from the background. Try to explicitely turn off interpolation:</p> <pre><code>plt.imshow(data1, interpolation='nearest') </code></pre>
numpy|matplotlib|nan|masked-array
1
355,704
70,785,821
How to apply panda group by with minimum and maximum size condition (Pythonic way)
<p>I have a dataframe in pandas which I need to group and store in a new array where I need the size of every group with a specific size and if one exceeds the minimum size, it should be added to one of the previous groups that have the smallest size. For example, after I grouped the data, I will have groups <code>G</...
<p>I was following this post since the beginning curious about how the discussion would g, because the OP's problem is not always possible to solve.</p> <h3>Existence of a solution</h3> <p>Take the following example: A group has 19 elements and you want to split it in sections of size between 10 and 15.</p> <p>The solu...
python|pandas|group-by
2
355,705
70,929,342
How to avoid memory mapping when loading a numpy file
<p>Csv file:</p> <pre><code>0,0,0,0,0,0,0,0,0,0.32,0.21,0,0.16,0,0,0,0,0,0,0.32 0,0,0,0,0,0,0.17,0,0.04,0,0,0.25,0.03,0.32,0,0.02,0.05,0.03,0.08,0 0.08,0.07,0.09,0.06,0,0,0.21,0.02,0,0,0,0,0,0,0,0.1,0.36,0,0,0 [goes on always 20 columns and x number of rows] </code></pre> <p>I'm saving the array this way:</p> <pre><cod...
<p>Looking into the <a href="https://numpy.org/doc/stable/reference/generated/numpy.load.html" rel="nofollow noreferrer">manual</a> we can see that the second parameter of <code>numpy.load</code> is called <code>mmap_mode</code> and is set to <code>&quot;r&quot;</code> in your code. This enables memory mapping the file...
python|numpy
3
355,706
51,641,188
passing text user input into another function as string
<p>I have an tkinter entry field where user can input text in the GUI...</p> <pre><code>manager_name_entry = tkinter.Entry() manager_name_entry.grid(in_=tab1, row=0, column=0, sticky=tkinter.N, pady=10) manager_name_entry.focus_set() </code></pre> <p>I also have a function which gets this text...</p> <pre><code>def ...
<p>While the <code>command=</code> parameter on a <code>Button</code> determines which function to call, it won't pass any parameter. So the function you put there must be a function that doesn't have any argument.</p> <p>The way to solve this is to fetch the user input from inside your function, instead of having it ...
python|pandas|tkinter
0
355,707
51,641,930
Multiindex reindexing using datetime component as level
<p>I can't for the life of me figure this out. I'm trying to reindex a dataframe based on two columns of my dataframe:</p> <pre><code>Index Donation AbsSiz Affil DonID Datetime_Obj 19 2000 25598000 Con ffed93...
<p>It's a little unclear what you mean by "re-index", but taken at face value I'll set the DataFrame index to the minute and Affil</p> <pre><code>df['datetime_obj_min'] = df['datetime_ob'].dt.minute df.set_index(['datetime_obj_min', 'Affil'], inplace=True, drop=True) </code></pre> <p>You mentioned wanting to group by...
pandas
0
355,708
51,972,980
Pandas Return top N from each group in MultiIndex
<p>I have a large multi-index dataframe with about 3 million data points. The first index is the date, the second is the name of the object. Then, each object has a value like so:</p> <pre><code>df = pd.DataFrame({'year': [2012, 2012, 2012, 2013, 2013, 2013], 'item':['apples', 'metals', 'water', 'apples', 'metals', 'w...
<p>IIUC <code>sort_values</code> before <code>groupby</code> <code>tail</code></p> <pre><code>df.sort_values('value').groupby(level=0).tail(2).sort_index() Out[258]: value year item 2012 metals 14 water 16 2013 apples 17 water 14 </code></pre>
pandas|sorting|dataframe|multi-index
4
355,709
51,605,661
How to compute the difference between 2 string columns in a pandas dataframe
<p>I have 2 columns in the same dataframe as below:</p> <pre><code>A B abcdef(as3456) as3456 pqrst(dh6546) dh6546 </code></pre> <p>I need to create another column C such as below:</p> <pre><code> C abcdef pqrst </code></pre> <p>I have been able to create column B from A however, my purpose i...
<p>For difference between columns per rows use <code>replace</code> with <code>strip</code>:</p> <pre><code>df = pd.DataFrame({'A': ['abcdef(as3456)', 'pqrst(dh6546)', 'abcdef(dh6546)'], 'B': ['as3456', 'dh6546', 'as3456']}) print (df) A B 0 abcdef(as3456) as3456 1 pqrst(...
python-3.x|pandas
1
355,710
51,941,201
index value vs. flight (data range A row & E row )
<p>I want to know the scatter plot of the sum of the flight fields per minute. My information is as follows <a href="http://python2018.byethost10.com/flights.csv" rel="nofollow noreferrer">http://python2018.byethost10.com/flights.csv</a> <br>My grammar is as follows</p> <pre><code>import matplotlib.pyplot as plt impor...
<p>Problem is in aggregation, in your code it return tuples in index.</p> <p>Solution is convert <code>time_dt</code> column to strings <code>HH:MM</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>Series.dt.strftime</code></a>:</p>...
pandas
2
355,711
51,825,969
How to calculate the sum of "submatrix" entries with numpy/pandas?
<p>I have the following 8x8 matrix in Python, which I have represented as either an 8-by-8 numpy array, or a pandas DataFrame:</p> <pre><code>import numpy as np import pandas as pd x = range(64) x = np.reshape(x,(8,8)) print(x) # [[ 0 1 2 3 4 5 6 7] # [ 8 9 10 11 12 13 14 15] # [16 17 18 19 20 21 22 23]...
<p>One way to do that with NumPy is this:</p> <pre><code>import numpy as np def as_submatrices(x, rows, cols=None, writeable=False): from numpy.lib.stride_tricks import as_strided if cols is None: cols = rows x = np.asarray(x) x_rows, x_cols = x.shape s1, s2 = x.strides if x_rows % rows != 0 o...
python|pandas|numpy|matrix
6
355,712
51,586,680
Linear regression with pytorch
<p>I tried to run linear regression on ForestFires dataset. Dataset is available on Kaggle and gist of my attempt is here: <a href="https://gist.github.com/Chandrak1907/747b1a6045bb64898d5f9140f4cf9a37" rel="nofollow noreferrer">https://gist.github.com/Chandrak1907/747b1a6045bb64898d5f9140f4cf9a37</a></p> <p>I am fa...
<h3>Problem 1</h3> <p>This is reference about MSELoss from Pytorch docs: <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.MSELoss" rel="nofollow noreferrer">https://pytorch.org/docs/stable/nn.html#torch.nn.MSELoss</a></p> <pre><code>Shape: - Input: (N,∗) where * means, any number of additional dimensions -...
pytorch
1
355,713
51,740,502
Compare the rows of two columns in one dataframe if they exist another dataframe | python
<p>I have a dataframe called <code>combined</code> which is have two columns <code>c1,c2</code> </p> <p>combine:</p> <pre><code> c1 c2 dr123 di878 dr987 di082 dr751 di715 dr156 di083 </code></pre> <p>Another dataframe called <code>specific</code> have <code>c1,c2,c3</code> </p> <p>specific:</p> <pre><code> c1 ...
<p>Use</p> <pre><code>In [312]: df1['label'] = df1.merge(df2[['c1', 'c2']], how='left', indicator=True )['_merge'].eq('both').astype(int) In [313]: df1 Out[313]: c1 c2 label 0 dr123 di878 0 1 dr987 di082 1 2 dr751 di715 1 3 dr156 di083 0 </code...
python|pandas|dataframe
0
355,714
51,710,176
Set the values out of the defined interval limits to a given value (f.e. NaN) for a column in pandas data frame
<p>Having a defined interval limits of valid values, all the pandas data frame column values out of it should be set to a given value, f.e. <code>NaN</code>. The values defining limits and data frame contents can be assumed to be of numerical type.</p> <p>Having the following limits and data frame:</p> <pre><code>min...
<p>Using <code>where</code> with <code>between</code></p> <pre><code>df.a=df.a.where(df.a.between(min,max),np.nan) df Out[146]: a b 0 5.0 12 1 NaN 3 2 7.0 10 3 NaN 9 </code></pre> <p>Or <code>clip</code> </p> <pre><code>df.a.clip(min,max) Out[147]: 0 5.0 1 NaN 2 7.0 3 NaN Name: a, dtyp...
python|pandas|dataframe|limit
6
355,715
51,699,494
AttributeError using scipy.sparse.toarray()
<pre><code>import scipy as sp import numpy as np a=sp.sparse.coo_matrix(np.random.randint(0,9,[4,5])) b=sp.sparse.coo_matrix(np.random.randint(0,9,[4,2])) sp.hstack([a,b]).toarray() </code></pre> <p>is giving me</p> <pre><code>AttributeError: 'numpy.ndarray' object has no attribute 'toarray' </code></pre> <p>could ...
<p><code>sp.hstack</code> (i.e. <code>numpy.hstack</code>) is the ordinary, <em>dense</em> hstack, which won't combine the sparse arrays correctly. It builds a 1D numpy array already (of object dtype; in other words, it just wraps the Python-level objects and crams them in there.) You want <code>scipy.sparse.hstack</...
python|numpy|scipy|sparse-matrix
2
355,716
51,761,353
About Tensor of tensorflow
<p>I want to change the shape/dimension of tensor. For example, </p> <pre><code>x = tf.constant([1, 2, 3]) </code></pre> <p>Then I want to get <code>y = tf.constant([1,1], [2,2], [3,3]).</code></p> <p>How can I get the new <code>y</code> transformation?</p> <p>I have run the code </p> <pre><code>y = tf.map_fn(lam...
<p>Make sure you declare explicitally the types:</p> <pre><code>y = tf.map_fn(lambda e : (e, e), x, dtype=(tf.float32, tf.float32)) </code></pre>
python|tensorflow|tensor
2
355,717
51,857,052
Pandas: how to collapse a Series' MultiIndex to a DateTimeIndex?
<p>As a followup of <a href="https://stackoverflow.com/questions/51854809/pandas-groupby-group-by-semester">Pandas groupby: group by semester</a> I need to collapse a Series' MultiIndex to a DateTimeIndex. </p> <p>I already gave a look at <a href="https://stackoverflow.com/questions/48431868/collapse-pandas-multiindex...
<p>You need join levels of <code>MultiIndex</code> or <code>Series</code> together and convert to <code>datetimes</code>:</p> <pre><code>idx = ser.index.get_level_values(0).astype(str) + ser.index.get_level_values(1).astype(str) ser.index = pd.to_datetime(idx, format='%Y%m') print(ser) 2016-01-01 78.0 2016-07-01 ...
python|pandas|pandas-groupby
2
355,718
51,841,420
Vectorizing with summation vs dot product
<p>I am writing a simple linear regression cost function (Python) for a simple neural network. I have come across the following two alternate ways of summing the error (cost) over m examples using numpy (np) matrices.</p> <p>The cost function is:</p> <pre><code>def compute_cost(X, Y, W): m = Y.size; H = h(X,W) error ...
<p>There's nothing special, just simple linear algebra.</p> <p>According to <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.dot.html" rel="nofollow noreferrer">numpy documentation</a>, <code>np.dot(a,b)</code> performs different operation on different types of inputs.</p> <blockquote> <p>...
numpy
0
355,719
51,871,187
Match one to many columns in Pandas dataframe
<p>I have 2 datasets in CSV file, using pandas each file is converted into 2 different dataframes. </p> <p>I want to find similar companies based on their url. I'm able to find similar companies based on 1 field (Rule1), but I want to compare more efficiently as following:</p> <p><strong>Dataset 1</strong></p> <pre>...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> by <code>Series</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.combine_first.html" rel="nofollow noreferrer"><code>combine_first</code></...
python|pandas|dataframe
2
355,720
51,947,586
Writing a dataframe to CSV where lists are converted to JSON arrays
<p>How would a list of strings be outputted as a JSON array when <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer">writing a dataframe to CSV</a>?</p> <p>E.g. <code>['foo', 'bar']</code> should be <code>["foo", "bar"]</code></p> <hr> <h3>Backgroun...
<p>Combine the approach in the question with these changes when writing the CSV:<br> Configure an escape character (typically backslash <code>\</code>) and disable double quoting.</p> <pre><code>df.to_csv(path, escapechar="\\", doublequote=False) </code></pre> <p>The row in the CSV will look like <code>[\"foo\", \"ba...
pandas|csv|dataframe|dask
0
355,721
51,754,608
Export dask groups to csv
<p>I have a single, large, file. It has 40,955,924 lines and is >13GB. I need to be able to separate this file out into individual files based on a single field, if I were using a <code>pd.DataFrame</code> I would use this:</p> <pre><code>for k, v in df.groupby(['id']): v.to_csv(k, sep='\t', header=True, index=Fal...
<p>You want to use <code>apply()</code> for this:</p> <pre><code>def do_to_csv(df): df.to_csv(df.name, sep='\t', header=True, index=False) return df df.groupby(['id']).apply(do_to_csv, meta=df._meta).size.compute() </code></pre> <p>Note - the group key is stored in the dataframe <code>name</code> - we return...
python|pandas|pandas-groupby|dask
3
355,722
51,672,903
Keras, Tensorflow: How to set breakpoint (debug) in custom layer when evaluating?
<p>I just want to do some numerical validation inside the custom layer. </p> <p>Suppose we have a very simple custom layer:</p> <pre><code>class test_layer(keras.layers.Layer): def __init__(self, **kwargs): super(test_layer, self).__init__(**kwargs) def build(self, input_shape): self.w = K.va...
<p>In TensorFlow 2, you can now add breakpoints to the TensorFlow Keras models/layers, including when using the fit, evaluate, and predict methods. However, you must add <code>model.run_eagerly = True</code> <strong>after</strong> calling <code>model.compile()</code> for the values of the tensor to be available in the ...
python|tensorflow|keras|pycharm
16
355,723
51,849,937
"unexpected indent" or "object has no attribute 'compile'" errors
<p>I am following the Tensorflow tutorials and have come to the basic regression <a href="https://www.tensorflow.org/tutorials/keras/basic_regression" rel="nofollow noreferrer">basic regression tutorial</a>. When I come to the Create the Model section, the following code gives errors:</p> <pre><code>def build_model()...
<p>By this line of the error message</p> <pre><code> File "&lt;stdin&gt;", line 1 </code></pre> <p>is evident that you wrote you code directly to the Python <em>interpreter</em>, and by this interpreter's prompt</p> <pre><code>&gt;&gt;&gt; </code></pre> <p>is obvious that you wrote the</p> <pre><code> optimizer ...
python|tensorflow|indentation
0
355,724
51,900,096
Connect output tensor to placeholder in tensorflow
<p>If I have a graph as follows:</p> <pre><code>x0 = tf.placeholder(tf.float32, shape=(None, None, None, None)) y0 = x0 + 10.0 </code></pre> <p>And a second one as follows:</p> <pre><code>x1 = tf.placeholder(tf.float32, shape=(None, None, None, None)) y1 = x1 * 5.0 </code></pre> <p>How do I connect the output of th...
<p>Assuming you want to compute <code>y1 = (x0+10.0)*5.0</code> you can to the following:</p> <pre><code>x0 = tf.placeholder(tf.float32, shape=(None, None, None, None)) y0 = x0 + 10.0 y1 = y0 * 5.0 </code></pre>
tensorflow|graph|connection
1
355,725
51,885,769
Pandas compare 1 columns values to another dataframe column, find matching rows
<p>I have a database that I am bringing in a SQL table of events and alarms (df1), and I have a txt file of alarm codes and properties (df2) to watch for. Want to use 1 columns values from df2 that each value needs cross checked against an entire column values in df1, and output the entire rows of any that match into a...
<h1>Method 1: <code>merge</code></h1> <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="noreferrer">merge</a>, on <code>B</code> and <code>0</code>. Then select only the <code>df1</code> columns</p> <pre><code>df1.merge(df2, left_on='B', right_on='0')[df1.columns...
python|pandas|python-2.7|dataframe
13
355,726
51,900,109
Python Pandas Pivot image data table
<p>I have a using Pandas dataframe I created a table that is 3000000x3 (pixels x rob bands) and am now trying to pivot it so I have a table that is 3x3000000 and then run a PCA against the new data. </p> <p>I am using that pandas pivot function but cannot figure out what I am doing wrong.</p> <pre><code>import pandas...
<p>Was seriously overthinking the problem. As I needed to completely swap the axis it was simple as transposing using <code>.T</code></p> <pre><code>data = pd.DataFrame({'bBnad':b.flat[:],'gBnad':g.flat[:],'rBnad':r.flat[:]}) datapivoted = data.T print(datapivoted.head()) print(datapivoted.shape) </code></pre>
python|pandas|pca|mat
0
355,727
51,645,667
A variable with two columns in pandas
<p>I am not sure how my variable, df['education'], when printed out has two identical columns, rather than just being one. When I check the type of the variable it says it is a Series, but how can a series have two columns?</p> <pre><code> df2['education'] education education 0 Highe...
<p>There is problem duplicated columns names, so if select get all columns in <code>DataFrame</code>.</p> <p>Solution is upgrade pandas for <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#read-csv-has-improved-support-for-duplicate-column-names" rel="nofollow noreferrer">0.19.0+</a> if use <code>rea...
python-3.x|pandas|duplicates|series
0
355,728
51,602,116
Conditional transformation of column in pandas Dataframe
<p>I would like to create a new column in my dataframe that is the difference between two variables IF a 3rd column in that row satisfies a certain condition.</p> <p>A min example looks like this:</p> <pre><code> dict1 = [{'var0': 0, 'var1': 1, 'var2': 2}, {'var0': 0, 'var1': 2, 'var2': 4}, {'var0': 1, 'var1': 5, 'v...
<p>You can do it in one line</p> <pre><code>import numpy as np df['var3'] = np.where( df.var2 &gt; 3, df['var0'] - df['var1'], df['var0'] - df['var2']) </code></pre>
python|pandas|conditional-formatting
4
355,729
51,616,960
Eager execution in tensorflow custom estimators
<p>I'm rewriting my code using custom Estimator logic, and I need to enable eager execution to get the metrics/predictions I need. However, it seems that enabling eager execution does not go through for some reason. To reproduce, I can use the example located at <a href="https://github.com/tensorflow/tensorflow/blob/ma...
<p>The <code>Estimator</code> API is pretty tightly tied to graph construction (each call to <code>train()</code>, <code>evaluate()</code> etc. reconstructs the graph). So it explicitly disables eager execution when invoked.</p> <p>Is it possible for you to use your own training loop or use <code>tf.keras.Model.fit()<...
python|tensorflow|tensorflow-estimator
1
355,730
51,602,862
First occurrence of consecutive elements in a numpy array
<p>I have a binary numpy masked array and I want to find the index of the elements along the axis=0 when there is at least 3 consecutive occurrence of 1. If no occurrence then -999 or NaN or anything that shows it is not an index. So for example my array is like:</p> <pre><code>masked_array( data=[[[1.0, 0.0], [0...
<p>IIUC, you can first make your np array 2D and build a data frame, which makes everything easier. Take a look</p> <pre><code>row, cols = m.shape[0], m.shape[1] * m.shape[2] df = pd.DataFrame(m.reshape(row, cols)) 0 1 2 3 0 1.0 0.0 0.0 1.0 1 0.0 1.0 0.0 1.0 2 1.0 1.0 1.0 1.0 3 1.0 1.0 1.0 0.0 4 1...
python-2.7|pandas|numpy
3
355,731
51,826,748
Querying a .csv file with conditions using Pandas and .shift
<p>I'm having trouble querying a simple .csv file of trade data with conditions. The .csv file has 5 columns - <code>[open, high, low, close, volume]</code> with a <strong>time-series index, of minute by minute trades</strong>.</p> <p>What I want to do is build a script that </p> <blockquote> <p>(1) tells me how ma...
<p>You are almost there. Just make <code>ts2</code> and <code>ts3</code> masks instead of actual queried dataframe.</p> <pre><code>ts2 = (ts["close"] - ts["open"].shift(1)) &gt; 0 #this is a mask ts3 = (ts["volume"].shift(1) - ts["volume"].shift(2)) &gt; 0 #this is a mask ts4 = ts.loc[ts2 &amp; ts3] #query using 2 ma...
python|pandas|csv|conditional-statements|querying
1
355,732
51,641,379
Concatenate list of strings in each dictionary value
<p>From a Pandas dataframe <code>df3pa</code> containing product line items (embedded in MDX query format) and product category codes, I have a dictionary <code>uni3pa</code> with product category code <code>Code</code> as the dictionary <code>keys</code>, and a list of strings <code>Item</code> (in MDX format) as the ...
<p>This is achieved by altering your list comprehension to a dictionary comprehension:</p> <pre><code>&gt;&gt;&gt; uni3pa = {'3PA SMARTPAY': ['[Item].[Item].[10006543 - Smartpay User Licence]', '[Item].[Item].[10006544 - SmartPay User Licence per Site]'], '3PA OTHER': ['[Item].[Item].[10001234 - 3rd Party App User Lic...
python|pandas|list|dictionary|list-comprehension
1
355,733
51,580,869
Extracting data from dataset Online
<p><a href="https://archive.ics.uci.edu/ml/machine-learning-databases/liver-disorders/" rel="nofollow noreferrer">DataSet Link</a></p> <p>I have a dataset that is available in Bupa.data as CSV at the link given above and the attributes data is given in point 7 at Bupa.name file.</p> <p><a href="https://archive.ics.uc...
<p>To create the code that is robust against different attribute names you can use a regular expression to get the data out of the files. In your particular case:</p> <pre><code>import pandas as pd import numpy as np import re from bs4 import BeautifulSoup from urllib.request import Request,urlopen soup_link1 = Beauti...
python|python-3.x|pandas|web-scraping|beautifulsoup
0
355,734
51,662,153
Merging Two Data Frames With Matching
<p>I have two data frames df1: <a href="https://i.stack.imgur.com/2gYIN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2gYIN.jpg" alt="enter image description here"></a></p> <p>and df2:<a href="https://i.stack.imgur.com/g2A1D.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g2A1D....
<p>You can use pandas - merge</p> <p>pd.merge(df1, df2, left_index=True, right_index=True)</p> <p>or concat </p> <p>pd.concat([df1]...[df2], axis=1)</p> <p>For more information you can look at this link:</p> <p><a href="https://jakevdp.github.io/PythonDataScienceHandbook/03.07-merge-and-join.html" rel="nofollow no...
python|pandas
0
355,735
51,896,058
Grouping data series by day intervals with Pandas
<p>I have to perform some data analysis on a seasonal basis.</p> <p>I have circa one and a half years worth of hourly measurements, from the end of 2015 to the second half of 2017. What I want to do is to sort this data in seasons. </p> <p>Here's an example of the data I am working with:</p> <pre><code>Date,Year,Mon...
<p>Define each season by filtering the relevant rows using <code>Day</code> and <code>Month</code> columns as presented for winter:</p> <pre><code>df_winter = df.loc[((df['Day'] &gt;= 21) &amp; (df['Month'] == 12)) | (df['Month'] == 1) | (df['Month'] == 2) | ((df['Day'] &lt;= 21) &amp; (df['Month'] == 3))] </code></pr...
python|pandas
0
355,736
51,660,670
How to select rows from pandas based on values of a list
<p>I have a pandas dataframe and one of the columns (let's say col_1) is a list of string. I'd like to select only rows from the dataframe where the col_1 (which is a list) contains a particular keyword, e.g. 'late'. Here is an example</p> <pre><code> col_1 col_2 0 [no issue] fff 1 [late.., ...
<p>You can apply a condition check to each row:</p> <pre><code>df[df.col_1.apply(lambda x: 'no issue' in x)] </code></pre>
python|pandas
1
355,737
51,851,016
How to find a list for each column index containing the row indices for the n minimum values?
<p>I have the distances between 60 delivery and 6 receiving points stored in the following list of a list (60 rows x 6 columns). Each column index is an id for the receiving point. Each row index is an id for a delivery point &amp; values in each row contains the distance values between receiving and delivery points. I...
<p>This might be way simpler as you think. Read your data:</p> <pre><code>data = np.array(the array that u gave us above) </code></pre> <p>and then you can read column by column using numpy formatting:</p> <pre><code>min_0_indices.append(np.argmin(data[:, [0]])) </code></pre> <p>the ":" means every line in column "...
python|list|numpy|arraylist|multidimensional-array
0
355,738
51,929,876
Why does Numpy.loadtxt work when called from IDLE and gives an IOError when called from shell?
<p>I try to do the following:</p> <h1>1 VBA script calls shell using</h1> <pre><code>RetVal = Shell(fullpythonexepath &amp; fullscriptpath) </code></pre> <h1>2 Shell get follwing command</h1> <pre><code>fullpythonexepath &amp; fullscriptpath </code></pre> <h1>3 Python Script</h1> <pre><code>import numpy as np th...
<p>When you start the script from shell the working directory for the script will be the directory from which it is called upon. Most IDLE define their own working directory. To check I suggest doing:</p> <pre><code>os.getcwd() </code></pre> <p>in both cases and look what directory is used in both cases</p>
python|excel|vba|shell|numpy
2
355,739
51,749,404
How to connect LSTM layers in Keras, RepeatVector or return_sequence=True?
<p>I'm trying to develop an Encoder model in keras for timeseries. The shape of data is (5039, 28, 1), meaning that my seq_len is 28 and I have one feature. For the first layer of the encoder, I'm using 112 hunits, second layer will have 56 and to be able to get back to the input shape for decoder, I had to add 3rd lay...
<p>You will probably have to see for yourself which one is better because it depends on the problem you're solving. However, I'm giving you the difference between the two approaches.</p> <p><a href="https://i.stack.imgur.com/LNXjF.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/LNXjF.jpg" alt="Difference &lt...
tensorflow|keras|deep-learning|lstm|autoencoder
67
355,740
51,661,293
How to convert user-string-input into conditions to pass as parameters to Python Pandas' drop function?
<p>In pandas if you want to drop some rows based on conditions, you can do something like:</p> <pre><code>df = df.drop(df[(df.score &lt; 50) &amp; (df.score &gt; 20)].index) </code></pre> <p>The main varying part is the followings which signifies the conditions:</p> <pre><code>(df.score &lt; 50) &amp; (df.score &gt;...
<p>You need to use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow noreferrer"><strong>pandas.DataFrame.query()</strong></a> which takes the expression as a <code>string</code>.</p> <pre><code>def drop_condition(df, cond_in_str): df.drop(df.query(cond_in...
string|python-3.x|pandas|dataframe|conditional
1
355,741
51,903,256
MultiLabelBinarizer mixes up data when inverse transforming
<p>I am using <code>sklearn</code>'s <code>multilabelbinarizer()</code> to train multiple columns in my machine learning which I use to train my model. </p> <p>After using it I noticed it was mixing up my data when it inverse transforms it. I created a test set of random values where I fit the data, transform it, and ...
<p>The issue comes from the data (and in this case a bad use of the model). If you create a Dataframe of your <code>MultiLabelBinarizer</code> you will have :</p> <p><a href="https://i.stack.imgur.com/Um7JJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Um7JJ.png" alt="enter image description here"></a></p>...
python|pandas|machine-learning|sklearn-pandas|multilabel-classification
5
355,742
51,971,844
Retraining the Inception V3 Model for Machine Learning
<p>I'm doing image classification with two classes using the Inception V3 model. Since I'm using two new classes(Normal and Abnormal) I'm freezing the top layers of the Inception V3 model and replacing it with my own. </p> <pre><code>base_model = keras.applications.InceptionV3( weights ='imagenet', inc...
<p><strong>No</strong>, it is <strong>not necessary</strong> to freeze the first layers of a CNN; you can just initialize the weights from a pre-trained model. However, in most cases it is <strong>recommended</strong> to freeze them as the features they can extract are <em>generic</em> enough to help in any image-relat...
python-3.x|tensorflow|machine-learning|keras|conv-neural-network
2
355,743
51,781,509
Split dataframe cells where first number is encountered
<p>I have a column in my dataframe and I would like to split it where the first numeric value is encountered. Here is a sample of my data:</p> <pre><code> col 1 Beb il Gisire, contrata 102 12 Bungemma, territorium 90, 115, ...
<p>Use <code>'(.*?)(\d.*)'</code> regex pattern to capture/split the groups.</p> <pre><code>In [237]: df.col.str.extract('(.*?)(\d.*)') Out[237]: 0 1 1 Beb il Gisire, contrata 102 12 Bungemma, territorium 90, 115, 130 13 ...
python|regex|pandas|dataframe
4
355,744
51,623,226
Concatenate variable and string python script
<p>I am trying to write a Python script in Spyder to deal with several files at the same time. </p> <p>Actual path is something like: </p> <pre><code>/TestCondition/TestDate-A1.txt </code></pre> <p>I want to control the TestCondition and TestDate only at the beginning. </p> <pre><code>FoldPath = TestCondition FileN...
<p>first..</p> <pre><code>dfA1 = pd.read_csv("/{}/{}-A1.txt".format(FoldPath, Filename) </code></pre> <p>but this code not recommanded. </p> <p>second.. <strong>use <code>os.path.join</code></strong></p> <pre><code>dfA1 = pd.read_csv(os.path.join(FoldPath, "{}-A1.txt".format(Filename, )) </code></pre>
python|pandas|concatenation|spyder
1
355,745
51,557,940
Python Keras - CNN stuck on epoch 1
<pre><code>from keras import * import os import numpy as np from keras.models import Sequential from keras.layers import Activation, Dropout, Flatten, Dense from keras.preprocessing.image import ImageDataGenerator from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D from keras import optimizers #from par...
<p>By decoding "Found 0 images belonging to 0 classes", one can conclude that the subdirectories for each class are not created. In keras, there must be a folder for every class and in that folder it must contain the images. So, make sure you make subdirectories for each class inside the train and test folders.</p>
python|tensorflow|keras
0
355,746
51,722,864
Reshaping pandas DataFrame Python 3.x
<p>I have a pandas like so:</p> <pre><code>df = cid pid purl tid turl sid surl c1 p1 urlp1 t1 urlt1 s1 urls1 c1 p1 urlp1 t1 urlt1 s2 urls2 c1 p1 urlp1 t1 urlt1 s3 urls3 c2 p2 urlp2 t2 urlt2 s5 urls5 c2 p2 urlp2 ...
<p>One manual solution is to use a list comprehension. The steps are:</p> <ol> <li>Set your index to the key column <code>cid</code>.</li> <li>Calculate the length of your list comprehension loop from the number of columns.</li> <li>Use <code>concat</code> with your list of dataframes and rename columns via <code>pipe...
python|pandas
3
355,747
51,663,231
Window-slide through an image
<p><strong>Objective:</strong> Slide a 2D 'window' through a 2D image (grayscale). For each pixel of the image, copy all the pixels inside the window (pattern) and move to the next pixel.</p> <p><strong>Problem:</strong> Very Slow. I want to speed this up.</p> <p>Except by using Cython (ewwww). </p> <p>I use this co...
<p>The obvious answer is to vectorize those loops. Without a complete example, it's hard to test anything, so I'll just give a sketch.</p> <p>We want to turn this:</p> <pre><code>for m in range(-ww2, ww2 + 1): try: pattern[k] = img[i + l, j + m] except: pattern[k] = 0 k...
python|multithreading|numpy
1
355,748
51,750,077
Iterate over pd df with date column by week python
<p>I have a one month DataFrame with a datetime object column and a bunch of functions I want to apply to it - by week. So I want to loop over the DataFrame and apply the functions to each week. How do I iterate over weekly time periods? </p> <p>My DataFrame looks like this: <a href="https://i.stack.imgur.com/e0mc8.p...
<p>If you really don't want to use groupby and aggregations then:</p> <pre><code>for week in df['date'].dt.week.unique(): this_weeks_data = df[df['date'].dt.week == week] </code></pre> <p>This will, of course, go wrong if you have data from more than one year.</p>
python|pandas|loops|datetime
3
355,749
51,825,793
Adding values with same frequency in time series with pandas:
<p>I have a pandas <code>DataFrame</code> indexed by <code>pandas.core.indexes.datetimes.DatetimeIndex</code> and I'd like to add new values starting from the last date in the series. I need that each new value inserted be in the next date using a daily frequency.</p> <pre><code>Example: TotalOrders Date ...
<p>Use <code>loc</code> with <code>DateOffset</code>:</p> <pre><code>df.loc[df.index.max()+pd.DateOffset(1)] = 5000 </code></pre> <p></p> <pre><code> TotalOrders Date 2013-12-29 3756 2013-12-30 6222 2013-12-31 4918 2014-01-01 5000 </code></pre>
python|pandas|time-series
4
355,750
51,577,538
Pandas custom re-sample for time series data
<p>I have a time series data in 1 Min frequency. I would like re-sample the data for every 5 min and re-sample data should include the data of first time step, middle time step and last time step. </p> <p>I have tried like this, but I am not getting what I am expecting...</p> <pre><code>def my_fun(array) return ...
<p>If I understood you correctly then you want the data for minutes 0,2,4,5,7,9,10,... in a new dataframe. A faster way than using resample may be:</p> <pre><code>df=pd.DataFrame(np.arange(60),index=pd.date_range('2017-01-01 00:00','2017-01-01 00:59', freq='1T')) l = len(df) df.loc[df.iloc[range(2,l,5)].index | df.ilo...
python|pandas|numpy
1
355,751
51,713,141
Couldn't install tensorflow on windows
<p>While installing tensorflow on my windows, the following error message is displayed.Please help me in fixing it. <a href="https://i.stack.imgur.com/0ZBay.png" rel="nofollow noreferrer">open this image for viewing the error message</a></p>
<p>If one of the following versions of Python is not installed on your machine, install it now:</p> <ul> <li>Python 3.5.x 64-bit from python.org</li> <li>Python 3.6.x 64-bit from python.org</li> </ul> <p>TensorFlow supports Python 3.5.x and 3.6.x on Windows. Note that Python 3 comes with the pip3 package manager, whi...
tensorflow|windows-7|python-3.6
0
355,752
51,976,576
Subset a pandas dataframe that has an index that contains duplicates
<p>For the data frame:</p> <pre><code>df = pd.DataFrame({ 'key': [1,2,3,4,5, np.nan, np.nan], 'value': ['one','two','three', 'four', 'five', 'six', 'seven'] }).set_index('key') </code></pre> <p>That looks like this:</p> <pre><code> value key 1.0 one 2.0 two 3.0 three 4.0 four 5.0 ...
<p>The thing is you have duplicated values <code>NaN</code>s as indexes. You should disconsider those when reindexing because they are duplicates and there is ambiguity on which value use in the new index.</p> <pre><code>df.loc[df.index.dropna()].reindex([1, 1, 6]) value key 1 one 1 one 6 NaN </code></pre>...
python|pandas
0
355,753
51,768,693
how to compare or merge two data frames using python pandas?
<p>How do I compare/merge two data frames based on the start and data columns and get the missing gaps with the count.</p> <p>Dataframe 1</p> <pre><code>id start 1 2009 1 2010 1 2011 1 2012 2 2010 2 2011 2 2012 2 2013 2 2014 </code></pre> <p>Data frame 2</p> <pre><code>id data 1 2010 1 2012 2 2010 2...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with <code>indicator=True</code> and outer join first:</p> <pre><code>df11 = df1.rename(columns={'start':'data'}) df = df2.merge(df11, how='outer', indicator=True, on=['id...
python|pandas
1
355,754
51,988,691
How to put parameters obtained through "pandas.describe" in a plot in one go?
<p>Like if i have a data frame with four columns and i want to plot any two columns of it just to visualize my data. And we can find the value of all the parameters by using this</p> <pre><code>pd.describe() count 332.000000 mean 5645.999337 std 391.081389 min 4952.290000 25% 5294.402500 50% ...
<p>Matplotlib has the option ax.text. So you need to convert this info into text. Here comes an example:</p> <pre><code>import pandas as pd df=pd.DataFrame({'A':[1,2,3]}) desc=df.describe() </code></pre> <p>Describe is also a DataFrame, you can turn every column into a string list:</p> <pre><code>data1=[i for i in d...
python-2.7|pandas|dataframe
4
355,755
51,948,262
Difference between .pb and .pbtxt in tensorflow?
<p>When saving a graph in tensorflow</p> <pre><code>tf.train.write_graph(     graph_or_graph_def,     logdir,     name,     as_text=True ) </code></pre> <p>There is this flag: <code>as_text</code>: If <code>True</code>, writes the graph as an ASCII proto.</p> <p>I found out that if it is <code>False</code> it saves ...
<blockquote> <p>Thanks to a comment this question can be answered (text is from <a href="https://chromium.googlesource.com/external/github.com/tensorflow/tensorflow/+/r0.10/tensorflow/g3doc/how_tos/tool_developers/index.md" rel="nofollow noreferrer">here</a>)</p> </blockquote> <p><strong>Text or Binary?</strong></p> <p...
tensorflow|machine-learning|deep-learning|ascii|protocol-buffers
13
355,756
51,953,630
Using arrays / other methods for optimization
<p>I have this code that is used to forecast predicted/ actual values essentially (units produced from a department) and the predicted values are extracted from a folder where I have 100 csv files labeled 1-100. I tell the program to go back into files before and compare it to the actual value produced( which is given ...
<p>Okay, so, a couple of things:</p> <ul> <li>You were reading each file 24 times (twice for each N).</li> <li>There was that needless repetition in generating x/y/z/w</li> </ul> <p>The optimizations/changes I made are, roughly:</p> <ul> <li>Using the lru_cache decorator to make sure each file is only read once (and...
python|pandas|csv
1
355,757
51,997,171
Pandas: vectorization with function on two dataframes
<p>I'm having trouble with implementing vectorization in pandas. Let me preface this by saying I am a total newbie to vectorization so it's extremely likely that I'm getting some syntax wrong.</p> <p>Let's say I've got two pandas dataframes.</p> <p>Dataframe one describes the x,y coordinates of some circles with radi...
<h2>Numba v1</h2> <p>You might have to install <code>numba</code> with </p> <pre><code>pip install numba </code></pre> <p>Then use <code>numba</code>s jit compiler via the <code>njit</code> function decorator</p> <pre><code>from numba import njit @njit def distances(point, points): return ((points - point) ** 2)...
python|pandas|vectorization
5
355,758
51,772,051
Filling in blank dictionary values based on other key value pairs
<p>I have a df that contains a column ['mjtheme_namecode'] which is in dictionary form containing a code and a name. The codes all have numbers but some of the names are missing. I would like to fill in the missing name values based on other pairs with the same code. Here is the df column in question:</p> <pre><co...
<p>You can take a similar approach of creating a new DataFrame, but then transition back:</p> <pre><code>theme= pd.DataFrame([val for pair in df['mjtheme_namecode'].values for val in pair]) mapper = theme.drop_duplicates().replace(r'', np.nan).dropna().set_index('code').name.to_dict() </code></pre> <p>Using a list co...
python|pandas|dictionary|missing-data
1
355,759
51,635,233
Can I create Excel workbooks with only Pandas (Python)?
<p>In the pandas documentation, it says that the optional dependencies for Excel I/O are:</p> <blockquote> <p>xlrd/xlwt: Excel reading (xlrd) and writing (xlwt)</p> <p>openpyxl: openpyxl &gt; version 2.4.0 for writing .xlsx files (xlrd &gt;= 0.9.0)</p> <p>XlsxWriter: Alternative Excel writer</p> </blockquote> <p>I can'...
<p>The pandas codebase does not duplicate Excel reading or writing functionality provided by the external libraries you listed. </p> <p>Unlike the csv format, which Python itself provides native support for, if you don't have any of those libraries installed, you cannot read or write Excel spreadsheets.</p>
python|pandas|pandas.excelwriter
3
355,760
51,919,344
Python for loop that stores image predictions to csv starts quickly but slows down
<p>I have a folder with >100,000 images, which I would like to classify using TensorFlow. I wrote a for loop that iterates over each image, returns a confidence score, and stores the predictions to a csv file. </p> <p>The problem is: The script starts very quickly (approx. 10 images per second for images 1-1000) and g...
<p>The problem lies within the <code>read_tensor_from_image_file</code> function. This function is called in each iteration of the loop. Within the function you are creating Tensorflow ops. As a rule of thumb, <code>tf.anything</code> calls are responsible for <em>building</em> the computational graph. They should only...
python|performance|csv|for-loop|tensorflow
1
355,761
51,987,556
Change variable based on other variable in Python
<p>I have the following dataframe called df containing a variable called Category. I would like to create new_variable with the below mentioned values in Python. How do I do? </p> <pre><code>df = pd.DataFrame({ 'Category': [ 'Foreign Stocks', 'Stocks China', 'Stocks', 'Bonds', 'Bonds USA', 'Bonds I...
<h2><code>pandas.Series.str.extract</code></h2> <pre><code>df.assign(New_Variable=df.Category.str.extract('(Bonds|Stocks)')) Category New_Variable 0 Foreign Stocks Stocks 1 Stocks China Stocks 2 Stocks Stocks 3 Bonds Bonds 4 Bonds USA Bonds 5 B...
python|pandas|if-statement|dataframe|conditional-statements
0
355,762
51,805,103
Python Pandas Regex specific string
<p>I would like to iterate through a column of records (string directory path's) and pull out the record id which is enclosed within parentheses. However, there are other instances where there are details enclosed within parentheses that are not record id's and need to be ignored.</p> <p>Code: </p> <pre><code>df1['D...
<p>This uses negative lookahead to filter out "Data Only" and date formats:</p> <pre><code>(\((?!Data Only)[^\-]+\)) </code></pre> <p><strong><em>Setup</em></strong>:</p> <pre><code>df = pd.DataFrame( {'Path': ['(Data Only) text (1, 2 and 3)', '(2013-08) foo (123)', '(Data Only) bar (1,2,3,4,5 and 6)']} ...
python|regex|pandas
0
355,763
51,665,386
Remove rows from a pandas df
<p>I am trying to delete all <code>rows</code> from a <code>pandas df</code>. Specifically, when the <code>row</code> beneath <code>X</code> in <code>Col A</code> is empty. So if the <code>row</code> underneath <code>X</code> in <code>Col A</code> is empty I want to delete all those rows until there is a <code>string</...
<p>Use:</p> <pre><code>m1 = df['A'] == 'X' g = m1.cumsum() m = (df['A'] == '') | m1 df = df[~m.groupby(g).transform('all')] print (df) A B C 3 X Val Val 4 Foo 1 2 5 3 4 6 X Val Val 7 Fou 1 2 8 3 4 9 X Val Val 10 Bar 1 2 </code></pre> <p><s...
python|pandas|sorting|select
1
355,764
36,182,380
How do display different runs in TensorBoard?
<p>TensorBoard seems to have a feature to display multiple different runs and toggle them. </p> <p><a href="https://i.stack.imgur.com/5E3eQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5E3eQ.png" alt="enter image description here"></a></p> <p>How can I make multiple runs show up here and how can assign a...
<p>In addition to TensorBoard scanning subdirectories (so you can pass a directory containing the directories with your runs), you can also pass multiple directories to TensorBoard explicitly and give custom names (example taken from the --help output):</p> <pre><code>tensorboard --logdir=name1:/path/to/logs/1,name2:/p...
tensorflow|tensorboard
153
355,765
35,894,080
using sympy solver and numpy dot doesn't work
<p>I'm trying to solve a long equation using sympy solve. This is a simplified version of the equation but the issue is the same.</p> <p>This code works fine:</p> <pre><code>import numpy as np import sympy as sy coupons = [0.504452818664, 0.486892427806, 0.47758800215, 100.468050176] rate = sy.Symbol('rat...
<p>A dot product of scalar <code>rate</code> and vector <code>coupons</code> hardly makes sense. You only get an element-wise multiplication of <code>rate</code> and each element. However, you can do this:</p> <pre><code>import numpy as np import sympy as sy coupons = np.array([0.504452818664, 0.486892427806, 0.47758...
python|numpy|sympy
2
355,766
36,031,749
Getting a function to work on every row of a dataframe (pandas)
<p>I want to pass each cell of a column in a dataframe to a function which then creates a new cell </p> <p>I've looked <a href="https://stackoverflow.com/questions/19667927/pass-entire-contents-of-a-dataframe-to-a-function-in-pandas">here</a> and <a href="https://stackoverflow.com/questions/15118111/apply-function-to-...
<p>Use <code>np.sqrt</code>, as this understands arrays:</p> <pre><code>In [86]: df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) df['sol'] = np.sqrt(df['A']) df Out[86]: A B C D sol 0 52 38 4 71 7.211103 1 59 4 36 15 7.681146 2 37 28 33 73 6.082763 ...
python|pandas
4
355,767
36,182,734
Plotting pandas dataframe with microseconds resolution
<p>I am trying to use python matplotlib to plot a pandas DataFrame. The DataFrame has a 'time' column and a 'val' column. The 'time' column is set as index and has resolution up to microseconds. When I go about plotting it, the values on the x-axis are are totally off (way outside the time range of the data). What ...
<p>You would need to convert your <code>time</code> column to <code>datetime</code> after reading it from the CSV file:</p> <pre><code>df['time'] = pd.to_datetime(df['time'], format="%H%M%S.%f") </code></pre> <p>alternatively you can do it on the fly when parsing your CSV file:</p> <pre><code>tm_parser = lambda x: p...
python|pandas|matplotlib
2
355,768
36,091,527
Receive multiple send commands using mpi4py
<p>How can I modify the following code (adapted from <a href="http://materials.jeremybejarano.com/MPIwithPython/pointToPoint.html" rel="nofollow">http://materials.jeremybejarano.com/MPIwithPython/pointToPoint.html</a>) so that every <code>comm.Send</code> instance is received by <code>root = 0</code> and the output pri...
<p>If you do not know how many messages you will send, then you have to introduce a message marking the end of messages. You can use this generically by using special tags. To avoid providing a mismatching buffer for the termination message, you can use <code>probe</code> checking what kind of message is coming in</p> ...
python|numpy|mpi|mpi4py
3
355,769
36,187,637
Convert Date Ranges to Time Series in Pandas
<p>My raw data looks like the following:</p> <pre><code> start_date end_date value 0 2016-01-01 2016-01-03 2 1 2016-01-05 2016-01-08 4 </code></pre> <p>The interpretation is that the data takes a value of <strong>2</strong> between <strong>1/1/2016</strong> and <strong>1/3/2016</strong>, and it takes a ...
<p>You may try this:</p> <pre><code>In [120]: df Out[120]: start_date end_date value 0 2016-01-01 2016-01-03 2 1 2016-01-05 2016-01-08 4 In [121]: new = pd.DataFrame({'dt': pd.date_range(df.start_date.min(), df.end_date.max())}) In [122]: new Out[122]: dt 0 2016-01-01 1 2016-01-02 2 2016-01-...
python|pandas|time-series
1
355,770
36,026,740
python3 interpreter gives different results than script for scipy.misc.imread
<p>I am trying to read image data into Python as a matrix.</p> <p>To this extent, I am trying to use <code>scipy.misc.imread('image.jpg').astype(np.float)</code>.</p> <p>When I execute the proper sequence of steps from a <code>python3</code> interpreter, everything works swimmingly, and I get a matrix as expected.</p...
<p>I figured out the solution to this. The <code>neural_style.py</code> script seems to be getting a different version of <code>scipy</code> module (or submodule) due to a side effect of importing <code>stylize.py</code> and, in turn, <code>vgg.py</code>. Adding this line:</p> <pre><code>import scipy.misc </code></p...
python|numpy|scipy
1
355,771
35,893,176
How to assign a value_count output to a dataframe
<p>I am trying to assign the output from a value_count to a new df. My code follows.</p> <pre><code>import pandas as pd import glob df = pd.concat((pd.read_csv(f, names=['date','bill_id','sponsor_id']) for f in glob.glob('/home/jayaramdas/anaconda3/df/s11?_s_b'))) column_list = ['date', 'bill_id'] df = df.set_ind...
<p>your column length doesn't match, you read 3 columns from the csv and then set the index to 2 of them, you calculated value_counts which produces a Series with the column values as the index and the value_counts as the values, you need to <code>reset_index</code> and then overwrite the column names:</p> <pre><code>...
python|pandas
12
355,772
35,820,676
Fail to implement Cardano method. Cube root of a complex number
<p>In order to improve <code>np.roots</code> performance on cubic equation, I try to implement <a href="https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Cardan#Formules_de_Cardan" rel="nofollow">Cardan(o) Method</a> :</p> <pre><code>def cardan(a,b,c,d): #"resolve P=ax^3+bx^2+cx+d=0" #"x=z-b/a/3=z-z0 =&gt; P=z^3+...
<p>You correctly identified the problem: there are three possible values of cubic root in a complex plane, resulting in 9 possible pairs of <code>((-q+r)/2)**(1/3)</code> and <code>((-q-r)/2)**(1/3)</code>. Of these 9, only 3 pairs lead to the correct roots: namely, those for which u*v = -p/3. An easy fix is to replace...
python|algorithm|numpy|math|numba
2
355,773
35,795,663
fastest way to find the smallest positive real root of quartic polynomial 4 degree in python
<p><strong>[What I want]</strong> is to find the only one smallest positive real root of quartic function <strong>a</strong>x^4 + <strong>b</strong>x^3 + <strong>c</strong>x^2 + <strong>d</strong>x + <strong>e</strong></p> <p><strong>[Existing Method]</strong> My equation is for collision prediction, the maximum degree...
<p>An other answer :</p> <p>do it with analytic methods (<a href="https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Ferrari" rel="nofollow">Ferrari</a>,<a href="https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Cardan#Formules_de_Cardan" rel="nofollow">Cardan</a>), and speed the code with Just in Time compilation (<a href="ht...
python|algorithm|numpy|math|scipy
5
355,774
37,592,935
How to append dynamically generated values into NumPy array?
<p>I want to add some dynamically calculated values to result array:</p> <pre><code>out = [] for item in foo: spam = get_spam(foo) out.append(spam) return np.array(out) </code></pre> <p>Unfortunately, this doesn't work, because <strong>spam</strong> shape is (10,1) and <strong>out</strong> array has one extr...
<p>You can use numpy <code>concatenate</code> function:</p> <pre><code>np.concatenate([get_spam(foo) for item in foo]) </code></pre> <p>It eventually accepts an argument <em>axes</em> for the direction of concatenation (vertically/horizontally).</p>
python|arrays|numpy
3
355,775
37,189,878
pandas add column to groupby dataframe
<p>I have this simple dataframe <code>df</code>:</p> <pre><code>df = pd.DataFrame({'c':[1,1,1,2,2,2,2],'type':['m','n','o','m','m','n','n']}) </code></pre> <p>my goal is to count values of <code>type</code> for each <code>c</code>, and then add a column with the size of <code>c</code>. So starting with:</p> <pre><co...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="noreferrer"><code>transform</code></a> to add a column back to the orig df from a <code>groupby</code> aggregation, <code>transform</code> returns a <code>Series</code> with its index aligned to the orig df:</p> <pre><code>In...
python|pandas
38
355,776
37,198,024
What is the difference between tensordot and einsum in numpy?
<p>For my understanding, tensordot <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.tensordot.html" rel="nofollow">http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.tensordot.html</a> is multiply two tensors and sum given indices. This is precisely einsum does. </p> <p>Actually...
<p>They are different approaches to similar problems. <code>einsum</code> is more general. Speed can be similar, though you need to check individual cases.</p> <p><code>tensordot</code> works by reshaping and transposing axes, reducing the problem to one that <code>np.dot</code> can solve. Its code, up to the <code...
python|numpy
8
355,777
37,239,627
Change values in pandas dataframe according to value_counts()
<p>I have following pandas dataframe :</p> <pre><code>import pandas as pd from pandas import Series, DataFrame data = DataFrame({'Qu1': ['apple', 'potato', 'cheese', 'banana', 'cheese', 'banana', 'cheese', 'potato', 'egg'], 'Qu2': ['sausage', 'banana', 'apple', 'apple', 'apple', 'sausage', 'banana', 'b...
<p>I would create a dataframe of same shape where the corresponding entry is the value count:</p> <pre><code>data.apply(lambda x: x.map(x.value_counts())) Out[229]: Qu1 Qu2 Qu3 0 1 2 1 1 2 4 3 2 3 3 1 3 2 3 3 4 3 3 3 5 2 2 3 6 3 4 3 7 2 4 3 ...
python|python-2.7|pandas
12
355,778
37,471,156
How to count multiple columns based on conditions
<p>dataframe:</p> <pre><code> a b c d name 0 t t t t john 1 t t t f doe 2 t t f f maria 3 t f f f smith </code></pre> <p>I would like to count the number of true in each column</p> <p><code>df[["a", "b", "c", "d"]].sum()</code> returns <code>Series([], dtype: float64)</code></p> <p>I would like to get</p> <pre><c...
<p>You can use sum on boolean columns. </p> <p><code>"t"</code> and <code>"f"</code> are strings not boolean, you have to first convert them to boolean:</p> <pre><code>In [11]: df == "t" Out[11]: a b c d name 0 True True True True False 1 True True True False False 2 True True...
pandas|dataframe
3
355,779
37,554,633
got TypeError when running linear regression with tensorflow. ' Op has type float64 that does not match type float32 of argument'
<p>I'm pretty new to tensorflow. I did a linear regression with tensorflow. when I ran the codes below, I got typeError like this:</p> <p>TypeError: Input 'y' of 'Mul' Op has type float64 that does not match type float32 of argument 'x'.</p> <p>Spent hours but could not figure out why. where did it go wrong? help ...
<p><strong>TL;DR:</strong> The placeholder <code>X</code> and variable <code>w</code> have different element types, and TensorFlow does not automatically cast op arguments, so the <code>tf.mul()</code> op fails.</p> <p>Your placeholder <code>X</code> has type <code>tf.float32</code> because it is defined to have dtype...
python|tensorflow
2
355,780
37,396,886
Combining Jupyter rich display and matplotlib charts
<p>I would like a piece of code (an analytical model) to produce a series out Jupter outputs so that when the module is run within Jupyter Notebook, it outputs to the notebook a number of tables, HTML outputs and matplotlib charts, in a specific order. </p> <p>The idea is that the model stores an list of objects, whi...
<p>You could also do something like this:</p> <pre><code>df = pd.DataFrame({'a':[1,2,3],'b':[3,2,1]}) plt.interactive(False) # This will prevent matplotlib from showing the plots immediately # You would want to create placeholders for different figures to show: fig1, ax1 = plt.subplots() fig2, ax2 = plt.subplots() ...
python|pandas|matplotlib|ipython|jupyter-notebook
3
355,781
37,402,046
Selecting rows from pandas dataframe based on cKDTree indices
<p>I was trying to do some quick-and-dirty reverse geocoding.</p> <p>I have the dataframe <code>poi</code> (around 50,000 rows), where each point of interest has a lat/lng coordinate.</p> <p>I have also the dataframe <code>postcode_existing</code> (around 180,000 rows), which maps lat/lng coordinates to postcodes.</p...
<p>I solved the problem. The issue was a mismatch between the position in the dataframe and the index due to the removal of certain rows.</p> <p>To fix this, I simply reset the index:</p> <pre><code>postcode_existing.reset_index(inplace=True, drop=True) </code></pre> <p>I was then able to use <code>loc</code> to ext...
python|pandas
1
355,782
37,497,704
Python.. image processing
<p>I need to store histograms of images from a database which can be later used to compare with the histogram of an image given by the user. The problem: how can I store histograms &amp; how can I compare histograms?</p> <pre><code>import numpy as np import cv2 from matplotlib import pyplot as plt def thresholded(cen...
<p>You can use again the <code>np.histogram</code> to get the values of the histogram into an array, Then save it to file with <code>np.save</code> and load it later with <code>np.load</code>. The histogram comparison is then easy. something like <code>np.linalg.norm(hist1 - hist2)</code>. see below (I changed <code>cv...
python-2.7|numpy|matplotlib
0
355,783
37,549,017
plot major ticks and labels only once per day in Pandas groupby DataFrame
<p>In Pandas, I have a DataFrame of observations (baby bottle feeding volumes) that are indexed by a datetime and grouped by date:</p> <pre><code>... bottles = bottles.set_index('datetime') bottles = bottles.groupby(bottles.index.date) </code></pre> <p>I want to use matplotlib to plot the cumulative values as they in...
<p>Since you didn't provide any data, I generated some dummy data. In essence, you can make the labels invisible by retrieving the ticks on the x-axis, and then making the hourly ticklabels visible.</p> <p>Note: this works for hours, so <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.r...
python|pandas|matplotlib
0
355,784
37,437,208
pandas DataFrame transpose/melt/pivot for one column only
<p>I have data like this in a pandas DataFrame:</p> <p><a href="https://i.stack.imgur.com/mfNpx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mfNpx.jpg" alt="Data 1"></a></p> <p>And I would like to transform it to this (in a pandas DataFrame): </p> <p><a href="https://i.stack.imgur.com/oW9dg.jpg...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a>:</p> <pre><code>print (df) ...
python|csv|pandas|dataframe
4
355,785
37,556,145
groupby multiple value columns
<p>I need to do a fuzzy <code>groupby</code> where a single record can be in one or more groups. </p> <p>I have a <code>DataFrame</code> like this:</p> <pre><code>test = pd.DataFrame({'score1' : pandas.Series(['a', 'b', 'c', 'd', 'e']), 'score2' : pd.Series(['b', 'a', 'k', 'n', 'c'])}) </code></pre> <p>Output:</p> ...
<p>Combine the two <code>columns</code> in a single <code>column</code> using e.g. <code>pd.concat()</code>:</p> <pre><code>s = pd.concat([test['score1'], test['score2'].rename(columns={'score2': 'score1'})]).reset_index() s.columns = ['val', 'grp'] val grp 0 0 a 1 1 b 2 2 c 3 3 d 4 4 e 5 ...
python|pandas|dataframe|group-by
2
355,786
37,247,161
pandas installation on ubuntu error code 1 in /tmp/pip-build-FM0q5o/pandas/
<p>i tried to install pandas in ubuntu but there is problem.<br> i already install numpy and go for pandas </p> <blockquote> <p>kcn@vaio :~$ sudo pip install pandas</p> </blockquote> <pre><code>The directory '/home/kcn/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been...
<p>I got this answer by my self<br> Actually in Ubuntu there are two version of Python already installed<br> so when pip install we have to do like this<br> first confirm your which python you are using by this <strong>python -version</strong> then make sure your desire python version by like this: <strong>alias pytho...
python|ubuntu|numpy|pandas
3
355,787
41,690,769
pandas df locate keep only first item
<p>i want to get the value of another column based on a value in a certain column, in the same row. </p> <p>example:</p> <p>for business id = '123', i want to retrieve the business_name</p> <p>df:</p> <pre><code>biz_id biz_name 123 chew 456 bite 123 chew </code></pre> <p>code:</p> <pre><code>df['b...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iat.html" rel="nofollow noreferrer"><code>iat</code></a> for select first value of <code>...
python|pandas
2
355,788
42,127,046
Fast slicing and multiplication of scipy sparse CSR matrix
<p>I have a scipy sparse <code>CSR</code> matrix of size 2M x 50k with 200M non-zero values (100 per row). I need to slice 120k rows of it by a (randomly distributed) index (which is a pandas <code>Series</code>) and then multiply that submatrix by a sparse vector of size 1x50k (with 100 non-zero values as well).</p> ...
<p>I explained in <a href="https://stackoverflow.com/questions/39500649/sparse-matrix-slicing-using-list-of-int">Sparse matrix slicing using list of int</a> that this kind of row indexing is actually performed with matrix multiplication. In effect it constructs a sparse vector with 1's for the desired rows, and does t...
python|pandas|matrix|scipy|sparse-matrix
1
355,789
41,762,553
List of class methods with Napoleon Sphinx extension using NumPyDoc style
<p>I am using NumPyDoc-style docstrings to document a Python package. I would like to switch from the <a href="https://pypi.python.org/pypi/numpydoc?" rel="noreferrer">'numpydoc'</a> Sphinx extension to <a href="http://www.sphinx-doc.org/en/1.5.1/ext/napoleon.html#module-sphinx.ext.napoleon" rel="noreferrer">Napoleon</...
<p><code>sphinx.ext.autosummary</code> helps to achieve a Sphinx table of contents for the lists of class methods and attributes</p> <p>I went through both the numpydoc and Sphinx documentation to understand how it works. Do find the details below.</p> <p><strong>SECTION 1</strong> : understanding working of numpydoc</...
python|documentation|numpydoc|sphinx-napoleon
0
355,790
41,964,462
How to compute the correlation coefficient between two columns from a data frame?
<p>I want to compute the correlation between two different columns from the same data frame. This is the code I use:</p> <pre><code>Correlation_unemp_demvote=np.corrcoef(New_table['unemp'], New_table['demVote']) Correlation_unemp_demvote </code></pre> <p>The outcome as follows:</p> <pre><code>array([[ 1. ...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.corr.html" rel="noreferrer"><code>pd.Series.corr</code></a> is what you want.<br> Do this instead</p> <pre><code>Correlation_unemp_demvote = New_table['unemp'].corr(New_table['demVote']) </code></pre> <hr> <p><strong><em>example</em></st...
python|pandas
5
355,791
41,947,353
initialize pandas SparseArray
<p>Is it possible to initialize a pandas SparseArray by providing only the dense entries? I could not figure this out from the documentation: <a href="http://pandas.pydata.org/pandas-docs/stable/sparse.html" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/stable/sparse.html</a> . </p> <p>For example, sa...
<p>A length 10 <code>SparseArray</code> with a one at index 9 and zeros everywhere else:</p> <pre><code>pd.SparseArray(1, index= range(1), kind='block', sparse_index= BlockIndex(10, [8], [1]), fill_value=0) </code></pre> <p>Notes:</p> <ol> <li><code>index</code> could be any list as l...
pandas
1
355,792
41,892,918
valuerror use np.all() or np.any() after using an assert
<p>I have this code:</p> <pre><code>import numpy as np class Variables(object): def __init__(self, var_name, the_method): self.var_name = var_name self.the_method = the_method def evaluate_v(self): var_name, the_method = self.var_name, self.the_method if the_method == 'dif...
<p><code>assert np.all(obs == expected_output)</code> works:</p> <pre><code>def test_evaluate_v_method_returns_correct_results( self, var_name, the_method,expected_output): var_name, the_method = self.variables.var_name, self.variables.the_method obs = self.variables.evaluate_v() ass...
python|numpy|pytest
1
355,793
42,054,132
Pandas/Numpy Get matrix from column of arrays
<p>I have a pandas dataframe with a column of lists.</p> <p>df:</p> <pre><code> inputs 0 [1, 2, 3] 1 [4, 5, 6] 2 [7, 8, 9] 3 [10, 11, 12] </code></pre> <p>I need the matrix</p> <pre><code>array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]]) </code></pre> <p>An efficient way ...
<p>You can convert the column to list and then apply numpy array, if all the lists in the column have the same length, this will make a 2D array:</p> <pre><code>arr = np.array(df.inputs.tolist()) #array([[ 1, 2, 3], # [ 4, 5, 6], # [ 7, 8, 9], # [10, 11, 12]]) arr.shape # (4, 3) </code></pre>...
python|pandas
7
355,794
42,081,511
Change value in specific row in pandas
<p>I need some help in python. I need to modify the value in a specific row. I have something like this. </p> <pre><code>ID Status Customer Name 345 New Braskem S.A 923 Closed Braskem 046 New Braskem S.A 195 New Braskem S.A 537 In Progress Braskem 237 ...
<p>There's a few ways to do this. Arguably the simplest is to use <code>pandas.DataFrame.replace</code>:</p> <pre><code>df.replace(to_replace='Braskem S.A', value='Braskem') </code></pre> <p>You can also use a boolean mask or a map.</p>
python|excel|pandas|rename
2
355,795
42,021,800
Fast reading of specified columns in df using pandas.to_hdf
<p>I have a dataframe of 2Gb that is a write once, read many df. I would like to use the df in pandas, therefore I was using <code>df.read_hdf</code> and <code>df.to_hdf</code> in a fixed format which works pretty fine in reading and writing.</p> <p>However, the df is growing with more columns being added, so I would...
<p>IMO the main advantage of using <code>format='table'</code> in conjunction with <code>data_columns=[list_of_indexed_columns]</code> is the ability to conditionally (see <code>where="where clause"</code> parameter) read huge HDF5 files. So that you can filter your data <strong>while reading</strong> and process your ...
python|pandas|hdf5
4
355,796
41,958,973
Pandas changing order of columns after data retrieval
<p>I would like to change the column names of a pd dataframe but I'm finding that the order of the columns change after data is retrieved. The below code specifies sector ETF symbols and fetches the data from yahoo finance. </p> <p>The problem is that once I run the code, for example, 'XLY' is no longer the first seri...
<p>use <code>reindex_axis</code></p> <pre><code>sec_perf.reindex_axis(secs, 1) </code></pre> <p><a href="https://i.stack.imgur.com/Mm0wJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mm0wJ.png" alt="enter image description here"></a></p> <p>You could also have used <code>sec_perf[secs]</code> to...
python|pandas|dataframe|renaming
4
355,797
42,046,525
Two staged training for different dependent graphs in tensorflow
<p>I am trying to perform two tasks (A and B) which have inputs <code>inp_A</code> and <code>inp_B</code> and corresponding outputs <code>out_A</code>, <code>out_B</code>.</p> <p>Task A is to be first achieved by a Graph <code>g_A</code>. After Task A is finished, I wish to use the weights of <code>g_A</code> into a n...
<p>I am using this kind of split for training and validation purposes, where I create dedicated input and output pipelines but share the inception part of the graph, although I'm using the same <em>graph</em> (as of <code>tf.Graph()</code>), but different (unconnected) <em>subgraphs</em> within it.</p> <p>Within one <...
python|tensorflow|deep-learning
1
355,798
42,074,595
Convolution neural network output value in range
<p>i'm trying to learn about convolution neural network using tensorflow , i'm using the code bellow to create my network .</p> <pre><code> # network weights W_conv1 = weight_variable([8, 8, 4, 32]) b_conv1 = bias_variable([32]) W_conv2 = weight_variable([4, 4, 32, 64]) b_conv2 = bias_variable([64]...
<p>if [a,b] is categorical, i.e. you have discrete classes (say n in total), you need to have n neurons as in readout layer, each corresponding to a given class representing its probability. Standard way to do it is using sigmoid cross entropy on logits (using tf.nn.sigmoid_cross_entropy_with_logits in case of tensorfl...
tensorflow|neural-network|deep-learning
0
355,799
41,929,772
Time difference within group by objects in Python Pandas
<p>I have a dataframe that looks like this:</p> <pre><code>from to datetime other ------------------------------------------------- 11 1 2016-11-06 22:00:00 - 11 1 2016-11-06 20:00:00 - 11 1 2016-11-06 15:45:00 - 11 12 2016-11-06 15:...
<pre><code>df.assign( timediff=df.sort_values( 'datetime', ascending=False ).groupby(['from', 'to']).datetime.diff(-1).dt.seconds.div(60).fillna(0)) </code></pre> <p><a href="https://i.stack.imgur.com/NCgJR.png"><img src="https://i.stack.imgur.com/NCgJR.png" alt="enter image description here"></a></p>
python|pandas|difference|data-science|pandas-groupby
19