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 |
|---|---|---|---|---|---|---|
351,500 | 57,305,123 | How to read a csv file from local network with pandas | <p>I would like to read the csv file from <code>192.168.214.241/data/myfile.csv</code></p>
<p>When I do </p>
<pre><code>data = pd.read_csv('//192.168.214.241/data/myfile.csv')
</code></pre>
<p>I get the error:</p>
<pre><code>FileNotFoundError: File b'//192.168.214.241/data/myfile.csv' does not exist
</code></pre>
... | <p>try this to see what directory you're currently in:</p>
<pre><code>import os
print(os.getcwd())
print(os.listdir())
</code></pre>
<p>your code looks fine so you're probably just in the wrong place.</p> | python|pandas|csv | 1 |
351,501 | 57,474,814 | Python balancing items in a list/numpy array | <p>I have an array of tokens, and each token corresponds to a different class from <code>1</code> to <code>n</code>. I need to <em>balance</em> the <code>tokens</code> array/list so that there are an equal number of tokens for each class. I want to do this by removing the elements of <code>tokens</code>.</p>
<p>In the... | <p>A solution with <code>Counter</code>:</p>
<pre><code>tokens = ['a','b','c','d','e','f','g','h','l']
lst = [ 1 , 1 , 1 , 1 , 2 , 2 , 3 , 3 , 3]
from collections import Counter
c = Counter(lst)
min_cnt = min(c.values())
new_lst = list( zip(tokens, lst) )
while True:
tmp = []
should_break = True
for ... | python|list|numpy | 2 |
351,502 | 57,517,046 | Create multiple pandas dataframes based on column value | <p>I have a df I'd like to split into 5 (named df1 - df5) based on the value of one column (<code>origin</code>). I've tried <code>groupby</code>, and a few other things (like <a href="https://stackoverflow.com/questions/19790790/splitting-dataframe-into-multiple-dataframes">this</a> and <a href="https://stackoverflow.... | <p>This should do </p>
<pre><code>
a = []
for value in df['origin'].unique():
a.append(df[df['origin']==value])
</code></pre>
<p>The array will contain the dataframes corresponding to the unique values.Let me know if I misunderstood anything.</p> | python|python-3.x|pandas | 2 |
351,503 | 57,580,249 | get coordinates of 4 corners of display screen on image | <p>I am trying to get 4 corners of screen (display) which is on image. I have two images taken from the same position (so I think good starting point will be extracting differences between two images /first and second image/). Just image on the screen has changed. So I would like to get top/bottom left/right (X,Y) coor... | <p>I have created a new solution using the difference between images and finding contours from that. I have left the old solution using hough line processing at the bottom.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import cv2
def main():
im1 = cv2.imread('s123/ss1.jpg')
im2 = cv2... | python|numpy|opencv|image-processing | 6 |
351,504 | 57,409,270 | How to find stride/padding information of a specific layer in h5 model of tensorflow or keras | <p>I have been working on extracting convolution layer information from h5 file, which includes neural network model. I have been able to extract information about number of convolution layers in h5 file but I can't see the way to get information about stride size or padding. I have been using h5py to read h5 model.</p... | <p>I was looking for the exact same thing, here is how i implemented it:</p>
<pre><code>from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
model = ResNet5... | tensorflow|keras|h5py | 0 |
351,505 | 57,375,899 | Calculating the difference between 2 days in tkinter gui takes a lot of time | <p>I have the following code that calculates the difference between <code>start_date</code> & <code>end_date</code>:</p>
<pre><code>from tkinter import *
import math
import pandas as pd
from datetime import datetime
root = Tk()
frame = Frame(root)
#frame.pack()
label1 = Label(root, text="Peak")
label1.grid(row=... | <p>I don't know if you have any use for <code>dates</code>, but this is the part that is costing you time. If you change <code>data_checker()</code> to the code below, calculating the days is almost instant. </p>
<pre><code>def date_checker():
try:
start_date = datetime.strptime(entry4.get(), '%Y-%m-%d %H:... | python|python-3.x|pandas|tkinter | 1 |
351,506 | 57,378,143 | How to get the full Jacobian of a derivative in PyTorch? | <p>Lets consider a simple tensor <code>x</code> and lets define another one which depends on <code>x</code> and have multiple dimension : <code>y = (x, 2x, x^2)</code>.</p>
<p>How can I have the full gradient <code>dy/dx = (1,2,x)</code> ? </p>
<p>For example lets take the code :</p>
<pre><code>import torch
from tor... | <p><code>torch.autograd.grad</code> in PyTorch is aggregated. To have a vector auto-differentiated with respect to the input, use <code>torch.autograd.functional.jacobian</code>.</p> | python|pytorch|autograd | 2 |
351,507 | 57,377,905 | why does this error happens:"Sliced assignment is only supported for variables" | <p>I have a deep network using Keras and I need to apply cropping on the output of one layer and then send to the next layer. for this aim, I write the following code as a lambda layer:</p>
<pre><code>def cropping_fillzero(img, rate=0.6): # Q = percentage
residual_shape = img.get_shape().as_list()
h, w = resid... | <p><code>h, w = residual_shape[1:3]</code></p>
<p>I'm not entirely sure what you're trying to do here, but Python interprets this as 'return between the 2nd element and the 4th'. Maybe you mean <code>residual_shape[1], residual_shape[3]</code>?</p> | python|tensorflow|keras|tensor | 0 |
351,508 | 57,559,712 | Creating a new column based off contents of others columns | <p>I have a dataframe, shown here.</p>
<p><a href="https://i.stack.imgur.com/YfZbF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YfZbF.png" alt="enter image description here"></a></p>
<p>I want to create a new column called <code>Result</code></p>
<p>Result should be created based off the follow... | <p>Use <code>mode</code>:</p>
<pre><code>df_start['Result']= df_result.mode(1).iloc[:, 0]
</code></pre>
<p>Output:</p>
<pre><code> P M F D Result
0 IG HY HY IG HY
1 HY HY NaN IG HY
2 IG IG HY IG IG
3 NaN NaN NaN HY HY
4 HY IG IG IG IG
</code></pre> | python|pandas | 2 |
351,509 | 57,335,184 | Dedupe Array of Strings in Python | <p>I have a final array of Url I <strong>scraped</strong> from a webpage but cannot seem to remove duplicates. Tried using set and got hashable error.</p>
<pre><code>import requests
import pandas as pd
from bs4 import BeautifulSoup
r = requests.get('https://www.census.gov/programs-surveys/popest.html')
soup = Beautif... | <p>I have used this before and it worked:</p>
<pre><code>fullArray = ["some", "data", "to", "store", "to", "later"]
finalArray = []
dupes = []
for item in fullArray:
if item not in finalArray:
finalArray.append(item)
else:
dupes.append(item)
</code></pre>
<p>And then as usual, print the arrays... | python|pandas | 0 |
351,510 | 57,442,533 | Grouping clients code registration by month and sum the transaction column | <p>I have three columns. </p>
<pre><code>Client_Number|Date|Transactions
1| 2018-01-13| 11.22|
1| 2018-07-23| 900|
2| 2018-01-12| 990|
7| 2018-07-13| 458|
2| 2018-01-21| 525|
5| 2018-02-24| 773|
5| 2018-02-14| 276|
7| 2018-07-17| 619.75|
3| 2018-08-25| 465.1|
3| 2018-08-28| 8000|
</code></pre>
<p>I ne... | <p>First make sure 'Date' is a timestamp</p>
<pre><code>df['Date']=pd.to_datetime(df['Date'])
</code></pre>
<p>Then add month to the dataframe</p>
<pre><code>df['Month']=df['Date'].dt.month
</code></pre>
<p>And use groupby()</p>
<pre><code>df_grouped=df.groupby(['Client_Number','Month'])['Transactions'].sum().rese... | python-3.x|pandas|pandas-groupby | 1 |
351,511 | 57,374,646 | Vectorize loop operation | <p>I have a following operation working with a for loop. Could anyone suggest a way to vectorize the operation using numpy? </p>
<pre><code># rgb is a 3 channel image
# points are computed using vector mult op (same size as rgb image)
# dtypes - rgb is uint8 and points is float
buffer = []
for v in range(rgb.shape[1... | <p>If you have a correspondence between struct types (C types) and numpy numerical types, this should be fairly simple. The documentation for struct is <a href="https://docs.python.org/3/library/struct.html#format-characters" rel="nofollow noreferrer">here</a>, while numpy's is <a href="https://docs.scipy.org/doc/numpy... | python|numpy|vectorization|numpy-ndarray | 1 |
351,512 | 57,414,239 | Split dataframe into groups of X number of rows and constraint on number of types in a group | <p>I have a dataframe 'DF' that contains columns 'COLUMN_Y' and 'Category'. I want to split the dataframe into chunks of SIZE, X. However, there is a constraint that there can be no more than 3 Categories in each group fo size X.</p>
<p>The idea is to return a list for a DF that contains a split-DF of size X (with th... | <p>IIUC, let's look at this exmaple.</p>
<p>Make test dataframe with your given dataframe and added a few records:</p>
<pre><code>df = pd.concat([df,pd.DataFrame({'COLUMN_Y':['value'+str(i) for i in range(14,20)],
'CATEGORY':['CAT5']*6})])
print(df)
</code></pre>
<p>Output:</p>
<pre... | python|pandas|dataframe|pandas-groupby | 0 |
351,513 | 57,480,424 | reshape a numpy ndarray python3 | <p>Let's say that I have an <code>ndarray</code> of shape <code>(10 x 1024 x 2)</code> presenting <code>10</code> vectors of <code>1024</code> complex values each value has a <code>real</code> and <code>imaginary</code> parts. and I want to reshape this array to <code>(10 x 2 x 1024)</code> meaning <code>10</code> vect... | <p>How about using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow noreferrer"><code>transpose</code></a>:</p>
<pre><code>a = np.random.rand(10, 1024, 2)
a_t = a.transpose(0,2,1) #shape is (10, 2, 1024)
</code></pre> | python-3.x|numpy | 2 |
351,514 | 57,484,396 | Vectorizing a "pure" function with numpy, assuming many duplicates | <p>I want to apply a "black box" Python function <code>f</code> to a large array <code>arr</code>. Additional assumptions are:</p>
<ul>
<li>Function <code>f</code> is "pure", e.g. is deterministic with no side effects.</li>
<li>Array <code>arr</code> has a small number of unique elements.</li>
</ul>
<p>I can achieve ... | <p>You actually can do this in one-pass over the array, however it requires that you know the <code>dtype</code> of the result beforehand. Otherwise you need a second-pass over the elements to determine it.</p>
<p>Neglecting the performance (and the <code>functools.wraps</code>) for a moment an implementation could lo... | python|pandas|numpy|unique|vectorization | 7 |
351,515 | 57,661,086 | my neural network is not learning cost is not changing | <p>I'm building a neural network for classifying mnist digits I got the data from
I tried to built it with only tensorflow I didn't want to use keras
<a href="https://www.kaggle.com/c/digit-recognizer/data" rel="nofollow noreferrer">https://www.kaggle.com/c/digit-recognizer/data</a>
and through epochs cost is not dec... | <p>For any neural network, parameter tuning is essential. You can try different combinations to come up with a suitable value. Cost function gives an idea as to whether convergence has reached or not. If it does not converge, try a new set of parameters.</p> | python|tensorflow|machine-learning|neural-network|mnist | 0 |
351,516 | 57,631,705 | RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation | <p>In a pytorch model training process I get this error:</p>
<blockquote>
<p>RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.LongTensor [128, 1]] is at version 8; expected version 7 instead. Hint: the backtrace further above shows the operatio... | <p>A tensor matching this description <code>torch.cuda.LongTensor [128, 1]</code>, should narrow down your search. </p>
<p>A quick google search revealed that, <code>LongTensors</code> are most commonly returned by <code>min</code> , <code>max</code>, <code>sort</code>. so the lines </p>
<pre><code>l=out_dec[:,0]
ch... | python|pytorch|in-place | 6 |
351,517 | 24,193,174 | Reset color cycle in Matplotlib | <p>Say I have data about 3 trading strategies, each with and without transaction costs. I want to plot, on the same axes, the time series of each of the 6 variants (3 strategies * 2 trading costs). I would like the "with transaction cost" lines to be plotted with <code>alpha=1</code> and <code>linewidth=1</code> whil... | <p>You can reset the colorcycle to the original with <a href="http://matplotlib.org/api/axes_api.html?#matplotlib.axes.Axes.set_color_cycle" rel="noreferrer">Axes.set_color_cycle</a>. Looking at the code for this, there is a function to do the actual work:</p>
<pre><code>def set_color_cycle(self, clist=None):
if c... | python|matplotlib|pandas | 104 |
351,518 | 24,171,905 | Keeping the N first occurrences of | <p>The following code will (of course) keep only the first occurrence of 'Item1' in rows sorted by 'Date'. Any suggestions as to how I could get it to keep, say the first 5 occurrences?</p>
<pre><code>## Sort the dataframe by Date and keep only the earliest appearance of 'Item1'
## drop_duplicates considers the column... | <p>You want to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.head.html" rel="nofollow">head</a>, either on the dataframe itself or <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-first-rows-of-each-group" rel="nofollow">on the groupby</a>:</p>
<pre><co... | python|pandas | 2 |
351,519 | 24,333,451 | What is the most simple and proper way to fitting data to sinc function using by numpy? | <p>I did some work and finally i got a data that its shape looked like sinc function and i tried to search how to fitting graph to sinc function using by numpy and i found this:</p>
<p><a href="https://stackoverflow.com/questions/22950301/fitting-a-variable-sinc-function-in-python">Fitting a variable Sinc function in ... | <p>Well to perform fitting the answer provided in the link you have given is good enough. But since you say you find it difficult I have an example code with data in the form a sine curve and a user defined function that fits the data. </p>
<p>Here is the code: </p>
<pre><code>import numpy as np
import matplotlib.pyp... | python|numpy|interpolation|curve-fitting|data-fitting | 2 |
351,520 | 24,291,798 | Numpy: Add Rows of Matrix over another Matrix of different dimension | <p>I have two matrices</p>
<pre><code>A = np.array(
[[1,2,3],
[4,5,6],
[7,8,9]])
B = np.array(
[[1,1,1],
[2,2,2]])
</code></pre>
<p>I would like to have a matrix, which is 3x3x2 which is [[A + first row of B], [A + second row of B]]</p>
<pre><code>C = np.array(
[[[2,3,4],
[5,6,7],
... | <p>Your <code>A =</code> and <code>B =</code> commands don't generate matrices, but lists of lists. The difference matters because they don't have numpy's nice vector math attached.</p>
<p>Anyway, you could expand <code>A</code> by creating a new axis using <code>[:,None]</code>, do the addition, and then swap the ax... | python|numpy|matrix | 1 |
351,521 | 24,256,511 | Denormalizing a column to a boolean matrix in Pandas? | <p>I'm trying to take a column of values such as:</p>
<pre><code>name tag
a 1
a 2
b 2
c 1
b 3
</code></pre>
<p>and ascribe a boolean matrix with new columns, "tag_(val)", such as:</p>
<pre><code>name tag_1 tag_2 tag_3
a T T F
b F T T
c T ... | <p>You could add a column full of <code>True</code> and then pivot:</p>
<pre><code>>>> df["val"] = True
>>> piv = df.pivot("name", "tag", "val").fillna(False)
>>> piv
tag 1 2 3
name
a True True False
b False True True
c True False F... | python|pandas|transformation|denormalization | 4 |
351,522 | 24,331,551 | How to sort a numpy array based on the values in a specific row? | <p>I was wondering how I would be able to sort a whole array by the values in one of its columns.</p>
<p>I have :</p>
<pre><code>array([5,2,8,2,4])
</code></pre>
<p>and:</p>
<pre><code>array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21,... | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="noreferrer">numpy.argsort</a> to get a list with the sorted indices of your array. Using that you can then rearrange the columns of the matrix.</p>
<pre><code>import numpy as np
c = np.array([5,2,8,2,4])
a = np.ar... | python|arrays|sorting|numpy | 16 |
351,523 | 23,992,447 | Read Euromillions Results url with Pandas read_csv ends up in MultiIndex | <p>The national lottery in the UK publish their results at:
<a href="http://www.national-lottery.co.uk/player/euromillions/results/downloadResultsCSV.ftl" rel="nofollow">http://www.national-lottery.co.uk/player/euromillions/results/downloadResultsCSV.ftl</a></p>
<p>The data looks to be a well formed csv table and the ... | <p>There is a blank line for the first line, skip this and it loads fine:</p>
<pre><code>In [6]:
import pandas as pd
url = 'http://www.national-lottery.co.uk/player/euromillions/results/downloadResultsCSV.ftl'
test = pd.read_csv(url, skiprows=1)
test
Out[6]:
DrawDate Ball 1 Ball 2 Ball 3 Ball 4 Ball 5 Lu... | python-2.7|pandas | 2 |
351,524 | 24,015,404 | How do I tell how good my exponential curve fit is in SciPy? | <p>I fit some data using Scipy:</p>
<pre><code>param=expon.fit(data)
pdf_fitted=expon.pdf(x,loc=param[-2],scale=param[-1])
plot(x,pdf_fitted,'r')
hist(data,normed=1,alpha=.3,histtype='stepfilled')
</code></pre>
<p>And I get a curve that looks like this:</p>
<p><img src="https://i.stack.imgur.com/ohpDK.png" alt="Expo... | <p>The standard method, assuming your errors are normally distributed, is to use the sum of the squared residuals. This, you can turn into rigurours statistics using the chi² distribution.</p>
<pre><code>values, edges = np.histogram(data, bins=np.sqrt(len(data)))
x = edges[:-1] + np.diff(edges)
pdf_fitted = expon.pdf... | python|numpy|exponential-distribution | 4 |
351,525 | 24,398,708 | Slicing a numpy array along a dynamically specified axis | <p>I would like to dynamically slice a numpy array along a specific axis. Given this:</p>
<pre><code>axis = 2
start = 5
end = 10
</code></pre>
<p>I want to achieve the same result as this:</p>
<pre><code># m is some matrix
m[:,:,5:10]
</code></pre>
<p>Using something like this:</p>
<pre><code>slc = tuple(:,) * len... | <p>As it was not mentioned clearly enough (and i was looking for it too):</p>
<p>an equivalent to:</p>
<pre><code>a = my_array[:, :, :, 8]
b = my_array[:, :, :, 2:7]
</code></pre>
<p>is:</p>
<pre><code>a = my_array.take(indices=8, axis=3)
b = my_array.take(indices=range(2, 7), axis=3)
</code></pre> | python|numpy | 56 |
351,526 | 24,344,512 | More Efficient way to parse JSON and convert to CSV in Python | <p>I'm not sure if this will be enough information to provide but I am currently trying to extract and format into csv a subset of data from a very large file containing many JSON objects as lines and dumping it into one csv file. I have the below implementation. Speed isn't too bad but I was wondering if there is a mo... | <p>I did the following:</p>
<ul>
<li>Annotated the original version with <code>STRANGE</code> (= I am not sure what you are doing), <code>EFFICIENT</code> (= can be made more efficient), <code>SIMPLIFY</code> (=can be made simpler).</li>
<li>Created two other versions that may be more efficient, but change behavior (i... | python|json|pandas | 1 |
351,527 | 24,064,509 | to_sql pandas method changes the scheme of sqlite tables | <p>When I write Pandas DataFrame to my SQLite database using <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-sql" rel="noreferrer">to_sql</a> method it changes the <code>.schema</code> of my table even if I use <code>if_exists='append'</code>. For example after execution</p>
<pre><code>with sqlite3.con... | <p>Starting from 0.14 (what you are using), the sql functions are refactored to use <code>sqlalchemy</code> to improve the functionality`. See the <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#sql" rel="noreferrer">whatsnew</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#sql-qu... | python|pandas | 9 |
351,528 | 43,679,734 | What is the difference between np.float64 and np.double? | <p>I tried running the following code to find out the difference between <code>float64</code> and <code>double</code> in <code>numpy</code>. The result is interesting as type double takes almost double the time compared with time taken for multiplication with <code>float64</code>. Need some light on this.</p>
<pre><co... | <p>I think you're comparing apples with oranges.</p>
<p>The first bench is basically <code>a * b</code> but the second <code>a * a</code>.</p>
<p>I suspect much less cache misses for the latter.</p> | python|numpy|precision | 10 |
351,529 | 43,801,770 | Python Pandas - Odds Ratio with Scipy (P Value = 0?) | <p>I am trying to calculate the Odds Ratio of a 2 x 2 grid (below)</p>
<pre><code> Lower Higher
A 11772336 18837138
B 3624890 4263509
</code></pre>
<p>I have done this code to get the Odds Ratio:</p>
<pre><code>import scipy.stats as stats
table = df.values
reversedTable = table[::-1]
oddsratio, ... | <p>In your case, the z score for the log odds ratio is 382.246, and the associated two-tailed p-value is 3.169 × 10<sup>-31731</sup>. This is smaller than the smallest positive value that can be represented with a 64-bit float (2<sup>−1074</sup>), which is what <code>fisher_exact</code> returns for the p-value.</p> | python|pandas|scipy | 1 |
351,530 | 43,562,029 | TensorFlow input pipeline for deployment on CloudML | <p>I'm relatively new to TensorFlow and I'm having trouble modifying some of the examples to use batch/stream processing with input functions. More specifically, what is the 'best' way to modify this script to make it suitable for training and serving deployment on Google Cloud ML?</p>
<p><a href="https://github.com/t... | <p>I think you have 3 options</p>
<p>1) You cannot reuse pandas preprocessing pipelines in TF. However, you could start TF with the output of your pandas preprocessing. So you could build a vocab and convert the text words to integers, and save a new preprocessed dataset to disk. Then read the integer data (which is e... | pandas|input|tensorflow|google-cloud-ml | 1 |
351,531 | 43,905,755 | How do I count the number of nonzero values in a given array column? | <p>I have an array that is as follows:</p>
<pre><code>[[0, 0, 0, 1],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
etc
</code></pre>
<p>I'd like to determine the sum of index [3] in each line.
For example, here I'd like to get <code>2</code> as a result.</p>
<p>I'm trying </p>
<pre><code>np.sum(np.c... | <p>You need to index the array as <code>a[:, 3]</code> (the third column of all rows), then you can do:</p>
<pre><code># if the array contains only 0 and 1
a[:,3].sum()
# 2
# if the array can have other values besides 0 and 1
np.count_nonzero(a[:,3])
# 2
</code></pre>
<p>Here is more info about <a href="https://docs... | python|arrays|python-3.x|numpy|count | 3 |
351,532 | 43,528,763 | Pandas: 3 state boolean indexing with string replacement | <p>I have a pandas dataframe that contains booleans (1 and -1) and nans. I would like to populate it with the words "High", "Low", and nans. I have tried:</p>
<p><strong>1) boolean indexing</strong> </p>
<pre><code>df[df==1] = 'High'
</code></pre>
<p>but then got a mixed type error when I went to the next conditio... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>replace</code></a> or double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p>
<pre><code>... | string|pandas|dataframe|boolean|where | 0 |
351,533 | 43,757,068 | Losing the header of a csv file after normlizing | <p>I've wrote the following code to read a csv file run a column wise normalization :</p>
<pre><code>from sklearn import preprocessing
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# reading Train values
Training ='Training.csv'
df = pd.read_csv(Training)
df =df.drop(df.columns[len(df.l... | <p>Well, that is because you use <code>preprocessing.MinMaxScaler()</code> which returns an array, not a dataframe.
After you create a dataframe based on this matrix, it does not know anything about your columns.</p>
<p>You could try something like</p>
<pre><code>normalized = pd.DataFrame(np_scaled, columns=df.column... | python|csv|pandas | 1 |
351,534 | 43,551,706 | Tensorflow Create Protobuf for a Tensor | <p>I want to have a Python script that converts Numpy arrays to TensorFlow Tensors in Protobuf Binary so later in C++ I can reload them. This can be done with a compute graph like <a href="https://stackoverflow.com/questions/41575442/tensorflow-export-compute-graph-to-xml-json-etc">this</a>.</p>
<p>I found the followi... | <p>I'll post the answer as I figure it out, so perhaps someone can pitch in with the rest of the solution.</p>
<p><strong>Python</strong></p>
<p>Tensor -> Protobuf Binary</p>
<pre><code>>>> import tensorflow as tf
>>> with tf.Graph().as_default():
... s = tf.constant([1.2, 3.4, 5.6, 7.8])._op.n... | python|c++|numpy|tensorflow | 5 |
351,535 | 43,665,016 | Pandas DataReader | <p>This may be a really simple question but I am truly stuck.
I am trying to call Pandas' DataReader like:</p>
<pre><code>from pandas.io.date import DataReader
</code></pre>
<p>but it does not get DataReader. I do not know what I am doing wrong, especially for such a simple thing. All I am trying to do is to acquire ... | <p>Pandas data reader was removed from pandas, it is now a separate repo and a separate install </p>
<p><a href="https://github.com/pydata/pandas-datareader" rel="noreferrer">https://github.com/pydata/pandas-datareader</a></p>
<p>From the readme.</p>
<blockquote>
<p>Starting in 0.19.0, pandas no longer supports pa... | python-3.x|pandas|yahoo|yahoo-finance|pandas-datareader | 11 |
351,536 | 43,550,631 | TensorFlow: Is fitting in small step increments equivalent to fitting in 1 large increment? | <p>I made a TensorFlow estimator with a certain model function:</p>
<pre><code>estimator = tf.contrib.learn.Estimator(
model_fn=_model_fn_for_penguin_model,
model_dir=/tmp/penguin_classification,
config=tf.contrib.learn.RunConfig(
save_summary_steps=5))
</code></pre>
<p>And then called <code>estima... | <p>These calls should be equivalent, but one thing to keep in mind is the behavior of your input_fn. If it does no randomization, for example, the first case can loop over as much as 1M training examples, while the second one will just revisit the same 200 examples many times.</p> | tensorflow | 1 |
351,537 | 43,605,690 | Java - train loaded tensorflow model | <p>Does anyone know if it is possible after a model is loaded into Java from Tensorflow Python to continue training the model?
I've come up with this snippet of code, but did not work (yes, the output is the same as the input)</p>
<pre><code>for(int i = 0; i < 10000; i++) {
Tensor cost = b.session().runner().fe... | <p>You are feeding inputs and fetching the loss; this won't train the model. To do so you'll need to feed batches of data and run the update ops (returned maybe from <code>optimizer.minimize</code>).</p>
<p>It is possible to do this from Java, but the infrastructure in python is more well-developed, including threads ... | java|python|machine-learning|tensorflow|protocol-buffers | 1 |
351,538 | 43,523,978 | Scraping an html table with beautiful soup into pandas | <p>I'm trying to scrape an html table using beautiful soup and import it into pandas -- <a href="http://www.baseball-reference.com/teams/NYM/2017.shtml" rel="nofollow noreferrer">http://www.baseball-reference.com/teams/NYM/2017.shtml</a> -- the "Team Batting" table. </p>
<p>Finding the table is no problem: </p>
<pre... | <p>I have tested that the below will work for your purposes. Basically you need to create a list, loop over the players, use that list to populate a DataFrame. It is advisable to not create the DataFrame row by row as that will probably be significantly slower.</p>
<pre><code>import collections as co
import pandas as ... | python-3.x|pandas|web-scraping|beautifulsoup | 1 |
351,539 | 43,508,491 | Extra Character: TensorFlow HelloWorld to Verify Correct Installation | <p>This is to make sure the result received from tensorFlow hello-world here is fine
<a href="https://www.tensorflow.org/install/install_windows" rel="nofollow noreferrer">The hello-world page</a></p>
<blockquote>
<p>If the Python program outputs the following, then the installation is successful and you can begin writ... | <p>It shows that this is a byte string (not a string). To know the difference, have a look at <a href="https://stackoverflow.com/questions/6224052/what-is-the-difference-between-a-string-and-a-byte-string">this question</a>.</p>
<p>In short, a string can't be directly stored on a disk directly. It has to be encoded fir... | python-3.x|tensorflow | 1 |
351,540 | 43,898,035 | Pandas - combine column values into a list in a new column | <p>I have a Python Pandas dataframe df:</p>
<pre><code>d = [['hello', 1, 'GOOD', 'long.kw'],
[1.2, 'chipotle', np.nan, 'bingo'],
['various', np.nan, 3000, 123.456]]
t = pd.DataFrame(data=d, columns=['A','B','C','D'])
</code></pre>
<p>which looks like this:</p>
<pre><code>print(t)
A B C ... | <p>try this :</p>
<pre><code>t['combined']= t.values.tolist()
t
Out[50]:
A B C D combined
0 hello 1 GOOD long.kw [hello, 1, GOOD, long.kw]
1 1.20 chipotle NaN bingo [1.2, chipotle, nan, bingo]
2 various NaN 3000 123.46 [vario... | python|list|pandas|lambda|apply | 107 |
351,541 | 43,745,527 | TensorFlow: How can I reuse Adam optimizer variables? | <p>After recently upgrading my TensorFlow version, I am encountering this error which I am not able to solve:</p>
<pre><code>Traceback (most recent call last):
File "cross_train.py", line 177, in <module>
train_network(use_gpu=True)
File "cross_train.py", line 46, in train_network
with tf.control_dep... | <p>Turns out I didn't need to instantiate two different Adam optimizers. I just created a single instance and there was no name conflict or issue of trying to share variables. I use the same optimizer regardless of which network branches are being updated:</p>
<pre><code> e_grads = opt.compute_gradients(e_loss)
wit... | python|tensorflow|conv-neural-network | 3 |
351,542 | 43,484,480 | how to make the title of the index same row as header | <blockquote>
<p>hi, I wish to have this dataframe:</p>
<pre><code> indicator a b c
hot 2 2 4
cold 3 1 1
</code></pre>
<p>The indicator column is my index, and the indicator row is my header.
After i set Indicator column as my index it become:</p>
<pre><code> ... | <p>It's just how python handles index and columns. You can't have index name and column names displayed on the same row.</p> | python|pandas|dataframe | 1 |
351,543 | 43,660,715 | How can I create a Satellite style map with Plotly and Pandas? | <p>Plotly provides an example of how to create a map with scattered points here: </p>
<p><a href="https://plot.ly/pandas/scatter-plots-on-maps/" rel="nofollow noreferrer">https://plot.ly/pandas/scatter-plots-on-maps/</a></p>
<p>This example uses an Atlas style. There is a link to edit the chart on the example page wh... | <p>Open <a href="https://plot.ly/pandas/scatter-plots-on-maps/" rel="nofollow noreferrer">North American Precipitation Map</a> in edit mode, you will see following map:</p>
<p><a href="https://i.stack.imgur.com/PrjDE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PrjDE.png" alt="enter image descrip... | python|pandas|plotly | 2 |
351,544 | 43,630,535 | manipulate data in a cell with Python (Openrefine) | <p>I need to edit all the 3000 phone numbers in a column so that the dialling code is in brackets. For example from:
+49 089 / 514 6977 - 18
To:
+49 (089) 514 6977 - 18</p>
<p>Im guessing with Panda should be possible. Im using open refine?</p> | <p>Try like this:</p>
<pre><code>df['Column_Name'] = df['Column_Name'].apply(lambda x: x[:4]+'('+x[4:7]+')'+x[9:])
</code></pre>
<p>And if you have a single and double or even triple digit after plus, go with this:</p>
<pre><code>df['Column_Name'] = df['Column_Name'].apply(lambda x: ' '.join([part if i != 1 else '('... | python|pandas|openrefine | 2 |
351,545 | 43,634,508 | Extract array from arrays of arrays | <p>I have this arrays:</p>
<pre><code>arr = np.array([[[ -1., -1., -1., 0., 0., 0.],
[ 0.1, 0.1, 0.1, 2., 3., 4.]], # <-- this one
[[ -1., -1., -1., 0., 0., -1.],
[ 0.1, 0.1, 0.1, 16., 17., 0.1]], # <-- and this one
[[ -1., ... | <p>That's a <code>3D</code> array and you are trying to select the second element of the second axis and extracting all elements along the rest of the axes. So, its as simple as -</p>
<pre><code>arr[:,1,:]
</code></pre>
<p>We can skip listing the <code>:</code> for the trailing axes, so it further simplifies to -</p>... | python|numpy | 7 |
351,546 | 43,713,697 | Error accessing pandas row element named class | <p>I am getting an invalid syntax error when I try obtain the class element in each row:</p>
<pre><code>for rows in testData.itertuples():
c = classify(rows.subj_text, priors, cpParams)
currC = rows.class
</code></pre>
<p>I believe the error might due to the fact that class is a reserved word? How could I fix... | <p>The keyword <code>class</code> is a problem. You can access the field in the tuple as:</p>
<pre><code>currC = rows[list(testData.columns).index('class') + testData.index.nlevels]
</code></pre> | python|pandas | 1 |
351,547 | 43,640,862 | How to concatenate a coo_matrix with a column numpy array | <p>I have a <code>coo_matrix</code> <code>a</code> with shape <code>(40106, 2048)</code> and a column numpy array <code>b</code> with shape <code>(40106,)</code>. </p>
<p>What I want to do is to simply concatenate the matrix and the array (i.e. the resulting data structure will have shape <code>(40106, 2049)</code> ).... | <p>Convert the second array, which is <code>1D</code> to <code>2D</code> and use then <code>hstack</code> -</p>
<pre><code>hstack([A,B[:,None]])
</code></pre>
<p>Sample run -</p>
<pre><code>In [86]: from scipy.sparse import coo_matrix, hstack
# Sample inputs as a coo_matrix and an array
In [87]: A = coo_matrix([[1,... | python|numpy|scipy | 1 |
351,548 | 43,697,747 | Getting the average and proportion of a column of a dataframe with respect to two other columns | <p>I have a DataFrame (<code>df</code>) with 4 columns: Age, Request_ID, Gender and Type. My values look like the following:</p>
<pre><code>Age Request_ID Gender Type
20 1 M A
28 2 F B
30 1 M C
50 7 M A
19 20 F B
</code></... | <p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow noreferrer"><code>agg</code></a> for aggregate column <code>Age</code> by <code>mean</code> and column <code>Request_ID</code> to <a href="http://pandas.pydata.org/pandas-docs/st... | python|pandas|dataframe | 1 |
351,549 | 43,763,897 | Slow parsing of fixed-width, alternating-line file to pandas dataframe | <p>I have written a function to parse <a href="https://www.dropbox.com/s/qn905d7y63siagk/wind.txt?dl=1" rel="nofollow noreferrer">this wind file (wind.txt ~1MB)</a> into a pandas dataframe but it's pretty slow (according to my colleague) because of the nastiness of the file format. The file linked above is just a subse... | <p>I'd use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_fwf.html" rel="nofollow noreferrer">pd.read_fwf(...)</a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">pd.read_csv(..., delim_whitespace=True)</a> method - it's desig... | python|pandas|parsing|multiline|fixed-width | 3 |
351,550 | 43,917,738 | how to split date and time and create separate columns | <p>I want to split <strong>DATE_H_REAL</strong> and create two columns. one for date and one hour, i use this :</p>
<pre><code>from datetime import datetime
df_picru = datetime.strptime(df_picru['DATE_H_REAL'], '%Y-%m-%d %H:%M:%S')
df_picru['day'] = df_picru.strftime('%Y-%m-%d')
df_picru['hour'] = df_picru.strftime('%... | <p>In pandas need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>Series.dt.strftime</code></a> ... | python|pandas|datetime|dataframe | 2 |
351,551 | 43,831,759 | Python: Creating the "negative" of an array | <p>I have this 64x64 2D array
<a href="https://i.stack.imgur.com/YVoe1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YVoe1.png" alt="enter image description here"></a>
the data for this array can be downloaded here - <a href="http://m.uploadedit.com/ba3s/1494223164755.txt" rel="nofollow noreferrer"... | <p>If your data is stored in a 2dim numpy array <code>arr</code>, you can do:</p>
<pre><code>arr2 = arr.max() + arr.min() - arr
</code></pre> | python|arrays|numpy | 4 |
351,552 | 43,509,953 | python - stumped by pandas conditionals and/or boolean indexing | <p>I am having trouble with conditionals / boolean indexing. I am trying to populate a dataframe (dfp) with logic which is conditional on data from a similarly shaped dataframe (dfs) plus the previous row of itself (dfp).
This is my latest fail...</p>
<pre><code>import pandas as pd
dfs = pd.DataFrame({'a':[1,0,-1,0,1... | <p>Not the best way to do it but something that works.</p>
<pre><code> dfs = pd.DataFrame({'a':[1,0,-1,0,1,0,0,-1,0,0],'b':[0,1,0,0,-1,0,1,0,-1,0]})
dfp = dfs.copy()
</code></pre>
<p>Define the function as follows. Usage of 'last' here is a little hacky.</p>
<pre><code> last = [0]
def f( x ):
... | python|pandas|indexing|boolean|conditional | 3 |
351,553 | 2,318,667 | Simple question: In numpy how do you make a multidimensional array of arrays? | <p>Right, perhaps I should be using the normal Python lists for this, but here goes:</p>
<p>I want a 9 by 4 multidimensional array/matrix (whatever really) that I want to store arrays in. These arrays will be 1-dimensional and of length 4096.</p>
<p>So, I want to be able to go something like</p>
<pre><code>column = ... | <p>Note that to leverage the full power of numpy, you'd be much better off with a 3-dimensional numpy array. Breaking apart the 3-d array into a 2-d array with 1-d values
may complicate your code and force you to use loops instead of built-in numpy functions.</p>
<p>It may be worth investing the time to refactor you... | python|arrays|multidimensional-array|numpy | 8 |
351,554 | 73,128,871 | Generate conditional lists of lists in Pandas, "Pythonically" | <p>I want to generate a conditional list of lists. The number of embedded lists is determined by the number of unique conditions, and each embedded list contains values from a given condition.</p>
<p>I can generate this list of lists using a for-loop. See the code below. However, I am looking for a faster and more Pyth... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>x = df.groupby("conditions")["values"].agg(list).to_list()
print(x)
</code></pre>
<p>Prints:</p>
<pre class="lang-py prettyprint-override"><code>[[-1, 78], [33, 74, -79], [59], [-32, -2, 52, -66]]
</code></pre>
<hr />
<p>Input dataframe:</p... | python-3.x|pandas|group-by | 1 |
351,555 | 72,876,689 | If value in column of DataFrame exists, replace it. If not, append to DataFrame Python | <p>I have a DataFrame with 2 columns: ['a', 'b'] and values x and y. If x exists in 'a', I need to replace the value in column 'b' for that row with y. If not, append x, y to the end of the DataFrame.</p>
<p>I can use if x in df['a'].values() to return if it exists, but this does not help to replace that row's 'b' colu... | <p>You can def your own function</p>
<pre><code>def yourfunc(df,x,y):
if df['a'].eq(x).any():
df.loc[df['a'].eq(x),'b'] = y
else :
df = pd.concat([df,pd.DataFrame([[x,y]],columns=df.columns)],ignore_index=True)
return df
</code></pre>
<p>Or use <code>combine_first</code> after <code>re... | python|pandas|dataframe | 1 |
351,556 | 73,006,909 | Can't import VecFrameStackFrame from Stable-baselines3 - importing problem | <p>I have a problem when importing some dependencies from stable baselines 3 library, I installed it with this command</p>
<pre><code>pip install stable-baselines3[extra]
</code></pre>
<p>But When I import my dependencies</p>
<pre><code>import gym
from stable_baselines3 import A2C
from stable_baselines3.common.vec_env ... | <p>I knew that stable baselines new version has changed the name from</p>
<pre><code>from stable_baselines3.common.vec_env import VecFrameStackFrame
</code></pre>
<p>To</p>
<pre><code>from stable_baselines3.common.vec_env import vec_frame_stack
</code></pre>
<p>and it worked for me</p> | python|deep-learning|pytorch|reinforcement-learning|stable-baselines | 1 |
351,557 | 73,141,348 | apply a self-written function to a column containing spacy objects | <p>I'm trying to apply a self-written function to a column containing spacy objects (processed text).</p>
<p>Consider the following example. I have a sentence: <code>sent = 'Dies ist ein generischer Satz mit einem bestimmten Wort und anderen Worten.'</code></p>
<p>I process this sentence with spacy and apply a matcher ... | <p>IIUC, this is what you actually want:</p>
<pre><code>df['matchwords'] = df.apply(lambda x: token_from_spacy_match(x['matches'], x['spacy_sent']), axis=1)
</code></pre> | python|pandas|spacy | 2 |
351,558 | 73,107,387 | Extracting Bank Data for given sheet in python pandas using schwifty library | <p>I do have a question, hoping you can provide me some support.
Suppose you have following frame (Existing Exce-File)</p>
<pre><code>Bank details Bank Keys Bank Account number IBAN
SE 950 00099602600124545 SE9495000099602600124545
NO DNBANOKK 15031641192 ... | <p>following solution helped me. The solution also considers the situation if a field is empty and error might occur</p>
<pre><code>Bank_Code_List=[]
for iban_value, bankkey_value in zip(df["IBAN"].values,df["BANKL"].values):
if iban_value!="nan":
... | pandas|conditional-formatting|np | 0 |
351,559 | 72,888,006 | Why is the backpropagation of 2D convolution failing with Tensorflow when using a distribute strategy? | <p>I followed the tutorial of Tensorflow to enable multi GPU training (from a single computer) with a distribute strategy for my custom training loop: <a href="https://www.tensorflow.org/guide/distributed_training?hl=en#use_tfdistributestrategy_with_custom_training_loops" rel="nofollow noreferrer">https://www.tensorflo... | <p>While writing the code at the end of my post, I tried some minor changes I haven't thought about before and randomly found the culprit. The <code>@tf.function</code> decorator above the <code>run_train_step</code> function was causing the issue! I think I added it by mistake while implementing the distribute strateg... | python|tensorflow|distributed-computing|backpropagation | 0 |
351,560 | 73,064,023 | how to configure the layouts for like this input and output example in tensorFlow and keras | <p>I have those input and output, and i want to configure the layouts using TensorFlow and Keras:</p>
<pre><code>input = [[5, 3, 10], [2, 1, 2], [6,2,9], [1,1,0], [10, 4, 3], [3, 5, 6], [8, 1, 10], [4, 4, 3],[7, 3, 6], [4, 2, 12]] #
output = [2000, 500, 2100, 300, 3000, 1200, 3400, 1300, 2500, 1900]
</code></pre>
<p>... | <p>Try changing your input shape to <code>(3,)</code>, since each samples has 3 features and when making predictions, add an additional dimension for the batch size:</p>
<pre><code>import tensorflow as tf
input = [[5, 3, 10], [2, 1, 2], [6,2,9], [1,1,0], [10, 4, 3], [3, 5, 6], [8, 1, 10], [4, 4, 3],[7, 3, 6], [4, 2, 1... | python|tensorflow|keras|layer | 1 |
351,561 | 72,889,234 | Appending tuples to a Pandas dataframe and "cannot concatenate" - what am I doing wrong? | <p>I want to fill up a dataframe from a scraping loop. Say I created an empty DF with four columns.</p>
<pre><code>df = pd.DataFrame(columns=['A','B','C','D'])
</code></pre>
<p>Then the loop to fill it looks like this:</p>
<pre><code>for i in range:
a = x['col1'][i]
b = x['col2'][i]
c = x['col3'][i]
d = x['col4... | <p>You can add dictionary instead of tuple:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(columns=["A", "B", "C", "D"])
for i in range(10):
a = i + 1
b = i + 2
c = i + 3
d = i + 4
d = {"A": a, "B": b, "C":... | pandas|dataframe|loops|tuples|typeerror | 1 |
351,562 | 73,093,171 | How To Store Column Mean As a Variable | <p><strong>ISSUE</strong></p>
<p>I am performing data cleansing. I have calculated a column mean based on conditions fed into the <code>.loc()</code> function. Storing this output in the z variable is producing a (1,1) dataframe and throwing an incompatibility error when I try to assign it to a missing value.</p>
<p><... | <p>You can use</p>
<pre class="lang-py prettyprint-override"><code>z = (train.loc[((train.MSSubClass == 190) &
(train.MSZoning == 'RL') &
(train.LotShape == 'IR1'))]
.agg({'LotFrontage': ['mean']})
.item()) # Return first element of Series
# or
z = (train.loc[((train.M... | python-3.x|pandas|variable-assignment | 2 |
351,563 | 73,070,658 | pandas.core.frame.DataFrame rename index problems | <p>In an existing table I got some summary by</p>
<pre><code>df.groupby('bin_fare')['fare'].agg(['count', 'sum', 'mean'])
</code></pre>
<p>The result is table above. bin_fare name of Indexes</p>
<p>bin_fare count sum mean</p>
<p><strong>1</strong> 491 3717.1413 7.570553</p>
<p><strong>2</strong> 47... | <p>You can just set a new index:</p>
<pre><code>df.index = pd.Series(fare_rate_names)
</code></pre>
<p>Or, the more pythonic ("pandastic"?):</p>
<pre><code>df.set_index(pd.Series(fare_rate_names), inplace=True)
</code></pre>
<p>Also, you could create a dummy name for the 0th index:</p>
<pre><code>fare_rate_na... | python|pandas|indexing|rename | 0 |
351,564 | 73,155,891 | Iterate over columns and rows (selected by label from label column) without overwriting | <p>I want to do the following thing:</p>
<ol>
<li>Get min and max for every measurement column within the same label (range of rows)</li>
<li>Define a range for the interesting values (e.g. maximum * 0.6 up to maximum)</li>
<li>Check for every measurement column within the same label if value lies in this interval (=Tr... | <p>Let us not use for-loop instead we can use a vectorized/fast approach, here is the annotated code:</p>
<pre><code># select the measurement cols
cols = df.filter(like='Measure')
# groupby label and find the max value per grp
max_ = cols.groupby(df['Label']).transform('max')
# Create a boolean condition
cond = c... | python|pandas | 1 |
351,565 | 72,906,207 | How to Rotate Points from a Meshgrid and Preserve Orthogonality | <p>When I use a rotation matrix to rotate points from a meshgrid, the points are no longer orthogonal. Using NumPy, how do I keep the gridlines perpendicular when rotating?</p>
<p><a href="https://i.stack.imgur.com/7AjLe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7AjLe.jpg" alt="enter image desc... | <p>How did you checked that the points are not orthogonal?</p>
<p>If you just look at the plot, and it doesn't looks like, try setting the aspect ratio equal for both axis with</p>
<pre><code>plt.gca().set_aspect('equal')
</code></pre>
<p><a href="https://i.stack.imgur.com/SFpXK.png" rel="nofollow noreferrer"><img src... | python|numpy|rotational-matrices | 2 |
351,566 | 73,018,827 | Pandas apply string format using multiple columns | <p>I have the following dataframe with two columns:</p>
<pre><code>data = pd.DataFrame(data={'fname': ['john', 'mike'],
'col2': ['my name is {name}, and today is {day}', 'my name is {name}, and today is {day}']},
index=pd.Series([1, 2], name='index'))
fname ... | <p>You mean:</p>
<pre><code>data.apply(lambda x: x['col2'].format(name=x['name'], year=2022), axis=1)
</code></pre>
<p>you can also do:</p>
<pre><code>[s.format(name=name, year=2022) for s,name in zip(data['col2'], data['col1'])]
</code></pre> | pandas|string|apply | 0 |
351,567 | 73,025,787 | Pandas explode on separator but retain suffix in both new records | <p>I have the current code that splits records if a / occurs in the value but I want it to be cloned and retain the non med or 65+ suffix (best method to identify the suffix is probably by using the first space as a delimiter). The Desired out is what I want the output to look like. Current Out is what the code below i... | <p>Given:</p>
<pre><code> col1 col2 col3 col4
0 29 312889.0 159834.15 5455/5456 (non med)
1 56 4168.0 2984.15 7065/7066 65+
2 26 45405.0 21013.45 5113.0
</code></pre>
<p>Doing:</p>
<pre><code># Split them into separate columns on the first space:
d... | python|pandas | 0 |
351,568 | 73,101,764 | Cannot load checkpoints | <p>I taught a model (<a href="https://colab.research.google.com/drive/1ysEKrw_LE2jMndo1snrZUh5w87LQsCxk#forceEdit=true&sandboxMode=true" rel="nofollow noreferrer">tensorflow tutorial</a>) in Jupyter then saved it, then succesfully loaded it back (kernel was restarted). Here's the code:</p>
<pre><code># Directory wh... | <p>You should be able to load the checkpoints according to the <a href="https://www.tensorflow.org/tutorials/keras/save_and_load?hl=en#manually_save_weights" rel="nofollow noreferrer">TensorFlow documentation</a> like this:</p>
<pre><code>checkpoint_num = 10
model.load_weights("/home/charlie-chin/william_model/tra... | tensorflow|keras | 2 |
351,569 | 72,944,386 | Completely Flatten JSON with nested list using Python Pandas | <p>Here is the example JSON:</p>
<pre><code>{
"ApartmentBuilding":{
"Address":{
"HouseNumber": 5,
"Street": "DataStreet",
"ZipCode": 5100
},
"Apartments":[
{
... | <p>Here is another way to do it using Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer">json_normalize</a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer">explode</a>:</p>
<pre class="lang... | python|json|pandas|dataframe | 1 |
351,570 | 73,126,603 | Correlation of every pandas row with another pandas dataframe as a new column | <p>Assuming I have the following <code>df</code>:</p>
<pre><code>Company Apples Mangoes Oranges
Amazon 0.75 0.6 0.98
BellTM 0.23 0.75 0.14
Cadbury 0.4 0.44 0.86
</code></pre>
<p>and then another data frame called <code>vendor</code>:</p>
<pre><code>Company Apples Ma... | <p>You need to use a Series in corrwith.</p>
<p>You can use:</p>
<pre><code>df.set_index('Company').corrwith(vendor.set_index('Company').loc['Deere'], axis=1)
</code></pre>
<p>output:</p>
<pre><code>Company
Amazon 0.779560
BellTM -0.376945
Cadbury 0.980927
dtype: float64
</code></pre>
<p>With your code:</p>
<... | python|pandas | 2 |
351,571 | 72,905,562 | Pytorch, how to get the parameters of my network | <p>I have a question about getting all parameters of the network. My network is defined as follow:</p>
<pre><code>activation = nn.ReLU()
class OneInputBasis(nn.Module):
def __init__(self):
super().__init__()
bo_b = True
bo_last = False
self.l1 = nn.Linear(200, 100, bias = b... | <p>Calling <code>self.set_lay.append(OneInputBasis())</code> with the instantiation of <code>node</code> does not register the fully-connected layers</p>
<pre><code> self.l1 = nn.Linear(200, 100, bias = bo_b).to(device)
self.l4 = nn.Linear(100, 100, bias = bo_last).to(device)
</code></pre>
<p>to the instance <code>fn... | pytorch | 0 |
351,572 | 73,003,747 | Possible bug with inf or too large values? | <p>I'm trying to train a neural network with keras and tesorflow. As usual, I replace -np.inf and np.inf values with np.nan to later run a dropna sequence and clear all that wrong data such as:</p>
<pre><code> Data.replace([np.inf, -np.inf], np.nan, inplace=True)
Data.dropna(inplace=True)
</code></pre>
<p>However, aft... | <p>Instead of specifically looking for infinities, just throw out data which is out of bounds, something like this:</p>
<pre><code>bad = Data < -1e20 | Data > 1e20 # use whatever your valid range is
Data.drop(bad.any('columns'), inplace=True)
</code></pre> | python|pandas|numpy|infinity|float32 | 1 |
351,573 | 72,932,218 | How to create DataFrame with 100 values consisting of 10 elementary numbers in Python Pandas? | <p>I need to create Data Frame in Python Pandas with 100 rows with random values consisting of 10 elementary numbers.
So as a result I need something like below "col1" has to be as date type string:</p>
<pre><code>col1
---------
1233459857
8463746781
9084756289
...
</code></pre>
<p>How can I do that in python... | <p>To ensure that values beginning with one or more zeros are properly formatted, we can create values of data type string with zero padding to 10 places:</p>
<pre class="lang-py prettyprint-override"><code>rng = np.random.default_rng()
df = pd.DataFrame(pd.Series(rng.integers(0, 10**10, size=100)).apply(lambda n: f'{n... | python|pandas|random | 2 |
351,574 | 73,071,399 | How to bound the output of a layer in pytorch | <p>I want my model to output a single value, how can I constrain the value to (a, b)?
for example, my code is:</p>
<pre class="lang-python prettyprint-override"><code>class ActorCritic(nn.Module):
def __init__(self, num_state_features):
super(ActorCritic, self).__init__()
# value
self.criti... | <p>Use an activation function on the final layer that bounds the outputs in some range, then normalize to your desired range. For instance, sigmoid function bound the output in the range [0,1].</p>
<pre><code>output = torch.sigmoid(previous_layer_output) # in range [0,1]
output_normalized = output*(b-a) + a # ... | pytorch|reinforcement-learning | 1 |
351,575 | 72,982,600 | Pandas group by one column and fill up another column | <p>I have the following dataframe with two columns:</p>
<pre><code>data = [['A', '3ykf'], ['A', '3ykf'], ['A', ], ['B', ], ['B', '6jbk'], ['B', ], ['B', ], ['C', ], ['C', ]]
df = pd.DataFrame(data, columns=['column1', 'column2'])
column1 | column2
A "3ykf"
A
A "3ykf"
... | <p>You can fill with the first avaiable value:</p>
<pre><code>df.column2 = df.groupby('column1').column2.transform('first')
</code></pre>
<p>Result:</p>
<pre><code> column1 column2
0 A 3ykf
1 A 3ykf
2 A 3ykf
3 B 6jbk
4 B 6jbk
5 B 6jbk
6 B 6jbk
7 C ... | python|pandas|dataframe|pandas-groupby | 1 |
351,576 | 73,145,739 | computing cosine similarity in vectorized operation | <p>I am trying to compute cosine similarity between 2D-array.</p>
<p>Let's say I have a dataframe whose shape is (5,4)</p>
<pre><code>df = pd.DataFrame(np.random.randn(20).reshape(5,4), columns=["ref_x", "ref_y", "alt_x", "alt_y"])
df
ref_x ref_y alt_x alt_y
0 2.523641 ... | <p>use cosine_similarity from sklearn</p>
<pre><code>from sklearn.metrics.pairwise import cosine_similarity
df = pd.DataFrame(np.random.randn(20).reshape(5,4), columns=["ref_x", "ref_y", "alt_x", "alt_y"])
co_sim = cosine_similarity(df.to_numpy())
pd.DataFrame(co_sim)
</code></p... | python|pandas|vectorization|cosine-similarity | 1 |
351,577 | 73,029,888 | How to select rows multiple times from a data frame if it appears multiple times in a list, without changing the column order? | <p>Suppose I have a dataframe</p>
<pre><code>data = {'Date': ['22-08-2021', '12-09-2021', '02-10-2021', '22-11-2021'], 'ID': ['A', 'B', 'C', 'O'], 'Item':['Apple','Banana','Carrot', 'Orange'], 'Cost':[10, 12, 15, 13]}
dataframe = pd.DataFrame(data)
dataframe
</code></pre>
<p><a href="https://i.stack.imgur.com/mC7gk.png... | <p>You can use <code>.reset_index()</code> to add the index as a normal column, then <code>set_index()</code> and <code>.loc[]</code> to fetch rows by ID. Then once you know the original indexes of the rows you want, you can use <code>.loc[]</code> again to get them.</p>
<pre><code>>>> orig_indexes = dataframe... | python|pandas|dataframe|csv|data-preprocessing | 1 |
351,578 | 73,075,341 | I cant retrieve values by index in filtered DataFrame | <p>Since the last time I posted this question I got a comment saying that my description is too complicated, this now is a simplified version:
(here you can find the more complicated question -> <a href="https://stackoverflow.com/questions/73070316/pandas-dataframe-i-cant-retrieve-values-by-index-after-filtering-df"... | <p>You did not post your dataframe so I cannot simulate.</p>
<p>Try instead using double square brackets:</p>
<pre><code>df4 = df4[['Name Block DWG']]
</code></pre> | pandas|dataframe|indexing|filter|series | 0 |
351,579 | 73,043,185 | Is there a way to specify the output dimension of pytorch least square solution? | <p>With <code>3 by n by k</code> tensor <code>A</code> and <code>1 by k by m</code> tensor <code>x</code> we can have<code>Ax = B</code> where <code>B</code> has shape of <code>[3, n, m]</code></p>
<p><code>torch.linalg.lstsq(A, B)</code> returns a <code>3 x k x m</code>tensor as solution. Is there a way to find the <c... | <p>The difference between <code>torch.lingalg.lstsq</code> and <code>torch.matmul</code> is that <code>torch.lingalg.lstsq</code> computes its answer based on batch-wise operation while <code>torch.matmul</code> does not.
And your <code>1 by k by m</code> solution will be non-batch wise solution or some kind of global ... | python|pytorch|linear-algebra|tensor | 1 |
351,580 | 73,088,274 | How to split array without separator comma in Python and fit to row csv | <p>I had an output array without comma separator, only separated by space, when I convert to pandas dataframe the array not split to any row, just stuck in 1 row</p>
<p>The output of array looks like this:</p>
<pre><code>pred_ct = [217.769 228.838 238.459 225.317 196.812 221.241 214.605 205.918 206.278
216.028 234.919... | <p>Don't focus so much on the comma separator. Pay more attention to what kinds of objects you produce. Things like <code>[],</code> are display indicators.</p>
<p>Lets make a simple 1d array:</p>
<pre><code>In [2]: x = np.arange(10)
In [3]: x
Out[3]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [4]: print(x)
[0 1 2 3 4 ... | python|arrays|pandas|numpy|export-to-csv | 1 |
351,581 | 72,879,617 | Python: Split using lambda and keeping second value | <p>I have the following df:</p>
<pre><code>pd.DataFrame({'Jugador': {0: 'A. Gignac', 1: 'N. Ibáñez'},
'Equipo': {0: 'Tigres UANL', 1: 'Pachuca'},
'Equipo durante el período seleccionado': {0: 'Tigres UANL', 1:
'Pachuca'})
</code></pre>
<p>I am trying to split the Jugador colum... | <p>The error is causing as you are trying to find the <code>1</code> index of the whole name. If there is no any surname, <code>1</code> index will be out of range. So, it is the reason for the error.</p>
<p>Try this:</p>
<pre><code>df.Jugador = df.Jugador.apply(lambda name: name.split(' ')[-1])
</code></pre> | python|pandas | 1 |
351,582 | 72,985,106 | Cumulative summing values in a dataframe based on a value in another dataframe | <p>I have the two dataframes: the first shows a customer's orders with the product they ordered, the order date, and the quantity they ordered, the second shows a master list of all orders placed by all customers.</p>
<pre><code>customer_id product_id order_date quantity
1 001 1/5/2022 10
1 ... | <pre><code> import pandas as pd
df1 = pd.DataFrame(
data={
"customer_id": [1, 1],
"product_id": ["001", "002"],
"order_date": ["1/5/2022", "1/5/2022"],
"quantity": [10, 10]... | python|pandas | 0 |
351,583 | 73,111,556 | Convert dictionary values inside a column of a Dataframe to new separate columns | <p>I have a csv file, and I have put it in a pandas dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>no</th>
<th>data</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>{"age": "30", "sex": "male"}</td>
</tr>
<tr>
<td>2</td>
<td>{"age"... | <p>We need to convert the <code>dict</code> like column to <code>dict</code> with <code>ast</code></p>
<pre><code>import ast
df = df.join(df.data.apply(lambda x : pd.Series(ast.literal_eval(x))))
df
Out[69]:
no data age sex
0 1 {"age": "30", "sex": &... | python|pandas|dataframe|csv|dictionary | 0 |
351,584 | 73,051,641 | Difference between Jupyter and Terminal in the same Kernel | <p>I'm trying to <code>import tensorflow as ts</code> in my script. While everything is fine in a Notebook, when I try to recreate the same script in a .py file the import returns the following, popular message:</p>
<p><code>ModuleNotFoundError: No module named 'tensorflow'</code></p>
<p>Note that both Jupyter and term... | <p>Make sure your <code>pyenv</code> installation doesn't interfere with the conda environments. Pyenv can overrule which python installation is used even if the conda environment has picked another. In my case it was the reason. Jupyter Notebook wasn't affected by pyenv. There are two solutions:</p>
<ol>
<li>Remove <c... | python|tensorflow|jupyter-notebook | 1 |
351,585 | 73,140,886 | UnicodeEncodeError: 'ascii' codec can't encode characters in position 55-56: ordinal not in range(128) | <p>I'm trying huggingface models on aws lambda but its throwing an error</p>
<p>Here's my code.</p>
<pre><code>import json
from transformers import pipeline
nlp = pipeline("zero-shot-classification")
def handler(event, context):
print(event['text'])
sequence = "Who are you voting for in 2020?&q... | <p>adding <code>PYTHONIOENCODING=utf8</code> as an environment variable and changing the line</p>
<p><code>"body": nlp(sequence, candidate_labels)[0]</code></p>
<p>to</p>
<p><code>"body": nlp(sequence, candidate_labels)</code></p>
<p>worked.</p> | python|amazon-web-services|aws-lambda|huggingface-transformers | 0 |
351,586 | 72,865,730 | Pandas DataFrame: update all values in all columns, based on condition | <p>I have 102 columns and I want to check all their values. If their values are greater than 100,000: I want to subtract 4294967295 from these values and then add 1 to them</p>
<p>I did it but for one column like this:</p>
<p><code>df.loc[df['12:00AM'] > 100000, '12:00AM'] = (4294967295 - df.loc[df['12:00AM'] > 1... | <p>I did it like this: where # A-B = -B+A</p>
<pre><code>df[df> 100000] = -1*df[df> 100000] + 4294967295+1
</code></pre> | python|pandas|dataframe | 1 |
351,587 | 73,158,037 | Capitalizing every first word after a period in a Pandas column | <p>I'm trying to capitalize the first letter (and ONLY the first one) of a new sentence in some body text stored in a Pandas DF.</p>
<p>Example: my dataframe has a Description column which may contain text like:</p>
<blockquote>
<p>This product has several different features. <strong>it</strong> is also <strong>VERY</s... | <p>re.findIter will return all the matches of a regex (in our case the .)</p>
<p>and you can just use to lower before it.</p>
<p>example (may not work as is didn't have an IDE handy):</p>
<pre class="lang-py prettyprint-override"><code>mystring = "SOOOme wEirdly capiTalised STRINg. Followed By CHARACTERS"
mys... | python|pandas|string | 0 |
351,588 | 73,069,857 | View column names and their indices in pandas | <p>I have a large dataset where I need to remove a sizeable chunk of columns, so I want to view the list of columns I have and their indices and then pass them in to a drop command with slice:</p>
<p><code>df.drop(df.columns[25:100], axis=1, inplace=True)</code></p>
<p>However I need to first see the indices for all th... | <p>Perhaps this could help:</p>
<pre><code>{k:i for i,k in enumerate(df.columns)}
</code></pre>
<p>This will produce a dictionary of each column and its index.
Additionally, if you want to query the index of specific columns:</p>
<pre><code>[list(df.columns).index(col) for col in COLUMN_NAMES]
</code></pre>
<p>Where CO... | python|pandas | 0 |
351,589 | 72,848,450 | python split map into rows | <p>I have data as below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">ID</th>
<th style="text-align: left;">country</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">01</td>
<td style="text-align: left;">{"23":1,"45":1,"65&q... | <pre><code>df = pd.DataFrame(data={'ID':['01', '02','03'], 'country':[{"23":1,"45":1,"65":1}, {"23":1,"48":1}, {"65":1}]})
df
</code></pre>
<p>Dataframe:</p>
<pre><code> ID country
0 01 {'23': 1, '45': 1, '65': 1}
1 02 {'23': 1, '48': 1}
2 03 {'65... | python|pandas|dataframe | 2 |
351,590 | 72,859,636 | Select by first index of multiindex (Pandas DataFrame) | <p>I have a DataFrame with index (a, b)</p>
<pre><code>df = pd.DataFrame({'a' : [1, 2, 3, 1], 'b' : [11, 11, 11, -7], 'val' : [10, 19, 24, 12]})
df.set_index(['a', 'b'], inplace=True)
</code></pre>
<pre><code>a | b | val
1 | 11 | 10
2 | 11 | 19
3 | 11 | 24
1 | -7 | 12
</code></pre>
<p>I'd like to pick from it only the... | <p>There are 2 options to pick the rows with <code>b==11</code>.</p>
<ol>
<li>As suggested by @ShubhamSharma, you can use <code>xs</code> but you lost the level <code>b</code>:</li>
</ol>
<pre><code>>>> df.xs(11, level=1)
val
a
1 10
2 19
3 24
</code></pre>
<ol start="2">
<li>You can also use <cod... | pandas|dataframe | 1 |
351,591 | 73,041,062 | NumPy ndarray of ndarray of float64 not flattening | <p>I have a pandas dataframe with a column called 'corr'. Each row contains an ndarray of float64. The following code is giving me issues:</p>
<pre><code>import pandas as pd
experimentDataFrame = pd.DataFrame({'corr': [np.array([1.0,2.0]),np.array([3.0,4.0]),np.array([5.0,6.0])]})
corr = experimentDataFrame['corr'].t... | <p>The problem is that <code>experimentDataFrame['corr'].to_numpy(copy=True)</code> is <strong>already flat</strong>, the shape is <code>(35,)</code>. You have a <code>dtype=object</code> array.</p>
<p>You just want something like:</p>
<pre><code>corr = np.concatenate([arr.ravel() for arr in experimentDataFrame['corr']... | python|numpy|numpy-ndarray | 1 |
351,592 | 73,066,883 | Display HTML table from xml file over web browser without using any software or installation on unix | <p>I am a very new to HTML and javascript. Have come across many questions with regard to my problem and after struggling a lot to find a solution, I am posting this question.</p>
<p><strong>Problem statment:</strong></p>
<p>I have an xml which I am trying to convert it to HTML so that I can display it over web browser... | <p>This should solve your issue (as asked), using pandas:</p>
<pre><code>import pandas as pd
xml_data = '''<?xml version="1.0" encoding="UTF-8"?>
<chapter name="ndlkjfidm" date="dfhkryi">
<edge name="nnn" P="ffgnp" V="0.825" T=&qu... | javascript|python|html|pandas|xml | 5 |
351,593 | 10,609,313 | represent numpy ellipsis | <p>I know how to slice array with numpy, for example</p>
<pre><code>v[1, :, :]
</code></pre>
<p>now I want a function taking as input the slice <code>(1,1,None)</code> and returning <code>v[1,:,:]</code></p>
<p>the problem is that I don't know how to represent ellipses</p> | <p>You can represent ellipses with <code>Ellipsis</code>.</p>
<p>It is mentioned <a href="http://docs.python.org/release/2.5.2/lib/bltin-ellipsis-object.html" rel="noreferrer">here</a></p> | python|numpy|slice | 5 |
351,594 | 3,315,894 | Optimal extraction of columns from numpy matrix | <p>Say I have a numpy matrix like so:</p>
<pre><code>[[ x1, x2, x3, ... ],
[ y1, y2, y3, ... ],
[ z1, z2, z3, ... ],
[ 1, 1, 1, ... ]]
</code></pre>
<p>From which I want to extract a list of lists like so:</p>
<pre><code>[[x1, y1, z1], [x2, y2, z2], [x3, y3, z3], ... ]
</code></pre>
<p>What is the most optima... | <p>Why not remove the last row before the transpose?</p>
<pre><code>m[:3].T.tolist()
# ^^^^^^^^^ optional
</code></pre>
<p>Micro-benchmark shows this method is faster than yours by 61%, and if you don't convert it into a list of list it is 45 times faster, for a 100×4 matrix.</p>
<pre><code>$ python2.5 -m... | python|optimization|numpy | 3 |
351,595 | 3,228,361 | Using PIL and NumPy to convert an image to Lab array, modify the values and then convert back | <p>I am trying to convert a PIL image into an array using NumPy. I then want to convert that array into Lab values, modify the values and then convert the array back in to an image and save the image. I have the following code:</p>
<pre><code>import Image, color, numpy
# Open the image file
src = Image.open("face-him... | <p>Without having tried it, scaling errors are common in converting colors:<br>
RGB is bytes 0 .. 255, e.g. yellow [255,255,0],
whereas <code>rgb2xyz()</code> etc. work on triples of floats, yellow [1.,1.,0].<br>
(<code>color.py</code> has no range checks: <code>lab2rgb( rgb2lab([255,255,0]) )</code> is junk.)</p>
<p>... | python|colors|numpy|python-imaging-library|color-space | 10 |
351,596 | 3,584,243 | Get the position of the largest value in a multi-dimensional NumPy array | <p>How can I get get the position (indices) of the largest value in a multi-dimensional NumPy array?</p> | <p>The <a href="http://www.scipy.org/Numpy_Example_List#head-e2829234dedbedccc333d32ee2738c28777f2e94" rel="noreferrer"><code>argmax()</code></a> method should help.</p>
<p><strong>Update</strong></p>
<p>(After reading comment) I believe the <code>argmax()</code> method would work for multi dimensional arrays as well... | python|arrays|indexing|numpy | 190 |
351,597 | 70,696,983 | how to Change duplicated rows with blank, keep first in range of columns in the dataframe pandas? | <p>Is there a way to change value of duplicated rows to blank in range of columns ? I have 20 const columns and then number and names of columns are dynamically changed. For specific columns i used code below:</p>
<pre><code> remove2 = lambda x: df[x].duplicated(keep='first')
df.loc[remove2('PKW'), 'PKW'] = ... | <p>IIUC:</p>
<pre><code>df.update(df.iloc[:, -20:].mask(df.iloc[:, -20:]
.apply(lambda x: x.duplicated())).fillna(''))
</code></pre> | python|arrays|pandas|dataframe | 0 |
351,598 | 70,716,371 | Using Series to group data and use as column names | <p>Here is the data frame I have</p>
<pre><code> Temp Time
Date
20220110 65 1
20220111 55 1
20220112 32 1
20220110 66 2
20220111 54 2
20220112 30 2
20220110 68 3
20220111 50 3
20220112 28 3
</code></pre>
<p>What I am looking for is... | <p>You can also use <code>pivot</code>:</p>
<pre><code>out = df.reset_index().pivot('Date','Time','Temp')
</code></pre>
<p>Output:</p>
<pre><code>Time 1 2 3
Date
20220110 65 66 68
20220111 55 54 50
20220112 32 30 28
</code></pre> | python|pandas|dataframe|pandas-groupby | 2 |
351,599 | 70,737,778 | groupby function returns undesired result for pandas dataframe | <p>so I have this dataframe here</p>
<pre><code>>>> df
uniprot_id protein_group protein_family protein_subfamily
0 Q8TAS1 Other KIS NaN
1 P35916 TK VEGFR NaN
2 Q96SB4 CMGC SRPK NaN
3 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> with remove missing values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dropna.html" rel="nofollow noreferrer"><co... | python|python-3.x|pandas|dataframe | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.