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
367,300
55,987,849
Expressing chained inequality for each combination of elements of multiple arrays in a concise and scalable way
<p>I'm having three one-dimensional arrays <code>a, b, c</code> of different sizes and I'd like to compute the chained inequality <code>x &lt; y &lt; z</code> for each combination <code>x in a, y in b, z in c</code>. For example:</p> <pre><code>import numpy as np a = np.random.randint(100, size=100) b = np.random.ran...
<p><code>np.ix_</code> is convenient here:</p> <pre><code>A,B,C = np.ix_(a,b,c) (A&lt;B)&amp;(B&lt;C) </code></pre> <p>arbitrary number of arrays:</p> <pre><code>l = [np.random.randint(10*i, size=i) for i in range(2,6)] L = np.ix_(*l) np.bitwise_and.reduce(list(map(np.less, L, L[1:]))) </code></pre> <p>or using <co...
python|python-3.x|numpy|vectorization|inequality
2
367,301
55,658,488
How to make a progress bar on a web page for pandas operation
<p>I have been googling for a while and couldn't figure out a way to do this. I have a simple Flask app which takes a CSV file, reads it into a Pandas dataframe, converts it and output as a new CSV file. I have managed to upload and convert it successfully with HTML</p> <pre><code>&lt;div class="container"&gt; &lt;f...
<p>OK, I narrowed down the problems I was missing and figured it out. The concepts I needed include</p> <p>Backend</p> <ul> <li>Redis as a key-value database to store the progress which can be queried by endpoint <code>/progress</code> for an <strong>event stream</strong> (HTML5)</li> <li><strong>Server-Sent Event (S...
python|ajax|pandas|flask|tqdm
9
367,302
55,725,127
Pandas shifting multiple columns after groupby results in shifting columns in alphabetical order
<p>Here is my dataframe:</p> <pre><code> Zip_Code Year Month Z Y X 0 75001 2009 1 15.305484 8.798710 2.188065 1 75001 2009 2 19.048929 13.492143 7.600714 2 75001 2009 3 20.611290 15.179032 9.875806 3 75001 2009 4 24.483000 18.44...
<p>You have to include the argument <code>sort=False</code> in the <code>groupby</code>:</p> <pre><code>df_temp[['A', 'B', 'C']] = df_temp.groupby(['Zip_Code', 'Month'], sort=False)[['Z', 'Y', 'X']].shift() print(df_temp) Zip_Code Year Month Z Y X A \ 0 75001 2009 ...
python-3.x|pandas|dataframe
3
367,303
55,603,451
Pandas Data Frame from Web is not Displaying Correctly Compared to the Native CSV File
<p>I am trying to make a program that analyzes stocks, and right now I wrote a simple python script to plot moving averages. Extracting the CSV file from the native path works fine, but when I get it from the web, it doesn't work. Keeps displaying an error: 'list' object has no attribute 'Date'</p> <p>It worked fine w...
<p>The data got placed in a (one-element) list.</p> <p>If you do this, after the <code>read_html</code> call, it should work:</p> <pre><code>df = df[0] </code></pre>
python|pandas|matplotlib|plotly
0
367,304
55,898,252
If possible batch drop dataframe's columns with something like slice selection method?
<p>For next dataframe, I want to drop the columns <code>c, d, e, f, g</code></p> <pre><code> a b c d e f g h i j 0 0 1 2 3 4 5 6 7 8 9 1 10 11 12 13 14 15 16 17 18 19 </code></pre> <p>So I use next code:</p> <pre><code>import pandas as pd import numpy as np df = pd...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> for select consecutive names of columns:</p> <pre><code>df = df.drop(df.loc[:, 'c':'g'].columns, axis=1) print (df) a b h i j 0 0 1 7 8 9 1...
python|pandas
3
367,305
55,635,473
Numpy: Pick elements based on bool array
<p>I've got an array and a boolean array (as one hot encoding)</p> <pre class="lang-py prettyprint-override"><code>a = np.arange(12).reshape(4,3) b = np.array([ [1,0,0], [0,1,0], [0,0,1], [0,0,1], ], dtype=bool) print(a) print(b) # [[ 0 1 2] # [ 3 4 5] # [ 6 7 8] # [ 9 10 11]] # [[ True False...
<p>After filter by <code>b</code> broadcast it </p> <pre><code>a[b][:,None] Out[168]: array([[ 0], [ 4], [ 8], [11]]) </code></pre> <p>Or </p> <pre><code>a[b,None] Out[174]: array([[ 0], [ 4], [ 8], [11]]) </code></pre>
python|arrays|numpy|mask
3
367,306
55,929,960
What is the best way to handle large data with Tensorflow.js and tf.Tensor?
<h1>Question</h1> <p>I am using <code>tf.Tensor</code> and <code>tf.concat()</code> to handle large training data, and I found continuous using of <code>tf.concat()</code> gets slow. What is the best way to load large data from file to <code>tf.Tensor</code>?</p> <h1>Background</h1> <p>I think it's common way to han...
<p>While the <code>tf.concat</code> and <code>Array.push</code> function look and behave similar there is one big difference:</p> <ul> <li><code>tf.concat</code> creates a <strong>new tensor</strong> from the input</li> <li><code>Array.push</code> adds the input to the first array</li> </ul> <h2>Examples</h2> <p><st...
javascript|node.js|tensorflow|deep-learning|tensorflow.js
4
367,307
55,750,761
How to fix VGG16 ValueError: could not broadcast input array from shape (20,4) into shape (20)?
<p>Some problem with CNN Keras VGG16. </p> <p>What is doing here is trying to use CNN to train some images with Keras and VGG16. It seems that it cannot take image size 32. Even I change it to 48, I still get an error. </p> <pre><code>---&gt; 32 labels[i * batch_size : (i + 1) * batch_size] = labels_batch ...
<p><strong>Use below code and let me know if you're facing any issue.</strong></p> <pre><code>from keras.applications import VGG16 conv_base = VGG16(weights='imagenet', include_top=False, input_shape=(32, 32, 3)) conv_base.summary() import os import numpy as np from keras.prepr...
python|tensorflow|keras
0
367,308
55,978,645
How to select and subset rows based on sting in pandas dataframe?
<p>My dataset looks like following. I am trying to subset my <code>pandas</code> dataframe such that only the responses by all 3 people will get selected. For example, in below data frame the responses that were answered by all 3 people were "I like to eat" and "You have nice day" . Thus only those should be subsetted....
<p>IIUC I am using <code>transform</code> with <code>nunique</code></p> <pre><code>yourdf=df[df.groupby('Response').Person.transform('nunique')==df.Person.nunique()] yourdf Out[463]: Person Response 0 1 I like to eat 1 1 You have nice day 3 2 I like to eat 4 2 You have nice...
python-3.x|string|pandas|dataframe|text
1
367,309
55,909,188
How can I apply a TensorFlow 2D Convolution (tf.nn.conv2d) to a single (non-batch) 2D image?
<p>I would like to use the function <code>tf.nn.conv2d()</code> on a <strong>single</strong> image example, but the TensorFlow documentation seems to only mention applying this transformation to a <strong>batch</strong> of images. </p> <p>The docs mention that the input image must be of shape <code>[batch, in_height, ...
<p>AFAIK there is no way around it. It seems (<a href="https://stackoverflow.com/questions/50779869/does-tensorflow-tf-slice-incur-allocation-and-or-memory-copy">here</a> and <a href="https://stackoverflow.com/questions/53398721/tensorflow-can-reshape-create-a-copy">here</a>) that the first operation creates a copy (so...
python|tensorflow|conv-neural-network|convolution
0
367,310
55,921,699
Inserting rows of varying lengths to Postgres with pyscopg2
<p>I am building multiple different pandas dataframes in a for loop, which have a different number of columns depending what data is available from a website I am scraping. </p> <p>The issue I am having is when I loop over the rows of the dataframe at the end of the initial loop to insert them into postgres using psy...
<p>With parameterization, you can streamline much of your processing without worrying about string formatting of values between the string and numeric types. However, the preferred <code>str.format</code> is used to build prepared statement but only once outside of any loop.</p> <p>Note: the parameter placeholder for ...
python|python-3.x|pandas|postgresql|psycopg2
1
367,311
55,732,128
How can I get the arrays to all be the same length in Pandas?
<p>I am able to scrape data from multiple web pages in a web site using BeautifulSoup, and I am using pandas to make a table of the data. The problem is I cannot get all of the arrays to be the same length and I get:</p> <blockquote> <p>ValueError: arrays must all be same length</p> </blockquote> <p>Here is the code I ...
<pre><code>d = {'Street' : addresses, 'City-State-Zip' : geographies, 'Rent' : rents, 'BR/BA' : units, 'Units Available' : availabilities } test_df = pd.DataFrame(dict([(k,pd.Series(v)) for k,v in d.items()])) </code></pre>
python-3.x|pandas|numpy|beautifulsoup
3
367,312
55,670,952
DataFrame take union of columns and retain find first non-NaN value
<p>Dataframe <code>df</code> has many thousand columns and rows. For a subset of columns that are given in a particular sequence, say columns <code>B, C, E</code>, I want to fill <code>NaN</code> values in <code>B</code> with first non-NaN value found in remaining columns (<code>C, E</code>) searching sequentially. Fin...
<p>IIUC, use <code>bfill</code> to backfill, then <code>drop</code> to remove unwanted columns.</p> <pre><code>df.assign(B=df[['B', 'C', 'E']].bfill(axis=1)['B']).drop(['C', 'E'], axis=1) A B D 0 18.161033 6.453597 18.542586 1 27.629402 40.654821 22.804547 2 15.459256 NaN ...
python|pandas|dataframe
2
367,313
55,887,014
matplotlib: break axis and scale unevenly
<p>I have a bar-chart that needs to be broken along the x-axis, and after the break the scale of the x-axis should change. </p> <p>The following code utilizes the <code>brokenaxes</code> package (<a href="https://github.com/bendichter/brokenaxes" rel="nofollow noreferrer">https://github.com/bendichter/brokenaxes</a>)....
<p>You could try </p> <pre><code>brokenaxes(xlims=((0, 11), (50, 90)), width_ratios=[1,1]) </code></pre> <p>for equal distribution of the subplots.</p>
python|pandas|numpy|matplotlib|bar-chart
2
367,314
55,856,144
Extract specific row values out of a data frame from row values of another dataframe
<p>I have a data frame (df1) like this:</p> <pre><code> X Y 1 200.0 50 2 200.1 57 3 200.2 69 4 200.3 77 5 200.5 84 6 200.6 93 </code></pre> <p>and I have another data frame (df2) like this:</p> <pre><code> ...
<p><code>pd.merge()</code> is the first thing we would think of when the requirement of "looking things up in another df" comes up, but <code>df.loc[]</code> itself does have "looking things up" meaning as well.</p> <pre><code>"""set the df1 and df2 up """ import pandas as pd import numpy as np s ="""20000 20000 2000...
pandas|dataframe|data-extraction
0
367,315
55,817,888
Input to DecodeRaw is not a multiple of 8, the size of double
<p>I want to build a tensorflow dataset from tfrecords. this is my code: </p> <pre><code>def make_dataset(): filenames = [train_tfrecords_dir + name for name in os.listdir(train_tfrecords_dir)] dataset = tf.data.TFRecordDataset(filenames) def parser(record): keys_to_features = { "mhot_labe...
<p>Because you use tf.decode_raw to convert your image to double(tf.float64) type, which's size is 8 bytes. so the parsed['mel_spec_raw'] should be a multiple of 8. You can print the type of <strong>parsed['mel_spec_raw']</strong>, it should be <strong>tf.string</strong>, which explain why the size of the parsed['mel_s...
python|tensorflow|tensorflow-datasets
1
367,316
55,779,768
Delete the first header row in python
<p>I am trying to delete the first header row of the table which is 'Table 2.......'. <img src="https://i.stack.imgur.com/esXiA.png" alt="original table"></p> <p>I tried the code below</p> <pre><code>d1t2.columns = d1t2.iloc[0] d1t2 = data1t2.reindex(d1t2.index.drop(0)).reset_index(drop=True) d1t2.columns.name = Non...
<p>You were close:</p> <pre><code>d1t2.columns = d1t2.iloc[0] d1t2.columns.name=None d1t2.drop(0, axis=0, inplace=True) </code></pre> <p>However, if you read <code>d1t2</code> from a file, it would be better to skip the first row.</p>
python|pandas|dataframe
3
367,317
55,834,790
ImageDataGenerator: how to add the 4th dimension to a numpy array?
<p>I have the following code that reads an image with opencv and displays it:</p> <pre><code>import cv2, matplotlib.pyplot as plt img = cv2.imread('imgs_soccer/soccer_10.jpg',cv2.IMREAD_COLOR) img = cv2.resize(img, (128, 128)) plt.imshow(img) plt.show() </code></pre> <p>I want to generate some random images by using ...
<p>Use <code>np.expand_dims()</code>:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np img = np.expand_dims(img, 0) print(img.shape) # (1, 128, 128, 3) </code></pre> <p>The first dimension specifies the number of images (in your case 1 image).</p>
python|numpy|tensorflow|keras|deep-learning
4
367,318
55,654,603
pandas dataframe multiply / formula the bottom row to top row
<p>Need to add math formula to calculate result based on row below, all the way to top of dataframe</p> <pre><code>import pandas as pd n = 2 df = pd.DataFrame({'A': [2, 4, 8, 7, 1, 8, 2, 4],'B': [10, 2, 1, 8, 2, 4, 8, 7]}) df.loc[7, 'C'] = df.loc[7, 'A'] print(df) </code></pre> <p>print the above then read below:...
<p>You could try iterating backwords through the <code>DataFrame</code> with a <code>for loop</code> and updating the value of <code>"C"</code> with <code>loc</code>:</p> <pre><code>for idx in df.index[::-1][:-1]: df.loc[idx - 1, 'C'] = (df.loc[idx, 'C'] * 2 + df.loc[idx - 1, 'A']) / n print(df) A B C 0...
python|pandas|loops
1
367,319
55,773,388
filtering based on multiple conditions in Python
<p>I have a df which has a list of stocks, index membership, market cap, rank of market cap, turnover and rank of turnover.</p> <p>i need to created another column called 'Deletes' which will delete stocks based on a few condition.</p> <p>list of conditions using &amp; and |</p> <ol> <li><p>the current index members...
<p>I think here is possible add another <code>()</code> like:</p> <pre><code>df['Deletes'] = np.where((df['Index Membership'] == 'DAX') &amp; ((df['MKT Rank'] &gt; 35) | (df['Turnover Rank'] &gt; 35)),'delete','') </code></pre> <p>because <a href="https://docs.python.org/3/reference/expressi...
python|pandas|numpy|filter
3
367,320
55,879,565
Does Keras build model with wrong amount of neurons?
<p>i'm new to Keras. I created my model to work with <a href="https://www.kaggle.com/zalando-research/fashionmnist" rel="nofollow noreferrer" title="MNIST Fashion">Fashion MNIST</a></p> <p>Here is my model:</p> <pre><code>model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(1), ke...
<p>the first layer has 784 weights, second has 1 the third has 10. Thats a total of 795 weights. </p> <p>Although its not a great network design as you lose a lot of information on the second layer, the single weight can contain quite an amount of data. </p> <p>Think of it this way, what if you build a network that h...
python|tensorflow|keras|neural-network
0
367,321
55,846,240
Creating a np.void object of mixed data type, to use in np.full
<p>I want to make an array that is filled with a particular value. For simple data types, I can do this with <code>np.full</code>. For example, the following code will generate an array of length 10, where each value is the 64-bit integer 10:</p> <pre><code>import numpy as np arr = np.full((10,), -1, np.int64) </code>...
<p>The short answer - don't use <code>np.full</code> to construct a structured array. Make the blank array, and assign the value with <code>arr[:] = default_tuple</code>.</p> <hr> <p>It's the <code>copyto</code> that's have problems broadcasting the default:</p> <pre><code>In [596]: np.full(3,default) ...
python|numpy
1
367,322
55,862,225
How to exclude more than one group in a groupby using python?
<p>I have grouped the number of customers by region and year joined using groupby in Python. However I want to remove several regions from the region group.</p> <p>I know in order to exclude one group from a <code>groupby</code> you can use the following code:</p> <pre><code>grouped = df.groupby(['Region']) df1 = df....
<p>It's not <code>df1 = df.drop(grouped.get_group(('Southwest','Northwest')).index)</code>. <code>grouped.get_group</code> takes a single name as argument. If you want to drop more than one group, you can use <code>df1 = df.drop((grouped.get_group('Southwest').index, grouped.get_group('Northwest').index))</code> since ...
python|pandas-groupby
0
367,323
55,805,384
(Python/Pandas) Divide two columns of pivoted dataframe based on a condition
<p>I generated the following pandas dataframe after pivotting my data:</p> <pre><code>df_pivot=df.pivot_table( values=[1911, 1912, 1916, 1917], index=['h_code','h_name'], columns=['sort_code', 'reg','c_name','c_code'] ) </code></pre> <p>I would now like to add a column to my <code>df</code> (let's call it <code>c_ne...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.xs.html" rel="nofollow noreferrer"><code>DataFrame.xs</code></a> for select by top level, create same names of level and divide with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" r...
python|pandas
1
367,324
55,857,699
Change dataframe values automatically
<p>I have a table.</p> <pre><code>Row_count EXP1 EXP2 2544 24 22 </code></pre> <p>I want it like this:</p> <pre><code>Row_count EXP TOTAL_I.V 2544 EXP1 24 2544 EXP2 22 </code></pre>
<pre><code>df2 = pd.melt(df, id_vars=["Row_count"], var_name="Exp", value_name="TOTAL_I.V") </code></pre>
python|pandas
1
367,325
55,617,302
Getting dynamic date in oracle SQL query executed from python environment using cx_Oracle package
<p>I'm trying to write a query which fetches the current date and gets the relevant log data. Have written a nested query which works from PL/SQL but it isn't working from Python environment. Please advise. </p> <p>Working query for PL/SQL:</p> <pre><code>SELECT * FROM TBLIRISVISITLOGS TLOG WHERE TLOG.IVL_VISITDATE =...
<p>seems like I've found the solution:</p> <pre><code>from pandas import Timestamp as tstamp test_query = """ SELECT * FROM TBLIRISVISITLOGS T WHERE T.IVL_LATITUDE&gt;0 AND T.IVL_VISITDATE = TO_DATE('{CURR_DATE}','YYYY-MM-DD') """.format(CURR_DATE=str(tstamp.now().date())) </code></pre>
python|sql|pandas|cx-oracle
1
367,326
55,626,421
Numpy tobytes() with defined byteorder
<p>Is it possible to define byte order when converting a <em>numpy</em> array to binary string (with <em>tobytes()</em>)?</p> <p>I would want to force little endianness, but I don't want byte-swapping if it is not necessary.</p>
<p>When interfacing with C code I use this pattern</p> <pre><code>numpy.ascontiguousarray(x, dtype='&gt;i4') </code></pre> <p>That dtype string specifies the endianess and precise bit width.</p> <p>You can check ndarray.flags to see if conversions are necessary.</p>
python|numpy|binary|endianness
5
367,327
55,867,274
How to feed ensemble model same input data as its sub models?
<p>I'm trying to create an ensemble model that gets the same input as the sub models.</p> <pre class="lang-py prettyprint-override"><code>models = list() nb_models = 3 #load all sub models for i in range(nb_models): model_tmp = load_model("lstm_model"+str(i+1)+".h5") model_tmp.name = "model_"+str(i+1) mod...
<p>See this example taken from <a href="https://machinelearningmastery.com/keras-functional-api-deep-learning/" rel="nofollow noreferrer">here</a></p> <pre><code># Multiple Inputs from keras.utils import plot_model from keras.models import Model from keras.layers import Input from keras.layers import Dense from keras....
python|tensorflow|keras|deep-learning
0
367,328
55,876,000
Numpy reshape with remainder throws error
<p>How can I partition this array into arrays of length 3, with a padded or unpadded remainder (doesn't matter)</p> <blockquote> <p>&gt;&gt;&gt; np.array([0,1,2,3,4,5,6,7,8,9,10]).reshape([3,-1])</p> <p>ValueError: cannot reshape array of size 11 into shape (3,newaxis)</p> </blockquote>
<pre class="lang-py prettyprint-override"><code>### Two Examples Without Padding x = np.array([0,1,2,3,4,5,6,7,8,9,10]) desired_length = 3 num_splits = np.ceil(x.shape[0]/desired_length) print(np.array_split(x, num_splits)) # Prints: # [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([ 9, 10])] x = np.a...
arrays|python-3.x|numpy|reshape|partitioning
2
367,329
55,782,954
Delete Row in Pandas Dataframe if value in Row, Column Matches Anywhere in Another Column
<p>What I am looking to do is delete a row in a pandas dataframe if a value in that row matches anywhere in another column. Here is a rough mocked up example in Excel:</p> <p><a href="https://i.stack.imgur.com/cEy79.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cEy79.png" alt="enter image descrip...
<p>You have to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> with the <code>~</code> operator to get the opposite with boolean indexing, you can read it as <code>not isin</code></p> <pre><code># Print example data...
python|pandas
3
367,330
55,808,797
Removing dot in front of digits using regular expression in pandas
<p>I need to remove the dot in front of digits using regular expressions in pandas.</p> <pre><code>What I have: .9/10 .8/10 What I want: 9/10 8/10 </code></pre> <p>I need to use <code>df.col.str.extract()</code>.</p> <p>Also <strong>beware</strong> because there are also float numbers 11.25/10, and in those cases I...
<p>I think this works on the small example you provided (Next time provide more data)</p> <pre><code>import re re.sub(r' $', '', re.sub(r'|^.', '', re.sub(r', .', ', ', '.9/10, .8/10 '))) '9/10, 8/10' </code></pre>
regex|pandas
1
367,331
55,742,177
New variable in a panda dataframe which counts consecutive values
<p>I have a panda dataframe (which is imported from excel), is made up of 2 variables, f is just a number the other is a boolean for if the number is out the range</p> <p>I want to create a new variable which counts consecutive TRUE vales. </p> <p>I read a little online and I think the new variable could use consecu...
<p>Use vectorized solution with replace <code>T</code> values:</p> <pre><code>a = df['outrange'] == 'T' #if values are boolean True #a = df['outrange'] b = a.cumsum() df['count_new'] = b-b.where(~a).ffill().fillna(0).astype(int) print (df) f outrange count count_new 0 1 F 0 0 1 2 F ...
python|pandas|dataframe
4
367,332
55,810,341
Find unique tuples inside a numpy array with np.where
<p>I want to find unique color tuples inside a numpy array with np.where. My code so far is:</p> <pre><code>from __future__ import print_function import numpy as np a = range(10) b = range(10,20) c = range(20,30) d = np.array(zip(a, b, c)) print(d) e = np.array(zip(c, b, a)) print(e) search = np.array((1,11,21)) sea...
<p>OK, finally found the solution myself, here is the code for doing it:</p> <pre><code>import numpy as np import cv2 image_a = cv2.imread("old_frame.png") image_b = cv2.imread("new_frame.png") cv2.imshow("image_a", image_a) cv2.imshow("image_b", image_b) transp_color = (0, 16, 8)[::-1] channels = 3 f = np.all((image...
arrays|numpy|tuples|unique|where
0
367,333
55,667,791
How can I calculate the week of the month from week of the year?
<p>I found a <a href="https://stackoverflow.com/questions/33647513/get-the-week-number-of-the-month-from-week-number-of-the-year">node.js</a> solution but couldn't find a python one. I have a <code>DataFrame</code> that looks like:</p> <pre><code> Year Month Week numOfTrips 0 2011 July 30 2608 1 2...
<p>I found a relatively long and ugly solution that seems to work. If there are errors/bugs or a cleaner implementation, let me know.</p> <p><strong>My approach</strong>: using example <code>2011 July 30 2608</code></p> <ol> <li>Get the weeks for the appropriate month in its respective year</li> </ol> <pre c...
python|pandas|date|calendar|time-series
0
367,334
55,794,563
Adding a new column for the amount of rows within the last month
<p>Let's start with a pandas dataframe as so:</p> <pre><code>&gt;&gt;&gt; df Date 0 2006-01-30 1 2006-02-02 2 2006-02-03 3 2006-02-04 4 2006-02-21 5 2006-02-23 6 2006-03-07 7 2006-03-11 8 2006-04-24 9 2006-04-25 </code></pre> <p>I would like to add a new column which is the amount o...
<p>You can try np's broadcast:</p> <pre><code>offset = df.Date + pd.DateOffset(months=-1) df['Past_Month'] = np.sum((df.Date.values &gt; offset.values[:,None]) &amp; (df.Date.values &lt; df.Date.values[:, None]), axis=1) </code></pre> <p>Output:</p> <pre><code> ...
python|pandas
1
367,335
55,696,805
Best way to create large array in python?
<p>I'm new to python and am trying to make a large array. Looking for the best method to do this.</p> <p>Basically I am trying to make a large array in python to put into another application. The array will have a variable number of rows and 5 columns. I have data for two of the columns stored in other lists and would...
<p>I'd need to know what your input lists are like but I'll make an attempt. Something like this?</p> <pre><code>array1 = [1,2,3,4] array2 = ['a','b','c','d'] output_array = [['x','y','z',a1,a2] for a1,a2 in zip(array1,array2)] print(output_array) [['x', 'y', 'z', 1, 'a'], ['x', 'y', 'z', 2, 'b'], ['x', 'y', '...
python|arrays|pandas|list|numpy
0
367,336
64,823,256
Filter data in Pandas Dataframe based on the type of values
<p>I am hardly trying to filter my dataframe set using the .loc function, with a condition based on the type of the data in one of my column.</p> <p>My goal is to apply (with .apply) a function on a column only on rows with a certain type.</p> <p>I tried to use &quot;dtype&quot;, but my column has values with 2 differe...
<p>As you mention, <code>dtypes</code> does work if you have multiple types. Here is what you could do instead:</p> <pre><code>employees = [('jack', 34, 'Sydney', 155), ('Riti', 31, 'Delhi', 177.5), ('Aadi', 16, 'Mumbai', 81), ('Mohit', 31, 45, 167), ('Veena', 12, 'Delhi'...
python|pandas|dataframe|conditional-statements
0
367,337
64,670,746
Built data frame of two lists
<p>How to build data frame out of two lists in a way shown below?<br /> I have tried iterate over lists but I couldn't figure out way add only one element to each list. like this:</p> <pre><code>for e in listone: for list in listtwo: list.insert(0, e) </code></pre> <p>Example:</p> <pre><code>listone = [1, 2,...
<p>Let's try a list comprehension on <code>product</code>:</p> <pre><code>from itertools import product [[x]+y for x,y in product(listone, listtwo)] </code></pre> <p>Output:</p> <pre><code>[[1, 4, 5, 6], [1, 7, 8, 9], [2, 4, 5, 6], [2, 7, 8, 9], [3, 4, 5, 6], [3, 7, 8, 9]] </code></pre>
python|pandas
1
367,338
64,765,350
pandas dataframe select list value from another column
<p>Everyone! I have a pandas dataframe like this:</p> <pre><code> A B 0 [1,2,3] 0 1 [2,3,4] 1 </code></pre> <p>as we can see, the A column is a list and the B column is an index value. I want to get a C column which is index by B from A:</p> <pre><code> A B C 0 [1,2,3] 0 ...
<p>Use list comprehension with indexing:</p> <pre><code>df['C'] = [x[y] for x, y in df[['A','B']].to_numpy()] </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a>, but it should be slowier if large ...
python|pandas|dataframe
3
367,339
64,799,737
using find in pandas dataframe in str range
<p>I have a dataframe column</p> <pre><code> code 0. Slip - Trans:S-BRT4-S-BRT4-98683Store:S-BRT4Terminal:S-BRT4 1. Slip - Trans:M-BXP2-M-BX2-65459Store:M-BXP2Terminal:M-BXP2 2. Slip - Trans:M-YyL2-M-YyL2-93949Store:M-YyL2Terminal:M-YyL2 </code></pre> <p>I want to specific string (below bold) in another column named ...
<p>If need values between <code>Trans:</code>: and <code>Store:</code> use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>Series.str.extract</code></a></p> <pre><code>df['TTT']= df['code'].str.extract('Trans:(.*)Store:', expand=False) p...
python|pandas
2
367,340
64,825,152
Pandas Dataframe : inplace column substitution vs creating new dataframe with transformed column
<p>Whenever I want to transform an existing column of a dataframe, I tend to use <code>apply/transform</code> which gives me altogether a new series and it does not modify the existing column in the dataframe.</p> <p>Suppose the following code performs an operation on a column and returns me a series.</p> <pre><code>ne...
<p>Since you are modifying an existing column, the first approach would be faster. Remember that both <code>drop</code> and <code>join</code> returns a copy of new data, so the second approach can be expensive if you have a big data frame with many columns.</p>
python-3.x|pandas|dataframe
0
367,341
64,780,193
Python type error: 'numpy.ndarray' object is not callable
<p>I'm defining a set of functions to convert from an Earth-centered reference frame to classical orbital elements. Here are my codes:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt #converting r,v to orbital elements u = 3.986*10e14 #gravitational parameter for Earth list_r = [-2413.9, 6083.8, -113...
<p>While local variables can be short, single names, functions should be more informative. In particular you have defined a function <code>h</code>, but you also use <code>h</code> as a local variable. That confuses you (and us).</p> <p>In several of the functions <code>h</code> is a local variable, and an array (at ...
python|arrays|numpy
1
367,342
64,726,462
Numpy indexing assignement preserve contiguousness?
<p>Let suppose that I have a contiguous array:</p> <pre><code>contiguous_array = np.ascontiguousarray(...) </code></pre> <p>and another non necessarily contiguous array:</p> <pre><code>generic = np.array([10, 100, 1000]) </code></pre> <p>if I do something like that:</p> <pre><code>indices = [0, 5, 10] contiguous_array[...
<p><code>contiguous_array</code> will still be contiguous. The assignment copies data into <code>contiguous_array</code>'s existing buffer; it does not change the memory layout. It is impossible to make a contiguous array non-contiguous.</p>
python|numpy|cython
1
367,343
64,932,974
How to multiply or divide two Series in python?
<p>I have a dataset like this. The actual dataset is much larger though.</p> <pre><code>data1 = pd.DataFrame({'Name':[&quot;Tom&quot;,&quot;Andy&quot;,&quot;Joseph&quot;,&quot;Joe&quot;,&quot;Mary&quot;,&quot;Alexa&quot;,&quot;Chris&quot;,&quot;Jessica&quot;,&quot;Jimmy&quot;,&quot;Andrea&quot;,&quot;George&quot;,&quot...
<p>The simplest way I can think of is by using the <code>numpy</code> &quot;outer product&quot; function, as such:</p> <pre><code>pd.DataFrame(np.outer(df_City.values, df_Car.values), index=df_City.index, columns=df_Car.index) </code></pre> <p>Which gives:</p> <pre><code>Car Ford GM Honda Nissan Porsche TOYOTA ...
python|pandas|numpy|series|divide
2
367,344
64,823,386
Create Pandas DF by searching for multiple record values across multiple columns
<p>I am trying to create a new dataframe that can pull rows based on multiple terms across multiple columns. I have a huge excel file (65k row) I am pulling into a df so that I can pull out new priority reports.</p> <p>So as an example, this is what I am using to search for multiple terms across 1 column (columnA in th...
<pre><code>newdf = df.loc[df.apply(lambda row: row.str.contains('dbcor|nopgms|swcor|bkupmems', case=False, regex=True, na=False).any(), axis=1)] </code></pre> <p>will return rows where any value matches the pattern. Replace <code>any</code> with <code>all</code> if you need all values to match it.</p>
python|pandas|dataframe
0
367,345
64,728,803
Is there any good way to group time series Stock Data?
<p>I am facing a problem to group my stock market data which has a custom time frame.. The raw data looks like the following.. I want to group this in 2 hours frame. As my data's starting time is 9:15AM I want to group 9:15:00 to 11:15:00 data for a particular date. also the data for a particular day ends at 15:15:00. ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html" rel="nofollow noreferrer">.resample(origin='start')</a> to start grouping by 2 hours at your first timestamp.<br> <br> Don't reinvent the wheel by defining you own open / high / low / close function. There's alrea...
python|pandas|dataframe|date
1
367,346
64,957,989
Jupyter Notebook - Erros with retrieving numpy
<p>Here is the error message that gets returned when trying to import pandas as pd</p> <hr /> <pre><code>ImportError Traceback (most recent call last) &lt;ipython-input-1-7dd3504c366f&gt; in &lt;module&gt; ----&gt; 1 import pandas as pd /usr/lib/python3/dist-packages/pandas/__init__.py in...
<p>So I solved my issue.</p> <p>When opening a new notebook in Jupyter notebook, it prompts you to open a Python3 notebook or Python3.9.0 64 bit notebook. Although Python3.9.0 64 bit is the most current edition, and one I had downloaded, it wasn't what I had installed. When opening a Python3 book I was able to import p...
pandas|numpy|jupyter-notebook
0
367,347
64,663,363
CNN: Which channel gives the most informations?
<p>while working with CNNs I was wondering which of my Input Channels gives the most information to the neural network for the prediction.</p> <p>For example: The is a image of a frog. The CNN is suppose to predict which kind of animal is in the image. So because frogs are green most of the time, the CNN uses the chann...
<p>IF a color channel is the most important, you can check manually by getting the weights of the input convolution layer. They will be in (filtersizex x filtersizey x 3) X the number of filters. you then need to add the weights so you get (1 x 3) X the number of filters. So you have for each filter the most important ...
python|tensorflow2.0|prediction|conv-neural-network
0
367,348
65,022,009
How to keep/extend index when oversample
<p>I've got a dataframe like that , and I want to oversample the column &quot;role&quot; (in a real case the number of rows/columns in much bigger than this minimal example)</p> <pre><code> role value pop_13vdpn1_site_1 1 1 pop_13vdpn1_site_1 1 1 pop_13vdpn1_site_1 1 2 pop_13vdpn1_site_1 1 ...
<p>Finally I've found a workaround (Maybe not optimal)</p> <pre><code>from sklearn.preprocessing import LabelEncoder le = LabelEncoder() df_tmp = df.reset_index() df_tmp['index'] = le.fit_transform(df_tmp['index']) aa,bb = smote.fit_sample(df_tmp,df_tmp[['role']]) aa['index'] = le.inverse_transform(aa['index']) aa.set_...
python|pandas|imbalanced-data|oversampling|smote
1
367,349
64,763,336
Group by Category and Set Threshold in Python
<p>I have a dataset, df, where I would like to group each threshold.</p> <pre><code>group start end Percent A 2019-04-01 2019-05-01 21 A 2019-05-01 2019-06-01 8 A 2019-07-01 2019-08-01 5 B 2020-06-01 202...
<p>Use <code>np.select(condition, choice, alternative)</code></p> <pre><code>condition=[(df.group.eq('B')&amp;df.Percent.gt(6))|(df.group.eq('A')&amp;df.Percent.gt(20)),(df.group.eq('B')&amp;df.Percent.lt(1))|(df.group.eq('A')&amp;df.Percent.lt(6))] choice=['Too High','Too Low'] df['result']=np.select(co...
python|pandas|numpy
3
367,350
64,956,168
macOS Big Sur python3 cannot import numpy due to polyfit error
<p><strong>update from Jan 2021:</strong> I performed a clean install of Big Sur in Jan 2021, and upgrade pip to latest version using <code>python3 -m pip install --upgrade pip --user</code>, and installed <code>numpy</code> without issues, and without the error message below.</p> <p><strong>original question from Nov ...
<p>The numpy installed by default in my question (and which caused the crash) was 1.19. I was able to use numpy with the following workaround:</p> <pre><code>python3 -m pip uninstall numpy python3 -m pip install numpy==1.18.0 --user </code></pre>
python|macos|numpy|macos-big-sur|xcode-command-line-tools
9
367,351
64,911,365
Tensorflow codart64_101.dll not found
<p>I have Tensorflow 2.3.1, Cuda 10.1 and v7.6.5.32 installend. The Path is also set and the File exist</p> <p><a href="https://i.stack.imgur.com/qAwmH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qAwmH.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/k5y1l....
<p>I found the problem. I was using the Python version from the Windows Store. This version runs in a sandbox, therefore it cannot access the CUDA files, with the Python Version from the Python website it is working.</p>
python|tensorflow
0
367,352
64,783,340
Dump JSON from pandas dataframe by unique column1 column2 combination
<p>I have some data in an SQL database that I'm looking to convert to JSON. For every unique combination of grp1 and grp2, I'd like for it to list grp1, grp2 and name. I guess the correct terminology is nested JSON?</p> <p>Here's my code so far:</p> <pre><code>import pandas as pd import json json_string = '[{&quot;g...
<p>You need to collect the items and map them to a temporary dictionary before eventually converting them to json-format.</p> <p>Here is the running code:</p> <pre><code>json_string = '[{&quot;grp1&quot;:&quot;aaa&quot;,&quot;grp2&quot;:&quot;streets&quot;,&quot;name&quot;:&quot;Carter&quot;},{&quot;grp1&quot;:&quot;aa...
python|json|pandas|dataframe|dictionary
2
367,353
64,639,852
Python replace error: replace() argument 2 must be str, not Series
<p>I want to update a string with html code. The string is something like this:</p> <pre><code>textHTMLextract = 'Hello, my name is name1 name2' </code></pre> <p>And I have a dataframe with variables like this:</p> <pre><code>import pandas as pd variables = [{'Var': 'name1', 'Value': '&lt;i&gt;John&lt;/i&gt;'}, ...
<p>Since you're using pandas here, you can leverage <code>Series.replace</code> which takes a dictionary of replacements and works with regex:</p> <pre><code>mappings = dict(zip(df['Var'], df['Value'])) pd.Series(textHTMLextract).replace(mappings, regex=True).item() # 'Hello, my name is &lt;i&gt;John&lt;/i&gt; &lt;i&gt...
python|pandas|dictionary|replace
1
367,354
64,823,326
Convert pandas series to int with NaN values
<p>I have a series (month_addded) in my DataFrame like this:</p> <pre><code>9.0 12.0 12.0 nan 1.0 </code></pre> <p>I want all the floats to be ints, and the NaN's to stay as they are. I did this:</p> <pre><code>for i in df['month_added']: if i &gt; 0: i=int(i) </code></pre> <p>But it did nothing.</p>
<p><code>NaN</code> is float typed, so Pandas would always downcast your column to float as long as you have <code>NaN</code>. You can use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html#nullable-integer-data-type" rel="nofollow noreferrer">Nullable Integer</a>, available from Pandas 0....
python|pandas|dataframe
4
367,355
64,868,040
`*** RuntimeError: mat1 dim 1 must match mat2 dim 0` whenever I run model(images)
<pre><code> def __init__(self): super().__init__() self.conv = nn.Sequential( nn.Conv2d(1, 64, kernel_size=5, stride=2, bias=False), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2, bias=False), nn.BatchNorm2d(64),...
<p>The output from <code>self.conv(x)</code> is of shape <code>torch.Size([32, 64, 2, 2])</code>: <code>32*64*2*2= 8192</code> (this is equivalent to (<code>self.conv_out_size</code>). The input to fully connected layer expects a single dimension vector i.e. you need to flatten it before passing to a fully connected la...
pytorch|conv-neural-network
6
367,356
64,786,172
Compare dataframe group by index row value with previous row value
<p>Just wondering if there is a simply solution to the following problem. Take the following setup</p> <pre><code>import datetime import pandas data = [ {&quot;date&quot;: datetime.date(2020, 1, 1), &quot;ticker&quot;: &quot;ticker-1&quot;, &quot;internal_id&quot;: &quot;T1&quot;, &quot;score_1&quot;: 10.0, &quot;...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a> with compared values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.shift.html" rel="nofollow norefe...
python|pandas|dataframe|pandas-groupby|data-science
0
367,357
64,847,761
pandas_ta Technical Indicators
<p>I am very new to this, and looking for some help. I have a .csv file which I have pulled into a dataframe. It contains 200 days of tickers, open, high, low &amp; close prices.</p> <p>I am trying to use pandas_ta (sma) to calculate the 10, 50 &amp; 100 day SMA. I tried did 3 commands:</p> <pre><code>df.ta.sma(...
<p>Be sure to use:</p> <pre><code>import pandas_ta as ta </code></pre> <p>And I've used it like your examples with ema, with the exception my OHLC is all lower case. Check your actual syntax: it is close or Close?</p> <pre><code>df.ta.ema(df['close'], length=14, offset=None, append=True) </code></pre>
python|pandas|finance|pandas-ta
2
367,358
64,965,873
Building a pandas condition query using a loop
<p>I am having an object filters which gives me conditions to be applied to a dataframe as shown below:</p> <pre><code>&quot;filters&quot;: [ { &quot;dimension&quot; : &quot;dimension1&quot;, &quot;operator&quot; : &quot;IN&quot;, &quot;value&quot;: [&quot;value1&quot;, &quot;value2&quot;, &...
<p>I have used <code>eval</code> function to create nested eval statements for pandas conditional filtering and then used it at the end to evaluate them all as shown below:</p> <pre><code>for eachFilter in filtersArray: valueString = &quot;&quot; values = eachFilter[self.queryBuilderMap[&quot;FI...
pandas
0
367,359
64,863,980
Grouping information by hour in pandas
<p>I have a pandas dataframe column that looks like this</p> <pre><code>0 01:41:21 1 01:41:42 2 01:41:56 3 01:58:41 4 07:34:08 </code></pre> <p>How can I group other columns by hour</p>
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_datetime</code></a>:</p> <pre><code>times = pd.to_datetime(df.col_timestamp) g = df.groupby(times.hour) </code></pre>
python|pandas|dataframe
1
367,360
64,819,984
Applying Size() function in groupby along with the aggregate parameter - Pandas
<p>i want to get the number of instances when using groupby function along with the agg parameter</p> <pre><code>Name Country X_Id Value Rahul 1 2 100 Rahul 1 2 50 Matthew 2 3 100 Matthew 1 1 25 Name Country X_Id Value Instances Rahul 1 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> with named aggregation:</p> <pre><code>df.groupby(['Name', 'Country', 'X_Id']).agg(Value = ('Value', 'mean'), ...
pandas|numpy|dataframe|automation|pandas-groupby
2
367,361
64,775,678
How to look for same columns from one dataframe in other dataframe pandas python?
<p>I have one dataframe like this,</p> <pre><code>tabla_aciertos= {'Numeros_acertados' : [5,5,5,4,4,3,4,2,3,3,1,2,2],'Estrellas_acertadas': [2,1,0,2,1,2,0,2,1,0,2,1,0]} categorias = [1,2,3,4,5,6,7,8,9,10,11,12,13] categoria_de_premios = pd.DataFrame (tabla_aciertos,index = [categorias] ) categoria_de_premios </code></p...
<pre><code># supposing that the indexes, starting from one, correspond to the the premiums categoria_de_premios['Categoria'] = df.index # Merge using pd.merge and the appropriate arguments sorteos_anteriores = (sorteos_anteriores.merge( categoria_de_premios, how='outer', left_on=['bolas_Acertadas','estrell...
python|pandas|numpy|dataframe|merge
0
367,362
64,640,182
How to modify numercial values in a column of mixed data types in a pandas dataframe?
<p>I have a pandas dataframe in python that looks like this (my actual dataframe is MUCH bigger than this):</p> <pre><code> col_1 col_2 0 0.8 0.1 1 nope 0.6 2 0.4 0.7 3 nope nope </code></pre> <p>How can I perform some operations on the numerical values of specific columns. For example, multiply the numer...
<p>To multiply your column by 10 and preserve your non-numeric values <code>&quot;nope&quot;</code> you'll need to convert your column to a numeric dtype and replace the non-numeric values with <code>NaN</code>. Then you'll perform your operation on that column and replace only the values in that column that were numer...
python|pandas|dataframe
1
367,363
64,827,451
How do I convert NBA-API List to DataFrame
<p>Having an issue converting NBA-API object to a DataFrame. What I get is a list of the dataframe. How do I pull the DataFrame out the list or skip the list and create the DataFrame.</p> <pre><code>## NBA API endpoints needed to obtain data import nba_api.stats.endpoints from nba_api.stats.static import players from...
<p>This?</p> <pre><code>df1=NewDF[0] df2=NewDF[1] </code></pre>
pandas|list|dataframe|nba-api
1
367,364
64,810,789
Python ValueError: could not convert string to float
<p>I have the code below, where the input is <code>h_ply =['0.12, 0.15, 0.2, 0.125']</code></p> <pre><code>h_ply = simpledialog.askstring('Laminate Properties','Ply Thickness') try: h_layer_list = [int(x) for x in h_ply.split(',')] h_layer = np.array(h_layer_list) * 0.001 </code></pre> <p>I have also tried</p...
<p>The way to deal with this is to properly access the string. Look at your data:</p> <pre><code>h_ply =( # a tuple, containing ... [ # a single element, a list, containing ... [ # a single element, a list, containing ... '0.12, 0.15, 0.2, 0.125' # ... a string that you...
python|numpy-ndarray
0
367,365
64,836,856
Why does't my pandas indexer work when I tried to filter just two values?
<p>I tried to use a indexer to filter just two values (1 and 2) from a DataFrame, but if I check the .csv file I found some 77 values. <img src="https://i.stack.imgur.com/Bn4kK.png" alt="" /></p> <p>#My len is 15333, this is because of &quot;77&quot; values, the correct it will be 15286, i.e taking account just 1 and 2...
<p>If I look at your code and you only want to take values <code>HAD_CPOX==1</code> or <code>HAD_CPOX==2</code>, then your still have to assign your filtered df back to variable df again like this:</p> <pre><code>df = df[(df['HAD_CPOX'] == 1) &amp; (df['HAD_CPOX'] == 2)] </code></pre> <p>You could also write:</p> <pre>...
pandas|numpy|dataframe|mask
0
367,366
64,752,584
Write Array and Variable to Dataframe
<p>I have an array in the format <code>[27.214 27.566]</code> - there can be several numbers. Additionally I have a Datetime variable.</p> <pre><code>now=datetime.now() datetime=now.strftime('%Y-%m-%d %H:%M:%S') time.sleep(0.5) agilent.write(&quot;MEAS:TEMP? (@101:102)&quot;) values = np.fromstring(agilent....
<p>I will assume you want to append a row to an existing dataframe <code>df</code> with appropriate columns : <code>value1, value2, ..., lastvalue, datetime</code> We can easily convert the array to a series : <code>s = pd.Series(array)</code></p> <p>What you want to do next is append the datetime value to the series :...
python-3.x|pandas|string|numpy
0
367,367
64,631,890
Convert Nested dictionary to Pyspark Dataframe
<p>Greetings to fellow programmer.</p> <p>I have recently started with pyspark and comes from a pandas background. I need to compute similarity of user in a data against each other. As I couldn't find from pyspark I resorted to use python dictionary to create a similarity dataframe.</p> <p>However, I run out of ideas t...
<pre><code>from pyspark.sql.types import * import pyspark.sql.functions as psf def cos_sim(a,b): return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))) dot_udf = psf.udf(lambda x,y: cos_sim(x,y), FloatType()) data.alias(&quot;i&quot;).join(data.alias(&quot;j&quot;), psf.col(&quot;i.user&quot;) != p...
python|pandas|pyspark
0
367,368
65,032,752
How to get datatype and data length of the columns of Dataframe in Pandas
<p>I am trying to fetch the <strong>datatype</strong> and <strong>datalength</strong> of the columns of <strong>dataframe</strong> in the format like <strong>object(10)</strong> where <strong>10 is the data length and object is the type of dataframe</strong>. I am using <strong>dtype function</strong> to get datatype o...
<p>EDIT:</p> <pre><code>#selected only integers and object columns df1 = df.select_dtypes([object, np.integer]) #dtypes s1 = df1.dtypes.apply(lambda x:x.name) #maximal length of data s2 = df1.astype(str).apply(lambda x: x.str.len()).max() #dict comprehension d = {k: f'string({b})' if a == 'object' ...
python|pandas|dataframe|validation
0
367,369
64,975,117
How do I concat numpy columns?
<p>I have a numpy array with the dimensions 216 x 3. Is there a pythonic way to concat these &quot;columns&quot; together? As these are not really columns, I don't know how to approach this problem. Many thanks!</p> <p>A sample of my data:</p> <pre><code>print(Allcombos) SSU MSU LSU SSU MSU LU SSU MSU LWU ...
<pre><code>arr=np.array([['SSU' ,'MSU','LSU'], ['SSU', 'MSU', 'LU'], ['SSU', 'MSU', 'LWU']] ) arr1=[] for i in arr: arr1.append(&quot;&quot;.join(i)) </code></pre> <p>output</p> <pre><code>['SSUMSULSU', 'SSUMSULU', 'SSUMSULWU'] </code></pre>
python|numpy
2
367,370
64,648,987
Python Pandas: if condition is true, put existing column value into new column
<p>I want to modify my pandas dataframe so if a <strong>can</strong> column value = 'Group Total', the <strong>cv1</strong> and <strong>cvs1</strong> values of the same row are placed in new <strong>pv1</strong> and <strong>pvs1</strong> columns for the above rows in my dataframe. If <strong>pty_n</strong> = 'Independe...
<p>The general pattern I use for this kind of thing is:</p> <p><code>dataframe.loc[condition, destination columns] = dataframe.loc[condition, source columns]</code></p> <p>This takes advantage of vectorized pandas operators</p> <p>More specifically, for your use-case this can be accomplished in two steps, something lik...
python|pandas|dataframe|loops|csv
0
367,371
64,981,589
Pass lists of columns to Pandas DataFrame instead of lists of rows
<p>I am trying to create a DataFrame like this:</p> <pre><code>column_names= [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] vals = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] df = pd.DataFrame(vals, columns=column_names) </code></pre> <p>Which results in the following DataFrame:</p> <pre><code> a b c 0 1 2 3 1 4 5 6 2 ...
<p>Just <code>zip</code> it:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(dict(zip(column_names, vals))) </code></pre> <p>Outputs:</p> <pre class="lang-py prettyprint-override"><code> a b c 0 1 4 7 1 2 5 8 2 3 6 9 </code></pre>
python|pandas|dataframe
4
367,372
65,012,697
Plot specific column values in Seaborn instead of every column value
<p>I can't figure out how to filter a column and then plot it successfully on Seaborn.</p> <p>The below code works perfectly and plots a line graph with all of the unique columns values separated.</p> <pre><code>import geopandas as gpd import matplotlib.pyplot as plt import pandas as pd import numpy as np import seab...
<p>With <code>sns</code> you should pass the data option and <code>x,y, hue</code> as the columns in the data:</p> <pre><code>sns.relplot(x='Sales_Year', y='Price_Per_Acre', hue='PLANNING_JURISDICTION', data=data.loc[data.PLANNING_JURISDICTION.isin(egs)], kind='line', ci=None ...
python|pandas|matplotlib|filtering|seaborn
1
367,373
64,688,464
problems with python Pandas converting int to float
<p>I'm using pandas read_csv to extract data and reformat it. For example, &quot;10/28/2018&quot; from the column &quot;HBE date&quot; will be reformatted to read &quot;eHome 10/2018&quot;</p> <p>It mostly works except I am getting reformatted values like &quot;ehome 1.0/2015.0&quot;</p> <pre><code>eHomeHBEdata['HBE da...
<h1>Solution</h1> <p>To convert (<em>reformat</em>) your date columns as <code>MM/YYYY</code>, all you need to do is:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;Your_Column_Name&quot;].dt.strftime('%m/%Y') </code></pre> <blockquote> <p>See <strong>Section-A</strong> and <strong>Section-B</strong> for ...
python|python-3.x|pandas
0
367,374
64,791,537
'numpy.ndarray' object has no attribute 'value'
<p>My working code has suddenly stopped working today because of this error. Can someone please help me in solving this?</p> <pre><code>style = Styler(bg_color = 'red',font_size=10) sf = StyleFrame(filtered_data) #Getting Error at following line: sf.apply_column_style(cols_to_style=filtered_data.columns.to_list(),style...
<p>The data is too big to be able to be taken dump. I finally managed to take its csv and while, I was taking its screenshot to show here, I noticed that one column name was mentioned twice. I think, That is why the error occurred! I am looking at the file carefully to see if I find more such columns. Thanks for findin...
python|python-3.x|pandas|numpy|styleframe
0
367,375
64,834,856
Groupby to count the number of calls on different days by id
<p>Given a dataframe like the one below:</p> <pre><code>df = pd.DataFrame({'date': ['2013-04-19', '2013-04-19', '2013-04-20', '2013-04-20', '2013-04-19'], 'id': [1,2,2,3,1]}) </code></pre> <p>I need to create another dataframe containing only the id and the number of calls made on different days. An examp...
<p>You can make use of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nunique.html" rel="nofollow noreferrer"><strong><code>.nunique()</code></strong> [pandas-doc]</a> to count the <em>unique</em> days per id:</p> <pre><code>table.groupby('id').date<b>.nunique()</b></code></pre> <p...
python|pandas
3
367,376
65,028,895
Ensemble with voting in deep learning models
<p>I am working on a multimodal deep learning classifiers with RGB-D images. i have developed two seperate models for each case. The first one is a LSTM with CNN in the begining for the RGB images with shape <code>(3046,200,200,3)</code> , and the second one is an LSTM for the depth images with shape <code>(3046,200,2...
<p>You have two classifier, in that cases directly voting does not make sense because how to resolve the ties?</p> <p>Since you are doing np.argmax on models' prediction, I believe the models output probabilities as a prediction. If you can not introduce a third model, you can average out these probabilities and then t...
python|tensorflow|machine-learning|keras|deep-learning
1
367,377
64,868,284
Alternatives to .apply() to increase performance speed
<p>I wrote a function that cleans the text of a given string. And I apply this function to a column in a dataframe(~ 1 million records).</p> <pre><code>from cleanco import cleanco import re import pandas as pd import unidecode def clean_name(text): #convert plain text to utf-8 text = unidecode.unidecode(te...
<p>This isn't the best solution, but one approach to reduce the time processing is the concatenation of the replace method.</p> <pre><code>import re text = text.upper() text = re.sub('[()]', '', text) text = text.replace(',' , '').replace(' - ', ' ').replace(r&quot;\(.*\)&quot;,&quot;&quot;).replace(' AND ', ' &amp; '...
python|regex|pandas
1
367,378
64,927,522
How tot get back from numpy datetime array to datetime?
<p>tried to write a simple programme for get the most vacation between two dates. E.g. for 2021, if wednesday is public holiday, you could get 9 free days with taking 4 holidays.</p> <p>..everything okay, my idea was:</p> <p>create busdaycalender, start, end, arange it and count all free days in a bool array and return...
<p>I now did it that way.</p> <pre><code>def get_vacation(list_dates): #get the dates of weekends and predefined vacation of a list containing dates #input: list of dates #outout: list with dates of weekends + vacations #indexlist of weekend+vacations ind=[index for index,value in enumerate(list_dat...
python|numpy|datetime
0
367,379
64,961,142
Append array and a scalar value to a numpy array
<p>I am trying to a append a numpy array and a scalar value to a numpy array.</p> <pre><code>logf= np.array([20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160]) logf = np.append(logf, [[logf*10], [logf*100]]) logf = np.append(logf, 20000) </code></pre> <p>In order to append a scalar value I am appending it using a second app...
<p>You're probably looking for <code>.concatenate()</code>:</p> <pre><code>import numpy as np logf = np.array([20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160]) logf = np.concatenate((logf, logf * 10, logf * 100, [20000])) print(logf) </code></pre> <p>Result:</p> <pre><code>[ 20. 25. 31.5 40. 50. 63. ...
python|numpy|append
0
367,380
39,983,835
Can python setup.py install use wheels?
<p>I am using setuptools. Is there a way to have the following command use wheels instead of source?</p> <pre><code>python setup.py install </code></pre> <p>In particular, I have a custom package that requires pandas. While pandas installs perfectly fine with pip (because it grabs the wheel), pandas won't install wh...
<p>One solution is to use <code>pip</code> to install you project. <code>pip</code> is able to handle your <code>setup.py</code> correctly and will use wheels by default if available.</p> <p>So you can try to replace:</p> <p><code>python setup.py install</code> by <code>pip install .</code></p> <p>That should work.<...
python|pandas|setuptools
6
367,381
40,136,428
Python: How to filter a DataFrame of dates in Pandas by a particular date within a window of some days?
<p>I have a DataFrame of dates and would like to filter for a particular date +- some days.</p> <pre><code>import pandas as pd import numpy as np import datetime dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="D") df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power']) </...
<p>The function I created to accomplish this is <code>filterDaysWindow</code> and can be used as follows:</p> <pre><code>import pandas as pd import numpy as np import datetime dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="D") df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns...
python|date|datetime|pandas|dataframe
1
367,382
40,137,372
Concatinating multiple Data frames of different length
<p>I have 88 different dataFrame of different lengths, which I need to concatenate. And its all are located in one directory and I used the following python script to produce such a single data frame.</p> <p>Here is what I tried,</p> <pre><code> path = 'GTFS/' files = os.listdir(path) files_txt = [os.path....
<p>The key is to make a <code>list</code> of different data-frames and then concatenate the list instead of individual concatenation.</p> <p>I created 10 <code>df</code> filled with random length data of one column and saved to <code>csv</code> files to simulate your data.</p> <pre><code>import pandas as pd import nu...
python|pandas|numpy|dataframe
3
367,383
40,269,699
Tensorflow textsum model- different source and target vocabs
<p>I want to use the textsum model for tagging named entities. Hence the target size vocab is very small. While training there doesn't seem to be an option to provide different vocabs on the encoder and on the decoder side-or is there? See <a href="https://github.com/tensorflow/models/blob/199db00e33a9c116c8d6a07f3724...
<p>No there is no out-of-the-box option to use the textsum in this way. I don't see any reason why it shouldn't be possible to modify the architecture to achieve this, though. Would be interested if you pointed towards some literature on using seq2seq w/attention models for NER</p>
tensorflow
0
367,384
40,069,151
count the number of groups of consecutive digits in a series of strings
<p>consider the <code>pd.Series</code> <code>s</code></p> <pre><code>import pandas as pd import numpy as np np.random.seed([3,1415]) p = (.35, .35, .1, .1, .1) s = pd.DataFrame(np.random.choice(['', 1] + list('abc'), (10, 20), p=p)).sum(1) s 0 11111bbaacbbca1 1 1bab111aaaaca1a 2 11aaa1b11a11a11 3 1ca11...
<p><strong>UPDATE:</strong> the idea is first to replace all consecutive groups of digist with single <code>1</code> and then delete everything which is not <code>1</code> and finally get the length of the changed string:</p> <pre><code>In [159]: s.replace(['\d+', '[^1]+'], ['1', ''], regex=True).str.len() Out[159]: 0...
python|pandas
4
367,385
39,992,985
Questions on pandas moving average
<p>I am a beginner of python and pandas. I am having difficulty with making volatility adjusted moving average, so I need your help.</p> <p>Volatility adjusted moving average is a kind of moving average, of which moving average period is not static, but dynamically adjusted according to volatility.</p> <p>What I'd li...
<p>first of all: you need to calculate <code>pct_change</code> on <code>price</code> to calculate <code>volatility</code> of <code>returns</code></p> <p><strong><em>my solution</em></strong></p> <pre><code>def price(stock, start): price = web.DataReader(name=stock, data_source='yahoo', start=start)['Adj Close'] ...
python|pandas
2
367,386
39,903,090
Efficiently replace values from a column to another column Pandas DataFrame
<p>I have a Pandas DataFrame like this: </p> <pre><code> col1 col2 col3 1 0.2 0.3 0.3 2 0.2 0.3 0.3 3 0 0.4 0.4 4 0 0 0.3 5 0 0 0 6 0.1 0.4 0.4 </code></pre> <p>I want to replace the <code>col1</code> values with the values in the second column (<code>col2</code>) only if <code>c...
<p>Using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer"><code>np.where</code></a> is faster. Using a similar pattern as you used with <code>replace</code>:</p> <pre><code>df['col1'] = np.where(df['col1'] == 0, df['col2'], df['col1']) df['col1'] = np.where(df['col1'] ==...
python|pandas|replace|dataframe
55
367,387
40,186,711
Variable initialization error in Tensorflow
<p>I am following a TensorFlow tutorial and running the below code but running into Variable initialization error:</p> <pre><code>num_points = 1000 vectors_set = [] for i in range(num_points): x1= np.random.normal(0.0, 0.55) y1= x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03) vectors_set.append...
<p>Lovely ... a crash confession, rather than an error message. I suspect that something in your set-up left one of your formal TF variables hanging, probably one of the one-letter names. To debug, I suggest that you insert a simple <strong>print</strong> statement after each initialization to report the value comput...
python|tensorflow
2
367,388
40,032,371
Pandas Date Range Monthly on Specific Day of Month
<p>In Pandas, I know you can use anchor offsets to specify more complicated reucrrences: <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offset" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offset</a></p> <p>I want to specify a date_range such that...
<p>IIUC you can do it this way:</p> <pre><code>In [18]: pd.DataFrame(pd.date_range('2016-01-01', periods=10, freq='MS') + pd.DateOffset(days=26), columns=['Date']) Out[18]: Date 0 2016-01-27 1 2016-02-27 2 2016-03-27 3 2016-04-27 4 2016-05-27 5 2016-06-27 6 2016-07-27 7 2016-08-27 8 2016-09-27 9 2016-10-27 </c...
python|datetime|pandas
10
367,389
40,074,732
Converting datetime to pandas index
<p>My pandas dataframe is structured as follows:</p> <pre><code> date tag 0 2015-07-30 19:19:35-04:00 E7RG6 1 2016-01-27 08:20:01-05:00 ER57G 2 2015-11-15 23:32:16-05:00 EQW7G 3 2016-07-12 00:01:11-04:00 ERV7G 4 2016-02-14 00:35:21-05:00 EQW7G 5 2016-03-01 ...
<p>If your <code>dtype</code> for a column is already <code>datetime</code> then you can just call <code>set_index</code> without the need to try to construct a <code>DatetimeIndex</code> from the column:</p> <pre><code>df.set_index(df['date'], inplace=True) </code></pre> <p>should just work, the dtype for the index ...
python-2.7|pandas
1
367,390
39,964,852
How to sum data field(s) for records with duplicate Key1 Key2 pairs, and end up with records with unique Key1 Key2 pairs
<p>Given a dataframe with an unspecified number of records with duplicate key1 &amp; key2 pairs, but not necessarily the same data. (I.e. The combination of Key1 and Key2 is non-unique.) I need to add the respective data columns for the duplicated records and end up with records that have unique key1 &amp; key2 values...
<p>as MaxU said, you could use <code>groupby</code> and then the <code>sum()</code> method such has:</p> <pre><code>frame.groupby(['key1', 'key2'])['data'].sum().reset_index() Out[12]: key1 key2 data 0 1 2 11 1 2 2 17 2 3 1 2 3 3 4 6 </code></pre>
pandas|dataframe|sum|duplicates|key
1
367,391
39,938,307
Determinism in tensorflow gradient updates?
<p>So I have a very simple NN script written in Tensorflow, and I am having a hard time trying to trace down where some "randomness" is coming in from. </p> <p>I have recorded the </p> <ul> <li>Weights, </li> <li>Gradients, </li> <li>Logits</li> </ul> <p>of my network as I train, and for the first iteration, it is c...
<p>There's a good chance you could get deterministic results if you run your network on CPU (<code>export CUDA_VISIBLE_DEVICES=</code>), with single-thread in Eigen thread pool (<code>tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=1)</code>), one Python thread (no multi-threaded queue-runners that you ge...
random|floating-point|tensorflow|precision|random-seed
9
367,392
40,209,520
daily data, resample every 3 days, calculate over trailing 5 days efficiently
<p>consider the <code>df</code></p> <pre><code>tidx = pd.date_range('2012-12-31', periods=11, freq='D') df = pd.DataFrame(dict(A=np.arange(len(tidx))), tidx) df </code></pre> <p>I want to calculate the sum over a trailing 5 days, every 3 days.</p> <p>I expect something that looks like this</p> <p><a href="https://i...
<p>the df you gave us is :</p> <pre><code> A 2012-12-31 0 2013-01-01 1 2013-01-02 2 2013-01-03 3 2013-01-04 4 2013-01-05 5 2013-01-06 6 2013-01-07 7 2013-01-08 8 2013-01-09 9 2013-01-10 10 </code></pre> <p>you could create your rolling 5-day sum series and then resample it. I can't th...
python|pandas|numpy
12
367,393
39,699,312
How to check whether particular column completely match or not
<p>I would like to compare particular column with the other one. For instance,when I compare A column with B by using some method, it should return False.</p> <pre><code> A B 0 1 2 1 2 2 2 3 3 3 4 4 </code></pre> <p>when I try</p> <pre><code>df.A==df.B </code></pre> <p>But this returns whether ...
<p>You can use <code>equals</code>:</p> <pre><code>df['A'].equals(df['B']) Out: False </code></pre> <p>This checks whether two Series are exactly the same - labels included.</p>
python|pandas|dataframe
6
367,394
39,770,171
When to stop CNN learning
<p>In tensorflow, I used to execute cnn learning for fixed number of epochs and save checkpoints in between after specified number of epochs interval. For evaluating the model, the checkpoints are restored and perform prediction on the validation dataset. </p> <p>I want to automate the learning process, instead of us...
<p>First for the number of iterations you can exit the training if your loss stopped improving on the batch i.e. if the difference between two loss values AVERAGED accross batches (to reduce batch fluctuations) is less than a determined threshold.</p> <p>But you probably realized that the threshold is an hyperparamete...
neural-network|tensorflow|conv-neural-network
1
367,395
39,536,940
Filtering a pandas dataframe based on a match to partial strings
<p>I have a pandas dataframe that contains strings of varying length and characters.</p> <p>For example:</p> <pre><code>print df['name'][0] print df['name'][1] print df['name'][2] print df['name'][3] </code></pre> <p>would return something like this:</p> <pre><code>UserId : Z5QF1X33A loginId : test.user UserId : 00...
<p>try this:</p> <pre><code>In [31]: df.name.str.extract(r'\b(?:UserId|loginId)\s*:\s*\b([^\s]+)\b', expand=True) Out[31]: 0 0 Z5QF1X33A 1 test.user 2 0000012348 3 Z5QF1X33A </code></pre>
python|regex|string|pandas|split
0
367,396
39,610,165
Does it harm if I use TensorFlow without an isolated python environment?
<p>I have installed TensorFlow using <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#anaconda-installation" rel="nofollow">Anaconda Installation</a>. </p> <p>During the installation, after sourcing into the 'tensorflow' environment (create by <em>conda</em>), I used <strong>pip in my anaco...
<p>If it works well for you, that's good, but in general this isn't an approach we test extensively or support, so your mileage may vary!</p>
tensorflow
0
367,397
39,786,406
How to match multiple columns in pandas DataFrame for an "interval"?
<p>I have the following pandas DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame('filename.csv') print(df) order start end value 1 1342 1357 category1 1 1459 1489 category7 1 1572 1601 category23 1 1587 1599 category2 1 1591 1639...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>, but if <code>DataFrames</code> are large, sca...
python|pandas|dataframe|match|intervals
3
367,398
39,598,371
Calculate mean of array with specific value from another array
<p>I have these numpy arrays:</p> <pre><code>array1 = np.array([-1, -1, 1, 1, 2, 1, 2, 2]) array2 = np.array([34.2, 11.2, 22.1, 78.2, 55.0, 66.87, 33.3, 11.56]) </code></pre> <p>Now I want to return a 2d array in which there is the mean for each distinctive value from array1 so my output would look something like thi...
<p>This is a typical grouping operation, and the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) provides extensions to numpy to perform these type of operations efficiently and concisely:</p> <pre><code>import numpy_indexed as n...
python|arrays|performance|numpy
3
367,399
39,620,501
How to iterate over the rows, columns and planes of a tensor?
<p>I'm trying to iterate over the output tensor in a custom operator. So far I only see the approach to flatten the tensor and iterate over it.</p> <p>Is there a better way so I can iterate over the rows, columns and planes?</p> <pre><code>auto output = output_tensor-&gt;flat&lt;float&gt;(); // I would like to itera...
<p>The Eigen Tensor library is documented ate the bottom of this page:</p> <p><a href="https://bitbucket.org/eigen/eigen/src/f6382682565c946d46612fe0e36e486bba1371ce/unsupported/Eigen/CXX11/src/Tensor/?at=default" rel="nofollow">https://bitbucket.org/eigen/eigen/src/f6382682565c946d46612fe0e36e486bba1371ce/unsupported...
c++|tensorflow
0