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
1,700
63,060,623
Can you create a data frame of a dictionary?
<p>I am trying to understand a black of code. Is it possible to have a data frame of a dictionary?</p> <pre><code>def plot_dists(num_samples, mu=0, sigma=1): norm_samples = numpy.random.normal( loc=mu, scale=sigma, size=num_samples) poisson_samples = numpy.random.poisson( lam=sigma**2, size=num_samples...
<p>pandas dataframe is a way to represent tabular data. if you read the documentation the first parameter of the class constrcutor (data ) accepts ndarray, Iterable, dict, or DataFrame.</p> <p>[https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html]</p> <p>so to create a data frame you can pa...
python|pandas|dictionary
0
1,701
62,968,978
How to add new column data by individual rows in Pandas DataFrame
<p>I have a dataframe <code>df</code>. I want to add 2 new columns <code>0</code> and <code>1</code> and add data to these columns by one row at a time, and not the complete column at once. By using <code>pd.Series</code> for all the rows in <code>df</code> I am getting <code>NaN</code> value in the new column data oth...
<p>It is not clear why you are trying to add rows one at a time with inefficient methods, hence I suggest not to use this code but to rely on vectorized solutions.</p> <p>However, if you really want to do it for some reason, you should modify your cycle like this</p> <pre><code>for j in range(len(df)): for i in ran...
python|pandas|loops|dataframe|nan
1
1,702
63,252,135
Pandas dataframes too large to append to dask dataframe?
<p>I'm not sure what I'm missing here, I thought dask would resolve my memory issues. I have 100+ pandas dataframes saved in .pickle format. I would like to get them all in the same dataframe but keep running into memory issues. I've already increased the memory buffer in jupyter. It seems I may be missing somethin...
<p>Have you considered to first convert the <code>pickle</code> files to <code>parquet</code> and then load to dask? I assume that all your data is in a folder called <code>raw</code> and you want to move to <code>processed</code></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import dask.dataf...
python|pandas|dataframe|jupyter|dask
1
1,703
67,665,159
How do I groupby, count or sum and then plot two lines in Pandas?
<p>Say I have the following dataframes:</p> <p><code>Earthquakes</code>:</p> <pre><code> latitude longitude place year 0 36.087000 -106.168000 New Mexico 1973 1 33.917000 -90.775000 Mississippi 1973 2 37.160000 -104.594000 Colorado 1973 3 37.148000 -104.571000 Colo...
<p>Input data:</p> <pre><code>&gt;&gt;&gt; df2 # Earthquakes year 0 2007 1 1974 2 1979 3 1992 4 2006 .. ... 495 2002 496 2011 497 1971 498 1977 499 1985 [500 rows x 1 columns] &gt;&gt;&gt; df1 # Wells BBLS year 0 16655 1997 1 7740 1998 2 37277 2000 3 20195 2014 4 ...
python|pandas|matplotlib|counter|spyder
1
1,704
67,941,538
Drop duplicate values from hierarchical index
<p>I have a hierarchical index. I want to get the unique values for each index. How can I do that?</p> <pre><code>Party Name Bahujan Agiaon Agiaon Amarpur Samajwadi Vaishali Vaishali Wazirgan...
<p>You can factorize the index , then convert to series and keep only the ones which aren't duplicated:</p> <pre><code>df[~pd.Series(df.index.factorize()[0]).duplicated().to_numpy()] </code></pre> <hr /> <pre><code>Party Name Bahujan Agiaon Amarpur Samajwadi Vaishali Wazi...
python|pandas|dataframe|data-science
0
1,705
68,002,677
model.predict() output dimensions is not the same as y_train dimensions
<p>I am currently working on an LSTM model to predict the closing price of a stock based on other data. It is my first time working with RNNs. I am using tensorflow.</p> <p>The issue arises when I try to predict prices over the X train data (which is what the model was trained on). I get different dimensions when compa...
<p>I managed to figure out what was wrong. Turns out it was a pretty silly mistake.</p> <p>This was the model that gave the error</p> <pre><code>model = Sequential() model.add(LSTM(50,return_sequences=True,input_shape=(100, 7))) model.add(Dropout(0.7)) model.add(LSTM(50,return_sequences=True)) model.add(Dropout(0.7)) ...
python|tensorflow|deep-learning|lstm
0
1,706
67,694,895
module 'tensorflow._api.v1.compat.v2' has no attribute '__internal__' google colab error
<p>I am running a tensorflow model on google colab. Today, I got this error:</p> <pre><code> Using TensorFlow backend. Traceback (most recent call last): File &quot;train.py&quot;, line 6, in &lt;module&gt; from yolo import create_yolov3_model, dummy_loss File &quot;/content/drive/MyDrive/yolo/y...
<p>Try these parameters, it works with me</p> <pre><code>!pip3 uninstall keras-nightly !pip3 uninstall -y tensorflow !pip3 install keras==2.1.6 !pip3 install tensorflow==1.15.0 !pip3 install h5py==2.10.0 </code></pre>
python|tensorflow|google-colaboratory
17
1,707
41,242,945
Python 3.x - Pandas apply is very slow
<p>I have created a recommender system. There are 2 dataframes – input_df and recommended_df</p> <p>input_df – Dataframe of content already viewed by users. This df is used for generating the recommendations</p> <pre><code>User_Name Viewed_Content_Name User1 Content1 User1 Content2 User1 Content5 User2 Cont...
<p>Try to only use apply as a last resort. You can concatenate user and content and then use boolean selection.</p> <pre><code>user_content_seen = input_df.User_Name + input_df.Viewed_Content_Name user_all = Recommended_df.User_Name + Recommended_df.Recommended_Content_Name Recommended_df[~user_all.isin(user_content...
python|pandas|apply|recommendation-engine
2
1,708
41,627,300
Pandas element wise if/else (IIF)
<p>Is there a element-wise IIF function in Pandas? </p> <p>E.g. given a dataframe:</p> <pre><code>w = pd.DataFrame({'Date':pd.to_datetime(['2016-01-01','2016-01-02','2016-01-03']),'A1':[0.3,0.1,0.1],'A2':[0.4,0.4,0.4]}).set_index(['Date']) </code></pre> <p>If the element > 0.2, set to 1, else set to 0. Such as bel...
<p>You need compare with <code>0.2</code> and <code>boolean DataFrame</code> cast to <code>np.uint8</code>:</p> <pre><code>print (w &gt; .2) A1 A2 Date 2016-01-01 True True 2016-01-02 False True 2016-01-03 False True w1 = (w &gt; .2).astype(np.uint8) print (w1) ...
pandas
3
1,709
61,519,128
How to fix the dimension error in the loss function/softmax?
<p>I am implementing a logistic regression in PyTorch for XOR (I don't expect it to work well it's just a demonstration). For some reason I am getting an error 'IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)'. It is not clear to me where this originates. The error points to log_softm...
<p>First of all, you are doing a binary classification task. So the number of output features should be 2; i.e., <code>num_outputs = 1</code>.</p> <p>Second, as it's been declared in <a href="https://pytorch.org/docs/stable/nn.html#crossentropyloss" rel="nofollow noreferrer"><code>nn.CrossEntropyLoss()</code></a> docu...
python|pytorch
1
1,710
61,602,880
Tensorflow 2.x: Convert byte string to int in map
<p>I have a TFRecordDataset of images. Each record has an image, an integer label, and a byte-array ID. The byte-array is a hex representation of some number.</p> <p>I wish to seed the random operations with a derivative of the ID. How do I do that?</p> <p>The following attempt failed:</p> <pre class="lang-py pre...
<p>Decoding a binary string (tensor) into an int (tensor) is actually quite straight-forward:</p> <pre class="lang-py prettyprint-override"><code>tf.io.decode_raw(tf.constant(b'ABC'), tf.uint8) </code></pre> <p>-&gt; <a href="https://www.tensorflow.org/api_docs/python/tf/io/decode_raw" rel="nofollow noreferrer">https:/...
tensorflow2.0|tensorflow-datasets
0
1,711
68,703,586
Identify and count objects different from background
<p>I try to use python, NumPy, and OpenCV to analyze the image below and just draw a circle on each object found. The idea here is not to identify the bug only identify any object that is different from the background.</p> <p>Original Image: <a href="https://i.stack.imgur.com/ykK7A.jpg" rel="nofollow noreferrer"><img s...
<p>Here is one way in Python/OpenCV.</p> <p>Threshold on the bugs color in HSV colorspace. Then use morphology to clean up the threshold. Then get contours. Then find the minimum enclosing circle around each contour. Then bias the radius to make a bit larger and draw the circle around each bug.</p> <p>Input:</p> <p><a ...
python|python-3.x|numpy|opencv
1
1,712
68,645,655
Use a multidimensional index on a MultiIndex pandas dataframe?
<p>I have a multiindex pandas dataframe that looks like this (called p_z):</p> <pre><code> p_z entry subentry 0 0 0.338738 1 0.636035 2 -0.307365 3 -0.167779 4 0.243284 ... ... 26692 891 -0.459227 892 ...
<p>IIUC:</p> <p>Input data:</p> <pre><code>&gt;&gt;&gt; p_z p_z entry subentry 0 0 0.338738 1 0.636035 2 -0.307365 3 -0.167779 4 0.243284 &gt;&gt;&gt; tofpid tofpid entry subentry 0 0 0 1 ...
python|pandas|multi-index|uproot|awkward-array
1
1,713
68,574,625
Calculated column with shift
<p>This is the base DataFrame:</p> <pre><code> g_accessor number_opened number_closed 0 49 - 20 3.0 1.0 1 50 - 20 2.0 14.0 2 51 - 20 1.0 6.0 3 52 - 20 0.0 6.0 4 1 - 21 1.0 4.0 5 2 - 2...
<p>You are assuming that the result for the previous row is available when the current row is calculated. This is not how pandas calculations work. Pandas calculations treat each row in isolation, unless you are applying multi-row operations like <code>cumsum</code> and <code>shift</code>.</p> <p>I would calculate the ...
python|pandas|dataframe
1
1,714
68,855,571
How to convert a nested JSON to CSV
<p>I want to convert nested json into csv format including sub rows for grouped list/dict.</p> <p>Here my json</p> <pre class="lang-json prettyprint-override"><code>data =\ { &quot;id&quot;: &quot;1&quot;, &quot;name&quot;: &quot;HIGHLEVEL&quot;, &quot;description&quot;: &quot;HLD&quot;, &quot;item&quot...
<p><strong>This should work for you:</strong></p> <pre><code>from copy import deepcopy import pandas def cross_join(left, right): new_rows = [] if right else left for left_row in left: for right_row in right: temp_row = deepcopy(left_row) for key, value in right_row.items(): ...
python|json|pandas|csv|json-normalize
3
1,715
36,294,145
Python: summarizing data in dataframe using a series
<p>I want to reduce dataframe down to more of summary data. I have the following dataframe:</p> <pre><code>In [8]: df Out[8]: CTRY_NM ser_no date 0 a 1 2016-01-01 1 a 1 2016-01-02 2 b 1 2016-03-01 3 e 2 2016-01-01 4 e 2 2016-01-02 5 a 2 ...
<p>You can use <code>agg</code> and specify an operation for each date value:</p> <pre><code>&gt;&gt;&gt; df.groupby(['ser_no', 'CTRY_NM']).date.agg( {'start_dt': min, 'end_dt': max, 'number_of_dt': 'count'}) number_of_dt start_dt end_dt ser_no CTRY_NM ...
python|pandas|dataframe
2
1,716
36,516,019
adding a counting colum to a numpy array in python
<p>I have a 1d numpy array <code>ans</code>, i.e.: </p> <pre><code>ans=[8,5,9,2,4] </code></pre> <p>I want to convert it into a 2d array like:</p> <pre><code>ans= {[1,8], [2,5], [3,9], [4,2], [5,4]} </code></pre> <p>the first column is in sequence:</p> <pre><code>[1,2,3......500,501..] </code></pre...
<p>Assuming you are actually working with numpy, and your question is just sloppy, here's one way with <code>numpy.vstack</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; right = np.array([8,5,9,2,4]) &gt;&gt;&gt; np.vstack([np.arange(1, len(right) + 1), right]).T array([[1, 8], [2, 5], ...
python|numpy
1
1,717
53,148,176
Tensorflow installation Mac error: unable to find matching distribution
<p>I am attempting to install TensorFlow on my Macintosh computer. I was following the instructions as provided on their website when I reached a problem. I had established a virtual environment in the MacOS terminal and attempted to use pip to install TensorFlow with the command</p> <pre><code>pip install tensorflow ...
<p>try updating pip using python3 -m pip3 install --upgrade pip3 and try again by specifying tensorflow version with pip3 install tensorflow==2.3.1</p>
python|macos|tensorflow|neural-network|pip
0
1,718
65,561,554
Counting elements of an array in a new column of a data frame row by row
<p>I didn't find a solution in the forum that helped me. I have a very big data frame of transportation data. One of my 33 columns of my data frame is an array which includes the allowed labels of the solution (of this row).</p> <p>So the column is:</p> <pre><code>usedLabels [db_fv, blablacar, flixbus] [db_fv, blabla...
<p>try:</p> <pre><code>df['UsedLabelsCount']=[len(i) for i in df['usedLabels']] </code></pre>
arrays|pandas|dataframe|count
1
1,719
65,762,778
Python pandas: how to compare multiple value within a dataframe
<p>My dataframe looks like this</p> <pre><code> cn id amount date 1 0051 45897 2021-01-14 1 0051 78484 2021-01-15 subtotal 124381 2 0052 1751591 2021-01-14 2 0052 2110386 2021-01-15 subtotal 3861977 3...
<p>You can just compare the amount with 2021-01-14 with the next amount in that column cause if it's bigger it takes more than 50 percent of subtotal</p>
python|pandas|dataframe
0
1,720
21,057,397
Possible Bug in pandas.groupby.agg?
<p>I might have found a bug in pandas.groupby.agg. Try the following code. It looks like what is passed to the aggregate function fn() is a data frame including the key. In my understanding, the agg function is applied to each column separately and only one column is passed. Since the 'year' column appears in groupby, ...
<p>To answer your question, if you absolutely want the function applied to a <code>Series</code>, use the <code>{column: aggfunc}</code> syntax in <code>.agg()</code>.</p> <p>That said, your code seems to work fine (at least on the current master). The function isn't actually being applied to the <code>year</code> col...
python|pandas
2
1,721
21,217,108
python datapanda: getting values from rows into list
<p>I'd like to get the values of my dataframe's rows into a list:</p> <pre><code> A B C 1 2 3 2 2 4 2 6 list1 = [2, 3 2] list2 = [4, 2, 6] </code></pre> <p>How can I do that?</p>
<p>You can do it using <code>values.tolist()</code>:</p> <pre><code>from pandas import DataFrame df = DataFrame({'a': [2,4], 'b': [3,2], 'c': [2,6]}) print df list1 = df.irow(0).values.tolist() list2 = df.irow(1).values.tolist() </code></pre> <p><strong>output:</strong></p> <pre><code> a b c 0 2 3 2 1 4 2...
python|pandas
2
1,722
21,371,180
numpy: apply operation to multidimensional array
<p>Assume I have a matrix of matrices, which is an order-4 tensor. What's the best way to apply the same operation to all the submatrices, similar to Map in Mathematica?<br></p> <pre><code>#!/usr/bin/python3 from pylab import * t=random( (8,8,4,4) ) #t2=my_map(det,t) #then shape(t2) becomes (8,8) </code></pre> <p><b>...
<p>First check the documentation for the operation that you intend to use. Many have a way of specifying which axis to operate on (<code>np.sum</code>). Others specify which axes they use (e.g. <code>np.dot</code>).</p> <p>For <code>np.linalg.det</code> the documentation includes:</p> <blockquote> <p>a : (..., M,...
python|arrays|numpy|multidimensional-array
1
1,723
20,903,865
Geometric progression using Python / Pandas / Numpy (without loop and using recurrence)
<p>I'd like to implement a geometric progression using Python / Pandas / Numpy.</p> <p>Here is what I did:</p> <pre><code>N = 10 n0 = 0 n_array = np.arange(n0, n0 + N, 1) u = pd.Series(index = n_array) un0 = 1 u[n0] = un0 for n in u.index[1::]: #u[n] = u[n-1] + 1.2 # arithmetic progression u[n] = u[n-1] * 1.2...
<p>Another possibility, that is probably more computationally efficient than using exponentiation:</p> <pre><code>&gt;&gt;&gt; N, un0, q = 10, 1, 1.2 &gt;&gt;&gt; u = np.empty((N,)) &gt;&gt;&gt; u[0] = un0 &gt;&gt;&gt; u[1:] = q &gt;&gt;&gt; np.cumprod(u) array([ 1. , 1.2 , 1.44 , 1.728 , 2.0...
python|math|numpy|pandas
11
1,724
21,030,391
How to normalize a NumPy array to a unit vector?
<p>I would like to convert a NumPy array to a unit vector. More specifically, I am looking for an equivalent version of this normalisation function:</p> <pre><code>def normalize(v): norm = np.linalg.norm(v) if norm == 0: return v return v / norm </code></pre> <p>This function handles the situation w...
<p>If you're using scikit-learn you can use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.normalize.html#sklearn.preprocessing.normalize" rel="noreferrer"><code>sklearn.preprocessing.normalize</code></a>:</p> <pre><code>import numpy as np from sklearn.preprocessing import normalize x...
python|numpy|scikit-learn|statistics|normalization
222
1,725
3,006,844
Python Library installation
<p>I have two questions regarding python libraries:</p> <ol> <li><p>I would like to know if there is something like a "super" python library which lets me install ALL or at least all scientific useful python libraries, which I can install once and then I have all I need.</p></li> <li><p>There is a number of annoying p...
<p>In Windows enviroments, <a href="http://www.pythonxy.com/" rel="noreferrer">pythonXY</a> is what your are looking for.</p>
python|numpy|matplotlib|python-imaging-library
5
1,726
63,585,260
Reading Columns without headers
<p>I have some code that reads all the CSV files in a certain folder and concatenates them into one excel file. This code works as long as the CSV's have headers but I'm wondering if there is a way to alter my code if my CSV's didn't have any headers.</p> <p>Here is what works:</p> <pre><code>path = r'C:\Users\Desktop\...
<pre><code> df = df[~df['Ran'].isin(['Active'])] </code></pre> <p>Instead of selecting a column by name, select it by index. If the <code>'Ran'</code> column is the third column in the csv use...</p> <pre><code> df = df[~df.iloc[:,2].isin(['Active'])] </code></pre> <hr /> <p>If some of your files have headers and some ...
python|pandas|csv
0
1,727
63,632,541
Order of spline interpolation for pandas dataframe
<p>I have the following dataframe which shows data from Motion Capture, where each column is a marker (i.e. position data) and rows are time:</p> <pre><code> LTHMB X RTHMB X 0 932.109 872.921 1 934.605 873.798 2 932.383 873.998 3 940.946 875.609 4 941.549 875.875 ... ... ......
<p>The order of spline has nothing to do with the number of features that you have in the dataset. Each feature will be interpolated independently to each other. Before applying an algorithm it is therefore important to understand how it works and what each of its parameters (such as 'order') contributes towards.</p> <...
python|pandas|dataframe|interpolation|spline
2
1,728
63,582,734
What can I apply numpy.std() to?
<p>I have very little knowledge of statistics, so forgive me, but I'm very confused by how the numpy function <code>std</code> works, and the documentation is unfortunately not clearing it up.</p> <p>From what I understand it will compute the standard deviation of a distribution from the array, but when I set up a Gaus...
<p>I suspect that you understand perfectly well how the function works, but are misunderstanding the meaning of your data. Standard deviation is a measure of the spread of data about the mean value.</p> <p>When you say <code>std(f)</code>, you are computing the the spread of the y-values about their mean. Looking at th...
python|numpy|standard-deviation
4
1,729
63,508,035
How to iterate through dataframe rows, split data to separate dataframes based on column?
<p>I've looked at iterrows, list comprehension, dictionary comprehension, apply, and itertuples. I cannot get any of those to do the scenario below. Any help would be greatly appreciated!</p> <p>Example original dataframe:</p> <pre><code>ID |State |Invoice|Price|Email 1000|Texas |1 |2 |texas@test.com 1000|T...
<p>I was able to create a dictionary that has each dataframe split out by ID using the following code:</p> <pre><code>dict_of_dfs = { ID: group_df for ID, group_df in df.groupby('ID') } </code></pre> <p>I was also able to create a list that has each dataframe split out by ID using the following code:</p> <...
python|pandas|dataframe
0
1,730
21,924,303
Numpy Mutidimensional Subsetting
<p>I have searched long and hard for an answer to this question, but haven't found anything that quite fits the bill. I have a multidimensional numpy array containing data (in my case 3 dimensional) and another array (2 dimensional) that contains information on which value I want along the last dimension of the origina...
<p>When you fancy-index a multidimensional array with multidimensional arrays, the indices for each dimension are broadcasted together. With that in mind, you can do:</p> <pre><code>&gt;&gt;&gt; rows = np.arange(a.shape[0]) &gt;&gt;&gt; cols = np.arange(a.shape[1]) &gt;&gt;&gt; a[rows[:, None], cols, b] array([[0, 3],...
python|arrays|numpy
2
1,731
21,687,633
adding column with per-row computed time difference from group start?
<p>(newbie to python and pandas)</p> <p>I have a data set of 15 to 20 million rows, each row is a time-indexed observation of a time a 'user' was seen, and I need to analyze the visit-per-day patterns of each user, normalized to their first visit. So, I'm hoping to plot with an X axis of "days after first visit" and a...
<p>Does this help you get started?</p> <pre><code>&gt;&gt;&gt; df = DataFrame({'uid':uid,'misc':misc,'ts':rng}) &gt;&gt;&gt; df = df.sort(["uid", "ts"]) &gt;&gt;&gt; df["since_seen"] = df.groupby("uid")["ts"].apply(lambda x: x - x.iloc[0]) &gt;&gt;&gt; df misc ts uid since_seen 0 2000-...
python|pandas
3
1,732
29,955,457
Cast dataframe groupby to dataframe
<p>All I need is to cast a DataFrameGroupBy object to a DataFrame in order to export to excel using <code>df.to_excel()</code>. When I try to do <code>df_groupby = pd.DataFrame(df_groupby)</code> I get the error: <code>PandasError: DataFrame constructor not properly called!</code></p> <p>Original df:</p> <pre><code> ...
<p>I am not sure what you want to achieve. So here goes for a set of possible answers. </p> <p>But first: the bad news. A groupby object is not a DataFrame, and it cannot be saved to excel (or simply turned into a DataFrame).</p> <p>1) If you just want to sort the DataFrame, this will also "group" things</p> <pre><c...
python|pandas|export-to-excel
3
1,733
30,267,338
Setting values in pandas Series is slow, why?
<h3>Question</h3> <p>Does anyone know why setting an item directly on a pandas series is so incredibly slow? Am I doing something wrong, or is it just the way it is?</p> <p>I ran a couple of tests to see what the fastest method is to set a value on a pandas Series object. Here are the results, ordered from fast to slow...
<p>From the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#fast-scalar-value-getting-and-setting" rel="noreferrer">docs</a></p> <blockquote> <p>Since indexing with [] must handle a lot of cases (single-label access, slicing, boolean indexing, etc.), it has a bit of overhead in order to figure...
python|pandas
5
1,734
53,380,971
Saving static files in redis session (Python flask)
<p>I'm trying to build a machine learning web app where users can input the parameters and the predictions will be outputted as a .txt file. I'm also trying to use redis sessions as part of the web app so each users' .txt file will be different from each other.</p> <p>I'm using </p> <pre><code>df.to_csv(filename.txt)...
<p>you need to serialize your .txt file but in my opinion I would not use Redis for such a task, maybe sqlite or directly in the server. </p>
python|pandas|dataframe|machine-learning|redis
0
1,735
53,689,868
Splitting Python MeshGrid Into Cells
<p><strong>Problem Statement</strong></p> <p>Need to split an N-Dimensional MeshGrid into "cubes":</p> <p>Ex) 2-D Case:</p> <p>(-1,1) |(0,1) |(1,1)</p> <p>(-1,0) |(0,0) |(1,0)</p> <p>(-1,-1)|(0,-1)|(1,-1)</p> <p>There will be 4 cells, each with 2^D points:</p> <p>I want to be able to process the mesh, placing th...
<p>This should give you what you need:</p> <pre><code>from itertools import product import numpy as np def splitcubes(K, d): coords = [np.linspace(-1.0 , 1.0, num=K + 1) for i in range(d)] grid = np.stack(np.meshgrid(*coords)).T ks = list(range(1, K)) for slices in product(*([[slice(b,e) for b,e in z...
python|numpy|geometry|simulation|computational-geometry
9
1,736
53,736,983
How to interpret TensorBoard loss graph?
<p><a href="https://i.stack.imgur.com/xyzNk.png" rel="nofollow noreferrer">TensorBoard</a></p> <p>I'm using Tensorflow API for object detection and here is the loss plot from its default settings. Can you help me interpret differences of <code>classification_loss</code>, <code>localization_loss</code> and <code>object...
<p>You could calculate the location loss like this:</p> <pre><code>def location_loss( x, y, width, height, l_x, l_y, l_width, l_height, alpha = 0.001 ): point_loss = ( tf.square( l_x - x ) + tf.square( l_y - y ) ) * alpha size_loss = ( tf.square( tf.sqrt( l_width ) - tf.sqrt( width ) ) + tf.square( tf.sqrt( l_...
tensorflow|tensorboard|object-detection-api
0
1,737
53,470,831
pandas get dummies for column with list
<p>Input:- </p> <pre><code>empNo name 1234 [ AB, DE ] 5678 [ FG, IJ ] </code></pre> <p>Command:-</p> <pre><code>dataFrame = dataFrame.join(dataFrame.name.str.join('|').str.get_dummies().add_prefix('dummy_name_')) </code></pre> <p>The above command brings dummy "for each character of ...
<p>I think the list is not the list , so we using ast to convert the string type column back to list </p> <pre><code>import ast df.name=df.name.apply(ast.literal_eval) </code></pre> <p>Then using str <code>get_dummies</code></p> <pre><code>s=df.name.apply(pd.Series).stack().str.get_dummies().sum(level=0).add_prefix...
python|pandas|dataframe
5
1,738
53,470,273
flask pandas to tabulator tables are all messed up
<p>I'm a new Dev , trying to pass Pandas DataFrame to Tabulator , it works but the table is so messed up </p> <p>original file : <a href="https://i.stack.imgur.com/4U3cV.png" rel="nofollow noreferrer">original file in excel</a></p> <p>without tabulator : <a href="https://i.stack.imgur.com/OLWok.png" rel="nofollow nor...
<p>Working with .to_json(orient = "records") is always the best for Tabulator</p> <p>Try this:</p> <p>1) If there's no Id yet, just:</p> <pre><code>df.insert(0,'id',range(1,len(df)+1)) df= df.to_json(orient='records') JsonResponse({'myDF':df}) </code></pre> <p>2) Once back in Javascript, when you try to load you...
javascript|python|pandas|flask|tabulator
0
1,739
17,628,589
perform varimax rotation in python using numpy
<p>I am working on principal component analysis of a matrix. I have already found the component matrix shown below</p> <pre><code>A = np.array([[-0.73465832 -0.24819766 -0.32045055] [-0.3728976 0.58628043 -0.63433607] [-0.72617152 0.53812819 -0.22846634] [ 0.34042864 -0.080...
<p>You can find a lot of examples with Python. Here is an example I found for Python using only <code>numpy</code>, on <a href="http://en.wikipedia.org/wiki/Talk:Varimax_rotation" rel="noreferrer">Wikipedia</a>:</p> <pre><code>def varimax(Phi, gamma = 1, q = 20, tol = 1e-6): from numpy import eye, asarray, dot, su...
python|arrays|numpy
16
1,740
20,344,908
Optimizing a nested for-loop which uses the indices of an array for function
<p>Let's imagine an empty NumPy array of 3x4 where you've got the coordinate of the top-left corner and the step size in horizontal and vertical direction. Now I would like to know the coordinates for the middle of each cell for the whole array. Like this:</p> <p><img src="https://i.stack.imgur.com/1IEuh.png" alt="ent...
<p>Surely the way you are computing the <code>x</code> and <code>y</code> coordinates is highly inefficient because it's not vectorized at all. You can do:</p> <pre><code>In [1]: import numpy as np In [2]: extent = (5530000.0, 5000.0, 0.0, 807000.0, 0.0, -5000.0) ...: x_steps = np.array([0,1,2]) * extent[1] ......
python|arrays|numpy|lambda|vectorization
3
1,741
15,914,742
Python Pandas Series gives NaN data when passing a dict with large index values
<p>I am trying to build a Pandas series by passing it a dictionary containing index and data pairs. While doing so I noticed an interesting quirk. If the index of the data pair is a very large integer the data will show up as NaN. This is fixed by reducing the size of the index values, or creating the Series using two ...
<p>I bet you are on 32-bit; on 64-bit this works fine. In 0.10.1, the default of creation via dicts is to use the default numpy integer creation, which is system dependent (e.g. int32 on 32-bit, and int64 on 64-bit). You are overflowing the dtype, which results in unpredictable behavior.</p> <p>In 0.11 (coming out thi...
dictionary|python-2.7|pandas|series
0
1,742
71,808,375
Expected scalar type Double but found Float
<p>I am getting this error while trying to give an input image batch to my Pytorch model</p> <p><code>&quot;RuntimeError: Given groups=1, weight of size [64, 3, 4, 4], expected input[5, 96, 96, 3] to have 3 channels, but got 96 channels instead&quot;.</code></p> <p>I read images with skimage. My images are 96x96 and ba...
<p>I usually print model summary using torchinfo library to debug such errors. Your input should be in the form of [5, 3, 192, 192]. If image size is 96x96, your image size before applying the convolution is less than 4x4 so it shows error. <a href="https://i.stack.imgur.com/Ott4L.png" rel="nofollow noreferrer">this im...
python|pytorch|computer-vision
0
1,743
71,866,676
How to fill locations of shapefile based on CSV data set?
<p>I'm using GeoPandas in Python to create a heatmap of the state of Florida from a given CSV dataset and a shapefile of Florida:</p> <p><a href="https://i.stack.imgur.com/QVOZv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QVOZv.png" alt="enter image description here" /></a></p> <p>This is the cod...
<ul> <li>I believe I have found same shape file you are working with. I don't know the source of your COVID data so have used NY Times data (<a href="https://github.com/nytimes/covid-19-data" rel="nofollow noreferrer">https://github.com/nytimes/covid-19-data</a>)</li> <li>the normal terminology for a map based heatmap...
python|csv|geopandas|shapefile
1
1,744
72,067,723
Find duplicates in dataframe and group them by assigning a key
<p>I´ve looked around and found similar questions but none of them really helped me to find a solution. I want my script to read a csv which looks like this:</p> <pre><code>hot_dict = {'Links': links, 'Titles': titles, 'Datestamps': datestamp_extended,'GroupID': &quot;&quot; } </code></pre> <p>I want to find all dupli...
<p>For a simple key with an integer ID, you can first convert the Links column to <a href="https://pandas.pydata.org/docs/user_guide/categorical.html" rel="nofollow noreferrer">categorical data</a>, then just obtain the category code from that:</p> <pre><code>df['GroupID'] = df['Links'].astype('category').cat.codes </c...
python|pandas|dataframe|csv
1
1,745
72,034,269
Using pandas how to add(math operations) multiple rows between two columns to get a total
<p>I have a csv file with multiple columns that represent office supplies sales. I want to find the total sales for <em>pens</em> (<strong>unit price</strong> and <strong>item</strong> are the two <strong>columns</strong>) so firstly I sorted the df to search for <em>pens</em> under the column <strong>item</strong> and...
<p>I think there is a slight flaw in the logic you presented, but it is hard without the full context - i.e. sample dataframe, code snippet, etc.</p> <p>In order to calculate total sales of pen items you would need to calculate the sum(price * quantity) of all sales.</p> <p>so simple df:</p> <pre><code>import pandas as...
python|pandas|math|add
2
1,746
16,930,632
Create new numpy array-scalar of flexible dtype
<p>I have a working solution to my problem, but when trying different things I was astounded there wasn't a better solution that I could find. It all boils down to creating a single flexible dtype value for comparing and inserting into an array.</p> <p>I have an RGB 24-bit image (so 8-bits for each R, G, and B) image ...
<p>I could make <code>insert()</code> work for your case doing (note that instead of <code>0</code> it is used <code>[0]</code>):</p> <pre><code>values = insert(values, [0], (1,2,3)) </code></pre> <p>giving (for example):</p> <pre><code>array([(0, 1, 3), (0, 0, 0), (0, 0, 4), ..., (255, 255, 251), (255, 255, 253), (...
python|numpy
1
1,747
22,081,878
get previous row's value and calculate new column pandas python
<p>Is there a way to look back to a previous row, and calculate a new variable? so as long as the previous row is the same case what is the (previous change) - (current change), and attribute it to the previous 'ChangeEvent' in new columns?</p> <p>here is my DataFrame</p> <pre><code>&gt;&gt;&gt; df ChangeEvent Sta...
<p>The way to get the previous is using the shift method:</p> <pre><code>In [11]: df1.change.shift(1) Out[11]: 0 NaT 1 2014-03-08 2 2014-04-08 3 2014-05-08 4 2014-06-08 Name: change, dtype: datetime64[ns] </code></pre> <p>Now you can subtract these columns. <em>Note: This is with 0.13.1 (datetime stu...
python|pandas
98
1,748
22,258,491
Read a small random sample from a big CSV file into a Python data frame
<p>The CSV file that I want to read does not fit into main memory. How can I read a few (~10K) random lines of it and do some simple statistics on the selected data frame?</p>
<p>Assuming no header in the CSV file:</p> <pre><code>import pandas import random n = 1000000 #number of records in file s = 10000 #desired sample size filename = &quot;data.txt&quot; skip = sorted(random.sample(range(n),n-s)) df = pandas.read_csv(filename, skiprows=skip) </code></pre> <p>would be better if <code>read...
python|pandas|random|io|import-from-csv
96
1,749
17,836,880
orthogonal projection with numpy
<p>I have a list of 3D-points for which I calculate a plane by numpy.linalg.lstsq - method. But Now I want to do a orthogonal projection for each point into this plane, but I can't find my mistake:</p> <pre><code>from numpy.linalg import lstsq def VecProduct(vek1, vek2): return (vek1[0]*vek2[0] + vek1[1]*vek2[1] ...
<p>You are doing a very poor use of <code>np.lstsq</code>, since you are feeding it a precomputed 3x3 matrix, instead of letting it do the job. I would do it like this:</p> <pre><code>import numpy as np def calc_plane(x, y, z): a = np.column_stack((x, y, np.ones_like(x))) return np.linalg.lstsq(a, z)[0] &gt;...
python|arrays|numpy
14
1,750
55,277,068
How to sort DataFrame columns sequently from the first column?
<p>I sorted df columns by max value of rows.</p> <pre><code>dff = centroids.reindex(df.sum().sort_values(ascending=False).index, axis=1) print(dff) 13 9 2 6 7 0 5 0 0.423586 0.472548 0.366301 0.423973 0.312807 0.476197 0.384652 1 0.639636 0.734712 0.5...
<p>We can create a list that will hold the required order of columns. Let's call it <code>l</code> and initially populate it with the first column <code>0</code>. Then we iteratively find the max correlation between the column stored as the last element in <code>l</code> and the subset of the DataFrame that excludes co...
python|pandas|sorting|dataframe|correlation
1
1,751
55,193,970
loading saved model causes "'getIndices' : no matching overloaded function found" in tfjs
<p>I meet a problem like <a href="https://stackoverflow.com/questions/52857230/loading-saved-model-causes-failed-to-compile-fragment-shader-for-gather-op">Loading saved_model causes &quot;Failed to compile fragment shader&quot; for gather op</a> <a href="https://i.stack.imgur.com/mocFF.png" rel="nofollow noreferrer">en...
<p>In the end, I give up it, as latest version has removed loadFrozenModel, and the support is little. I try to use keras model and it works.</p>
tensorflow.js|tensorflowjs-converter
0
1,752
56,813,049
Tensorflow: concat two tensors with shapes [B, None, feat_dim1] and [B, feat_dim2] during graph construction
<p>As a tensorflow newbie, I'm trying to concatenate two tensor, <code>t1</code> and <code>t2</code>, together during graph construction. <code>t1</code>, <code>t2</code> have different ranks: <code>[B, T, feat_dim1]</code> and <code>[B, feat_dim2]</code>. But <code>T</code> can only be known during runtime, so in grap...
<ol> <li>Add another dimension to tensor <code>t2</code>: <code>(B, feat_dim2) --&gt; (B, 1, feat_dim2)</code>.</li> <li>Tile tensor <code>t2</code> <code>None</code> times along the previously added second dimension, where <code>None</code> is the dynamic second dimension of tensor <code>t1</code>.</li> <li>Concatenat...
tensorflow
2
1,753
56,616,824
IndexSlice on a datetime multindex not working, but doesn't seem different from a properly-working toy equivalent
<p>I'm used to using <code>IndexSlice</code> on <code>datetime</code> indices. This is a toy equivalent of my multindex DataFrame and you can see the slicing works</p> <pre><code>#slicing works on a simple DateTime index qf = pd.DataFrame(index=pd.date_range(start="1Jan2019",freq="d",periods=30)) qf.loc[idx['2019-1-1...
<p>This seems like a bug. According to <a href="https://github.com/pandas-dev/pandas/issues/10331#issuecomment-189582481" rel="nofollow noreferrer">this discussion</a>, check line 2614-2637 of the <code>multi.py</code> of pandas package:</p> <pre><code> try: if key.start is not None: ...
python|pandas
3
1,754
56,642,128
How to use k means for a product recommendation dataset
<p>I have a data set with columns titled as product name, brand,rating(1:5),review text, review-helpfulness. What I need is to propose a recommendation algorithm using reviews. I have to use python for coding here. data set is in .csv format. </p> <p>To identify the nature of the data set I need to use kmeans on the d...
<p>You did not plot anything.</p> <p>So nothing shows up.</p>
python|data-mining|k-means|recommendation-engine|sklearn-pandas
2
1,755
26,409,153
Slicing a pandas series using a list of float slices
<p>I have a large pandas Series with a float64 index.</p> <p>e.g. </p> <pre><code>s = pandas.Series([1,2,3,4,5], index=[1.0,2.0,3.0,4.0,5.0]) </code></pre> <p>but with 100,000s of rows.</p> <p>I would like to pull back multiple slices into a single subsetted series. At the moment I am doing this by building a list ...
<p>It will require some clever <code>numpy</code> <code>array</code> broadcasting, to check, for each value in <code>index</code>, if the value is between each of the intervals in the <code>interval</code> list (open on both end, such that >=low_end and &lt;=high_end):</p> <pre><code>In [158]: import numpy as np def f...
python|pandas
0
1,756
66,991,667
Numba jit unknown error during python function
<p>I made this function, but numba always give me error. Both chr_pos and pos are 1D arrays. What can be the problem?</p> <pre><code>@nb.njit def create_needed_pos(chr_pos, pos): needed_pos=[] needed_pos=np.array(needed_pos,dtype=np.float64) for i in range(len(chr_pos)): for k in range(len(pos)): ...
<p>The message</p> <pre><code>Cannot unify array(float64, 1d, C) and int32 for 'needed_pos.1' </code></pre> <p>is telling you that you are trying to assign an integer variable to an array. That happens in this line:</p> <pre><code> needed_pos=pos[k] </code></pre> <p>You can do that in normal Python, but Numba re...
numpy|numba
1
1,757
66,977,227
"Could not load dynamic library 'libcudnn.so.8'" when running tensorflow on ubuntu 20.04
<p>Note: there are many similar questions but for different versions of ubuntu and somewhat different specific libraries. I have not been able to figure out what combination of symbolic links, additional environment variables such as <code>LD_LIBRARY_PATH</code> would work</p> <p>Here is my <em>nvidia</em> configurati...
<p>So I had the same issue. As the comments say, it's because you need to install CUDNN. For that, there is a guide <a href="https://docs.nvidia.com/deeplearning/cudnn/install-guide/index.html" rel="noreferrer">here</a>.</p> <p>But as I know already your distro (Ubuntu 20.04) I can give you the command lines already:</...
python|tensorflow
41
1,758
66,806,959
How to assigne a dataframe mean to specific rows of dataframe?
<p>I have a data frame like this</p> <pre><code>df_a = pd.DataFrame({'a': [2, 4, 5, 6, 12], 'b': [3, 5, 7, 9, 15]}) Out[112]: a b 0 2 3 1 4 5 2 5 7 3 6 9 4 12 15 </code></pre> <p>and mean out</p> <pre><code>df_a.mean() Out[118]: a 5.800 b 7.800 dtype: float64 </code>...
<p>If you want to overwrite the values of rows in a list, you can do it with <code>iloc</code></p> <pre class="lang-py prettyprint-override"><code>df_a = pd.DataFrame({'a': [2, 4, 5, 6, 12], 'b': [3, 5, 7, 9, 15]}) idx_list = [3, 4] df_a.iloc[idx_list,:] = df_a.mean() </code></pre> <p>Output</p> <pre><code> a ...
pandas|dataframe|row|mean|unassigned-variable
0
1,759
47,105,912
Pandas dataframe values not changing outside of function
<p>I have a pandas dataframe inside a for loop where I change a value in pandas dataframe like this:</p> <pre><code>df[item].ix[(e1,e2)] = 1 </code></pre> <p>However when I access the df, the values are still unchanged. Do you know where exactly am I going wrong?</p> <p>Any suggestions?</p>
<p>You are using chained indexing, which usually causes problems. In your code, <code>df[item]</code> returns a series, and then <code>.ix[(e1,e2)] = 1</code> modifies that series, leaving the original dataframe untouched. You need to modify the original dataframe instead, like this:</p> <pre><code>import pandas as ...
pandas|dataframe
0
1,760
68,130,307
Python Excel file to Dictionary
<p>I would like to create depandant combobox from the Excel file. If the combo1 is selected, the combo2 will be changed depending on Combo1. The input is as below.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">City</th> <th style="text-align: right;">Name</th> </...
<p>Try via <code>groupby()</code>,<code>agg()</code> and <code>to_dict()</code> method:</p> <pre><code>out=df.groupby('City')['Name'].agg(list).to_dict() #you can also use apply() in place of agg() method </code></pre> <p>output of <code>out</code>:</p> <pre><code>{'AA': ['John', 'Anne'], 'BB': ['Sean', 'Dylan']} </cod...
python|pandas|pyqt
0
1,761
68,358,632
How to interpolate with groupby object in pandas?
<p>Original Dataframe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>a</th> <th>b</th> <th>yyyymm</th> <th>price</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>a</td> <td>200101</td> <td>3000</td> </tr> <tr> <td>1</td> <td>a</td> <td>200102</td> <td>np.nan</td> </tr> <tr> <td>1</td> <td>a...
<p>This works as expected:</p> <pre><code>df = pd.DataFrame({'a': [1,1,1,1,1,1,1,1,2,2,2,2], 'b': list('aaaabbbbaaaa'), 'yyyymm': [200101, 200102, 200103, 200104, 200101, 200102, 200103, 200104, 200101, 200102, 200103, 200104], 'price': [3000,np.NaN,np.NaN...
pandas|dataframe
1
1,762
68,098,208
changing index of 1 row in pandas
<p>I have the the below df build from a pivot of a larger df. In this table 'week' is the the index (dtype = object) and I need to show week 53 as the first row instead of the last</p> <p>Can someone advice please? I tried reindex and custom sorting but can't find the way Thanks!</p> <p><a href="https://i.stack.imgur.c...
<p>One way of doing this would be:</p> <pre><code>import pandas as pd df = pd.DataFrame(range(10)) new_df = df.loc[[df.index[-1]]+list(df.index[:-1])].reset_index(drop=True) </code></pre> <p>output:</p> <pre><code> 0 9 9 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 </code></pre> <p>Alternate method:</p> <pre><code>n...
python|pandas
0
1,763
68,344,150
Cythonize list of ndarrays to indirect_contiguous
<p>I want to cythonize a list of ndarrays (with different sizes) to speed up the performance of a function. A data structure of the type [:: view.indirect_contiguous,::1] seems the way to go, creating a contiguous array of pointers linked to contiguous memoryview of different sizes, but it is not clear to me how to set...
<p>Here's a possible solution that uses a temporary memoryview to get the pointer to the data. If anyone finds a better, cleaner or quicker answer please let me know.</p> <p>I wonder if I got the memory management right or if something is missing.</p> <pre><code># indirect_contiguous.pyx cimport numpy as np from cpytho...
python|performance|numpy|cython
0
1,764
59,433,143
TensorFlowJS fails to load a JS generated image
<p>TensorFlowJS can load the image from HTML but cannot normally load an image from a JavaScript generated image object. </p> <p>The code is shown as follows. The first group of loading methods can load the image from HTML. </p> <pre><code>h = document.getElementById("dandelion"); let image1 = await tf.browser.fromPi...
<p>It is failing to load the image, because the image has not completed to load before.</p> <pre><code>image.onload = () =&gt; { tf.browser.toPixels(image, x); } </code></pre>
javascript|html|tensorflow|tensorflow.js
0
1,765
59,092,292
How do I reindex my dataframe and also apply some of the operations or transformation on that data at the same time i am performing reindexing
<p>I have tried by this piece of code, but its not working for me</p> <pre><code>import pandas as pd Df1=pd.DataFrame({Price:[10,20,30,40],Company:['Abcd','Efgh','Ijkl','mnop'],City:['Delhi','Bangalore','Bombay','Chennai']}) Df2=Df1.reindex(index=[0,2],columns=['Price',Company],Df1['Price'].fill_value=Df1['Price']*12)...
<p>not sure your expected output is correct and worded correctly. 3 assumptions; </p> <ol> <li>10*12 should be 120 ? </li> <li>corresponding Price values should be used? (so 20 and not 30 for Company 'Efgh')</li> <li>you want the first 2 (or first 'x') rows? or any slice? (rather then condition based)</li> </ol> <p>...
python|pandas
0
1,766
59,071,835
Seaborn / MatplotLib Axis and Data Values formatting: Hundreds, Thousands, and Millions
<p>I have a problem, which, as far as I know hasn't been solved yet. </p> <p>I need formatting of my axes and data points for my Seaborn / Matplotlib graphs to be dynamic. An example of what I'd like to achieve is below (done via Keynote, I used a log scale to make the point clearer).</p> <p>What would be the best wa...
<p>Matplotlib has an <a href="https://matplotlib.org/api/ticker_api.html?highlight=engformatter#matplotlib.ticker.EngFormatter" rel="nofollow noreferrer">Engineering formatter</a> for specifically this purpose. You can use it to format the axis (using <code>set_major_formatter()</code>) or to format any number, using <...
python|pandas|matplotlib|seaborn
2
1,767
59,256,876
Best strategy for reading multiple large csv files in python with multiprocessing?
<p>I am writing some code and hoping to improve it with multiprocessing.</p> <p>Originally, I had the following code:</p> <pre class="lang-py prettyprint-override"><code>with Pool() as p: lst = p.map(self._path_to_df, paths) ... df = pd.concat(lst, ignore_index=True) </code></pre> <p>where <code>self._path_t...
<p>If the end result is too large to fit into memory try dask,</p> <pre><code>import dask.dataframe as dd df = dd.read_csv('*.csv') </code></pre> <p>then once it is read, you can do your aggregates, etc. and finally compute to get your desired answer.</p>
python|pandas|multiprocessing
0
1,768
59,462,913
Python group by and Combine all Text
<p>Working on an NLP Project in python is there a way to group all feedback below per specific Issue Group?</p> <pre class="lang-py prettyprint-override"><code>Out[40]: Issue Group Feedback 24 Accessories Nope, just make a longer charging cord :) 49 Accessories ...
<p>You can try groupby,</p> <pre><code>df.groupby('Issue Group').agg(lambda x: ','.join(x)) </code></pre> <p>Output of this will be text separated by comma ,</p> <pre><code>Nope, just make a longer charging cord :),Everything was very helpful and nice handled kEEP DOING WHAT YOU ARE DOING,None! Keep up the good work...
python|pandas|join|nlp
1
1,769
44,923,701
How to find matching python data frame values with other data frame
<p>I want to update in df1['Result'] as True or False if df1['Field1'] values exist in other dataframe df2['SersName']</p> <p>Please help...</p> <p>df1:</p> <pre><code>Field1 Field2 Result 2020RATIO001001 A TRUE 2020RATIO001003 B TRUE 2020RATIO001005 C TRUE 2020RATIO001XYZ D FALSE 2...
<p>You need to use <code>isin</code></p> <pre><code>import pandas as pd df1 = pd.read_csv(StringIO("""Field1 Field2 2020RATIO001001 A 2020RATIO001003 B 2020RATIO001005 C 2020RATIO001XYZ D 2020RATIO001123 E"""),sep=" ") df2 = pd.read_csv(StringIO("""SersName Field2 2020RATIO001001 1 2020RATIO001003 2 2020RATIO001005 ...
python|pandas|dataframe
0
1,770
56,944,155
Merging two string lists in pandas
<p>I have a dataframe with two series x and y. I want to merge them to create a new series: tag, but I'm not able to achieve the expected output. I've tried:</p> <pre><code>df['tag'] = df['x'] + df['y'] </code></pre> <p>I've looked everywhere and haven't been able to find a solution to the problem.</p> <p><strong>Cu...
<p>I do not think that is <code>list</code> , so you may convert it into <code>list</code> , them you can <code>sum</code> </p> <pre><code>import ast df.x = df.x.apply(ast.literal_eval) df.y = df.y.apply(ast.literal_eval) df['tag'] = df['x'] + df['y'] </code></pre> <hr> <p>More info </p> <pre><code>df=pd.DataFrame...
python|pandas
2
1,771
57,023,470
Pandas how to keep the LAST trailing zeros when exporting DataFrame into CSV
<p>In this question, my goal is to preserve the <strong>last</strong> <strong>trailing</strong> <code>zeros</code> when exporting the <code>DataFrame</code> to <code>CSV</code></p> <p>My <code>dataset</code> looks like this:</p> <pre><code>EST_TIME Open High 2017-01-01 1.0482 1.1200 2017-01-02 1.0483 1....
<blockquote> <p>Try this: Float format both to display your data with 4 decimal places and to save it with 4 decimal.</p> <p>when reading to pandas:</p> </blockquote> <pre><code>pd.options.display.float_format = '{:,.4f}'.format </code></pre> <blockquote> <p>when saving to CSV.</p> </blockquote> <pre><cod...
python|python-3.x|pandas|dataframe|export-to-csv
3
1,772
57,063,872
Weird tf.Print bug
<p>I am trying to use a tf.Print like this:</p> <pre><code>residual = tf.Print(residual, [residual], message='enc', summarize=100) </code></pre> <p>but it crashes with this error:</p> <pre><code>ValueError: Single tensor passed to 'data', expected list while building NodeDef 'tf_op_layer_tf_op_layer_TransformerEncod...
<p>Found answer here:</p> <p><a href="https://epcsirmaz.blogspot.com/2018/06/display-full-value-of-tensor-in.html" rel="nofollow noreferrer">https://epcsirmaz.blogspot.com/2018/06/display-full-value-of-tensor-in.html</a></p> <p>Basically, when using Keras, you have to wrap it in a lambda layer.</p>
python|python-3.x|tensorflow
2
1,773
57,041,639
How to make piechart from Pandas Dataframe
<p>I have created a shape (1,105) dataframe which has the classroom number as column name and the only row of the dataframe contains the total number of students in each classroom inside their appropriate column. I would like to make a piechart with as labels the column names and as data the corresponding number inside...
<p>To plot a pie chart from your DataFrame very simply, you can do:</p> <pre><code>df.transpose().plot.pie(subplots=True) </code></pre> <p>I tried it with this simple DataFrame:</p> <pre><code>df = pd.DataFrame([[24, 65, 13, 23, 10]], columns=[1, 2, 3, 4, 5]) </code></pre>
python|pandas|pie-chart
0
1,774
56,896,021
Model.fit in keras with multi-label classification
<p>I'm trying to learn how to implement my own dataset on the model seen here: <a href="https://keras.io/examples/cifar10_resnet/" rel="nofollow noreferrer">resnet </a>which is just a resnet model written in keras. Within the code they write this line</p> <pre><code>(x_train, y_train), (x_test, y_test) = cifar10.load_...
<p>So, <code>model.fit()</code> expects <code>x_train</code> as the features and <code>y_train</code> as the labels for a particular classification problem. I'll be taking into consideration <strong>multiclass image classification</strong>.</p> <ul> <li><p><code>x_train</code>: For image classification, this argument ...
python|tensorflow|keras
2
1,775
35,376,293
Extracting selected feature names from scikit pipeline
<pre><code># Load dataset iris = datasets.load_iris() X, y = iris.data, iris.target rf_feature_imp = RandomForestClassifier(100) feat_selection = SelectFromModel(rf_feature_imp, threshold=0.5) clf = RandomForestClassifier(5000) model = Pipeline([ ('fs', feat_selection), ('clf', clf), ])...
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectFromModel.html" rel="noreferrer"><code>SelectFromModel</code></a> has a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectFromModel.html#sklearn.feature_selection.SelectFromModel.get_supp...
python|numpy|scikit-learn
6
1,776
11,697,887
Converting Django QuerySet to pandas DataFrame
<p>I am going to convert a Django QuerySet to a pandas <code>DataFrame</code> as follows:</p> <pre><code>qs = SomeModel.objects.select_related().filter(date__year=2012) q = qs.values('date', 'OtherField') df = pd.DataFrame.from_records(q) </code></pre> <p>It works, but is there a more efficient way?</p>
<pre><code>import pandas as pd import datetime from myapp.models import BlogPost df = pd.DataFrame(list(BlogPost.objects.all().values())) df = pd.DataFrame(list(BlogPost.objects.filter(date__gte=datetime.datetime(2012, 5, 1)).values())) # limit which fields df = pd.DataFrame(list(BlogPost.objects.all().values('author...
python|django|pandas
135
1,777
50,808,911
Segmentation fault when opencv and tensorflow both use libgtk
<p>When OpenCV and tensorflow both use libgtk, a segmentation fault occurs. I have given below a simple script that creates the problem, relevant hardware and software versions and a stack trace. FWITW, the same versions of opencv, tensorflow, pandas etc worked just fine when I installed it on another machine in March...
<p>The basic problem here is that the same process was using two different version of gtk. </p> <p>My OpenCV used GTK3. Python uses GTK2 (in import gtk). Tensorflow and pandas both import gtk somewhere in their processing, hence they do have the same problem. </p> <p>For now, I have worked around this by recompiling...
tensorflow|gtk3|opencv3.0
0
1,778
51,097,526
Making a 2 dimensional list/matrix with different number of columns for each row
<p>I would like to make a list or matrix that has a known number of rows(3), but for each row the number of elements will be different. So it could look something like this:</p> <pre><code>[[4, 6, 8], [1, 2, 3, 4], [0, 2, 3, 4, 8]] </code></pre> <p>Each row will have a known maximum of elements(8). </p> <p>So far I ...
<p>Here is a sample of what your code should look like:</p> <pre><code>from random import * myMatrix = [ [], [], [] ] elementsNums = [1, 2, 3, 4, 5, 6, 7, 8] # possible length of each list in the matrix elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # random values in each list in the matrix def addElem...
python|python-2.7|list|numpy|arraylist
0
1,779
51,100,921
How to find out how many times a max value occurs in pandas?
<p>I wondered how to solve the following problem in pandas: </p> <p>I have a dataframe with a number of rows that have different values and would like to find out how often the highest value occurs per row. I have used df2 ['MAX_Value']=df2.max(axis=1) to get the highest value per row. </p> <p>This is an example of m...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>assign</code></a> with comapring by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>eq</code></a> and <code>sum</co...
python|pandas|dataframe|max
0
1,780
33,324,652
String Kernel SVM with Scikit-learn
<p>I am new to scikit-learn and I saw a sample solution posted in one of other questions on string kernels in scikitearn on Stackoverflow. So i tried that out, but I am getting this error message:</p> <pre><code>&gt;&gt;&gt; X = np.arange(len(data)).reshape(-1, 1) &gt;&gt;&gt; X array([[0], [1], [2]]) de...
<p>The specific error you're seeing actually has nothing to do with SVM. On this line in your <code>string_kernel</code> function:</p> <pre><code>R = np.zeros((len(x), len(y))) </code></pre> <p>lowercase <code>x</code> (and <code>y</code>) are currently undefined, hence the <code>UnboundLocalError</code>. <s>You</s> ...
python|numpy|machine-learning|scikit-learn|svm
1
1,781
9,595,898
numpy array of histograms
<p>I am currently working with a 2d numpy object array filled with collections.counter objects Each counter is basically a histogram.</p> <ul> <li>Keys are always from a limited set of integers eg between 0 and 1500</li> <li>number of items in each counter is variable, most are small but some have every key</li> </ul...
<p>If there are lots of empty counts,a sparse matrix representation may be a good fit, where the memory use is proportional to the number of non-empty elements in the array. SciPy has decent support for what it sounds like you're looking at: <a href="http://docs.scipy.org/doc/scipy/reference/sparse.html" rel="nofollow...
python|numpy
1
1,782
66,534,803
How to scatter plot values in a range color with cartopy?
<p>I have this <code>df</code>:</p> <pre><code> STATION LONGITUDE LATITUDE TMAXPERC 0 000130 -80.45750 -3.81333 9.034495 1 000132 -80.45722 -3.50833 7.291477 2 000134 -80.23722 -3.57611 15.760175 3 000135 -80.32194 -3.44056 5.256434 4 000136 -80.66083 -3.94889 12.301515 .. ... ...
<p>You need to specify some options properly:</p> <pre><code>plt.scatter( x=df[&quot;LONGITUDE&quot;], y=df[&quot;LATITUDE&quot;], c=df[&quot;TMAXPERC&quot;], cmap='viridis', #this is the changes s=4, alpha=1, transform=ccrs.PlateCarree() ) </code></pre>
pandas|matplotlib|cartopy
3
1,783
66,747,190
Count number of unique names per ID and write result in new pandas column
<p>I have a pandas dataframe:</p> <pre><code>df = pd.DataFrame( { &quot;id&quot;: [&quot;K0&quot;, &quot;K0&quot;, &quot;K0&quot;, &quot;K1&quot;, &quot;K1&quot;, &quot;K2&quot;, &quot;K2&quot;,&quot;K2&quot;], &quot;name&quot;: [&quot;Peter&quot;, &quot;Peter&quot;, &quot;Max&quot;, &quot;Jim&quot;, &quot;...
<p>Try with <code>transform</code></p> <pre><code>df['freq_name'] = df.groupby(['id','name'])['id'].transform('count') df Out[401]: id name freq_name 0 K0 Peter 2 1 K0 Peter 2 2 K0 Max 1 3 K1 Jim 1 4 K1 Lucy 1 5 K2 Lucy 2 6 K2 Lucy ...
pandas|group-by|pandas-groupby|aggregate
1
1,784
66,368,668
Crop Boxes in Tensorflow Object Detection and display it as jpg image
<p>I'm using the tensorflow objection detection to detect specific data on passports like full name and other things. I've already trained the data and everything is working fine. It perfectly identifies data surrounding it with a bounding box. However, now I just want to crop the detected boxes.</p> <p>Code:</p> <pre>...
<p>I found the solution of this by add this pice of code after end of this line:</p> <pre><code>(boxes, scores, classes, num) = sess.run([detection_boxes, detection_scores, detection_classes, num_detections],feed_dict={image_tensor: image_expanded}) </code></pre> <p>I add this:</p> <pre><code>(frame_height, frame_width...
python|tensorflow|object-detection
0
1,785
66,644,162
Extract data using indicator matrix (binary matrix)
<p>How can one use a binary matrix in order to get the specific positions in a dataset. So, for example if we took a matrix with categories 1 and 2 looked like this</p> <pre><code>1 2 0 0 2 1 0 0 2 </code></pre> <p>and the original data (<code>A</code>) looked like this:</p> <pre><code>a b c e f g i j k </code><...
<p>Rather than using this &quot;indicator matrix&quot; one could use a nested for loop with a nested if statement. This would let you get to the final answer. It would be inefficient but would still get you the desired result.</p>
python|arrays|numpy|matrix|sympy
1
1,786
66,642,466
Pandas - Stacked bar chart with multiple boolean columns
<p><a href="https://i.stack.imgur.com/PKPVm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PKPVm.png" alt="enter image description here" /></a></p> <p>I have data like this. I would like to make a stacked bar chart where the x-axis is the ball color and each stack in the bar is the percentage of bal...
<p>Use:</p> <pre><code>code_samp.groupby('Ball Color').sum().plot.bar() </code></pre> <p>or</p> <pre><code>code_samp.groupby('Ball Color').mean().plot.bar() </code></pre>
python|pandas|matplotlib
0
1,787
66,354,845
Create a new dataframe using the values of a categorical variable in a dataframe?
<p>Tried to retrieve Cost, if s['O_Status'] values is Closed, using below code.</p> <blockquote> <p>Got this error, ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()</p> </blockquote> <p>.</p> <pre><code> FClose = [i for i in s['Cost'] if s['O_Status'] == 'Closed'...
<pre><code>import io df = pd.read_csv(io.StringIO('''Cost Year O_Status 6100000 2001 Closed 100004 2009 Operating 2004000 2015 Closed 144007 1999 Operating'''), sep='\s+', engine='python') FClose = df[df['O_Status'] == 'Closed']['Cost'].tolist() print(FClose) FOp = df[df['O_St...
pandas|dataframe
0
1,788
66,446,450
Is it possible for me to run two python processes at once, one using the coral tpu, and another using only the cpu?
<p>For example if I wanted to run a lane detection algorithm, and an object detection algorithm at simulataneously.</p>
<p>Running two or more simultaneous python processes is possible but only one model can be executed on the TPU at once. When multiple models are too slow to run on a single Edge TPU, they needs to be executed across multiple Edge TPUs, so plugging the USB Accelerator into the DevBoard is a good test environment for tha...
python|tensorflow|raspberry-pi|tpu|google-coral
0
1,789
57,528,376
Extract future timeseries data and join on past timeseries that are 12 hours apart?
<p>I am in a data science course and my instructor isn't very strong in python. </p> <p>Use a shift function to pull prices by 12 hours (aligning prices 12 hours in the future with a row's current prices). Then create a new column populated with this info. </p> <p>So I should have my index, column 1, and newcolumn</p...
<p>This seemed to work </p> <pre><code>slice= currency [currency.index.min():currency.index.max()] #Move the datetime values forward an hour shifted = slice.shift(periods=1, freq='12H') </code></pre>
python|pandas|slice|data-science
1
1,790
24,147,029
Parsing a Multi-Index Excel File in Pandas
<p>I have a time series excel file with a tri-level column MultiIndex that I would like to successfully parse if possible. There are some results on how to do this for an index on stack overflow but not the columns and the <code>parse</code> function has a <code>header</code> that does not seem to take a list of rows....
<p>You can <code>fillna</code> the null values. I don't have your file, but you can test </p> <pre><code>#Headers as rows for now df = pd.read_excel(xls_file,0, header=None, index_col=0) #fill in Null values in "Headers" df = df.fillna(method='ffill', axis=1) #create multiindex column names df.columns=pd.MultiInde...
python|excel|parsing|pandas|time-series
7
1,791
43,876,776
Can't edit dataframe data through iloc in pandas
<p>So something really weird is happening when I try editing :</p> <pre><code>In [119]: print(GDP.iloc[1][0]) Out [119]: Andorra </code></pre> <p>When I try to edit it with <code>.iloc</code> and query it again this happens:</p> <pre><code>In [120]: GDP.iloc[1][0]="Cats" print(GDP.iloc[1][0]) Out [120]: An...
<p>It is best to avoid chaining assignments in pandas, see this <a href="https://stackoverflow.com/questions/21463589/pandas-chained-assignments">SO post</a> which refers to this Pandas doc about <a href="http://pandas-docs.github.io/pandas-docs-travis/indexing.html#why-does-assignment-fail-when-using-chained-indexing"...
python|pandas|numpy|dataframe|copy
2
1,792
72,851,617
how to select particular rows and columns without hardcoding in pandas python
<p>I want to select name and score from index 1 to 3 and store it to a dataframe. Can we extract that without hardcoding by giving a start word and end word.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd name_dict = { 'Name': ['a','b','c','d', 'e'], 'Score': ['0.90(sub...
<p>You can use <code>iloc</code>:</p> <pre><code>&gt;&gt;&gt; df.iloc[1:4] Name Score 1 b 80 2 c 95 3 d 20 </code></pre>
python|pandas
0
1,793
72,965,898
Python DataFrame - merging many urls into one cell
<p>I'm trying to merge many urls into one cell and save it as excel file, each row has many urls. This is the code of what I have tried</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd urls1 = [&quot;https://url1.com/&quot;,&quot;https://url2.com/&quot;] urls2 = [&quot;https://url3.com/&quot;,&qu...
<p>Try this:</p> <pre><code>import pandas as pd urls1 = [&quot;https://url1.com/&quot;,&quot;https://url2.com/&quot;] urls2 = [&quot;https://url3.com/&quot;,&quot;https://url4.com/&quot;] df1 = pd.DataFrame([urls1, urls2], columns=['column 1', 'column 2'], index=[&quot;First url&quot;, &quot;Second url&quot;]) df1.to_e...
python|excel|pandas|dataframe
0
1,794
73,143,171
how to calculate weighted average or sum by groupby from a list?
<p>I have a data frame and a list of weight as follows</p> <pre><code>import pandas as pd import numpy as np data = [ ['A',1,2,3,4], ['A',5,6,7,8], ['A',9,10,11,12], ['B',13,14,15,16], ['B',17,18,19,20], ['B',21,22,23,24], ['B',25,26,27,28], ['C',29,30,31,32], ['C',33,34,35,36], ['C',37,38,39,40], ...
<p>IIUC, you can use a <code>groupby.apply</code>:</p> <pre><code>df.groupby('Name').agg(lambda g: sum(g*weights[:len(g)])/sum(weights[:len(g)])) </code></pre> <p>output:</p> <pre><code> num1 num2 num3 num4 Name A 6.333333 7.333333 8.33333...
python|pandas|dataframe|group-by|weighted-average
2
1,795
72,972,473
Extract full year from Quarter value using Python
<p>I have a dataset where there is a column from where I would like to extract the full year.</p> <pre><code>**Data** ID Qtr AA Q123 AA Q123 BB Q226 BB Q327 **Desired** ID Qtr Year AA Q123 2023 AA Q123 2023 BB Q226 2026 BB Q327 2027 **Doing** df1 = datetime.datetime.strptim...
<p><a href="https://stackoverflow.com/users/9177877/it-is-chris">@It_is_Chris</a> talked through the simplest way, which is just string slicing. The following method actually creates datetimes. This is slower, but more powerful if you need to do anything more complex with your dates.</p> <p><code>&gt; df</code></p> <pr...
python|pandas|numpy
1
1,796
72,844,557
How to solve memory error? Should I increase memory limit?
<p>I was loading this but it says error.</p> <pre><code>import pandas as pd import numpy as np userMovie = np.load('userMovieMatrixAction.npy') numberUsers, numberGenreMovies = userMovie.shape genreFilename = 'Action.csv' genre = pd.read_csv(genreFilename) </code></pre> <p>MemoryError: Unable to allocate 3.63 GiB f...
<p>If the program runs out of memory, it seems like an issue with <a href="https://www.etalabs.net/overcommit.html" rel="nofollow noreferrer">overcommit handling</a> of your operative system. If you are in Linux, you can try to run the following command to enable &quot;always overcommit&quot; mode, which can help you l...
python|pandas|numpy|memory|out-of-memory
2
1,797
10,707,671
How to call a java function from python/numpy?
<p>it is clear to me how to extend Python with C++, but what if I want to write a function in Java to be used with numpy? </p> <p>Here is a simple scenario: I want to compute the average of a numpy array using a Java class. How do I pass the numpy vector to the Java class and gather the result?</p> <p>Thanks for any ...
<p>I spent some time on my own question and would like to share my answer as I feel there is not much information on this topic on <em>stackoverflow</em>. I also think Java will become more relevant in scientific computing (e.g. see WEKA package for data mining) because of the improvement of performance and other good ...
java|numpy
13
1,798
70,689,385
How to fit using float64?
<p>I've set all the layers in my model to use float64, yet when fitting the loss appears to still be coming out as float32 (based on the rounding I see). I'd like to ensure that all processing under the hood is in double. How can I guarantee that?</p>
<p>instead of manually setting the dtype for each layer, you can define a global policy with:</p> <pre><code>policy = tf.keras.mixed_precision.Policy(&quot;float64&quot;) tf.keras.mixed_precision.set_global_policy(policy) </code></pre> <p>or alternativly set the backend default float:</p> <pre><code>tf.keras.backend.se...
tensorflow|tensorflow2.0
1
1,799
42,820,063
divide by previous element by group in Pandas
<p>My question is the same as the one I posted for R (<a href="https://stackoverflow.com/questions/42726018/divide-by-previous-element-by-group">divide by previous element by group</a>), except I'd now like to do the same thing in Pandas.</p> <p>I have a data frame as created below: </p> <pre><code>origdate = pd.Seri...
<p>Use <code>groupby</code> + <code>pct_change</code> + <code>add(1)</code></p> <pre><code>A.assign(dbal=A.groupby('origdate').bal.pct_change().add(1)) </code></pre> <p>Or <code>groupby</code> + <code>shift</code> + <code>div</code></p> <pre><code>A.assign(dbal=A.groupby('origdate').bal.apply(lambda x: x.div(x.shift...
python|pandas
0