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 |
|---|---|---|---|---|---|---|
4,000 | 53,553,558 | Subset pandas dataframe on multiple columns based on values from another dataframe | <p>I have two dataframes as</p>
<pre><code>import pandas as pd
points = pd.DataFrame({'player':['a','b','c','d','e'],'points':[2,5,3,6,1]})
matches = pd.DataFrame({'p1':['a','c','e'], 'p2':['c', 'b', 'd']})
</code></pre>
<p>I want to retain only those rows from dataframe matches where both p1 and p2 have points great... | <p>I would avoid the joins in this case and write it like this:</p>
<pre><code>scorers = points.query('points > 2').player
matches.query('p1 in @scorers and p2 in @scorers')
</code></pre>
<p>I think it's more readable.</p>
<p>It feels a little silly to benchmark on such a small example, but on my machine this met... | python|python-3.x|pandas|performance|dataframe | 2 |
4,001 | 17,449,701 | to convert a list to a 2D matrix in python | <pre><code>arr2=[0]*(x^2) # x is the length of the list data
for i in range(x):
arr2[i]=data[i].split(',')#data is a list like:['1,2','3,4']
arr2=np.array(arr2)
A=np.asmatrix(arr2)
print A.I
</code></pre>
<p>This is giving error as setting an array element with a sequence</p> | <p>Something like this:</p>
<pre><code>>>> data = ['1,2','3,4']
>>> arr2=[ map(float,x.split(',')) for x in data]
>>> arr2 = np.asarray(arr2)
>>> A = np.asmatrix(arr2)
>>> A.I
matrix([[-2. , 1. ],
[ 1.5, -0.5]])
</code></pre> | python|numpy | 0 |
4,002 | 16,986,317 | Multipying and adding inside of a too large array | <p>I have an array A that is of the shape (M,N) now I'd like to do the operation</p>
<p><code>R = (A[:,newaxis,:] * A[newaxis,:,:]).sum(2)</code></p>
<p>which should yield an (MxM) array. Now the problem is that the array is quite large and I get a Memory error, because the MxMxN array won't fit into memory.</p>
<p>... | <p>I'm not sure how large you arrays are but the following is equivalent:</p>
<pre><code>R = np.einsum('ij,kj',A,A)
</code></pre>
<p>And can be quite a bit faster and is much less memory intensive:</p>
<pre><code>In [7]: A = np.random.random(size=(500,400))
In [8]: %timeit R = (A[:,np.newaxis,:] * A[np.newaxis,:,:]... | python|numpy | 7 |
4,003 | 16,617,973 | why isn't numpy.mean multithreaded? | <p>I've been looking for ways to easily multithread some of my simple analysis code since I had noticed numpy it was only using one core, despite the fact that it is supposed to be multithreaded. </p>
<p>I know that numpy is configured for multiple cores, since I can see tests using numpy.dot use all my cores, so I ju... | <blockquote>
<p>I've been looking for ways to easily multithread some of my simple analysis code since I had noticed numpy it was only using one core, despite the fact that it is supposed to be multithreaded.</p>
</blockquote>
<p>Who says it's supposed to be multithreaded?</p>
<p><code>numpy</code> is primarily des... | python|multithreading|performance|numpy | 29 |
4,004 | 22,099,246 | Numpy: evaluation of standard deviation of values above/below the average | <p>I want to calculate the standard deviation for values below and above the average of a matrix of n_par parameters and n_sample samples. The fastest way I found so far is:</p>
<pre><code>stdleft = numpy.zeros_like(mean)
for jpar in xrange(mean.shape[1]):
stdleft[jpar] = p[p[:,jpar] < \
m... | <p>Pandas is your friend. Convert your matrix in pandas Dataframe and index the Dataframe logically. Something like this</p>
<pre><code>mat = pandas.DataFrame(p)
</code></pre>
<p>This creates a DataFrame from original numpy matrix <code>p</code>. Then we compute the column means for the DataFrame.</p>
<pre><code>m =... | python|optimization|numpy|standards|deviation | 2 |
4,005 | 55,378,909 | How to preprocessing sequential data for 2D-CNN | <p>Is there any way to transform sequential data to 2-dimensional data in order to use it for a common CNN?</p>
<p>My dataset Looks like: 14,40,84,120,38,29,395,58,153,...</p>
<p>But I need a 2-dimensional representation for that. Is there any established algorithm for that purpose?</p> | <p>Are you really sure that a CNN is what you want? It might not be the best choice for sequential data. If you want to learn more about alternative ways to deal with sequential data (like time series), I recommend reading the paper "<a href="https://arxiv.org/abs/1602.01711" rel="nofollow noreferrer">The Great Time Se... | tensorflow|machine-learning|neural-network|conv-neural-network | 0 |
4,006 | 55,286,449 | How to calculate the number of days between stages in this df Python Pandas? | <pre><code>df = pd.DataFrame({'Campaign ID':[48464,48464,48464,48464,26380,26380,22676,39529,39529,46029,46029,46029,17030,46724,46724,39379,39379,39379],
'Campaign stage':["Lost","Developing","Discussing","Starting","Discussing", "Starting","Developing", "Discussing","Starting","Developing", "Discussing","Startin... | <pre><code>df['Campaign Date'] = pd.to_datetime(df['Campaign Date'],format='%m/%d/%Y')
compare= {}
for ids,gp in df.groupby('Campaign ID'):
try:
compare[ids]= gp.loc[gp['Campaign stage']=='Discussing']['Campaign Date'].iloc[0] - gp.loc[gp['Campaign stage']=='Starting']['Campaign Date'].iloc[0]
except:
... | python|pandas|dataframe|pandas-groupby | 0 |
4,007 | 55,182,326 | Understanding ResourceVariables in tensorflow | <p>From <a href="https://stackoverflow.com/questions/40817665/whats-the-difference-between-variable-and-resourcevariable-in-tensorflow">here</a></p>
<blockquote>
<p>Unlike tf.Variable, a tf.ResourceVariable has well-defined semantics. Each usage of a ResourceVariable in a TensorFlow graph adds a read_value operation... | <p>Two remarks:</p>
<ol>
<li><p>The order in which you write variables/ops in the first argument of <code>sess.run</code> does not mean that is the order of execution.</p></li>
<li><p>If something worked in one step it does not mean it will work if you add loads of parallelism.</p></li>
</ol>
<p>The answer to the que... | python|tensorflow|deep-learning | 2 |
4,008 | 55,575,061 | Vectorizing consequential/iterative simulation (in python) | <p>This is a very general question -- is there any way to vectorize consequential simulation (where next step depends on previous), or any such iterative algorithm in general?</p>
<p>Obviously, if one need to run M simulations (each N steps) you can use <code>for i in range(N)</code> and calculate M values on each ste... | <p>Perhaps <a href="https://en.wikipedia.org/wiki/Multigrid_method" rel="nofollow noreferrer">Multigrid in time methods</a> can give some improvements.</p> | python|numpy|numerical-computing | 0 |
4,009 | 56,764,823 | AttributeError: module 'torch' has no attribute 'hub' | <pre><code>import torch
model = torch.hub.list('pytorch/vision')
</code></pre>
<p>My pytorch version is 1.0.0, but I can't load the hub, why is this?</p> | <p>You will need <code>torch >= 1.1.0</code> to use <code>torch.hub</code> attribute.</p>
<p>Alternatively, try by downloading <a href="https://github.com/pytorch/pytorch/blob/master/torch/hub.py" rel="nofollow noreferrer">this</a> <code>hub.py</code> file and then try below code:</p>
<pre><code>import hub
model =... | pytorch | 3 |
4,010 | 56,650,180 | Where is the CUDA toolkit located on Ubuntu? | <p>I installed Nvidia's 375 driver and CUDA 8.0 on Ubuntu 16.04 from <a href="https://developer.nvidia.com/cuda-80-ga2-download-archive" rel="nofollow noreferrer">Nvidia's .deb package</a>. I want to build TensorFlow with GPU support. This is the output of TensorFlow's <code>configure</code> script:</p>
<pre class="la... | <p>The .deb package I downloaded only installed the repository's metadata. As the <a href="https://developer.download.nvidia.com/compute/cuda/8.0/secure/Prod2/docs/sidebar/CUDA_Quick_Start_Guide.pdf?pMqazYtU3YrzLLpA6_pwd14SOox0Yj_A2Vr5TteRSOCfVSHzRqUHx52uMuPSoWM0TLndXavlSb4zjvqOX8q6s3mLYEtUICWZ45aQoY7hSS-aR2rYl9-q7QguS... | linux|tensorflow|cuda|installation|ubuntu-16.04 | 1 |
4,011 | 56,604,264 | find duplicate rows containing various types of lists (of lists) in pandas dataframe | <p><strong>Background</strong></p>
<p>I have the following <code>df</code> that contains a mix of list types</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Size' : [[[['small', 'small', 'big', 'big']]], [['big', 'small','small']], ['big'], ['big']],
'ID': [1,2,3,3],
'Anim... | <pre><code>df.loc[df.astype(str).drop_duplicates().index]
</code></pre> | python-3.x|pandas|list|duplicates | 0 |
4,012 | 25,766,831 | Numpy structured arrays: string type not understood when specifying dtype with a dict | <p>Here's what happens if I initialize a struct array with the same field names and types in different ways:</p>
<pre><code>>>> a = np.zeros(2, dtype=[('x','int64'),('y','a')])
>>> a
array([(0L, ''), (0L, '')],
dtype=[('x', '<i8'), ('y', 'S')])
</code></pre>
<p>So initializing with list of tuple... | <p>As a workaround, it works if you specify the string width:</p>
<pre><code>>>> mdtype = dict(names=['x','y'],formats=['int64','a1'])
>>> np.dtype(mdtype)
dtype([('x', '<i8'), ('y', 'S1')])
</code></pre>
<p>Probably related to <a href="https://stackoverflow.com/questions/25219344/numpy-set-value... | python|numpy|structured-array | 3 |
4,013 | 26,260,127 | Numpy only way to read text file and keep comments | <p>Here is a minimal working example of a text file:</p>
<pre><code># A B C
1 7 9
7 2 10
10 20 30
</code></pre>
<p>Loading this file using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow"><code>numpy.loadtxt</code></a> will discard the commented line. Is there a nice way... | <p>Looks like the comment character doesn't bother <code>genfromtxt</code>. It can still treat that 1st line as a source for names, and load the data as a structured array.</p>
<pre><code>In [189]: s="""\
# A B C
1 7 9
7 2 10
10 20 30
"""
In [190]: X=np.genfromtxt(s.splitlines(),names=True)
In [191]: X
Out[191]:
arr... | python|numpy | 3 |
4,014 | 66,891,947 | Tensorflow error can't figure out what it is | <p>I was doing tensorflow object detection project to detect sign languages using google colab<br />
I was getting tensorflow has no attribute gflie error and I found that i have to downgrade to tensorflow 1<br />
so I ran <code>!pip install tensorflow==1.13.0rc1</code> in my colab cell<br />
But now when I run the sam... | <p>In <code>generate_tfrecords.py</code>, remove line 61 and change line 62 to <code>label_map_dict = label_map_util.get_label_map_dict(args.labels_path)</code> and if you have any line that says <code>fine_tune_checkpoint_version</code> in the <code>pipeline.config</code> file, delete that and try</p> | python|tensorflow|object-detection | 0 |
4,015 | 67,042,817 | append sequence number with padded zeroes to a series using padas | <p>I have a dataframe like as shown below</p>
<pre><code>df = pd.DataFrame({'person_id': [101,101,101,101,202,202,202],
'login_date':['5/7/2013 09:27:00 AM','09/08/2013 11:21:00 AM','06/06/2014 08:00:00 AM','06/06/2014 05:00:00 AM','12/11/2011 10:00:00 AM','13/10/2012 12:00:00 AM','13/12/2012 11... | <p><strong>Update 2:</strong> Just realized my previous answers also added 100000 to the first index. Here is a version that uses <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><strong><code>GroupBy.transform()</code></strong></a> to ... | python|pandas|dataframe|pandas-groupby|series | 2 |
4,016 | 67,160,127 | Return value in referencing column of dataframe with apply/lambda function | <h3>Problem</h3>
<p>I have the following dataframe</p>
<pre class="lang-python prettyprint-override"><code>p = {'parentId':['071cb2c2-d1be-4154-b6c7-a29728357ef3', 'a061e7d7-95d2-4812-87c1-24ec24fc2dd2', 'Highest Level', '071cb2c2-d1be-4154-b6c7-a29728357ef3'],
'id_x': ['a061e7d7-95d2-4812-87c1-24ec24fc2dd2', 'd2b... | <p>You can use <code>.map()</code>:</p>
<pre><code>mapping = dict(zip(df["id_x"], df["name"]))
df["Parent_name"] = df["parentId"].map(mapping).fillna("no sub-dependency")
print(df)
</code></pre>
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code> ... | python|pandas|function|dataframe|lambda | 1 |
4,017 | 67,087,138 | Joining multiple DateTime columns into one Columns (Python) | <p>I am trying to gather all my date time infromation into only one columns. Right now I have a columns for each period over the span of 6 months , however in order to do a Time series Analysis , I was trying to gather all the date time into a single columns.</p>
<p>Here is what I tired:</p>
<pre><code> df['Dates'] = d... | <p>IIUC use:</p>
<pre><code>Dates = df[["1 Month Date","2 Month Date","3 Month Date","4 Month Date","5 Month Date","6 Month Date"]].apply(pd.Series.explode).sum(axis=1)
</code></pre> | python|pandas|datetime|typeerror|keyerror | 0 |
4,018 | 47,262,654 | How to select identical rows from a pandas dataframe along with null | <p>I'm new to pandas and I'm having problem with row selections from dataframe.</p>
<p>Following is my DataFrame :</p>
<pre><code> Index Column1 Column2 Column3 Column4 Column5
0 1234 500 NEWYORK NY NaN
1 5678 700 AUSTIN TX 5678956010
2 1234 300 NE... | <p>I think you need 2 sets of conditions - for <code>NaN</code>s in <code>Column5</code> and for non NaNs and last chain them by <code>|</code> (or):</p>
<pre><code>m1 = df['Column1'].duplicated(keep=False) & df['Column5'].isnull()
m2 = df['Column5'].duplicated(keep=False) & df['Column5'].notnull()
df = df[m1... | python|pandas|dataframe | 2 |
4,019 | 11,253,495 | numpy: applying argsort to an array | <p>The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html#numpy.argsort" rel="noreferrer"><code>argsort()</code></a> function returns a matrix of indices that can be used to index the original array so that the result would match the <code>sort()</code> result.</p>
<p>Is there a way to app... | <p>This is probably overkill, but this will work in the nd case:</p>
<pre><code>import numpy as np
axis = 0
index = list(np.ix_(*[np.arange(i) for i in z2.shape]))
index[axis] = z2.argsort(axis)
z2[index]
# Or if you only need the 3d case you can use np.ogrid.
axis = 0
index = np.ogrid[:z2.shape[0], :z2.shape[1], :z... | python|arrays|numpy | 10 |
4,020 | 68,436,818 | How can I create an array based on another array? | <p>I am new to python, I would like to try to create a array based on another array.</p>
<p>If I have a array like:</p>
<pre><code>array = [[1, 1], [1, 2], [2, 2], [3, 2], [3, 3], [4, 2], [5, 1], [5, 3]]
</code></pre>
<p>Then if the matrix would like to be created based on array if there's a value for corresponding pos... | <p>The first array (named <code>array</code>) is called a <em>sparse binary matrix representation</em>. The second array (named <code>result</code>) is called a <em>dense binary matrix representation</em>. If you want to convert the values to ranks (while respecting duplicates) beforehand, you can use the <code>numpy.u... | python|arrays|numpy | 4 |
4,021 | 68,283,607 | How to check if any row is more than x and return name of column? | <p>I have dataframe of id, col1,col2,col3,col4 as it is described on picture.</p>
<p>I want to write function which find if any row is more than x an return name of column in which this condition was true and return it in result column.</p>
<pre><code>userid col1 col2 col3 col4 result
d1 40 50 75 65 c... | <p>You can use <code>idxmax</code> with <code>(axis=1)</code> to work on columns :</p>
<pre class="lang-py prettyprint-override"><code>>>> df[['col1','col2','col3','col4']].idxmax(axis=1)
0 col3
1 col4
2 col2
3 col1
dtype: object
</code></pre>
<p>And to assign it to your <code>df</code> :</p>
<pre ... | python|pandas | 3 |
4,022 | 68,182,976 | How to make bar subplots in plotly using pandas pivot dataframes? | <p>Below are the pivot dataframes df1 and df2. Now I am trying to make subplots in plotly by using below dataframes. But I am getting key error while executing my code. My code as under:</p>
<pre><code>import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_sub... | <ul>
<li>you are using <strong>plotly express</strong> concepts to create the traces. You need to create a trace for each bar column</li>
<li>simple case of then adding that to the subplots figure</li>
</ul>
<pre><code>import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
impo... | pandas|plotly | 1 |
4,023 | 68,239,584 | numpy.ndarray has no attribute read (when trying to pass a video) | <p>I am attempting to write a video with annotations to a file ( or at least print it our on-screen while using google colab). I've tried using cv_imshow but this prints the video one frame at a time, which is not what I'm after. I've amended the script to use <code>VideoWriter</code>, but still getting stuck when usin... | <p>I managed to adjust the code in order to the VideoWriter to work. As hpaulj pointed out, I was assigning the variable cap twice.</p>
<p>The correct code is below:</p>
<pre><code>cap = cv2.VideoCapture(r'/content/drive/MyDrive/Workspace/Images/Test/vid3.mp4')
res=(800,600)
fourcc = cv2.VideoWriter_fourcc(... | python|numpy|object-detection|video-processing|object-detection-api | 0 |
4,024 | 68,287,676 | Pandas won´t create .csv file | <p>I recently started diving into algo trading and building a bot for crypto trading.</p>
<p>For this i created a backtester with pandas to run different strategies with different parameters. The datasets (csv files) I use are rather larger (around 40mb each).</p>
<p>These are processed, but as soon as i want to save t... | <p>You can simplifiy your code by a great deal and write it as (should also run faster):</p>
<pre><code>results_df = pd.DataFrame(results)
results_df.columns = ['strategy', 'number_of_trades', "capital"]
print(results_df)
first_row_capital= results_df.capital.iloc[0]
indexer_capital_smaller= results_df.... | python|pandas|csv|anaconda | 1 |
4,025 | 59,433,626 | Assign column values to unique row in pandas dataframe | <p>I have the foll. dataframe:</p>
<pre><code>AA AB AC AD Col_1 Col_2 Col_3
Northeast Argentina Northeast Argentina South America Corrientes Misiones
Northern Argentina Northern Argentina South America Chaco Formosa Santiago D... | <p>You can try this:</p>
<pre><code>df = df.melt(id_vars=['AA','AB','AC','AD'])
df.dropna(inplace=True)
df.drop(columns='variable', inplace=True)
df = df.sort_values('AA').reset_index(drop=True)
df.rename(columns={'value':'Col'}, inplace=True)
AA AB AC AD Co... | python|pandas | 3 |
4,026 | 59,193,734 | TypeError: Tensors in list passed to 'values' of 'ConcatV2' Op have types [bool, float32] that don't all match | <p>I'm trying to reproduce the notebook for entity recognition using LSTM that i found on this link:
<a href="https://medium.com/@rohit.sharma_7010/a-complete-tutorial-for-named-entity-recognition-and-extraction-in-natural-language-processing-71322b6fb090" rel="noreferrer">https://medium.com/@rohit.sharma_7010/a-comple... | <p>I also came across this problem today. what worked for me was to remove <code>mask_zero=True</code> from the embedding layer. unfortunately I don't know why this helps.</p> | python|tensorflow|keras|lstm|named-entity-recognition | 9 |
4,027 | 59,278,891 | how to find the english and chinese combination records in pandas dataframe | <p>In pandas, data frame has 2 columns like "FirstName" and "LastName". From that columns "FirstName" column would be either english or chinese combination and same as "LastName" column would be either chinese or english combination. so, i want to display the those records of english-chinese combination in dataframe.</... | <p>You can search for the unicodes as i do here. You can inverse the matches as well:</p>
<pre><code>df.query("FirstName.str.contains(r'[\u4e00-\u9FFF]', regex=True) or LastName.str.contains(r'[\u4e00-\u9FFF]', regex=True)")
or
df[(df['FirstName'].str.contains(r'[\u4e00-\u9FFF]', regex=True)) | ( df['LastName'].st... | python|pandas|numpy|pandas-groupby | 2 |
4,028 | 59,437,334 | How to sample different number of rows from each group in DataFrame | <p>I have a dataframe with a category column. Df has different number of rows for each category. </p>
<pre><code>category number_of_rows
cat1 19189
cat2 13193
cat3 4500
cat4 1914
cat5 568
cat6 473
cat7 216
cat8 206
cat9 197
cat10 147
cat11 130
cat12 49
cat13 38
cat14 ... | <h2>Artificial data generation</h2>
<hr />
<h3>Dataframe</h3>
<p>Let's first generate some data to see how we can solve the problem:</p>
<pre><code># Define a DataFrame containing employee data
df = pd.DataFrame({'Category':['Jai', 'Jai', 'Jai', 'Princi', 'Princi'],
'Age':[27, 24, 22, 32, 15],
'Addre... | python|python-3.x|dataframe|random|pandas-groupby | 11 |
4,029 | 59,390,946 | Is there an easy way to lock some columns in pandas dataframe from being manipulated? | <p>I want to apply a function to every column except a couple that needs to remain unchanged.
The way I am doing it right now:</p>
<ol>
<li>Assign xxx columns to a variable</li>
<li>Drop xxx columns from df</li>
<li>Do some operation on df</li>
<li>Merge variable to df</li>
</ol>
<p>Example:</p>
<pre><code>cobId = c... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.difference.html" rel="nofollow noreferrer"><code>pd.Index.difference</code></a>:</p>
<pre><code>cols = combined.columns.difference(['Id','SalePrice'])
combined[cols] = combined[cols].sub(combined[cols].mean()).div(combined[cols].st... | python|pandas | 1 |
4,030 | 59,287,621 | Unexpected KeyError with for loop but not when manual | <p>I have written a function that manually creates separate dataframes for each participant in the main dataframe. However, I'm trying to write it so that it's more automated as participants will be added to the dataframe in the future.</p>
<p>My original function:</p>
<pre><code>def separate_participants(main_df):
... | <p>Thanks @Iguananaut for the answer:</p>
<p>Your DataFrame has a column named 'participant' but you're indexing it with the value of the variable participant which is presumably not a column in your DataFrame. You probably wanted main_df['participant']. Most likely the KeyError came with a "traceback" leading back to... | python|python-3.x|pandas|dataframe | 1 |
4,031 | 44,959,020 | How to find the mean of the value at an index in numpy | <p>Suppose I have a numpy array as show below and I want to calculate the mean of values at index 0 of each array (1,1,1) or index 3 (4,5,6). Is there a numpy function that can solve this? I tried numpy.mean, but it does not solve the issue.</p>
<pre><code>[[1,2,3,4],
[1,2,3,5], --> = [(1+1+1)/3, (2+2+2)/3, (3+3+3... | <pre><code>a = array([[1, 2, 3, 4],
[1, 2, 3, 5],
[1, 2, 3, 6]])
np.mean(a, axis=0)
-> array([ 1., 2., 3., 5.])
</code></pre>
<p>The parameter <code>axis</code> lets you select the direction across which you want to calculate the mean.</p> | python|arrays|numpy | 3 |
4,032 | 44,947,554 | Python/Pandas - How to assign value for each row which depends on cells values | <p>I have data frame like this:</p>
<pre><code> x y z
0 AA BB CC
1 BB NaN CC
2 BB AA NaN
</code></pre>
<p>and dictionary:</p>
<pre><code>d = {'AA': 1, 'BB': 2, 'CC': 3}
</code></pre>
<p>I want to compare values from each cell with values from dictionary and add another new column with sum of these values for ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="noreferrer"><code>replace</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="noreferrer"><code>sum</code></a> per row by <code>axis=1</code>, last convert... | python|pandas | 4 |
4,033 | 45,038,037 | Counting changes of value in each column in a data frame in pandas ignoring NaN changes | <p>I am trying to count the number of changes of value in each column in a data frame in pandas. The code I have works great except for NaNs: if a column contains two subsequent NaNs, it is counted as a change of value, which I don't want. How can I avoid that?</p>
<p>I do as follows (thanks to <a href="https://stacko... | <pre><code>change = (frame.fillna(0).diff() != 0).sum()
</code></pre>
<p>Output:</p>
<pre><code>time 2
X1 3
X2 2
dtype: int64
</code></pre>
<p>NaN are <a href="https://stackoverflow.com/questions/43925797/why-python-pandas-does-not-use-3-valued-logic">"truthy"</a>. Change NaN to zero then evaluate.</p>... | python|pandas|dataframe | 3 |
4,034 | 45,099,544 | Splitting Pandas dataframe on string properties index | <p>I'm trying to split a dataset into 2 types of datapoints. Currently I have a pandas dataframe with this format.</p>
<pre><code>CS1001 True value1
CM1001 False value2
CS1002 True value3
</code></pre>
<p>Now i would like to split this into a S and a M dataframe like this:</p>
<p>S frame:</p>
<pre>... | <p>IIUC:</p>
<pre><code>In [15]: data
Out[15]:
1 2
CS1001 True value1
CM1001 False value2
CS1002 True value3
In [16]: data.groupby(data.index.str[:2]).groups
Out[16]:
{'CM': Index(['CM1001'], dtype='object'),
'CS': Index(['CS1001', 'CS1002'], dtype='object')}
</code></pre>
<p>Removing seco... | python|python-3.x|pandas | 1 |
4,035 | 45,200,428 | How to find intersection of a line with a mesh? | <p>I have trajectory data, where each trajectory consists of a sequence of coordinates(x, y points) and each trajectory is identified by a unique ID.</p>
<p>These trajectories are in <strong>x - y</strong> plane, and I want to divide the whole plane into equal sized grid (square grid). This grid is obviously invisible... | <p>This can be solved by shapely:</p>
<pre><code>%matplotlib inline
import pylab as pl
from shapely.geometry import MultiLineString, LineString
import numpy as np
from matplotlib.collections import LineCollection
x0, y0, x1, y1 = -10, -10, 10, 10
n = 11
lines = []
for x in np.linspace(x0, x1, n):
lines.append(((... | python|algorithm|numpy|grid|intersection | 9 |
4,036 | 56,927,222 | concatenate pandas dataframes with priority replacment of NaN | <p>I have data collected from a lineage of instruments with some overlap. I want to merge them to a single pandas data structure in a way where the newest available data for each column take precedence if not NaN, otherwise the older data are retained. </p>
<p>The following code produces the intended output, but invol... | <p>In your case </p>
<pre><code>s=pd.concat([df0,df1,df2],sort=False)
s[:]=np.sort(s,axis=0)
s=s.dropna(thresh=1)
s
x y
t
0 0.0 0.0
1 1.0 1.0
2 2.0 2.0
3 3.0 3.0
4 4.0 3.1
3 4.1 4.1
4 5.1 5.1
5 6.1 6.1
6 8.2 NaN
8 10.2 NaN
</code></pre> | python|pandas|numpy|dataframe|merge | 0 |
4,037 | 56,922,718 | How to strip columns from dataframe using pd.read_html and return output as a list | <p>I'm trying to get a list of stock symbols using the Pandas <code>read_html</code> function (instead of using Beautiful Soup to scrape the web). </p>
<p>The website I'm referencing is:</p>
<p><a href="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies" rel="nofollow noreferrer">https://en.wikipedia.org/wiki... | <p>Using <code>pandas</code> library to read html table data. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.tolist.html#pandas.Series.tolist" rel="nofollow noreferrer">tolist()</a> is used to convert a series to list.</p>
<pre><code>import pandas as pd
url = 'https://en.wikipedia.o... | python|pandas | 2 |
4,038 | 56,987,018 | How to encode a feature which has a list of categorical values in each row for training an machine learning model? | <p>I have a dataset where I have list of categorical values as value of a feature. How can I encode it to train a model?</p>
<p>For example, I have some data like:</p>
<pre><code>feature1: [a, b, c]
feature2: [[category1, category2, category3], [category2], [category3, category4]]
</code></pre>
<p>how to encode feat... | <p>You can use <code>LabelEncoder</code> AND <code>OneHotEncode</code> :-</p>
<pre><code>from sklearn.preprocessing import LabelEncoder,OneHotEncoder
labelencoder_x=LabelEncoder()
X[:, 0]=labelencoder_x.fit_transform(X[:,0])
onehotencoder_x=OneHotEncoder(categorical_features=[0])
X=onehotencoder_x.fit_transform(X)... | python|numpy|machine-learning|scikit-learn | 0 |
4,039 | 56,917,161 | Installing Keras and Tensorflow on AWS SageMaker | <p>I am trying to download Keras to my notebook instance on AWS SageMaker. The code and the errors or warnings are listed below:</p>
<pre><code>from keras.models import Sequential #Sequential Models
from keras.layers import Dense #Dense Fully Connected Layer Type
from keras.optimizers import SGD #Stochastic Gradient D... | <p>Try this:</p>
<pre><code>!pip install tensorflow -t ./
</code></pre>
<p>it will install tensorflow in your current directory</p> | tensorflow|keras|amazon-sagemaker | 2 |
4,040 | 57,278,231 | Cannot store an array using dask | <p>I am using the following code to create an array and and store the the results sequentially in a hdf5 format. I was checking out the dask documentation, and the suggested to use dask.store to store the arrays generated in a function like mine. However I receive an error: <code>dask has no attribute store</code></p>
... | <p>As suggested in the comments, you're currently doing this</p>
<pre><code>import dask as da
</code></pre>
<p>When you probably meant to do this</p>
<pre><code>import dask.array as da
</code></pre> | numpy|dask|h5py | 1 |
4,041 | 35,638,151 | Populating new numpy array with another's values in for loop | <p>I'm doing something stupid with <code>numpy</code>. Trying to populate one <code>numpy</code> array with values from another via a for loop, like this: </p>
<pre><code>for i in range(0,9998):
a[i] = b[i] * c[i]
</code></pre>
<p>I'm getting the following error: </p>
<blockquote>
<p>"TypeError: 'numpy.float64... | <p>I suspect you are doing something like this:</p>
<pre><code>In [281]: a=np.float64(0)
In [282]: a[0]=2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-282-ed5200211ec0> in <module>()
-... | python|numpy | 0 |
4,042 | 50,950,638 | Filter down the dataframe based on condition that value in a column is a whole number (integer) | <p>I am struggling to filter my dataframe, so that I have only rows with whole numbers (like 21.00).
I saw one similar QA (<a href="https://stackoverflow.com/questions/40370382/creating-new-column-in-pandas-df-populated-by-true-false-depending-on-whether-an/40370477">Creating new column in pandas df populated by True,... | <p>You can use a Boolean series to filter a dataframe:</p>
<pre><code>res = df[df['value'].map(lambda x: x.is_integer())]
print(res)
index value
0 0 43.0
3 3 349.0
</code></pre>
<p>For performance, you may wish to compare a series against an integer version of itself:</p>
<pre><code>res = df[df['v... | python|pandas|dataframe|floating-point|series | 3 |
4,043 | 50,773,874 | Functions in Python with or without parentheses? | <p>In Python, there are functions that need parentheses and some that don't, e.g. consider the following example:</p>
<pre><code>a = numpy.arange(10)
print(a.size)
print(a.var())
</code></pre>
<p>Why does the size function not need to be written with parentheses, as opposed to the variance function? Is there a genera... | <p>It sounds like you're confused with 3 distinct concepts, which are not specific to python, rather to (object oriented) programming.</p>
<ul>
<li><strong>attributes</strong> are values, characteristics of an object. Like <code>array.shape</code></li>
<li><strong>methods</strong> are functions an object can run, acti... | python|numpy|syntax | 4 |
4,044 | 33,248,117 | How to group a dataframe by some transform of a column | <p>Is there a way to group the rows of a dataframe not by the value of some column, but rather by the result of applying some function to the value of that column? For example, to group the rows of the dataframe according to whether the value of a certain column is > 0 or ≤ 0.</p>
<p>Of course, I realize that o... | <p>The example you give is pretty simple:</p>
<pre><code>import numpy
import pandas
numpy.random.seed(0)
N = 15
df = pandas.DataFrame({
'A': numpy.arange(N),
'B': numpy.round(numpy.random.normal(size=N), 2)
})
print(df.to_string())
A B
0 0 1.76
1 1 0.40
2 2 0.98
3 3 2.24
4 4 1.... | python|pandas | 3 |
4,045 | 33,177,274 | Pandas: Most efficient way to make dictionary of dictionaries from DataFrame columns | <hr>
<pre><code>import pandas as pd
import numpy as np
import random
labels = ["c1","c2","c3"]
c1 = ["one","one","one","two","two","three","three","three","three"]
c2 = [random.random() for i in range(len(c1))]
c3 = ["alpha","beta","gamma","alpha","gamma","alpha","beta","gamma","zeta"]
DF = pd.DataFrame(np.array([c1,... | <p>IIUC, you could take advantage of <code>groupby</code> to handle most of the work:</p>
<pre><code>>>> result = df.groupby("c3")[["c1","c2"]].apply(lambda x: dict(x.values)).to_dict()
>>> pprint.pprint(result)
{'alpha': {'one': 0.440958516531,
'three': 0.677464637887,
'two': 0... | python|pandas|hash|machine-learning|dataframe | 4 |
4,046 | 33,431,286 | Float required in list output | <p>I am trying to create a custom filter to run it with the generic filter from SciPy package.</p>
<blockquote>
<p>scipy.ndimage.filters.generic_filter</p>
</blockquote>
<p>The problem is that I don't know how to get the returned value to be a scalar, as it needs for the generic function to work. I read through the... | <p>If I understand, you want to substract each pixel the min of its 3-horizontal neighbourhood. It's not a good practice to do that with lists, because numpy is for efficiency( ~100 times faster ). The simplest way to do that is just :</p>
<pre><code>test-sc.generic_filter(test, np.min, size=3)
</code></pre>
<p>The... | python|numpy|filtering | 2 |
4,047 | 33,143,810 | Pandas histogram from count of columns | <p>I have a big dataframe that consist of about 6500 columns where one is a classlabel and the rest are boolean values of either 0 or 1, the dataframe is sparse.</p>
<p>example:</p>
<pre><code>df = pd.DataFrame({
'label' : ['a', 'b', 'c', 'b','a', 'c', 'b', 'a'],
'x1' : np.random.choice(2, 8),... | <p>You could try pivoting:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'label' : ['a', 'b', 'c', 'b','a', 'c', 'b', 'a'],
'x1' : np.random.choice(2, 8),
'x2' : np.random.choice(2, 8),
'x3' : np.random.choice(2, 8)})
pd.pivot_table(df, index='label').trans... | python|pandas | 3 |
4,048 | 66,341,349 | How to group and sum certain columns of an array based on their classification (eg to group cities by country) | <h2>The issue</h2>
<p><strong>I have arrays which track certain items over time. The items belong to certain categories. I want to calculate the sum by time and category, e.g. to go from a table by time and city to one by time and country.</strong></p>
<p><strong>I have found a couple of ways, but they seem clunky - th... | <p>You can use <code>df.groupby(categories, axis=1).sum()</code> for a substantial speedup.</p>
<pre><code>import numpy as np
import pandas as pd
import time
def make_data(periods, n):
categories = np.tile(['red','green','yellow','brown'],n)
my_array = np.random.randint(low = 0, high = 10, size = (periods, le... | python|pandas|dataframe|numba | 1 |
4,049 | 16,178,471 | Numpy running at half the speed of MATLAB | <p>I've been porting MATLAB code over to Python and, after quite a lot of work, I have stuff that works. The downside, however, is that Python is running my code more slowly than MATLAB did. I understand that using optimised ATLAS libraries will speed things up, but actually implementing this is confusing me. Here's wh... | <h2>Simple example</h2>
<p>Numpy is calculating both the eigenvectors and eigenvalues, so it will take roughly twice longer, which is consistent with your slowdown (use <code>np.linalg.eigvals</code> to compute only the eigenvalues).</p>
<p>In the end, <code>np.linalg.eig</code> is a tiny wrapper around dgeev, and li... | python|performance|matlab|numpy|atlas | 12 |
4,050 | 16,366,124 | Share a numpy array in gunicorn processes | <p>I have a big numpy array that is stored in redis. This array acts as an index. I want to serve filtered result over http from a flask app running on gunicorn and I want all the workers spawned by gunicorn to have access to this numpy array. I don't want to go to redis every time and deserialize the entire array in m... | <p>Create an instance of a Listener <em>server</em> and have your gunicorn children connect to that process to fetch whatever data they need as Clients. This way the processes can modify the information as needed and request it from the main process instead of going to Redis to reload the entire dataset.</p>
<p>More i... | python|numpy|flask|ipc|gunicorn | 7 |
4,051 | 16,420,097 | What is the difference between np.sum and np.add.reduce? | <p>What is the difference between <code>np.sum</code> and <code>np.add.reduce</code>?<br>
While <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduce.html">the docs</a> are quite explicit: </p>
<blockquote>
<p>For example, add.reduce() is equivalent to sum().</p>
</blockquote>
<p>The perf... | <p>Short answer: when the argument is a numpy array, <code>np.sum</code> ultimately calls <code>add.reduce</code> to do the work. The overhead of handling its argument and dispatching to <code>add.reduce</code> is why <code>np.sum</code> is slower.</p>
<p>Longer answer:
<code>np.sum</code> is defined in <a href="http... | python|numpy | 32 |
4,052 | 57,706,068 | How to align text to center in reportlab python? | <p>I am generating a pdf using reportlab and I want my title to be in center. But how do achieve it, unable to find a soltuion.</p>
<p>Here is my code:</p>
<pre><code>def add_text(text, style="Normal", fontsize=12):
Story.append(Spacer(1, 12))
ptext = "<font size={}>{}</font>".format(fontsize, tex... | <p>I would create my own text style and refer to this, in your case</p>
<pre><code>def add_text(text, style="Normal", fontsize=12):
</code></pre>
<p>to </p>
<pre><code>def add_text(text, style="Normal_CENTER", fontsize=12):
</code></pre>
<p>Below is how you create your own style:</p>
<pre><code>from reportlab.lib.... | python|pandas|pdf|reportlab | 2 |
4,053 | 57,648,928 | I would like to convert a pivot table's column data to rows (unpivot a table) | <p>I have a dataframe that I created from an Excel file of the following form: </p>
<pre><code>
Ticker 0 Ticker 1 Ticker 2 Delta 0 ... Gamma 1 Gamma 2 IL Var
2019-01-01 -0.0 -1.0 -1.0 0.0 ... -3.0 2.0 10 5
2019-01-02 0.0 -0.0 -1.0 -1.0 ... ... | <p>Seems like you're converting from a wide format to a longitudinal format. Try</p>
<pre><code>df.reset_index(inplace = True)
df = pd.wide_to_long(df, ['Ticker', 'Delta', 'Gamma'], i = 'index', j = 'timepoint', sep = " ")
</code></pre>
<p>where the stubnames of your variables are <code>['Ticker', 'Delta', 'Gamma']<... | python|pandas|dataframe|pivot | 1 |
4,054 | 57,357,049 | How to load grayscale image dataset to Mobile net model | <p>I am trying to load a grayscale image dataset(fashion-mnist) to MobileNet model to predict hand written numbers but according to <a href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l06c01_tensorflow_hub_and_transfer_learning.ipynb#sc... | <p>Probably pre-trained MobileNet is not suitable for this task. You have two different problems. Mobilenet is made for Imagenet images which are 224x224 images with 3 color channels, while MNIST dataset is 28x28 images with one color channel. You can repeat the color channel in RGB: </p>
<pre><code># data.shape [7000... | python|tensorflow|conv-neural-network|mobilenet | 2 |
4,055 | 57,652,508 | How to convert a dict which is inside a list inside an array of json object into a dataframe? | <p>I have an array in json text file which has a list of dicts. I need to extract all of it into a dataframe. Array is something on these lines:-</p>
<pre><code>[{ "_id" : "abc" , "players" : [ "1" , "2"] , "tId" : "1" , "ef" : 200 , "pr" : 360 , "mode" : 1.0 , "1" : { "before" : { "rm" : { "$numberLong" : "1070"} , "... | <p>You can use this:</p>
<pre><code>pd.io.json.json_normalize(data, "shots", "_id")
</code></pre>
<p>Output of the head "_id" is located in the last column, all the others columns are what's inside data:</p>
<pre><code> iBS bSTOP aSTOP bSPB aSPB lBP iBP bP iTO iCOPG nTCCOP iCOPS ... | python|json|python-3.x|pandas|dictionary | 1 |
4,056 | 57,480,658 | Sorting column labels by numeric in string, Python | <p>I have successfully connected Python to Microsoft Access Database. The problem appears when I am trying to sort the column labels in the data frame by number in increasing order. The column names also contain characters.</p>
<p>I have looked into several sorting functions, but none of them seems to work for this is... | <p>I think this might be answer you are looking for:</p>
<pre><code>data.reindex_axis(sorted(data.columns, key=lambda x: float(x[1:])), axis=1)
</code></pre>
<p>You can freely modify the value in x[1:] to include or exclude more characters in the string.</p> | python|pandas|sorting|columnsorting | 1 |
4,057 | 57,679,220 | Expand nested lists to rows, create headers, and map back to original columns | <p>I would like to expand the nested lists to multiple rows and columns. At the same time, map back the results to the corresponding column values.</p>
<p>The dataframe is like the following.</p>
<pre><code>df=pd.DataFrame({
'column_name':['income_level', 'geo_level'],
'results':[[[0, 12, 13], [0, 98, 43], [1, 29, 73... | <p><code>Explode</code> column <code>results</code> and assign to <code>df1</code>. Create the new dataframe from list of sublist of <code>df1.results</code> and <code>reset_index</code></p>
<pre><code>df1 = df.explode('results')
pd.DataFrame(df1.results.tolist(),
index=df1.column_name,
colu... | python|pandas|list | 1 |
4,058 | 24,236,252 | Read the properties of HDF file in Python | <p>I have a problem reading hdf file in pandas. As of now, I don't know the keys of the file.</p>
<p>How do I read the file [data.hdf] in such a case? And, my file is .hdf not .h5 , Does it make a difference it terms data fetching?</p>
<p>I see that you need a 'group identifier in the store'</p>
<pre><code>pandas.io... | <p>First (.hdf or .h5) doesn't make any difference.
Second, I'm not sure about the pandas, but I read the HDF5 key like:</p>
<pre><code>import h5py
h5f = h5py.File("test.h5", "r")
h5f.keys()
</code></pre>
<p>or</p>
<pre><code>h5f.values()
</code></pre> | python|pandas|hdf5|hdfstore|hdf | 1 |
4,059 | 24,126,542 | Pandas multi-index slices for level names | <p>The latest version of Pandas supports multi-index slicers. However, one needs to know the integer location of the different levels to use them properly.</p>
<p>E.g. the following:</p>
<pre><code>idx = pd.IndexSlice
dfmi.loc[idx[:,:,['C1','C3']],idx[:,'foo']]
</code></pre>
<p>assumes that we know that the <strong>... | <p>This is still an open issue for enhancement, see <a href="https://github.com/pydata/pandas/issues/4036" rel="nofollow">here</a>. Its pretty straightforward to support this. pull-requests are welcome!</p>
<p>You can easily do this as a work-around:</p>
<pre><code>In [11]: midx = pd.MultiIndex.from_product([list(ran... | python|pandas | 6 |
4,060 | 43,576,321 | Error when using KNeighborsClassifier using sklearn | <p>I am doing KNN classification for a dataset of 28 features and 5000 samples:</p>
<pre><code>trainingSet = []
testSet = []
imdb_score = range(1,11)
print ("Start splitting the dataset ...")
splitDataset(path + 'movies.csv', 0.60, trainingSet, testSet)
print ("Start KNeighborsClassifier ... \n")
neigh = KNeighborsC... | <p>So you got 6000 samples, use 60% of these, resulting in 3362 samples (as it seems, i don't seed your exact calculations).</p>
<p>You call <code>fit(X,Y)</code> <a href="http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier" rel="nofollow ... | numpy|machine-learning|scikit-learn|knn | 1 |
4,061 | 43,656,763 | np.concatenate a list of numpy.ndarray in new dimension? | <p>I have a list with numpy.ndarrays - each of shape <code>(33,1,8,45,3)</code></p>
<p>Problem that when i concatenate the list using <code>a = np.concatenate(list)</code>
The output shape of a becomes </p>
<pre><code>print a.shape
(726,1,8,45,3)
</code></pre>
<p>instead of shape <code>(22,33,1,8,45,3)</code>. </p>... | <p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer"><code>np.concatenate</code></a>:</p>
<blockquote>
<p>Join a sequence of arrays along an <strong>existing axis</strong>.</p>
</blockquote>
<p><a href="https://docs.scipy.org/doc/numpy/reference/generate... | python|numpy | 2 |
4,062 | 2,148,538 | Python: strange numbers being pulled from binary file /confusion with hex and decimals | <p>This might be extremely trivial, and if so I apologise, but I'm getting really confused with the outputs I'm getting: hex? decimal? what?</p>
<p>Here's an example, and what it returns:</p>
<pre><code>>>> print 'Rx State: ADC Clk=', ADC_Clock_MHz,'MHz DDC Clk=', DDC_Clock_kHz,'kHz Temperature=', Temperatur... | <p>Found out it's incredibly easy to do this with numpy.fromfile</p>
<p>Specify what you want to extract (e.g. uint32, int16 etc.) and it extracts it as an array.
You can even specify your own types as a collection of existing types, meaning you can extract known structures in one go (e.g. 2 uint32s then 1 string then... | python|binary|numpy|hex | 0 |
4,063 | 1,764,859 | How to compute laplacian of a field? | <p>I'm trying to compute the laplacian of a 2d field <strong>A</strong> using <em>scipy.ndimage.convolve</em>.</p>
<pre><code>stencil = numpy.array([[0, 1, 0],[1, -4, 1], [0, 1, 0]])
scipy.ndimage.convolve(A, stencil, mode='wrap')
</code></pre>
<p>This doesn't seem to give me the right answer though. Any ideas where ... | <p>I got another idea: did you take into account that your stencil, in order to approximate the Laplacian, should be divided by step**2, where step is the step size of your grid? Only then can you compare the ndimage.convolve result with the analytical result.</p>
<p>In fact, with a Gaussian, I obtain results that in... | python|numpy|scipy | 2 |
4,064 | 72,891,291 | Why can't you format the date? | <p>I have a dataframe with different dates with the following format 15 January 2012 and want to pass it with a format 15/01/2012</p>
<p>My code</p>
<pre><code>data['Last Date'] = pd.to_datetime(data['Last Date'], format="%d/%B/%Y")
print(data.info())
</code></pre>
<p>but I get an error.</p>
<pre><code>TypeEr... | <p>Convert the column to datetime in the parsed format and then convert it to the format you want</p>
<pre><code>
date = pd.to_datetime(data["Last Date"], format="%d %B %Y")
data['Last Date'] = date.dt.strftime("%d/%m/%Y")
</code></pre>
<p>Example:</p>
<pre><code>import pandas as pd
time... | python|python-3.x|pandas|dataframe|date | 0 |
4,065 | 72,971,755 | Deciles in Python | <p>I want to group a column into deciles and assign points out of 50.</p>
<p>The lowest decile receives 5 points and points are increased in 5 point increments.</p>
<p>With below I am able to group my column into deciles. How do I assign points so the lowest decile has 5 points, 2nd lowest has 10 points so on ..and the... | <p>Simple enough; you can apply operations between columns directly. Deciles are numbered from 0 through 9, so they are naturally ordered. You want increments of 5 points per decile, so multiplying the deciles by 5 will give you that. Since you want to start at 5, you can offset with a simple sum. The following gives y... | python|pandas|cut | 1 |
4,066 | 73,030,553 | Does PyTorch allocate GPU memory eagerly? | <p>Consider the following script:</p>
<pre><code>import torch
def unnecessary_compute():
x = torch.randn(1000,1000, device='cuda')
l = []
for i in range(5):
print(i,torch.cuda.memory_allocated())
l.append(x**i)
unnecessary_compute()
</code></pre>
<p>Running this script with PyTorch (1.11) g... | <p><code>torch.cuda.memory_allocated()</code> returns the memory that has been allocated, not the memory that has been "used".</p>
<p>In a typical GPU compute pipeline, you would record operations in a queue along with whatever synchronization primitives your API offers. The GPU will then dequeue and execute ... | memory-management|pytorch|gpu|lazy-evaluation | 1 |
4,067 | 70,629,560 | What is the difference between batch, batch_size, timesteps & features in Tensorflow? | <p>I am new to deep learning and I am utterly confused about the terminology.</p>
<p>In the Tensorflow documentation,</p>
<p>for [RNN layer] <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/RNN#input_shape" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/layers/RNN#input... | <h2>Difference between <code>batch_size</code> v. <code>batch</code></h2>
<p>In the documentation you quoted, <code>batch</code> means <code>batch_size</code>.</p>
<h2>Meaning of <code>timesteps</code> and <code>feature</code></h2>
<p>Taking a glance at <a href="https://www.tensorflow.org/tutorials/structured_data/time... | tensorflow|keras|lstm | 1 |
4,068 | 70,611,600 | Displaying None and Values with pandas dictionaries Python | <p>There are <code>None</code> values indicating there is no value for the <code>Last Month</code> row within the dictionary <code>a</code> below. How would I be able to modify the pandas style format so that it could print table <code>a</code> and still place dollar signs and in front of the set columns?</p>
<pre><cod... | <pre><code>import numpy as np
import pandas as pd
a = {'Timeframes': ['Entirety:',
'Last Month:',
'Three Months:',
'Six Months:',
'Last Year:',
'Last Two Years:'],
'Compounding With Lev': np.array([2398012.89, None, 90.07, 85.29,
620.39, 30611.48], dtype=float),
'... | python|pandas|database|numpy|format | 1 |
4,069 | 70,706,171 | Displaying all multindex labels in pandas dataframe as html | <p>Whenever multiline index is used, pandas merges same value indexes during export with <code>to_html</code>. I am looking for a solution to unmerge it or disable merging, so even if values are repeated in index, they are not merged
Currently pandas displays data as</p>
<p><img src="https://i.stack.imgur.com/5nHpl.png... | <p>When you export with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html" rel="nofollow noreferrer"><code>to_html</code></a>, use the <code>sparsify=False</code> option:</p>
<pre><code>df.to_html('output.html', sparsify=False)
</code></pre>
<blockquote>
<p>sparsify: bool, optional, de... | pandas|dataframe|multi-index | 0 |
4,070 | 42,831,629 | Changing label name when retraining Inception on Google Cloud ML | <p>I currently follow the tutorial to retrain Inception for image classification:
<a href="https://cloud.google.com/blog/big-data/2016/12/how-to-train-and-classify-images-using-google-cloud-machine-learning-and-cloud-dataflow" rel="nofollow noreferrer">https://cloud.google.com/blog/big-data/2016/12/how-to-train-and-cl... | <p>Online prediction certainly allows this, the model itself needs to be updated to do the conversion from int to string.</p>
<p>Keep in mind that the Python code is just building a graph which describes what computation to do in your model -- you're not sending the Python code to online prediction, you're sending the... | tensorflow|google-cloud-platform|image-recognition|google-cloud-ml | 0 |
4,071 | 30,419,722 | In PIL, why isn't convert('L') turning image grayscale? | <p>For a program I'm writing, I need to convert an RGB image to grayscale and read it as a NumPy array using PIL.</p>
<p>But when I run the following code, it converts the image not to grayscale, but to a strange color distortion a bit like the output of a thermal camera, as presented.</p>
<p>Any idea what the proble... | <p>matplotlib's <code>imshow</code> is aimed at scientific representation of data - not just image data. By default it's configured to use a high constrast color palette.</p>
<p>You can force it to display data using grayscale by passing the following option:</p>
<pre><code>import matplotlib.cm
imshow(inverted, cmap=... | python|numpy|python-imaging-library | 9 |
4,072 | 26,438,710 | Pandas Dataframe reindexing issue | <p>I have a DF that looks like this:</p>
<pre><code> value
objectID
ab798 54.68
ab799 45.98
ab800 38.79
etc.. etc..
</code></pre>
<p>where "value" is accesible as a column but "objectID" isn't, it's as if the DF has been indexed by "objectID". I want to have objectID be a column head... | <p>You can reset the index</p>
<pre><code>df.reset_index()
</code></pre>
<p>Or, you can access it as an index:</p>
<pre><code>df.index.values
</code></pre> | pandas|indexing|dataframe | 1 |
4,073 | 26,652,873 | numpy 3D indexing by list | <p>Why do these different ways of indexing into X return different values?</p>
<pre><code>print vertices[0]
print X[vertices[0]]
print X[tuple(vertices[0])]
print X[vertices[0][0]], X[vertices[0][1]], X[vertices[0][2]]
print [X[v] for v in vertices[0]]
</code></pre>
<p>And the output:</p>
<pre><code>[(0, 2, 3), (0, ... | <p>If you had used four vertices instead of three, writing</p>
<pre><code>vertices = [[(0, 2, 3), (0, 2, 4), (0, 3, 3), (3,3,3)],]
</code></pre>
<p>followed by</p>
<pre><code>print X[tuple(vertices[0])]
</code></pre>
<p>then the error message</p>
<pre><code>IndexError: too many indices for array
</code></pre>
<p>... | python|numpy | 1 |
4,074 | 39,384,066 | Bokeh - Link dataframe time series data to Select interaction | <p>I'm trying create a single line chart in Bokeh and linking different charts in one dataframe to a Select interaction. The dataframe structure looks something like this:</p>
<p>Date, KPI1, KPI2, KPI3, KPI4 ... ...</p>
<p>Date is always x axis, whereas KPI's should be changeable on the y axis.</p>
<p>I can't get i... | <p>I found an answer to my question here:</p>
<p><a href="https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/2rCCRIyXtk8" rel="nofollow">https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/2rCCRIyXtk8</a></p> | python|pandas|bokeh | 1 |
4,075 | 39,375,738 | How can I pass the previous state of a tuple-based tf.nn.MultiRNNCell to the next sess.run() call in TensorFlow? | <p>I am using a stack of RNNs built with <code>tf.nn.MultiRNNCell</code> and I want to pass the <code>final_state</code> to the next graph invocation. Since tuples are not supported in the feed dictionary, is stacking the cell states and slicing the input to yield a tuple at the beginning of the graph the only way of a... | <p>Suppose you have 3 RNNCells in your MultiRNNCell and each is a LSTMCell with an LSTMStateTuple state. You must replicate this structure with placeholders:</p>
<pre><code>lstm0_c = tf.placeholder(...)
lstm0_h = tf.placeholder(...)
lstm1_c = tf.placeholder(...)
lstm1_h = tf.placeholder(...)
lstm2_c = tf.placeholder(.... | tensorflow | 4 |
4,076 | 38,986,074 | Creating a matrix of a certain size from a dictionary | <p>I am wanting to solve a systems of equations through linalg.solve(A, b) Solve a linear matrix equation, or system of linear scalar equations from scipy.org. Specifically, I have two dictionaries, dict1 and dict1, and I need to convert them to matrices in order to use the above script. </p>
<pre><code> food = ['frui... | <p>You can create a numpy array from the dictionary using list comprehensions:</p>
<pre><code>import numpy as np
A = np.array([[(consumptions[x]["daily"]*consumptions[y]["daily"],
consumptions[x]["rarely"]*consumptions[y]["rarely"])
for y in food]
for x in food])
... | python|python-2.7|numpy|dictionary|matrix | 2 |
4,077 | 39,029,480 | Pandas Python - Finding Time Series Not Covered | <p>Hoping someone can help me out with this one because I don't even know where to start.</p>
<p>Given a data frame that contains a series of start and end times, such as:</p>
<pre><code>Order Start Time End Time
1 2016-08-18 09:30:00.000 2016-08-18 09:30:05.000
1 2016-08-18 09:30:00.005 20... | <h3>Setup</h3>
<pre><code>from StringIO import StringIO
import pandas as pd
text = """Order Start Time End Time
1 2016-08-18 09:30:00.000 2016-08-18 09:30:05.000
1 2016-08-18 09:30:00.005 2016-08-18 09:30:25.001
1 2016-08-18 09:30:30.001 2016-08-18 09:30:56.002
1 2016-08-18 ... | python|pandas|time-series | 1 |
4,078 | 33,801,584 | pandas multi index slicing "Level type mismatch" | <p>I moved to pandas version 0.17 from 0.13.1 and I get some new errors on slicing.</p>
<pre><code>>>> df
date int data
0 2014-01-01 0 0
1 2014-01-02 1 -1
2 2014-01-03 2 -2
3 2014-01-04 3 -3
4 2014-01-05 4 -4
5 2014-01-06 5 -5
>>> df.set_index("da... | <p>This error occurs because you're trying to slice on dates (labels) that are not included in the index. To solve this Level mismatch error and return values within a range that may or may not be within a df multiindex use:</p>
<pre><code>df.loc[df.index.get_level_values(level = 'date') >= datetime.date(2013,12,30... | python|pandas|slice|multi-index | 2 |
4,079 | 33,673,281 | How to find the appropriate linear fit in Python? | <p>I am trying to find the most appropriate linear fit for a large amount of data that has linear behaviour for most of samples. The data (<a href="https://drive.google.com/file/d/0BwwhEMUIYGyTcy1OaVlaZ0FBVms/view?usp=sharing" rel="nofollow noreferrer">link</a>) when plotted in the raw form is as shown below:</p>
<p><... | <p>You're looking to calculate the <strong>linear regression</strong> of your points. To do that, </p>
<pre><code>import numpy as np
x = np.array([0, 1, 2, 3])
y = np.array([-1, 0.2, 0.9, 2.1])
A = np.vstack([x, np.ones(len(x))]).T
m, c = np.linalg.lstsq(A, y)[0]
</code></pre>
<p>This will give you values m and c tha... | python|numpy|matplotlib|scipy|linear-regression | 3 |
4,080 | 23,713,434 | Installing gfortran for numpy with homebrew | <p>I want to install a working version of <code>numpy</code> using brew. <code>brew install numpy</code> gives the message: </p>
<pre><code>==> python setup.py build --fcompiler=gnu95 install --prefix=/usr/local/Cellar/numpy/1.8.1
File "/private/tmp/numpy-ncUw/numpy-1.8.1/numpy/distutils/fcompiler/gnu.py", line 197... | <p><code>brew install gcc</code></p>
<p>Numpy install now works fine.</p> | python|numpy|fortran|homebrew|gfortran | 9 |
4,081 | 22,752,443 | Convert nested dictionary into dataframe | <p>My dictionary looks like this</p>
<pre><code>mydict =
{240594.0: {1322.0: 1.6899999999999999, 1323.0: 1.6900000000000002, 1324.0: 1.6899999999999999, 1325.0: 1.6899999999999999, 1326.0: 1.6899999999999999, 1327.0: 1.6900000000000002, 1328.0: 1.6899999999999999, 1329.0: 1.6899999999999999, 1356.0: 1.690000000000000... | <p>As you have probably discovered, <code>DataFrame(mydict)</code> is valid code. You could simply take the transpose (<code>.T</code>) to get your desired result.</p>
<p>A better way, in terms of code readability and directness, is available: use the specific DataFrame constructor <code>DataFrame.from_dict</code>, wh... | python|dictionary|pandas|dataframe | 2 |
4,082 | 22,704,802 | numpy to generate discrete probability distribution | <p>I'm following a code example I found at <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html#subclassing-rv-discrete" rel="nofollow noreferrer">http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html#subclassing-rv-discrete</a> for implementing a random number generator for discrete values of... | <p>I try to answer my own question based on comments from @user333700 and @user235711:</p>
<p>I insert into the method before <code>normdiscrete = ...</code></p>
<pre><code>if tail == 'right':
gridint = gridint[npointsh:]
probs = probs[npointsh:]
s = probs.sum()
probs = probs / s
elif tail == 'left':
... | python|numpy|scipy | 0 |
4,083 | 62,141,428 | Is there a way to get the element 1 before/after upper indexing limit? | <p>I have a Dataframe with Timeindex and a Timeindex till which I want to slice the dataframe. </p>
<pre><code>df[:upper_Timeindex_Timevalue]
</code></pre>
<p>The Question:</p>
<p>How do I get the element before this "limiting-index"?</p>
<pre><code>df[:upper_Timeindex_Timevalue -1] # this wouldnt work this way bc ... | <p>You can use boolean indexing:</p>
<pre><code>df.loc[df.index < upper_Timeindex_Timevalue].last()
</code></pre>
<p>or</p>
<pre><code>df.loc[df.index > lower_Timeindex_TimeValue].first()
</code></pre> | python|pandas|dataframe|indexing|datetimeindex | 1 |
4,084 | 62,141,614 | Concatenate Series using For | <p>I'm having some trouble creating a DataFrame with some Series. Is there a way to concat them with a for? Because each time I try I only get the last Series in the DF, when I really want it to concat it the columns and not in place.</p>
<pre><code>suma_queries = list()
for query in queries:
cur.execute(query)
... | <p>you should reasign the appended dataframe back to itself in the for loop:</p>
<pre><code>for query in queries:
cur.execute(query)
schema = lib.get_schema_sql(cursor = cur)
table = lib.get_table_sql(cur)
df = pd.DataFrame(data = table, columns = schema)
suma_queries=suma_queries.append(df.iloc[... | python|pandas|for-loop | 0 |
4,085 | 62,364,889 | Pandas text column group by based on unique id | <p>I have below csv file,</p>
<pre><code>itemid testresult duplicateid
100 textboxerror 0
101 text_input_issue 100
102 menuitemerror 0
103 text_click_issue 100
104 text_caps_error 100
105 menu_drop_down_error 102
106 text_lower_error ... | <p>Copy the column of test results and update it with the first four characters as the group name. Replace it with the final group name. Then remove the unnecessary columns and reorder them. Does this meet the intent of your question?</p>
<pre><code>df['simlartestresult'] = df['testresult'].copy()
# Update to group_n... | python|pandas|pandas-groupby | 0 |
4,086 | 62,198,966 | Tensorflow installing error: __ is not a supported wheel on this platform | <p>I'm trying to install tensorflow on my PC but I keep getting errors.</p>
<p>I have seen multiple posts about tensorflow installing errors online but all I found was solutions saying that the version of python was not compatible. However, I am using python 3.8 and I am using the URL for python 3.8 provided on tensor... | <p>It's likely you're using the 32bit version of python 3.8 instead of the 64bit version. You can check by opening the interpreter and looking at the first line. If it has <code>32 bit (Intel)</code> or something similar, then it would be the 32 bit version. To get the 64bit edition, scroll down to Files on this link <... | python|python-3.x|tensorflow|pip | 3 |
4,087 | 51,536,617 | How rename pd.value_counts() index with a correspondance dictionary | <p>I am doing a <code>value_counts()</code> over a column of integers that represent categorical values. </p>
<p>I have a dict that maps the numbers to strings that correspond to the category name. </p>
<p>I want to find the <strong>best</strong> way to have the index with the corresponding name. As I am not happy wi... | <p>This is my solution :</p>
<pre><code>>>> weather_correspondance_dict = {1:"sunny", 2:"rainy", 3:"cloudy"}
>>> df["weather"].value_counts().rename(index=weather_correspondance_dict)
sunny 2
cloudy 1
rainy 1
Name: weather, dtype: int64
</code></pre> | python|pandas|dictionary|dataframe|counting | 7 |
4,088 | 51,453,933 | Frequency of words in a DataFrame | <p>I've a pandas DataFrame containing a list of words in 'review' column.
I need to find the frequency of the words that occurs in the review column. </p>
<pre><code>id sentiment review
0 5814_8 1 [stuff, going, moment, mj, 've, started, liste...
1 2381_9 1 [\the, classic, war, worlds\, '', timothy, hin..... | <p>You could use a list comprehension inside counter:</p>
<pre><code>Counter([i for s in df.review for i in s])
</code></pre> | list|pandas|dataframe | 0 |
4,089 | 51,470,574 | Close HDF File After to_hdf() using mode='a' | <p>I want to save a series of DataFrame using pandas into hdf file. So I use to_hdf()</p>
<pre><code> x = pd.DataFrame(np.random.rand(10, 10), index=pd.date_range(end='1/1/2018', periods=10), columns=list('abcdefghij'))
x.iloc[:5, :].to_hdf('append.h5', format='table', key='part1', mode='a')
</code></pre>
<p>A... | <pre><code>import pandas as pd
x = pd.DataFrame(np.random.rand(10, 10), index=pd.date_range(end='1/1/2018', periods=10), columns=list('abcdefghij'))
x.iloc[:5, :].to_hdf('append.h5', format='table', key='part1', mode='a')
y = pd.read_hdf('append.h5', key='part1', mode='r')
</code></pre>
<p>is working (as said in the ... | python|python-3.x|pandas | 0 |
4,090 | 51,327,767 | Python Data Analysis from SQL Query | <p>I'm about to start some Python Data analysis unlike anything I've done before. I'm currently studying numpy, but so far it doesn't give me insight on how to do this. </p>
<p>I'm using python 2.7.14 Anaconda with cx_Oracle to Query complex records.</p>
<p>Each record will be a unique individual with a column for E... | <p>At least <strong>you need to structurate this data</strong> to make a good analysis, you can do it in your database engine or in python (I will do it by this way, using pandas like SNygard suggested).</p>
<p>At first, I create some fake data(it was provided by you):</p>
<pre><code>import pandas as pd
import numpy... | python|pandas|numpy|analytics | 1 |
4,091 | 51,402,547 | Given a value how can I know in which columns it is present? | <p>I have a huge data frame with 4000 columns, and I need to look if a value exist in one or more columns (I need the name of columns), how can I index the number of columns and the column names in pandas? So far I tried to apply this idea:</p>
<pre><code>df.index[df.columns] == 'my_val'].tolist()
</code></pre>
<p>Ho... | <p>I think need:</p>
<pre><code>cols = df.columns[(df == 'my_val').any()]
</code></pre>
<p><strong>Sample</strong>:</p>
<pre><code>df = pd.DataFrame({'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2... | python|python-3.x|pandas | 4 |
4,092 | 51,270,348 | How can you identify the best companies for each variable and copy the cases? | <p>i want to compare the means of subgroups. The cases of the subgroup with the lowest and the highest mean should be copied and applied to the end of the dataset:</p>
<pre><code>Input
df.head(10)
Outcome
Company Satisfaction Image Forecast Contact
0 Blue 2 3 3 1
1 Blue 2 1 3 2
2 Y... | <p>I have a solution. First i create a dictionary with the variables i want to create a dummy company for best and worst:</p>
<pre><code>variables = ['Contact','Forecast','Satisfaction','Image']
</code></pre>
<p>After i loop over this columns and adding the cases again with the new label "Best" or "Worst":</p>
<pre>... | python-3.x|pandas | 0 |
4,093 | 51,445,026 | Pandas - Look in 2 columns and check each column for a different element, if both columns contain the elements return the value in a different column | <p>I have a data frame which has 3 columns (called all_names). The first column is called ID, the second column is 'First_names' and the third is 'Last_names' - the data frame has 1 million rows. I have a different data frame (called combos) which has 2 rows: 'First' and 'Last'. (the data frames also have an index colu... | <p>Your problem can be solved using <code>merge</code>. Let's say we have</p>
<pre><code>all_names = pd.DataFrame({'First_names':['John','John','Bob','Robert'],
'Last_names':['Do','Smith','Do','Smith'],'ID':[1,2,3,4]})
combos = pd.DataFrame({'First':['John','Bob','Robert'],'Last':['Smith','Do... | python|pandas | 2 |
4,094 | 51,146,054 | How do I get the address for an element in a Python array? | <p>I'm a newbie and I'm trying to get the address of an element at a particular index in a Numpy or regular Python array. I'm following a class on Coursera where the instructor gets the address but I'm confused as to if I can do the same in Python since the class is taught in another language. Here's a mathematical sam... | <p>An array and its attributes:</p>
<pre><code>In [28]: arr = np.arange(1,8)
In [29]: arr.__array_interface__
Out[29]:
{'data': (41034176, False),
'strides': None,
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (7,),
'version': 3}
</code></pre>
<p>The data buffer location for a slice:</p>
<pre><code>... | python|python-3.x|numpy | 3 |
4,095 | 48,005,035 | Pandas sorting multiple columns | <p>I have the following dataframe</p>
<pre><code>A B
b 10
b 5
a 25
a 5
c 6
c 2
b 20
a 10
c 4
c 3
b 15
</code></pre>
<p>How can I sort it as follows:</p>
<pre><code>A B
b 20
b 15
b 10
b 5
a 25
a 10
a 5
c 6
c 4
c 3
c 2
</code></pre>
<p>Column A is sorted based on the su... | <p>Create a temporary column <code>_t</code> and sort using <code>sort_values</code> on <code>_t, B</code></p>
<pre><code>In [269]: (df.assign(_t=df['A'].map(df.groupby('A')['B'].sum()))
.sort_values(by=['_t', 'B'], ascending=False)
.drop('_t', 1))
Out[269]:
A B
6 b 20
10 b 15
0 b ... | python|pandas|sorting | 2 |
4,096 | 48,362,180 | Find common tangent line between two cubic curves | <p>Given two functions, I would like to sort out the common tangent for both curves:</p>
<p><a href="https://i.stack.imgur.com/vTBod.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vTBod.png" alt="enter image description here"></a></p>
<p>The slope of the common tangent can be obtained by the follo... | <h3>Symbolic root finding</h3>
<p>Your system of equations consists of a quadratic equation and a cubic equation. There is no closed-form symbolic solution of such a system. Indeed, if there was, one would be able to apply it to a general 5th degree equation <code>x**5 + a*x**4 + ... = 0</code> by introducing <code>y ... | python|numpy|scipy|sympy|equation-solving | 6 |
4,097 | 48,274,053 | Python - Calculating Percent of Grand Total in Pivot Tables | <p>I have a dataframe that I converted to a pivot table using pd.pivot_table method and a sum aggregate function:</p>
<pre><code>summary = pd.pivot_table(df,
index=["Region"],
columns=["Product"],
values=['Price'],
a... | <p>This can be done very easily:</p>
<pre><code> import numpy as np
import pandas as pd
# Create table
table_1 = np.matrix([[100, 200, 650, 950],
[200, 250, 350, 800],
[400, 500, 200, 200],
[700, 950, 1200, 2850]])
column_l... | python|pandas|pivot-table|percentage | 1 |
4,098 | 48,400,250 | Subtract two objects data type in python | <p>I want to subtract two columns in order to get the time, but my columns are object types.</p>
<p>This are my initial columns dtypes:</p>
<pre><code>Column1 object
Column2 object
EVS_START object
Column3 object
time object
dtype: object
</code></pre>
<p>I changed EVS_START and time to da... | <p>There is a similar question here, discussing incompatibility between <code>datetime64[ns]</code> and <code><M8[ns]</code>:</p>
<p><a href="https://stackoverflow.com/questions/29206612/difference-between-data-type-datetime64ns-and-m8ns">Difference between data type 'datetime64[ns]' and '<M8[ns]'... | python|pandas | 0 |
4,099 | 48,883,106 | Pandas replace column by value in row | <p>How can I vectorise a replace, by looking for a value in the row. </p>
<p>For a dataframe as follows: </p>
<pre><code>df = pd.DataFrame([(1, 2, 3, 4, np.NaN, np.NaN, 4),
(1, 2, 3, 0, 0, np.NaN, 0),
(1, 2, 3, 4, 5, np.NaN, 5)],
columns = ['P0', 'P1', ... | <p>Vectorized, as requested. Perform broadcasted comparison, find the indices of replacement, and just replace accordingly. Afterwards, you can assign the result back using a neat <code>df[:] = ...</code> trick.</p>
<pre><code>v = df.values
i = v[:, :-1]
j = v[:, -1]
v[np.arange(v.shape[0]), (i == j[:, None]).argmax(... | python|pandas | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.