Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
366,400
66,684,869
Seaborn regression lineplot for a vector stored as list in a dataframe column
<p>I have a dataframe where one of the columns is a 16 element vector (stored as a list). In the past, I have found seaborn's <code>lineplot</code> highly useful for regression analysis on a scalar column. The vector column has me in a bind.</p> <p>Consider a seaborn sample program:</p> <pre><code>import seaborn as sns...
<p>Assuming that you want one line for each index in the list, e.g., the value at the 0th index for all rows will create a single line. To do this, we need to first <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>explode</code></a> the l...
python|pandas|dataframe|plot|seaborn
1
366,401
66,576,427
Color 1 word in a text string in Pandas Dataframe and corresponding values
<p>I am using jupyter notebook to return this dataframe. I am trying to color the word &quot;Bullish&quot; green and &quot;Bearish&quot; red. Also if it is bullish the Buy/Sell Trade price should be green and Bearish the Buy/Sell price should be Red. Thanks for your help!</p> <p>Sample file here: <a href="https://drive...
<p>You can colour using <code>style</code></p> <pre><code>def cts(x): c1 = 'color: red' c2 = 'color: green' c3 = 'color: black' if 'BULLISH' in x['INDEX']: return c3,c1,c1 elif 'BEARISH' in x['INDEX']: return c3,c2,c2 else: return c3,c3,c3 df = df.reset_index(drop=True)....
python|pandas|dataframe
1
366,402
16,106,639
Pandas floating point issue with cumsum and division
<p>I've ranked the total sales (TOTAL_2012) in descending order and am trying to get the list of groups to have roughly 25% of the sales thus tier 1 group is grossing the most sales/company. </p> <pre><code>sales['PERCENT_2012'] = sales['TOTAL_2012'] / sales['TOTAL_2012'].sum() sales['CUM_PERCENT_2012'] = sales['PERC...
<p>Add .round():</p> <pre><code>sales['PERCENT_2012'] = sales['TOTAL_2012'] / sales['TOTAL_2012'].sum() sales['CUM_PERCENT_2012'] = sales['PERCENT_2012'].cumsum().round(2) </code></pre> <p>This actually rounds the data before adding it to the column. You can also use np.round(df) to round the data only for presentin...
python|pandas|floating-point-precision
3
366,403
16,359,955
Concatenating dictionaries of numpy arrays of different lengths (avoiding manual loops if possible)
<p>I have a question similar to the one discussed here <a href="https://stackoverflow.com/questions/16106134/concatenating-dictionaries-of-numpy-arrays-avoiding-manual-loops-if-possible#comment23006444_16108847">Concatenating dictionaries of numpy arrays (avoiding manual loops if possible)</a></p> <p>I am looking for ...
<p>One way is to go is use a dictionary of Series (i.e. the values are Series rather than arrays):</p> <pre><code>In [11]: d2 Out[11]: {'r': array([ 0.3536318 , 0.29363604, 0.91307454]), 's': array([46])} In [12]: d2 = {name: pd.Series(arr) for name, arr in d2.iteritems()} In [13]: d2 Out[13]: {'r': 0 0.353632 ...
python|dictionary|pandas|concatenation
1
366,404
16,147,559
Using numpy vector elements in Fraction module in Python
<p>I'm trying to use elements from a numpy array as an input for the <code>Fraction</code> module and I'm getting the following error: <em>"TypeError: both arguments should be Rational instances"</em></p> <p>For example, if I do:</p> <pre><code>Y = np.array([7,1], dtype='int64') X = Y[0]*3+Y[1] </code></pre> <...
<p>This seems to be one of the unfortunate artifacts of the way Numpy integers interact with Python's abstract classes (and it's also dependent on whether you run a 32-bit or 64-bit Python, because <code>dtype='int'</code> means either <code>np.int32</code> or <code>np.int64</code>, but never Python <code>int</code>).<...
python|numpy|fractions
5
366,405
16,377,503
Use SWIG to wrap C++ <vector> as python NumPy array
<p>I have a C++ library that defines the following (and more like them) types:</p> <pre><code>typedef std::vector&lt; double &gt; DoubleVec; typedef std::vector&lt; DoubleVec &gt; DoubleVecVec; typedef std::vector&lt; int &gt; IntVec; typedef std::vector&lt; IntVec &gt; IntVecVec; </code></pre> <p>I am trying to c...
<p>Try this as a starting point.</p> <pre><code>%include "numpy.i" %apply (size_t DIM1, double* IN_ARRAY1) {(size_t len_, double* vec_)} %rename (foo) my_foo; %inline %{ int my_foo(size_t len_, double* vec_) { std::vector&lt;double&gt; v; v.insert(v.end(), vec_, vec_ + len_); return foo(v); } %} %apply ...
c++|numpy|swig
4
366,406
57,381,360
Tensorflow 2.0 beta GPU running in jupyter notebook, but not in google colab
<p>I am working with tensorflow 2.0 beta, and while i managed to get my GPU working on anaconda through a few youtube tutorials I am unable to get my gpu running in google colab. I know google has the option to enable a gpu from one of their servers but My GTX 1070 is much faster, and i need to run off colab and not ju...
<p>If you can get it running on your own Jupyter server then you can point colab to that local server.</p> <p>Full instructions here: <a href="https://research.google.com/colaboratory/local-runtimes.html" rel="nofollow noreferrer">https://research.google.com/colaboratory/local-runtimes.html</a> but edited highlights a...
tensorflow|google-colaboratory|tensorflow2.0
1
366,407
57,701,907
how to change start end time in CustomBusinessHour based weekmask is equal to monday
<p>I want to change start end time in CustomBusinessHour if i get monday in weekmask list from startdate and enddate . start = 00:01 end = 23:59 </p> <p>i am trying to change this start to 07:00 and end =23:59 if i get monday b/w startdate and enddate </p> <pre><code>data = { 'start': ['2018-10-29 18:48:46.69700...
<p>You could use <code>apply</code> with a function, to feed the start and end <code>datetime</code> for each row. Then you use a mask on top of your <code>CustomBusinessHour</code>.</p> <pre><code>import pandas as pd from pandas.tseries.offsets import CustomBusinessHour from pandas.tseries.holiday import USFederalHol...
python|pandas|numpy
2
366,408
57,307,326
How I can give the names of 3D matrix dimensions using dataframe (Pandas)
<p>I want to give the names to the 3D matrix from a list I already have. I can only able to give one side a name but not to other 2 sides.</p> <p>As mentioned in the code, I am only able to put one side, but I want to put names of 3 different sides.</p> <pre><code>subjects_in_graph = ['C', 'c1', 'c2'] edges_in_graph ...
<p>Put <code>index</code> and <code>columns</code> in <code>pd.DataFrame</code>:</p> <pre><code>df=pd.concat([pd.DataFrame(x, index=edges_in_graph[::-1], columns=subjects_in_graph) for x in matrix], keys=subjects_in_graph) print(df) </code></pre> <p>Output:</p> <pre><code> C c1 c2 C p1 0.0 0.0 0.0 ...
python|pandas|numpy|tensor
0
366,409
57,386,859
the best way to get uniform behavior for dense and sparse array?
<p>For example, in the following operation, you get different variable types and dimension shapes for normal array or matrix. This is a bit annoying. I am writing a function that accepts either array or sparse array for the universal operation. Besides just its sparsity and convert it to dense array ahead of time, is t...
<pre><code>In [162]: b Out[162]: &lt;2x2 sparse matrix of type '&lt;class 'numpy.int64'&gt;' with 2 stored elements in Compressed Sparse Row format&gt; In [163]: b.A ...
numpy|scipy|sparse-matrix
0
366,410
57,373,485
How to automate extraction of values represented by numpy array associated with keys as separate data from a dictionary
<p>I have a python dictionary that contains values that are saved within multiple numpy arrays for each key. I want to extract the values from each key in an automated way rather than individually go through each key to extract the values with for instance dictname[key1], dictname[key2], etc.</p> <p>I have tried 'for...
<p>You need to use <code>dict.items</code> to access the key-value</p> <p><strong>Ex:</strong></p> <pre><code>for key, value in Win_mapping.items(): node_key = [value] print(node_key) </code></pre>
python|numpy|dictionary
0
366,411
57,465,798
Equivalent of pd.Series.str.slice() and pd.Series.apply() in cuDF
<p>I am wanting to convert the following code (which runs in pandas) to code that runs in cuDF.</p> <p>Sample data from <code>.head()</code> of Series being manipulated is plugged into OG code in the 3rd code cell down -- should be able to copy/paste run.</p> <h1>Original code in pandas</h1> <pre><code># both are fl...
<p>You can use cuDF string methods (via nvStrings) for almost everything you're trying to do. You will lose some precision converting these floats to strings in cuDF (though it may not matter in your example above), so for this example I've simply converted beforehand. If possible, I would recommend initially creating ...
python|pandas|series|rapids|cudf
1
366,412
57,595,257
Styling upper triangular, lower triangular, and diagonal of a pandas dataframe
<p>I have generated a pandas dataframe and I want to use <code>pd.DataFrame().style</code> to highlight some cells.</p> <pre><code> v1 v2 v3 v4 v5 v1 0 1 1 1 0 v2 0 0 1 1 1 v3 0 0 0 0 0 v4 0 0 0 0 0 v5 0 0 0 0 0 </code></pre> <p>I want to color its upper and lower t...
<p>IIUC, try this:</p> <p>where df_vals:</p> <pre><code> v1 v2 v3 v4 v5 v1 0 1 1 1 0 v2 0 0 1 1 1 v3 0 0 0 0 0 v4 0 0 0 0 0 v5 0 0 0 0 0 def triang(df): temp=df.copy() ut=np.triu(np.ones(df.shape),1).astype(np.bool) lt=np.tril(np.ones(df.shape),-1)...
pandas|dataframe|pandas-styles
3
366,413
57,323,465
Assign Keras/TF/PyTorch layer to hardware type
<p>Suppose we have the following architecture:</p> <ol> <li>Multiple CNN layers</li> <li>RNN layer</li> <li>(Time-distributed) Dense classification layer</li> </ol> <p>We want to train this architecture now. Our fancy GPU is very fast at solving the CNN layers. Although using a lower clockrate, it can perform many co...
<p>Basically, in Pytorch you can control the device on which variables/parameters reside. AFAIK, it is your responsibility to make sure that for each operation all the arguments reside on the same device: i.e., you cannot <code>conv(x, y)</code> where <code>x</code> is on GPU and <code>y</code> is on CPU.</p> <p>This ...
tensorflow|keras|deep-learning|pytorch
1
366,414
57,298,589
Loop all columns for value in any column
<p>I'm trying to loop through all columns in a dataframe to find where a "Feature" condition is met in order to alter the FeatureValue. So if my dataframe(df) looks like below:</p> <pre><code>Feature FeatureValue Feature2 Feature2Value Cat 1 Dog 3 Fish ...
<p>Here is a way to do it :</p> <pre><code># First we construct a dictionary linking each feature to its value column feature_value = {'Feature' : 'FeatureValue', 'Feature2' : 'Feature2Value'} # We iterate over each feature column for feature in feature_value: df.loc[df[feature]=='Cat', feature_value[feature]] = ...
python|pandas
2
366,415
57,673,256
Pivoting Data in python
<p>I'm calculating attendance of employees, here is the sample table</p> <pre><code>df = pd.DataFrame({ 'E_ID': [1001, 1001, 1001, 1002, 1002, 1002, 1002], 'Date': [ '28-07-2019 08:27:00', '28-07-2019 18:10:00', '29-07-2019 08:10:00', '28-07-2019 08:07:00', '29-07-2019 0...
<p>For python object dates in output <code>OfficePunch</code> column use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>Series.dt.date</code></a> with aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.co...
python|pandas|date|dataframe|pivot
7
366,416
57,545,103
Compare every value in Dataframe to create new Dataframe
<blockquote> <p>trying to compare EVERY value within the row of one dataframe against EVERY other value</p> <p>based on if decision in row that relates to the row before</p> </blockquote> <pre><code>&gt; If value1 &gt; value2: # in row_x &gt; based_on_previous_value(value1) </code></pre> <blockquote> <...
<p>Yeah, so you'll want to do several things :</p> <p>See, if you order your columns, in ascending order, the smallest value will appear at the beginning and the largest will appear at the end.</p> <p>Thanks to that, we can multiply the values by multiples of 2 depending on how far along they are on the <code>axis=1<...
python|pandas|dataframe
1
366,417
57,639,434
Use PyTorch to adjust Tensor matrix values based on numbers I calculate from the Tensors?
<p>I have two tensors (matrices) that I've initialized:</p> <pre><code>sm=Var(torch.randn(20,1),requires_grad=True) sm = torch.mm(sm,sm.t()) freq_m=Var(torch.randn(12,20),requires_grad=True) </code></pre> <p>I am creating two lists from the data inside these 2 matrices, and I am using spearmanr to get a correlation ...
<p>Pytorch has an autograd package, that means if you have variable and you pass them through differentiable functions and get a scalar result, you can perform a gradient descent to update the variable to lower or augment the scalar result.</p> <p>So what you need to do is to define a function f that works on tensor l...
python|machine-learning|pytorch|tensor|autograd
1
366,418
57,582,270
Creating one GroupBy object from another GroupBy object
<p>I grouped df by a column of interest:</p> <pre><code>grouped = df.groupby('columnA') </code></pre> <p>Now I want to retain only the groups with at least 5 members: </p> <pre><code>grouped.filter(lambda x: len(x) &gt;= 5) </code></pre> <p>If I try:</p> <pre><code>df2 = grouped.filter(lambda x: len(x) &gt;= 5) <...
<p>One workaround is to call <code>groupby</code> method on the filtered data frame</p> <pre><code>grouped = grouped.filter(lambda x: len(x) &gt;= 5).groupby('columnA') </code></pre>
python|pandas
2
366,419
57,389,459
How do I access specific columns in a pandas groupby object?
<p>I have a dataframe called p_assets_df that looks like this:</p> <pre><code> &lt;close&gt; &lt;high&gt; &lt;low&gt; &lt;open&gt; &lt;vol&gt; &lt;date&gt; &lt;ticker&gt; 20110101 AEDCAD 0.2707 0.2715 0.2707 0.2...
<p>I believe you need <code>level=1</code> and for correct align output add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>DataFrame.reset_index</code></a> by first level with <code>drop=True</code> for remove it instead <code>.value...
python|pandas
1
366,420
57,380,020
Why are Pytorch and Keras implementations giving vastly different results?
<p>I am trying to train a 1-D ConvNet for time series classification as shown in this paper (refer to FCN om Fig. 1b) <a href="https://arxiv.org/pdf/1611.06455.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1611.06455.pdf</a></p> <p>The Keras implementation is giving me vastly superior performance. Could someone...
<p>The reason of different results is due to different default parameters of layers and optimizer. For example in <code>pytorch</code> <code>decay-rate</code> of <code>batch-norm</code> is considered as <code>0.9</code>, whereas in <code>keras</code> it is <code>0.99</code>. Like that, there may be other variation in d...
keras|pytorch
2
366,421
57,331,539
jupyter nternalError: cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version
<p>I installed anaconda 3.7 on windows (following this guide: <a href="https://www.youtube.com/watch?v=tPq6NIboLSc" rel="nofollow noreferrer">https://www.youtube.com/watch?v=tPq6NIboLSc</a>) and then tried to run a code using tensorflow (<a href="https://github.com/DeepRNN/image_captioning" rel="nofollow noreferrer">ht...
<ol> <li>Updating the NVIDIA driver may solve your issue.</li> <li>Maybe you have to first match your tensorflow version with your installed Cuda Toolkit version like shown <a href="https://www.tensorflow.org/install/source#tested_build_configurations" rel="nofollow noreferrer">here</a></li> </ol>
tensorflow|anaconda|jupyter
0
366,422
57,495,344
Custom layer updates
<p>i want to create a custom layer with weights that update only in training phase.</p> <p>from the official documentation this is the way:</p> <pre><code>from keras import backend as K from keras.layers import Layer class MyLayer(Layer): def __init__(self, output_dim, **kwargs): self.output_dim = outpu...
<p>There are two types of weights:</p> <ul> <li>Trainable = Updated automatically by the optimizer with backpropagation</li> <li>Untrainable = Not updated by backpropagation</li> </ul> <p>For the trainable weights, it's really not recommended to use updates, you will be mixing the optimizer's updates with your own upda...
tensorflow|keras
1
366,423
57,351,618
Why does np.corrcoef() normalise to unity?
<p>I feel like this is a stupid question, but the site of np.corrcoef(), </p> <p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html</a></p> <p>states that it returns C_ij/sqrt{C_iiC_jj}, ...
<p>The documentation you're misreading describes the relationship between a correlation coefficient matrix and a <em>covariance matrix</em>, not the relationship between <code>numpy.corrcoef</code>'s output and input.</p> <p>If you were to compare <code>numpy.corrcoef(numpy.identity(5))</code> and <code>numpy.cov(nump...
python|numpy
1
366,424
57,598,729
K-means clustering, how to divide datas vertically?
<p>I tried to use K-means clustering method to divide 3 part of my Dataframes. I used same method and codes in 2 different Dataframes. In my first dataframe, I get 3 clusters and they separated vertically which I want. But in the second one, It clustered my datas horizontally. How can fix it? I also need to separate my...
<p>If you want to cluster vertically, <strong>use only the y attribute</strong> for clustering.</p> <p>If you also pass the x attribute data to the algorithm it will be used. And depending how you scale your data, it may depend mostly on the x or only the y attribute have I'd they vary a lot in scale.</p>
python|pandas|plot|cluster-analysis|k-means
0
366,425
57,699,599
Tensorflow keras, shuffle not shuffling sample_weight?
<p>I have a sample weight array I am feeding in to fit(). It is of equal size to the number of training examples in my input. If I turn my learning rate to zero and train for a number of epochs, I see different loss results for each epoch. If I turn shuffle=False, results stays constant and match the result from eva...
<p>You need to make <code>Shuffle=True</code> and also it shuffles only the training data and not the <a href="https://keras.io/getting-started/faq/#is-the-data-shuffled-during-training" rel="nofollow noreferrer">validation data</a>.</p> <p>If you want to explicitly shuffle the weights in keras you can use <a href="ht...
tensorflow|keras|tf.keras
0
366,426
57,454,271
Should I still normalize image data (divide by 255) before using per_image_standardization?
<p>When using Tensorflow and loading image data I currently have:</p> <pre><code>image = tf.io.decode_png(tf.io.read_file(path), channels=3) image = tf.reshape(image, [84, 84, 3]) image = tf.cast(image, tf.float32) return image / 255.0 </code></pre> <p>But, I want to use <code>tf.per_imdage_standardization</code>, sh...
<p>It is not needed anymore. The reason for normalizing the images is to avoid the possibility of exploding gradients because of the high range of the pixels <code>[0, 255]</code>, and improve the convergence speed. Therefore, you either standardize the each image, so that the range is <code>[-1, 1]</code> or you just ...
tensorflow|machine-learning
12
366,427
57,444,342
Folium popup doesn't show when viewing html in Internet Explorer
<p>HTML doesn't show in internet explorer when Folium Popups are included.</p> <p>I've spent hours trying to get my HTML of a map showing in my browser with folium popups included (without them it works fine). After hours of trying to figure it out I decided to try opening the HTML on my phone instead (with google chr...
<p>Have you used F12 dev tools in IE to check if there's any error in console?</p> <p>Besides, I think Folium itself may have compatibility issues with IE. Even the <a href="https://python-visualization.github.io/folium/quickstart.html" rel="nofollow noreferrer">official examples</a> can't shown in IE. You could open ...
python|internet-explorer|popup|geopandas|folium
0
366,428
57,566,367
Convert dictionary to python dataframe which has key value pair
<p>I have my dictionary as</p> <pre><code>{'id': '6576_926_1', 'name': 'xyz', 'm': 926, 0: {'id': '2896_926_2', 'name': 'lmn', 'm': 926}, 1: {'id': '23_926_3', 'name': 'abc', 'm': 928}} </code></pre> <p>And I want to convert it into dataframe like</p> <pre><code>Id Name M 6576_926_1 Xyz 926 2896_926_2 ...
<pre><code>import pandas as pd data={'id': '6576_926_1','name': 'xyz','m': 926,0: {'id': '2896_926_2', 'name': 'lmn', 'm': 926},1: {'id': '23_926_3', 'name': 'abc','m': 928}} Id=[] Name=[] M=[] for k,val in data.items(): if type(val) is dict: Id.append(val['id']) Name.append(val['name']) ...
python|pandas|dataframe|dictionary
0
366,429
57,678,455
Pandas concat outer join doesn't work properly
<p>I'm trying to join 2 dataframes. I will explain using my codes below. My apology because I don't know how to show table outputs, so please run the code and you will see what I mean. </p> <p>Setup:</p> <pre><code>df1 = pd.DataFrame({'A': ['A2', 'A3', 'A6', 'A7'], 'B': ['B2', 'B3', 'B6', 'B7'], ...
<p><code>pd.concat</code> is not working because it aligns on indexes (row or column) rather than on arbitrary columns. You're probably looking form <code>merge</code>,</p> <pre><code>df1.merge(df2,left_on=['A','B','C'],right_on=['A_','B_','C_'],how='outer') </code></pre>
python|pandas
2
366,430
57,512,442
Row-wise string concatenation in Pandas
<p>I'm trying to prepare some Pandas Dataframes for output to (non tabular) ascii files. As part of this process, I'm looking to concatenate each row of some dataframes containing numeric data into a Pandas Series of tab separated strings.</p> <p>At the moment, my code for doing this is something like this:</p> <pre>...
<p>The part it seems to take more time is converting the floats to string. Afterwards, the way I would do it is as follows:</p> <pre><code>demo_input = demo_input.astype(str) sep = " " concatenation = "" for column in demo_input.columns: # This works fast concatenation += demo_input[column] + sep </code></pre>
python|pandas
0
366,431
57,321,481
Pandas sort_values gives unexpected results
<p>I am having trouble seeing why the sort order differs between the two sort_by commands. The example is taken directly from my data. According to the docs, sort_values should sort by the specified axis (default axis=0) and the specified (by=) index/column(s). </p> <p>The way I see it, both sort_values commands shoul...
<p>This is a general effect of how strings work: every character <a href="https://de.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange" rel="nofollow noreferrer">corresponds to a numeric value</a>.</p> <pre><code>&gt;&gt;&gt; {ch: ord(ch) for ch in '1!@'} {'1': 49, '!': 33, '@': 64} </code></pre> ...
pandas|sorting
3
366,432
57,625,422
conditional cumsum in pandas
<p>I have following dataframe in pandas</p> <pre><code> code rank quant sales 123 1 0 2 123 1 12 2 123 1 0 2 123 2 0 1 123 2 10 1 </code></pre> <p>I want to do a conditional cumsum of s...
<p>Add columns first and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumsum.html" rel="nofollow noreferrer"><code>GroupBy.cumsum</code></a> with <code>df['rank']</code> Series:</p> <pre><code>df['cumsum'] = df['quant'].add(df['sales']).groupby(df['rank']).cum...
python|pandas
2
366,433
57,519,681
The order of the item for get_dummies
<p>I have a Python dataframe that includes a comma separated value.</p> <pre><code> ID Items Random 1 K93,J11,W34,Z38 38 2 J11,M88 487 3 T44,P03,M88 314 4 K93,P03,D32 79 5 M88,Z38,E49 33 6 443 </code></pre> <p>When I try to one-hot-encode it I fa...
<p>You can first split the string and stack the list then apply get_dummies.</p> <pre><code>( df.Items.str.split(',').apply(pd.Series).stack() .pipe(pd.get_dummies, prefix='Items') .sum(level=0) ) </code></pre>
python|pandas|one-hot-encoding
2
366,434
57,475,348
Tensorflow, Keras pretrained MobileNetV2 Model doesn't download
<p>I following this tutorial on on transferred learning in tensorflow keras. An error occurs when it tries to download the mobilenetV2 model.</p> <p>This is the code that fails:</p> <pre class="lang-py prettyprint-override"><code>base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, ...
<p>I had a similar error once and fixed it by upgrading the <code>requests</code> package:</p> <pre class="lang-sh prettyprint-override"><code>pip install --upgrade requests </code></pre> <p>or in your case:</p> <pre class="lang-sh prettyprint-override"><code>conda update requests </code></pre> <p><strong>Edit:</st...
python|python-3.x|tensorflow|runtime-error|tf.keras
2
366,435
57,612,608
Sublist extraction in Python
<p>I'm trying to write a piece of code to solve the following assignment. I have a two-column dataset with the following structure: a "country" column, which contains names of countries that repeat many times (e.g. "USA", "China","Italy", "USA",...), and a "date" column, that assign to each country a specific calendar ...
<p>You can do that basically with <code>cumsum</code> to get the position in the list. It works like this:</p> <pre><code># define your list of groups # as stated in your post from each group take # the firstoccurance (so in this case # the 1st, the 4th, the 9th and the 12th) selection= [3, 5, 3, 2] # calculate the a...
python|pandas
1
366,436
57,391,305
Shifting timeseries data using per group using shift() and groupby() results in NaN
<p>Given the following dataset</p> <pre><code>df = pd.DataFrame( { 'YearMo': ['01', '02', '01', '02', '01', '02'], 'Prod': ['a', 'a', 'b', 'b', 'c', 'c'], 'Value': [1, 2, 3, 4, 5, 6] } ) </code></pre> <p>I'm trying to lag data per year/prod group. It is my understanding this can be don...
<p>I guess you are missing the fact that groups defined by <code>.groupby(['YearMo', 'Prod'])</code> are groups consisting of only one item. Shift of one item returns <code>NaN</code>s.</p> <p>Your desired output can be reached by the following code:</p> <pre><code>df['shifteddata'] = df.groupby(['Prod'])['Value'].sh...
python|pandas|dataframe|time-series|pandas-groupby
4
366,437
57,713,315
Normalize using a given NumPy array (From Python To C#)
<p>I'm trying to convert some Python code into C#, but the difference in code implementation is preventing me from roaching my goal.</p> <p>I tried creating different arrays and different functions to normalize a C# float array using another array.</p> <p>Code in Python: </p> <pre><code>mean_vec = np.array([102.9801...
<pre><code> for (int k = 0; k &lt; 3; k++) { for (int j = 0; j &lt; newBitmap.Height; j++) { for (int i = 0; i &lt; newBitmap.Width; i++) { floatArray[k, j, i] = (float)Conv...
c#|python|arrays|numpy|normalize
0
366,438
57,583,901
How to access index of outer for loop of nested iterrow in pandas?
<p>I am iterating through a datafile in the outermost loop and a series in the inner loop. I am using iterrows() and items() to iterate through both data structures respectively. From the pandas documentation, it seems that the 'index' name cannot be a variable name I declare. </p> <p>So, when I am inside the items() ...
<p>If I understand right, you just need to use different variable names for the two loop variables:</p> <pre><code>for df_index, row in ldf.iterrows(): for comp_index, value in comp.items(): if row['Type'] == comp_index: if row['Score'] &lt; value: ldf.drop(df_index, inplace=Tru...
python|pandas|indexing
1
366,439
57,527,511
How to speedup the counting of matching strings in a large dataframe?
<p>I have a list of keywords and I would like to count the number of times each keyword has appeared in an article. The problem is that I have more than half a million articles (in a dataframe format) and I already have a code that produce the desired results. However, it takes around 40-50 seconds to count the instanc...
<p>Options:</p> <ol> <li><p>Convert a collection of text documents to a matrix of token counts: <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html" rel="nofollow noreferrer">sklearn count vectorizer</a></p></li> <li><p>Construct a Bag of Words with Gensim or...
python|string|pandas|performance
0
366,440
57,661,317
numpy.argpartition documentation not clear enough
<p>I've tried to understand the <code>numpy.argpartition</code> by reading its documentation, but I still get confused.<br> In <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html" rel="nofollow noreferrer">the documentation</a>, it is said that </p> <blockquote> <p>it returns an arr...
<pre><code>In [163]: np.argpartition(a, 3) Out[163]: array([2, 0, 3, 5, 1, 4, 6, 7]) In [164]: a[_] Out[164]: array([215, 352, 400, 498, 538, 631, ...
python|numpy
2
366,441
57,421,808
Boolean Matrix with more than 1 comparison raises error "The truth value of an array with more than one element is ambiguous"
<p>I am trying to find if a pixel's HSV value is within the right threshold, but it's raising an error:</p> <pre><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>What I'm trying to do is:</p> <pre><code>x, y = numpy.where(0.081969696969696...
<pre><code>x, y = numpy.where(0.08196969696969696 &gt;= img &gt;= 0.1 and 0.7285714285714286 &gt;= img &gt;= 0.525 and 150 &gt;= img &gt;= 95) </code></pre> <p>Focus to the argument, which should produce a n-d boolean array:</p> <pre><code>0.08196969696969696 &gt;= img &gt;= 0.1 and 0.7285714285714286 &gt;= img &gt;=...
python|numpy|opencv|pixel|boolean-logic
0
366,442
57,552,697
Merging columns into float type
<p>Given Data Frame df = </p> <pre><code>ordinal id A B 1 14318 45.0714 7.6187 2 14318 45.0739 7.6195 3 14318 45.0745 7.6152 4 14318 45.0833 7.6145 5 14318 45.0946 7.6194 </code></pre> <p>I want ...
<p>IIUC need:</p> <pre><code>df['C'] = list(zip(df.A.astype(int), df.B.astype(int))) print (df) ordinal id A B C 0 1 14318 45.0714 7.6187 (45, 7) 1 2 14318 45.0739 7.6195 (45, 7) 2 3 14318 45.0745 7.6152 (45, 7) 3 4 14318 45.0833 7.6145 (45, 7) 4 ...
python|pandas
1
366,443
57,339,092
How to convert two lists to a dataframe without ['xxx'] tags in python?
<p>I created the following two lists in Python and want to convert these into a dataframe. </p> <p>When I run the following code:</p> <pre><code>print(scores) print('-'*100) print(player) print('-'*100) dataframe = {'Score': scores, 'Player': player} df = pd.DataFrame(data=dataframe) print(df) </code></pre> <p>I g...
<p>A quick fix </p> <pre><code>df=df.apply(lambda x : x.str[0]) </code></pre> <p>Fix from beginning</p> <pre><code>dataframe = {'Score': sum(scores,[]), 'Player': sum(player,[])} df = pd.DataFrame(data=dataframe) </code></pre> <p>Speed it up </p> <pre><code>import itertools list(itertools.chain.from_iterable(a)))...
python|pandas|dataframe
3
366,444
57,687,857
How to convert the header row to a normal row in pandas
<p>I am having a excel sheet where I skipped multiple rows and finally arrived at a dataframe with some little structure. But I have a dataframe which looks like this. Bold are headers. </p> <p><a href="https://i.stack.imgur.com/UrTJK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UrTJK.png" alt="e...
<p>You can skip header with header = None if you use <code>.read_csv</code></p> <p><code>df = pd.read_csv(file_path, header=None, usecols=[3,6])</code></p>
python|pandas
2
366,445
57,598,331
Pandas filtering based on pandas field containing joined string being in list of strings
<p>I am trying to do data frame filtering using this approach</p> <pre><code>reduced_df = full_df[(full_df['field1'] == some_defined_value1) &amp; \ (full_df['field2'] == some_defined_value2) &amp; \ (full_df['field3'].apply(lambda x: x for x in ','.join(list_of_comma_separate...
<p><code>split</code> and <code>explode</code> (pandas 0.25 required) the string, then check if <code>any</code> word <code>isin</code> the list <code>l</code> (no need for the long name).</p> <pre><code>df['field3'].str.split(',').explode().isin(l).any(level=0) </code></pre> <h3>Sample:</h3> <pre><code>import panda...
python|pandas
1
366,446
57,421,542
How to join unique strings from a column in dataframe based on another column
<p>I need to join unique strings within one column based on values from another column.</p> <p>I tried groupby, but either I'm missing something obvious or it's an overkill.</p> <p>Below is input dataframe. I want to join unique strings from <code>col2</code> for each value in <code>col1</code></p> <pre><code>df = p...
<p>I think you are quite close, add a <code>strip</code> here:</p> <pre><code>df2['col_out2'] = df2.groupby('col1')['col2'].transform(lambda x: ';'.join(x.unique())).str.strip(';') </code></pre> <p>It has output:</p> <pre><code> col1 col2 col0 col_out col_out2 0 a 1 s2;s3 s2;s3 1 a s2 2 s2;s3 ...
python|pandas
1
366,447
57,714,520
When loading CSV data with pandas, the first line is mistaken for the title
<p>How to prevent the following? When I load a file with <code>pd.read_csv()</code>, the first line gets unwantedly treated as a header (list of column names):</p> <pre><code>import pandas as pd data = pd.read_csv('namefile',sep=' ') print(data) </code></pre> <p>and only the second line onwards gets treated as the da...
<p>you can use the option of header to exclude columns <code>data=pd.read_csv('namefile',sep=' ', header =None)</code></p>
python|pandas|csv|header|header-row
4
366,448
57,450,132
Combine columns from different dataframes on timestamp
<p>I have several dataframes with a ID, Timestamp and a value. I'm creating the final dataframe by merging the dataframes and I would like to list all the values (if any) from each dataframe based on the timestamp. Now my (wrong) final dataframe is this:</p> <pre><code> Date ID ValDf1 ...
<p>This?</p> <pre><code>df.groupby(['Date', 'ID']).sum() ValDf1 ValDf2 ValDf3 Date ID 04:00:00 13971 5.333333 0.0 0...
python|pandas
0
366,449
57,353,986
Can we do dataframe level exception handling for pandas?
<p>I am new to pandas, I want to know that does pandas dataframe have their own way of exception handling other than using try/ except python. </p> <p>I have tried exec function of python to write entire try/except in one line but I want pandas specific syntax or way of exception handling that can be done in a single ...
<p>It looks like you are trying to apply a custom function in a <strong>very bad</strong> way, using a lambda, with a function defined using <code>eval</code> within an optional parameter.</p> <p>You should try and go for something like this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd da...
python|pandas
1
366,450
57,526,904
Python - Create a column based on multiple other columns in a dataframe
<p>I want to create a new column that outputs ascending or descending depending on values in other columns</p> <pre><code> Index Leg Map Number 0 AD J1 1 1 AD J1 2 2 AD J1 3 3 AD J2 5 4 AD J2 3 4 AF J1 9 5 AF J1 6 </code></pre> <p>So looking at t...
<p>IIUC, you need:</p> <pre><code>s=df.groupby(['Leg','Map'])['Number'].transform(lambda x: (x.diff()&gt;0).any()) </code></pre> <p>Or:</p> <pre><code>s=df.groupby(['Leg','Map'])['Number'].transform(lambda x: x.is_monotonic) #thanks Mark Wang df['Updown']=np.where(s,'ascending','descending') print(df) </code></pre> ...
python|pandas|dataframe
1
366,451
57,597,808
Creating a new column after every iteration of For loop in Python
<p>I want to create a column and assign it to a dataframe after every iteration of the for loop in python.</p> <pre><code>df_xyz = pd.DataFrame() for j in range(0,3): for k in range(j+1,4): print(j,k) </code></pre> <p>So, in this case it should create 6 new columns in the dataframe with the name as "ABC1"...
<p>It really looks awful, but I think you are trying to do this:</p> <pre class="lang-py prettyprint-override"><code>In [1]: import pandas as pd import numpy as np z= np.array([1,2,4]) df_xyz = pd.DataFrame() iterator = 1 for j in range(0,3): for k in range(j+1,4): print(j,k) col_name = 'ABC' + s...
python|pandas
2
366,452
57,482,811
How do I prevent a value from converting to a date or executing as division?
<p>I have a column in a dataframe that has values in the format XX/XX (Ex: 05/23, 4/22, etc.) When I convert it to a csv, it converts to a date. How do I prevent this from happening?</p> <p>I tried putting an equals sign in front but then it executes like division (Ex: =4/20 comes out to 0.5).</p> <pre><code>df['uniq...
<p>Check the datatypes of your dataframe with <code>df.dtypes</code>. I assume your column is interpreted as date. Then you can do <code>df[col] = df[col].astype(np_type_you_want)</code></p> <p>If that doenst bring the wished result, check why the column is interpreted as date when creating the df. Solution depends on...
python|pandas|dataframe
0
366,453
57,701,684
How to store this type of numpy array into HDF5, in each row there is an int and a numpy array of several ints, which varies in size for each row
<p>My data looks like this</p> <pre><code>array([[0, array([ 4928722, 3922609, 14413953, 10103423, 8948498])], [1, array([12557217, 5572869, 13415223, 2532000, 14609022, 9830632, 9800679, 7504595, 10752682])], [2, array([10458710, 7176517, 10268240, 4173086, 8617671, 467...
<p>As @kcw78 pointed out, store the columns separately. </p> <p>To store </p> <pre><code>h5f = h5py.File('data.h5', 'w') dt = h5py.special_dtype(vlen=np.dtype('int32')) h5f.create_dataset('batch', data=sampleDF[:,1], dtype=dt, compression='gzip', compression_opts=9) h5f.create_dataset('labels', data=sampleDF[:,0].ast...
python|numpy|hdf5|h5py|pytables
0
366,454
57,500,865
Combine repeated columns in the same Dataframe
<p>I have data from various csv files I am trying to put together. I put it all in one Dataframe. How can I combine the data into the corresponding A, B, C columns and include a header for each row?</p> <pre><code>for data_base in data: base_data.append(data_base['A']) base_data.append(data_base[' B']) bas...
<p>Here's a solution based on Nycbros comment.</p> <pre><code>import pandas as pd # Dummy data data_double = pd.DataFrame(data=[{'x': x, 'y': 2 * x} for x in range(5)]) data_triple = pd.DataFrame(data=[{'x': x, 'y': 3 * x} for x in range(5)]) print(data_double) </code></pre> <p>Output:</p> <pre><code> x y 0 0 ...
python|pandas|csv|dataframe|reshape
0
366,455
57,531,672
Python misinterprets 3 character string as UTF-8 continuation byte
<p>When saving a Pandas dataset to Excel I ran into </p> <pre><code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe6 in position 0: invalid continuation byte </code></pre> <p>Some digging showed that I can put together 3 ascii characters and the resulting string appears to start with an UTF-8 continuation byt...
<p>In the example in question <code>str(0xe6)</code> takes an integer <code>0xe6</code> (<code>230</code> in decimal notation) and calls <code>repr(object)</code> on it. This produces string <code>'230'</code>. <code>string_from_3_ascii_chars</code> does start with <code>'230'</code>. <code>startswith</code>confirms th...
python|pandas|unicode|utf-8
0
366,456
24,032,282
Create Contour Plot from Pandas Groupby Dataframe
<p>I have following Pandas Dataframe:</p> <pre><code>In [66]: hdf.size() Out[66]: a b 0 0.0 21004 0.1 119903 0.2 186579 0.3 417349 0.4 202723 0.5 100906 0.6 56386 ...
<p>Thanks a lot! My fault was, that I did not realize, that I have to apply some function to the groupby dataframe, like <code>.size()</code>, to work with it...</p> <pre><code>hdf = aggdf.groupby(['a','b']).size() hdf </code></pre> <p>gives me</p> <pre><code>a b 1 -2.0 1 -1....
python|matplotlib|pandas|group-by|contour
22
366,457
24,152,509
slicing a pandas multiindex using datetime datatype
<p>I am new to pandas (ver 0.14.0) and have encountered the following problem: </p> <p>I am trying to slice a pandas data frame utilizing a multiindex. The index contains a timestamp. If slicing using only a date for the timestamp it works fine. When slicing using a time in the timestamp it returns nothing or an excep...
<p>You can slice on the Timestamps rather than the strings:</p> <pre><code>In [11]: df.loc[(slice(pd.Timestamp('2012-01-01 12:12:12'),pd.Timestamp('2012-01-03 12:12:12')))] Out[11]: A B C D date frequency 2012-01-01 12:12:12 1 0.7965...
python|pandas
5
366,458
24,112,803
how to expand sum column using pandas dataframe
<p>So, I have table like this: df:</p> <pre><code> A B C D 0 1 1 0 7 1 1 1 0 9 2 1 1 1 5 3 1 1 1 3 </code></pre> <p>After doing <code>df.groupby(['A','B','C']).sum()</code> i get:</p> <pre><code> A B C D 0 1 1 0 16 1 1 1 1 8 </code></pre> <p>By what method I can get</p> <pre><code> A B C D 0 1 1 0 16 1 1 1 0 16...
<p>IIUC, you want <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow"><code>transform</code></a>: it does the aggregation but returns an object indexed the same way as the original.</p> <pre><code>&gt;&gt;&gt; df A B C D 0 1 1 0 7 1 1 1 0 9 2 1 1 1 5 3 1 ...
python|pandas|dataframe
1
366,459
24,227,805
Slicing Pandas DataFrame based on csv
<p>Let's say I have a Pandas DataFrame like following.</p> <pre><code>df = pd.DataFrame({'Name' : ['A','B','C'], 'Country' : ['US','UK','SL']}) Country Name 0 US A 1 UK B 2 SL C </code></pre> <p>And I'm having a csv like following.</p> <pre><code>Name,Extended A,Jorge B,Al...
<p>You can use the "fillna" function from pandas like this:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'Name' : ['A','B','C'], 'Country' : ['US','UK','SL']}) df2 = pd.DataFrame.from_csv('mycsv.csv', index_col=None) df_merge = pd.merge(df, f, how="left", on="Name") df_merge["Extended"].fillna...
python|csv|pandas|dataframe
1
366,460
24,264,470
Deducting the median from each column
<p>I have a dataframe, <code>df</code> with numbers, like so:</p> <pre><code>1 1 1 2 1 1 2 1 3 </code></pre> <p>I'd like to deduct the median from each column so that the median of each becomes 0.</p> <pre><code>-1 0 0 0 0 0 0 0 2 </code></pre> <p>How do I do this in a pythandic way? I'm guessing it is possible wit...
<p>Just like this</p> <pre><code>df -= df.median(axis=0) </code></pre> <p><code>median</code> of <code>numpy</code> computes <strong>median</strong> of overall data. To accomplish using <code>numpy</code>, try this code instead.</p> <pre><code>df -= median(df, axis=0) </code></pre> <p>for more detail, see the docum...
python|numpy|pandas
4
366,461
24,065,547
Apply styles while exporting to 'xlsx' in pandas with XlsxWriter
<p>I use the .to_excel method of pandas to write a DataFrame as an Excel workbook. This works nice even for multi-index DataFrames as index cells become merged. When using the pure XlsxWriter I can apply formats to cells what also works nice.</p> <p>However I couldn't find a way to do the same with the pandas method. ...
<blockquote> <p>Is there any way to do so</p> </blockquote> <p>Currently no. There isn't a formatting mechanism like that in Pandas for formatting the Excel output (apart from a few hard-coded formats).</p> <p>However, even if it was XlsxWriter doesn't currently support formatting cells after data is added. It is o...
python|io|pandas|xlsx|xlsxwriter
12
366,462
24,194,069
Query data using pandas with kwargs
<p>I'm trying to Query data using python pandas library. here is an example json of the data...</p> <pre><code>[ { "name": "Bob", "city": "NY", "status": "Active" }, { "name": "Jake", "city": "SF", "status": "Active" }, { "name": "Jill", "city": "NY", "status": "Lazy" }, { "name": "Steve", "city": "NY", "s...
<p>**Kwargs is nothing really to do with Pandas, it is a basic Python thing, you simply need to make a function that accepts Kwargs and substitute the variable Kwargs into the pandas Df query statement (inside the function). Don't have the time to code it for you but reading the Python docs should get you going. Pandas...
python|json|pandas|data-analysis|keyword-argument
0
366,463
24,039,023
Add column with constant value to pandas dataframe
<p>Given a DataFrame:</p> <pre><code>np.random.seed(0) df = pd.DataFrame(np.random.randn(3, 3), columns=list('ABC'), index=[1, 2, 3]) df A B C 1 1.764052 0.400157 0.978738 2 2.240893 1.867558 -0.977278 3 0.950088 -0.151357 -0.103219 </code></pre> <p>What is the simplest way to add a n...
<h1>Super simple in-place assignment: <code>df['new'] = 0</code></h1> <p>For in-place modification, perform direct assignment. This assignment is broadcasted by pandas for each row.</p> <pre><code>df = pd.DataFrame('x', index=range(4), columns=list('ABC')) df A B C 0 x x x 1 x x x 2 x x x 3 x x x </...
python|pandas
169
366,464
24,293,745
Pandas read_csv import results in error
<p>My csv is as follows (MQM Q.csv):</p> <pre><code>Date-Time,Value,Grade,Approval,Interpolation Code 31/08/2012 12:15:00,,41,1,1 31/08/2012 12:30:00,,41,1,1 31/08/2012 12:45:00,,41,1,1 31/08/2012 13:00:00,,41,1,1 31/08/2012 13:15:00,,41,1,1 31/08/2012 13:30:00,,41,1,1 31/08/2012 13:45:00,,41,1,1 31/08/2012 14...
<p>This appears to be a bug with the csv parser, firstly this works:</p> <pre><code>df = pd.read_csv('MQM Q.csv') </code></pre> <p>also this works:</p> <pre><code>df = pd.read_csv('MQM Q.csv', usecols=['Value']) </code></pre> <p>but if I want <code>Date-Time</code> then it fails with the same error message as yours...
python|csv|pandas
5
366,465
43,572,359
Keep column and row order when storing pandas dataframe in json
<p>When storing data in a json object with to_json, and reading it back with read_json, rows and columns are returned sorted alphabetically. Is there a way to keep the results ordered or reorder them upon retrieval? </p>
<p>You could use <code>orient='split'</code>, which stores the index and column information in lists, which preserve order:</p> <pre><code>In [34]: df Out[34]: A C B 5 0 1 2 4 3 4 5 3 6 7 8 In [35]: df.to_json(orient='split') Out[35]: '{"columns":["A","C","B"],"index":[5,4,3],"data":[[0,1,2],[3,4,5],[6...
python|pandas|dataframe
17
366,466
43,828,226
Pandas - merging dataframes conditionally on multiple columns
<p>I have 2 dataframes and I want to take one of the columns from one and create a new column in the second based on values in multiple (other) columns</p> <p>First dataframe (<code>df1</code>):</p> <pre><code>df1 = pd.DataFrame({'cond': np.repeat([1,2], 5), 'point': np.tile(np.arange(1,6), 2), ...
<p><strong><em>Option 1</em></strong><br> <em>For grace and speed with pure <code>pandas</code>, we can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow noreferrer"><strong><code>lookup</code></strong></a></em><br> This will produce the same output as all ot...
python|pandas|dataframe|merge
5
366,467
43,887,706
Behavior of Dropout layers in test / training phase
<p>According to the Keras documentation dropout layers show different behaviors in training and test phase:</p> <blockquote> <p>Note that if your model has a different behavior in training and testing phase (e.g. if it uses Dropout, BatchNormalization, etc.), you will need to pass the learning phase flag to your...
<p>Dropout is used in the training phase to reduce the chance of overfitting. As you mention this layer deactivates certain neurons. The model will become more insensitive to weights of other nodes. Basically with the dropout layer the trained model will be the average of many thinned models. Check a more detailed expl...
tensorflow|keras|neural-network|theano|keras-layer
9
366,468
43,588,442
Merge and aggregate list entries with pandas, without removing fields
<p>I have lists of this format:</p> <pre><code>['bear', 'brown', 'mammal', 1233], ['cat', 'black', 'mammal', 1533], ['bear', 'brown', 'mammal', 2345], ['bear', 'black', 'mammal', 2345] </code></pre> <p>I would like to aggregate the numbers at the end if the first three strings are identical and remove the duplicate e...
<pre><code>In [137]: pd.DataFrame(d).groupby([0,1,2]).sum().reset_index().values.tolist() Out[137]: [['bear', 'black', 'mammal', 2345], ['bear', 'brown', 'mammal', 3578], ['cat', 'black', 'mammal', 1533]] </code></pre> <p>where <code>d</code> is a list:</p> <pre><code>In [138]: d Out[138]: [['bear', 'brown', 'mamma...
python|pandas
3
366,469
43,791,017
Pandas how to use boolean indexing to update column from second dataframe column?
<p>I have two dataframes, each of which has two columns: unique_id, price. df1 has a subset of all unique_id's in df2. </p> <p>Now I need to add a third column to df1 that has the price for that unique_id element in df2. i.e. the columns will be: unique_id, price, price2. </p> <p>How do I do this? </p>
<p>Consider the dataframes <code>df1</code> and <code>df2</code></p> <pre><code>df1 = pd.DataFrame({ 'unique_id': [1, 2, 3], 'price': [11, 12, 13], }) df2 = pd.DataFrame({ 'unique_id': [1, 2, 3, 4, 5], 'price': [9, 10, 11, 12, 13], }) </code></pre> <p><strong><em><code>merge</code></em></...
pandas|dataframe|merge|boolean
3
366,470
43,684,072
How to import multiple bands from an image into numpy?
<p>I'm new to python/numpy. I need to import <em>n</em> bands of data (~125) from a multiband image into an <em>n</em>-dimensional array. Each value is a 16-bit signed integer. Currently I have python code that looks like this:</p> <pre><code>stream = bytearray() mbImage = open(filename, mode='rb'); while curr &lt;...
<p>GDAL already returns a Numpy array, so wrapping <code>np.array</code> is unnecessary.</p> <p>If you want to read all bands in the dataset, you can skip selecting the bands one at a time and use:</p> <p><code>data = ds.ReadAsArray()</code></p> <p>The first dimension of the array are the bands (check with <code>pri...
python|arrays|numpy|image-processing|gdal
3
366,471
43,846,001
feature concatenation tf.concat(x, tf.square(x), axis=1) fails for a placeholder x
<p>If I try</p> <pre><code>import tensorflow as tf x_data = [1,2,3] x = tf.placeholder(tf.float32) z = tf.concat([x, tf.square(x)], axis=1) with tf.Session() as sess: sess.run(z, feed_dict={x: x_data}) </code></pre> <p>it fails. I basically want to make a vector [[x],[x^2]]. Could you help?</p>
<p><code>tf.concat</code> can only be used to concatenate tensors along dimensions that <em>already</em> exist. If you want to concatenate tensors along a new dimension you can use <code>tf.stack</code>:</p> <pre><code>import tensorflow as tf x_data = [1,2,3] x = tf.placeholder(tf.float32) z = tf.stack([x, tf.square...
tensorflow
0
366,472
43,738,823
Memory Error when trying to create numpy matrix
<pre><code>text = codecs.open("lith.txt", encoding= 'utf-8') text = text.read().lower().replace('"','').replace('?','').replace(',','').replace('!','').replace('.','') text = text.split() words = sorted(list(set(text))) Unigram = np.zeros([len(words)]) ind = range(len(words)) Lexicon = dict(zip(words,ind)) Bigram = np....
<p>I assume that the line that raises the exception in:</p> <pre><code>Bigram = np.zeros([len(words),len(words)]) </code></pre> <p>If <code>len(words)</code> is 200,000, then the size of the matrix is 200,000^2 integers. Assuming <code>int64</code>, this requires 320gb of memory.</p> <p>Assuming most entries will re...
python|numpy
3
366,473
43,791,870
Creating a Pandas DataFrame from Uneven List of Dictionaries
<p>I am trying to get a dictionary into a formatted DataFrame.</p> <p>I am getting the data through an API call from: <a href="https://www.cryptonator.com/api" rel="nofollow noreferrer">https://www.cryptonator.com/api</a></p> <pre><code>r = requests.get('https://api.cryptonator.com/api/ticker/btc-usd') x = r.json() <...
<p>You can pull out the pieces you need</p> <pre><code>pd.DataFrame({ 'ticker': x['ticker'], 'timestamp': x['timestamp'] }).T base change price target volume ticker BTC 0.3766203596 443.7807865468 USD 31720.1493969300 timestam...
python-3.x|pandas|dictionary|dataframe|key-value
2
366,474
43,611,519
Fit spline through scatter
<p>I a have two sets of data of which I want to find a correlation. Although there is quite some scattering of data there's obvious a relation. I currently use numpy polyfit (8th order) but there is some "wiggling" of the line (especially at the beginning and the end) which is not appropriate. Secondly I don't think th...
<p>Take a look at @MatthewDrury's answer for <a href="https://stats.stackexchange.com/questions/226553/why-use-regularisation-in-polynomial-regression-instead-of-lowering-the-degree/226566#226566">Why use regularisation in polynomial regression instead of lowering the degree?</a>. It's simply fantastic and spot on. The...
python|numpy|scipy|non-linear-regression
3
366,475
43,723,028
Pandas: Using group by, combine multiple column values as one distinct group within the groupby
<p>I have a data-frame which I'm using the <code>pandas.groupby</code> on a specific column and then running aggregate statistics on the produced groups (mean, median, count). I want to treat certain column values as members of the same group produced by the groupby rather than a distinct group per distinct value in th...
<p>For me works:</p> <pre><code>#for join values convert values to string df['SUB_NUM'] = df['SUB_NUM'].astype(str) #create mapping dict by dict comprehension L = ['1','2'] d = {x: ','.join(L) for x in L} print (d) {'2': '1,2', '1': '1,2'} #replace values by dict a = df['SUB_NUM'].replace(d) print (a) 0 1,2 1 1...
python|pandas|dataframe|group-by
3
366,476
43,772,214
how to append to empty dataframe in for loop
<p>I'm using pandas as pd and python 2.7</p> <p>I have a bunch of queries and each query is returning serial numbers. Then I'm using that serial number in a bunch more queries. I want to append all the results to a list. When I append to an empty list, it just returns nothing. I don't know what I'm doing wrong.</p> <...
<p>You are resetting the list to be empty at the beginning of each <code>for</code> loop. This should be:</p> <pre><code>a = [] for serial_number in results['SerialNumbers']: new_query = """ SELECT * FROM blah b where b.SerialNumber = '{}' """ new_query = new_query.format(serial_number) results = p...
python|python-2.7|pandas
1
366,477
43,612,705
R, keras: TypeError: Value passed to parameter 'shape' has DataType float32 not in list of allowed values: int32, int64
<p>I'm trying to make some neural networks in R, using kerasR package on tensorflow within a tensorflow anaconda environment.</p> <p>Here you can see my setup:</p> <pre><code>library(reticulate) use_condaenv("tensorflow", required = TRUE) py_config() </code></pre> <p>The result is:</p> <pre><code>python: C...
<p>The error says in somewhere of your tensorflow code, you try to assign float value to a parameter, but that parameter can't be float, it should be int,</p>
r|tensorflow|anaconda|keras
1
366,478
43,478,867
Handling Variable Number of Columns Dataframe - Python
<p>I am trying to write a list of lists into an excel sheet using pandas the list looks like: </p> <pre><code>List_of Lists = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], ........, ] </code></pre> <blockquote> <p>The number of these lists inside the mai...
<p>I believe you can just pass the list into <code>pd.DataFrame()</code> and you will just get NaNs for the values that don't exist.</p> <p>For example:</p> <pre><code>List_of_Lists = [[1,2,3,4], [5,6,7], [9,10], [11]] df = pd.DataFrame(List_of_Lists) print(df) 0...
python|pandas|dataframe|xlw
10
366,479
43,889,944
rename certain value in pandas series
<p>I have the following panda Series:</p> <pre><code>print(df.head()) Country Energy Supply Energy Supply per Capita % Renewable 0 Afghanistan 3.210000e+08 10 78.669280 1 Albania 1.020000e+08 35 100.000000 2 Algeria 1.959000e+09 ...
<p>You can use if need replace <code>index</code>:</p> <pre><code>df = df.set_index('Country') df = df.rename(index={'Afghanistan':'Afghanistan_renamed'}) print (df) Energy Supply Energy Supply per Capita % Renewable Country Afghani...
python|pandas|series
9
366,480
43,633,422
tostring vs. tofile for creating raw binary files
<p>I need to save a numpy array to a raw binary file, and based on advice from colleagues, I understand that <code>tostring</code> and <code>tofile</code> should be doing roughly the same thing. However, when I run</p> <pre><code>x=np.load('foo.npy') (open('foo_1.dat', 'w')).write(x.T.tostring()) x.T.tofile('foo_2.dat...
<blockquote> <blockquote> <p>I don't know if this is the issue, but the file should be opened in binary >>mode: open('foo_1.dat', 'wb')</p> </blockquote> </blockquote> <p>That was it! Thank you!</p>
python|numpy
0
366,481
43,766,123
Match strings between two dataframes and create column
<p>I am trying to match parts of string from <code>bad_boy</code> to <code>good_boy</code> and create a column in the original df (<code>bad_boy</code>) called the <code>Right Address</code> but having hard time getting this accomplished. I have looked at the links below:</p> <p><a href="https://stackoverflow.com/ques...
<p>You can use merge combined with str.extract for partial match</p> <pre><code>df1 = df1.merge(df2, left_on = df1.Address.str.extract('(\d+)', expand = False), right_on = df2.Address.str.extract('(\d+)', expand = False), how = 'inner').rename(columns = {'Address_y': 'Right_Address'}) </code></pre> <p>You get</p> <p...
python|pandas
4
366,482
43,885,486
Python pandas dataframe to vertica table using vertica-python
<p>I am using python to communicate with vertica. Is there an elegant way to create a new vertica table with a pandas dataframe. I am using vertica-python 0.6.14. The only way I know is to use a for loop to write each row of the dataframe into vertica. Also it is very painful to create the table in vertica since you ne...
<p>You can use copy statement to insert data from Pandas data frame to Vertica:</p> <pre><code>import vertica_python conn_info = {'host': host, 'port': port, 'user': user, 'password': password, 'database': database, # 10 minutes timeout on queries ...
python|pandas|vertica
3
366,483
43,919,084
Tricky sort of a multi-index dataframe
<p>After spending some time jumping through the pandas docs and searching questions here, I can't figure out how to accomplish the following:</p> <p>Sort the "Ax" blocks by the value determined by index "B0" and column "G".</p> <p>An example output is given below (I manually sorted the blocks for the desired result)....
<p>As @EdChum mentioned, there may be consequences to re-sorting your index, but here would be a way.</p> <pre><code>idx = pd.IndexSlice sort_order = df.loc[idx[:, 'B0'], 'G'].argsort().values sort_order # Out[21]: array([0, 2, 1], dtype=int64) label_order = df.index.levels[0].take(sort_order) label_order # Out[25]: ...
sorting|pandas
0
366,484
43,738,956
Index based style.format
<p>You can specify a format for each column by using <code>df.style.format()</code>, however, i want this behavior but then index based instead of column based. I realise its a bit more tricky because a column has a specific datatype, and a row can be mixed. </p> <p>Is there a workaround to get it anyway? The <code>df...
<p>You may not need to use the <code>Styler</code> class for this if the target is to re-format row values. You can use that <code>mapper</code> dictionary to match the formats you want, through a <code>map</code> and <code>apply</code> combination by row. The following should be a decent start:</p> <pre><code>df.appl...
python|pandas
2
366,485
43,497,472
How to convert dataframe to 1D array ?
<p>First of all apologies. I am very new to pandas, scikit learn and python. So I am sure I am doing something silly. Let me give a little background.</p> <p>I am trying to run KNeighborsClassifier from scikit learn (python) Following is my strategy</p> <pre><code>#Reading the Training set data = pd.read_csv('Path_TO...
<p>Thanks Vivek and Thornhale</p> <p>Indeed I was doing two wrong things.</p> <ol> <li>As pointed by you guys, I should have been using 1, 0 in stead of Y, N. </li> <li>I was giving wrong parameters to the function score. It should be accuracy=neigh.score(t, actual) , where t is test feature set and actual is test la...
python|pandas|dataframe|scikit-learn
0
366,486
43,662,094
im2txt: Load input images from memory (instead of read from disk)
<p>I'm interested in modifying <a href="https://github.com/tensorflow/models/tree/master/im2txt" rel="nofollow noreferrer">the tensorflow implementation of Show and Tell</a>, in particular <a href="https://github.com/tensorflow/models/tree/f653bd2340b15ce2a22669ba136b77b2751e462e/im2txt" rel="nofollow noreferrer">this ...
<p>The original code:</p> <pre><code>with tf.gfile.GFile(filename, "r") as f: image = f.read() </code></pre> <p>has image as a python string.</p> <p>Your code:</p> <pre><code>def encode_image(filename): g2 = tf.Graph() from keras.preprocessing.image import img_to_array with g2.as_default() as g: ...
python|arrays|numpy|tensorflow
0
366,487
43,748,288
Optimising python code that uses numpy sin,cos,sum and abs
<p>I have some python code that currently runs too slowly for it to be useful. Having done some speed tests, the bulk of the time seems to be spent performing mathematical operations to calculate corr (see code below).</p> <pre><code>import numpy as np from multiprocessing import Pool from contextlib import closing d...
<p>Firstly, you can improve your code slightly by computing <code>phi_t(...)-psi_t(...)</code> once for both trigonometric functions <a href="https://stackoverflow.com/questions/43748288/optimising-python-code-that-uses-numpy-sin-cos-sum-and-abs#comment74540674_43748288">as @hpaulj noted</a>. However, the biggest issue...
python|arrays|performance|numpy|vectorization
2
366,488
43,918,518
How do I rename a blank column name in pandas df?
<p>I am using pandas_datareader to return stock prices. The document states that a pandas data frame is returned by the pandas_datareader. The issue is that the data frame is returned with a blank column name. That means until I rename the column I (believe this to be true) cannot add another column. Anyway here is my ...
<p>That AttributeError posted in the comments is important – you have a Series, equivalent to a single column, not a DataFrame.</p> <pre><code>main_df.to_frame() </code></pre> <p>will return a dataframe, which you can then rename the columns of and add new columns to.</p>
python-3.x|pandas|pandas-datareader
0
366,489
43,557,489
scipy.optimize.curvefit fails when using bounds
<p>I'm trying to fit a set of data with a function (see the example below) using <code>scipy.optimize.curvefit</code>, but when I use bounds (<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow noreferrer">documentation</a>) the fit fails and I simply get the init...
<p>I encountered the same behavior today in a different fitting problem. After some searching online, I found this link quite helpful: <a href="https://stackoverflow.com/questions/15624070/why-does-scipy-optimize-curve-fit-not-fit-to-the-data">Why does scipy.optimize.curve_fit not fit to the data?</a></p> <p>The short...
python|numpy|scipy
1
366,490
43,727,790
Populating a numpy array with values from a list while keeping relations
<p>I have a list where the columns are ID#, date, value. So just for this example, lets say it looks like this:</p> <pre><code>[('1', 13152, '131'), ('1', 13168, '-9999'), ('1', 13177, '345'), ('2', 13152, '-9999'), ('2', 13168, '212'), ('2', 13177, '693'), ('3', 13152, '456'), ('3', 13168, '-9999'), ('...
<p>The simplest possible solution I could think of:</p> <pre><code>import numpy as np a = [('1', 13152, '131'), ('1', 13168, '-9999'), ('1', 13177, '345'), ('2', 13152, '-9999'), ('2', 13168, '212'), ('2', 13177, '693'), ('3', 13152, '456'), ('3', 13168, '-9999'), ('3', 13177, '103')] b = -9999*np.ones(shape...
python|arrays|list|numpy|indexing
0
366,491
43,821,167
How does one input images and labels for Semantic Instance Segmentation with neural networks?
<p>So I know for a standard convolutional neural network you can provide the neural net (NN) a file with a list of labels or simply separate your classes by folders but for instance segmentation I imagine it's different right? </p> <p>For example using a site like labelme2 you can annotate and segment images and then ...
<p>You'll want to train your NN in such as way that you'll be able to use it for prediction. </p> <ul> <li><p>If you want to just predict the classes from the image, then all you want to send to your NN is </p> <ul> <li>the original image (probably color balanced) and</li> <li>predict the classes from the XML (conve...
python|machine-learning|tensorflow|conv-neural-network|image-segmentation
0
366,492
43,616,373
MemoryError tensorflow
<p>I'm running this model from AWS instance of type P2.xlarge. It is giving an error as:</p> <pre><code>Exception in thread Thread-16: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 754, in run self.__tar...
<p>I got stacked with the same problem. But the reason is that I use the raw text file for test. It is the transferred binary file should be used. I'm not sure whether your situation is the same with me.</p>
python|python-2.7|amazon-web-services|tensorflow|p2
1
366,493
43,661,027
Python py2exe executable silent crash with scipy.linalg or numpy.linalg
<p>I've been using py2exe to package some scripts as executable, which has worked well until this error.</p> <p>In one script I need to solve a straightforward system of linear equations. I've been doing this with scipy.linalg.lstsq.</p> <p>The problem is that any script I package with any scipy.linalg or numpy.linal...
<p>I managed to solve this problem and wanted to post the solution.</p> <p>The link posted by J.J. Hakala, showed that an error with the same symptoms can occur with matplotlib because py2exe does not transfer some necessary dll's to the new dist directory. I was already transferring the dll's mentioned in that post m...
python|numpy|scipy|py2exe
0
366,494
1,589,706
Iterating over arbitrary dimension of numpy.array
<p>Is there function to get an iterator over an arbitrary dimension of a numpy array?</p> <p>Iterating over the first dimension is easy...</p> <pre><code>In [63]: c = numpy.arange(24).reshape(2,3,4) In [64]: for r in c : ....: print r ....: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16...
<p>What you propose is quite fast, but the legibility can be improved with the clearer forms:</p> <pre><code>for i in range(c.shape[-1]): print c[:,:,i] </code></pre> <p>or, better (faster, more general and more explicit):</p> <pre><code>for i in range(c.shape[-1]): print c[...,i] </code></pre> <p>However, ...
python|numpy|loops
71
366,495
72,917,368
reshape df with timeseries to have n-1 value
<p>Given I have the current df. I am trying to create a new column with the n-1 value.</p> <pre><code> Date id Val 2012-03-01 a 1 2012-06-01 a 2 2012-09-01 a 3 2012-12-01 a 4 2013-03-01 a 5 2013-06-01 a 6 2013-09-01 a 7 2013-12-01 a 8 2012-03-01 b 100 2012-06-01 b 101 201...
<p>Well, I figured it out myself.</p> <pre><code>df['Valu_n_minus_1'] = df.sort_values(by=['Date']).groupby('id')['Val'].shift() </code></pre>
python|pandas|date|time-series
1
366,496
72,888,800
How to go through my entire Excel sheet and get each cell value?
<p>I am trying to get values from an <code>xlsx</code> Excel sheet, and input those values into a SQL Insert statement.</p> <p>For example, I have this as the first 3 rows of my Excel sheet.</p> <pre><code>Id Title Make Model isCurrent 1 Red Ranger Ford Ranger XLT 1 2 White CRV Ho...
<p>Instead of looping through everything, could you not just insert via <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html" rel="nofollow noreferrer"><code>DataFrame.to_sql</code></a>?</p> <p>If that isn't an option, you could also use <a href="https://pandas.pydata.org/docs/reference/ap...
python-3.x|pandas
2
366,497
73,059,412
Get the index of a value passed to map() in pandas
<p>I have a DataFrame that's read in from a csv. The data has various problems. The one i'm concerned about for this post is that some data is not in the column it should be. For example, '900' is in the zipcode column, or 'RQ' is in the langauge column when it should be in the nationality column. In some cases, these ...
<p>I guess this would do what you want ...</p> <pre><code>is_zipcode_mask = df['ZIPCODE'].str.match(regex_for_zipcode) print(len(df[is_zipcode_mask])) </code></pre>
python|pandas|csv
1
366,498
73,016,288
VLOOKUP+FOR loop in python
<p>I am learning python right now and I need help to complete a project. So, I have an excel file of 1M rows and I am trying to write a script that will fill out the &quot;Account type&quot; column based on the account number.</p> <p><a href="https://i.stack.imgur.com/XtgWQ.png" rel="nofollow noreferrer">SCREENSHOT</a>...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>pandas.cut</code></a> like this:</p> <pre><code>df['Account Type'] = pd.cut( df_data['Account Number'], bins=[0, 99, 1999, 2899, 2999, 3999, 4999, 5199, 5399, 5999, 6699, 6799], labels=[ ...
python|pandas|vlookup
0
366,499
73,120,492
How can I make a new column from other column's string?
<p>input df:</p> <pre><code>A Jan.S1 Jan.S2 Feb.S1 Feb.S2 x 1 2 3 4 y 6 7 8 9 </code></pre> <p>output df:</p> <pre><code>A month S1 S2 x Jan 1 2 x Feb 3 4 y Jan 6 7 y Feb 8 9 </code></pre> <p>How can I make input become output format?</p>
<p>If you had a numeric value only after the '.' you could use <a href="https://pandas.pydata.org/docs/reference/api/pandas.wide_to_long.html" rel="noreferrer"><code>pandas.wide_to_long</code></a>.</p> <p>As this is not the case, you can use a manual reshaping with a MultiIndex and <code>stack</code>:</p> <pre><code>ou...
python|pandas
4