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
10,900
56,755,756
How to create numpy arrays automatically?
<p>I wanted to create arrays by for loop to assign automatically array names.</p> <p>But using a for loop, it didn't work and creating a dictionary with numpy.array() in it, does not work, too. Currently, I have no more ideas... I am not really safe in handling with python.</p> <pre><code> import numpy as np fo...
<p>You can do it with <code>globals()</code> if you really want to use the strings as named variables.</p> <pre><code>globals()[filename] = np.array() </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; globals()['test'] = 1 &gt;&gt;&gt; test 1 </code></pre> <p>Of course this populates the global namespace. Other...
python|arrays|numpy
0
10,901
25,598,093
use hour unit in pandas to_timedelta
<p>From pandas document of pandas.to_timedelta(arg, box=True, unit='ns'), the unit has been explained as below:</p> <pre><code>unit of the arg (D,h,m,s,ms,us,ns) denote the unit, which is an integer/float number </code></pre> <p>So I think "h" should be means hours. but it seems I am wrong because below example doesn...
<p>[Moved from comments to close it:]</p> <p>This was a bug, see <a href="https://github.com/pydata/pandas/issues/7611" rel="nofollow">GH #7611</a>, and was fixed for 0.14.1:</p> <pre><code>&gt;&gt;&gt; pd.__version__ '0.14.1' &gt;&gt;&gt; base = pd.to_datetime("00:00", format="%H:%M") &gt;&gt;&gt; base + pd.to_timed...
python|pandas
3
10,902
26,067,850
Cleanest way to perform pandas join involving an index and also columns
<p>Suppose I want to merge (concat?) two pandas tables by joining on both an unnamed index and a column (here "identifier"). Is there a clean way to do this? </p> <pre><code> tvType identifier 2014-04-08 12:05:00 TMM_ISPREAD ISIN: US92344GAS57 2014-04-08 12:10:00 TMM_ISPREAD...
<p>Simply supply <code>left_index</code> and <code>right_index</code> too:</p> <pre><code>In [96]: print df1 tvType identifier 2014-04-08 12:05:00 TMM_ISPREAD ISIN:US92344GAS57 2014-04-08 12:10:00 TMM_ISPREAD ISIN:US92344GAS57 2014-04-08 12:15:00 TMM_ISPREAD ISIN:US92344GAS57 2...
python|join|pandas|concat
1
10,903
66,996,453
Pandas Melt Columns to Rows
<p>I have data that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Country</th> <th>Channel</th> <th>App-Purchase-Laptop</th> <th>App-Purchase-Cell</th> <th>App-Sell-Laptop</th> <th>App-Sell-Cell</th> <th>Web-Purchase-Laptop</th> <th>Web-Purchase-Cell</th> <t...
<p>Try this:</p> <pre><code>dfi = df.set_index(['Date','Country','Channel']) dfi.columns = pd.MultiIndex.from_tuples(dfi.columns.str.split('-', expand=True), names=['Category', None, 'Source']) df_out = dfi.stack([0,2]).reset_index() df_out </code></pre> <p>Output:</p> <pre><...
python|pandas|dataframe|melt
3
10,904
67,087,322
Copy non-na rows to fill non-na columns using pandas
<p>I have a dataframe like as shown below</p> <pre><code>df = pd.DataFrame({'person_id': [101,101,101,101], 'sourcename':['test1','test2','test3','test4'], 'Test':[np.nan,np.nan,'B5','B6']}) </code></pre> <p>What I would like to do is copy <code>non-na</code> rows from <co...
<h3><a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.update.html" rel="nofollow noreferrer"><code>Series.update</code></a></h3> <p>We can <code>update</code> the values in <code>sourcename</code> column with the <code>non NaN</code> values from <code>Test</code> column</p> <pre><code>df['sourcename']...
python|pandas|dataframe|series|na
5
10,905
66,829,754
Create a new column by adding matching cell content in pandas
<p>Hello everyone I would need help in order to to fusionnate columns containt when there is a specific grep value inside.</p> <p>Here is an exemple</p> <pre><code>Species COL1 COL2 COL3 COL4 COL5 SPf_1 4 f_G1 None None None SP1 9 -_Haploviric -_unclassified f_G3 ...
<p>Let us <code>filter</code> and <code>stack</code> the columns from <code>COL1</code> to <code>COL5</code>, then <code>extract</code> the <code>f_pattern</code> strings followed by <code>groupby</code> + <code>first</code> on <code>level=0</code></p> <pre><code>df.filter(regex='COL[1-5]').stack()\ .str.extract(r'^(...
python|python-3.x|pandas
5
10,906
66,828,699
Hugging Face Trainer: Error in the model init
<p>I am getting the following error:</p> <pre><code>You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference. Traceback (most recent call last): File &quot;./run_hyperparameter_search.py&quot;, line 74, in &lt;module&gt; trainer = Trainer( File &quot;/ext3/mi...
<p>From the <a href="https://huggingface.co/transformers/_modules/transformers/trainer.html" rel="nofollow noreferrer">Huggingface trainer docs</a> it looks like <code>model_init</code> takes a callable. So rather than instantiating the parameter it should take the callable itself i.e. without parenthesis:</p> <pre><co...
nlp|huggingface-transformers
0
10,907
47,354,626
Error Tensorflow Couldn't find field google.protobuf.EnumDescriptorProto.EnumReservedRange.start
<p>Hi I'm trying running an tensorflow application in my computer. I installed the tf , using the pip and follow the steps in the tensorflows documentation.</p> <p>I'm using python 3.6.3 in ubuntu 17.10</p> <pre><code>KeyError: "Couldn't find field google.protobuf.EnumDescriptorProto.EnumReservedRange.start" </code>...
<p>I get this error when I try to use TensorFlow with Anaconda rather than Python 2.7 on a Mac. To see if you are using Anaconda, use the <strong>which</strong> command:</p> <blockquote> <p>which python</p> <ul> <li>/Users/me/anaconda2/bin/python</li> </ul> </blockquote> <p>If this is causing your problem...
python|python-3.x|ubuntu|tensorflow
1
10,908
11,348,708
2d interpolation in python with random spot
<p>I checked the available interpolation method in scipy, but could not get the proper solution for my case. assume i have 100 points whose coordinates are random, e.g., their x and y positions are:</p> <pre><code>x=np.random.rand(100)*100 y=np.random.rand(100)*100 z = f(x,y) #the point value calculated by certain f...
<p>Use <code>scipy.interpolate.griddata</code>. It does the exact thing you need</p> <pre><code># griddata expects an ndarray for the interpolant coordinates interpolants = numpy.array([xnew, ynew]) # defaults to linear interpolation znew = scipy.interpolate.griddata((x, y), z, interpolants) </code></pre> <p><a hr...
python|numpy|scipy
3
10,909
11,003,662
Container list in Python: standard list vs numpy array
<p>I'm writing some python code that needs to store and access a list of different kinds of elements. Each element of this list will be of a different class type. For example:</p> <pre><code>def file_len(fname): i = 0 with open(fname) as f: for i, l in enumerate(f): pass return i + 1 ...
<p>This is not a full answer, but I spotted two things I could contribute.</p> <p>Here is an improved version of <code>file_len()</code>. This one will return 0 if the file is zero-length. Your function returns 1 for a zero-length file, and 1 for a file with one line.</p> <pre><code>def file_len(fname): i = 0 ...
python|memory-management|numpy
1
10,910
68,409,148
Pandas read_excel returns xlrd dependency error only for a specific file
<p>I have a python script which reads a number of Excel files (.xlsx) with no issue, thus:</p> <pre><code>df_file1 = pd.read_excel(myfile1, mysheet) </code></pre> <p>However, I then tried to read another similar file using similar code and received a dependency error:</p> <p><code>ImportError: Missing optional dependen...
<p>From the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html" rel="nofollow noreferrer">read_excel documentation</a>, xlrd is used when no engine is specified and the file is in .xls format. However, the file was definitely saved in .xlsx format.</p> <p>Explicitly specifying th...
python-3.x|pandas|xlsx
2
10,911
68,038,676
TypeError: 'retval_' has dtype int32 in the main branch, but dtype float32 in the else branch
<p>I am training my model to address image classification problem, i have 1000 images classified into 4 classes. When training the model i am getting &quot;Type Error&quot;, I have reviewed my code several times and don't know where i have committed an error in the code, if possible could some one please suggest me re...
<p>As the error indicates, you have returned <code>int32</code> (<code>return 0</code>) in the main branch but <code>float32</code> (<code>return fbeta_score</code>) in else, and this happened in the <code>fbeta_score</code> function.</p> <p>So, change <code>return 0</code> =&gt; <code>return 0.0</code>.</p>
python|tensorflow|deep-learning|typeerror|multilabel-classification
1
10,912
59,381,440
Highlight a specific cell in a pandas dataframe
<p>I'd like to highlight a specific cell in my pandas dataframe. I can grab the exact position using the <code>.loc[]</code> function. I've tried to look at some examples using <code>df.style.apply(lambda x: ['background color: yellow' ...]</code> but I am not sure how to pass in the exact position I am trying to acces...
<p>For a specific cell, you can do:</p> <pre><code># toy example df = pd.DataFrame({'i1':[0,0,0,1,1,1], 'i2':[0,1,2,0,1,2], 'col1':[1,2,3,4,5,6]}).set_index(['i1','i2']) subsets = pd.IndexSlice[(0,1), 'col1'] df.style.applymap(lambda x: "background-color: yellow", subset=subsets)...
python|pandas
6
10,913
59,253,056
Python Pandas DataFrame convert columns of each row to one single column as Pandas Series
<p>I am trying to get the data of Pandas.DataFrame (df) into the shape (3,1) with each row being a Pandas.Series. When I run my code I keep getting NaN in every single cell instead of the Pandas.Series.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])...
<p>This might be what you want</p> <pre><code>X_train = np.array(pd.Series(df.values.tolist())).reshape(3, 1) print(X_train.shape) (3, 1) </code></pre>
python|pandas|dataframe|series
0
10,914
59,344,571
Why Keras behave better than Pytorch under the same network configuration?
<p>Recently, I have compared unet++ implementation of Keras version and Pytorch version on the same dataset. However, with Keras the loss decrease continuously and the accuracy is higher after 10 epochs, while with Pytorch the loss decrease unevenly and the accuracy is lower after 10 epochs. Anyone has met such probl...
<p>Well, it's pretty hard to say without any code snippets. that being said, in general, initialization is way more important than you might think. I'm sure that the default initialization of pytorch is different from keras and I had similar issues in the past.</p> <p>Another thing to check is the optimizer parameters...
tensorflow|keras|pytorch
1
10,915
44,856,341
getting both "'numpy.ndarray' object is not callable" and "'Tensor' object is not callable"
<p>I'm working on building a binary classifier: I'm inexperienced in ML so, using code adapted from the Iris classification tutorial on TensorFlow.org I'm getting 85% accuracy on the test set. However, this evaluation is run using a threshold value of 0.5: I'd like to be able to try different threshold values just to s...
<pre><code>TypeError: 'numpy.ndarray' object is not callable </code></pre> <p>This means you have a numpy array at this point, and you are trying to use as though it were a function. That is, you are 'calling' it with <code>arr(...)</code> syntax. Either you should be indexing it <code>arr[...]</code>, or this objec...
python|numpy|machine-learning|tensorflow|neural-network
0
10,916
44,894,012
Appending a Matrix in Python within loop
<p>I have a matrix <strong>y</strong> with size (3,3). Say it is a 3 by 3 matrix with all elements = 1.</p> <p>I then have a loop to create multiple (3,3) matrices. So these are the outputs:</p> <p>First loop I get this matrix:</p> <pre><code> [[ 88. 42.5 9. ] [ 121.5 76. 42.5] [ 167. 121.5 88. ]] ...
<p>It exists <code>np.append</code>, but it is very costly in a loop (if you append one by one). See <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>A copy of arr with values appended to axis. Note that append does not ...
python|arrays|loops|numpy|append
3
10,917
44,982,084
Numpy addition to an element of an array
<p>I am coding a neural network in python, and need to adjust my weights. In order to do so, I need to add my change variable to an element of my weights array. However, I don't know how to do this. The code would look like:</p> <pre><code>weights = numpy.array([1, 2, 3]) change = 1 weights[0]+= change print(weights) ...
<p>If you're trying to add your variable 'change' to just the first element of the weights array, then your code works fine. if you are trying to add 'change' to all elements of the weights array, simply put</p> <pre><code>weights=numpy.array([1,2,3]) change=1 weights+=change print(weights) </code></pre> <p>this code...
python|arrays|numpy|add
1
10,918
56,895,543
tensor equality and boolean as return value
<p>So, I followed this <a href="https://stackoverflow.com/questions/32996281/how-to-check-if-two-torch-tensors-or-matrices-are-equal">answer</a> on SO</p> <p>I'm trying to equate two tensors </p> <p><code>torch.equal(x_valid[0], x_valid[:1])</code> returns <code>False</code> whereas <code>torch.all(torch.eq(x_valid[...
<p><code>torch.equal(tensor1, tensor2)</code> return <code>True</code> if two tensors have the same size and elements, <code>False</code> otherwise. Check <a href="https://pytorch.org/docs/stable/torch.html#torch.equal" rel="nofollow noreferrer">here</a>.</p> <p>Example:</p> <pre><code>y = torch.tensor([[0, 0, 0]]) p...
pytorch|tensor
0
10,919
57,216,086
Alternative in Python for apply method on creating a new train dataframe?
<p>In the process of making a train method I observed that .apply method is way way too slow. It would be nice if someone can recommend another method which is semnificantly faster because I am talking about len =~ 3.5 milions.</p> <p>train2.head() looks like this </p> <pre><code> Email SaleDate NetGr...
<p>Can you try doing it by passing the dataframe itself to a function. For example, like this:</p> <pre><code>def compute_rfm(train2, end_calibration): x = train2.groupby(['Email'])['SaleDate'].agg(['max', 'min', 'count']).reset_index() x['recency'] = (x['max'] - x['min']).dt.days x['frequency'] = x['count...
python|pandas|performance|dataframe|apply
0
10,920
57,083,551
Averaging data while merging
<p>I have two dataframes as shown below:</p> <pre><code> result1 time browncarbon blackcarbon 180.7452 0.506824055392119 0.4693240205237933 180.748 0.5040641475588111 0.4671092323195378 180.7508 0.49911820575405846 0.46344714546409305 180.7535 0.4957944583911674 0.46030629341216...
<p>Use cross join by all combination of rows, then filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html" rel...
python-3.x|pandas
0
10,921
56,910,175
how to find rows with both positive and negative values in pandas dataframe
<p>I have a dataframe like this:</p> <pre><code> e_col in_col word_col w_col 31 9 algorithm -0.053538 31 9 ubc -0.053578 31 9 kth -0.053595 31 8 ubc -0.053633 30 8 algorithm 0.043637 ...
<p><strong>Edit 2</strong>: you may also use <code>transform</code> to avoid <code>set_index/reset_index</code> as follows:</p> <pre><code>m = df.w_col.lt(0).groupby(df.word_col).transform('nunique').eq(2) df.loc[m] Out[2768]: e_col in_col word_col w_col 0 31 9 algorithm -0.053538 4 30 ...
python|pandas|dataframe
2
10,922
57,080,180
Assigning Values to a Nested Dictionary Error
<p>I have data coming in that contains a Timestamp, and Open, High, Low, and Close values.</p> <p>I'm trying to organize it in a dictionary so that at each timestamp, there is a key holding the corresponding Open, High, Low and Close values.</p> <p>What I've done so far:</p> <p>I started by initialing an empty dicti...
<p>Judging by the names, like <code>append</code> and <code>newest_bar</code>, you are trying to place bar information into a dictionary keyed by timestamp. There is no reason for having a key called <code>Timestamp</code>: access to the bar information is provided by the timestamp itself. As such, you will probably wa...
python|pandas|dictionary|nested
1
10,923
23,386,759
Pandas stack chart with multiple dataframes
<p>I have a multiple dataframes (each dataframe is a picked file) which look like this:</p> <pre><code> DB Size Time 0 blue 19 2000-01-01 00:00:00 1 green 17 2000-01-01 01:00:00 2 red 20 2000-01-01 02:00:00 3 yellow 18 2000-01-01 03:00:00 4 red 17 2000-01-01 04:00:00 5 y...
<p>If I understand your question correctly, you can do this.</p> <p>Assuming your data are in df1, df2, or more :</p> <pre><code>df=pd.concat([df1,df2]) df['Date'] = [d.date() for d in df['Time'] ] df['Size_Interval'] = pd.cut(df['Size'],bins=[0,5,10,15,25]) count_df = df.pivot_table(rows='Date', cols='Size_Interva...
plot|pandas|stack
0
10,924
23,115,502
Not getting the expected speedup with Cython
<p>Here are two code samples</p> <pre><code>def hough_transform_1(active_points, size_trame, size_max_song): m = np.linspace(0.95, 1.05, 11) p = np.linspace(-size_trame, size_max_song, size_max_song + size_trame + 1) acc = np.zeros([m.size, p.size]) for m_i in m: for x_i, y_i in active_points: ...
<p>First, type everything. Secondly, actually type them.</p> <p>These aren't typed(!) and should be typed in the argument list:</p> <pre><code> cdef size_trame = sizetrame cdef size_max_song = sizemaxsong </code></pre> <p>This is redundant:</p> <pre><code> cdef np.ndarray[DTYPE_FLOAT_t, ndim=2] active_poi...
python|numpy|cython
3
10,925
35,734,868
str_replace_all() r equivalent in python
<p>I am transitioning from R to Python and have a sample dataframe as follows:</p> <pre><code>df = df = pd.DataFrame({'characterisitics': pd.Series(['Walter White made meth', 'Jessie Pinkman was called meth-head', 'Saul Goodman is always happy']), 'name': pd.Series(['Walter White', 'Jessie Pinkman', 'Saul Goodman'])})...
<p>I think for this one you have to apply a quick <code>lambda</code> to each row. You don't actually need regex for your simple example so the standard <code>str.replace()</code> works fine:</p> <pre><code>df.apply(lambda row: row['characterisitics'].replace(row['name'], ''), axis='columns') Out[8]: 0 ...
python|regex|pandas|dataframe
3
10,926
11,917,779
how to plot and annotate hierarchical clustering dendrograms in scipy/matplotlib
<p>I'm using <code>dendrogram</code> from <code>scipy</code> to plot hierarchical clustering using <code>matplotlib</code> as follows:</p> <pre><code>mat = array([[1, 0.5, 0.9], [0.5, 1, -0.5], [0.9, -0.5, 1]]) plt.subplot(1,2,1) plt.title("mat") dist_mat = mat linkage_matrix = linkage(dist_m...
<p>The input to <code>linkage()</code> is either an n x m array, representing n points in m-dimensional space, or a one-dimensional array containing the <a href="https://stackoverflow.com/questions/13079563/how-does-condensed-distance-matrix-work-pdist"><em>condensed</em> distance matrix</a>. In your example, <code>ma...
python|numpy|matplotlib|scipy|dendrogram
70
10,927
28,395,624
trouble with pip and easy_install to install python packages
<p>I am going to install <code>numpy</code> library as a <code>*.whl</code> file, as <code>numpy-1.9.2rc1+mkl- cp27-none-win32</code>, on my Windows 7 machine...</p> <p>Here is my approaches to do that, are which <code>pip</code> and <code>easy_install</code> packages... The odd thing is that both don't work in the ca...
<p>You should upgrade your pip to version 6.0, the .whl file you're using isn't compatible with earlier versions. </p> <p>To bump up your pip version on Windows : python -m pip install -U pip</p>
python|python-2.7|numpy
2
10,928
28,578,522
How to merge two sparse coo_matrix matrices in python?
<p>Say, I have two coo_matrix (i,j) value: mat_1:</p> <pre><code> (0, 1) 0.5 (0, 2) 0.5 (1, 2) 1.0 (3, 0) 0.5 (3, 3) 0.5 (5, 0) 0.5 (5, 3) 0.5 </code></pre> <p>mat_2:</p> <pre><code> (2, 0) 0.25 (4, 0) 0.25 (2, 1) 0.25 (4, 1) 0.25 ...
<p>Since the number of columns is the same of both sparse matrices you want to combine, you could try using <code>sparse.vstack</code>:</p> <pre><code>sparse.hstack((mat1, mat2)) </code></pre>
python|numpy|scipy|sparse-matrix
0
10,929
50,823,233
Does keras.backend.clear_session() deletes sessions in a process or globally?
<p>I create up to 100 keras models in separated script an save them localy with model.save(). For Training them, I use multiprocessing.pool. In those processes I load each model separately. Because of occuring Memory Errors I used keras.backend.clear_session(). This seems to work but I have also read that it deletes th...
<p>I faced similar kind of issue but I am not running models in parallel but alternatively i;e; either of the models (in different folders but same model file names) will run. </p> <p>When I run the models directly without clear_session it was conflicting with the previously loaded model and cannot switch to other mod...
python|tensorflow|keras|multiprocessing
3
10,930
51,084,192
Datetime conversion issue pandas
<p>I have a pandas dataframe with the first column of type "datetime64[ns]" on python3. Here is a snippet of my code:</p> <pre><code>import pandas as pd import numpy as np from pandas.tseries.offsets import BDay import datetime as dt d = {'Date': [np.datetime64('2017-12-31','ns'), np.datetime64('2018-01-01','ns'), np...
<p>The dataframe is not indexed by <code>Date</code> column. You will need to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer">set_index</a> before slicing.</p> <pre><code>&gt;&gt;&gt; analytics.set_index("Date")[yr1_plus1:last] </code></pre>
python-3.x|pandas|datetime|timestamp|weekday
1
10,931
50,828,688
How to add a threshold in softmax scores
<p>When doing multi-classcification usually I got a softmax score and predictoins with below, </p> <pre><code>softmax_scores = tf.nn.softmax(logits=self.scores, dim=-1) prediction=tf.argmax(self.scores, 1, name="predictions") </code></pre> <p>If the softmax_socres I got is <code>[0.5,0.2,0.3]</code>.The prediction is...
<p>How about doing it this way, with the use of <code>tf.where</code></p> <pre><code>threshold = 0.6 softmax_scores = tf.nn.softmax(logits=self.scores, dim=-1) other_class_idx = tf.cast(tf.shape(softmax_scores)[0] + 1, tf.int64) other_class_idx = tf.tile( \ tf.expand_dims(other_class_idx, 0), \ [tf.shape(sof...
python|tensorflow|deep-learning|classification|multilabel-classification
1
10,932
50,839,892
Installing Tensorflow (cpu) on Jenkins agent
<p>To run our tests on Jenkins, we need to install tensorflow in the virtual environment inside the Jenkins agent. I am getting the following error. </p> <pre><code>import tensorflow as tf File "/prod/msp/build/slave1/workspace/Jobs_uiuc_simplesilo_master-7ENH27JSQENY42PFYNEOG3SJGXLTHWJC5Z6KNZUHEDUIGUWU5ZHQ/venv2/lib/...
<p>I tried running tensorflow inside a Docker image on Jenkins and it worked.</p>
python|jenkins|tensorflow
-1
10,933
50,893,011
Print the result without the tag 'array' in a list?
<p>I would like to display my result without the tag ARRAY before which array in a list</p> <p>My result is this:</p> <pre><code>[array([202.632 , 565.74 , 177.258 , 0.01627 , 0.00008 , 0.00919 , 0.00963 , 0.02756 , 0.0717 , 0.833 , 0.03515 , 0.04265 , 0.0646 , 0.10546 , 0.078...
<p>You could use <a href="https://docs.python.org/3.5/library/reprlib.html#subclassing-repr-objects" rel="nofollow noreferrer"><code>reprlib</code></a> and <a href="https://docs.python.org/3/library/sys.html#sys.displayhook" rel="nofollow noreferrer"><code>sys.displayhook</code></a>.</p> <p>The following code very clo...
python|numpy
0
10,934
51,025,590
python - error while sorting csv by column
<p>I'm trying to sort a .csv file by multiple columns, I'm using pandas, this is the .csv file:</p> <pre><code>col1;col2;col3;col4;col5 6943000;11;1.0;2016-01-01 15:30:31;? 6943000;19;1.0;2016-01-01 15:38:07;? 6943000;13;1.0;2016-01-01 15:54:27;? 6942992;10;1.0;2016-01-01 00:52:59;? 6942993;8;1.0;2016-01-01 12:08:36;?...
<p>Your csv is delimited by a semi-colon <code>';'</code>, by default the separator for <code>read_csv</code> is <code>','</code>, pass param <code>sep=';'</code>:</p> <pre><code>In[21]: import io t="""col1;col2;col3;col4;col5 6943000;11;1.0;2016-01-01 15:30:31;? 6943000;19;1.0;2016-01-01 15:38:07;? 6943000;13;1.0;201...
python|pandas
3
10,935
20,527,617
Group by - select most recent 4 events
<p>I have the following df in pandas:</p> <pre><code>df: DATE STOCK DATA1 DATA2 DATA3 01/01/12 ABC 0.40 0.88 0.22 04/01/12 ABC 0.50 0.49 0.13 07/01/12 ABC 0.85 0.36 0.83 10/01/12 ABC 0.28 0.12 0.39 01/01/13 ABC 0.86 0.87 0.58 04/01/13 ABC 0.95 0.39 0.87 07...
<p>For this I think you can use <code>transform</code> and <code>rolling_sum</code>. Starting from your dataframe, I might do something like:</p> <pre><code>&gt;&gt;&gt; df["DATE"] = pd.to_datetime(df["DATE"]) # switch to datetime to ease sorting &gt;&gt;&gt; df = df.sort(["STOCK", "DATE"]) &gt;&gt;&gt; rsum_columns ...
python|pandas
0
10,936
33,199,052
How to calculate rolling mean on a GroupBy object using Pandas?
<p>How to calculate rolling mean on a GroupBy object using Pandas?</p> <p>My Code:</p> <pre><code>df = pd.read_csv("example.csv", parse_dates=['ds']) df = df.set_index('ds') grouped_df = df.groupby('city') </code></pre> <p>What grouped_df looks like:</p> <p><a href="https://i.stack.imgur.com/InLjM.png" rel="nofollo...
<p>You could try iterating over the groups</p> <pre><code>In [39]: df = pd.DataFrame({'a':list('aaaaabbbbbaaaccccbbbccc'),"bookings":range(1,24)}) In [40]: grouped = df.groupby('a') In [41]: for group_name, group_df in grouped: ....: print group_name ....: print pd.rolling_mean(group_df['bookings'],3) ...
python|pandas|dataframe
2
10,937
66,682,642
Breaking up a dataframe column into two columns
<p>I am currently having a problem where I am splitting a column into two separate columns. When I perform my code it runs without any errors, but the dataframe is still the same. I'm not sure where my mistake is.</p> <pre><code>url = 'https://www.teamrankings.com/nba/player/clint-capela/game-log' html = requests.get(u...
<p>Pandas operations by default doesn't change the original dataframe and returns a new object, so</p> <pre class="lang-py prettyprint-override"><code>players_log = players_log.join(players_log['FGM-FGA'].str.split('-', 1, expand=True).rename(columns={0:'A', 1:'B'})) </code></pre> <p>should do it</p>
python|pandas|dataframe
2
10,938
66,736,842
Pandas: Merge dataframe and series based on index
<p>I created following dataframe <code>priceearning_byyear</code>, which is still incomplete:</p> <p><a href="https://i.stack.imgur.com/QNivF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QNivF.png" alt="enter image description here" /></a></p> <p>Afterwards, I would like to &quot;insert&quot;/merg...
<p>You are almost there. Just pass <code>left_index</code> and <code>right_index</code> simultaneously to get the desired effect as below.</p> <pre><code># Reproduce your data import pandas as pd priceearning_byyear = pd.DataFrame(dict(year=[2016,2017,2018,2019,2020], eps=[2.09,2.32,3.00,2.99,3.31])).set_index('year') ...
python|pandas
2
10,939
66,724,605
Linear Regression with Pytorch : constant loss
<p>I'm working on a linear regression problem with Pytorch (y=A*x, where the dimensions of A are 2x2). I wrote the following code. I don't know why the loss doesn't change... Can someone help me ?</p> <p>Thanks,</p> <p>Thomas</p> <pre><code>import torch import numpy as np from scipy.integrate import odeint from matplot...
<p>In my laptop it worked ...<br /> since you are running it on just <code>10 epochs </code>...and using <code>lr = 0.0001</code> ,you wont see it in just <code>10 epochs</code>.</p> <p>i did this <code>optimizer = torch.optim.SGD(our_model.parameters(), lr = 0.01)</code> (increased <code>lr</code> )which actually decr...
python|tensorflow|pytorch|linear-regression|loss
0
10,940
66,478,467
pandas insert only new values from one df to another with conditions
<p>my pandas <strong>dataframes</strong> df1 and df2</p> <p>df2 is empty <strong>dataframe.</strong></p> <p>df1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>name</th> <th>address</th> <th>startdate</th> <th>enddate</th> <th>middate</th> </tr> </thead> <tbody> <tr> <td>0</td>...
<p>Using <code>groupby()</code></p> <ul> <li>collapse <strong>name</strong> and <strong>address</strong></li> <li><code>groupby()</code> <strong>name</strong> to update <strong>enddate</strong> and <strong>middate</strong> to <strong>startdate</strong> of next row in the group</li> </ul> <pre><code>df1 = pd.read_csv(io...
python|python-3.x|pandas|dataframe
1
10,941
66,615,107
How to tackle inconsistent results while using pandas rolling correlation?
<p>Let me preface this by saying, in order to reproduce the problem I need a large data, and that is part of the problem, that I can't predict when the peculiarity is going to pop up. Anyway, the <em><strong>data is too large (~13k rows, 2 cols) to be pasted in the question, I have added a pastebin link at the end of t...
<p>What if you compute you replace the sums in your pearson formula with rolling sums</p> <pre class="lang-py prettyprint-override"><code> def rolling_pearson(a, b, n): a_sum = a.rolling(n).sum() b_sum = b.rolling(n).sum() ab_sum = (a*b).rolling(n).sum() aa_sum = (a**2).rolling(n).sum() bb_sum = (b*...
python|pandas|numpy|rolling-computation|pearson-correlation
3
10,942
57,355,397
python - Plot Precision Recall Curve for different multi-class classifiers
<p>I have predicted output for validation data which is single label multi-class classifier. I have run multiple classifiers. I want to plot the PR curves for each of them in a single plot. I am not able to do that. Any pointers? </p> <pre><code>For a single classifier, the dataframe with results look like this : la...
<p>You can seperately calculate metrics you want to observe for different cutoffs, and then refer to <a href="https://plot.ly/python/line-charts/" rel="nofollow noreferrer">this page</a> later on. Plotly comes with handy notebook integration, as interactive plots. You can add different lines with "add_trace" method whi...
python|pandas|matplotlib
1
10,943
57,462,091
Using DataFrame to make highlighted regions of plot using axvspan
<p>I have a DataFrame:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd highlight_data = pd.DataFrame(columns=list('XY')) highlight_data.columns = ['Start','Stop'] highlight_data['Start'] = [20, 25, 42, 56] highlight_data['Stop'] = [80, 35, 48, 72] </code></pre> <p>And I am trying to make multiple ...
<p>You probably want to iterate over the rows of the dataframe, not the column-names.</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd highlight_data = pd.DataFrame(columns=list('XY')) highlight_data.columns = ['Start','Stop'] highlight_data['Start'] = [20, 25, 42, 56] highlight_data['Stop'] = [80, ...
python|pandas|matplotlib
1
10,944
57,571,337
Combine tensorflow low level API (tensors/placeholders) with Keras model
<p>According to <a href="https://www.tensorflow.org/guide/keras#build_advanced_models" rel="nofollow noreferrer">tensorflow</a>. Using <code>tf.keras.Input</code> gives a placeholder and using <code>tf.keras.layers.Dense</code> gives a Tensor. So I wanted to test the equivalence using Tensors and Placeholders with tens...
<p>You can't mix <code>tf.placeholder</code> and <code>tf.keras.Input</code>. In other words, if you want to use the <code>tf.keras</code> API then use <code>tf.keras.Input</code>, or if you want to use the <code>tf</code> native API the go with <code>tf.placeholder</code>. In addition, your choice will reflect other p...
python|tensorflow|machine-learning|keras|deep-learning
3
10,945
23,964,581
Split numpy recarray based on value in one column
<p>my real data has some 10000+ items. I have a complicated numpy record array of a format roughly like:</p> <pre><code>a = (((1., 2., 3.), 4., 'metadata1'), ((1., 3., 5.), 5., 'metadata1'), ((1., 2., 4.), 5., 'metadata2'), ((1., 2., 5.), 5., 'metadata2'), ((1., 3., 8.), 5., 'metadata3')) </cod...
<p>You can always access those rows easily using fancy indexing:</p> <pre><code>In [34]: a[a['meta']=='metadata2'] Out[34]: rec.array([(array([ 1., 2., 4.], dtype=float32), 5.0, 'metadata2'), (array([ 1., 2., 5.], dtype=float32), 5.0, 'metadata2')], dtype=[('coords', '&lt;f4', (3,)), ('value...
python|numpy|recarray
2
10,946
43,804,799
Pandas - Merge of Dataframe with a Series Values
<p>I have a Dataframe (doc2) which basically looks like:</p> <pre><code> Index AgeGroups Factor Cancer 0 0_5 wo-statin Yes 1 6_10 wo-statin Yes 2 11_15 wo-statin Yes 3 16_20 wo-statin Yes 4 21_25 wo-statin Yes 5 26_30 wo-statin Y...
<p>Try this:</p> <pre><code>In [170]: doc2.merge(frame_concat.to_frame('Frequency'), left_on='AgeGroups', right_index=True, how='left') Out[170]: AgeGroups Factor Cancer Frequency Index 0 0_5 wo-statin Yes 0 1 6_10 wo-statin Yes 0 2 1...
python|pandas
2
10,947
43,688,938
Pandas - insert rows where data is missing
<p>I have a dataset, here is an example:</p> <pre><code>df = DataFrame({"Seconds_left":[5,10,15,25,30,35,5,10,15,30], "Team":["ATL","ATL","ATL","ATL","ATL","ATL","SAS","SAS","SAS","SAS"], "Fouls": [1,2,3,3,4,5,5,4,1,1]}) Fouls Seconds_left Team 0 1 5 ATL 1 2 10 ATL 2 3 ...
<p>Create a MultiIndex and reindex + reset_index:</p> <pre><code>idx = pd.MultiIndex.from_product([df['Team'].unique(), np.arange(5, df['Seconds_left'].max()+1, 5)], names=['Team', 'Seconds_left']) df.set_index(['Team', 'Seconds_left']).reindex(idx)....
python|pandas
5
10,948
73,118,867
how to understand the convolutional layer output depth
<p>I am a bit confused about the output depth of the convolutional layer. For example, as shown in <a href="https://i.stack.imgur.com/MT5V4.png" rel="nofollow noreferrer">this</a> image, there are <code>2</code> filters of size <code>3 x 3</code> for input image of size <code>6 x 6 x 3</code>, the output is a <code>4 x...
<p>In the example image posted by OP for input of size <code>6 x 6 x 3</code> (<code>input_dim=6, channel_in=3</code>) with <code>2</code> filters of size <code>3 x 3</code> (<code>filter_size=3</code>) the spatial dimension can be computed as <code>(input_dim - filter_size + 2 * padding) / stride + 1</code> = <code>(6...
tensorflow|machine-learning|neural-network|conv-neural-network
2
10,949
73,142,074
Shifting value from one row to another
<p>So I have a dataset that has electricity load over 24 hours:</p> <pre><code> Time_of_Day= loadData.groupby(loadData.index.hour).mean() Time_of_Day Load Time 0 31.269373 1 26.810803 2 20.998901 3 18.513907 4 17.752296 5 19.093729 6 22.972921 7 29.144652 8 34.138466 9 37.169422 10 37...
<p>Something like this.</p> <pre><code>df = pd.DataFrame({'time': [0, 1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23], 'load': [31.269373, 26.810803, 20.998901, 18.513907, 17.752296, 19.093729, 22.972921, 29.144652, 34.138466, 37.169422, 37.544159, 37.499416, 38.579195, 38.251304, 37...
pandas|numpy|jupyter-notebook|time-series|google-colaboratory
2
10,950
72,938,485
Applying a mask to a dataframe, but only over a certain range inside the dataframe
<p>I currently have some code that uses a mask to calculate the mean of values that are overloads, and values that are baseline values. It does this over the entire length of the dataframe. However, now I want to only apply this to a certain range in the dataframe column, between <code>first</code> and <code>last</code...
<p>Assuming <code>no_overload_cycles == 1</code> always, you can simply use slice objects to index the <code>DataFrame</code>.</p> <p>Say you wish to, in your example, specifically pick cycles 5, 10 and 15 and use them as overload. Then you can get them by doing <code>df.loc[5:15:5]</code>. On the other hand, if you wi...
python|pandas|dataframe|numpy
1
10,951
10,819,330
Numpy genfromtxt Column Names
<p>How can I have <code>genfromtxt</code> to return me its <code>list</code> of column names which were automatically retrieved by <code>names=True</code>? When I do:</p> <pre><code>data = np.genfromtxt("test.csv",names=True,delimiter=",",dtype=None) print data['col1'] </code></pre> <p>it prints the entire column val...
<p><code>genfromtxt</code>returns a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html" rel="noreferrer">numpy.ndarray</a>.</p> <p>You can get the data type with </p> <pre><code>data.dtype </code></pre> <p>or just the names with</p> <pre><code>data.dtype.names </code></pre> <p>which is...
python|numpy
25
10,952
70,727,944
python dataframe date on second row instead of header row
<p>i have a dataframe downloading as:</p> <p><a href="https://i.stack.imgur.com/cWqeL.png" rel="nofollow noreferrer">the dataframe with the date header on a separate row</a></p> <p>if i export it to a csv file and import it again it has all the headers on the first row.</p> <p>if i look for the information from the row...
<p>This code will let you switch the date as a columns and reset your index. You will need to import pandas</p> <pre><code>df['Date'] = df.index df.reset_index(drop=True, inplace=True) </code></pre>
python|pandas|dataframe|date
-1
10,953
70,699,708
Error trying to solve a matrix using numpy
<p>Im trying to solve for x1 x2 x3 and x4 for this matrix but I keep getting errors. Matrix A contains all the coefficients for x1 x2 x3 x4 respectively and Matrix B contains what it is equal to.</p> <p>I wrote the following code which in theory should work but it keeps saying I provided 5 arguments or something like t...
<p>I shouldn't have to do this, since you should show the full traceback with the error:</p> <pre><code>In [396]: a = np.matrix([2, 5, 6, 4], [5, 10, 9, 5], [7, 17.5, 21, 14], [0, 0, ...: 2, 5]) ...: b = np.matrix([23.5, 34, 82.25, -13]) ...: ...: x = np.linalg.solve(a,b) Traceback (most recent cal...
numpy|matrix
2
10,954
70,659,327
Fast Bitwise Sum in Python
<p>Is there an efficient way to calculate sum of bits in each column over array in Python?</p> <p>Example (Python 3.7 and Numpy 1.20.1):</p> <ol> <li>Create numpy array with values 0 or 1</li> </ol> <pre><code>import numpy as np array = np.array( [ [1, 0, 1], [1, 1, 1], [0, 0, 1], ] ) </...
<p>Using <code>np.unpackbits</code> can be problematic if the input array is big since the resulting array can be <strong>too big to fit in RAM</strong>, and even if it does fit in RAM, this would be far from being efficient since the huge array have to be written and read from the (slow) main memory. The same thing ap...
python|numpy|bitwise-operators|binary-operators
2
10,955
70,423,380
cursor.execute() invalid syntax error when exporting data to SQL Server - column name starts with a number
<p>I am exporting data from pandas Dataframe to SQL Server using Pyodbc. I have a problem, faced for the first time - that when I insert into a SQL Server column with a name that starts with a number - <code>5star</code> - the for loop doesn't capture the name of the column, highlights number as it was not part of the...
<p>I recommend using <code>sqlalchemy</code>:</p> <pre><code>from sqlalchemy import create_engine import pandas as pd quoted = urllib.parse.quote_plus(&quot;DRIVER={SQL Server Native Client 11.0};SERVER=(localDb)\ProjectsV14;DATABASE=database&quot;) engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quot...
sql|pandas|pyodbc
0
10,956
42,734,801
Matplotlib button generating random circles
<p>everyone! I'm using matplotlib and I have a field with randomly generated circles. Also I have button which has to generate new random circles in the field but every time I press it, circles are generated inside the BUTTON, but not in the field. Please show me what I'm doing wrong, I'm new to python(actually sta...
<p>You need to tell matplotlib that you want to use the main figure axis to draw the points. By calling <code>plt.scatter</code> you tell matplotlib to use the current axis, which in your case happens to be the button itself. Here's a modified version of your code that uses explicit axes:</p> <pre><code>import numpy a...
python|numpy|matplotlib
1
10,957
42,737,699
Inconsistent PIL.ImageTk.PhotoImage() performance
<p>I am converting numpy arrays (webcamera footage loaded with OpenCV) into Tkinter PhotoImage objects to display them on Tkinter GUI. However, the function <code>PIL.ImageTk.PhotoImage()</code> experiences around 800 ms peaks that result in serious drops in frame rate. Here's the snippet:</p> <pre><code>ar = Image.fr...
<p>Whereas I did not find out the reason or fix to this, I found a workaround that allowed me to have reasonable performance without constant freezes. This solution has two parts:</p> <p>1) Every captured frame is transfromed into <code>ImageTk.PhotoImage</code> object as before. However, I also measured the duration ...
python|opencv|numpy|tkinter|python-imaging-library
0
10,958
42,917,899
Changing pixel values in of a 50x50 square 2d numpy array
<p>Doing a bit of image processing in python and I am trying to change the value of a 50x50 square of numpy array and each square would change every 200 pixels. So far this is what I have:</p> <pre><code> image_data[0::200,0::200] = 999 </code></pre> <p>This plants an extremely bright pixel every 200 spaces. I, howev...
<p>You can do it like that:</p> <pre><code>import numpy as np image_data=np.zeros([1017,1017]) places=np.arange(-25,26) centers=np.array([[200*i]*len(places) for i in range(1,len(image_data)//200+1)]) index_list=np.concatenate(centers+places) index_list=index_list[index_list&lt;len(image_data)] image_data[np.ix_(index...
python|arrays|numpy|image-processing
1
10,959
43,019,241
Pandas sum of all word counts in column
<p>I have a pandas column that contains strings. I want to get a word count of all of the words in the entire column. What's the best way of doing that without looping through each value?</p> <pre><code>df = pd.DataFrame({'a': ['some words', 'lots more words', 'hi']}) </code></pre> <p>when run on <code>df['a']</code>...
<p>You could use the <a href="http://pandas.pydata.org/pandas-docs/stable/text.html" rel="noreferrer">vectorized string operations</a>:</p> <pre><code>In [7]: df["a"].str.split().str.len().sum() Out[7]: 6 </code></pre> <p>which comes from</p> <pre><code>In [8]: df["a"].str.split() Out[8]: 0 [some, words] 1...
python|pandas
9
10,960
42,660,052
How to make numpy array the same shape as another
<p>I have a numpy array that looks like this: </p> <pre><code>[ 7.1101 6.5277 9.5186 8.0032 6.8598 9.3829 8.4764 9.5781 7.4862 6.0546 6.7107 15.164 6.734 9.4084 6.6407 6.3794 7.3654 6.1301 7.4296 8.0708 7.1891 21.27 6.4901 7.3261 6.5649 19.945 13.828 11.957 ...
<p>Search for "numpy reshape" and you'll soon have your answer. ;)</p> <pre><code>my_array.reshape(m, n) </code></pre> <p>returns the array reshaped as requested (m rows, n columns).</p> <p>Note that it doesn't modify the original my_array object.</p>
python|arrays|numpy
1
10,961
42,792,185
Get data array from object in Python
<p>I'm using a <a href="http://pykriging.com/" rel="nofollow noreferrer">library</a> which produces 3 plots given an object <code>k</code>.</p> <p>I need to figure the data points <code>(x,y,z)</code> that produced these plot, but the problem is that the plots comes from a function from <code>k</code>.</p> <p>The lib...
<p>There is no single data array that produces the plot. Instead many arrays used for plotting are generated inside the kriging plot function.<br> Changing the filled contours to line contours is of course not a style option. One therefore needs to use the code from the original plotting function. </p> <p>An option i...
python|numpy|matplotlib|kriging
1
10,962
26,939,766
Looping through csv files and outputting calculations to one consolidated csv file
<p>I am trying to loop through a specified folder, containing a bunch of .csv files. The purpose is to gather three metrics listed in each file, add them up, and output that to a row in a consolidated, soon-to-be-produced-by-python csv file.</p> <p>This is my code:</p> <pre><code>import pandas as pd import os result...
<p>When you create the <code>results_output</code> dataframe, you are creating it with zero elements in the index. That's why (I think) it throws you an error when you try to access it. Try creating it with an index equal to the number of files. I also changed the way you used <code>count</code> 'cause I think it was o...
python|python-2.7|loops|csv|pandas
1
10,963
27,310,325
Is there a way to let numpy matrix to store object?
<p>I would like to store a tuple inside numpy matrix, but it seems like it will return an error. Is there a way to go about it?</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; y = numpy.zeros((4,4)) &gt;&gt;&gt; y[1][1] = (1,1) ValueError: setting an array element with a sequence. </code></pre> <p>Thanks</p>
<p>use <code>dtype=object</code> and you can put anything in your array that you want:</p> <pre><code>&gt;&gt;&gt; arr = np.zeros((4, 4), dtype=object) &gt;&gt;&gt; arr[1, 1] = (1, 1) &gt;&gt;&gt; arr array([[0, 0, 0, 0], [0, (1, 1), 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], dtype=object) </code></pre>
python|object|numpy|matrix
5
10,964
25,059,140
Pandas Multiindex not working with read_csv and datetime objects
<p>I have a problem loading a dataframe from csv when I have a multiindex with more than one date in it.</p> <p>I am running the following code:</p> <pre><code>import pandas as pd import datetime date1 = datetime.date.today() date2 = datetime.date.today().replace(month=1) date_cols=['date1', 'date2'] index = pd.Multi...
<p>What you are doing is subtlely different.</p> <pre><code>In [31]: df.index.levels[0] Out[31]: Index([2014-07-31], dtype='object') In [32]: dfr.index.levels[0] Out[32]: &lt;class 'pandas.tseries.index.DatetimeIndex'&gt; [2014-07-31] Length: 1, Freq: None, Timezone: None </code></pre> <p>The initial creation (usin...
python|datetime|pandas|multi-index
1
10,965
25,086,316
Merging and Filling in Pandas DataFrames
<p>I have two dataframes in Pandas. The columns are named the same and they have the same dimensions, but they have different (and missing) values.</p> <p>I would like to merge based on one key column and take the max or non-missing data for each equivalent row.</p> <pre><code>import pandas as pd import numpy as np ...
<p>Often it is easiest in these circumstances to do:</p> <pre><code>df_together = pd.concat([df1, df2]).groupby('key').max() </code></pre>
python|python-2.7|pandas|merge|dataframe
3
10,966
39,358,024
python - different encoding results by setting the "encoding" parameter in diff. functions
<p>I have a function like </p> <pre><code>f = open('workfile', 'r', encoding='utf-8') df = pandas.read_csv(...) </code></pre> <p>, which opens a csv file. When I tried to set the <code>encoding</code> parameter to <code>read_csv</code> function, I got other encoding results, than by setting the parameter to <code>ope...
<p>This is what happens in your program</p> <pre><code>f = open('workfile', 'r', encoding='utf-8') # 1 df = pandas.read_csv(f, encoding=e) # 2 </code></pre> <p>(1) The file is told to decode bytes using the encoding 'utf-8'. If you print the representation of the file handle f it will show something like </p> <pre><...
python|pandas|character-encoding
0
10,967
39,191,111
How to create Panda Dataframe from csv that is compressed in tar.gz?
<p>How can I create the pandas DataFrame from csv file that's compressed in tar.gz? I found this code which does that but with zip file. What should I change in the following code to make it work with tar.gz without downloading the tar.gz and csv file. </p> <pre><code>import pandas, requests, zipfile, StringIO r =req...
<p>Can you try below for extracting tar.gz as below :</p> <pre><code>import tarfile tar = tarfile.open(fname, "r:gz") tar.extractall() tar.close() </code></pre>
python|csv|pandas|gzip|tar
1
10,968
23,762,712
Python Pandas: Adding methods to class pandas.core.series.Series
<p>I want to work with a time series in Python and, therefore, Pandas' Series class is just perfect and has a lot of useful methods.</p> <p>Now I want to add some methods that I need and are not implemented. For example, let us say I am interested in adding a method which appends two times one value to the time series...
<p>You could do something like this. You don't need to sub-class at all, rather just <a href="http://pandas-docs.github.io/pandas-docs-travis/faq.html#adding-features-to-your-pandas-installation" rel="noreferrer"><em>monkey-patch</em></a>. And this would be more efficient that appending twice (as an append copies).</p>...
python|pandas
8
10,969
23,922,250
How do I get the subset of a DataFrame using pandas?
<p>I'm trying to split a DataFrame by a date column, where one DataFrame will be those observations that are before a certain date, and the other DataFrame will be those observations that are after that date.</p> <p>I have some data frame with some columns, where the date column is named 'date_posted'. The data frame ...
<p>This should work, so you likely have trouble with the 'date_posted' column. Is it a string and not an int?</p> <p>If its already an int try:</p> <pre><code>out_1 = proj[proj['date_posted'] &gt;= 20140101] out_2 = proj[proj['date_posted'] &lt; 20140101] </code></pre> <p>If its really a string try converting it fi...
python|pandas
0
10,970
15,330,521
NumPy array size issue
<p>I have a <code>NumPy</code> <code>array</code> that is of size (3, 3). When I print shape of the <code>array</code> within <code>__main__</code> module I get <code>(3, 3)</code>. However I am passing this array to a function and when I print its size in the function I get <code>(3, )</code>.</p> <p>Why does this ha...
<p>A tuple like this: <code>(3, )</code> means that it's a tuple with a single element (a single dimension, in this case). That's the correct syntax - with a trailing <code>,</code> because if it looked like this: <code>(3)</code> then Python would interpret it as a number surrounded by parenthesis, not a tuple.</p> <...
python|numpy|scipy
2
10,971
29,808,025
Add single element to array as first entry in numpy
<p>How to achieve this? I have a numpy array containing:</p> <pre><code>[1, 2, 3] </code></pre> <p>I want to create an array containing:</p> <pre><code>[8, 1, 2, 3] </code></pre> <p>That is, I want to add an element on as the first element of the array.</p> <p>Ref:<a href="https://stackoverflow.com/questions/73328...
<p>Use <code>numpy.insert()</code>. The docs are here: <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html#numpy.insert" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html#numpy.insert</a></p>
numpy
1
10,972
62,208,786
Float element are wrongly split when converting tuples to list in Pandas
<p>I have list of tuples that looks like given below in a Pandas column. </p> <pre><code>0 [(1, 2)] 1 [(6, 1)] 2 [(8, 10), 4+] 3 [] 4 [0.6, 1.5] 5 [] 6 [2+] 7 [(0, 1)] 8 [] 9 [] 10 [0.7, 1+] 11 ...
<p>Use custom function for flatten iterables like tuples, but not strings (because there are not floats, but string repr of floats):</p> <pre><code>#https://stackoverflow.com/a/2158532 def flatten(l): for el in l: if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)): yie...
python|python-3.x|pandas|tuples|nested-lists
0
10,973
62,222,758
Parsing Pandas Series From Another Series
<p>Am trying to parse a series of text, using a series of numbers like the code below, but all i get in return is a series of NaN's.</p> <pre><code>import numpy as np import pandas as pd numData = np.array([4,6,4,3,6]) txtData = np.array(['bluebox','yellowbox','greybox','redbox','orangebox']) n = pd.Series(numData) t ...
<p>You can use a simple list comprehension if in reality you can't chop off the last 3 characters and need to rely on your slice ranges. You will need error handling if your data aren't guaranteed to be all strings, or if <code>end</code> can exceed the length of the string.</p> <pre><code>pd.Series([x[:end] for x,end...
python|pandas
4
10,974
62,155,683
What is the fastest way to populate one pandas dataframe based on values from another pandas dataframe?
<p>I have a pandas dataframe <strong>position</strong></p> <pre><code> row column 1 3 Brazil 2 6 USA 3 3 USA 4 7 Canada </code></pre> <p>and another <strong>x</strong></p> <pre><code> Brazil Canada USA 1 False False False 2 False Fal...
<p>I will do <code>crosstab</code> with <code>update</code> </p> <pre><code>x.update(pd.crosstab(df.row,df.column).eq(1)) x Out[44]: Brazil Canada USA 1 False False False 2 False False False 3 True False True 4 False False False 5 False False False 6 False False True 7 False True False <...
python|pandas|numpy|dataframe
4
10,975
62,314,390
sklearn impute rows satisfying condition
<p>I'm trying to use sklearn SimpleImputer to impute missing ages from a particular column in a pandas DataFrame containing Titanic data. However, I want to <em>separately</em> impute the missing values for passengers whose names contain the word "Master" using the average of the other Master's ages.</p> <p>I tried lo...
<p>You need to fit first and use that to transform the data. When you fit the imputer you use the column along with the missing values. Use that fitted model to impute the missing values using transform as i used below.</p> <p>Can you try this?</p> <pre><code>imp = Imputer(missing_values='NaN', strategy='mean', axis=...
python|pandas|scikit-learn|imputation
0
10,976
62,108,063
RuntimeError: Error(s) in loading state_dict for Actor - torch.load()
<p>I have created a custom environment in open ai gym and i am facing error while loading the weights Could some one help me to resolve the issue . I am training a TD3 network in a custom environment and i have trained successfully but while inferencing i am facing this issue </p> <pre><code>class Actor(nn.Module): ...
<p>it was answered by @MicaelJungo</p> <p>The weights you saved were not from the model you are using here. Make sure to load the correct checkpoint, which was created when training this particular model.</p>
python-3.x|pytorch|reinforcement-learning|openai-gym
0
10,977
62,447,235
Why a reading in numpy array would be slower than in a dict?
<p>I tried to make a comparaison between reading in a dictionary and in a numpy array. </p> <p>I was sure that the numpy array will be faster, as when I do <code>numpy_array[i]</code> it just have to check the ith word after the start of the array, but doing <code>dictionary[i]</code> will use hash computation and use...
<p>One thing to note is that a numpy array has quite a lot of book-keeping, see <a href="https://numpy.org/devdocs/reference/arrays.ndarray.html#array-attributes" rel="nofollow noreferrer">ndarray attributes</a>. You can corrupt an array, just for fun, by changing the value of the <code>strides</code> attribute.</p> <...
python|arrays|numpy
0
10,978
62,363,134
Time series dataframe fill values with same period data
<p>I have a dataframe that contains NaN values and I want to fill the missing data using information of the same month.</p> <p>the dataframe looks this:</p> <pre><code>data = {'x':[208.999,-894.0,-171.0,108.999,-162.0,-29.0,-143.999,-133.0,-900.0], 'e':[0.105,0.209,0.934,0.150,0.158,'',0.333,0.089,0.189], } d...
<p>Try grouping in index.month and get mean (<code>transformed</code>) then fillna</p> <pre><code>df.index = pd.to_datetime(df.index) out = df.fillna({'e':df.groupby(df.index.month)['e'].transform('mean')}) </code></pre> <hr> <pre><code>print(out) x e 2020-01-01 208.999 0.1050 2020-02-01 -8...
python|pandas
2
10,979
62,090,924
This code work for only 4 or 5 iteration, how is this possible?
<p>my code is genetic algorithm and its only works for 4-5 times and after 4-5. work, suddenly stops and gives error "IndexError: index 22 is out of bounds for axis 0 with size 22" ,I paid attention to making "-1" to avoid index error, but the code still insists on stopping. It's genetic algorithm code, and its solving...
<p>OK found the problem. In the following loops <code>counter</code> can indeed end up <code>&gt;21</code></p> <pre><code>counter=point1 for i in range(city-1): for j in range(point1+1,point2): if parent2[i]==parent1[j]: counter=counter+1 child1[counter]=parent2[i] counter=poin...
python|algorithm|numpy|genetic
2
10,980
51,325,424
Using an array for indexing for training network (tensorflow)
<p>I am relatively new to tensorflow and am running into problems trying to index tensors properly. Towards the bottom of the shown, I am trying to use x (which itself is a tensor containing an array form such as [[0,1], [2,3]]) in order to index the y_rt tensor (one can think it as slicing the y_rt tensor). However, I...
<p>As of version 1.9 TensorFlow doesn't support indexing by arrays using slice notation. From the <a href="https://www.tensorflow.org/api_docs/python/tf/boolean_mask" rel="nofollow noreferrer">tf.Tensor documentation for <code>__getitem__</code></a>:</p> <blockquote> <p>This operation extracts the specified region f...
python|numpy|tensorflow|tensor
0
10,981
51,513,861
Error while changing Pandas DataFrame index using map method
<pre><code>import pandas as pd import numpy as np import string df = pd.DataFrame(np.arange(12).reshape(3,4), index = list('abc'), columns = list('wxyz')) df w x y z a 0 1 2 3 b 4 5 6 7 c 8 9 10 11 </code></pre> <p>I know that I can change the index using the map method in this way.</p> <pre><...
<p>There is no syntactical difference. There is a difference in the type of object you are using as a parameter to <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.Index.map.html" rel="nofollow noreferrer"><code>pandas.Index.map</code></a>. The docs make clear what's permitted:</p> <blockqu...
python|string|pandas|dataframe
0
10,982
48,191,115
Is the data parameter for pandas.DataFrame lazily evaluated?
<p>Re:</p> <blockquote> <p>class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)[source]</p> </blockquote> <p>And:</p> <blockquote> <p>classmethod DataFrame.from_records(data, index=None, exclude=None, columns=None, coerce_float=False, nrows=None)[source]</p> </blockquote> <p>I...
<p>See testcase in original post. the methods are eager</p>
python|sql-server|pandas
0
10,983
48,083,474
Finish Tensorflow training in progress
<blockquote> <p>Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?</p> </blockquote> <p>I'm currently training <a href="https://github.com/ibab/tensorflow-wavenet/blob/master/README.md" rel="nofollow noreferrer">Tensorfl...
<p><code>train.py</code> has an option for how often to save a checkpoint. For example,</p> <pre><code>train.py --checkpoint_every=10 ... </code></pre> <p>to save the checkpoint every 10 steps. By default, it is saved every 50 steps. Once you have a checkpoint, you should be able to use <code>generate.py</code>.</p>
algorithm|audio|tensorflow|machine-learning|artificial-intelligence
0
10,984
48,724,272
How do i merge a dataframe based off an address and longitude and latitude? Python
<p>I have a csv davaset like this which i geocoded and added in the long lat columns, and it has these columns<a href="https://i.stack.imgur.com/EKHlJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EKHlJ.png" alt="My Dataset"></a></p> <p>now i download an updated one online and it sometimes adds in...
<p>If you have primary indices in both tables, I think the easiest way is to use <code>pandas</code>, something similar to:</p> <blockquote> <pre><code>import pandas as pd a = pd.read_csv('filename1.csv') b = pd.read_csv('filename2.csv') c = a.merge(b, how = 'left', left_on = 'INDEX IN A', right_on = 'INDEX IN B') </...
python|pandas|merge|concatenation
0
10,985
48,880,934
Performance decrease for huge amount of columns. Pyspark
<p>I met problem with processing of spark wide dataframe (about 9000 columns and sometimes more). <br>Task:</p> <ol> <li>Create wide DF via groupBy and pivot. </li> <li>Transform columns to vector and processing in to KMeans from pyspark.ml.</li> </ol> <p>So I made extensive frame and try to create vector with Vector...
<p>Actually solution was found in <a href="https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.map" rel="nofollow noreferrer">map</a> for rdd. </p> <ol> <li>First of all we going to create map of values. </li> <li>Also extract all distinct names.</li> <li>Penultimate step we are searching each val...
python|pandas|apache-spark|machine-learning|pyspark
2
10,986
48,552,996
Recursive FFT discards the imaginary part
<p>I am trying to implement recursive FFT.</p> <pre><code>import numpy as np from math import e, pi def rdft(a): n = a.size if n == 1: return a i = complex(0, 1) w_n = e ** (2 * i * pi / float(n)) w = 1 a_0 = np.zeros(int(math.ceil(n / 2.0))) a_1 = np.zeros(n / 2) for index in ...
<p>You try to cast complex numbers to a numpy array that has been defined as float. To overcome this problem, define <code>y</code> as a numpy array with complex values:</p> <pre><code>y = np.zeros(n, dtype = complex) </code></pre> <p>Output after this change:</p> <pre><code>[-1.+0.j 1.+2.j 3.+0.j 1.-2.j] </code>...
python|python-2.7|numpy|fft
2
10,987
48,446,306
Large dataset with many weights causing an extremely slow training process with Tensorflow
<p>I have a background in biology and am currently experimenting and learning machine learning to train a microarray dataset I have that consists of 140 cell lines with 54871 gene expressions of each cell line. Essentially, I have 140 rows, each row is comprised of 54871 columns representing a value that is a gene expr...
<p>A few key issues here. You're trying to define a 1-layer neural network, which sounds good for this problem. But your hidden layer is much larger than it should be. Experiment with smaller weight sizes. Try 128, 256, 512, numbers like this (powers of two are not required). </p> <p>Also, your input dimensionality is...
python|tensorflow|large-data|large-files
1
10,988
70,854,880
Pytorch: Most computationally and memory efficient way to make a series of concatenations from extracting tensor rows?
<p>Say that this is my sample tensor</p> <pre><code>sample = torch.tensor( [[2, 7, 3, 1, 1], [9, 5, 8, 2, 5], [0, 4, 0, 1, 4], [5, 4, 9, 0, 0]] ) </code></pre> <p>I want to have a new tensor, which will consist of concatenations of 2 rows from the sample tensor.</p> <p>So I have a tensor whi...
<p>What you have should be pretty fast. An alternative is</p> <pre class="lang-py prettyprint-override"><code>sample[cat_indices].reshape(cat_indices.shape[0],-1) </code></pre> <p>You would have to benchmark the performance on your machine though to see which is better.</p>
pytorch
2
10,989
70,875,955
How to remove duplicated rows based on values in column
<p>Good morning guys. So my problem is to remove duplicates from dataframe caused by many diffrent values in one of columns.</p> <p>The base dataframe looks like this below:</p> <p><a href="https://i.stack.imgur.com/z86SS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z86SS.png" alt="enter image des...
<p>It depends what need - if possible duplicates per <code>Name</code> and <code>Id</code> is necessary aggregate <code>max</code>:</p> <pre><code>df = (pd.get_dummies(df, columns=['Category']) .groupby(['Name','Id'], as_index=False) .max()) print (df) Name Id Category_A Category_B Category_C 0 ...
python|pandas|numpy|series
1
10,990
70,749,135
How to running a custom function with Groupby and Apply in Pandas
<p>I am trying to run a custom function on a Pandas dataframe, so that I runs for each name and gives me output, then runs on a similar group of names. But I'm stuck and can't seem to figure out how to finish up here.</p> <pre><code>INPUT: NAME STEPS 0 Andrew PASS 1 Andrew PASS 2 And...
<p>Assuming your function does what it should you can run it like this to get what you want.</p> <pre><code>results = {} for name in df.NAME.unique(): results[name] = my_function(df[df[&quot;NAME&quot;]==name]) </code></pre>
python|pandas
0
10,991
51,647,825
Keras and make_csv_dataset compatibility
<p>Can tf.contrib.data.make_csv_dataset() be used for Keras models in tensorflow 1.9.0?</p>
<p>Yes, tf.contrib.data.make_csv_dataset() returns a tf.data.Dataset and you can pass tf.data.Dataset to the fit method of Keras models. See some examples here: <a href="https://www.tensorflow.org/guide/keras#input_tfdata_datasets" rel="nofollow noreferrer">https://www.tensorflow.org/guide/keras#input_tfdata_datasets</...
tensorflow|keras
1
10,992
51,766,729
Pandas group: how to find the N largest values in multiple columns of each group?
<p>I log a device and read 3 values (<code>W1</code>, <code>W2</code>, <code>W3</code>) every 15 minutes. They could be repeated.</p> <p>I need to find <strong>for every hour what are the max 3 values among the 12 that has been read</strong> in that interval. I am not interested to know <em>when</em> they occurred, on...
<p>You can first flatenning all values to <code>1d</code> array by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html" rel="nofollow noreferrer"><code>numpy.ravel</code></a>, <a href="https://stackoverflow.com/a/45877045/2901002">sort it in descending order</a> and return top <code>3</code> ...
pandas|pandas-groupby
2
10,993
41,948,035
Numpy solving 3d linear equation without loop
<p>I want solve linear equation Ax= b, each A contains in 3d matrix. For-example,</p> <p>In Ax = B, Suppose A.shape is (2,3,3) </p> <p>i.e. = [[[1,2,3],[1,2,3],[1,2,3]] [[1,2,3],[1,2,3],[1,2,3]]]</p> <p>and B.shape is (3,1) i.e. [1,2,3]^T</p> <p>And I want to know each 3-vector <strong>x</strong> of Ax = B i.e.(x_...
<p>For invertible matrices, we could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html" rel="nofollow noreferrer"><code>np.linalg.inv</code></a> on the <code>3D</code> array <code>A</code> and then use tensor matrix-multiplication with <code>B</code> so that we lose the last and fi...
python|numpy|matrix|vectorization
1
10,994
64,345,289
Normalizing images passed to torch.transforms.Compose function
<p>How to find the values to pass to the transforms.Normalize function in PyTorch? Also, where in my code, should I exactly do the transforms.Normalize?</p> <p>Since normalizing the dataset is a pretty well-known task, I was hoping there should be some sort of script for doing that automatically. At least I couldn't fi...
<h2>Source code errors</h2> <blockquote> <p>How to pass these values and where? I assume I should do it in transforms.Compose method but I might be wrong.</p> </blockquote> <p>In <code>MothLandmarksDataset</code> it is no wonder it is not working as you are trying to pass <code>Dict</code> (<code>sample</code>) to <cod...
machine-learning|deep-learning|computer-vision|pytorch|normalize
2
10,995
49,111,093
Pandas combine multiple csv files
<p>I have multiple csv files that I would like to combine into one df.</p> <p>They are all in this general format, with two index columns:</p> <pre><code> 1 2 CU0112-005287-7 Output Energy, (Wh/h) 0.064 0.066 CU0112-005287-7 Lights (Wh) 0 0 ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> instead <code>merge</code>:</p> <pre><code>df = pd.concat([pd.read_csv(f, index_col=[0,1]) for f in files]) </code></pre>
python|pandas
4
10,996
49,312,367
I need some explanations about GAN codes
<p><a href="https://github.com/SherlockLiao/pytorch-beginner/blob/master/09-Generative%20Adversarial%20network/simple_Gan.py" rel="nofollow noreferrer">Here is github codes</a></p> <pre class="lang-python prettyprint-override"><code>for epoch in range(num_epoch): for i, (img, _) in enumerate(dataloader): num_img...
<p>As you probably know: In GAN, generator tries to fool the discriminator by convincing that a fake example is a true example. Discriminator trained to distinguish true examples and fake examples. On the other hand, the generator is trained to generate (fake) examples that look very close to the real examples.</p> <h...
python-3.x|pytorch|generative-adversarial-network
2
10,997
58,658,265
How to set kernel values for Keras convolutional layer in TF 2.0?
<p>How can I set kernel values for Conv1D layer in TF 2.0?</p> <pre><code>model = tf.keras.Sequential() model.add(tf.keras.layers.Conv1D(1, 3, activation='relu', input_shape=(6, 1))) inp = tf.reshape(tf.constant([1,3,3,0,1,2.]), (1, 6, 1)) print(f'{model(inp)}') # [[[3.6809962 ] # [5.356483 ] # [2.4707034 ] # [...
<p><strong>Data</strong>:</p> <pre><code>import numpy as np input_data = np.array([1,3,3,0,1,2]).reshape((1,-1,1)) #(1 sample, length, 1 channel) kernel = np.array([2,0,1]).reshape((3,1,1)) #(size, input_channels, output_channels) bias = np.zeros((1,)) # 1 channel </code></pre> <p><strong>Model</strong>:</p> <p>...
python|tensorflow|keras|conv-neural-network
2
10,998
59,034,334
Plot cluster matrix
<p>I want to plot a cluster matrix from K-means from scikit-learn using the following pandas dataframe:</p> <pre><code>from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() # toy dataset data = pd.DataFrame(cancer.data, columns=[cancer.feature_names]) df = data.iloc[:,4:8] #select subset df.col...
<p>IIUC, you could simplify using <a href="https://seaborn.pydata.org/generated/seaborn.pairplot.html" rel="nofollow noreferrer"><code>seaborn.pairplot</code></a> and pass in <code>Kmeans.label_</code> as the <code>hue</code> argument. For example:</p> <pre><code>import seaborn as sns from sklearn.cluster import KMean...
python|pandas|matplotlib|scikit-learn|cluster-analysis
2
10,999
58,957,951
Convert json to pandas with no header
<p>I have an incoming json from a http request. I can get the result back without problems. But i can't seem to get it into a dataframe. I will end up as null when doing this. I have tried with several variations of dataframe and other. But it will either end up null och with throwing an error.</p> <pre><code>r=reques...
<p>After reading the second comment it was crystal clear. Just posting the answer for clarity.</p> <p>Using the incoming JSON directly with the from_records will correctly create the dataframe. Also for me coming from Spark I tried with different things like head() etc. for printing the dataframe. This can be done dir...
python|pandas
0