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 |
|---|---|---|---|---|---|---|
350,400 | 67,653,215 | Keras Model return predictions when evaluating | <p>I have a dataset with multiple fields, but only two are relevant for my machine learning implementation. The rest shall not be considered for predictions, but might unveil interesting correlations.</p>
<p>Is there a way to return prediction results when calling <code>model.evaluate</code>?
For example:</p>
<pre><cod... | <p>AFAIK, we can't get prediction on <code>x</code> using <code>model.evaluate</code>, it simply returns the <code>loss</code> and <code>acc</code>, <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#evaluate" rel="nofollow noreferrer">source</a>. But for your need, you can write a custom class and defi... | python|tensorflow|machine-learning|keras|deep-learning | 2 |
350,401 | 68,008,101 | How to combine two columns of text in pandas dataframe | <p>I have a 20 x 4000 dataframe in Python using pandas. Two of these columns are named Year and quarter. I'd like to create a variable called period that makes Year = 2000 and quarter= q2 into 2000q2.</p>
<p>Can anyone help with that?</p> | <p>If both columns are strings, you can concatenate them directly:</p>
<pre><code>df["period"] = df["Year"] + df["quarter"]
</code></pre>
<p>If one (or both) of the columns are not string typed, you should convert it (them) first,</p>
<pre><code>df["period"] = df["Year"... | python|pandas | 2 |
350,402 | 67,735,233 | Python code arrays based to index using condition? | <p>I have two python ndarrays arr1 and arr2 as follows:</p>
<pre><code> import numpy as np
arr1 = np.array([1. , 1. , 0.1862802 , 0.19957115, 0.18623812,
0.1802321 , 0.17464815, 0.16460853, 0.1487719 , 0.12968006,
0.10464501, 0.07183418, 0.00124706, 0.27353592, 0.81713212,
... | <p>A simple solution by just storing the arr1 indices that matches the a) conditions.</p>
<pre><code>
#Define the output list
arr1_index = []
#Loop on arr1,arr2
for i,(a1,a2) in enumerate(zip(arr1,arr2)):
#(a) all the values in arr1 where first value of corresponding tuple in arr2 is >0
#(b) the index of... | python|arrays|numpy | 1 |
350,403 | 67,620,438 | Tensorflow CNN only 1 output predict value | <p>I've already looked into similar topics but none of the tips helped me. My model predicts and outputs only 1 class, even in the console I see only 1 array value. I have to check if the font in the account number is fake or real. It prints an accuracy of 0.99 even 1.00 but after manually checking it with model.predic... | <p>You're using your model as if you had two output neurons in your output layer. <code>np.argmax(model.predict(images))</code> would return the index of the neuron with the maximum value, but since you only have 1, it will always return 0. Just check if the value returned by <code>predict</code> exceeds the threshhold... | python|tensorflow|conv-neural-network|artificial-intelligence | 0 |
350,404 | 67,737,291 | Logical indexing python | <p>I am working on improving the speed of logical indexing in Python. So, currently I have to plot some heatmaps, for which I am divinding the inputs data into specified number of x and y bins, and then through the function <strong>return_val</strong>, I am using logical indexing to compute the mean value in a given bi... | <p>Half the time spent by the code is in implicitly <em>allocating temporary arrays</em> (due to <code>logical_and</code> and comparison operators) and another half the time is spent in the <em>slow nested loops calling a function</em> with the slow CPython <em>interpreter</em>. One way to overcomes these issues is sim... | python|performance|numpy | 1 |
350,405 | 67,947,056 | How can i combine years and month variables on pandas dataframe in python? | <p>I have 2 integer variables in pandas dataframe. These are months and years. I want to combine them into one variable like 2021-1. Each index is matching one-to-one (No problem).New variable must be the time series. How can I do that.</p>
<p>For example my dataframe seems like this:</p>
<pre><code>import pandas as pd... | <p>There are multiple ways to do this, two examples:</p>
<pre><code>import datetime as dt
r = pd.date_range("1-jan-2018", freq="M", periods=24)
df = pd.DataFrame({"year":r.year, "month":r.month})
df.assign(ymstr=df.astype({"year":"string","month":... | python|pandas|dataframe | 0 |
350,406 | 67,694,568 | How to get RGB values from a video? | <p>I want to get the RGB values of a video and put it in a 2D array with frames (frame,rgb value) and save it in a file.
I only found a way to get it on image pixles and don't know how to save the array in a file.</p>
<pre><code>from PIL import Image
im = Image.open("D:\swim\Frames1\Frames1.png")
pix=im.load(... | <p>Things you should know:</p>
<p>Step 1 - Convert your videos into Frames</p>
<pre><code>import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame-by-frame
ret, frame = cap.read()
-------------------... | python|arrays|numpy|opencv|cv2 | 2 |
350,407 | 67,623,823 | ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list) | <pre><code>import random
import json
import pickle
import numpy as np
import nltk
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout
from tensorflow.keras.optimizers import SGD
nltk.download('punkt')
nltk.download('wordne... | <p>the code was creating the bag list incorrectly, basically, it was empty. please try the below code:</p>
<pre><code> for word in words:
#if word in word_patterns: comment out this line
bag.append(1) if word in word_patterns else bag.append(0) # and fix its identation
</code></pre>
<p>so your train ... | python|numpy|tensorflow|chatbot|valueerror | 1 |
350,408 | 67,890,605 | Adding a new column whose values are based on another column in either dataframe or excel | <p>I want to add a new column "X" whose values should be either 0 or 1 such that if there exists a value(particularly date in my case) in column "A", it should give 1 or any text <br />
example:</p>
<pre><code>A | X
----------
*date* | 1
null | 0
*date* | 1
*date* | 1
*date* | 1
null | 0
</... | <p>Here is an example in excel:</p>
<pre><code>=if(isnull(a2);0;1)
</code></pre>
<p>or</p>
<pre><code>=if(a2>0;1;0)
</code></pre>
<p>(dates are aways greater then zero.</p> | python-3.x|excel|pandas|dataframe|excel-formula | 0 |
350,409 | 67,618,764 | How to validate Pan card number from dataframe pandas | <p>i have dataframe like below and i want to valid date Pan Number Using python Function</p>
<pre><code> Name PAN
0 x BBDFW7894Q
1 s
2 A QWE7892E
</code></pre>
<p>i want a <strong>function</strong> for this , if PAN is blank/Not valid then return PAN is not present and for valid PA... | <p>You can use <code>np.where</code>:</p>
<pre><code>df['valid'] = np.where(df.PAN.str.contains(r'^[A-Z]{5}[0-9]{4}[A-Z]$', regex=True), 'Valid PAN' ,'is not valid PAN number')
</code></pre>
<p><code>OUTPUT</code>:</p>
<pre><code> Name PAN valid
0 x BBDFW7894Q Valid PAN
1 ... | python|pandas|function | 3 |
350,410 | 67,953,604 | Random Forest Feature Importance Python | <p>I am trying to get the feature importance from my data after performing hyperparameter tuning and getting the best parameters for my classifier. I have also fitted my best parameters to the training set and now I am trying to get the important features but I keep getting errors and have tried every possible solution... | <p>The part of the code where <code>train_test_split</code> is done is missing from question. The <code>train_test_split</code> returns <code>numpy</code> array and not pandas dataframe, hence <code>X_train.columns</code> will fail. Taking the <code>df.columns</code> from the pandas dataframe itself as a <code>list</co... | python|scikit-learn|data-science|random-forest|numpy-ndarray | 0 |
350,411 | 67,925,267 | find 4 in a row column or diagonal | <p>I have an array <code>N x M</code> with different chars (<code>['.','1','0']</code>) which represent a conncet-4 game board.</p>
<p>I need a FAST, way to check if there are 4 "1"s in a row, column or diagonal.
I currently iterate over the entire array and check 4 directions (<code>UP,RIGHT,RIGHT-UP,RIGHT-D... | <p>I'm new to python, so not sure about how you make use of numpy, but I'd suggest maintaining multiple views of the connect 4 board.</p>
<ul>
<li>The rows</li>
<li>The columns</li>
<li>The right down diagonals</li>
<li>The left down diagonals</li>
</ul>
<p>You'd update all 4 views when you drop a piece in. Connect 4 d... | python|pandas|numpy | 0 |
350,412 | 67,981,750 | Create a list with numpy arrays from a list that contains the directories of images in Google Colaboratory | <p>I have a list named <code>dir</code>with the directories of 18900 RGB images (3 channels) with dimensions 64x64 pixels in my drive in Google Colab. I opened the first image with the Image module from PIL library: <code>img = Image.open(dir[0])</code>. I converted the image to an array with numpy library: <code>arra... | <p>Your code is IO-bound. This is lingo for: while your code is running, it spends the majority of its time waiting for your hard-drive to send data. Unfortunately, there is no one magic line that you can write that makes your IO run fast. However, there are a two things that you can change to minimize the pain in (lo... | python|numpy|python-imaging-library|google-colaboratory | 1 |
350,413 | 67,821,588 | Is it possible to run multiple CUDA version on windows? | <p>I am doing an experiment on a chest x-ray Project. and I want multiple versions of the CUDA toolkit but the problem is that my system put the latest version which I installed lastly is appearing.
Is it possible to run any of CUDA like 9.0, 10.2, 11.0 as required to GitHub code?</p>
<p>I have done all the initial ste... | <p>You may set CUDA_PATH_V9_0, CUDA_PATH_V10_0, etc properly, then set CUDA_PATH to any one of them (e.g. CUDA_PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0).</p>
<p>Then in your VS project, set your cuda library path using the CUDA_PATH (e.g. $CUDA_PATH\lib).</p>
<p>To switch, just set the CUDA_PATH to ... | cuda|pytorch|nvidia|torchvision | 5 |
350,414 | 67,815,908 | Pandas group by and sum, but create a new row when a certain amount is exceeded | <p>I currently have a data set where im trying to group up rows based on a column and sum the columns where the values are integers.</p>
<p>However, the catch is I would like to create a new row once the sum has reached a certain threshhold</p>
<p>For example, in the below dataframe, I am trying to group the rows based... | <p>I think here are necessary loops, so for improve performance is use <code>numba</code>, modified <a href="https://stackoverflow.com/a/56905635/2901002">solution from Divakar</a>, called function per groups by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.tra... | python|pandas|pandas-groupby | 4 |
350,415 | 67,728,287 | How to save results from an API call that uses a pandas column for the requests before the whole thing times out when using apply? | <p>I have a pandas dataframe with strings that I'm using to query an API and return the results.</p>
<p>I'm trying to call the API using a function and <code>.apply</code> and then save the results from the api call into a csv file. The problem is that I'm trying to do 10000+ requests and my kernel/notebook crashes. Ba... | <p>If it's a memory issue, what I'd do is write the API calling function as a generator with the <code>yield</code> statement. Then, you can loop through the <code>api_fetch_function</code> generator and save smaller data frames for the csv files rather than holding everything in memory in one go.</p>
<pre class="lang-... | python|pandas|dataframe|python-requests | 0 |
350,416 | 67,888,841 | Generating columns names with pandas assign | <p>I have a data frame with ten columns and one mean column and I would like to do something like this:</p>
<pre><code>monthly_volume:
Month 1984 1985 1986 Mean
1 10 5 4 6.33
2 9 5 8 7.33
3 4 8 1 4.33
4 5 8 1 4.67
5 3 6 3 3.33
.. .. .. .. ....
f... | <pre><code>for year in range(1, 4):
kwards = {'difference': monthly_volume[monthly_volume.columns[-year+1]] - monthly_volume['MEAN']}
monthly_volume = monthly_volume.assign(**kwards)
</code></pre> | python|pandas | 1 |
350,417 | 67,671,179 | Why I can't use groupby? Where is the problem? | <p>I have a large dataframe and I would like to use groupby function but I got the error:</p>
<pre><code>TypeError: sequence item 0: expected str instance, list found
</code></pre>
<p>Data:</p>
<pre><code>lokalnyid object
powiat int64
status_bdo object
kategoria_ object
funkcja_og ob... | <p>You can <code>.apply</code> in <code>groupby</code> like this</p>
<pre><code>df.groupby(['lokalnyid', 'powiat', 'status_bdo', 'kategoria_', 'funkcja_og', 'funkcja_sz', 'zabytek', 'geometry', 'liczba_kon'])['1_5000_pi025'].apply(list)
</code></pre> | python|pandas | 0 |
350,418 | 67,862,787 | Dividing the dataset in training and testing data with lables | <p>I am trying to divide the dataset to training and testing set, in below code, <code>df_min_max_scaled</code> is my normalized data, <code>df</code> is my unnormalized data, but I am getting error</p>
<pre><code>import numpy as np
train_ind = df.sample(frac=0.65, replace=True)
train = df_min_max_scaled[train_ind,]
te... | <p>I would recommend you to use <code>train_test_split</code> from sklearn. This could contain following steps:</p>
<ol>
<li>Load your data (e.g. <code>df = pd.read_csv(...)</code> if your data comes from CSV files)</li>
<li>Split them using train test split (<code>from sklearn.model_selection import train_test_split</... | python|r|python-3.x|pandas|numpy | 1 |
350,419 | 67,622,214 | How to find overlaps between subsets of a pandas dataframe | <p>I have a large dataframe. Column A has website names, and Column B has all the IDs that visit that website. So - if a website has 100,000 visitors, there will be 100,000 rows for Website A, etc.</p>
<p>I want to get the overlap between all pairs of these websites - so, to understand how many people visit A&B, A&... | <p>To get the total number of visitors to each website you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>df.groupby("project_name").size()
# proje... | python|pandas|merge | 1 |
350,420 | 67,953,527 | pandas.interpolate doesn't give wanted result | <p>i'm trying to fill the empty y field in my dataset[from 12 to 16]
, here is the original data vizualisation <br />
<a href="https://i.stack.imgur.com/oP7xA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oP7xA.png" alt="enter image description here" /></a></p>
<p>I have NaN values at the end, here... | <p>Based on the <a href="https://stackoverflow.com/questions/22491628/extrapolate-values-in-pandas-dataframe">this answer</a>, when you want to extrapolate data which is infer how the data behaves outside of the scope of interpolation, you need to rely on some more powerful <a href="https://docs.scipy.org/doc/scipy/ref... | python|pandas|data-science|interpolation | 0 |
350,421 | 31,873,014 | Modifying values with conditions | <p>I am facing a problem quite similar to the one explained in the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow">documentation</a>. This code works but raises a warning:</p>
<pre><code>In [296]: dfb = DataFrame({'a' : ['one', 'one', 'two',
.....: ... | <p>Use <code>loc</code>, place the boolean condition within the square brackets <code>[]</code> and the column of interest after the comma so you are not performing <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow">chained indexing</a>:</p>
<pre><code>In [40]:... | python|pandas | 1 |
350,422 | 31,683,098 | numpy array from csv file for lasagne | <p>I started learning how to use theano with lasagne, and started with the mnist example. Now, I want to try my own example: I have a train.csv file, in which every row starts with 0 or 1 which represents the correct answer, followed by 773 0s and 1s which represent the input. I didn't understand how can I turn this fi... | <p>You can use <code>numpy.genfromtxt()</code> or <code>numpy.loadtxt()</code> as follows:</p>
<pre><code>from sklearn.cross_validation import KFold
Xy = numpy.genfromtxt('yourfile.csv', delimiter=",")
# the next section provides the required
# training-validation set splitting but
# you can do it manually too, if ... | python|numpy|theano|lasagne | 2 |
350,423 | 31,969,633 | Transform an array of count data into a matrix of ones and zeroes | <p>I have an array <code>n</code> of count data, and I want to transform it into a matrix <code>x</code> in which each row contains a number of ones equal to the corresponding count number, padded by zeroes, e.g:</p>
<pre><code>n = [0 1 3 0 1]
x = [[ 0. 0. 0.]
[ 1. 0. 0.]
[ 1. 1. 1.]
[ 0. 0. 0.... | <p>Here's one way to vectorize it:</p>
<pre><code>>>> n = np.array([0,2,1,0,3])
>>> width = 4
>>> (np.arange(width) < n[:,None]).astype(int)
array([[0, 0, 0, 0],
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 0],
[1, 1, 1, 0]])
</code></pre>
<p>where if you liked, <cod... | python|numpy | 3 |
350,424 | 32,050,030 | Rotation of colorbar tick labels in matplotlib | <p>I would like to rotate the colorbar tick labels so that they read vertically rather than horizontally. I have tried as many variations as I can think of with <code>cbar.ax.set_xticklabels</code> and <code>cbar.ax.ticklabel_format</code> and so on with <code>rotation='vertical'</code> but haven't quite landed it yet.... | <p>If you're happy with tick locations and labels and only want to rotate them: </p>
<pre><code>cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(), rotation='vertical')
</code></pre> | python|numpy|matplotlib|colorbar | 9 |
350,425 | 31,872,659 | Python & Pandas: How to do conditional calculation | <p><code>df['direction']</code> is the number of direction of the wind, ranging from 1-16. I want to convert it into <code>360-degree system</code>.
<code>#1</code> direction is <code>90</code>, and <code>#2</code> is <code>67.5</code>, they run in clockwise.</p>
<p>I can do<code>df['degree'] = 90-(df.direction-1)*22... | <p><code>df['degree'] = df['degree'].apply(lambda x: x + 360 if x < 0 else x)</code></p> | python|pandas | 6 |
350,426 | 31,714,517 | Why does adding a column to a Pandas DataFrame return a SettingWithCopy warning when the column is a boolean test of an existing column? | <p>I couldn't find an answer to this in the existing <code>SettingWithCopy</code> warning questions, because the common <code>.loc</code> solution doesn't seem to apply. I'm loading a table into pandas then trying to create some mask columns based on values in the other columns. For some reason, this returns a <code>Se... | <p>I guess <code>invs</code> causes the warning. To resolve that, copy it explicitly like this:</p>
<pre><code>invs = all_invs[all_invs['uniqueIDs'].str.contains('p1')].copy()
</code></pre> | python|pandas | 1 |
350,427 | 31,950,331 | How can I calculate cumulative percentage change from beginning period | <p>I am trying to create a <code>DataFrame</code> with a rolling cumulative percentage change. I would like to show the percentage change of the stock from the initial buy date (2014-09-05).</p>
<pre><code>import pandas as pd
import pandas.io.data as web
cvs = web.get_data_yahoo('cvs', '2014-09-05')['Adj Close']
cvs... | <p>Thank you @EdChum </p>
<p>What I was looking for was...</p>
<pre><code>PriceChange = cvs.diff().cumsum()
PercentageChange = PriceChange / cvs.iloc[0]
</code></pre> | python|pandas|dataframe | 6 |
350,428 | 31,978,154 | How to define values for RegularGridInterpolator | <p>I have n equal length arrays whose transpose corresponds to the coordinates in an n dimensional parameter space:</p>
<pre><code>x = np.array([800,800,800,800,900,900,900,900,900,1000,1000,1000,1000,1000])
y = np.array([4.5,5.0,4.5,5.0,4.5,5.0,5.5,5.0,5.5,4.5,5.0,5.5,5.0,5.5])
z = np.array([2,2,4,4,2,2,4,4,4,2,2,4,4... | <p>Your input would fit better with <code>LinearNDInterpolator</code> or <code>NearestNDInterpolator</code>:</p>
<pre><code>from scipy.interpolate import LinearNDInterpolator
ex = LinearNDInterpolator((x, y, z), v)
ex((800, 4.5, 2))
#array(1.0)
ex([[800, 4.5, 2], [800, 4.5, 3]])
#array([ 1., 2.])
</code></pre>
<p>... | python|arrays|numpy|scipy|interpolation | 3 |
350,429 | 31,756,894 | Trouble displaying a graph of a Lissajous curve | <p>wrote a program to graph Lissajous curves but for whatever reason when the graph is shown it's blank. Is there something I missed? </p>
<pre><code>#this program given a set of parameters calculates and graphs Lissajous Curves
from numpy import *
from matplotlib.pyplot import *
from math import *
t=arange(0,4*pi/2... | <p>To make this a <a href="https://en.wikipedia.org/wiki/Lissajous_curve" rel="nofollow noreferrer">Lissajou</a> we have to plot X vs Y and not t. Using the hints from the comments that leads to</p>
<pre class="lang-py prettyprint-override"><code>#this program given a set of parameters calculates and graphs Lissajous ... | python|numpy|matplotlib | 0 |
350,430 | 31,974,828 | Convert UTC to local time | <p>I have a fairly large dataset that has UTC timestamps. I need to convert the UTC to local (central) timezone..I tried my google-fu, to no avail.</p>
<p>Dataframe is below. </p>
<pre><code>STID UTCTIME TRES VRIR RETY REWT WEDN DELP WDIR DERT RTAX GAIN DEVD
0 ARFW 2012-01-01T00:00 28.47 65 -999 -999 4... | <p>In your code in the <code>strptime</code> line you do not use the actual date string from your dataframe, but the literal string "UTCTIME".</p>
<pre><code>from_zone = tz.gettz('UTCTIME')
to_zone = tz.tzlocal()
utc = datetime.strptime('UTCTIME', '%Y-%m-%dT%H:%M') # <====== STRING
utc = utc.replace(tzinfo = from_... | python-2.7|pandas | 0 |
350,431 | 31,887,686 | Python on my Mac is a mess, help me uninstall what I don't need | <p>I'm unable to import numpy in Python 2.7 in the shell. I installed Python with <code>brew install</code>, then numpy with <code>sudo pip install</code>. I tried without <code>sudo</code> but I get a permission denied error. Anyway, I get this:</p>
<pre><code>ImportError: dlopen(/usr/local/Cellar/python/2.7.10_2/Fra... | <p>As for workaround, try downgrading your Python to 2.7.9 like:</p>
<pre><code>brew switch python 2.7.9
</code></pre>
<p>by overriding the existing one, as it seems there is some particular problem with 2.7.10. Then re-link it again (if required).</p>
<p>Also make sure your <code>PYTHONPATH</code> is correct (you d... | python|macos|numpy | 1 |
350,432 | 31,777,056 | Python3 MatPlotLib : How can I get Multiple Line Plots | <p>I have a list of Tuples like this :</p>
<pre><code>list_months = [ ('A', 'January'),
('A', 'January'),
('A', 'January'), # Total 10 instances of ('A', 'January')
('A', 'March'),
('A', 'March'),
('A', 'March'),
('A', 'Fe... | <p>It will be easier to plot if you leave the data in a DataFrame. I made a sample DataFrame using the example data from your post:</p>
<pre><code>list_months = [ ('A', 'January'),
('A', 'January'),
('A', 'January'), # Total 10 instances of ('A', 'January')
('A', 'March... | python|pandas|matplotlib|graph|plot | 3 |
350,433 | 31,703,327 | (matpolotlib) ValueError: too many values to unpack | <p>I am getting the following error when trying to display data values instead of markers:</p>
<p><strong>Complete Traceback:</strong></p>
<pre><code>Traceback (most recent call last):
File "plotpoints.py", line 45, in <module>
plt.annotate(grid_x,grid_y)
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py"... | <p>I don't think you are calling <code>annotate</code> correctly</p>
<pre><code>plt.annotate(grid_x,grid_y)
</code></pre>
<p>That looks like 2 arrays or lists of points (I haven't fully deduced how you define those 2 variables).</p>
<p>But the documentation is:</p>
<pre><code>ax.annotate('local max', xy=(3, 1), ..... | python|unix|numpy|matplotlib|scipy | 1 |
350,434 | 32,079,489 | Using NumPy Vectorization to Create Column Containing Length of Another Column | <p>I think I have a pretty straightforward question here. Essentially I have a table with one column where each row contains a set of values that had previously been converted from a JSON string. </p>
<p>For example, here is one cell value for the column "options":</p>
<pre><code>[u'Tide Liquid with a Touch of Downy ... | <p>As mentioned in the comments above, there's not really any way to vectorize operations on arrays that contain arbitrary Python objects.</p>
<p>I don't think you can do much better than using a simple <code>for</code> loop or list comprehension, e.g.:</p>
<pre><code>df['num_choices'] = np.array([len(row) for row in... | python|numpy|pandas | 0 |
350,435 | 31,788,019 | Python optimizing arithmetic | <p>I have fragment of code in python which take to long time with long arrays:</p>
<pre><code>n =30000
t = range(1,n)
s = sum(t)
for i in t:
for j in t[i:]:
if ts-j == i*j:
//some simple code
</code></pre>
<p>Is there any way to optimize it? I have checked that both diff and multiply took to much time. I'... | <p>As you don't specify what <code>ts</code> is, we must assume that it is an integer constant.</p>
<p>The condition of the inner loop is <code>ts - j == i * j</code>, which is possible only when <code>i + 1</code>and <code>j</code> divide <code>ts</code>.</p>
<p>So you should factor <code>ts</code> and generate all ... | python|math|numpy|optimization | 1 |
350,436 | 41,513,252 | One-hot representation of a matrix in numpy | <p>What is the easiest/smartest way of going from a matrix of values to one hot representation of the same thing in 3d tensor? For example if the matrix is the index after argmax in a tensor like:</p>
<pre><code>indices=numpy.argmax(mytensor,axis=2)
</code></pre>
<p>Where tensor is 3D [x,y,z] and indices will natural... | <p>One of the perfect setups to use <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> -</p>
<pre><code>indices[...,None] == np.arange(mytensor.shape[-1])
</code></pre>
<p>If you need in ints of <code>0s</code> and <code>1s</code>, append w... | python|numpy|argmax | 3 |
350,437 | 41,575,442 | TensorFlow export compute graph to XML, JSON, etc | <p>I want to export a TensorFlow compute graph to XML or something similar so I can modify it with an external program and then re-import it. I found <a href="https://www.tensorflow.org/versions/master/how_tos/meta_graph/" rel="nofollow noreferrer">Meta Graph</a> but this exports in a binary format which I wouldn't kno... | <p>The native serialization format for TensorFlow's dataflow graph uses <a href="https://developers.google.com/protocol-buffers/" rel="noreferrer">protocol buffers</a>, which have bindings in many different languages. You can generate code that should be able to parse the binary data from the two message schemas: <a hr... | json|xml|tensorflow|export | 8 |
350,438 | 41,497,982 | Tensorflow model works in Python but not in C++ | <p>For a little background, my main goal is to use Tensorflow's C++ API to classify an image and time it on different systems.</p>
<p>I have used <a href="https://github.com/ry/tensorflow-vgg16" rel="nofollow noreferrer" title="Ry's model converter">Ry's model converter</a> to convert his Caffe model to Tensorflow... | <p>For anyone looking at this in the future, this problem was caused by using the wrong input layer name.</p> | python|c++|tensorflow | 1 |
350,439 | 41,309,467 | Matplotlib: Plot multiple lines per time series subplot | <p>Using subplots, is there a pythonic way to plot multiple lines per subplot? I have a pandas dataframe with two row indices, datestring and fruit, with store for columns and quantity for values. I want 5 subplots, one for each store, with datestring as the x-axis and quantity as the y axis, with each fruit as its own... | <p><strong><em>setup</em></strong><br>
always provide sample data that reproduces your problem.<br>
I've provided some here</p>
<pre><code>cols = pd.Index(['TJ', 'WH', 'SAFE', 'Walmart', 'Generic'], name='Store')
dates = ['2015-10-23', '2015-10-24']
fruit = ['carrots', 'pears', 'mangos', 'banannas',
'melons',... | python|pandas|matplotlib|plot|plotly | 6 |
350,440 | 41,450,963 | Using Pandas to Find Minimum Values of Grouped Rows | <p>This might be a trivial question but I'm still trying to figure out pandas/numpy.</p>
<p>So, suppose I have a table with the following structure:</p>
<pre><code>group_id | col1 | col2 | col3 | "A" | "B"
x | 1 | 2 | 3 | NaN | 1
x | 3 | 2 | 3 | 1 | 1
x | 4 |... | <p>To get the minimum of column A for each group use <code>transform</code></p>
<pre><code>df.groupby('group_id')['A'].transform('min')
</code></pre> | python|pandas|numpy|dataframe | 14 |
350,441 | 41,329,217 | extracting header data from text file using Pandas | <p>I previously asked a question of how to enter this .txt file using pandas.
I was trying with pandas.read_csv</p>
<p>What I found is that I can not read this file using read_csv unless I remove the header data (down to the "#").</p>
<p>The problem is, I need to extract data like, Well Name, Well KB, Well Type... fr... | <p>You can parse the file with the comment indicator as the delimiter and then use pandas <code>str.extract</code></p>
<pre><code>from io import StringIO
import pandas as pd
txt = """# WELL TRACE FROM PETREL
# WELL NAME: ZZ-0113
# WELL HEAD X-COORDINATE: 9999999.00000000 (m)
# WELL HEAD Y-COORDINATE: 99... | python|pandas | 1 |
350,442 | 41,370,937 | Calculating percentiles in pandas | <p>new to python and am learning as I go along. I mainly work from pandas dataframes.</p>
<p>I have a consumer survey and I want to break it into groups based on income percentile. So bottom 10th, 10th-20th etc. And I'd want to create a seperate column describing which %ile each agent lies in. </p>
<p>Any help apprec... | <pre><code>from string import ascii_letters
import pandas as pd
import numpy as np
df = pd.DataFrame(dict(
Agent=pd.DataFrame(np.random.choice(list(ascii_letters), (100, 5))).sum(1),
Salary=np.random.randint(50000, 150000, (100))
))
df['Salary Decile'] = pd.qcut(df.Salary, 10, labels=list(map(... | pandas | 1 |
350,443 | 41,486,565 | How do I add a dynamic number of white spaces to the beginning of each row of a pandas dataframe? | <p>How would I pad each row of the df to the left with enough spaces to ensure the row totals 30 characters?</p>
<p>I tried going down this path, but it didn't work and I believe <code>ljust</code> is deprecated:</p>
<pre><code>'{: <30}'.format(df['test1'])
</code></pre>
<p>Currently:</p>
<pre><code>>>>... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.rjust.html" rel="nofollow noreferrer"><code>str.rjust</code></a>:</p>
<pre><code>print (df.test1.str.rjust(30, ' '))
0 1234jjjjjjjdddd
1 1234jjjjjjjdd
2 1234jjjjjjj... | python|pandas|dataframe | 4 |
350,444 | 41,504,375 | Numpy Matrix to tkinter Canvas | <p><strong>How to display a Numpy matrix, as a bitmap, into a Tkinter canvas?</strong>
More precisely, how to fill a <code>PhotoImage</code> with content from a matrix?</p>
<pre><code>photo = ImageTk.PhotoImage(...)
self.canvas.create_image(0,0,image=photo,anchor=Tkinter.NW)
</code></pre> | <p><a href="http://www.swharden.com/wp/2010-06-24-fast-tk-pixelmap-generation-from-2d-numpy-arrays-in-python/" rel="nofollow noreferrer">Here</a> is working solution, slightly modified to make it work (some function was deprecated) and to simplify it to keep only the necessary part. We have to use <code>Image.frombytes... | python|numpy|canvas|tkinter|tkinter-canvas | 2 |
350,445 | 41,449,084 | shapely's scale function in geopandas returns points of similar magnitude | <p>I have a .shp file that I read into a geopandas dataframe. I change the coordinate reference system to 2163 since I'm making some rectangular maps and want them to look somewhat normal. </p>
<pre><code>geo_df = geo.GeoDataFrame.from_file('path to shp files here')
geo_df = geo_df.to_crs(epsg=2163)
</code></pre>
<p>... | <p>The scaling is defined relative to a center point. The scaling you applied actually did make the polygons smaller, but kept the center point at the center of the bounding box of the polygon. The <code>origin</code> keyword argument in <code>shapely.affinity.scale</code> defaults to the polygon center; to reduce the ... | python|gis|scale|shapely|geopandas | 5 |
350,446 | 41,565,101 | Merge DataFrames based on conditioning datetime64 | <p>I am trying to merge 2 Dfs under curtain conditioning on dates.</p>
<p>df 1:
<a href="https://i.stack.imgur.com/6Taor.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6Taor.png" alt="enter image description here"></a></p>
<p>df2:
<a href="https://i.stack.imgur.com/PrFA9.png" rel="nofollow norefer... | <p>I think you need convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>to_timedelta</code></a> int value or use <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects" rel="nofollow noreferrer">offsets</a>:</p... | python|pandas|filter|merge|date-arithmetic | 1 |
350,447 | 41,617,584 | ValueError: Couldn't broadcast input array from shape (51) to (51,1) | <p>I am getting the above value error for the following code:</p>
<pre><code>np.random.seed(0);
num_samples=1000; len_time=50; dim_data=1;
#The times series X_{1:T} is uniform in the grid [0,1]^2;
#X_train is a collection of such time series
X_train=np.random.uniform(0,1,(num_samples,len_time+1,dim_data));
... | <p>To do broadcasting the dimensions need to be compatible, and you're assigning a 1D array to a 2D array. If <code>dim_data</code> is always 1 you can get rid of it, or do <code>Y_train=squeeze(np.zeros_like(X_train));</code> to make <code>Y_train</code> 2D, so <code>Y_train[k]</code> is 1D. Alternatively you can add ... | python|numpy | 1 |
350,448 | 41,276,401 | Pandas/NumPy: concisely label first N values matching a mask | <p>I have a sorted Series like this:</p>
<pre><code>[2, 4, 5, 6, 8, 9]
</code></pre>
<p>I want to produce another Series or ndarray of the same length, where the first two odd numbers and the first two even numbers are labeled sequentially:</p>
<pre><code>[0, 1, 2, _, _, 3]
</code></pre>
<p>The <code>_</code> value... | <p>Great Problem! I'm still exploring and learning.</p>
<p>I've basically stuck with what you've done so far with modest tweaks for efficiency. I'll update if I think of anything else cool.</p>
<p><strong><em>conclusions</em></strong><br>
So far, I've thrashed around alot and haven't improved much.</p>
<p><strong>... | pandas|numpy | 1 |
350,449 | 41,446,192 | Python Pandas Calculating Percentile per row | <p>I have the following code and would like to create a new column per Transaction Number and Description that represents the 99th percentile of each row.</p>
<p>I am really struggling to achieve this - it seems that most posts cover calculating the percentile on the column. </p>
<p>Is there a way to achieve this? I ... | <p>The following should work:</p>
<p><code>df['99th_percentile'] = df[cols].apply(lambda x: numpy.percentile(x, 99), axis=1)</code></p>
<p>I'm assuming here that the variable 'cols' contains a list of the columns you want to include in the percentile (You obviously can't use the Description in your calculation, for e... | python|pandas|dataframe|percentile | 3 |
350,450 | 41,376,510 | How to make zero by zero devision result in zero in Python pandas? | <p>I want to divide one dataframe by another in Pandas to eventually represent a percentage change. Both dataframes values contain NaN and 0. Now, when I divide one dataframe by the other, the result where the value from both dataframes was zero is NaN. I know why 0/0 is set to np.nan, but from a percentage change pers... | <p>Here's an approach with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>dataframe.where method</code></a> -</p>
<pre><code>mask = (data_with_zeros[['a','b']].values == [0,0]).all(1)
data_with_zeros['a'].div(data_with_zeros['b'], fill_value=... | python|pandas|numpy | 2 |
350,451 | 41,229,174 | Python Pandas: Count quarterly occurrence from start and end date range | <p>I have a dataframe of jobs for different people with star and end time for each job. I'd like to count, every four months, how many jobs each person is responsible for. I figured out away to do it but I'm sure it's tremendously inefficient (I'm new to pandas). It takes quite a while to compute when I run the code on... | <p>This answer assumes that each job-person combination is unique. It creates a series for every row with the value equal to the job an index that expands the dates. Then it resamples every 4th month (which is not quarterly but what your solution describes) and counts the unique non-na occurrences.</p>
<pre><code>def ... | python|pandas | 0 |
350,452 | 41,545,036 | based on a value in column A, shift the values in columns C and D to the right in a pandas dataframe | <p>How can i achieve the desired result based on the following dataset ?</p>
<pre><code> A B C D E
1 apple 5 2 20 NaN
2 orange 2 6 30 NaN
3 apple 6 1 40 NaN
4 apple 10 3 50 NaN
5 banana 8 9 60 NaN
</... | <p>IIUC you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html" rel="nofollow noreferrer"><code>np.roll</code></a> on the rows of interest, here we need to select only the rows where 'A' is 'apple' and then <code>roll</code> these by a single column row-wise and assign back:</p>
<pre... | pandas|dataframe | 0 |
350,453 | 41,367,191 | Even distribution of percentile labels on x axis | <p>Forgive my terminology, I'm not an expert at statistics or plotting! </p>
<p>Using Pandas, I am attempting to plot quantile data that is bucketed up to "5 9s". That is, for a given DataFrame 'df' that has a series 'foo' of unevenly distributed integer values:</p>
<pre><code>q = df['foo'].quantile([.1, .2, .3, .4, ... | <p>I'd use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html" rel="nofollow noreferrer"><code>pd.qcut</code></a></p>
<p><strong><em>example</em></strong> </p>
<pre><code>import pandas as pd
import numpy as np
a = np.sort(np.random.rand(1000))
b = a.repeat(np.arange(len(a)))
b += np.ran... | python|pandas|matplotlib|plot|quantile | 0 |
350,454 | 41,403,146 | Tensorflow can't save model | <p>I encountered this weird problem...I use this code to construct tensorflow saver: </p>
<pre><code>tf.train.Saver(tf.all_variables(), max_to_keep=FLAGS.keep)
</code></pre>
<p>which is supposed to be very standard. However, when I point the saving directory to my custom directory (under my username) instead of "/tmp... | <p><strong>TL;DR:</strong> In the new checkpoint format, the "filename" that you pass to the saver is actually used as the prefix of several filenames, and no file with that exact name is written. You can use the old checkpoint format by constructing your <a href="https://www.tensorflow.org/api_docs/python/state_ops/sa... | tensorflow | 4 |
350,455 | 41,609,649 | custom JSON format output from pandas dataframe | <p>I have a Pandas DataFrame like below: </p>
<pre><code>ID | Category | Description | Score
-----------------------------------
1 | 1 | Desc 1 | 20.0
2 | 1 | Desc 2 | 30.0
3 | 1 | Desc 3 | 30.0
4 | 2 | Desc 4 | 50.0
5 | 2 | Desc 5 | 50.0
6 | 3 ... | <p>thanks @IanS<br>
I took idea from your code and I used the below snippet to get my output: </p>
<pre><code>cList = []
groupDict = outputDF.groupby('Category').apply(lambda g: g.drop('Category', axis=1).to_dict(orient='records')).to_dict()
for key, value in groupDict.items():
cList.append(dict(name=str(key)), c... | json|python-3.x|pandas | 3 |
350,456 | 41,360,265 | How to do a FIFO push-operation for rows on Pandas dataframe in Python? | <p>I need to maintain a Pandas dataframe with 500 rows, and as the next row becomes available I want to push that new row in and throw out the oldest row from the dataframe. e.g. Let's say I maintain row 0 as newest, and row 500 as oldest. When I get a new data, I would push data to row 0, and it will shift row 0 to ro... | <p>@JohnGalt posted an answer to this on the comments. Thanks a lot. I just wanted to put the answer here just in case if people are looking for similar information in the future.</p>
<p><code>df.shift(1) df.loc[0] = new_row</code></p>
<p><code>df.shift(n)</code> will shift the rows <code>n</code> times, filling the fi... | python|pandas | 5 |
350,457 | 41,368,492 | how would you take the white pixels generated by a mask and put them into a list | <p>I have a picture of a street, (the street has small variations of color) and with some help I was able to crop part of the street for a sample of the color I then took the color and calculated the mean and stdv and created the lower and upper boundry for a mask.
I took the mask output and ran <code>closing = cv2.mo... | <p>In order to get the lists you asked, you can do it like:</p>
<pre><code>coords, colors = [], []
for y in range(closing.shape[0]):
for x in range(closing.shape[1]):
if np.all(closing[y, x] > 0):
coords.append((y, x))
colors.append(original[y, x])
</code></pre>
<p>Thus you get ... | python|opencv|numpy | 1 |
350,458 | 41,456,163 | List returned from Series.axes doesn't look like a normal list | <p>From the pandas documentation, i get <code>Series.axes</code> will return a list, and indeed it is a list</p>
<pre><code>$ python3 process_data.py
<class 'list'>
</code></pre>
<p>However, when I attempted to print the string representation of the list, I get this</p>
<p>To run print directly </p>
<pre><co... | <p>When you use <code>iterrows()</code>, every row is a pandas Series, the <code>axes</code> attribute returns a list of labels/or index. So what is contained in the list are index objects, check this simple example:</p>
<pre><code>s = pd.Series([1,2,3])
s.axes
# [RangeIndex(start=0, stop=3, step=1)]
</code></pre>
<p... | python|list|pandas|numpy | 2 |
350,459 | 41,502,529 | How do you rotate elements in a 2D numpy array by 'n' units? | <pre><code>x = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
</code></pre>
<p>Rotation by 1 unit should give:</p>
<pre><code>x = [[4, 1, 2],
[7, 5, 3],
[8, 9, 6]]
</code></pre>
<p>Basically, I want to shift each circular layer in the array by 'n' units.</p>
<p>I looked at numpy.roll but couldn't figure out ... | <p>Here's an approach assuming you are looking to rotate such that the amount of shift is constant across slices, where by slice we mean the outermost layer of elements directed outwards from the center -</p>
<pre><code>def outer_slice(x):
return np.r_[x[0],x[1:-1,-1],x[-1,:0:-1],x[-1:0:-1,0]]
def rotate_steps(x,... | python|arrays|numpy | 3 |
350,460 | 27,579,328 | python pandas timeseries: assign value to time (currently omitted from index) | <p>I'd like to assign a value to a time in a time series that currently doesn't exist in the index, inserting it in the correct position. ie 2014-01-02 for the following:</p>
<pre><code>import pandas as pd
from numpy.random import randn as randn
rng = pd.date_range('1/3/2014', periods=6, freq='D')
ts = pd.Series(randn... | <p>Sometimes you may not want the index to be sorted. So Pandas does not do this automatically. If you do want to sort the index, call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a>:</p>
<pre><code>ts['2014-01-02'] = 1
ts = t... | python|pandas | 1 |
350,461 | 27,513,596 | access scipy matrix in dense format | <p>I was building graph using networks as follows:</p>
<pre><code>>>> import networkx as nx
>>>
>>> G = nx.DiGraph()
>>> G.add_edge(1, 2, weight = 1.0)
>>> G.add_edge(1, 4, weight = 2.0)
>>> G.add_edge(2, 3, weight = 3.0)
>>> G.add_edge(2, 4, weight = 4.0)... | <p>This should work:</p>
<pre><code>S.todense()[0, 0]
</code></pre>
<p><code>todense()</code> returns <code>np.matrix</code>, you also could use <code>.A</code> to return an<code>np.array</code>. In this case:</p>
<pre><code>S.A[0][0]
</code></pre>
<p>Would work, but </p>
<pre><code>S.A[0,0]
</code></pre>
<p>is s... | python|numpy|matrix|scipy|networkx | 2 |
350,462 | 27,535,246 | Pandas - plot events with unequal interval | <p>I have a list of datetime objects representing events log:</p>
<pre><code> [datetime.datetime(2014, 12, 16, 0, 18, 12),
datetime.datetime(2014, 12, 16, 0, 18, 27),
datetime.datetime(2014, 12, 16, 0, 18, 27),
datetime.datetime(2014, 12, 16, 0, 19, 9),
datetime.datetime(2014, 12, 16, 0, 19, 39),
datetime.da... | <p>You may want to use 'value_counts' to count the number the instances of a particular time event and then resample the dataframe to fill na, like so, </p>
<pre><code>import pandas as pd
import datetime
events = [datetime.datetime(2014, 12, 16, 0, 18, 12),
datetime.datetime(2014, 12, 16, 0, 18, 27),
datetime.dat... | python|matplotlib|pandas|ipython-notebook | 7 |
350,463 | 27,444,261 | convert list of strings to numpy list of lists | <p>I'm reading data (numbers) from a file into a list, as follows:</p>
<pre><code> weight_file = open(model_name, 'r').readlines()
weights = weight_file[6:]
</code></pre>
<p>It seems that I can't read them straight into a <code>numpy.array</code> because the first rows of the file contains words.</p>
<p>So no... | <p>If <code>weights_np</code> is this:</p>
<pre><code>In [23]: weights_np = np.array([1, 2, 3, 4, 5, 6])
</code></pre>
<p>then you could use <code>reshape</code> to make it 2-dimensional with 3 columns:</p>
<pre><code>In [24]: weights_np = weights_np.reshape((-1, 3))
In [25]: weights_np
Out[25]:
array([[1, 2, 3],
... | python|list|numpy | 2 |
350,464 | 27,770,906 | Why are lil_matrix and dok_matrix so slow compared to common dict of dicts? | <p>I want to iteratively build sparse matrices, and noticed that there are two suitable options for this according to the SciPy documentation:</p>
<p><a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.lil_matrix.html#scipy.sparse.lil_matrix" rel="noreferrer">LiL matrix</a>:</p>
<blockquo... | <p>When I change your <code>+=</code> to just <code>=</code> for your 2 sparse arrays:</p>
<pre><code>for row, col in zip(rows, cols):
#freqs[row,col] += 1
freqs[row,col] = 1
</code></pre>
<p>their respective times are cut in half. What's consuming the most time is the indexing. With <code>+=</code> it is h... | python|numpy|scipy | 14 |
350,465 | 27,576,099 | Pandas convert_object(convert_numeric=True) not producing np.nan for full series of non-numeric values | <p>Tried on Pandas v0.12 from ActiveState (Python 2.7.2) and Pandas v0.14 from Anaconda (Python 2.7.8).</p>
<p>When a DataFrame's column is full of values that can't be converted to numeric values, none of the column values are converted to NAN. When 1 or more values can be converted to numeric values, all of the non... | <p>Set 'nan' where value is not a number</p>
<pre><code>>>> import pandas as pd
>>> df1 = pd.DataFrame({"c1":["1","2","3"], "c2":["a","b","c"]})
>>> df2 = pd.DataFrame({"c1":["1","2","3"], "c2":["a","b","4"]})
>>> M = lambda x: x.isdigit()==True
>>> df1[~df1.applymap(M)]... | python|pandas | 1 |
350,466 | 27,779,373 | Calculation and construction of two dimensional array with nested loop | <p>I am trying to do a calculation with Python. I want to yield a 20*20 array with a nested loop. I do not know if I am in the right direction, but here is my code:</p>
<pre><code>w = 1.5
m = 0.556
E = np.linspace(15.4, 4.0, num=20)
u = np.linspace(0.29, 0.79, num=20)
Q = 0
for j in E:
for i in u:
Q = E *... | <p>It seems that you want <code>Q</code> to be your final 20x20 array. One key point with Numpy is that you should avoid <code>for</code> loops whenever possible as they are much slower than vectorised array operations. There are faster ways to build the 2D array from <code>E</code> and <code>u</code>.</p>
<p>The main... | python|arrays|numpy | 5 |
350,467 | 27,855,953 | How to make np.loadtxt return multidimensional arrays even the file has only one dimensional? | <p>I need to get the last four column data of a <code>ndarray</code>, most of time code <code>arr[:, -4:]</code> is ok, but if the array just has one dimension, this will throw <code>IndexError: too many indices</code>.</p>
<p>My data is get with <code>arr = np.loadtxt('test.txt')</code>, so if <code>test.txt</code> h... | <p>Just found it <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow">here</a>.</p>
<p>You can ask it to have at least 2 dimensions with:</p>
<pre><code>arr = np.loadtxt('test.txt', ndmin=2)
</code></pre> | python|arrays|numpy|multidimensional-array | 4 |
350,468 | 27,891,020 | sckit-learn fit() leads to error after normalising the data | <p>I have been trying this:</p>
<ol>
<li>Create X features and y dependent from a dataset</li>
<li>Split the dataset</li>
<li>Normalise the data</li>
<li>Train using SVR from Scikit-learn</li>
</ol>
<p>Here is the code using a pandas dataframe filled with random values</p>
<pre><code>import pandas as pd
import numpy... | <p>The error here is in the df you pass as your labels: <code>y_trainN</code></p>
<p>if you compare against the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html" rel="noreferrer">sample docs</a> version and your code: </p>
<pre><code>In [40]:
n_samples, n_features = 10, 5
np.random.seed... | python|numpy|pandas|scikit-learn|svm | 5 |
350,469 | 27,863,108 | Fastest way of creating a list through iteration | <p>I recently created a script to create a Dragon Curve, and managed to optimize the code quite a bit.
Basically, i start by generating a list of rules, looking something like <code>[1, 1, -1, 1, 1, -1, -1]</code>, where 1 represents a right turn, and -1 represents a left turn. This goes very fast with numpy arrays.</... | <p>As the results of <code>sin</code> and <code>cos</code> are zero, one, or minus one, and cyclic, you can look them up, modulo four:</p>
<pre><code>pos = [100, 100]
direction = 0
east_west_lookup = [0, -1, 0, 1]
north_south_lookup = [1, 0, -1, 0]
for i in dragon + [0]:
east_west_step = east_west_lookup[directi... | python|list|loops|optimization|numpy | 3 |
350,470 | 61,470,655 | how to use slicing to get 2 numbers in a multiple array (numpy) | <p>if i have an array</p>
<pre><code>a = np.array([[1,2,3],[4,5,6],[7,8,9]])
</code></pre>
<p>output would be a =[1,2,3],[4,5,6],[7,8,9]</p>
<p>using slice [start:endindex:stepindex],
how could i retrieve 3 and 7?</p>
<p>is it possible?</p>
<p>I have tried </p>
<pre><code>a[:3:2]
</code></pre>
<p>this gave me 1r... | <pre><code>In [928]: a = np.array([[1,2,3],[4,5,6],[7,8,9]])
In [929]: a
Out[929]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
</code></pre>
<p>[3,7] isn't regul... | python|arrays|numpy | 1 |
350,471 | 61,474,125 | How to serialize class object for keras model | <p>I tried to save keras full model and i encountered this error</p>
<pre><code>Traceback (most recent call last):
File "d:/Workspace/College/Semester 8/Tugas Akhir/Keras-RFCN-master/Keras-RFCN-master/testing.py", line 133, in <module>
main()
File "d:/Workspace/College/Semester 8/Tugas Akhir/Keras-RFCN-m... | <p>If you are using subclass model, then after defining the model, you need to call the model on some data like <code>model.predict(x)</code> which will creates weights and enable model to be saved using <code>model.save</code> or 'model.save_weights<code>and</code>load_weights` </p>
<blockquote>
<p>First of all, a ... | python|tensorflow|keras | 0 |
350,472 | 61,502,324 | NameError on Global 'Key Position' Variable, and ax.cla() majorly slowing things down - Matplotlib, Python | <p>I have a big dataframe that consists of one X column (wavelength) and 73 Y columns (Spec1-73). I am trying to create a code to flip through the plots contained in this dataframe utilizing Matplotlib, plotting the x and a singular y on each plot in sequence, and keeping the axes consistent. </p>
<p>I am utilizing a ... | <p>The brief code below alone gives
<code>SyntaxError: name 'curr_pos' is assigned to before global declaration</code>.
The error is different from yours, but this may be related with the rest of the code you have, and an indicator that the <code>global ...</code> may be a source of error.
It is best if you also show w... | python|pandas|matplotlib | 0 |
350,473 | 61,199,173 | compare column values only with identical datetime index | <p>I have a long df from 07:00:00 to 20:00:00 (df1) and a short df with only fractions of the long one (df2) (identical datetime index values).</p>
<p>I would like to compare the groupsize values of the two data frames.</p>
<p>The datetime index, id, x, and y values should be identical.</p>
<p>I can i do this?</p>
... | <p>Do a Merge where everything is equal but make sure to reset index so its part of the merge condition</p>
<pre><code>df1_t = df1.reset_index()
df2_t = df1.reset_index()
results = df1_t.merge(df2_t, left_on = ['date', 'ids', 'x', 'y'],
right_on = ['date', 'ids', 'x', 'y'],
... | python|pandas|dataframe|datetime | 0 |
350,474 | 61,522,164 | selective averaging of dataframe entries depending on labels | <p>I have a dataframe </p>
<pre><code> ID KD DT
0 4 2 5.6
1 4 5 8.7
4 4 8 1.9
5 4 9 1.7
6 4 1 8.8
3 4 3 7.2
9 4 4 3.1
</code></pre>
<p>I also have an array of labels, same size as the total number of unique <code>KD</c... | <p>IIUC, first set_index the KD column, then you can select 'DT' and with <code>where</code> replace values that are not <code>isin(l1)</code> with Nan. then you <code>groupby.transform</code> the <code>map</code> of the column KD with their group number in <code>L</code> and get the <code>mean</code>. Finally <code>lo... | python-3.x|pandas | 1 |
350,475 | 61,308,113 | Add a dataframe that represents the max value based on comparison of other dataframes | <p>I have the following multi-index dataframe where one df represents the daily high of hypothetical stocks and the other consists of their previous day close. </p>
<pre><code> High_Price Yest_Close
Ticker ABC XYZ RST ABC XYZ. RST
2/1/19 3 10 90 2 9 88
1/31/19 3.5 9 ... | <p>You want <code>level=1</code> inside <code>max</code> ,then create a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.from_product.html" rel="nofollow noreferrer"><code>multiindex</code></a> followed by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Da... | python|pandas|dataframe | 1 |
350,476 | 61,512,957 | Pandas: Compare all values within a dataframe by row | <p>I am trying to match rows and aggregate them in a single row. </p>
<p>For example for the table below, I want to aggregate the first three rows because they are similar. 4th isnt similar. In my check, I do nothing for any row that has col 1 as B. And then again aggregation for final two rows:</p>
<pre><code>|-----... | <p>I think <code>groupby.size</code> can do it like:</p>
<pre><code>print (df.groupby(['Col 1','Col 2', 'Col 3']).size().reset_index(name='Col 4'))
Col 1 Col 2 Col 3 Col 4
0 A 12st 13 3
1 A 12st 17 1
2 B 11aa 10 1
3 C 10ee 10 2
</code></pre> | python|pandas|dataframe | 5 |
350,477 | 61,258,958 | Indexing 2d array with 2d array in Numpy | <p>I have a question that bothers me for a few days.
Let's assume we define a 2d array in Numpy:</p>
<pre><code>x = np.array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
</code></pre>
<p>We also define a 1d array for indexing, let's say:</p>
<p><code>ind = np.array([2,1])</code></p>
<p>If we will ... | <p>In the last case with the indexing array:</p>
<pre><code>print(ind)
array([[2, 1],
[2, 2]])
</code></pre>
<p>Since <code>ind</code> is a <code>2D</code> array of shape <code>(2,2)</code>, and your taking a full slice along the first axis, with <code>ind</code> you'll be indexing along the columns of <code>A... | python|arrays|numpy | 1 |
350,478 | 61,533,977 | Cannot copy multiple excel columns at once with pandas | <p>I am trying to copy multiple columns from one xlsx file to another, my code only works for copying only one column, how can I copy more than one? </p>
<pre><code>column = data_Sheet['NDB_No']
with pd.ExcelWriter('parsedData.xlsx', mode='w') as writer:
column.to_excel(writer, sheet_name= "new sheet name", index... | <p>Choose multiple columns from one dataframe like this:</p>
<pre><code>list_of_columns = ['col1', 'col2', 'col3',...] ## Put your actual columns here
columns = data_Sheet[list_of_columns]
</code></pre>
<p>Now write this into another excel:</p>
<pre><code>with pd.ExcelWriter('parsedData.xlsx', mode='w') as writer:
... | python|excel|pandas | 0 |
350,479 | 61,346,527 | Pandas Dataframe to Numpy Vstack Array by Unique Column Value | <p>I have a dataframe with following structure:</p>
<pre><code>import numpy as np
import pandas as pd
data = {'Group':['1', '1', '2', '2', '3', '3'], 'Value':[1, 2, 3, 4, 5, 6]}
df = pd.DataFrame(data)
</code></pre>
<p>I need to convert that dataframe (which has approx 4000 values per unique group, and 1000 groups... | <p>IIUC, this is just <code>pivot</code>:</p>
<pre><code>(df.assign(col=df.groupby('Group').cumcount())
.pivot(index='Group', columns='col', values='Value')
.values
)
</code></pre>
<p>Output:</p>
<pre><code>array([[1, 2],
[3, 4],
[5, 6]], dtype=int64)
</code></pre> | python|arrays|pandas|numpy|vstack | 1 |
350,480 | 61,208,730 | Add column to multiindex as ratio of two other level=0 columns | <p>I have a <code>DataFrame</code> with a <code>MultiIndex</code>:</p>
<pre><code>MultiIndex(levels=[['field1', 'field2'], ['product1','product2','product3']],
codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2]],
names=['metric', 'label'])
</code></pre>
<p>Having <code>import pandas as pd</code>, I am able to... | <p>Create <code>MultiIndex</code> for new DataFrame and add to original:</p>
<pre><code>idx = pd.IndexSlice
df = (data.loc[:,idx['field1']] / (data.loc[:,idx['field2']]))
df.columns = pd.MultiIndex.from_product([['new'], df.columns])
data = data.join(df)
</code></pre>
<p>Another way is create columns by reshape by <... | python|pandas|multi-index | 0 |
350,481 | 61,528,943 | Extracting parts of CSV data constructed in different ways in the same file using python pandas | <pre><code>Kill #,Timestamp,Bot,Weapon,TTK,Shots,Hits,Accuracy,Damage Done,Damage Possible,Efficiency,Cheated
1,17:56:13:353,TileFrenzyStrafing Cube,TileFrenzy Challenge,0.308s,2,1,0.5,100,400,0.25,false
2,17:56:13:672,TileFrenzyStrafing Cube,TileFrenzy Challenge,0s,1,1,1,100,200,0.5,false
...
Weapon,Shots,Hits,Damage... | <p>It seems as if the last 29 rows of the file-snippet you pasted are not real-csv entries.</p>
<p>You could try using the parameter <code>skipfooter</code> (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">pandas.read_csv() manual</a>):</p>
<pre><cod... | python|pandas|csv | 0 |
350,482 | 61,367,204 | 'Sequential' object has no attribute 'classifier' | <p>How to find in_features of a Pytorch model? model.classifier.in_features is working on densenet121 but nit on vgg18, is there any function which may work on all torchvision models?</p> | <p><code>classifier</code> is a <code>Sequential</code> module in the <code>VGG</code>'s implementation, so, if you want to access the <code>in_features</code> passed to the <code>classifier</code>, you have to check the <code>in_features</code> of the first layer.</p>
<pre class="lang-py prettyprint-override"><code>m... | opencv|pytorch|artificial-intelligence|conv-neural-network|torchvision | 0 |
350,483 | 61,405,822 | python (gspread) - whole data table placed in one cell of my Google Sheets instead of separate cells | <p>My goal is to update a Google Sheets document by replacing the content of its first sheet by a table of my own data (that is, a table of instances against attributes of a class). I have attempted to use the module gspread to do so but it hasn't been working out so well: If I run the line</p>
<pre><code>client.open(... | <p>As the official Sheets API says at <a href="https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#request-body" rel="nofollow noreferrer">Method: spreadsheets.values.append Request body</a></p>
<blockquote>
<p>The request body contains an instance of ValueRange.</p>
</blockquote>
... | python|json|pandas|google-sheets|gspread | 1 |
350,484 | 61,425,339 | Plot dataframe column by each entry belonging to certain range of numbers? | <p>I have a pandas dataframe as follows:</p>
<pre><code>x = pd.DataFrame({'total':[100,340,238,394,5859,324,5545,75858,563,613,123,6654,253,7567]})
#actual number of entries can be in thousands
</code></pre>
<p>And I want to first convert them in to ranges whatever they might be, for example range of 10 values. All... | <pre><code>x = pd.DataFrame({'total': [100, 340, 238, 394, 5859, 324, 5545, 75858, 563, 613, 123, 6654, 253, 7567]})
m = x['total'].max()
jumps = []
# creating the jumps (ranges of 100)
for item in range(0, m, 100):
jumps.append([item, item + 100])
# creating filter for each range
for item in jumps:
filter_nu... | python|pandas|dataframe|plot | 1 |
350,485 | 61,482,631 | Replacing some dataframe values with NaN | <p>I've edited this question a bit to clarify things.
I have a dataframe like this: </p>
<pre><code>ID (index col) 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3
</code></pre>
<p>where the ID column is strings but the rest of the df is floats. Like <a href="https://stackoverflow.com/questions/40311987/p... | <p>Ok I ended up finding a solution with iterrows but I'm still interested to know if anyone can suggest a better/more correct way. </p>
<pre><code>concentrations = ['1','2','3'...]
for k in concentrations:
tf = df[k]
for index,row in tf.iterrows():
counter = 0
for item in row:
if math.isnan(item) ==... | python|pandas|dataframe | 0 |
350,486 | 61,468,407 | pandas match/compare multiple columns | <p>I want to compare two pandas-tables by two columns.
Consider following example:
I would like to get a boolean Series which indicates True ONLY if BOTH conditions match.
I tried is.in() without much success. I could either loop over "One" or combine (add) both columns together in both dataframes, but is there some... | <pre><code>tab1.eq(tab2).all(1)
0 True
1 False
2 False
3 True
dtype: bool
</code></pre>
<p>Update</p>
<pre><code>tab1.merge(tab2,indicator=True,how='left')['_merge'].eq('both')
0 True
1 False
2 False
3 True
Name: _merge, dtype: bool
</code></pre> | python|pandas|comparison | 2 |
350,487 | 61,609,286 | How to convert rows into columns but only for part of a table in python? | <p>I have a table which has the same structure as the below simplified example: </p>
<p><a href="https://i.stack.imgur.com/oZWTE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oZWTE.png" alt="enter image description here"></a></p>
<p>I would like to convert Columns 1 and 2 into column headers with... | <p>assumption here is that the tables have the same exact columns, so u can morph this into a function and apply to each one : also, the speed is about half of ur solution with the pivot table.</p>
<pre><code>def reshape(df):
#get various variables that will be reused
other = ['Name','Date Added','Colu... | python|pandas|pivot-table|transpose | 0 |
350,488 | 61,346,618 | .py script for automating a function | <p>I'm looking for a way to do the following:</p>
<ul>
<li>import attachment from email client, for example Gmail </li>
<li>save this file XXX.xlsx -> convert this to CSV but in the name format have the date YYYYMMDD.csv</li>
<li>Then finally this needs to be uploaded to a specific SFTP folder.</li>
</ul>
<p>And this... | <p>I am not sure to understand your question,</p>
<p>For what I understand you want "to select" a file, IMO that means reference it by a variable but I may be wrong if so I encourage you to edit your question.
There are a lot of hardcoded things in your code, and you may encounter other bugs with path...</p>
<pre><co... | python|pandas|csv | 0 |
350,489 | 61,526,526 | Xlsxwriter - use variable in table to excel | <p>I'm using pandas concat to merge several dataframe (tables) to an excel document.
I use Xlsxwriter for the excel output. </p>
<p>My question is, in the code below I specify the range for the table in excel using the <code>worksheet.add_table('A1:D26')</code>. That works for this example file. But in the final docum... | <p>You might try a format string. Here I define x1 and x2, then insert them into your cell range string using <code>%d</code> to specify integer format. The string is followed by <code>% (<arg1>,<arg2>)</code>.</p>
<pre><code>x1 = 2
x2 = 27
worksheet.add_table('A%d:D%d'%(x1,x2), {'data': result.values.T.... | python|excel|pandas|concat|xlsxwriter | 1 |
350,490 | 61,235,049 | How to calculate Levenshtein distance for every unique value using a for loop on a dataframe in pandas | <p>I am trying to calculate Levenshtein distance in a dataframe using for loop.</p>
<pre><code>df2_2=df2_1[['Concat','Count','ffour']].copy()
for a in df2_2['Concat'].unique():
dw2_2=df2_2[df2_2['Concat']==a]
vv = dw2_2.iloc[:, 1::2].values
iRow, iCol = np.unravel_index(vv.argmax(), vv.shape)
iCol = iC... | <p>I will you suggest you to check the values of both <code>b</code> and <code>c</code>.
You can always just use <code>str(b)</code>, and <code>str(c)</code> and it might do the trick.<br>
Like that:</p>
<pre><code>distance=lev.distance(str(b),str(c))
</code></pre>
<p>Or you can just apply str() on all the values in... | python|pandas|levenshtein-distance | 1 |
350,491 | 61,382,157 | pandas assign result from list of columns | <p>Suppose I have a dataframe as shown below:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
np.random.seed(42)
df = pd.DataFrame({'A':np.random.randn(5), 'B': np.zeros(5), 'C': np.zeros(5)})
df
>>>
A B C
0 0.496714 0.0 0.0
1 -0.138264 0.0 0.0
2... | <p>Use numpy indexing for improve performance:</p>
<pre><code>idx = df.A < 0
res = ['B', 'C']
arr = df.values
arr[idx, df.columns.get_indexer(res)] = 1
print (arr)
[[ 0.49671415 0. 0. ]
[-0.1382643 1. 0. ]
[ 0.64768854 0. 0. ]
[ 1.52302986 0. 0. ... | pandas|dataframe | 3 |
350,492 | 61,522,143 | Divide by Zero Warning in LU Decomposition- Doolittle Algorithm working | <p>I have implemented the standard equations/algorithm of LU Decomposition of a Matrix by following this link: (<a href="https://www.geeksforgeeks.org/doolittle-algorithm-lu-decomposition/" rel="nofollow noreferrer">1</a>) and (<a href="http://mathonline.wikidot.com/the-algorithm-for-doolittle-s-method-for-lu-decomposi... | <p>It seems that you may have made some indentation errors regarding the first inner level <code>for</code> loops: <code>U</code> must be evaluated before <code>L</code> ; you also didn't correctly compute the summation term <code>acc</code> and didn't properly set the diagonal terms of <code>L</code> to 1. Following s... | python|numpy|linear-algebra | 2 |
350,493 | 61,196,528 | Resize torch tensor channels | <p>I have a torch tensor with 3 channels, and I want it to be 1 channel (all other dimensions should stay the same).
So if my current dimensions are <code>torch.Size([6, 3, 512, 512])</code> I want it to be <code>torch.Size([6, 1, 512, 512])</code></p>
<p>How can I do that?</p> | <p>Does this solve your problem?</p>
<pre><code>a = torch.ones(6, 3, 512, 512)
b = a[:, 0:1, :, :]
print(b.size()) # torch.Size([6, 1, 512, 512])
</code></pre> | pytorch|tensor | 0 |
350,494 | 61,289,020 | Fast Implied Volatility Calculation in Python | <p>I am looking for a library which i can use for faster way to calculate implied volatility in python. I have options data about 1+ million rows for which i want to calculate implied volatility. what would be the fastest way i can calculate IV's. I have tried using py_vollib but it doesnt support vectorization. It tak... | <p>You have to realize that the implied volatility calculation is computationally expensive and if you want realtime numbers maybe python is not the best solution.</p>
<p>Here is an example of the functions you would need:</p>
<pre><code>import numpy as np
from scipy.stats import norm
N = norm.cdf
def bs_call(S, K, T,... | python|pandas|quantitative-finance|quantlib|volatility | 8 |
350,495 | 61,420,301 | Removing outliers after performing a group by | <p>This is my first post so please take it easy on me. </p>
<p>I am trying to plot a box chart for the Life Expectancy of every country from the year 2000 to 2015. My CSV file contains every country 16 times, 1 per year. I plotted the box using <code>df.boxplot(by=['Country'], column='Life Expectancy')</code> and I wa... | <p>If you're trying to remove outliers I would use zscore instead of quantile</p>
<pre><code>from scipy import stats
df['outlier'] = (np.abs(stats.zscore(df['Life Expectancy'])) >= 3) # replace 3 with a threshold of your choice
new_df= df[df['outlier']==False].copy()
</code></pre>
<p>But since you want to do this... | python|pandas|group-by|statistics|outliers | 2 |
350,496 | 61,461,990 | Pandas duplicated rows with missing values | <p>Hello I have a dataframe that contains duplicates.</p>
<pre><code>df = pd.DataFrame({'id':[1,1,1],
'name':['Hamburg','Hamburg','Hamburg'],
'country':['Germany','Germany',None],
'state':[None,None,'Hamburg']})
</code></pre>
<p>removing the duplicates with <... | <p>In your very special case, here's my proposal :</p>
<pre><code>import pandas
df = pandas.DataFrame({'id':[1,1,1,2,2],
'name':['Hamburg','Hamburg','Hamburg','Paris','Paris'],
'country':['Germany','Germany',None, None, 'France'],
'state':[None,None,'Hamburg',... | python|pandas|duplicates | 1 |
350,497 | 61,513,860 | How to add a value to specific rows and columns on pandas? | <p>So here's the deal, I have this dataframe, lets kindly name it lovely_df:</p>
<pre><code> foo? fah? boo? Nice Numbers
0 foo fah boo 10
1 meh fah boo 20
2 meh fah boo 30
3 foo fah boo 40
4 meh fah boo 50
</code></pre>
<p>tried to do it like that:</p>
<pre><code>
lovely_df.loc[lovely_df['foo?'... | <p>You can use <code>numpy.where</code> with your condition</p>
<pre><code>lovely_df['new_col'] = np.where(lovely_df['foo?'] == 'meh',
lovely_df['Nice Numbers'].add(1),
lovely_df['Nice Numbers'])
print(lovely_df)
foo? fah? boo? Nice Numbers new_col
0... | python|python-3.x|pandas | 1 |
350,498 | 61,265,668 | pandas - str (row) slicing based on int in another column | <p>I have a df:</p>
<pre><code> colA colB
0 'abcde' 4
1 'abcde' 2
2 'abcde' 1
3 np.nan np.nan
4 'wxyz' 3
5 'wxyz' 2
</code></pre>
<p>What I would like is to be able to remove the first X characters from colA based on the value in colB and return the value to a new column C like below.</p>
<p... | <p>You can create custom function for return missing values if indexing failed:</p>
<pre><code>def f(a, b):
try:
return a[int(b):]
except:
return np.nan
df['colC'] = [f(a,b) for a, b in zip(df['colA'], df['colB'])]
</code></pre>
<p>Or:</p>
<pre><code>df['colC'] = df.apply(lambda x: f(x['colA... | python|string|pandas | 4 |
350,499 | 61,502,981 | Bulk inserting a dataframe using psycopg2 (error: 'dict' object does not support indexing) | <p>Big thanks in advance, relatively new to psycopg2.</p>
<p>I'm trying to bulk insert data in the form of a pandas dataframe to my existing postgres database.</p>
<pre><code>try:
psycopg2.extras.execute_values(
cur=cur,
sql=sql.SQL("""
INSERT into {table_name} ( {c... | <p>This seems like a case of an unhelpful error message. Quoting from another <a href="https://stackoverflow.com/a/8666415/5666087">SO answer</a>:</p>
<blockquote>
<p>You have to give <code>%%</code> to use it as <code>%</code> because <code>%</code> in python is use as string formatting so when you write single <code>... | python|pandas|postgresql|psycopg2 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.