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
11,300
57,234,478
rearrange name order in pandas column
<p><strong>Background</strong></p> <p>I have the following <code>df</code></p> <pre><code>import pandas as pd df= pd.DataFrame({'Text' : ['Hi', 'Hello', 'Bye'], 'P_ID': [1,2,3], 'Name' :['Bobby,Bob Lee Brian', 'Tuck,Tom T ', 'Mark, Marky '], ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace</code></a> with values before and after <code>,</code>, <code>\s*</code> means there are optionally whitespace after <code>,</code>:</p> <pre><code>df['Rearranged...
python-3.x|string|pandas|split|apply
1
11,301
57,287,719
How to extract certain string from a text?
<p>I have a certain feature "Location" from which I want to extract country.</p> <p>The feature looks like:</p> <pre><code>data['Location'].head() 0 stockton, california, usa 1 edmonton, alberta, canada 2 timmins, ontario, canada 3 ottawa, ontario, canada 4 n/a, n/a, n/a Name: Location,...
<p>You can also use regex patterns:</p> <pre><code>df['Country'] = df['Location'].str.split('(,\s)(\w+)$', n = 1, expand = True)[2] </code></pre> <p>Output:</p> <pre><code>df['Country'].head(3) Out[111]: 0 usa 1 canada 2 canada Name: country, dtype: object </code></pre>
python|pandas
2
11,302
57,283,084
Keras Multi_GPU_Model: Slow like Molasses
<p>I am investigating Keras for multi gpu modeling. So before I invest time on it, I tried out a simple skipgram model on a 4 gpu instance from lambdalabs.</p> <p>The one gpu performance, is slightly worse than on Kaggle's kernel (the number of cores are smaller on lambda labs gpus).</p> <p>But the multi gpu perform...
<p>when <code>use_multiprocessing=True</code> and <code>workers&gt;0</code>, keras will use multiprocess to generate your data in cpu and feed them to gpu.</p>
python|tensorflow|keras|multi-gpu
0
11,303
56,938,467
Pandas - First find header, then only load certain columns on an Excel sheet
<p>I am trying to read multiple large Excel files with Pandas and combine them into a single CSV and only need data from one data sheet from each file. </p> <p>Within this data sheet, there are a number of filler rows that I do not need data from - basically, the data that I need starts at different places in each fil...
<p>You can tell Pandas to just load the first <code>20</code> rows (assuming your header is there). You can then locate the <code>Row Labels</code> value and then use this location to load the whole Excel file. For example:</p> <pre><code>import pandas as pd filename = 'input.xlsx' sheet = 'Sheet1' df = pd.read_exce...
python|excel|pandas|csv
1
11,304
46,044,437
Loading large numpy matrix as partitioned variable in tensorflow graph
<p>Imagine that i have big pretrained embeddings, which i can load as numpy array, for example with shape [3000000, 200]. Size of this matrix is greater than 2GB, so with this code:</p> <pre><code>data = np.zeros(shape=(3000000, 200)) variable = tf.get_variable( "weigths", [3000000, 200], initializer=tf.co...
<p><strong>SOLUTION</strong></p> <p>this is ugly, but it works:</p> <pre><code>def init_partitioned(session, var_name, data): partitioned_var = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=var_name + "/part_\d+:0") print("For {} founded {} parts".format(var_name, len(partitioned_var))) dtype = ...
tensorflow
4
11,305
45,910,491
Python Pandas Fill Dataframe with another DataFrame
<p>I have a dataframe </p> <pre><code>x = pd.DataFrame(index = ['wkdy','hr'],columns=['c1','c2','c3']) </code></pre> <p>This leads to 168 rows of data in the dataframe. 7 weekdays and 24 hours in each day. I have another dataframe</p> <pre><code>dates = pd.date_range('20090101',periods = 10000, freq = 'H') y = DataF...
<p>Your dataframe x doesn't have 168 rows but looks like</p> <pre><code> c1 c2 c3 wkdy NaN NaN NaN hr NaN NaN NaN </code></pre> <p>and you can't index it using a tuple like in <code>x.loc[(w,h)]</code>. What you probably had in mind was something like</p> <pre><code>x = pd.DataFrame( index=pd.Mu...
python|pandas|dataframe
0
11,306
35,597,333
Resample withing a specified interval in Pandas?
<p><strong>Update: I have updated my example to clarify my question a bit</strong><br> I have a data frame with a date index and a value, like: </p> <pre><code> date | value | ------------+-------| category A 2016-01-04 | 6 | 2016-01-05 | 4 | 2016...
<p>I believe you want to specify your start and end dates and then reindex your resampled data (Pandas 0.17+).</p> <pre><code># Sample data. df = pd.DataFrame({'a': range(5), 'b': range(5)}, index=pd.DatetimeIndex(start='2016-1-1', periods=5, freq='D')) idx = pd.DatetimeIndex(start='2016-1-1', end='2016-2-29', freq='...
python|datetime|pandas
3
11,307
35,732,254
slice a 3d numpy array using a 2d numpy array
<p>Is it possible to slice a 3d array using a 2d array. Im assuming it can be done but would require that you have to specify the axis?</p> <p>If I have 3 arrays, such that:</p> <pre><code>A = [[1,2,3,4,5], [1,3,5,7,9], [5,4,3,2,1]] # shape (3,5) B1 = [[1], [2], [3]] # shape (3, 1) B2 = [[4],...
<p>Numpy is optimized for homogeneous arrays of numbers with fixed dimensions, so it does not support varying row or column sizes.</p> <p>However you can achieve what you want by using a list of arrays:</p> <pre><code>Out = [A[i, B1[i]:B2[i]+1] for i in range(len(B1))] </code></pre>
python|arrays|numpy|slice
4
11,308
35,344,648
Why can't I apply value to entire pandas column after subsetting my data frame by two conditions?
<p>I've got a data frame with three columns, representing Year, Name, and Year_2</p> <p>I'd like to change the value of the Year_2 column based on Year and Name, like such:</p> <p><code>(df[(df['Year']==1980) &amp; (df['Name'].str.contains("John"))])['Year_2']=2010</code></p> <p>I thought this would be the same thin...
<p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a>:</p> <pre><code>df.loc[(df['Year']==1980) &amp; (df['Name'].str.contains("John")),'Year_2'] = 2010 </code></pre>
python|pandas
1
11,309
28,584,422
Python3 Pandas column in seconds
<p>I have this .csv file containing data looking like this</p> <pre><code>"Time","CH-1[V]","CH-2[V]","CH-3[V]", 0.000000000E+00,-4.07000E-01, 3.01000E-01,-4.40000E-01, 1.000000000E+01,-4.11000E-01, 3.01000E-01,-4.29000E-01, 2.000000000E+01,-3.99000E-01, 3.01000E-01,-4.15000E-01, 3.000000000E+01,-3.87000E-01, 3.010...
<pre><code>In [9]: df = pd.read_csv(StringIO(data), index_col=0) In [10]: df Out[10]: CH-1[V] CH-2[V] CH-3[V] Unnamed: 4 Time 0 -0.407 0.301 -0.440 NaN 10 -0.411 0.301 -0.429 NaN 20 -0.399 0.301 -0.415 NaN 30 -0.387 0.301 -0.409 NaN 40 -...
python|datetime|csv|python-3.x|pandas
1
11,310
28,576,540
How can I normalize the data in a range of columns in my pandas dataframe
<p>Suppose I have a pandas data frame surveyData:</p> <p>I want to normalize the data in each column by performing:</p> <pre><code>surveyData_norm = (surveyData - surveyData.mean()) / (surveyData.max() - surveyData.min()) </code></pre> <p>This would work fine if my data table only contained the columns I wanted to n...
<p>You can perform operations on a sub set of rows or columns in pandas in a number of ways. One useful way is indexing:</p> <pre><code># Assuming same lines from your example cols_to_norm = ['Age','Height'] survey_data[cols_to_norm] = survey_data[cols_to_norm].apply(lambda x: (x - x.min()) / (x.max() - x.min())) </co...
python|pandas
40
11,311
51,013,667
Understanding python slice syntax
<pre><code>N = 100 # number of points per class D = 2 # dimensionality K = 3 # number of classes X = np.zeros((N*K,D)) y = np.zeros(N*K, dtype='uint8') for j in xrange(K): ix = range(N*j,N*(j+1)) r = np.linspace(0.0,1,N) # radius t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta X[ix] = np.c_[r*np...
<p>X is not a builtin python list. It's a numpy array. Have a look at the documentation for <code>zeros</code> <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.zeros.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.zeros.html</a></p> <p>and ind...
python|numpy|slice
1
11,312
9,588,331
Simple cross-tabulation in pandas
<p>I stumbled across <a href="http://pandas.pydata.org/" rel="noreferrer">pandas</a> and it looks ideal for simple calculations that I'd like to do. I have a SAS background and was thinking it'd replace proc freq -- it looks like it'll scale to what I may want to do in the future. However, I just can't seem to get my h...
<blockquote> <p><strong><code>v0.21</code> answer</strong></p> </blockquote> <p>Use <code>pivot_table</code> with the <code>index</code> parameter: </p> <pre><code>df.pivot_table(index='category', aggfunc=[len, sum]) len sum value value category AB 2 300 AC 1...
python|pandas|dataframe|pivot-table
17
11,313
6,170,158
Is it possible to use numpy.argmax with a custom field of objects in a list?
<p>Something like:</p> <pre><code>class Test: def __init__(self, n): self.id = n def __str__(self): return str(self.id) my_list = [] my_list.append(Test(1)) my_list.append(Test(2)) my_list.append(Test(3)) </code></pre> <p>Would it be possible to get the element in the list with the maximum o...
<p>You wouldn't even need to resort to <code>numpy.argmax()</code> in your example. Since your objects are in a standard Python list, you can also use Python's built-in <code>max()</code> function:</p> <pre><code>index = max(range(len(my_list)), key=lambda i: my_list[i].id) </code></pre> <p>or</p> <pre><code>index ...
python|numpy
3
11,314
66,452,346
how to get a mean of a "value" column split into groups based on the value of another column
<p>I want to take a simple dataframe, sum a column (&quot;value&quot; column) into groups - based on the value in another column (&quot;name&quot; column). After that, I want to get a mean of that &quot;value&quot; column</p> <pre><code>In [1]: import pandas In [2]: df = pandas.DataFrame(data = [{'name': 'a', 'val': 1...
<p>For first only aggregate <code>mean</code>:</p> <pre><code>df1 = df.groupby('name', as_index=False)['val'].mean() print (df1) name val 0 a 1 1 b 3 </code></pre> <p>For second aggregate <code>sum</code> and <code>mean</code> in names aggregation by <a href="http://pandas.pydata.org/pandas-docs/stable/r...
python|pandas
1
11,315
66,754,532
replace NaN with random values from a range
<p>I am using this code to replace NaN with random values from a range</p> <pre><code>import numpy as np def processNan (x): return np.random.choice([1.0, 2.0]) assure['codeTypePieceIdentite'] = assure['codeTypePieceIdentite'].apply(lambda x: processNan(x) if x is nan else x) </code></pre> <p>its not working for s...
<p>Always avoid using <code>.apply</code> when possible, it is not an optimal solution since it does not take advantage of vectorization. In this case, you can do something like this:</p> <pre><code>mask = df[&quot;codeTypePieceIdentite&quot;].isna() df.loc[mask, &quot;codeTypePieceIdentite&quot;] = np.random.choice([1...
python|pandas|dataframe|random|jupyter-notebook
3
11,316
66,648,432
Pytorch: test loss becoming nan after some iteration
<p>I am trying to train a deep learning architecture, the model trains perfectly. I am testing after each epoch. For 7 epoch all the loss and accuracy seems okay but at 8 epoch during the testing test loss becomes nan. I have checked my data, it got no nan. Also my test accuracy is higher than train which is weird. Tra...
<p>Assuming that a very high learning rate isn't the cause of the problem, you can clip your gradients before the update, using PyTorch's <code>gradient clipping</code>.</p> <p>Example:</p> <pre><code>optimizer.zero_grad() loss, hidden = model(data, hidden, targets) loss.backward() torch.nn.utils.clip_grad_nor...
deep-learning|pytorch
2
11,317
57,631,847
ImportError when importing numpy under Spyder from within a Python 3.7 conda environment
<p>I have created a conda environment named <code>python3</code> on my Ubuntu virtual machine using:</p> <pre class="lang-sh prettyprint-override"><code>conda create -n python3 python=3.7 </code></pre> <p>I have installed several packages under this environment, including numpy. When typing <code>conda list</code>, n...
<p>The apt-get installation of Spyder does not know about your conda environment. You should use conda to install Spyder to the environment. Activate the environment, then launch Spyder.</p> <pre><code>conda install -n python3 spyder conda activate python3 spyder </code></pre>
python|numpy|conda|spyder|environment
3
11,318
57,442,975
Absurd loss and metric values when using flow_from_directory
<p>I am trying to train a UNet for image segmentation in <code>keras</code> using the following custom loss function and metric:</p> <pre class="lang-py prettyprint-override"><code>def dice_coef(y_true, y_pred): ''' Params: y_true -- the labeled mask corresponding to an rgb image y_pred -- the pred...
<p>Thanks to the insight by @today, I realized both the images and the masks were being loaded as arrays with values ranging from 0 to 255. So I added a preprocessing function to normalize them, which solved my problem:</p> <pre class="lang-py prettyprint-override"><code>image_datagen = ImageDataGenerator(preprocessin...
python|tensorflow|machine-learning|keras
0
11,319
57,630,132
Extracting thumbnails from an image in numpy
<p>I have a weird question, it concerns slicing arrays and extract small thumbnail cutouts. I do have a solution, but it's a chunky for loop which runs fairly slowly on big images.</p> <p>The current solution looks something like this:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np image = np...
<p>Reshape to <code>4D</code>, permute axes, reshape again -</p> <pre><code>H,W = 10,10 # height,width of thumbnail imgs m,n = image.shape cutouts = image.reshape(m//H,H,n//W,W).swapaxes(1,2).reshape(-1,H,W) </code></pre> <p><a href="https://stackoverflow.com/a/47978032/"><code>More info on the intuition behind...
python|numpy
2
11,320
24,101,525
pandas vectorized string replace by index
<p>Trying to change the first two characters in a pandas column string.</p> <pre><code>def shift(x): x=list(x) x[0] = '1' x[1] = '9' print x #this prints the correct result as list ##str(x) return ''.join(x) ## this works mc_data['timeshift'] = mc_data['realtime'].map(lambda x: shift(x) ) </code></pre> <p>output is...
<p>Instead of replacing the first two characters, you could build new strings:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({"A": ['abcd']*4}) &gt;&gt;&gt; df A 0 abcd 1 abcd 2 abcd 3 abcd &gt;&gt;&gt; df["A"] = "19" + df["A"].str[2:] &gt;&gt;&gt; df A 0 19cd 1 19cd 2 19cd 3 19cd </code></pre>
python|pandas
0
11,321
43,855,685
Python Pandas: Check if string in one column is contained in string of another column in the same row
<p>I have a dataframe like this:</p> <pre><code>RecID| A |B ---------------- 1 |a | abc 2 |b | cba 3 |c | bca 4 |d | bac 5 |e | abc </code></pre> <p>And want to create another column, C, out of A and B such that for the same row, if the string in column A is contained in the string of co...
<p>You need <code>apply</code> with <code>in</code>:</p> <pre><code>df['C'] = df.apply(lambda x: x.A in x.B, axis=1) print (df) RecID A B C 0 1 a abc True 1 2 b cba True 2 3 c bca True 3 4 d bac False 4 5 e abc False </code></pre> <p>Another solution with <code>l...
python|pandas
61
11,322
43,905,595
How to apply pandas.qcut as part of the sqlalchemy query in python?
<p>I am querying the table which returns specific columns, and based on these column values I need to update another column by checking the condition.<br> How can I apply <code>qcut</code> directly in sqlalchemy query? Is it possible?</p> <p>My quartile thresholds are:</p> <pre><code>2 -- A(updatable value) 4 -- B 5 ...
<p>You can do this with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a> (rather than quartile <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>qcut</code></a>):</p> <pre><cod...
python|mysql|pandas|dataframe|sqlalchemy
0
11,323
43,702,323
How to load only specific weights on Keras
<p>I have a trained model that I've exported the weights and want to partially load into another model. My model is built in Keras using TensorFlow as backend.</p> <p>Right now I'm doing as follows:</p> <pre><code>model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=input_shape, trainable=False)) model.add(A...
<p>If your first 9 layers are consistently named between your original trained model and the new model, then you can use <code>model.load_weights()</code> with <code>by_name=True</code>. This will update weights only in the layers of your new model that have an identically named layer found in the original trained mod...
machine-learning|tensorflow|keras|conv-neural-network
44
11,324
72,840,258
Concatenating dataframes along the column axis with identical indexes containing duplicate indices
<p>Is it expected behaviour that no error is raised when concatenating dataframes with identical indexes which contain duplicate indices? Can I rely on this?</p> <p>For example,</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df_A = pd.DataFrame(index=[0, 0], ... data=[0, 1], ... ...
<p><code>pandas.concat</code> is clever enough to correctly align the indices in that case.</p> <p>However, if there is a different number of duplicated indices between the two DataFrames, it will complain, e.g.</p> <pre><code>&gt;&gt;&gt; df_A = pd.DataFrame(index=[0, 0, 0], data=[0, 1, 4], ...
python|pandas
0
11,325
10,457,584
Redefining the Index in a Pandas DataFrame object
<p>I am trying to re-index a pandas <code>DataFrame</code> object, like so,</p> <pre><code>From: a b c 0 1 2 3 1 10 11 12 2 20 21 22 To : b c 1 2 3 10 11 12 20 21 22 </code></pre> <p>I am going about this as shown below and a...
<p>Why don't you simply use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#add-an-index-using-dataframe-columns" rel="noreferrer"><code>set_index</code></a> method?</p> <pre><code>In : col = ['a','b','c'] In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col) In : data Out: a b ...
python|pandas|dataframe
190
11,326
3,835,083
Numpy csv script gives 'ValueError: setting an array element with a sequence'
<p>I have a python script that successfully loads a csv file into a 2d numpy array and which then successfully extracts the value of a desired cell based on its column and row header values. For diagnostic purposes, I have the script print the contents of the data matrix before it is put into a numpy array. The scrip...
<p>found the answer. I needed to change the following line of code:</p> <pre><code>data = [[] for dummy in xrange(11)] </code></pre> <p>xrange needed to be set to 11 and not to 13.</p> <p>simple answer, but it took a lot of digging. this thread is answered/finished now.</p>
python|arrays|csv|numpy
3
11,327
70,476,228
ValueError: Input 0 of layer "sequential_41" is incompatible with the layer: expected shape=(None, 70, 23, 1), found shape=(None, 23, 1)
<p><strong>The X_train shape is 70,23,1</strong> When i fit my model a have a vallueError:&quot;Input 0 of layer &quot;sequential_41&quot; is incompatible with the layer: expected shape=(None, 70, 23, 1), found shape=(None, 23, 1)&quot;</p> <pre><code>import tensorflow.keras as keras input_shape=(X_train.shape[0],X_tr...
<p>Problem is with your input_shape</p> <p><strong>Working sample code</strong></p> <pre><code>import tensorflow.keras as keras from tensorflow.keras import datasets (train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data() train_images, test_images = train_images / 255.0, test_images / ...
python|tensorflow|keras|conv-neural-network
0
11,328
70,702,577
Fill empty columns with values from another column of another row based on an identifier
<p>I am trying to fill a dataframe, containing repeated elements, based on an identifier. My Dataframe is as follows:</p> <pre><code> Code Value 0 SJHV 1 SJIO 96B 2 SJHV 33C 3 CPO3 22A 4 CPO3 22A 5 SJHV 33C #&lt; -- Numbers stored as strings 6 TOY 7 TOY #&lt; -- These ...
<p>The empty strings should go to the bottom if you sort them, then you can just drop duplicates.</p> <pre><code>import pandas as pd df = pd.DataFrame({'Code':['SJHV','SJIO','SJHV','CPO3','CPO3','SJHV','TOY','TOY'],'Value':['','96B','33C','22A','22A','33C','','']}) df = ( df.sort_values(by=['Value'], ascending=Fals...
python|python-3.x|pandas
1
11,329
70,452,495
Pandas: Add columns by values of another dataframe
<p>This is quite a weird question, but I don't come along with it.</p> <p>I do have two dataframes, named df1 and df2. There structure is:</p> <pre><code>df1: Eval Lang Average Model df2: Eval Lang Mean </code></pre> <p>The model column has exactly six different values available and there exists exactly...
<p>You can <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> <code>df2</code> to get the values from the <code>Model</code> column as the new columns and the values from the <code>Average</code> column as the new values:</p> <pre><code>df...
python-3.x|pandas|dataframe|join
1
11,330
70,407,960
CSV reading with pandas doesn't return expected value
<p>I've been trying to search for a specific keyword in a specific CSV column and print the value found, although when I get the print it returns the whole row.</p> <p>I have tried the <code>data.filter</code> function command I didn't have much luck.</p> <p>What I plan to do is:</p> <ol> <li>Get to the right column</l...
<p>From the comments:</p> <p>Use</p> <pre><code>print(*keyword[&quot;Size&quot;], sep='\n') </code></pre> <hr /> <p>If you want to store the results in a variable you can use</p> <pre><code>lst = [*keyword[&quot;Size&quot;]] </code></pre> <p>or even better,</p> <pre><code>lst = keyword['Size'].tolist() </code></pre>
python|pandas|csv
1
11,331
42,987,549
Using numpy to make an average over multiple files
<p>I am pretty new to Python and want to use <code>numpy</code> to make an average over multiple files. I have seen some similar questions but I am not familiar enough with python yet to use it for my goal.</p> <p>The Situation:</p> <p>I have a loop which creates in each step 101 <code>.dat</code> files. Those files ...
<p>So if I get this right you have 101 steps with 101 .dat files each ranging from 0_00000.dat to 100_00100.dat and you want to calculate the average of each row for each of the 101 .dat files in each step, resulting in 101 .dat files with 10 lines each containing the averages of the respective rows of all .dat files f...
python|arrays|loops|numpy
1
11,332
43,010,969
numpy matrix. move all 0's to the end of each row
<p>Given a matrix in python numpy which has for some of its rows, leading zeros. I need to shift all zeros to the end of the line. E.g.</p> <pre><code>0 2 3 4 0 0 1 5 2 3 1 1 </code></pre> <p>should be transformed to</p> <pre><code>2 3 4 0 1 5 0 0 2 3 1 1 </code></pre> <p>Is there any nice way to do this in python ...
<p>To fix for leading zeros rows -</p> <pre><code>def fix_leading_zeros(a): mask = a!=0 flipped_mask = mask[:,::-1] a[flipped_mask] = a[mask] a[~flipped_mask] = 0 return a </code></pre> <p>To push all zeros rows to the back -</p> <pre><code>def push_all_zeros_back(a): # Based on http://stacko...
python|numpy|theano
4
11,333
25,255,267
Column arithmetic in pandas dataframe using dates
<p>I think this should be easy but I'm hitting a bit of a wall. I have a dataset that was imported into a pandas dataframe from a Stata .dta file. Several of the columns contain date data. The dataframe contains 100,000+ rows but a sample is given:</p> <pre><code> cat event_date total 0 G2 2006-03-08 16 1 ...
<p>Not sure why the numpy <code>datetime64</code> is incompatible with pandas dtypes but using <code>datetime</code> objects worked fine for me:</p> <pre><code>In [39]: import datetime as dt mydata['new'] = mydata['event_date'] - dt.datetime(2006,1,1) mydata Out[39]: cat event_date total new Index ...
python|pandas|dataframe|datetime64
6
11,334
25,194,842
Close to 100k data points with RuntimeWarning: overflow encountered within for loop
<p>I have a normalized data set array with 96495 rows and 5 columns. I am only interested in plotting along the first two. (the third provides a sigma value for the second column, and the others are not of concern.)</p> <p>I am unable to provide the exact code or dataset as per my adviser (I am a student), I will do m...
<p>So the problem was solved!</p> <p>The overflows and nan values were coming from the fact that a mean value was being taken over various ranges.</p> <pre><code>rolling_window(the range of means values was the problem) ''' This is not the actual code, as stated in the original question, I have not been allowed ...
python|arrays|loops|for-loop|numpy
0
11,335
30,696,741
How to implement Kernel density estimation in multivariate/3D
<p>I have dataset like the following fromat and im trying to find out the Kernel density estimation with optimal bandwidth. </p> <pre><code>data = np.array([[1, 4, 3], [2, .6, 1.2], [2, 1, 1.2], [2, 0.5, 1.4], [5, .5, 0], [0, 0, 0], [1, 4, 3], [5, .5, 0], [2, .5, 1.2]]) </code></pre> <p>but I couldn...
<p>Interesting problem. You have a few options:</p> <ol> <li>Continue with scikit-learn</li> <li>Use a different library. For instance, if the kernel you are interested in is the gaussian - then you could use <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.stats.gaussian_kde.html" rel="nofo...
python|numpy|machine-learning|scikit-learn|kernel-density
5
11,336
26,923,466
matrix of mean 0 and standard deviation 0.1 with python
<p>How do I initialize a matrix with random values so that the mean should be 0 and standard deviation should be 0.1? Is there a easy way to do this with python??</p> <p>Some one please tell me how to do this.</p>
<p>I am assuming that you mean that each entry of the matrix should be drawn from a normal distribution with mean 0 and standard deviation 0.1. This can be achieved using numpy with:</p> <pre><code>from numpy import random a = random.normal(0, 0.1, (10, 10)) </code></pre> <p>This will create a 10x10 random matrix.</...
python|numpy|scipy
5
11,337
26,593,223
Why is 2.4 not equal to 2.4? Python / NumPy
<p>I am new to coding in Python and am having trouble with something VERY basic. I did a search on this site for numbers not being equal but only found something related to Java. I have a very simple question. Why does 2.2 = 2.2 but 2.4 != 2.4? Code is presented below and here is a screenshot of the output I get: <a hr...
<p>Any language that stores floating points will usually store them as IEEE 32 or 64 bit binaries, which are essentially base 2 scientific notation, and therefore will never be exactly "2.1" or "2.4". As such, be very wary of doing any "==" comparisons with floating points in your code. Even if the numbers start off ...
python|numpy
0
11,338
39,199,270
How to copy parameters from global model to thread-specific model
<h3>Context:</h3> <p>I am new to TensorFlow and I'm trying to implement some of the algorithms in <a href="https://arxiv.org/pdf/1602.01783v2.pdf" rel="nofollow">this paper</a> which require occasionally copying from a global shared model to local thread-specific model.</p> <h3>Question:</h3> <p>What is the best/cor...
<p>About <a href="https://www.tensorflow.org/api_docs/python/framework/core_graph_data_structures#Graph" rel="nofollow noreferrer">tf.Graph</a> class in Tensorflow:</p> <blockquote> <p>Important note: This class is not thread-safe for graph construction. All operations should be created from a single thread, or ex...
python|tensorflow
3
11,339
39,285,808
autosummary “toctree contains reference to nonexisting document” warnings
<p>I am facing the same problem as in this <a href="https://i.stack.imgur.com/Yq4qv.png" rel="nofollow noreferrer">thread</a>. When I build my Sphinx documentation with <code>make html</code> then I get a lot of warnings like this</p> <pre class="lang-sh prettyprint-override"><code>None:None: WARNING: toctree contains ...
<p>It seems to me that you are currently using the <code>numpydoc</code> extension. Please note that Numpy and Google style docstrings are now supported by the builtin <code>sphinx.ext.napoleon</code> extension.</p> <p>Removing the <code>numpydoc</code> extension and using <code>sphinx.ext.napoleon</code> will likely ...
python|python-sphinx|numpydoc
1
11,340
39,294,132
Shrink pandas Df by deleting rows through modulo
<p>I need to reduce (or select) for example multiple of 4 of the index. i have a 2MS dataframe and i want to get less data for a future plot. so the idea is to work with 1/4 of the data. leaving only the rows with index 4 - 8 - 16 - 20 - 4*n (or maybe the same but with 5*n) if someone has any idea i will be grateful.</...
<p>You can use the <code>iloc</code> function, which takes a row/column slice. </p> <p>From the <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.iloc.html" rel="nofollow">docs</a></p> <blockquote> <p>Purely integer-location based indexing for selection by position.</p> <p...
python|pandas|dataframe
1
11,341
13,170,435
Python: How does one typically get around "Maximum allowed dimension exceeded" error?
<p>I'm trying to make a 2^n x 2^n numpy array of all possible dot product permutations of a <em>very large</em> set of vectors. My test array, "data", is a (129L, 222L) numpy array. My function seems (in my novice opinion) to be pretty straightforward. It's just the fact that I have too much data to process. How do pro...
<p>Why are you passing <code>num,num</code> to reshape, but not the actual thing you're reshaping?</p> <p>Perhaps you want something like <code>return np.reshape(S, (num, num))</code> instead?</p> <hr> <p>As for the actual error, 2^129 is a pretty darn large number - even your regular 64-bit integer can only index u...
python|numpy|multidimensional-array|large-data
3
11,342
29,334,523
How to add string as value for new column for dataframe
<p>I am trying to add string value and assign to a new column for dataframe , but could not figure it out the best way to do this. </p> <pre><code>Df['new'] = "my value" </code></pre> <p>But this is not working and I couldn't understand why, can someone please explain to me ? Or how exactly can I do this in Python us...
<p>Do you mean this?</p> <pre><code>import pandas as pd d = {'a':[1,2,3], 'b':[4,5,6]} j = {'c':['a','hello','t']} x = pd.DataFrame(d) y = pd.DataFrame(j) x.insert(2, 'c', y) </code></pre>
python|pandas
0
11,343
33,678,435
Pandas Plotting with twinx
<p>I'm attempting to have a bar plot and line plot on the same figure using Pandas matplotlib API. However, it is not going very well. I am using twinx() which seems to be the generally accepted way of accomplishing this.</p> <p>Note that this is done in a Jupyter notebook, with the plot being shown inline. Thank you ...
<p>What seems to be the problem? Your code appears to work fine.</p> <pre><code>%matplotlib inline from matplotlib import pyplot as plt trend_df_hours = pd.Series(np.random.rand(10)) trend_df_qty = pd.Series(np.random.rand(10)) fig0, ax0 = plt.subplots() ax1 = ax0.twinx() trend_df_hours.plot(kind='bar', stacked=Tr...
python|pandas|matplotlib|plot
6
11,344
33,534,665
Plotting PCA results including original data with scatter plot using Python
<p>I have conducted PCA on iris data as an exercise. Here is my code: </p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use("ggplot") from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler fro...
<p>Here is the way I think you can visualize it. I'll put PC1 on X-Axis and PC2 in Y-Axis and color each point based on its category. Here is the code:</p> <pre><code>#first we need to map colors on labels dfcolor = pd.DataFrame([['setosa','red'],['versicolor','blue'],['virginica','yellow']],columns=['Species','Color'...
python|numpy|matplotlib|scikit-learn|pca
3
11,345
33,890,746
Creating a dictionary of arrays, using values in one of the columns as the key
<p>I've been trying to do this for a while, with little success so far. I have a large (>400,000 data points) 2D array in python. The array itself could be split into a series of smaller rows based on the date (dd\mm\yyyy).</p> <p>To achieve my end goal, one of the things I want to do is to change a numpy.ndarray (sim...
<p>The error message would be pointing to the first line of the loop: as it says, that's not how you index an array. <code>row</code> is already the list of values in the row; you already know how to get a single item, via just <code>row[0]</code>, and to get a list it's exactly the same: <code>row[1:]</code>. So your ...
python|arrays|numpy|dictionary
1
11,346
23,913,743
Matplotlib timeseries plot from numpy matrix
<p>How would I be able to go about plotting a timeseries graph from a numpy matrix that looks like such:</p> <pre><code>data = [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 48. 48. 48. 48. 48. 48. 48. 48. 48. 48.] [ 48. 48. 48. 48. 48. 48. 48. 48. 48. 48.] [ ...
<p>Here's an example with a subset of data similar to yours.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np data = [[ 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.], [ 49., 48., 48., 48., 48. , 48., 48., 48., 48., 48.], [ 9., 18., 28., 38., 48., ...
python|numpy|matplotlib|time-series
3
11,347
22,681,615
Can't export pandas dataframe to excel / encoding
<p>I'm unable to export one of my dataframes due to some encoding difficulty.</p> <pre><code>sjM.dtypes Customer Name object Total Sales float64 Sales Rank float64 Visit_Frequency float64 Last_Sale datetime64[ns] dtype: object </code></pre> <p>csv export w...
<p>You need to use pandas >= 0.13, and the <code>xlsxwriter</code> engine for excel, which supports native unicode writing. <code>xlwt</code>, the default engine will support passing an encoding option will be available in 0.14.</p> <p>see <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#excel-writer-engin...
python|pandas|xlwt
3
11,348
22,467,590
categorising data in a pandas dataframe based on value
<p>I frequently need to categorise a range of numbers:</p> <p>For example:</p> <pre><code>|Num| cat| | 2 |low | | 7 | med| | 10|high| </code></pre> <p>What I want! I want to build two functions.</p> <p><strong>Function 1. -</strong> Takes in 3 parameters: Parameter 1: dataframe name Parameter 2: a column na...
<p>I think you're looking for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer">cut</a>:</p> <pre><code>In [11]: s = pd.Series(np.random.randint(1, 11, (10, ))) In [12]: s Out[12]: 0 7 1 10 2 5 3 8 4 5 5 4 6 3 7 3 8 4 9 1 dt...
python|pandas
4
11,349
15,143,253
Is there any documentation on the interdependencies between packages in the scipy, numpy, pandas, scikit ecosystem? Python
<p>Is there any documentation on the interdependencies and relationship between packages in the the scipy, numpy, pandas, scikit ecosystem?</p>
<p>AFAIK, here is the dependency tree (numpy is a dependency of everything):</p> <ul> <li>numpy <ul> <li>scipy <ul> <li>scikit-learn</li> </ul></li> <li>pandas</li> </ul></li> </ul>
python|numpy|scipy|pandas|scikit-learn
6
11,350
29,514,854
Numpy Select indices with complex conditions
<p>Simple question... I hope...</p> <p>I've got a matrix, <strong>a</strong> , of size (n x m)</p> <pre><code>a = np.matrix([[1,2,3],[3,2,1],[6,4,1]]) </code></pre> <p>and I'd like to extract a bool matrix, <strong>b</strong>, of size (n x m) for the following condition; </p> <pre><code>b = 3 &lt; a &gt; 7 and a !=...
<p>You can't use <code>and</code> with arrays as you're trying to compare a single value with an array you have to use <code>&amp;</code>, also you need to enclose the conditions in parentheses due to operator precedence:</p> <pre><code>In [56]: a[(a &gt; 3 ) &amp; (a &lt; 7) &amp; (a != 6)] Out[56]: matrix([[4]]) </...
python|loops|numpy|matrix|indices
2
11,351
62,114,501
How to filter within a subgroup (Pandas)
<p>here is my problem: </p> <p>You will find below a Pandas DataFrame, I would like to groupby Date and then filtering within the subgroups, but I have a lot of difficulties in doing it (spent 3 hours on this and I haven't find any solution). </p> <p>This is what I am looking for : I first have to group everything b...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a> first by 2 columns, then remove duplicates by 2 columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dro...
python|pandas|numpy|filter|time-series
3
11,352
62,448,426
Sort, bucket and apply function to DataFrame
<p>I have the following sample dataframe:</p> <pre><code>pd.DataFrame({'Name': ['A', 'B', 'C', 'D', 'E'], 'Score': [2, 6, np.nan, 3, 4], 'Value 1': [10, 30, 20, 5, 15], 'Value 2': [400, 250, 100, 300, 150]}) Name Score Value 1 Value 2 0 A 2.0 10 ...
<p>You can apply qcut as follows;</p> <pre><code>df['bucket'] = pd.qcut(df['Score'], 4, ['q1','q2','q3','q4']) df.groupby('bucket')[['Value 1','Value 2']].mean() </code></pre> <p>Normally, it will exclude NaN, thus I change the bucket column to str ,or you can apply fillna to specify the value to NaN.</p> <pre><code...
pandas|dataframe
1
11,353
62,358,642
Convert one-hot encoding back to number label
<p>I have a series of one-hot encoding vector, say</p> <p><code>np.array([[1,0,0,0],[0,1,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]])</code></p> <p>I want to convert it back to </p> <p><code>np.array(0,1,1,2,3)</code></p> <p>Is there an efficient way of doing without for loop?</p>
<p>As pointed out by @Divakar in the comments, NumPy's <a href="https://numpy.org/doc/stable/reference/generated/numpy.argmax.html" rel="nofollow noreferrer"><code>argmax</code></a> is the easiest way to get the job done. Notice that you need to pass the function the proper value of parameter <code>axis</code>.</p> <p...
numpy
1
11,354
62,199,137
Checking panda dataframe column for a match in a list
<p>I have a pandas dataframe with two columns, a file id number and a list of keywords from that file. I essentially want to be able to iterate through each row and see if a chosen keyword is in the list of file key words and if it is print out the file id. Or I could make a new dataframe with all positive matches and ...
<p>A solution can be pandas inner join: You'd better first convert your key_word array to a pandas dataframe. let's say you have saved the array as "key_words.csv" and give the label of "my_key" to that:</p> <pre><code>col_name = ['my_key'] df1 = pd.read_csv("key_words.csv", names = col_name ,skiprows=[0],encoding ='u...
python|pandas|dataframe
0
11,355
62,097,728
How do I replace every nth instance in an ndarray?
<p>I have a numpy array <code>atoms.numbers</code> which looks like:</p> <pre><code> array([27, 27, 27, 27, 27, 27, 57, 57, 57, 57, 57, 57, 57, 57, 27, 27, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 27, 27, 27, 27, 27, 27, 57, 57, 57, 57, 57, 57...
<p>Use <code>np.where</code> to find the indexes of the items of interest. Find every n'th index. Update the items:</p> <pre><code>locations = np.where(numbers == 57)[0] numbers[locations[::n]] = 38 </code></pre>
python-3.x|scipy|instance|numpy-ndarray|numpy-slicing
1
11,356
62,402,562
Python: Split Start and End Date into All Days Between Start and End Date
<p>I've got data called 'Planned Leave' which includes 'Start Date', 'End Date', 'User ID' and 'Leave Type'.</p> <p>I want to be able to create a new data-frame which shows all days between Start and End Date, per 'User ID'.</p> <p>So far, I've only been able to create a date_list which supplies a range of dates betw...
<p>In my opinion, <em>Date</em> column alone is not enough. Your output DataFrame should also contain at least <em>Employee ID</em>, to know which person is on leave at the given date.</p> <p>To do your task, define the following function:</p> <pre><code>def datesplit(data): parts = [] for idx, row in data.it...
python|pandas|numpy|datetime|data-science
0
11,357
62,368,244
Multiplying list with array as dot product
<p>I came across a code performing a general dotproduct of a list 'A' with a numpy Array 'B'.</p> <pre><code>A = [1,2,3,4,5,6] B = np.arange(18).reshape(3, len(A)) result = np.dot (B,A) result2 = np.dot (A,B) </code></pre> <p><code>np.dot(A,B)</code> gives an error: "Value Error: shapes (6,) and (3,6) not aligned: 6...
<p>Normally, this operation would never work since <code>A</code> and <code>B</code> are of different shapes.</p> <p>However, the reason <code>np.dot(B, A)</code> works is because <code>np.dot</code> is <a href="https://numpy.org/doc/1.18/reference/generated/numpy.vectorize.html" rel="nofollow noreferrer">vectorized</...
python|python-3.x|numpy
1
11,358
51,472,487
output tuple of numpy.histogram returs a tuple with two lists of different lengths
<pre><code>np.histogram([1,2,1,1,1,1,3,5], bins=[0,1,2,3,4,5]) </code></pre> <p>returns me tuple with a list including the count how often a number occurs in my input list and the bin as a list. The output looks like this:</p> <pre><code>(array([0, 5, 1, 1, 1], dtype=int32), array([0, 1, 2, 3, 4, 5])) </code></pre> ...
<p>In your particular case, you are looking for the left bin boundary (because it is included in the bin, while the right boundary is not - except for the last bin that includes its own right boundary, too). Function <code>zip</code> combines two lists/arrays. If one of the lists is longer, it is truncated, which is wh...
python|python-3.x|numpy
1
11,359
51,311,240
How to use WmdSimilarity function provided in gensim along with word embeddings which are in numpy.ndarray data type
<p>Using Word2vec (skip-gram) model in tensorflow , I wrote the code to obtain word embeddings from document-set. The final embeddings are in numpy.ndarray format</p> <p>Now to obtain similar documents , I need to use the WMD(Word Movers Distance) algorithm.</p> <p>(I don't have much knowledge of gensim) The gensim.s...
<p>If you're looking for similarity between 2 words, use</p> <pre><code>my_gensim_word2vec_model.most_similar('king') </code></pre> <p><code>my_gensim_word2vec_model</code> is the gensim model, of course, not your own tensorflow model.</p> <p>If you want the most similar to a bunch of words:</p> <p><code>my_gensim_...
python-3.6|gensim|word2vec|numpy-ndarray|wmd
0
11,360
51,118,553
How to make a new matrix from another matrix by using its first column as new's first row?
<p>I want to use a python function or library - if any - for creating a new matrix whose first row beginning from the right-below is created by using old matrix's first column beginning from the left-top. That matrix can have different columns and rows but of course my new matrix have to have same dimension as previous...
<p>In keeping with the brief style of the question:</p> <pre><code>In [467]: alist = [5,6,4,3,4,5,3,2,5,3,1,2,2,3,2,1,3,1,1,1] In [468]: arr = np.array(alist).reshape(4,5) In [469]: arr Out[469]: array([[5, 6, 4, 3, 4], [5, 3, 2, 5, 3], [1, 2, 2, 3, 2], [1, 3, 1, 1, 1]]) In [470]: arr.reshape(5,4...
python-3.x|numpy|matrix
1
11,361
51,144,033
Tensorflow : Understanding tf.contrib.seq2seq.BasicDecoder
<p>I am trying to understand tf.contrib.seq2seq.BasicDecoder, Every example on web just use that wrapper but I couldn't find the explanation of what actually tf.contrib.seq2seq.BasicDecoder doing , I tried with one simple example :</p> <pre><code>import numpy as np import tensorflow as tf from pprint import pprint fro...
<p>As you run <code>decoder.step(tf.constant(3), step_next_inputs, step_state)</code>, it means the decoder already decodes 4 steps (from <code>0</code> to <code>3</code> and the <code>3</code> is finished), so the step finished is <code>array([ True, True, True, True, True])</code>.</p> <p>If you run <code>decode...
python-3.x|tensorflow|keras|deep-learning|lstm
0
11,362
48,084,262
Sort a list based on values from dataframe
<p>Is my approach here the right way to do it in Python? As I'm new to Python, I appreciate any feedback you can provide, especially if I'm way off here.</p> <p>My task is to order a list of file names based on values from a dataset. Specifically, these are file names that I need to sort based on site information. ...
<p>I like your use of Pandas, but it isn't the most Pythonic as it uses data structures that are a superset of Python. Nevertheless, I think we can improve on what you have. I will show an improved version and I will show a completely native Python way to do it. Either is fine I suppose? </p> <p>The strictly Python ve...
python|pandas|sorting
0
11,363
48,315,955
CET and CEST conversion to UTC
<p>I have code to convert the Europe/Brussels time to UTC. Will this code take care of both CET and CEST conversions ? i.e. does it handle day light savings conversion as well to UTC ? If not, can some one suggest how to handle it ?</p> <pre><code>df['datetime'] = pd.to_datetime(df['date'] + " " + df['time']).dt.tz_lo...
<p>Yes, it handles DST natively. Check this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'date': pd.to_datetime(['2017-08-30 12:00:00', '2017-12-30 12:00:00'])}) df['date'].dt.tz_localize('Europe/Brussels').dt.tz_convert('UTC').dt.strftime('%Y-%m-%d %H:%M:%S') </code></pre> <p>I picked one date with DST, i....
python|pandas
3
11,364
48,409,527
Multiple regex string replace on large text file using Python
<p>I am having some very large text file on which I want to execute multiple regex based string replacement. Currently I am doing it using Sublime's similar feature. However, in files larger than a GB my system is hanging. </p> <p>I am running some of the below matches in my sublime currently</p> <p><code>\\\n</code>...
<p>If I understand correctly you could do as below .<br> This seems to work with the data sample you shared</p> <pre><code>import pandas as pd df = pd.read_csv('story_all.csv', sep=',') # Chars to replace chars = [ '\n', ] output = df.replace(chars, '', regex=True) output.to_csv('story_done.csv', sep=',', encod...
python|regex|pandas|parsing|replace
1
11,365
48,421,703
Change unicode hardwrited in csv to corresponding character
<p>I have a csv with 1 column having hard writed unicode character :</p> <pre><code>["Investir dans un parc d'activit\u00e9s"] ["S\u00e9curiser, restaurer et g\u00e9rer 1 372 ha de milieux naturels impact\u00e9s par la construction de l'autoroute"] ["Am\u00e9liorer la consommation \u00e9nerg\u00e9tique de b\u00e2timen...
<p>if this <code>'\u00e9'</code> is actually written into the file as <code>\</code> <code>u</code> <code>0</code> <code>0</code> <code>e</code> <code>9</code> as normal characters by the source of the data, you need to do a string replace.</p> <p>the trick here is that you need to escape the <code>\</code> character ...
python|python-3.x|pandas|dataframe|encoding
1
11,366
48,391,061
Getting keys from a dictionary: keys() vs 'keys for keys in dict.keys()'
<p>Trying to figure out best coding practices as I'm getting started with python. I wrote a csv to dataframe reader with pandas. It uses the format: </p> <pre><code>dataframe = read_csv(csv_input, usecols=column_names, dtype=test_dictionary) </code></pre> <p>We're using a dictionary to determine the columns we want t...
<p>In Python 3, <code>keys()</code> does not return a list, but rather <a href="https://docs.python.org/3/library/stdtypes.html#dict-views" rel="nofollow noreferrer">a "view" of the keys in the dictionary</a>.</p> <pre><code>&gt;&gt;&gt; d = {'x': 1, 'y': 2, 'z': 3} &gt;&gt;&gt; keys = d.keys() &gt;&gt;&gt; keys dict_...
python|pandas
4
11,367
48,500,534
pandas,Replace Values in a dataframe, depending on other Column
<p>I have A dataframe like below,</p> <pre><code>df = pd.Dataframe({'Col1' : pd.Series(['Abc','Cde','Efg','Abc'], index=['a', 'b', 'c','d']), 'Col2' : pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd']), 'Col3' : pd.Series([1, 2., 3., 4.], index=['a', 'b', 'c', 'd'])}) </code></pre> <p>By Depending on the value...
<p>This should work:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Col1' : pd.Series(['Abc','Cde','Efg','Abc'], index=['a', 'b', 'c','d']), 'Col2' : pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd']), 'Col3' : pd.Series([1, 2., 3., 4.], index=['a', 'b', 'c', 'd'])})...
python|pandas|dataframe
4
11,368
48,862,429
python 3.5 pandas read excel and convert to a list
<p>I have an excel file with a data as shown below:</p> <pre><code> Col_Title1 | Col_Title2 | Col_Title3 | Label Row11 | Row12 | Row13 | 1 Row21 | Row22 | Row23 | 2 Row31 | Row32 | Row33 | 3 </code></pre> <p>Using pandas, I read this excel file like this:</p> <pre><cod...
<p>I believe you need remove <code>Label</code> column, convert to numpy array by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html" rel="nofollow noreferrer"><code>values</code></a> and then to <code>list</code>:</p> <pre><code>a = df.drop('Label', 1).values.tolist() print (a...
python|python-3.x|list|pandas|dataframe
3
11,369
48,873,321
Improve a POC of linear regression with sklearn and pandas
<p>Basically, I'm deploying a proof of concept on a linear regression model to validate the accuracy coefficient percentage based on a specific dataset. To a high-level previous build my model I apply a kind of manipulation in my dataset to ensure that all columns required as input are numeric and OK.</p> <p>A datase...
<p>There are two things that you can improve:</p> <p>1) You need to configure the hyper-parameters of your linear model properly. The scikit-learn <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDRegressor.html" rel="nofollow noreferrer">SGDRegressor</a> is very sensitive to the choice...
python|pandas|machine-learning|scikit-learn
1
11,370
48,784,925
concatenate dataframes with different shapes
<p>How should I use pd.concat to concatenate df1 and df2 in order to get df3?</p> <pre><code> df1=pd.DataFrame(data=[[1,2],[3,4],[5,6]],index=[1,2,2]) df2=pd.DataFrame(data=[[1,2],[3,4]],index=[2,2]) df3 =pd.DataFrame(data=[[1,2,np.nan,np.nan],[3,4,1,2],[5,6,3,4]],index=[1,2,2]) df1 Out[27]: 0 ...
<p>Create <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><...
python|pandas|dataframe
1
11,371
48,611,998
Type error on first steps with Apache Parquet
<p>Rather confused by running into this type error while trying out the Apache Parquet file format for the first time. Shouldn't Parquet support all the data types that Pandas does? What am I missing?</p> <pre><code>import pandas import pyarrow import numpy data = pandas.read_csv("data/BigData.csv", sep="|", encoding...
<p>In Apache Arrow, table columns must be homogeneous in their data types. pandas supports Python object columns where values can be different types. So you will need to do some data scrubbing before writing to Parquet format. </p> <p>We've handled some rudimentary cases (like both bytes and unicode in a column) in th...
python|pandas|csv|data-science|parquet
2
11,372
71,015,394
Can't use conda environment in VSCode
<p>Today I can't use my env in Visual Studio Code. I've tried to restart my computer, reinstall Jupyter extensions in VSCode but nothing works. Here are some pictures of the &quot;errors&quot;:</p> <ol> <li><p>Here it can't even print 1 <a href="https://i.stack.imgur.com/lvJih.png" rel="nofollow noreferrer"><img src="h...
<p>Apparently, it was giving me this error due to not updating <code>tensorflow</code> to version <code>2.8</code>. The issue here is that I was succesfully using this env for the past 6 months without any problem, so I don't know why now sstarted failing...</p>
python|tensorflow|visual-studio-code|jupyter-notebook|anaconda
0
11,373
70,755,630
Python: Function to fill in the previous row of a non-null value
<p>I have a dataset which is mostly timedelta values which relate to the shift length worked by emergency workers. If certain conditions were met, then the shift time was combined with the prior shift length time ['Combined Time']</p> <p>What I'm having trouble getting is the 'Final Times' column. To not double count h...
<p>You can use pandas <code>where()</code> + <code>bfill()</code> to fill previous row with a &quot;check&quot; value, so <code>my_func()</code> will test it to calculate &quot;final times&quot;.</p> <pre><code>df['Combined Time'] = df['Combined Time'].where( df['Combined Time'].bfill(limit=...
python|pandas|function|timedelta
1
11,374
51,737,205
iterate over columns to plot a graph of output data
<p>I have written a small python script that plots a graph of my data. I wanted to modify the y variable such that I do not have to change the usecols=range(1,11) parameter every time my input changes. Is it possible to define a for loop within the np.gefromtxt function?</p> <pre><code>import numpy as np import matplo...
<p>Like the previous answer suggested, the best course of action is probably to read the entire csv in first, then slice the first column as x, and the remaining as y. That way, as long as the first column in the csv is x, the script will work.</p> <p>For a bit more nuanced solution, you can look into pandas as it sup...
python|python-2.7|numpy|matplotlib
0
11,375
41,948,367
How to load a very large into Tensorflow and create minibatchs?
<p>I have a hdf5 file that has been written into the disk by a python code (I only have the file, not the code). The size of this file is 90GB and the data in this file has the following format: (N, 250,360,3). Just as side note, the data can't fit into memory.</p> <p>Now I want to write a data loader in Tensorflow wh...
<p>The Tensorflow MNIST tutorial shows how this can be done: <a href="https://www.tensorflow.org/tutorials/mnist/beginners/" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/mnist/beginners/</a></p> <p>If you look at the implementation on Github, you'll see that it uses a <code>next_batch</code> function...
python|tensorflow
1
11,376
64,344,708
Trying to Parse JSON using Pandas in the YoutubeAnalytics Api and Convert it CSV
<p>I am trying to download my youtube data using the <strong>Youtube Analytics and Reporting API</strong> from here <a href="https://developers.google.com/youtube/analytics/reference/reports/query?apix_params=%7B%22dimensions%22%3A%22day%22%2C%22endDate%22%3A%222020-10-05%22%2C%22ids%22%3A%22channel%3D%3DMINE%22%2C%22m...
<pre><code>pd.DataFrame(json_file['rows']) </code></pre> <p>you can add column names as u req if u want</p> <pre><code> pd.DataFrame(json_file['rows'],columns=[a,b,c,...]) </code></pre>
python|json|pandas|dataframe
2
11,377
64,409,264
Why is `to_numpy()` recognized as an attribute rather than a method of dataframe?
<pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np class CLF: Weights = 0 def fit(DF_input, DF_output, eta=0.1, drop=1000): X, y = DF_input.to_numpy(copy=True), DF_output.to_numpy(copy=True) N,d = X.shape m = len(np.unique(y)) self.Wei...
<p>An instance method is a type of attribute; this is a more general error message that keys on the <code>.</code> (dot) operator, rather than parsing through to the left parenthesis to discriminate your usage.</p> <p>The problem is that you defined an instance method <code>fit</code>, but named your instance as <code>...
python|pandas|methods|attributes|numpy-ndarray
1
11,378
47,972,917
LSTM Numpy, Loss, Cell State, Gradients, Weights going NAN after ~250 training iterations
<p>I am doing a LSTM implementation with numpy and I've run into nan values after a few training iterations. I am following this guide.</p> <p><a href="https://wiseodd.github.io/techblog/2016/08/12/lstm-backprop/" rel="nofollow noreferrer">https://wiseodd.github.io/techblog/2016/08/12/lstm-backprop/</a></p> <p>Model ...
<p>Clipping the gradient of the hidden state and cell state dealt with this error, I suspect the gradient was exploding out of control.</p> <p>original:</p> <pre><code>def backpropagate(self, y, ht1, ct1): n, d = self.n, self.d Wi, Wf, Wo, Wc, Wy = self.rnn.Wi, self.rnn.Wf, self.rnn.Wo, self.rnn.Wc, self.rnn.Wy dWi,...
python|numpy|lstm|rnn
0
11,379
47,951,007
Must explicitly set engine if not passing in buffer or path for io
<p>I am a beginner, could you help me to see where the problem lies? So I think maybe <code>read_excel</code> have some problem but I can't solve it. When I run this program I get: <em>"Must explicitly set engine if not passing in buffer or path for io"</em>. </p> <pre><code>import pandas as pd data=pd.read_excel("C:\...
<p>You need only filename in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow noreferrer"><code>read_excel</code></a> with double backslash:</p> <pre><code>data=pd.read_excel("C:\\test.xlsx") </code></pre> <p>Or <code>r</code> for raw string:</p> <pre><code>data=pd...
python|excel|pandas
0
11,380
47,706,351
Combine columns of dataframe into new dataframe
<p>I am new to <a href="https://pandas.pydata.org/" rel="nofollow noreferrer">pandas</a> and working with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow noreferrer">DataFrames</a>. I'm looking at the documentation for <a href="https://pandas.pydata.org/pandas-docs/s...
<p>We can using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.wide_to_long.html" rel="nofollow noreferrer"><code>wide_to_long</code></a>, if you need column name to be x, y , you can <a href="https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.rename.html" rel="nofollo...
python|pandas
1
11,381
49,061,416
Is tensorflow lite model already quantized?
<p>Does the converted tensorflow lite model always have quantized calculation and output? Or it depends on the tensorflow model's input and inference type?</p>
<p>It depends on the inference type.</p> <p>First the input model should be instrumented with quantization operations, <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/quantize" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/quantize</a...
tensorflow|quantization|tensorflow-lite
3
11,382
49,330,430
Storing large amount of text data for TensorFlow training?
<p>I'm wondering what's the recommended way to store such data in a sequence-to-sequence problem to make it easily usable and efficient with tf.data.Dataset? Basically, I could have a file called data.txt and another called labels.txt and each pair of lines from these lines would be a training example.</p> <p>Basicall...
<p>Whether to convert strings to ints as a separate processing steps probably depends on your usage scenario. If you are mostly training on fixed vocabulary, it is better to convert to ints once. If you are using the model online and can get new vocabulary items at run time, you will have to allocate new ids online.</p...
tensorflow|text
0
11,383
49,199,053
Chained conditional count in Pandas
<p>I have a dataframe that looks at how a form has been filled out. Here's an example:</p> <pre><code>ID Name Postcode Street Employer Salary 1 John NaN Craven Road NaN NaN 2 Sue TD2 NAN NaN 15000 3 Jimmy MW6 Blake Street Bank 40000 ...
<p>I think you can use <code>notnull</code> and <code>cummin</code>:</p> <pre><code>In [99]: df.notnull().cummin(axis=1).sum(axis=0) Out[99]: Name 6 Postcode 5 Street 3 Employer 2 Salary 2 dtype: int64 </code></pre> <p>Although note that I had to replace your NAN (Sue's street) with a float Na...
python|pandas
1
11,384
58,616,850
pandas type error when trying to modify values of a column
<p>I have csv file that looks something like this</p> <pre><code> x y z 0 a_b_c 30 40 1 d_e_f 50 57 </code></pre> <p>I am trying to modify column x by splitting the string at the first underscore and only keeping the string right before it. Based on this <a href="https://stackoverflow.com/a/13682381/694...
<p>use</p> <pre><code>df['x'].str.split("_").str[0] </code></pre> <p>when you call <code>df['x'].map(...)</code>, you operate each <code>element</code> of <code>x</code> column. you can't use <code>str</code> on an <code>element</code>. It can be used on the <code>x</code> column, a <code>Series</code>.</p>
python-3.x|pandas
0
11,385
58,965,227
Keras custom layer issue for loop
<p>I am trying to dynamically create layers in Keras (Lambda Layers) but for some reason when I use for loop I get the same error in the list, compared to manually appending elements into the list.</p> <p>Where is my bug?</p> <pre><code>other_channels_out = [] out_channel = [] for i in range(out_number_model_0): ...
<p>I don't have enough reputation to comment, but the issue is that the scope of <code>i</code> is outside the <code>lambda</code> function, so the value of <code>i</code> changes after the <code>lambda</code> is created. By moving the <code>Lambda</code> (and hence <code>lambda</code>) creation to another function, yo...
python|tensorflow|keras
0
11,386
70,061,232
how to merge dataframes based on column names
<p>I would like to merge 2 dataframes with different index column names. I have df1 with the proper order of tickers that i want and would like to merge df2 witch the same tickers but in a different order and additional information.</p> <p>so my df1 looks like:</p> <h2>df1</h2> <div class="s-table-container"> <table cl...
<pre><code>import pandas as pd # Import the tables you provided, which I saved as CSVs df1 = pd.read_csv('df1.csv') df2 = pd.read_csv('df2.csv', header=1) # Rename the &quot;ticker&quot; column so that all it is the same as the corresponding column name in df1 df2.rename(columns={'ticker': 'index'}, inplace=True) # ...
python|pandas|dataframe
0
11,387
70,230,172
How do I sort values by name that have a matching element?
<p>In this DataFrame, the teams need to stay in the same position, but I want to sort the players within each team.</p> <pre><code> Team Player Apps 0 Newcastle_United Joelinton 5.0 1 Newcastle_United Allan Saint-Maximin 5.0 2 Newcastle_United Callum Wi...
<p>Sort by <strong>multiple</strong> <strong>columns</strong> in a <strong>Pandas Table</strong></p> <pre><code>df.sort_values(by=['Team', 'Player']) </code></pre> <p><strong>Sample Script Demo Sort by <strong>multiple</strong> <strong>columns</strong> in a <strong>Pandas Table</strong></strong></p> <pre><code>import p...
pandas|dataframe|sorting
1
11,388
70,096,392
Split an integer cell into two columns based on digit location, python
<p>I am dealing with thousands of csv GPS files which I want to plot in a GIS software. To do this I need decimal degrees, but the data was collected in degree decimal minutes. I have a function that converts the degree decimal minutes into the format I desire however the layout of the data in each csv file requires ma...
<p>My solution is not very efficient in terms of iteration abuse, but you can try this:</p> <pre><code>import pandas as pd data = [[5710.7240,'N',917.3222,'W'],[710.7239,'N',917.3225,'W']] df = pd.DataFrame(data, columns=['L2','NS','L4','EW']) split_L1, split_L2 = [],[] for i, row in df.iterrows(): split_L1.appen...
python|pandas|gis|dd
0
11,389
70,253,101
Adding a column based on another dataframe when merging is not possible
<p>My first dataframe (same <code>name</code> and <code>object</code> might appear multiple times):</p> <pre><code>df_1= name object number1 number2 0 n1 o1 0.0 1.0 1 n1 o2 1.0 1.0 2 n2 o1 0.0 1.0 3 n3 ...
<p>It looks like you just want to do a join/merge on the <code>object</code> column:</p> <pre><code>df1.merge(df2,on=['object']).replace(to_replace={'number3':['No', 'Yes']}, value={'number3':[0.0, 1.0]})``` </code></pre>
python|pandas|dataframe|merge
2
11,390
56,080,498
Element not part of the graph when using VGG for data generation and loss calculation
<p>I have a VGG19 encoder which takes an input image <code>y</code> of <code>(256,256,3)</code> and returns a tensor of dimension <code>(32,32, 512)</code> from conv-4-1 layer of vgg. I need to turn it into a numpy array to apply some transformations and reconstruct the image using my decoder.</p> <p>In short, I'm try...
<p>You can check a similar question : <a href="https://stackoverflow.com/a/56178638/7454706">https://stackoverflow.com/a/56178638/7454706</a></p> <p>Create one extra function</p> <pre><code>def load_model(): global model model = yourmodel(weights=xx111122) # this is key : save the graph after loading ...
python|tensorflow|machine-learning|keras|autoencoder
0
11,391
64,686,876
remove a dictionary from a dictionary based on a conditoon
<p>I want to remove a dictionary from a nested dictionary based on a condition.</p> <p>dict :</p> <pre><code>{1: {'A': [1, 2, 3, 0], 'B': ['ss', 'dd', 'ff', 'aa']}, 2: {'A': [0, 1, 2, 3], 'B': ['ee', 'ff', 'bb', 'gg']}, 3: {'A': [0, 1, 2], 'B': ['ar', 'hh', 'ww']}, 4: {'A': [ 1, 0], 'B': [ 'll', 'jj']}} </code></pr...
<p>Check</p> <pre><code>s=pd.DataFrame(d) new_d = s.loc[:,s.loc['B'].str[0].str[0]=='a'].to_dict() Out[99]: {1: {'A': [0, 1, 2, 3], 'B': ['aa', 'ss', 'dd', 'ff']}, 3: {'A': [0, 1, 2], 'B': ['ar', 'hh', 'ww']}} </code></pre>
python|python-3.x|pandas|dataframe|pandas-groupby
1
11,392
64,900,604
Categorical column after melt in pandas
<p>Is it possible to end up with a categorical variable column after a <code>melt</code> operation in pandas?</p> <p>If I set up the data like this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df = pd.DataFrame( np.random.randn(3, 5), columns=[&quot;A&quot;, &quo...
<p>One efficient option is with<br /> <a href="https://pyjanitor-devs.github.io/pyjanitor/api/functions/#janitor.functions.pivot.pivot_longer" rel="nofollow noreferrer">pivot_longer</a> from <a href="https://pyjanitor-devs.github.io/pyjanitor/" rel="nofollow noreferrer">pyjanitor</a>, using the <code>names_transform</c...
python|pandas|dataframe|melt
0
11,393
64,922,614
Comparing another array with a list full of arrays
<p>So I've essentially split an array#1(full of float values) into 100 arrays contained in a list, and what I want to do is compare it to an array#2(also full of floats) and have the program give me the number of values in array#2 that fall within the range of each of the 100 arrays in the list.</p> <p>I may not have e...
<p>This question requires some numpy high dimension array operation:</p> <pre><code>import numpy as np threshim_by_size = np.random.rand(300) manual_bins_threshim = np.array_split(threshim_by_size, 100) array2 = np.random.rand(20) def count(rand, ll, rr): return len(list(i for i in rand if ll &lt;= i &lt;= rr)) ...
python|arrays|numpy
1
11,394
64,873,832
Using two types of grouping, one for plotting line one for color in matplotlib
<p>I'm new to any type of coding so please bear with me. I plot a set of data with originally 33 columns into a plot using <code>df.groupby</code>. This is so that I have multiple lines, each line representing the change over time of a particular sample. With my method each line has a unique color. I want the lines whi...
<p>Here is a quick fix using <code>matplotlib colormaps</code>:</p> <pre><code>import pandas as pd from matplotlib import cm groups = df.groupby(['Material', 'Colour', 'Storage Temperature']) fig, ax = plt.subplots(figsize=(15, 9)) max_T = max(df['Storage Temperature']) cmap = cm.get_cmap('viridis') for element, grou...
python|matplotlib|colors|pandas-groupby
1
11,395
39,963,357
Speed up creation of numpy array from list
<p>I have a 33620x160 <code>pandas</code> <code>DataFrame</code> which has one column that contains lists of numbers. Each list entry in the <code>DataFrame</code> contains 30 elements.</p> <pre><code>df['dlrs_col'] 0 [0.048142470608688, 0.047021138711858, 0.04573... 1 [0.048142470608688, 0.047021138711...
<p>you can do it this way:</p> <pre><code>In [140]: df Out[140]: dlrs_col 0 [0.048142470608688, 0.047021138711858, 0.04573] 1 [0.048142470608688, 0.047021138711858, 0.04573] 2 [0.048142470608688, 0.047021138711858, 0.04573] 3 [0.048142470608688, 0.047021138711858, 0.04573]...
python|arrays|performance|pandas|numpy
1
11,396
40,071,628
How to look up rows in certain condition
<p>I have a dataframe and I would like to search strange rows like below :</p> <pre><code>  month 0 201605     1 201606 2 201607 3 08 4 nan 5 201610 </code></pre> <p>For instance, I would like to extract rows with elements that is not 6 digits like below :</p> <pre><code> month 3 08 4 nan </code></...
<p>Suppose your month column is of <code>str</code> type, you can use <code>.str.len()</code> to get the number of digits for each element and use the result for subsetting:</p> <pre><code>df[df.month.str.len() != 6] # month #3 08 #4 NaN </code></pre>
python|pandas|dataframe
1
11,397
44,258,507
Read file into pandas dataframe (using soh to split data)
<h1>Question:</h1> <p>I have seen some websites about how to read files into dataframe but can't find one that teach me how to read file that use soh to split data.</p> <p>The files I get don't have extension but they look like .txt file.</p> <p>For now I read the files row by row to create dataframes and it takes lots...
<p>If your data doesn't have headers, this should do it:</p> <pre><code>import pandas as pd table = pd.read_table('filename', sep='\x01', header=None, names=['column1','column2']) </code></pre> <p>You can rear more about reading files <a href="http://pandas.pydata.org/pandas-docs/version/0.20/io.html#parsing-options"...
python|pandas|dataframe
0
11,398
44,286,529
pandas dataframe from nested JSON
<p>I have the following json as web api response:</p> <pre><code>{"prices": [ { "start_date": "2016-07-06T00:00:00+02:00", "end_date": "2016-07-07T00:00:00+02:00", "values": [ { "start_date": "2016-07-06T00:00:00+02:00", "end_date": "2016-07-06T00:30:00+02:00", "upward_weighted": 45....
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html" rel="nofollow noreferrer"><code>json_normalize</code></a>:</p> <pre><code>from pandas.io.json import json_normalize df = json_normalize(d['prices'], 'values') print (df) downward_marginal downward_...
python|json|pandas
3
11,399
69,451,126
Input_from Conv_1D signal data
<p>This is my signal <a href="https://i.stack.imgur.com/NWTE1.png" rel="nofollow noreferrer">data</a></p> <p>The length of each sample data is = 64. The sum of train data is =49572</p> <pre><code>length=len(x_train) model = tf.keras.models.Sequential([ tf.keras.layers.Conv1D(32, 3, activation='relu', input_shape=(l...
<p>From the keras <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv1D" rel="nofollow noreferrer"><code>Conv1D</code></a> documentation:</p> <blockquote> <p>When using this layer as the first layer in a model, provide an input_shape argument (tuple of integers or None, e.g. (10, 128) for sequences...
tensorflow|keras|deep-learning
0