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
366,900
70,980,990
How to install terality on google colabrotary
<p>I want to install terality on google colab how to do that</p> <p>i tried this first i wrote:</p> <pre><code>pip install --upgrade terality terality account configure --email myemail@gmail.com </code></pre> <p>but after the next command it shows this error:</p> <pre><code>File &quot;&lt;ipython-input-5-01d28d6ffdce&g...
<p>These snippets are not Python code, but shell commands. In Google Colab, as well as in most Jupyter notebooks, a cell runs Python code by default.</p> <p>To run a shell command in a cell, prefix the commands with a <code>!</code>:</p> <pre><code>!pip install terality </code></pre> <pre><code>!terality account config...
pandas|google-colaboratory
0
366,901
70,964,964
can't compile model using Non Max Suppression + Dense layer because of unknown NMS output size
<p>I'm trying to write a model that extracts 10 regions of interest out of 128 proposals and feeds them into a Dense layer:</p> <pre><code># x is an input tensor of size [None, 128, 4]. # scores is the corresponding [None, 128] score vector. indices = tf.image.non_max_suppression(x, scores, 10) x = x[indices] x = tf....
<p>I managed to fix this problem by padding the indices to a fixed length like so:</p> <pre><code>fixed_size_indices = tf.zeros(10, tf.int32) indices = tf.image.non_max_suppression(x, scores, 10) if tf.less_equal(tf.size(indices), 10): indices = tf.concat([indices, tf.zeros(10 - tf.size(indices), dtype=&quot;int32&...
tensorflow|keras|object-detection-api|non-maximum-suppression
0
366,902
71,080,976
TFCamemBERT model trains but no results in test
<p>Currently I am working on Named Entity Recognition in the medical domain using Camembert, precisely using the model: <a href="https://huggingface.co/jplu/tf-camembert-base" rel="nofollow noreferrer">TFCamembert</a>.</p> <p>However I have some problems with the fine-tuning of the model for my task as I am using a pri...
<p>I would first verify on a single sentence whether the model gives reasonable predictions after training, as follows:</p> <pre><code>from transformers import BertTokenizer, TFBertForTokenClassification import numpy as np tokenizer = BertTokenizer.from_pretrained(&quot;jplu/tf-camembert-base&quot;) model = TFBertForT...
python|tensorflow|nlp|huggingface-transformers|named-entity-recognition
1
366,903
70,887,834
Geopandas Explore - Reorder Items in Legend
<p>I'm working on plotting some Census data on a map using the Geopandas Explore method and am running into some issues with customizing the legend. For background, I've pulled together Household tract-level income data form the Census and created a household income classification column where I'm assigning one of 5 in...
<p>This is currently not possible using the public API as the order is hard-coded in the code. But you can try using the private function that creates the legend to get the desired outcome. Just try not to rely on it in a long-term. I'll open an issue on this in GeoPandas to implement this kind of customisation directl...
python|mapping|visualization|geopandas|folium
1
366,904
70,816,829
Partial update tensor based on boolean mask in TensorFlow
<p>I want to update part of the tensor based on some conditions.</p> <p>I know that TensorFlow tensors are immutable so creating a new tensor would be ok for me. I tried <code>tensor_scatter_nd_update</code> method but I couldn't make it work</p> <p>This is code that I want to replicate in TensorFlow written in NumPy.<...
<p>In TensorFlow, we do not update tensors that are in fact immutable objects. Instead we create new tensors from other tensors like in functional languages.</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf a = tf.random.uniform(shape=(1, 3)) b = tf.constant([[0, 1, 0]], dtype=tf.int32) c =...
python|tensorflow|tensorflow2.0
2
366,905
70,985,437
AttributeError: shape | When using skimage resize with pyscreenshot.grab() as input?
<p>I'm attempting to resize an image captured using pyscreenshot.grab() to 28x28 pixels</p> <pre><code>import pyscreenshot from skimage.transform import resize def captureAndSubsample(): userImage = pyscreenshot.grab(bbox=(785, 335, 1125, 675)) userImageResized = resize(userImage, (28, 28)) </code></pre> <p>Th...
<p>Converting <code>userImage</code> to a numpy array before passing to the scikit-image function does the trick.</p> <pre><code>import pyscreenshot import numpy as np from skimage.transform import resize userImage = pyscreenshot.grab(bbox=(785, 335, 1125, 675)) userImage = np.array(userImage) userImageResized = resiz...
python|numpy|screenshot|shapes|scikit-image
1
366,906
70,884,608
Getting optimal vocab size and embedding dimensionality using GridSearchCV
<p>I'm trying to use <code>GridSearchCV</code> to find the best hyperparameters for an LSTM model, including the best parameters for vocab size and the word embeddings dimension. First, I prepared my testing and training data.</p> <pre><code>x = df['tweet_text'] y = df['potentially_harmful'] from sklearn.model_selecti...
<p>I tried with scikeras but I got errors because it doesn't accept <a href="https://github.com/adriangb/scikeras/blob/cbc7940df9b77e69f1bf3f2735fc980849cfd4a7/scikeras/wrappers.py#L630" rel="nofollow noreferrer">not-numerical inputs</a> (in our case the input is in <em>str</em> format). So I came back to the standard ...
python|tensorflow|machine-learning|keras|hyperparameters
0
366,907
70,861,809
Dimension mismatch during Keras to ONNX conversion (2D output)
<p>I am observing a dimension mismatch in Keras to ONNX conversion. I saved my model as a .h5 file. It can successfully be saved and loaded again. However, when converting it to an ONNX model, I get different output dimensions.</p> <p>I think I experience this due to 2D output, because one of my output dimension is sim...
<p>I have no problem following the example I try by loading and run it still have the same results but I using the pdb format. The pdb format is a molecular format that includes sutures and using from model.save( ... )</p> <h3>( 1 ) : Save and convert</h3> <p>import tensorflow as tf import tf2onnx import onnx</p> <p>mo...
python|tensorflow|keras|onnx
1
366,908
70,786,941
Parse CSV in 2D Python Object
<p>i am trying to do Analysis on a CSV file which looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">timestamp</th> <th style="text-align: center;">value</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">1594512094.39</td> <td style="...
<p>You can first filter the rows which timestamp values are between the 'start' and 'end.' Then you can calculate the values of the filtered rows, as follows: (But, in the sample data, it seems that there is no row, which timestamp are between the range from 1594512109.13668 to 1594512129.37415. You can edit the range ...
python|pandas|csv
0
366,909
70,988,639
pandas column to list for a json file
<p>from a Dataframe, I want to have a JSON output file with one key having a list:</p> <p>Expected output:</p> <pre><code>[ { &quot;model&quot;: &quot;xx&quot;, &quot;id&quot;: 1, &quot;name&quot;: &quot;xyz&quot;, &quot;categories&quot;: [1,2], }, { ... }, ] </code></pre> <p>What I have:</p...
<p>You can use:</p> <pre><code>df = pd.read_excel('data_threated.xlsx').reset_index(drop=True) df['categories'] = df['categories'].apply(lambda x: [int(i) for i in x.split(',')] if isinstance(x, str) else '') df.to_json('output.json', orient='records', indent=4) </code></pre> <p>Content of <code>output.json</code></p> ...
json|pandas|dataframe|to-json
1
366,910
70,892,231
RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x3072 and 64x3072)
<p>I'm trying to make an image detection neural network. The train data is loaded within a batch size of 64. After running this code I get the RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x3072 and 64x3072). It's confusing, because to me these 2 shapes/size seem like they're the same. Can anyone help me f...
<p>The shape of <code>x</code> at <strong>#5</strong> is <code>(64, 768, 2, 2)</code>, i.e. <code>3072</code> components per batch element. Yet <code>fc1</code> only expects <code>64</code> features. For instance, you could replace <code>fc1</code> and <code>fc2</code> with:</p> <pre><code>self.fc1 = nn.Linear(3072, 64...
python|pytorch
0
366,911
70,763,876
Dask ParserError: Error tokenizing data when reading CSV
<p>I am getting the same error as <a href="https://stackoverflow.com/questions/45752805/dask-read-csv-fails-where-pandas-doesnt">this question</a>, but the recommended solution of setting <code>blocksize=None</code> isn't solving the issue for me. I'm trying to convert the NYC taxi data from CSV to Parquet and this is...
<p>The raw file <code>s3://nyc-tlc/trip data/yellow_tripdata_2010-02.csv</code> contains an error (one too many commas). This is the offending line (middle) and its neighbours:</p> <pre><code>VTS,2010-02-16 08:02:00,2010-02-16 08:14:00,5,4.2999999999999998,-73.955112999999997,40.786718,1,,-73.924710000000005,40.8413350...
python|pandas|csv|dask
1
366,912
70,864,603
convert json to csv without keys and put all values in one row
<p>how can i convert from this json-format:</p> <pre><code>{ &quot;Key1&quot;: { &quot;Value&quot;: &quot;123&quot;, &quot;Value&quot;: &quot;456&quot;, }, &quot;Key2&quot; : { &quot;Value&quot;: &quot;789&quot;, }, &quot;Key3&quot;: { &quot;Value&quot;: &quot;000&quot;, },...
<p>Assuming that the JSON is fixed to be valid, then you can easily do this with a nested list comprehension:</p> <pre class="lang-py prettyprint-override"><code>data = { &quot;Key1&quot;: { &quot;Value1&quot;: &quot;123&quot;, # Note: I've fixed your JSON here. &quot;Value2&quot;: &quot;456&quot;, ...
python|json|pandas|csv|row
2
366,913
70,977,707
Make stacked barplot using pandas
<p>I have the following dataframe:</p> <pre><code> condition area Month Oct Poor 11.386331 Oct Better 65.483997 Oct Favourable 5.165156 Oct Exceptional 17.964516 Nov Poor 14.589887 Nov Better 62.965886 Nov Favourable 4.942206 Nov Exceptional 17.50202...
<p>The problem with the code is, that <code>df.plot.bar()</code> does not group the index of your Dataframe and stacks only multiply columns for the same index.</p> <p>For your task you have to rearrange your data. For this use <code>reset_index</code> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.Da...
python|pandas|dataframe
1
366,914
70,947,589
How to convert XML file to pandas dataframe?
<p>I have the following XML and I am trying to convert, some data, into a pandas dataframe:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;DataSet xmlns=&quot;http://tempuri.org/&quot;&gt; &lt;xs:schema id=&quot;NewDataSet&quot; xmlns=&quot;&quot; xmlns:xs=&quot;http://www.w3.org/...
<p>You can use <code>read_xml</code> for loading xml files to a dataframe with pandas : <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_xml.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.read_xml.html</a></p>
python|pandas|xml
0
366,915
70,797,687
Fill in series to mirror a column if another column contains missing values in Python
<p>I have a dataset where I would like to fill in a series to mirror a column if another column contains missing values in Python</p> <p><strong>Data</strong></p> <pre><code>index1 id stat id_A id_B 1 aa y aa_Q1.22_1 aa_Q1.22_1 1 aa y aa_Q2.22_2 aa_Q2.22_2 1 ...
<p>Another option is to use <code>np.where</code>. Simply choose from &quot;id_A&quot; or &quot;id_B&quot; depending on if <code>df['id_B']== ''</code> is True or False:</p> <pre><code>df['id_B'] = np.where(df['id_B']== '', df['id_A'], df['id_B']) </code></pre> <p>Output:</p> <pre><code> index1 id stat id_A ...
python|pandas|numpy
2
366,916
70,750,200
Building tkinter GUI to track time
<p>I'm trying to build a GUI that tracks the amount of time I'm working on different projects. I've been using tkinter, and want a different frame for each project that has start/stop/reset buttons. Unless I'm misunderstanding, to accurately track the time by project, each project frame will need it's own independent f...
<p>I have enjoyed looking at your question. I took your code and a radically different approach. I believe that classes are a most important aspect of python programming, especially when dealing with tkinter gui's. There are several descriptions of python classes such as<a href="http://introtopython.org/classes.html...
python|pandas|loops|tkinter
0
366,917
70,962,806
How would I display all rows in a CSV in pycharm?
<p>So far I have</p> <pre><code>import pandas as pd data = pd.read_csv(r&quot;C:\Users\Username\Desktop\Serial.csv&quot;) print(data) </code></pre> <p>I have tried</p> <pre><code>pd.set_option('display.max_rows', see.shape[0]+1) </code></pre> <p>and it still only displays a few rows.</p>
<p>This works for me in PyCharm.</p> <pre><code>import pandas as pd df = pd.DataFrame({'x':list(range(500))}) pd.set_option('display.max_rows', df.shape[0]) print(df) </code></pre>
python|pandas
0
366,918
70,896,878
Pandas: apply result_type="expand": wrong dtypes
<p>I want to add multiple columns to a DataFrame:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( [ (0, 1), (1, 1), (1, 2), ], columns=['a', 'b'] ) def apply_fn(row) -&gt; (int, float): return int(row.a + row.b), float(row.a / row.b) ...
<p>I believe this is happening because <code>result_type='expand'</code> causes to be expanded as a Series, so the first <strong>row</strong> is in its own series, then the next row, etc. <em>But</em>, because Series objects can only have one dtype, the ints get converted to floats.</p> <p>For example, look at this:</p...
python|pandas|apply|dtype
3
366,919
70,896,761
What is the best solution to pick up value from rigth column based on range in left column?
<p>What is the best solution to pick up value from rigth column based on range in left column? What is best not to use heavy loops: numpy array, pandas series, dict, list. Data itself in Dataframe and ranges are bigger that in the example. And not only one value it could be a row with many values.</p> <p><a href="https...
<p>IIUC, split your range into two other columns (left and right) then return the right value from right column if <code>(left &lt;= x) &amp; (x &lt;= right)</code></p> <pre><code>df = pd.DataFrame({'range': ['51-60', '61-70'], 'value': [6505.00, 6730.00]}) df[['left', 'right']] = df['range'].str.split('-', expand=True...
python|pandas|dataframe|numpy
1
366,920
70,824,186
How to count hypothenuses with pandas udf, pyspark
<p>I want to write a panda udf which will take two arguments cathetus1, and cathetus2 from other dataframe and return hypot.</p> <pre><code># this data is list where cathetuses are. data = [(3.0, 4.0), (6.0, 8.0), (3.3, 5.6)] schema = StructType([StructField(&quot;cathetus1&quot;,DoubleType(),True),StructField(&quot;ca...
<p>You can apply <code>np.hypot</code> on the 2 <code>cathetus</code> directly without extracting individual values.</p> <pre class="lang-py prettyprint-override"><code> from pyspark.sql import functions as F from pyspark.sql.types import * data = [(3.0, 4.0), (6.0, 8.0), (3.3, 5.6)] schema = StructType([StructField(&...
pandas|dataframe|pyspark
0
366,921
70,922,095
Pygeos option for geopandas slows down read_file procces
<p>I have a 95000 item shapefile, I import the file with GeoPandas using <code>read_file</code>. The item are polygons with fairly simple geometry, with the biggest polygon with 316 points.</p> <p><strong>Problem</strong></p> <p>While doing some speed tests using the option <code>options.use_pygeos = True</code> actua...
<p>Can you try this code before reading the shapefiles? I have got this same error so far:</p> <pre><code>import shapely shapely.speedups.disable() </code></pre>
python|geopandas
0
366,922
70,785,653
Replacing numeric value with a different numeric value
<p>I imported a CSV file in Python. One of the fields is numeric with 11 digits. The first 2 digits all start with 27. How can i replace the 27 with a 0?</p>
<p>Just try following code: df['column_name']=df['column_name'].replace([original_value], new_value) if you want to replace more than one values: df['column_name']=df['column_name'].replace([v1, v2, v3], [a, b, c])</p>
python|pandas
0
366,923
70,783,357
How do I normalize the pixel value of an image to 0~1?
<p>The type of my <strong>train_data</strong> is '<strong>Array of unit 16</strong>'. The size is <strong>(96108,7,7)</strong>. Therefore, there are 96108 images.</p> <p>The image is different from the general image. My image has a sensor of 7x7 and 49 pixels contain the number of detected lights. And one image is the ...
<p><strong>Contrast Normalization</strong> (or contrast stretch) should not be confused with <strong>Data Normalization</strong> which maps data between 0.0-1.0.</p> <hr /> <h2>Data Normalization</h2> <p>We use the following formula to normalize data. The <em>min()</em> and <em>max()</em> values are the possible minimu...
python|image|numpy|normalization
3
366,924
70,889,750
Function will not run properly within a class but will run fine in a script on its own
<p>I am having a challenging time finding references to my issue after searching. I have a function that performs an Asana task update. It will run just fine when accessed in a simple script. I copied it into a class and now I get an invalid JSON error.</p> <p>The traceback is as follows:</p> <pre><code>Traceback (mos...
<p>Thank you all for the sound advice on both my potential issue as well as helping to improve my style...It turns out that I was formatting null values as nan when using the pd.fillna method in the function in question which was causing the JSON structure to fail. After reformatting it to a value of 0 all works as des...
python|pandas|dataframe|asana|asana-api
0
366,925
51,669,232
Pandas merge with duplicated key - removing duplicated rows or preventing it's creation
<p>I have two dataframes that i want to merge, but my key column contains duplicates. Dataframes looks like this:</p> <pre><code>Name,amount,id John,500.25,GH10 Helen,1250.00,GH11 Adam,432.54,GH11 Sarah,567.12,GH12 Category,amount,id Food,500.25,GH10 Travel,1250.00,GH11 Food,432.54,GH11 </code></pre> <p>And I'm perf...
<p>I suggest create new helper column for count <code>id</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="noreferrer"><code>cumcount</code></a> and then merge by this values:</p> <pre><code>df1['g'] = df1.groupby('id').cumcount() df2['g'] =...
python|pandas|dataframe
13
366,926
51,608,651
what ImagePairData layers means in Caffe?
<p>I have a Caffe .prototxt file and i want to convert Caffe layers in Keras or TensorFlow. There is one layer type: "ImagePairData", i don't understand what this means and what's its conversion to Keras or TensorFlow? Here is the Layer:</p> <pre><code>layer { name: "pairdata" type: "ImagePairData" top: "data" ...
<p>This layer is not part of caffe's "basic" layers (the layers caffe is "shipped" with, see a list of caffe layers <a href="http://caffe.help/manual/layers.html" rel="nofollow noreferrer">here</a>). It is probably a custom layer written by whomever you are trying to take this model from. </p> <p>Without looking at th...
tensorflow|keras|deep-learning|caffe|caffe2
0
366,927
51,691,240
Adding col to pd.df with value looked up from second df
<p>I am looking to add a new column to a df which I look up from a second df (df2). The df:</p> <pre><code> code date settlement strike type 0 CBT_21_G2015_S 2015-01-02 1.343750 126.0 C 1 CBT_21_G2015_S 2015-01-02 4.359375 131.5 P 2 CBT_21_G2015_S 2015-01-02 24.671875 102.5 ...
<p>IIUC, you can use index matching</p> <pre><code>df = df.set_index('code') df['expiry'] = df2.set_index('code')['expiry_date'] df.reset_index() code date settlement strike type expiry 0 CBT_21_G2015_S 2015-01-02 1.343750 126.0 C 2015-01-23 1 CBT_21_G2015_S 2015-01-02 4.3593...
python|pandas|python-3.7
1
366,928
51,882,858
Tensorflow - training Adam
<p>I try to build my first simple neural network with tensorflow, above you can see my code. My code can calculate the loss, but when i try to add the train_step i got the error message <code>InvalidArgumentError (see above for traceback): Matrix size-incompatible: In[0]: [2,2], In[1]: [1024,1]</code>, which says that ...
<p>The reason is due to your input and labels being inconsistent. For your inputs, you have 2 input vectors with dimensions (1, 5). In your output layer, you have one output. And in your labels, you have only one example of dimension (1,2).</p> <p>Two fixes depending on what you wanted to do. If you meant to do tw...
tensorflow|matrix|optimization
0
366,929
51,574,218
tensorflow softmax_cross_entropy_with_logits_v2 throws ValueError
<p>I have defined a neural network of a single input layer and an output layer. My data is in csv format which I have converted to tfrecord format. Using tf.data api i batch it and feed it as follows :</p> <ul> <li>Features : 32(batch size) x 24(feature column)</li> <li>Label : 32(batch size) x 4(onehot encoded)</l...
<pre><code>trainStep, cross_entropy, features, ground_truth = model() </code></pre> <p>This 4 return values do not match your return statement:</p> <pre><code>return train_op, ground_truth_input, bottleneck_input, loss_mean </code></pre>
python|python-2.7|tensorflow
1
366,930
51,720,348
How to merge a dataframe with MultiIndex into another dataframe in an efficient way?
<p>I have two DataFrames and I would like to take the median of one column grouped by a set of two other columns from dataframe A and then merge the calculated median into dataframe B. Let me explain it using the example below:</p> <p>I have two <code>DataFrame</code>s which look like</p> <pre><code># DataFrame 1 ...
<p>Turn <code>a</code> into a dataframe and rename the values to <code>median_fare</code> using <code>a.to_frame('median_fare')</code>, reset the index, then do an outer merge with <code>df2</code>. It will automatically merge on the 2 columns in common (<code>do_c</code> and <code>pu_c</code>)</p> <pre><code>df2.merg...
python|python-2.7|pandas|pandas-groupby
2
366,931
51,719,643
Error converting pandas grouped column into string
<p>I'm trying to convert a grouped column of a pandas frame into a string:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'date' : ['2018-01-01','2018-01-01','2018-01-02','2018-01-02'], 'product' : ['apple','banana','banana','pear'], 'price' : [100,200,300,400] }) grouped_df = d...
<p>Try like this:</p> <pre><code>grouped_df['product'] = grouped_df['product']['unique'].apply(lambda x: ';'.join(x)) &gt;&gt;&gt; grouped_df date product price unique sum 0 2018-01-01 apple;banana 300 1 2018-01-02 banana;pear 700 </code></pre> <p>The issue was that you...
python|pandas|csv
2
366,932
51,622,411
Can't import frozen graph after adding layers to Keras model
<p>I'm trying to load a trained Keras model from the .h5 file, then wrap a couple TensorFlow layers around it and save as a ProtoBuf. The saving works just fine, but when I import the graph def, I get the error:</p> <blockquote> <p>ValueError: Input 0 of node batch_normalization_24_1/cond/ReadVariableOp/Switch_1 was...
<p>I'v just successfully coped with almost the same issue. As denoted in <a href="https://stackoverflow.com/a/52823701/2953509">my answer</a> on the other question this issue probably related with </p> <pre><code>keras.backend.set_learning_phase(0) </code></pre> <p>which should be placed right before model loading.<...
python|tensorflow|keras
2
366,933
51,872,892
pandas create new column based on grouping
<p>I have a pandas dataframe which looks like the following.</p> <pre><code>df = index| date | amount| type| 0 | 2015 | 1000 | A | 1 | 2015 | 100 | B | 2 | 2016 | 3500 | A | 3 | 2017 | 150 | C | </code></pre> <p>I want to produce a dataframe with a new...
<p>you can try</p> <pre><code>ss=df.groupby(['date','type']).sum().reset_index() ss.pivot(index='date',columns='type',values='amount').fillna(0) </code></pre>
python|python-3.x|python-2.7|pandas|numpy
2
366,934
51,609,299
Python np.lognormal gives infinite results for big average and St Dev
<p>I am trying to draw the lognormal distribution for my data. using the following code:</p> <pre><code>mu, sigma = 136519., 50405. # mean and standard deviation hs = np.random.lognormal(mu, sigma, 1000) #mean, s dev , Size count, bins, ignored = plt.hist(hs, 100, normed=True) x = np.linspace(min(bins), max(bins)...
<p>The parameters mu and sigma in <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html" rel="noreferrer">np.random.lognormal</a> are <strong>not</strong> the mean and STD of the lognormal distribution. They are the mean and STD of the <em>underlying normal distribution</em>, that is...
python|numpy|statistics|mean|standard-deviation
7
366,935
51,737,175
insert multiple rows at a matching value
<p>Using Pandas, I want to insert multiple rows for a given matching id <code>matchid</code>.</p> <p>Meaning, I currently string together a list of results and insert at a given row in an existing DF:</p> <pre><code>matchid | events_categories ----------------------------- 0 event_a, event_b, event_c 1 ...
<p>This is unnest</p> <pre><code>s=df['events_categories'].str.split(',') pd.DataFrame({'matchid':df['matchid'].repeat(s.str.len()),'events_categories':np.concatenate(s.values)}) Out[517]: events_categories matchid 0 event_a 0 0 event_b 0 0 event_c 0 1 e...
python|pandas
1
366,936
51,777,688
How to use weekday_name function for day/month/year format of datetime
<p>I am trying to use Weekday function inside pandas to classify the actual dates with name of the day of the week but its not working. The format of my dates is <code>day/month/year</code>.</p> <pre><code>**My code** data['date/time'] = pd.to_datetime(data['Actual Pickup date/time']) data['Day_of_Week_AP'] =data['da...
<p>Adding the <code>dayfirst</code></p> <pre><code>df['date/time'] = pd.to_datetime(df['Actual Pickup date/time'],dayfirst=True) df['date/time'].dt.weekday_name Out[814]: 0 Tuesday 1 Tuesday 2 Tuesday 3 Tuesday 4 Tuesday 5 Tuesday 6 Tuesday 7 Tuesday Name: date/time, dtype: object </code></pre...
python|python-3.x|pandas|weekday
3
366,937
51,832,453
Stack part of dataframe and then merge it into original dataframe in pandas
<p>I'm having trouble with using the <code>stack()</code> function on a section of a dataframe in pandas and then merging that stacked data back into the original dataframe.</p> <p>To explain more understandably through an example, suppose I have the following df:</p> <pre><code>&gt;&gt;&gt;df date name favo...
<p>IIUC <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.wide_to_long.html" rel="nofollow noreferrer">wide_to_long</a></p> <pre><code>pd.wide_to_long(df,'day',i=['date','name','favorite_color'],j='days',sep='_').\ rename(columns={'day':'value'}).\ reset_index() Out[1002]: ...
python|pandas|dataframe
1
366,938
51,795,156
Deleting Rows (Data Wrangling) in Python with csv and/or pandas modules
<p>I have a set of csv files I am trying to clean up before placing them in a database. These files are tab delineated, and come in two formats. One format looks like this:</p> <pre><code>Some text string Field1\tField2\tField3\tField4 </code></pre> <p><code>Some text string</code> always starts with the same sequen...
<p>Since you are simply matching a line of text, there is no benefit to using Pandas for this (in fact it will probably be slower and more difficult). But you can open each file just once if you're careful:</p> <pre><code>for csvFile in csvFiles: with open(csvFile) as f: line = f.readline() if lin...
python|python-3.x|pandas|csv
0
366,939
51,567,414
Trouble with plotly charts
<p>I am giving myself an intro to plotting data and have come across some trouble. I am working on a line chart that I plan on making animated as soon as I figure out this problem. I want a graph that looks like this: <a href="https://i.stack.imgur.com/LaDZx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgu...
<p>It looks like you have to sort the values first based on the date. Now it's connecting a value in the year 1997 with a value in 1994.</p> <pre><code>df_pre_2003.sort_values(by = ['year']) </code></pre>
pandas|plot|data-visualization|plotly
1
366,940
51,862,682
Pandas Assign Same Number of Random Values
<p>I have a dataframe of tasks that I need to randomly assign to workers. Each task should receive one random worker, and each worker should have the same number of tasks as the other workers. </p> <pre><code>import pandas as pd import numpy as np tasks = ['Task 1','Task 2','Task 3','Task 4','Task 5','Task 6','Task 7...
<p>Using <code>shuffle</code></p> <pre><code>a=np.array([1,2,3]*3) np.random.shuffle(a) a Out[230]: array([1, 3, 3, 2, 1, 2, 3, 1, 2]) df['New']=a df Out[232]: Tasks New 0 Task 1 1 1 Task 2 3 2 Task 3 3 3 Task 4 2 4 Task 5 1 5 Task 6 2 6 Task 7 3 7 Task 8 1 8 Task 9 2 </code><...
python|pandas|numpy|dataframe
2
366,941
51,612,489
tensorflow tf.edit_distance explanation required?
<p>How does tensorflow <code>tf.edit_distance</code> function works? How it compares string stored in two different sparse matrix equivalent of 2d or 3d dense matrix. </p> <p>Example given on tensorflow web page <a href="https://www.tensorflow.org/api_docs/python/tf/edit_distance" rel="nofollow noreferrer">https://www...
<p>hypothesis in dense form looks like this</p> <pre><code>[[['a']], [['b']]] # (2, 1, 1) </code></pre> <p>truth is this</p> <pre><code>[[[],['a']], [['b', 'c'], ['a']]] # (2, 2, 2) </code></pre> <p>We are trying to find the <a href="https://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Le...
python|tensorflow
1
366,942
51,972,496
How to run a tensorflow program on an EC2 instance while staying in the free tier
<p>I've attempted to setup an EC2 instance so I can run my <code>Tensorflow</code> script. However, I've noticed that I cannot setup the instance with a storage space of <code>&lt; 75</code> <code>GiB</code>.</p> <p>This is the error message I get...</p> <blockquote> <p>Launch Failed</p> <p>Volume of size 30GB is small...
<p>AWS Snapshots cannot be restored to an EBS volume smaller then the snapshot. You can restore to a larger EBS volume.</p> <p>Your option is to use a standard Linux AMI such as Amazon Linux 2, Ubuntu, etc. and then install Tensorflow yourself. If you are learning Tensorflow, I recommend going thru the process of inst...
amazon-web-services|tensorflow|amazon-ec2
0
366,943
51,936,227
Pandas - unify dataframe horizontally turning the rows into columns
<p>I have two data frames which I want to combine in a horizontal way. I'll explain myself:</p> <p>DataFrame A:</p> <pre><code> Name Total Score Charles 67 Peter 98 Mark 78 </code></pre> <p>DataFrame B:</p> <pre><code>Name Category Score Charles Category A ...
<p><code>merge</code> df on the <code>pivot</code>ted df2:</p> <pre><code>df.merge(df2.pivot('Name', 'Category', 'Score'), left_on='Name', right_index=True) Name Total Score Category A Category B 0 Charles 67 4 9 1 Peter 98 3 1 2 Mark ...
python|pandas|dataframe
4
366,944
51,944,004
How to find output_node_name to build frozen graph?
<p>I am referring <a href="https://github.com/dennybritz/cnn-text-classification-tf" rel="nofollow noreferrer">https://github.com/dennybritz/cnn-text-classification-tf</a> as a reference. My goal is to build frozen graph from model files. I want to know input and output node in the signature to effectively build the ...
<p>I recommend to use Tensorboard to visualize graph structure instead of using text file with nodes. You can find more details <a href="https://stackoverflow.com/a/43493222/3086290">here</a>.</p> <p>However the graph itself doesn't have notion of inputs or outputs. You can treat nodes without input connections as goo...
python-3.x|tensorflow|machine-learning|deep-learning
2
366,945
51,897,708
Convert pandas dataframe to tuple of tuples
<p>I have the following pandas <strong>dataframe</strong> df:</p> <pre><code> Description Code 0 Apples 014 1 Oranges 015 2 Bananas 017 3 Grapes 021 </code></pre> <p>I need to convert it to a tuple of tuples, like this:</p> <pre><code>my_fruits = ( ('Apples', '014'), ...
<p>Would something like this work?</p> <pre><code>tuple(df.itertuples(index=False, name=None)) </code></pre>
python|pandas|dataframe|tuples
11
366,946
51,684,952
How to get tf.gradients from keras API model?
<p>I would like to know how to get <code>tf.gradients</code> from a model built using the Keras API.</p> <pre><code>import Tensorflow as tf from tensorflow import keras from sklearn.datasets.samples_generator import make_blobs # Create the model inputs = keras.Input(shape=(2,)) x = keras.layers.Dense(12, activation=...
<p>I think you shouldn't create a new session directly with Tensorflow when using Keras. Instead, it is better to use the session implicitly created by Keras:</p> <pre><code>import keras.backend as K sess = K.get_session() </code></pre> <p>However, I think in this case you don't need to retrieve the session at all. ...
python|tensorflow|neural-network|keras|deep-learning
0
366,947
51,763,717
How to manage the special character \r in pandas dataframes
<p>How comes the symbol <code>\r</code> makes pandas bug when reading a csv file? </p> <p>Example:</p> <pre><code>test = pd.DataFrame(columns = ['id','text']) test.id = [1,2,3] test.text = ['Foo\rBar','Bar\rFoo','Foo\r\r\nBar'] test.to_csv('temp.csv',index = False) test2 = pd.read_csv('temp.csv') </code></pre> <p>Th...
<p>In order to have valid csv data all fields containing a newline should be enclosed in double quotes.</p> <p>The generated csv should look like this:</p> <pre><code>id text 1 "Foo\rBar" 2 "Bar\rFoo" 3 "Foo\r\r\nBar" </code></pre> <p>or:</p> <pre><code>id text 1 "Foo Bar" 2 "Bar Foo" 3 "Foo Bar" </...
python|pandas|csv|character-encoding|pickle
1
366,948
51,643,678
New to Keras, massive amounts of memory Conv2D
<p>My understanding from a convolution neural network is it is a set of smaller filters that applies over an image.</p> <p>So a Conv2D like in the simple model below</p> <pre><code>model = Sequential() model.add(Conv2D(128,(3,3),activation='relu',input_shape=(101,101,1))) model.add(MaxPooling2D(pool_size=(2,2))) mode...
<p>This is awfully big:</p> <pre><code>model.add(Flatten()) #shape: (batch, 128*50*50) model.add(Dense(101*101,activation='sigmoid')) #parameters: 128*50*50*101*101 + 101*101 = 3264330201 </code></pre> <p>THREE BILLION parameters. (Check your <code>model.summary()</code> to confirm)</p> <p>You're applying a dense l...
python|tensorflow|keras
2
366,949
51,907,888
python making bitmap data from 2d array
<p>I have a device that accepts bitmap binary data. I would like to convert a numpy 2d array to bitmap and send it to this device. Currently what I do is to save the 2d array to a bitmap file, then read it into a variable and send that to the device. I'd like to skip the writing to the disk step. Is there an easy way t...
<p>You can use <a href="https://docs.python.org/2/library/io.html#io.BytesIO" rel="nofollow noreferrer">io.BytesIO</a> as a memory buffer to store the bitmap and send it without writing to disk.</p> <p>As an example, assuming you use PIL or Pillow to save your bitmap file :</p> <pre><code>import io from PIL import Im...
python|arrays|numpy|bitmap|bmp
1
366,950
51,723,928
Splitting groupby() in pandas into smaller groups and combining them
<pre><code> city temperature windspeed event day 2017-01-01 new york 32 6 Rain 2017-01-02 new york 36 7 Sunny 2017-01-03 new york 28 12 Snow ...
<p>You can create a helper column via <code>GroupBy</code> + <code>cumcount</code> to count the occurrence of each city.</p> <p>Then use <code>dict</code> + <code>tuple</code> with another <code>GroupBy</code> to create a dictionary of dataframes, each one containing exactly one occurence of each city.</p> <pre><code...
python|python-2.7|pandas|grouping|pandas-groupby
2
366,951
51,959,329
Getting TypeError when trying to retrieve values from keys in a list of dictionaries
<p>I have an array of dictionaries in a pandas DataFrame: </p> <pre><code> 0 [{'id': 16, 'name': 'Animation'}, {'id': 35, 'name': 'Comedy'}, {'id': 10751, 'name': 'Family'}] 1 [{'id': 12, 'name': 'Adventure'...
<p>Iterating over a data-frame iterates over the <em>names</em> of the columns, `:</p> <pre><code>In [15]: df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]}) In [16]: df Out[16]: a b 0 1 4 1 2 5 2 3 6 In [17]: for x in df: ...: print(x) ...: a b </code></pre> <p>It is like a <code>dict</code> that ...
python|string|list|pandas|dictionary
0
366,952
51,943,872
3D Tensor in a correct data shape for neural network
<p>I'm starting with Neural Networks and I'm having some issues with my data format. I have a <code>pandas</code> <code>DataFrame</code> with <code>130</code> rows, <code>4</code> columns and each data point is an array of <code>595</code> items.</p> <pre><code> | Col 1 | Col 2 | Col 3 ...
<p>You have to reshape your data to a 3d numpy array.</p> <p>Suppose we have a data frame where each cell is a numpy array as you described</p> <pre><code>import pandas as pd import numpy as np data=pd.DataFrame(np.zeros((130,4))).astype('object') for i in range(130): for k in range(4): #print(i,k) ...
pandas|dataframe|neural-network|keras|jupyter-notebook
1
366,953
51,676,880
Rolling mean using groupby of two columns with window size of variable length in
<p>I want to calculate the rolling mean of modal_price grouped by (APMC,Commodity) for each year with window_length as no. of months of that year . According to my solution I'm getting all Nan's . The dataset is as follows :</p> <pre><code> APMC | Commodity | qtl _weight| min_price | max_price | modal_...
<p>I think you want to form groups for each year x APMC x Commodity and then use <code>.expanding().mean()</code> to calculate the rolling mean for each group. Since your data appears to be monthly, this will be a rolling mean every month.</p> <h2>Sample Data</h2> <pre><code>import pandas as pd import numpy as np np...
python|pandas|group-by
0
366,954
51,838,355
Applying interpolation on DataFrame based on another DataFrame
<p>I have a <code>DataFrame</code> on which I would like to somehow add new columns based on the value of a specific column, whose result depends on data contained in <em>another</em> <code>DataFrame</code>.</p> <p>More specifically, I have</p> <pre><code>df_original = Crncy Spread Duration 0 EUR 100 ...
<p>Suppose we have <code>df1</code> and <code>df2</code> </p> <pre><code>&gt;&gt;&gt; df1 Crncy Spread Duration 0 EUR 100 1.2 1 CHF 200 2.5 &gt;&gt;&gt; df2 CRNCY TENOR Adj_EUR Adj_USD 0 EUR 1 10 20 1 EUR 2 20 30 2 EUR 5 30 ...
python|pandas
1
366,955
51,849,237
Get if there's been a record in the last week
<p>I need to calculate if a customer is recurrent or not. Recurrent clients are defined if it has an activity in the past week.</p> <p>I have a table like this:</p> <pre><code>DATE | Document | CUSTOMER 2018-08-14 | 12038120 | A </code></pre> <p>So far I am able to only get a count of activities per customer p...
<p>Use the datetime module.</p> <pre><code>#convert string to datetime object datetime_object = datetime.datetime.strptime("2018-08-14", '%Y-%m-%d') # check if now is within 7 days of the above string if datetime.datetime.now()-datetime_object&lt;datetime.timedelta(days=7): print True </code></pre>
python|pandas|numpy
1
366,956
51,617,008
Using numpy.arange to create a list of floats with given precision
<p>My aim is to generate a list <code>ls</code> of numbers which starts from <code>1.0</code> and ends at <code>1.499</code> where the step between subsequent numbers is <code>0.001.</code></p> <p>Ultimately, I am loading a file that has a column of float numbers, e.g., <code>1.293, 1.101, ...</code> all with 3 numbers...
<p>Floating point numbers are not exact real numbers, only the closest numbers that can fit in a 52-bit binary fraction. </p> <p>For example, you can't fit <code>1.001</code> in a binary fraction; the nearest value is <code>1.000999999999999889865875957184471189976</code>. If you add <code>0.001</code> to that, the ne...
python|numpy
2
366,957
51,895,745
not able to convert string to float in python and how to train the model with this dataset
<p>I have a dataset with columns: age (float type), gender (str type), regions (str type) and charges(float type). </p> <p>I want to predict charges using age gender and region as features, how can I do that in scikit learn?</p> <p>I have tried something but it shows <code>"ValueError: could not convert string to flo...
<p>The column <code>region</code> contains strings, which can't be used as such in the SVM classifier as it is not a vector.</p> <p>Threfore you have to turn this column into something that is usable by the SVM. Here is an example by changing <code>region</code> into a categorical series:</p> <pre><code>import pandas...
pandas|machine-learning|scikit-learn
2
366,958
51,635,734
How to read and take average of multiple table files in pandas?
<p>So that's how two tables look like</p> <pre><code>5113.440 1 0.25846 0.10166 27.96867 0.94852 -0.25846 268.29305 5113.434129 5074.760 3 0.68155 0.16566 120.18771 3.02654 -0.68155 101.02457 5074.745627 5083.340 2 0.74771 0.13267 105.59355 2.15700 -0....
<p>Concatenate all of the files into a single <code>DataFrame</code> and then use the <code>wave</code> value to group and calculate the mean. </p> <pre><code>import os import pandas as pd path_to_files = 'something' lst = [] for filen in [x for x in os.listdir(path_to_files) if '.ares' in x]: lst.append(pd.read_...
python|pandas
3
366,959
51,940,600
Tensorflow Simple Audio Recognition Error on Freeze.py
<p>I've been following <a href="https://www.tensorflow.org/tutorials/sequences/audio_recognition" rel="nofollow noreferrer">the tutorials</a> on how to make a Simple Audio Recognition.</p> <p>First I encountered an error when I entered</p> <pre><code>python tensorflow/examples/speech_commands/freeze.py </code></pre> ...
<p>Its working, all i had to do was to run the command line in the TensorFlow source like <a href="https://i.stack.imgur.com/yXtHl.jpg" rel="nofollow noreferrer">this</a></p>
python|python-3.x|tensorflow|audio|speech-recognition
0
366,960
51,654,821
getting item with max frequency from multiple columns in a dataframe
<p>I have a dataframe like this:</p> <pre><code>a1 a2 a3 a4 4 4 4 4 4 4 4 4 2 3 2 3 2 3 3 3 2 2 2 2 2 2 2 2 </code></pre> <p>Desired output:</p> <pre><code>a1 a2 a3 a4 max_freq 4 4 4 4 4 4 4 4 4 4 2 3 2 3 3 2 3 3 3 3 2 2 2 2 2 2 2 ...
<p>If you're concerned about speed, and don't care about the restraint on <code>a4</code> as you mentioned in the comments, you can use <strong><code>scipy.stats.mode</code></strong>:</p> <pre><code>df['freq'] = scipy.stats.mode(df.values, 1)[0] a1 a2 a3 a4 freq 0 4 4 4 4 4 1 4 4 4 4 4 ...
python|pandas|function|multiple-columns|frequency
3
366,961
51,827,333
Commit error after uploading data
<p>i have a simple program that stores some inputs in a database. I use flask-sqlalchemy as a ORM and didn't have any issues until now. Due some issues, i had to save my data onto CSV files and erase everything. After that, i uploaded the data back again using the <code>df.to_sql</code> method from <code>pandas</code>...
<p>Thanks to the comments from @mad_ I was able to solve my problem. The issue presented when I uploaded a table back to my database. When I tried to commit a new observation to the DB I got an error.</p> <p>A workaround is to explicitly declare the <code>primary key</code>. With this I got a new error which was solve...
python-3.x|pandas|flask|flask-sqlalchemy
0
366,962
51,573,410
How to iterate through dataframe based on timer?
<p>I have a dataframe that looks like this: </p> <pre><code>id text number url 1 test1 123 a.com 2 test2 456 b.com </code></pre> <p>Once per day I want to iterate through only one row of a dataframe into an api. Example on 7/28, send number <code>123</code> text <code>test1</code>. On 7/29 ...
<pre><code>import time for index, row in df.iterrows(): data = { 'phone': row.number, 'message':row.text, 'url':row.URL, } r = requests.post(URL,headers=headers,params=data) print(r.text) time.sleep(86400) </code></pre>
python|pandas|iterator|api-design
0
366,963
36,034,725
Generate samples from a random matrix
<p>Assume we have a random matrix A of size n*m. Each elements A_ij is the success probability of a Bernoulli distribution. </p> <p>I want to draw a sample z from A with the following rule:</p> <p>z_ij draw from Bernoulli(A_ij)</p> <p>Is there any numpy function support this?</p> <p>EDIT: operations such as</p> <p...
<p>You can directly give an array as one of the arguments of your binomial distribution, for example:</p> <pre><code>import numpy as np arr = np.random.random([10, 5]) sp = np.random.binomial(1, arr) sp </code></pre> <p>gives</p> <pre> array([[0, 0, 0, 0, 0], [1, 0, 0, 1, 1], [1, 0, 1, 0, 0], [0...
python|numpy|random
3
366,964
35,960,574
Numpy matrices - how to handle arbitrary size
<p>I have some code which carries out various processing functions on a matrix of input data. The input data may be 2, 3 or 4D.</p> <p>I need to remove n-1 dimensional matrices from the input data for processing and then another matrix receives this processed data. What is the best way to do this, in order to handle t...
<p>These are functionally the same:</p> <pre><code>output_matrix[i,:,:,:] output_matrix[i,...] output_matrix[i] </code></pre> <p>or more generally:</p> <pre><code>x[:,i,j,:,:] x[:,i,j,...] x[:,i,j] </code></pre> <p>As long as it is clear where dimensions are being indexed, trailing `:' can be omitted, or replaced w...
python|arrays|numpy|matrix
1
366,965
36,042,508
OpenCV putText in Python - Error after array manipulation
<p><strong>SHORT</strong></p> <p>I want to write text into an image. I am, however, unable to understand the following behavior:</p> <pre><code>import numpy as np import cv2 # create an image img = np.ones((512,512,3), dtype = np.uint8) # create an image container (I have to do this as I cycle through many folder and...
<p>Changing the following line solves the problem</p> <pre><code>img_from_container = img_container[:,:,:,0].copy() </code></pre> <p><code>np.copy()</code> makes it clear to make another copy of the data, then opencv is able to write to that array. The previous code gets a view from a higher dimensional numpy array, ...
python|opencv|numpy
3
366,966
35,890,051
How does a static member in a TensorFlow OpKernel behave?
<p>Specifically, if I have an Op inheriting from OpKernel, and inside this I have some private member declared <code>static</code>. Am I safe to assume that all instantiations of this kernel will access the same static member? Are all kernels placed on the same machine/worker (possibly different CPUs) in the same addre...
<p>A <code>static</code> member of a <code>tensorflow::OpKernel</code> is shared between all instances of that kernel in the same process. If you are running a single TensorFlow process, then all instances (including instances assigned to CPU or GPU, and instances from different sessions) will share the same <code>stat...
tensorflow
3
366,967
35,972,066
Frequency of unique values in different columns in pandas
<p>I have a pandas data frame like this:</p> <pre><code>Index arrival_1 arrival_2 arrival_3 1 elephant lion buffalo 2 buffalo antelope hippo 3 lion buffalo antelope 4 hippo lion antelope 5 elephant buffalo lion 6 buffalo ...
<p>Try below.</p> <pre><code>df.stack().value_counts() </code></pre>
python|pandas
5
366,968
36,101,873
The right way to query a pandas MultiIndex
<p>I've got a huge dataframe (13 million rows) which stocks and stock prices in. I've indexed them using <code>MultiIndex(['stock', 'date'])</code>, where <code>date</code> has been parsed as a <code>DateTime</code>.</p> <p>This means I can select price data based upon stock easily <code>df.loc['AAPL']</code>, and by ...
<p>I think what you did is fine, but there are alternative ways also.</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({ 'stock':np.repeat( ['AAPL','GOOG','YHOO'], 3 ), 'date':np.tile( pd.date_range('5/5/2015', periods=3, freq='D'), 3 ), 'price':(np.random.randn(9).cumsum() + 10...
pandas
6
366,969
35,969,916
Replace header in a csv file python with pandas
<p>I'm trying to replace header string of my <code>csv</code> file with pandas libraries, but i can't understand how can I do this.</p> <p>I try to see <code>DataFrame</code> but i don't see anything to do this. anyone can help me? thanks</p>
<p>From a glance at the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow">docs</a>, it looks like it would be something like</p> <pre><code>df = pandas.Dataframe.read_csv(filename, ...) new_header = ['new', 'column', 'names'] df.to_csv(new_filename, header=new...
python|csv|pandas
1
366,970
35,866,067
Fastest way to get union of lists - Python
<p>There's a C++ comparison to get union of lists from lists of lists: <a href="https://stackoverflow.com/questions/11362002/the-fastest-way-to-find-union-of-sets">The fastest way to find union of sets</a></p> <p>And there's several other python related questions but none suggest the fastest way to unionize the lists:...
<p>What's fastest depends on the nature of <code>x</code> -- whether it is a long list or a short list, with many sublists or few sublists, whether the sublists are long or short, and whether there are many duplicates or few duplicates.</p> <p>Here are some timeit results comparing some alternatives. There are so many...
python|list|numpy|set|union
7
366,971
35,955,144
Working with multiple graphs in TensorFlow
<p>Can someone explain to me how <code>name_scope</code> works in TensorFlow? </p> <p>Suppose I have the following code:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf g1 = tf.Graph() with g1.as_default() as g: with g.name_scope( "g1" ) as scope: matrix1 = tf.constant([[3., ...
<p>Your <code>product</code> is a global variable, and you've set it to point to "g2/MatMul".</p> <p>In particular</p> <p>Try</p> <pre><code>print product </code></pre> <p>and you'll see</p> <pre><code>Tensor("g2/MatMul:0", shape=(1, 1), dtype=float32) </code></pre> <p>So the system takes <code>"g2/MatMul:0"</cod...
tensorflow
17
366,972
36,192,074
Manual Histogram plot in python
<p>I'm using matplotlib to make a histogram.</p> <p>Basically, I'm wondering if there is any way to manually set the bins as well as the their values and still get the result as if the graph is made my matplotlin histogram. Below are my bins and their corresponding value.</p> <pre><code>0-7 0.9375 7-13 0.94907...
<p>From the documentation linked by @roadrunner66,</p> <blockquote> <p><code>matplotlib.pyplot.bar(left, height, width=0.8, bottom=None, hold=None, data=None, **kwargs)</code></p> <p>Make a bar plot with rectangles bounded by:</p> <p><code>left</code>, <code>left + width</code>, <code>bottom</code>, <code>bottom + heig...
python|numpy|pandas|matplotlib|histogram
5
366,973
35,846,555
what is a better way to check if two complex numbers are identical in python?
<p>While testing mpi4py's <code>comm.reduce()</code> and <code>comm.Reduce()</code> methods in python 2.7.3 I encountered the following behaviour:</p> <ul> <li><p>sometimes subtracting two complex numbers (type 'numpy.complex128', which are the output of some parallel calculation) that appear identical when printed on...
<p><code>float</code> values derived in a way that produces the same logical result won't always have the same representation in binary, because <code>float</code> is not infinite precision, and there are limitations to its representation. The same logically equivalent steps in different orders will sometimes have prec...
python|python-2.7|numpy
1
366,974
36,186,980
Using Pandas in Python to Join Multiple Files Based on Date
<p>I have csv files that I need to join together based upon date but the dates in each file are not the same (i.e. some files start on 1/1/1991 and other in 1998). I have a basic start to the code (see below) but I am not sure where to go from here. Any tips are appreciated. Below please find a sample of the differe...
<p>You didn't read the csv files correctly.</p> <p>1) You need to comment out the following lines because you never use it later in your code.</p> <pre><code> files = os.listdir(directory) print(files) </code></pre> <p>2) <code>glob.glob(directory)</code> didnt return any match files. glob.glob() takes <strong...
python|date|csv|join|pandas
1
366,975
36,177,339
delete values that repeat more than 3 times except for first one in Pandas DataFrame
<p>I have a pandas DataFrame.For example,</p> <pre><code> Date Time A B C 0 1.1.2015 00:00 2 16 50 1 1.1.2015 01:00 2 9 50 2 1.1.2015 02:00 4 6 50 3 1.1.2015 03:00 3 7 31 4 1.1.2015 04:00 2 7 42 5 1.1.2015 05:00 2 7 22 ...
<p>You can do, with <code>itertools</code> help:</p> <pre><code>import itertools import numpy as np def f(serie): xs = [] for el, gr in itertools.groupby(serie): x = np.repeat(True, len(list(gr))) if len(x)&gt;=3: x[1:]=False xs.append(x) return np.concatenate(xs) df[df...
python|pandas
1
366,976
35,850,582
Can Pandas DataFrame efficiently calculate PMI (Pointwise Mutual Information)?
<p>I've looked around and surprisingly haven't found an easy use of framework or existing code for the calculation of Pointwise Mutual Information (<a href="https://en.wikipedia.org/wiki/Pointwise_mutual_information" rel="nofollow">Wiki PMI</a>) despite libraries like Scikit-learn offering a metric for overall Mutual I...
<p>I would add three bits.</p> <pre><code>def pmi(dff, x, y): df = dff.copy() df['f_x'] = df.groupby(x)[x].transform('count') df['f_y'] = df.groupby(y)[y].transform('count') df['f_xy'] = df.groupby([x, y])[x].transform('count') df['pmi'] = np.log(len(df.index) * df['f_xy'] / (df['f_x'] * df['f_y'])...
python|pandas|dataframe|entropy
10
366,977
35,990,721
Pandas: Group by with MultiColumn
<p>I have a data frame with multiColumns. It is quite large, so here is some information:</p> <pre><code>In [73]: test.shape Out[73]: (83, 82573) </code></pre> <p>Here's the first rows/columns</p> <pre><code>first senator words \ second ...
<p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p> <pre><code>df2 = df.groupby(df.index).sum() #remove first level of multiindex in columns df2.columns = df2.columns.droplevel(0) print df2 second 000003198s 000s...
python|pandas
2
366,978
37,593,275
multi-GPU tower; ValueError: None values not supported
<p>I've tried to use multi-GPU tower defs from cifar10_train_multiGPU.py to LeNet with MNIST data in jupyter-notebook environments.</p> <p>-but, I don't use movingaveragedecay for losses and variables</p> <p>But, implementing those defs occurs errors and I don't know why. Please, help me to understand and ,if you hav...
<p>From your output, it looks like each tower is creating a new set of variables:</p> <pre><code>[(, ), (, ), (, ), (, ), (, ), (, ), (, ), (, )] [(None, ), (None, ), (None, ), (None, ), (None, ), (None, ), (None, ), (None, ), (, ), (, ), (, ), (, ), (, ), (, ), (, ), (, )] </code></pre> <p>Note that there are twice ...
tensorflow
2
366,979
37,282,988
Pandas create random samples without duplicates
<p>I have a pandas dataframe containing ~200,000 rows and I would like to create 5 random samples of 1000 rows each however I do not want any of these samples to contain the same row twice.</p> <p>To create a random sample I have been using:</p> <pre><code>import numpy as np rows = np.random.choice(df.index.values, 1...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="noreferrer"><code>df.sample</code></a>.</p> <p>A dataframe with 100 rows and 5 columns:</p> <pre><code>df = pd.DataFrame(np.random.randn(100, 5), columns = list("abcde")) </code></pre> <p>Sample 5 rows:<...
python|pandas
7
366,980
37,425,628
Combine multiple columns into 1 column [python,pandas]
<p>I have a pandas data frame with 2 columns: <code>{'A':[1, 2, 3],'B':[4, 5, 6]}</code></p> <p>I want to create a new column where: <code>{'C':[1 4,2 5,3 6]}</code></p>
<h3>Setup</h3> <pre><code>df = pd.DataFrame({'A':[1, 2, 3],'B':[4, 5, 6]}) </code></pre> <h3>Solution</h3> <p>Keep in mind, per your expected output, <code>[1 4,2 5,3 6]</code> isn't a thing. I'm interpreting you to mean either <code>[(1, 4), (2, 5), (3, 6)]</code> or <code>["1 4", "2 5", "3 6"]</code></p> <h3>Fir...
python|pandas
2
366,981
37,259,417
Add number to column each time a different column has group of True bools
<p>I have two columns I am working with. The first column is populated with zeros and the second column is populated with booleans. </p> <pre><code>column 1 column 2 0 True 0 True 0 False 0 True 0 True 0 Fal...
<p>One trick which often comes in handy when vectorizing operations on contiguous groups is the shift-cumsum pattern:</p> <pre><code>&gt;&gt;&gt; c = df["column 2"] &gt;&gt;&gt; c * (c &amp; (c != c.shift())).cumsum() 0 1 1 1 2 0 3 2 4 2 5 0 6 0 7 3 Name: column 2, dtype: int32 </code></pre>
python|pandas
4
366,982
37,198,847
Pandas: Splitting a Row Into Multiple Rows Efficiently
<p>The problem I am currently facing is taking a pandas DataFrame and efficiently taking each record and breaking it down into multiple records in the following way:</p> <p>Input:</p> <pre><code>In [16]: pd.DataFrame({'Name': 'Person1', 'State': 'Indiana', 'Money1': 100.42, 'Money2':54.54, 'Money3': 23.45}, index=[1]...
<p>This should work for a dataframe with an arbitrary number of columns.</p> <pre><code>df = pd.DataFrame({'Name': ['Person1', 'Person2'], 'State': ['Indiana', 'NY'], 'Money1': [100.42, 200], 'Money2': [54.54, 25], 'Money3': [23.45, 10]}) ...
python|numpy|pandas
2
366,983
37,203,156
Finding intersection of values in a column associated with unique values in another column Pandas
<p>If I have a DataFrame like this <em>(very minimal example)</em></p> <pre><code> col1 col2 0 a 1 1 a 2 2 b 1 3 b 2 4 b 4 5 c 1 6 c 2 7 c 3 </code></pre> <p>and I want the intersection of all <code>col2</code> values when they are related to their unique <cod...
<p>One way is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p> <pre><code>In [11]: cross = df.pivot_table(index="col1", columns="col2", aggfunc='size') == 1 In [12]: cross Out[12]: col2 1 2 3 4 col1 a ...
python|pandas
2
366,984
37,259,200
Merge 2 dataframes using <> condition
<p>I have two <code>DataFrame</code> objects: </p> <ul> <li><code>df1</code>: <code>columns = [a, b, c]</code> </li> <li><code>df2</code>: <code>columns = [d, e]</code></li> </ul> <p>I want to merge <code>df1</code> with <code>df2</code> using the equivalent of <code>sql</code> in <code>pandas</code>:</p> <pre><cod...
<p>The following sequence of steps should get you there:</p> <pre><code>df1 = df[df1.c==0] merged = df1.merge(df2, left_on='b', right_on='e') merge = merged[merged.b != merged.d] </code></pre>
python|pandas|dataframe|merge
1
366,985
37,179,218
getting word from id at Tensorflow RNN sample
<p>I'm trying to modify Tensorflow's RNN sample here.</p> <p><a href="https://www.tensorflow.org/versions/r0.8/tutorials/recurrent/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.8/tutorials/recurrent/index.html</a></p> <p>At ptb_word_lm.py I guess they are inputting int array of word index (m.input...
<p>You need to retain vocabulary ( which is an index from word to id ) first.</p> <p>At the top of main, retain 4th returned value from reader.ptb_raw_data() like below.</p> <pre><code>raw_data = reader.ptb_raw_data(FLAGS.data_path) train_data, valid_data, test_data, vocabulary = raw_data </code></pre> <p>Then pass ...
python|tensorflow
1
366,986
37,518,901
Python pandas - merging a table with itself
<p>I have a dataframe that looks conceptually like this:</p> <pre><code>ID SUM Stime Etime 3 10.0 18:00:00 18:09:59 2 12.0 18:15:00 18:26:59 3 3.0 18:36:00 18:38:59 4 3.0 18:36:00 18:38:59 5 59.0 18:00:00 18:58:59 12 10.0 17:00:00 17:09:59 12 16.0 18:24:00 18:39:59 7 16.0 18:24:00 1...
<pre><code>d = {'ID' : [1, 2, 3,12, 4,12,5,12],'SUM' : [4, 3, 2, 16,1,19,2,11]} df =pd.DataFrame(d) &gt;&gt;&gt; df ID SUM 0 1 4 1 2 3 2 3 2 3 12 16 4 4 1 5 12 19 6 5 2 7 12 11 df.groupby(['ID']).sum() SUM ID 1 4 2 3 3 2 4 1 5 2 12 46 </code></p...
python|pandas
0
366,987
37,266,574
Splitting Pandas Dataframe with groupby and last
<p>I am working with a pandas dataframe where i want to group by one column, grab the last row of each group (creating a new dataframe), and then drop those rows from the original. </p> <p>I've done a lot of reading and testing, and it seems that I can't do that as easily as I'd hoped. I can do a kludgy solution, but ...
<p>If you use <code>.reset_index()</code> first, you'll get the index as a column and you can use <code>.last()</code> on that to get the indices you want.</p> <pre><code>last_lines = df.reset_index().groupby('A').index.last() df.drop(last_lines) </code></pre> <p>Here the index is accessed as <code>.index</code> beca...
python|pandas|dataframe|group-by
2
366,988
37,513,355
Converting Pandas dataframe into Spark dataframe error
<p>I'm trying to convert Pandas DF into Spark one. DF head:</p> <pre><code>10000001,1,0,1,12:35,OK,10002,1,0,9,f,NA,24,24,0,3,9,0,0,1,1,0,0,4,543 10000001,2,0,1,12:36,OK,10002,1,0,9,f,NA,24,24,0,3,9,2,1,1,3,1,3,2,611 10000002,1,0,4,12:19,PA,10003,1,1,7,f,NA,74,74,0,2,15,2,0,2,3,1,2,2,691 </code></pre> <p>Code:</p> <...
<p>I made this script, It worked for my 10 pandas Data frames</p> <pre><code>from pyspark.sql.types import * # Auxiliar functions def equivalent_type(f): if f == 'datetime64[ns]': return TimestampType() elif f == 'int64': return LongType() elif f == 'int32': return IntegerType() elif f == 'float64': re...
python|pandas|apache-spark|spark-dataframe
85
366,989
41,691,081
Pandas use and operator in LOC function
<p>i want to have 2 conditions in the <code>loc</code> function but the <code>&amp;&amp;</code> or <code>and</code> operators dont seem to work.:</p> <p>df:</p> <pre><code>business_id ratings review_text xyz 2 'very bad' xyz 1 'passable' xyz 3 'okay' abc 2 ...
<p>You need <code>&amp;</code> for <code>and</code> logical operator, because need element-wise <code>and</code>, see <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer">boolean indexing</a>:</p> <pre><code>id = 'xyz' mylist=df.loc[(df['ratings'] &lt; 3) &amp; (df['bus...
python|pandas|operator-keyword
15
366,990
41,942,882
Make NA based on condition in Pandas DF
<p>I feel like this probably has a simple solution, I just can't figure it out.</p> <p>I have a Pandas DF similar to this MWE:</p> <pre><code>In [92]: test_df = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9], 'B':[9,8,7,6,5,4,3,2,1]}) In [93]: test_df Out[93]: A B 0 1 9 1 2 8 2 3 7 3 4 6 4 5 5 5 6 4 6 7 3...
<p>You can assign <code>NaN</code> using <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer">boolean indexing</a>:</p> <pre><code>In [25]: test_df[test_df &lt; 4] = np.nan In [26]: test_df Out[26]: A B 0 NaN 9.0 1 NaN 8.0 2 NaN 7.0 3 4.0 6.0 4...
python|pandas|nan
3
366,991
41,793,571
Pandas dataframe transformation: adding columns from dictionary k-v pairs
<p>I would like to transform a DataFrame looking like this:</p> <pre><code> dictionary 0 {'b': 2, 'a': 1} 1 {'c': 4, 'b': 3} </code></pre> <p>from</p> <pre><code>import pandas df = pandas.DataFrame() df['dictionary'] = [{'a':1,'b':2},{'b': 3,'c':4}] </code></pre> <p>onto a DataFrame looking like this:</p>...
<p>A vectorized approach by converting the given series to it's <code>list</code> representation and then performing concatenation column-wise: </p> <pre><code>pd.concat([df['dictionary'], pd.DataFrame(df['dictionary'].values.tolist())], axis=1) </code></pre> <p><a href="https://i.stack.imgur.com/Crvem.png" rel="nofo...
python|pandas
4
366,992
42,014,888
Find if rows in a large file contain a substring from a seperate list?
<p>I have a large (30GB) file consisting of random terms and sentences. I have two separate lists of words and phrases I want to apply to that and mark (or alternatively filter) a row in which a term for that list appears.</p> <p>If a term from list X appears in a row of the large file, mark it X, if from list Y, mark...
<p>If I understand correctly, you need to do the following:</p> <pre><code>fileContent = ['yes','foo','junk','yes','foo','junk'] x_list = ['yes','no','maybe-so'] y_list = ['foo','bar','fizzbuzz'] def x_or_y(keyword): if keyword in x_list: return 'X' if keyword in y_list: return 'Y' return '' results =...
python|pandas
0
366,993
42,078,259
Indexing a numpy array using a numpy array of slices
<p><strong>(Edit: I wrote a solution basing on hpaulj's answer, see code at the bottom of this post)</strong></p> <p>I wrote a function that subdivides an n-dimensional array into smaller ones such that each of the subdivisions has <code>max_chunk_size</code> elements in total.</p> <p>Since I need to subdivide many a...
<p>Your slices produce 2x6 and 2x3 arrays.</p> <pre><code>In [36]: subslice=slices[:2,1:3] In [37]: subslice[0,0] Out[37]: array([slice(0, 2, None), slice(6, 12, None)], dtype=object) In [38]: ar[tuple(subslice[0,0])] Out[38]: array([[ 6, 7, 8, 9, 10, 11], [21, 22, 23, 24, 25, 26]]) </code></pre> <p>My nu...
python|arrays|numpy|slice
3
366,994
42,121,596
Entropy of a MNIST image with Tensorflow
<p>I want to measure the entropy of an MNIST image. However most of the intensity values are 0, and <code>tf.log</code> returns <code>inf</code>. I know that I can simply calculate the entropy:</p> <pre><code>entropy = tf.reduce_mean(-tf.reduce_sum(X * tf.log(X), axis=1)) </code></pre> <p>where X is a placeholder the...
<p>Entropy depends on the <em>probability</em> of each intensity value, not on the value itself. A value with a probability of 0 doesn't enter into the calculations.</p> <p>Write code to compute the proportion of each intensity value that appears in the photo. <em>Those</em> form your X vector.</p> <hr> <p>I think...
python|tensorflow|entropy|mnist
2
366,995
41,866,745
Tensorflow shuffle_batch speed
<p>I noticed a big difference in speed if I load my training data into memory and feed it into the graph as a numpy array vs using a shuffle batch of the same size, my data has ~1000 instances. </p> <p>Using memory 1000 iterations takes less than a few seconds but using a shuffle batch it takes almost 10 minutes. I ge...
<p>In this case, you're running a session 3 times per step - once in <code>avgs_batch.eval</code>, once for <code>pdiff_batch.eval</code>, and once for the actual <code>sess.run</code> call. That doesn't explain the magnitude of the slow down, but it's definitely something you should keep in mind. At the very least the...
tensorflow
3
366,996
42,038,086
Pandas converting datetime to minutes
<p>I have a dataframe that looks like this:</p> <pre><code>import pandas as pd name = pd.Series(["A", "B", "C", "D", "E", "F"]) c1 = pd.Series(["0", "0", "01:56:00", "10:01:00", "120", "2 hours"]) c2 = pd.Series(["00:60:00", "0", "10", "12:00:00", "20 mins", "100"]) df = pd.DataFrame({"name": name, "time1": c1, "time...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow noreferrer"><code>mask</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>contains</code></a> and where <code>...
python|pandas|datetime|dataframe
0
366,997
41,689,670
Dropout in Tensorflow CNN network while using triplet based training
<p>I have implemented distance learning using triplets of data using a CNN in Tensorflow. For this I have a shared set of weights for each layer. I want to employ dropout technique to compensate for over-fitting. I was thinking of doing this in the following way:</p> <pre><code>h_fc1_drop = tf.nn.dropout(h_fc1, keep_...
<p>Assuming everything has the same shape, setting the same seed should make them all identical.</p> <p>In practice though data samples are minibatched, and <code>tf.nn.dropout</code> will drop out the same units in the entire minibatch, so switching to stacking your examples is probably a good idea here.</p>
machine-learning|tensorflow|neural-network|deep-learning
1
366,998
41,884,126
Can I overlay two stacked bar charts in plotly?
<p>Using pandas &amp; matplotlib I've created a handy graphic for our team to monitor revenue. For each of our customers it shows last month (light grey), best month (dark grey), and the forecast range for this month (green).</p> <p><a href="https://i.stack.imgur.com/QCkG2.png" rel="nofollow noreferrer"><img src="htt...
<p>The graph could use some tweaking but it's definitely doable with Plotly.</p> <ul> <li>Add <a href="https://plot.ly/python/horizontal-bar-charts/" rel="nofollow noreferrer"><code>orientation='h'</code></a> to both traces to make them <code>h</code>orizontal</li> <li>Add <a href="https://plot.ly/python/bar-charts/#s...
pandas|matplotlib|plotly
4
366,999
42,058,483
How to calculate a value inside a group after groupby pandas
<p>Suppose I have a pandas DataFrame:</p> <pre><code>a b c d .... z 1 10 3 . 1 20 4 . 2 30 5 . 3 40 6 . 3 50 7 . .... . </code></pre> <p>I want to produce a DataFrame:</p> <pre><code>a *not sure how to refer to this column?* 1 (10+20)/(3+4) 2 30/5 3 (40+50)/(6+7) </code></pre> ...
<p>try this:</p> <pre><code>In [216]: df.groupby('a').apply(lambda x: x['b'].sum()/x['c'].sum()) Out[216]: a 1 4.285714 2 6.000000 3 6.923077 dtype: float64 </code></pre>
python|pandas|group-by
9