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 |
|---|---|---|---|---|---|---|
19,800 | 54,832,721 | How to do complex selection in pandas? | <p>I have a df like below:</p>
<pre><code>President Start Date End Date
B Clinton 1992-01-01 1999-12-31
G Bush 2000-01-01 2007-12-31
B Obama 2008-01-01 2015-12-31
D Trump 2016-01-01 2019-12-31 # not too far away!!
</code></pre>
<p>I want to create another df, something like this</p>
<pre><code>... | <p>This is another <a href="https://stackoverflow.com/a/53218939/7964527">unnesting</a> problem </p>
<pre><code>df['New']=[pd.date_range(x,y).tolist() for x , y in zip (df.StartDate,df.EndDate)]
unnesting(df,['New'])
</code></pre>
<hr>
<p>FYI I have pasted the function here </p>
<pre><code>def unnesting(df, explod... | python|pandas|dataframe | 4 |
19,801 | 54,764,760 | Get data from Pandas DataFrame using column values | <pre><code>>>> df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},
... index=['dog', 'hawk'])
>>> df
num_legs num_wings
dog 4 0
hawk 2 2
>>> for row in df.itertuples():
... print(row)
...
Pandas(Index='dog', num_legs=4, ... | <p>I faced the same error when using a variable.</p>
<pre><code>v = 'num_legs'
for row in df.itertuples():
print(row[v])
TypeError: tuple indices must be integers or slices, not str
</code></pre>
<p>To use <code>df.itertuples()</code> and use the attribute name as a variable.</p>
<pre><code>v = 'num_legs'
for r... | python|pandas|dataframe | 3 |
19,802 | 49,743,017 | Pandas: replacing similar values with a derived values | <p>How do I group proximate values (within some threshold) and replace them with an aggregate (e.g. mean, max, etc.). For example, consider the following data:</p>
<pre><code>cat1 cat2 value new_value
A a 1523314515 1523314515
A b 1523318114 1523318114
A c 1523318115 1523318114
B a 1... | <p>If I understand you correctly, here's a solution using <code>np.where</code>. Row 2 comes out differently from your expected output, so I think I'm not capturing your description exactly -- or <code>df.loc[2, 'new_value']</code> should be <code>1523318115</code> instead of <code>1523318114</code>.</p>
<pre><code>ca... | pandas | 0 |
19,803 | 49,564,318 | Issue with fine-tuning inceptionv3 in slim tensorflow and tf record batches | <p>I am trying to fine-tune inceptionv3 model using slim tensorflow library.
I am unable to understand certain things while writing the code for it. I tried to read source code (no proper documentation) and figured out few things and I am able to fine-tune it and save the check point. Here are the steps I followed
1... | <p>Here are answers to your questions.</p>
<ol>
<li><p>You cannot give epochs directly to <code>slim.learning.train</code>. Instead, you give the number of batches as the argument. It is called <code>number_of_steps</code>. It is used to set an operation called <code>should_stop_op</code> on <a href="https://github.co... | python|tensorflow|deep-learning|tf-slim|tfrecord | 1 |
19,804 | 49,608,041 | Adding to a view of a numpy array | <pre><code>>>> a = np.array([0, 0])
>>> a[[0, 0, 1, 1]] + [1, 2, 3, 4]
array([1, 2, 3, 4])
>>> a[[0, 0, 1, 1]] += [1, 2, 3, 4]
>>> a
array([2, 4])
</code></pre>
<p>I understand that <code>a[[0, 0, 1, 1]]</code> returns a view of <code>a</code>, whose first two elements point to <cod... | <p>You may want to look into <code>np.add.at</code></p>
<pre><code>>>> np.add.at(a, [0,0,1,1], [1,2,3,4])
>>> a
array([3, 7])
</code></pre>
<p>Please note that often <code>np.add.at</code> can be replaced with <code>np.bincount</code> to gain a considerble speedup.</p>
<p>Finally, advanced indexing... | python|numpy | 3 |
19,805 | 49,558,030 | Pandas dataframe hierarchical index columns - Scale slice of dataframe | <p>I have a pandas dataframe in which I have both continuous and discrete data. I'm separating the continous from the discrete data by using an hierarchical column index to process them in a different way.</p>
<p>Let's assume the following dataframe:</p>
<p>At first I'm building an hierarchical index, that I can use ... | <p>I'm not really sure why your approach is not working. I guess Multiindexes are still kind of experimental in pandas.
However there is a simple workaraound:</p>
<pre><code>df_scaled = df.copy()
df_scaled.loc[:,'continuous'] = scaler.transform(df.loc[:,'continuous'])
</code></pre>
<p>If you want to know in more deta... | python|pandas|dataframe|multi-index | 0 |
19,806 | 73,327,979 | Pandas conditionally copy values from one column to another row | <p>I have this Dataframe: <a href="https://i.stack.imgur.com/XFy8v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XFy8v.png" alt="Dataframe" /></a></p>
<p>I would like to copy the value of the Date column to the New_Date column, but not only to the same exact row, I want to every row that has the sa... | <p>try this:</p>
<pre><code>df['New_Date'] = df.groupby('User_Id')['Date'].transform('first')
</code></pre> | python|pandas|conditional-statements|data-science | 1 |
19,807 | 73,402,823 | Unable to get output from Tensorflow lite object detection model in C | <p>I trained an Tensorflow Lite object detection model with Yolo architecture in Python. Now I am trying to do the inference in C but I cannot make it work after the interpreter is invoked.</p>
<p>The <code>main.c</code> file looks something like this:</p>
<p><code>main.c</code></p>
<pre><code>#include <stdio.h>
... | <p>From what you said you have 2 outputs and the first one is correct with shape [1, 13, 13, 18].
So you need to fetch the second one</p>
<pre><code>const TfLiteTensor* output_tensor_2 =
TfLiteInterpreterGetOutputTensor(interpreter, 1);
/// Copy the data like below to your own buffer, you can adjust to whatever t... | c|object-detection|tensorflow-lite|yolo | 0 |
19,808 | 67,572,164 | Weighted average grouping by date (in index) in pandas DataFrame (different operations per column) | <p>I have a dataframe with several rows per day, a 'mass' column and a '%' value that needs to be ponderated as a weighted average depending on the mass; and the mass column a sum... creating a new dataframe with all values.</p>
<pre><code>d = {'date': [1, 1, 1, 2, 2], 'mass': [3, 40, 10, 12, 15], '%': [0.4, 0.7, 0.9, ... | <p>Multiply the 2 columns and then groupby with aggregate, then divide:</p>
<pre><code>#df = df.set_index('date')
out = df.assign(k=df['mass'].mul(df['%']))[['mass','k']].sum(level=0)
out['%'] = out.pop('k').div(out['mass'])
</code></pre>
<hr />
<pre><code>print(out)
mass %
date
1 ... | python|pandas|dataframe|weighted-average | 2 |
19,809 | 67,517,942 | How to groupby in Pandas by datetime range from different DF | <p>I've stuck and can't solve this...
I have 2 dataframes.
One has datetimes intervals, another has datetimes and values.
I need to get MIN() values based on datetime ranges.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
timeseries = pd.DataFrame(
[
['2018-01-01T00:00:00.000000000... | <p>Use <code>IntervalIndex</code> created by <code>timeseries</code> columns, then get positions by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_indexer.html" rel="nofollow noreferrer"><code>Index.get_indexer</code></a>, aggregate <code>min</code> and last add to column to <code>t... | pandas|dataframe|pandas-groupby | 2 |
19,810 | 67,527,710 | Python Pandas Dataframe to calculate the selected columns' mean values for each category and return as a dataframe? | <p>There are multiple categories in Doc_type column, I want to calculate the mean values using selected columns for each category and add the category back into a dataframe. Instead of having all records from the original DataFrame, I want to only have one row for each category contains the mean values for selected col... | <p>Let's assume here is your Sample data:</p>
<pre><code>sample = pd.DataFrame({'a':[1,2,3,4],'b':[4,5,6,7], 'c':[8,9,7,6]})
</code></pre>
<p>Then mean values for selected column:</p>
<pre><code>sample[['a','b']].mean()
</code></pre>
<p>Sample Output:</p>
<pre><code>a 2.5
b 5.5
dtype: float64
</code></pre> | python|pandas|dataframe | 0 |
19,811 | 67,338,092 | How to use numpy linspace on multiple lines in dataset | <p>Hello I need to use linspace to create points between two rows at a time in a dataset.</p>
<pre><code>'location'
1
10
12
14
</code></pre>
<p>Essentially use linspace to find points between rows 1 & 2(1,10), then 3 & 4(12,14) (...for hundreds of rows). Any advice would be really helpful!</p> | <p>If you have a list of locations, you could just iterate over the list in steps of two:</p>
<pre><code>import numpy as np
# List of locations
locs = [1, 10, 12, 14] # …possibly more
# List for storing linspace output
lins = list()
# Iterate over the locations list in steps of two
for i in range(0, len(locs), 2):
... | python|numpy|linspace | 0 |
19,812 | 59,986,691 | Drop sorted row based on value count column | <p>My dataframe looks like this:</p>
<pre><code> year id
0 2019 x1
1 2012 x1
2 2017 x1
3 2013 x1
4 2018 x2
5 2012 x2
6 2013 x2
</code></pre>
<p>I want to filter my whole dataframe such that if there are more than 3 observations per id, the observation with the lowest year should be droppe... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.head.html" rel="nofollow noreferrer"><code>Gro... | python|pandas | 3 |
19,813 | 60,017,049 | Extend a 2D plot to 3D | <p>I'm trying to show my 2D data on a 3D space.</p>
<p>Here is my code below:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
i = 60
n = 1000
r = 3.8
eps = 0.7
y = np.ones((n, i))
# random numbers on the first row of array x
np.random.seed(1)
x = np.ones((n+1, i))
x[0, :] = np.random.random(i)... | <p>Plotting 3d images in <code>matplotlib</code> is a little tricky. Generally you plot whole surfaces at once instead of plotting one line at a time. You do so by passing three 2d arrays, one for each position dimension (x, y, z). But you can't just pass any old 2d arrays either; the points themselves have to be in a ... | python|numpy|matplotlib|plot|mplot3d | 1 |
19,814 | 60,032,073 | Select specific rows of 2D PyTorch tensor | <p>Suppose I have a 2D tensor looking something like this: </p>
<pre><code>[[44, 50, 1, 32],
.
.
.
[7, 13, 90, 83]]
</code></pre>
<p>and a list of row indices that I want to select that looks something like this <code>[0, 34, 100, ..., 745]</code>. How can I go through and create a new tensor that contains only the ... | <p>You could select like with numpy</p>
<pre><code>import torch
x = torch.Tensor([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 8, 7, 6],
[5, 4, 2, 1]])
indices = [0, 3]
print(x[indices])
# tensor([[1., 2., 3., 4.],
# [5., 4., 2., 1.]])
</code></pre> | python|indexing|pytorch|tensor | 7 |
19,815 | 65,258,742 | generate conditional column in pandas | <p>I have:</p>
<pre><code>pd.DataFrame({'price':['45p','£1.35']})
</code></pre>
<p>I want to convert these to numeric, and get:</p>
<pre><code>pd.DataFrame({'price':['45p','£1.35'],'numeric':[0.45,1.35]})
</code></pre>
<p>I tried:</p>
<pre><code>df['numeric']=np.where(df.price.str.contains('p') is True,
... | <p>Try one step at a time:</p>
<pre><code># where values in pennies
is_pennies = df['price'].str.contains('p')
# remove the currency characters and convert to numerics
df['price'] = df.price.str.replace('p|£', '').astype(float)
# update the values in pennies
df.loc[is_pennies, 'price'] /= 100
</code></pre>
<p>Output:... | pandas|conditional-statements|calculated-columns | 2 |
19,816 | 65,089,390 | Find column labels in a filtered numpy array from pandas data frame | <p>I have a pandas data frame which I need to export to numpy to perform some operations. Those operations result in deletion of some of the columns. I would like to compare the resulting numpy array to my original data frame to obtain the labels of the columns which were retained. The problem is, that some of the colu... | <p>Idea is create mask by chaining both conditions and use for filter columns names in <code>DataFrame</code> constructor:</p>
<pre><code>loci = np.array(loci_df)
m1 = np.isnan(loci)
m2 = loci[0]==loci
mask = ~(m1|m2).all(0)
loci = loci[:,mask]
print (loci_df.columns[mask])
Index(['SNP3', 'SNP4', 'SNP5', 'SNP6', 'SNP... | pandas|numpy|dataframe|label | 0 |
19,817 | 65,135,890 | Modifying the date column calculation in pandas dataframe | <p>I have a dataframe that looks like this</p>
<p><a href="https://i.stack.imgur.com/FcyOF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FcyOF.png" alt="enter image description here" /></a></p>
<p>I need to adjust the <code>time_in_weeks</code> column for the 34 number entry. When there is a duplic... | <p>Question not very clear. Happy to correct if I interpreted it wrongly.</p>
<p>Try use <code>np.where(condition, choiceif condition, choice ifnotcondition)</code></p>
<pre><code>#Coerce dates into datetime
df['rma_processed_date']=pd.to_datetime(df['rma_processed_date'])
df['rma_created_date']=pd.to_datetime(df['rma_... | python|pandas | 1 |
19,818 | 65,237,524 | Replace values in dataframe with difference to last row value by condition | <p>I'm trying to replace every value above 1000 in my dataframe by its difference to the previous row value.</p>
<p>This is the way I tried with pandas:</p>
<pre class="lang-py prettyprint-override"><code>data_df.replace(data_df.where(data_df["value"] >= 1000), data_df["value"].diff(), inplace=Tr... | <pre><code>import numpy as np
import pandas as pd
d = {'value': [1000, 200002,50004,600005], }
data_df = pd.DataFrame(data=d)
data_df["diff"] = data_df["value"].diff()
data_df["value"] = np.where((data_df["value"]>10000) ,data_df["diff"],data_df["value"]... | python|pandas|dataframe|replace|difference | 2 |
19,819 | 65,066,242 | Running a DDQN on CPU-only tensorflow, my laptop is 50x faster than my AMD 3900 | <p>I was running a sample program on my laptop (DDQN from <a href="https://github.com/keon/deep-q-learning/blob/master/ddqn.py" rel="nofollow noreferrer">here</a>).</p>
<p>My laptop can perform a step about every .04 seconds (Lenovo P51 running Ubuntu 18.04, 32gb of memory, ssd). I tried this same program on my workst... | <p>This could be due to a change in a large number of things - off the top of my head, the most likely is <code>num_workers</code> - this is the number of workers and is supposed to increase as the number of threads increase, and defaults to 1 - change this to 8 or 16 and see if performance increases.</p>
<p>However, t... | python|performance|tensorflow | 0 |
19,820 | 65,252,886 | Uncaught (in promise) Error: Unknown layer | <p>I am following an <a href="https://www.tensorflow.org/tutorials/images/classification" rel="nofollow noreferrer">image classification tutorial from google</a>. At some point, there are some data augmentation that are done: <code>RandomFlip</code>, <code>RandomRotation</code>, <code>RandomZoom</code>.</p>
<p>When don... | <p>Change <code>modelTopology.model_config.class_name</code> from <code>Sequential</code> to <code>Model</code>.</p>
<pre><code> {"format": "layers-model", "generatedBy": "keras v2.4.0", "convertedBy": "TensorFlow.js Converter v2.4.0", "modelTopology"... | javascript|tensorflow.js | 0 |
19,821 | 65,330,039 | How do i plot this polynomial fraction using numpy and matplotlib? | <p>The task is to print quotient and remainder of this <a href="https://i.stack.imgur.com/aNITu.png" rel="nofollow noreferrer">polynomial fraction</a> and then plot the original function and the quotient. I figured out how to plot the quotient, but what is the best way to plot f(x)?</p>
<pre><code>import matplotlib.pyp... | <p>The simplest way would be to define a x-range and evaluate the function. Straight forward:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import numpy as np
px = np.poly1d([1, -7, 15, -21, 36])
qx = np.poly1d([1, -7, 6])
hx, rx = np.polydiv(px, qx)
print("\nh(x):&... | python|numpy|matplotlib | 2 |
19,822 | 65,250,088 | How to convert a set of images into a numpy array? | <p>I'm building my first Neural Network taking as example those on the book "Deep Learning with Python - Francois Chollet" and I immediately found my first issue. When the author imported the MNIST dataset he also printed the shape, obtaining that it is a 1D tensor. I'm trying to import a folder containing al... | <p>If you want to feed your images to a neural network, I suggest you don't use a for-loop to load all your images in memory. Rather, you can use this function:</p>
<pre><code>import tensorflow as tf
import os
os.chdir('pictures')
files = tf.data.Dataset.list_files('*jpg')
def load_images(path):
image = tf.io.rea... | python|numpy|tensorflow | 0 |
19,823 | 64,163,602 | Pytorch issue: torch.load() does not correctly load a saved model from file after closing and reopening Spyder IDE | <p>I followed the most basic code procedure for saving and loading neural network model parameters and it works perfectly fine. After training the network, it is saved to a specified file in a specified folder in the package using the standard torch.save(model.state_dict(), file) method; when I need to rerun the progra... | <p>It might be due to the fact that the state of your program is known while running the IDE but when closing it the state is lost resulting in the inability to know how to load the model (because the IDE doesnt know what model you are using). To solve this, try defining a new model and loading the parameters to it via... | python|machine-learning|neural-network|pytorch|spyder | 1 |
19,824 | 47,022,363 | Applying function on merge | <p>I have two dataframes. Snippets are pasted below</p>
<p>Employee</p>
<p><a href="https://i.stack.imgur.com/ixwaA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ixwaA.png" alt="enter image description here"></a></p>
<p>Project</p>
<p><a href="https://i.stack.imgur.com/okuLg.png" rel="nofollow ... | <p>You can ,<code>drop_duplicates</code> select the min cost one</p>
<pre><code>Employee=Employee.sort_values(['Level','skill','CostToCompany']).drop_duplicates(['Level','skill','Rating'],keep='first')
</code></pre>
<p>Then, </p>
<pre><code>Project1=pd.merge(Project,Employee['Level','skill','Employee ID'].on='cols')... | python-3.x|pandas|merge|min|concat | 2 |
19,825 | 63,266,368 | Find related value in a dataframe column | <p>I have a dataframe with IDs, names and flags.</p>
<p>I want to create a new column, where related IDs would be filled in.</p>
<p>Here are some rules:</p>
<ul>
<li>If the flag = '0' or 'A', then there is no related id</li>
<li>If the flag = 'B' we need to find the same name (minus the flag in name) but with flag 'A' ... | <p><code>groupby</code> with <code>shift</code></p>
<pre><code>df['related id']=df.groupby(df.name.str.split().str[0]).id.shift()
df
Out[11]:
name id flag related id
0 test1 A 1 A NaN
1 test1 B 2 B 1.0
2 test2 A 3 A NaN
3 test2 B 4 B 3.0
4 test3 5 ... | python|pandas|dataframe|pandas-groupby | 2 |
19,826 | 62,905,464 | Is there a way to import several .txt files each becoming a separate dataframe using pandas? | <p>I have to work with 50+ .txt files each containing 2 columns and 631 rows where I have to do different operations to each (sometimes with each other) before doing data analysis. I was hoping there was a way to import each text file under a different dataframe in pandas instead of doing it individually. The code I've... | <p>Yes. If you store your file in a list named <code>filelist</code> (maybe using glob) you can use the following commands to read all files and store them on a dict.</p>
<pre><code>dfdict = {f: pd.read_table(f,...) for f in filelist}
</code></pre>
<p>Then you can use each data frame with <code>dfdict["filename.tx... | python|pandas|dataframe|python-import|data-analysis | 1 |
19,827 | 63,052,728 | tensorflow lite models for android and instructions | <p>I am trying to follow instructions here to generate models for android.
<a href="https://github.com/tensorflow/examples/tree/master/lite/examples/gesture_classification/ml" rel="nofollow noreferrer">https://github.com/tensorflow/examples/tree/master/lite/examples/gesture_classification/ml</a></p>
<p>But when I try t... | <p>You need to first use the gesture classification web app to generate the TensorFlow.js model trained by your gestures.
<a href="https://github.com/tensorflow/examples/tree/master/lite/examples/gesture_classification/web" rel="nofollow noreferrer">https://github.com/tensorflow/examples/tree/master/lite/examples/gestu... | tensorflow|tensorflow-lite|tensorflow.js|google-codelab | 1 |
19,828 | 67,870,323 | How to get list of previous n values of a column conditionally in DataFrame? | <p>My dataframe looks like below:</p>
<pre><code>Subject Score
1 15
2 0
3 18
2 30
3 17
1 5
4 9
2 7
1 20
1 8
2 9
1 12
</code></pre>
<p>I want to get the previous 3 scores for each record grouped by... | <p>Since rolling only supports production of numeric values, this has to be a work around.</p>
<p>Try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html#pandas-dataframe-sort-values" rel="nofollow noreferrer"><code>sort_values</code></a> first then <a href="https://pan... | python|pandas|dataframe | 3 |
19,829 | 61,430,504 | Filtering by using queries from input | <p>I would like to search within more columns some words selected by input. It could be just one word or more than one (so a list of words).
This is how my dataset looks like:</p>
<pre><code>Text1 Text2
Include details about your goal... Include any error messages...
Describe expect... | <p>you use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.lower.html" rel="nofollow noreferrer"><code>Series.str.lower()</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.c... | python|pandas | 1 |
19,830 | 61,435,121 | Python convert conditional array to dataframe | <p>I have a dataframe with the following information:</p>
<pre><code> ticker date close gap
0 BHP 1981-07-31 0.945416 -0.199458
1 BHP 1981-08-31 0.919463 -0.235930
2 BHP 1981-09-30 0.760040 -0.434985
3 BHP 1981-10-30 0.711842 -0.509136
4 BHP 1981-11-30 0.778578 -0... | <p>Just extended your code a bit to get the <code>zero_crossings</code> into the original dataframe as required.</p>
<pre><code>import pandas as pd
import numpy as np
BHP_data = pd.DataFrame({'gap': [-0.199458, 0.472563, 0.463312, 0.493318, -0.509136, 0.534985, 0.784124]})
BHP_data['zero_crossings'] = 0
zero_crossin... | python|pandas|numpy|numpy-ndarray | 2 |
19,831 | 61,553,779 | Zombie process does not allow deallocating GPU memory | <p>I am loading NLP models in GPU to do inferencing.
But once the inference is over the GPU does not deallocate its memory:</p>
<p><a href="https://i.stack.imgur.com/XMYOG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XMYOG.png" alt="nvidia-smi image"></a></p>
<p>But then the command <code>ps -a ... | <p>I'm having a similar problem, a pytorch process on the GPU became zombie and left GPU memory used. Furthermore, in my case the process showed 100% usage in the GPU (<code>GPU-util</code> in the <code>nvidia-smi</code> output). <strong>The only solution I have found so far is rebooting the system.</strong></p>
<p>In ... | pytorch|nvidia|zombie-process | 0 |
19,832 | 68,655,292 | How to list the specific countries in a df which have NaN values? | <p>I have created the df_nan below which shows the sum of NaN values from the main df, which, as seen, shows how many are in each specific column.</p>
<p>However, I want to create a new df, which has a column/index of countries, then another with the number of NaN values for the given country.</p>
<pre><code>Country ... | <p>Suppose, you want to get Null count for each Country from "Cropland Footprint" column, then you can use the following code -</p>
<pre><code>Unique_Country = df['Country'].unique()
Col1 = 'Cropland Footprint'
NullCount = []
for i in Unique_Country:
s = df[df['Country']==i][Col1].isnull().sum()
Null... | python|pandas|dataframe | 0 |
19,833 | 68,862,402 | Passing multiple lambda functions in Pandas.DataFrame.transform in Python | <p>this is the code (in python)</p>
<pre><code>import numpy as np
import pandas as pd
df_5 = pd.DataFrame({'A': range(3), 'B': range(1, 4)})
df_5.transform([lambda x: x**2, lambda x: x**3])
</code></pre>
<p>and see the DataFrame for reference</p>
<p><a href="https://i.stack.imgur.com/43csp.png" rel="nofollow noreferrer... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a>:</p>
<pre><code>df = df_5.apply([lambda x: x**2, lambda x: x**3])
print (df)
A B
<lambda> <lambda> <lambda&... | python|pandas|dataframe | 1 |
19,834 | 53,184,109 | Is it possible to restore a tensorflow estimator from saved model? | <p>I use <code>tf.estimator.train_and_evaluate()</code> to train my custom estimator. My dataset is partitioned 8:1:1 for training, evaluation and test. At the end of the training, I would like to restore the best model, and evaluate the model using <code>tf.estimator.Estimator.evaluate()</code> with the test data. The... | <p>Maybe you can try tf.estimator.WarmStartSettings: <a href="https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/estimator/WarmStartSettings" rel="noreferrer">https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/estimator/WarmStartSettings</a></p>
<p>It can load weights in pb file and continue trainin... | tensorflow|tensorflow-estimator | 5 |
19,835 | 65,907,190 | Looking for an ideas to implement dynamic column renaming in pandas | <p>I have 143 column names in my df and 141 columns has same column format as shown below and want to update last 3 bytes of column name with month for columns starting with passengers or want to update whole column like '2009-jan' format based on targeted value</p>
<p>0: 'airport',
1: 'type of traffic',
2: 'Passengers... | <pre class="lang-py prettyprint-override"><code>import calendar
# df = your dataframe
df = pd.DataFrame([[1,2],[2,4],[3,5]], columns=['Passengers 2009M01', 'Passengers 2009M02'])
column_names = df.columns.to_list()
for each_column in column_names:
if('Passengers' in each_column):
dd = each_column.split(' '... | python|pandas|dataframe | 0 |
19,836 | 65,681,034 | How to load model for inference? | <p>I am using a simple perceptron based classifier to generate sentiment analysis in Pytorch, complete code here <a href="https://github.com/joosthub/PyTorchNLPBook/blob/master/chapters/chapter_3/3_5_Classifying_Yelp_Review_Sentiment.ipynb" rel="nofollow noreferrer">Classifying Yelp Reviews</a>.</p>
<p>The example does... | <p>I found a nice tutorial explaining how to load model for inference, here is the link</p>
<p><a href="https://pytorch.org/tutorials/recipes/recipes/saving_and_loading_models_for_inference.html" rel="nofollow noreferrer">https://pytorch.org/tutorials/recipes/recipes/saving_and_loading_models_for_inference.html</a></p>... | python|machine-learning|flask|deep-learning|pytorch | 0 |
19,837 | 63,623,211 | Better way to do calculations for multiple dataframes and return statement? | <ul>
<li>My function looks through 3 dataframes, filters between different dates, and creates a statement.</li>
<li>As you can see, the function is reusing the same steps over and over, and I would like to reduce them.</li>
<li>I believe using a <code>for-loop</code> would help, but I'm unsure of how the <code>return</... | <p>I would just pass 3 parameters to your function those being df, date1 and date2 and then call your function 3 times.</p>
<pre><code>def stat_generator(df,date1,date2):
"..."
return statement
</code></pre>
<p>Then pass in your data as a list of lists or something similar. For example:</p>
<pre><code... | python|pandas | 2 |
19,838 | 63,476,978 | Python + Pandas JSON Url Call via api : Cannot save resuls as CSV index problem scalar values | <p>Trying to do a simple script to save as csv. My python Version is 3.8.3 and I am using window 10.
I am trying to use the tool pandas : <a href="https://pandas.pydata.org" rel="nofollow noreferrer">https://pandas.pydata.org</a></p>
<p>I am trying to get data results from the URL <code>https://barcode.monster/api/306... | <p>There are many ways of solving this issue. If you're going to use open a text file, then you'll need to convert the string to json. Try using <code>json.load(f)</code>. Doing so, you can call <code>DataFrame</code>. You will then need to either set the index to the first item or wrap the json data in a json object.<... | python|python-3.x|pandas|dataframe|web-scraping | 2 |
19,839 | 53,437,621 | Pandas iloc wrong index causing problems with subtraction | <p>I should start by saying that I am quite new to pandas and numpy (and machine learning in general).</p>
<p>I am trying to learn some basic machine learning algorithms and am doing linear regression. I have completed this problem using matlab, but wanted to try implementing it in python - as that is a more practical... | <p>Looks like the calculation you actually want to do is on the series (individual columns). So you should be able to do:</p>
<pre><code>predictions[0].subtract(y[1])
</code></pre>
<p>To get the value you want. This looks kind of confusing because you have numbers as DataFrame columns, you are selecting the columns y... | python|pandas | 2 |
19,840 | 55,168,903 | create a time series picking the values from an existing one but changing the dates in python | <p>I have a time series and want to duplicate it and assign a new set of date index to it, because I need to concatenate it to the original series (I need a longer time series in order to perform filtering).</p>
<pre><code>>>>len(ts_interp)
109
>>>ts_interp.head()
date
2016-12-06 0.118412
2016-12-... | <p>I don't understand what you are trying to accomplish by concatenating a time series twice for "filtering", but if you insist, try to conclude with:</p>
<pre><code>pre_series.loc[start_date1:end_date1] = \
pre_series.loc[start_date2:end_date2].values
</code></pre>
<p>Namely assign the values of the lower half t... | python|pandas|time-series | 1 |
19,841 | 55,340,168 | Add dimension numpy array | <p>I have two numpy arrays such as:</p>
<pre><code>a = np.array([1, 2, 3])
b = np.array([101, 102, 103 ])
</code></pre>
<p>I want to create a new array with shape (len(a), 2), such as</p>
<pre><code>array([[1, 101], [2, 102], [3, 103]])
</code></pre>
<p>How can I do it with numpy?</p> | <p>This is so called <code>column_stack</code></p>
<pre><code>np.column_stack((a,b))
Out[309]:
array([[ 1, 101],
[ 2, 102],
[ 3, 103]])
</code></pre> | arrays|numpy | 2 |
19,842 | 66,862,566 | Easiest method to interpolate over missing dates in a time series? | <p>I have some stock market data in excel covering the past 20 years or so which contains gaps from holidays and weekends. I wish to interpolate over those missing dates to obtain the approximate stock index for those days.<br />
<a href="https://i.stack.imgur.com/4e7RU.png" rel="nofollow noreferrer"><img src="https://... | <p>Pandas has methods specifically for this type of situation:</p>
<pre><code>df.interpolate() # will fill in based on the linear average of the before and after
df.fillna(method='ffill') # forward fill
df.fillna(method='bfill') # backward fill
</code></pre> | python|pandas|interpolation | 1 |
19,843 | 47,271,631 | Assign variable in pytorch | <p><strong>I'd like to know if it is possble to the following code, but now using pytorch, where dtype = torch.cuda.FloatTensor. There's the code straight python (using numpy):</strong> Basically I want to get the value of x that produces the min value of fitness.</p>
<pre><code>import numpy as np
import random as ran... | <p>You can simply do as follows.</p>
<pre><code>import torch
dtype = torch.cuda.FloatTensor
def main():
pop, xmax, xmin = 30, 5, -5
x = (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
y = torch.pow(x, 2)
[miny, indexmin] = y.min(0)
best = x.squeeze()[inde... | gpu|assign|pytorch | 0 |
19,844 | 68,196,785 | How To Loop Through Pandas df? | <p>I have this df</p>
<p><a href="https://i.stack.imgur.com/owHWK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/owHWK.jpg" alt="Covid-19 Italy" /></a></p>
<p>and I want to create a loop that is capable to get specified value:</p>
<ul>
<li>the sum of people (between M and F) vaccinated,</li>
<li>sum... | <p>I think what you want is a groupby.</p>
<pre><code>cols = [s for s in vaccini.columns if s.startswith('sesso') or s.endswith('dose')]
vaccini.groupby(['fornitore', 'fascia_anagrafica', 'nome_area'])[cols].sum()
</code></pre>
<p>This would sum the provided columns within each group. If you want a specific sum, just q... | python|pandas|dataframe|loops|for-loop | 0 |
19,845 | 45,877,690 | Replace a a column of values with a column of vectors in pandas | <p>I'm using python pandas to organize some measurements values in a DataFrame.
One of the columns is a value which I want to convert in a 2D-vector so let's say the column contains such values:</p>
<pre><code> col1
25
12
14
21
</code></pre>
<p>I want to have the values of this column changed one by one (in a fo... | <p>That exception comes from the fact that you want to insert a <code>list</code> or <code>array</code> in a column (<code>array</code>) that stores <code>int</code>s. And <code>array</code>s in Pandas and NumPy can't have a "ragged shape" so you can't have 2 elements in one row and 1 element in all the others (except ... | python|arrays|pandas|dataframe | 1 |
19,846 | 45,963,576 | Python write value from dictionary based on match in range of columns | <p>From my df showing employees with multiple levels of managers (see prior question <a href="https://stackoverflow.com/questions/45929048/python-hierarchy-from-manager-and-employee-id">here</a>), I want to map rows to a department ID, based on a manager ID that may appear across multiple columns:</p>
<pre><code>eid, ... | <p>I added a solution, if manager columns (mid,l2mid,l3mid) value match the dictionary keys, then the values are joined splitted by <code>,</code>:</p>
<pre><code>s = df.drop('eid',1).applymap(country.get)
.dropna(how='all', axis=0)
.apply(lambda x: ', '.join(x.dropna()), 1)
df = df.loc[s.index].assign(co... | python|pandas | 2 |
19,847 | 50,938,992 | TensorFlow lite: High loss in accuracy after converting model to tflite | <p>I have been trying TFLite to increase detection speed on Android but strangely my .tflite model now almost only detects 1 category.</p>
<p>I have done testing on the .pb model that I got after retraining a mobilenet and the results are good but for some reason, when I convert it to .tflite the detection is way off.... | <p>I faced the same issue while I was trying to convert a .pb model into .lite.</p>
<p>In fact, my accuracy would come down from 95 to 30!</p>
<p>Turns out the mistake I was committing was not during the conversion of .pb to .lite or in the command involved to do so. But it was actually while loading the image and pr... | tensorflow|tensorflow-lite | 5 |
19,848 | 66,688,358 | Not able to use Embedding Layer with tf.distribute.MirroredStrategy | <p>I am trying to parallelize a model with embedding layer, on tensorflow version 2.4.1 . But it is throwing me the following error :</p>
<pre><code>InvalidArgumentError: Cannot assign a device for operation sequential/emb_layer/embedding_lookup/ReadVariableOp: Could not satisfy explicit device specification '' because... | <p>So finally I figured out the problem, if anyone is looking for an answer.</p>
<p>Tensorflow does not have complete GPU implementation of Adagrad optimizer as of now. ResourceSparseApplyAdagradV2 operation gives error on GPU, which is integral to embedding layer. So it can not be used with embedding layer with data p... | python|tensorflow|tensorflow2.0|multi-gpu | 3 |
19,849 | 66,464,114 | Why does pandas Dataframe bfill or ffill yield random results when used with groupby? | <p>The following is the example data</p>
<pre><code>id,c1,c2
1,1,g1
2,,g2
3,,g1
4,2,g2
5,,g1
6,,g2
7,3,g1
8,,g2
9,,g1
10,4,g2
11,,g1
12,,g2
</code></pre>
<pre><code>df=pd.read_clipboard(sep=',')
</code></pre>
<p><a href="https://i.stack.imgur.com/RMljB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com... | <p>I only found this answer after writing the question. I will close my question, but still publish it so the future generation have a better chance of finding it on Google.</p>
<p><a href="https://stackoverflow.com/questions/44403916/pandas-why-does-bfill-ffill-act-differently-than-ffill-bfill-on-group">(pandas) Why d... | python|pandas|dataframe | 0 |
19,850 | 66,505,026 | How to solve type object 'Series' has no attribute '_get_dtypes' error using modin.pandas? | <p>I am using modin.pandas to remove the duplicates from dataframe.</p>
<pre><code>import modin.pandas as pd
import json, ast
df = pd.DataFrame(columns=['contact_id', 'test_id'])
df['test_id'] = df['test_id'].astype(str) # Coverting test_id column data type to string
df = df.drop_duplicates(subset=['test_id', 'contac... | <p>It looks like that Modin version, which you are using, is old enough. I don't have the issue on the latest master. Please, try install Modin from sources:</p>
<pre><code>pip uninstall modin # remove current Modin at first
pip install git+https://github.com/modin-project/modin
</code></pre>
<p>By the way, Modin relea... | python|pandas|dataframe|modin | 1 |
19,851 | 66,501,368 | Filling In Empty Dates With Previous Data in Pandas | <p>So I have the current file in Excel where I have dates and don't have dates for everything which can be seen.</p>
<p><a href="https://i.stack.imgur.com/Mxv5j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mxv5j.png" alt="enter image description here" /></a></p>
<p>I read this excel file into a pa... | <p>After reading the data into a dataframe, you can fill missing values using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">fillna</a> with method='ffill' for forward fill</p> | python|pandas | 1 |
19,852 | 66,580,936 | Install pandas on Mac M1 Big Sur into multiple virtualenv | <p>Like many others I was not able to install (using pip) pandas on my MacBook M1, eventually thanks to this <a href="https://stackoverflow.com/a/66048187/9095551">answer</a> I managed to install it from source.<br />
After cloning pandas the steps are</p>
<pre><code>source venv/bin/activate
pip install cython
cd panda... | <p>Instead of <code>python3 setup.py install</code> run <code>pip wheel .</code>, save the wheel from <code>dist/</code> folder and next time install from the wheel:</p>
<pre><code>pip install /path/to/pandas.whl
</code></pre> | python|pandas|pip|apple-m1 | 1 |
19,853 | 57,686,968 | Getting KeyError while merging pandas dataframe: Name: TimeStamp, dtype: datetime64[ns] | <p><b>Getting error while trying to merge two dataframes on datetime column</b></p>
<p>Where df1 has:</p>
<pre><code>TimeStamp Value1
01-01-2019 00:00:00 v1
</code></pre>
<p>And df2 will have:</p>
<pre><code>TimeStamp Value2
01-01-2019 9:23:52 v5
01-01-2019 10:33:52 ... | <p>First of all reverse the <em>merge</em> direction. A more natural approach is that
the "base" DataFrame is <em>df2</em>.</p>
<p>The second point to correct is that the merge should be on <em>TimeStamp</em> column,
converted to <em>DateTime</em> and in case of <em>df2</em> - with the time part "cancelled"
(I assume ... | python-3.x|pandas|dataframe|merge|datetime-format | 1 |
19,854 | 70,632,628 | How to convert this Python code to SQL query using only a select statement? | <p>I have created a data frame in Python like given below</p>
<pre><code> df = pd.DataFrame({'status': ["Applied", "Applied", "NotApplied", "Applied", "NotApplied", "Applied", "Applied"],
'date1': ["2022-02-02", "2022-03-10&qu... | <pre><code>select status, date2 as 'date1', date2 from table where status = 'Applied'
</code></pre> | python|sql|pandas|date | 1 |
19,855 | 51,530,947 | How to add data from another DataFrame, where differing granularities of dates match? | <p>Hello I am newish to python and pandas</p>
<p>I have two DataFrames, one on a higher timeframe with Daily granularity, and one on a lower timeframe with hourly granularity. What I want to do is append the 'trend' data from the higher timeframe to the lower time frame where the day is the same. I'm having some troub... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a>:</p>
<pre><code>d = {'state_x':'state','state_y':'trend'}
df = pd.merge_asof(df2, df1, on='time', direction='forward').rename(columns=d)
print (df)
time ... | python|pandas|date|dataframe | 1 |
19,856 | 51,449,901 | Sort words alphabetically in each row of a dataframe python | <p>I have a column in dataframe which contains string values as given below:</p>
<pre><code>sortdf=pd.DataFrame(data= {'col1':["hello are you","what happenend","hello you there","issue is in our program","whatt is your name"]})
</code></pre>
<p>I want to sort each word in a element alphabetically.</p>
<p>Desired out... | <p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow noreferrer"><code>pd.Series.apply</code></a> with an anonymous <code>lambda</code> function:</p>
<pre><code>sortdf['col1'] = sortdf['col1'].apply(lambda x: ' '.join(sorted(x.split())))
</code></pre>
<p><co... | python|string|pandas|sorting|dataframe | 5 |
19,857 | 51,891,651 | Interval look-up on pandas DataFrame | <p>There are two dataframes, <code>df_A</code> and <code>df_B</code></p>
<pre><code>df_A
Out[61]:
A B
0 1 10
1 2 60
2 3 40
df_B
Out[62]:
A B D
0 1 5 10
1 1 10 25
2 1 20 60
3 2 5 10
4 2 10 25
5 2 20 60
6 3 10 20
7 3 15 40
8 3 25 80
</code></pre>
<p>Now I need to left j... | <p>I'm sure there is a more pandas / vectorized way to do this but here is an option:</p>
<pre><code>C = []
for A, B in zip(df_A['A'],df_A['B']):
idx = ((df_B[df_B['A']==A]['B'] > B).cumsum() == 0).sum() - 1
C.append(df_B[df_B['A']==A].iloc[idx,-1])
df_C = df_A.copy(deep=True).assign(C=C)
</code></pre>
<p... | python|pandas | 0 |
19,858 | 51,663,572 | Add/fill pandas column based on range in rows from another dataframe | <p>Working with pandas, I have df1 indexed by time samples:</p>
<pre><code>data = '''\
time flags input
8228835.0 53153.0 32768.0
8228837.0 53153.0 32768.0
8228839.0 53153.0 32768.0
8228841.0 53153.0 32768.0
8228843.0 61345.0 32768.0'''
fileobj = pd.compat.StringIO(data)
df1 = pd.... | <p>I think you can using <code>IntervalIndex</code> with <code>loc</code></p>
<pre><code>df2.index=pd.IntervalIndex.from_arrays(df2.start,df2.end,'both')
df2.loc[df.index]
Out[174]:
check start end
[1, 2] True 1 2
[4, 5] True 4 5
[7, 8] True 7 8
df['newcol']=df2.loc[df.index].c... | python|pandas | 2 |
19,859 | 51,897,251 | Check, if one Line Segment intersects with a set of line segments | <p>I have a a line segment <code>AB</code> (2d) from point <code>A</code> to point <code>B</code>. For the representation of a <code>coastline</code> (closed polygon, 3*10^3 vertices), I have a <code>NumPy</code> array (2d) of points which start and end at the same point. I want to know, if the connection between point... | <p>This is a collision detection problem.</p>
<p>So in your case the best is to put your coastline inside one spatial datastrcture such as bsp-tree, quad-tree, aabb-tree, etc.</p>
<p>Then perform intersection between your line segment and the tree-structure.</p>
<p>See for instance CGAL AABB_tree:
<a href="https://d... | python|algorithm|performance|numpy|cython | 2 |
19,860 | 35,842,357 | From which index array values are inside a specific error band? | <p>Is there any built-in <code>numpy</code> function to check from which index a signal (array) does not leave a specific error band?</p>
<hr>
<p>Working with digital filters, I need to determine the length of an impulse response to use in <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.filt... | <p>In general, no. You're taking advantage of some signal-specific knowledge that isn't universally applicable (the fact the envelope decays with time). Your solution is a good one I think if you want to do it numerically. </p>
<p>You could do someting like take the impulse response equation, symbolically differen... | python|numpy|scipy|signal-processing | 0 |
19,861 | 37,309,910 | Substitute numpy functions with Python only | <p>I have a python function that employs the numpy package. It uses numpy.sort and numpy.array functions as shown below:</p>
<pre><code>def function(group):
pre_data = np.sort(np.array(
[c["data"] for c in group[1]],
dtype = np.float64
))
</code></pre>
<p>How can I re-write the sort and ... | <p>Well, it's not strictly possible because the return type is an <code>ndarray</code>. If you don't mind to use a list instead, try this:</p>
<pre><code>pre_data = sorted(float(c["data"]) for c in group[1])
</code></pre> | python|arrays|sorting|numpy | 2 |
19,862 | 37,599,647 | Group by and aggregate problems for numpy arrays over word vectors | <p>My pandas data frame looks something like this:</p>
<pre><code>Movieid review movieRating wordEmbeddingVector
1 "text" 4 [100 dimensional vector]
</code></pre>
<p>I am trying to run a doc2vec implementation and I want to be able to group by movie ids and the take the sum of the vectors in w... | <p>There is a bug in your code. Inside your lambda function you sum across the entire dataframe instead of just the group. This should fix things:</p>
<pre><code>movie_groupby = movie_data.groupby('movie_id').agg(lambda v: np.sum(v['textvec']))
</code></pre>
<p>Note: I replaced <code>hotel_data</code> with <code>movi... | python|pandas|machine-learning|word2vec|doc2vec | 0 |
19,863 | 64,544,351 | IndexError: index 0 is out of bounds for axis 0 with size 0 for trying to find mode (most frequent value) | <p>I concatenated 500 XSLX-files, which has the shape (672006, 12). All processes have a unique number, which I want to groupby() the data to obtain relevant information. For temperature I would like to select the first and for number the most frequent value.</p>
<p>Test data:</p>
<pre><code>df_test =
pd.DataFrame({&q... | <p>I think your problem is one or more of your groupby is returning all NaN heights:</p>
<p>See this example, where I added a number 4 with np.NaN as its heights.</p>
<pre><code>df_test = pd.DataFrame({"number": [1,1,1,1,2,2,2,2,3,3,3,3,4,4],
'temperature': [2,3,4,5,4,3,4,5,5, 3, 4, 4, 5, 5],
'height': [100... | python|pandas|index-error | 1 |
19,864 | 64,508,754 | Pandas pd.series returns a data frame | <p>I want to ask a question about Panda's series.</p>
<p>I am reading a book on Python on Data Science by O'Reilly publications and was reading on Pandas.</p>
<p>Consider the following code:</p>
<pre><code>frame = pd.DataFrame(np.random.randn(4,3), columns=list('bde'),
index=['Utah', 'Ohio', 'Texas', 'O... | <p>A Pandas Series is a 1D array of some type. A DataFrame is a 2D array where each column is a Series and they can have different types.</p>
<p>However, the part you are probably missing is that the "type" can be the generic Python <code>object</code> which is a reference to any object. For example:</p>
<p... | python|pandas|dataframe|series | 0 |
19,865 | 47,601,533 | Getting a crime 'count' from pandas big dataset | <p>This is quite a broad question because I can't copy all the different things I have tried. From this dataset of NYPD crime: <a href="https://data.cityofnewyork.us/Public-Safety/NYPD-Complaint-Data-Historic/qgea-i56i" rel="nofollow noreferrer">https://data.cityofnewyork.us/Public-Safety/NYPD-Complaint-Data-Historic/q... | <p>It seems like this would be a very good time to use the groupby method. You could implement <code>df.groupby(['CMPLNT_FR_DT', 'Borough']).count()</code>, which will give you a new dataframe with a count of all of the instances with the same date and borough regardless of the format of the date so long as they are a... | python|pandas|loops|bigdata | 2 |
19,866 | 47,937,697 | Scalable solution for str.contains with list of strings in pandas | <p>I am parsing a pandas dataframe <code>df1</code> containing string object rows. I have a reference list of keywords and need to delete every row in <code>df1</code> containing any word from the reference list.</p>
<p><em>Currently, I do it like this:</em></p>
<pre><code>reference_list: ["words", "to", "remove"]
df... | <p>For a scalable solution, do the following - </p>
<ol>
<li>join the contents of words by the regex OR pipe <code>|</code></li>
<li>pass this to <code>str.contains</code></li>
<li>use the result to filter <code>df1</code></li>
</ol>
<p>To index the 0<sup>th</sup> column, don't use <code>df1[0]</code> (as this might ... | python|regex|string|pandas|dataframe | 18 |
19,867 | 49,256,211 | How to set unexpected data type to na? | <p>I have a data frame like this:</p>
<pre><code>a = pd.DataFrame({'foo':[1,2,3,'str']})
foo
0 1
1 2
2 3
3 str
</code></pre>
<p>I want to set the data type to int64:</p>
<pre><code>a['foo'].astype('int32')
</code></pre>
<p>but I got an error message:</p>
<pre><code>ValueError: invalid literal for int(... | <p>The best is convert all values to <code>float</code>s, because <code>NaN</code>s are <code>float</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> with parameter <code>errors='coerce'</code>:</p>
<pre><code>df = pd.... | python|pandas | 4 |
19,868 | 49,191,254 | Python loop output | <p>I have tried looping into a column, there are three different values which should be filled in the columns but only one value is getting filled.</p>
<pre><code>for i in df_j['token']:
if i in ["AK","BK","BW","AC","AK","AR","BA"]:
df_j['check']='1_Check'
elif i in ["AW","AA"]:
df_j['check']='... | <p>You could search SO, find <a href="https://stackoverflow.com/questions/21702342/creating-a-new-column-based-on-if-elif-else-condition">Creating a new column based on if-elif-else condition</a> and apply <a href="https://stackoverflow.com/a/21711869/7505395">Zelazny7's answer</a> to your situation.</p>
<p>This is a ... | python|python-3.x|pandas | 0 |
19,869 | 49,116,343 | Dataset API 'flat_map' method producing error for same code which works with 'map' method | <p>I am trying to create a create a pipeline to read multiple CSV files using TensorFlow Dataset API and Pandas. However, using the <code>flat_map</code> method is producing errors. However, if I am using <code>map</code> method I am able to build the code and run it in session. This is the code I am using. I already o... | <p>As <a href="https://stackoverflow.com/questions/49116343/dataset-api-flat-map-method-producing-error-for-same-code-which-works-with-ma#comment85240575_49116343">mikkola points out in the comments</a>, the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#map" rel="noreferrer"><code>Dataset.map()</c... | pandas|tensorflow|tensorflow-datasets | 9 |
19,870 | 49,186,198 | Python: unable to convert list to Pandas dataframe | <p>I able to get raw javascript raw data from a link to a list datatype but unable to convert it to Pandas Dataframe.</p>
<pre><code>import re
import request
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = req... | <p>This is probably the ugliest answer but it seems to work. The response from that url is a JavaScript object so my thought was to use <code>JSON.stringify</code> to parse it into proper JSON as shown here:</p>
<ul>
<li><a href="https://repl.it/repls/ImmaculateGainsboroEmulators" rel="nofollow noreferrer">https://rep... | python|pandas | 0 |
19,871 | 58,611,013 | reading a JSON file and converting to CSV with python pandas | <p>i have this json file i wanted to convert it to CSV using pandas</p>
<pre><code> {
"partes": [
{
"processo": "1001824-89.2019.8.26.0493",
"tipo": "Reqte: ",
"nome": "Sérgio Izaias Massaranduba Advogada: Mariana Pretel E Pretel ",
... | <ul>
<li>Remember that <code>pandas</code> is about tables of data, with repeating column headers.</li>
<li>The JSON presented here, as a whole, does not correspond to tabular data.</li>
<li>This JSON needs to be read in by separate keys</li>
<li>Alternatively, <code>partes</code> and <code>movimentacoes</code> must be... | python|json|pandas | 2 |
19,872 | 70,085,474 | How to resample hourly this dataframe? | <p>I have this dataset, I'm trying to have a mean of "AC_POWER" every hour but isn't working properly. The dataset have 20-22 value every 15 minutes. I want to have something like this:</p>
<pre><code> DATE AC_POWER
'15-05-2020 00:00' 400
'15-05-2020 01:00' 500
'15-05-2020 02:00' 500
'15-05-2020 ... | <p>I think you're looking for <code>DataFrame.resample</code>:</p>
<pre><code>df.resample(rule='H', on='DATE_TIME')['AC_POWER'].mean()
</code></pre> | python|pandas | 0 |
19,873 | 70,212,523 | Select random ordered sequence from dataframe | <p>Given an example dataframe which holds data such as that below:</p>
<pre><code>ID Field_1 Field_2 Group
1 ABC XYZ B
2 BCD ABF B
3 EEJ KYA B
..
12 KAS UUY Z
13 OEP PLO Z
..
84 HJH HIE N
85 YSU SAR N
</code></pre>
<p>How can one get a random, <st... | <p>One simple method would be to generate a dictionary of groups and use a list comprehension with <code>sample</code> and <code>pandas.concat</code>:</p>
<pre><code>order = ['B', 'Z', 'N', 'B']
d = dict(list(df.groupby('Group')))
df_sample = pd.concat([d[k].sample(1) for k in order])
</code></pre>
<p>output:</p>
<pre>... | python|python-3.x|pandas|dataframe | 1 |
19,874 | 56,387,280 | Python math operation on column | <p>Data from json is in df and am trying to ouput to a csv.
I am trying to multiply dataframe column with a fixed value and having issues how data is displayed</p>
<p>I have used the following but the data is still not how i want to display</p>
<pre class="lang-py prettyprint-override"><code>df_entry['Hours'] = df_en... | <p>That happens because the dtype of the column is str. You need to convert it to float before multiplication.</p>
<pre><code>df_entry['Hours'] = df_entry['Hours'].astype(float) * 2
</code></pre> | python|pandas|dataframe|multiplication | 2 |
19,875 | 56,070,864 | python pandas : lambda or other method to count NaN values / len(value)<1 along rows | <p>Derive a new pandas column based on lengh of string in other columns</p>
<p>I want to count the number of columns which have a value in each row and create a new column with that number. Assume if I have 6 columns and two columns starts with a have some value then new column for that row will have the value 2.</p>
... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>DataFrame.filter</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ne.html" rel="nofollow noreferrer"><code>Series.ne</code></a> and <a... | python|pandas|nan | 2 |
19,876 | 56,048,345 | Is there a way to use the "read_csv" method to read the csv files in order they are listed in a directory? | <p>I am plotting plots on one figure using matplotlib from csv files however, I want the plots in order. I want to somehow use the read_csv method to read the csv files from a directory in the order they are listed in so that they are outputted in the same fashion.</p>
<p>I want the plots listed under each other the s... | <p>you could use <code>os.listdir()</code> to get all the files in the folder and then sort them out in a certain way, for example by name(it would be enough using the python built in <code>sorted()</code> ). Instead if you want more fancy ordering you could retrieve both the name and last modified date and store them ... | python|pandas|csv|matplotlib|python-3.7 | 2 |
19,877 | 56,361,893 | efficiently aggregate large CSV file with multiple int columns | <p>I have a large CSV file with some string type columns (dtype <code>object</code>) and other columns that are <code>int64</code> type.<br>
Both the string columns and the integer columns can be empty in the CSV. An empty value in the integer columns represent zero and an empty string should stay an empty string. </p>... | <p>If the file is unsorted it is hard to process without using a lot of memory: you need to keep a running aggregation for every key (list of dimension values) that appears in the file. There might be a good way to do that but it depends on details like how many possibilities there are. It might be possible to do the... | python|pandas|csv|dask | 1 |
19,878 | 56,128,043 | how to find standard deviation of pandas dataframe column containg list in every row? | <p>i have an pandas dataframe </p>
<p>dd1=</p>
<pre><code> A B C D E F Result
10 18 13 11 9 25 []
6 32 27 3 18 28 [6,32]
4 6 3 29 2 23 [29,35,87]
</code></pre>
<p>now i want to find std of result column by adding C column value with Result column 1st value... | <p>Try using <code>lambda</code> and <code>apply</code>:</p>
<pre><code>l = lambda x: sum([np.std([x['C'], i], ddof=1) for i in x['Result']])
dd1['output'] = dd1.apply(l, 1)
</code></pre> | python|pandas|dataframe|standard-deviation | 1 |
19,879 | 55,930,479 | TypeError When Utilizing Include_Numbers Feature In WordCloud | <p>I'm trying to utilize the WordCloud package in python and am getting errors when trying to utilize the include_numbers parameter. I've copied the github link for the package, the specific parameter definition (I've tried both the correct spelling and noted incorrect spelling) and I get the below error</p>
<p><a hre... | <p>I looked through the wordcloud source code and the issue seems to be that the code on github and the pypi package for pip installing are not the same. The version you get when pip installing does not contain the include_numbers parameter.</p>
<p>I submitted this issue on github here: <a href="https://github.com/amu... | python|pandas|word-cloud | 0 |
19,880 | 55,999,813 | Preserve sign when squaring values in dataframe | <p>I have tried this: </p>
<pre><code>>>> (-10) ** 2
100
>>> -10 ** 2
-100
</code></pre>
<p>In short, I was trying to get the output of the negative values squaring as negative.<br>
So I tried the above simple expressions.<br>
Then I tried the same formula on Pandas DataFrame, but I received ll the... | <p>You can multiple values by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.sign.html" rel="nofollow noreferrer"><code>numpy.sign</code></a> for <code>-1</code> for negative values:</p>
<pre><code>print (df**2 * np.sign(df))
0
0 -100
1 -4
2 4
3 9
4 16
5 25
6 -10000
... | python|pandas | 3 |
19,881 | 55,913,594 | how to best structure multiple time series for multiple stocks? | <p>I'm new to the world of Pandas, and am trying to figure out best practices for structuring the data frame(s) for various time calculations on financial time series.</p>
<p>I'm currently importing pricing time series as follows:</p>
<pre><code>data_frames = { }
START_DATE = '2000-01-01'
TICKERS = [ 'SPY', 'VWO', 'T... | <p>You could drop the index level <code>symbol</code> into a column as categorical variable</p>
<pre class="lang-py prettyprint-override"><code>df = data_frames.drop_index(level='symbols')
</code></pre>
<p>Then you can select your data based on that column (<code>df[df['type''] == 'SPY']</code>) or perform operations... | pandas | 0 |
19,882 | 64,824,027 | Average measure for all GPS points within certain range | <p>I have a pandas dataframe with latitude, longitude, and a measure for 100K+ GPS points.</p>
<pre><code>df = pd.DataFrame({'lat': [41.260637, 45.720185, 45.720189, 45.720214, 45.720227, 46.085716, 46.085718, 46.085728, 46.085730, 46.085732],
'lng': [2.825920, 3.068014, 3.068113, 3.067929, 3.068199, 3.34165... | <p>In this example, the point itself is always included itself. Making it part of the average itself. You would need to modify that part if you want to exclude the point itself.</p>
<p>We can use BallTree</p>
<pre><code>import pandas as pd
from sklearn.neighbors import BallTree
import numpy as np
</code></pre>
<p>And ... | python|pandas|gps|pandas-groupby|distance | 1 |
19,883 | 39,878,921 | python Numpy transpose and calculate | <p>I am relatively new to python and numpy. I am currently trying to replicate the following table as shown in the image in python using numpy.</p>
<p><a href="https://i.stack.imgur.com/nVKbb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nVKbb.png" alt="enter image description here"></a>
As in the... | <p>Try this out :</p>
<pre><code>import numpy as np
import pandas as pd
a=np.array([(1,-1,10),(1,0,10),(1,-2,15),(1,-3,1),(1,-4,1),(1,0,12),(1,-5,16)], dtype=[('group',float),('sub_group',float),('value',float)])
df = pd.DataFrame(a)
for i in df.index:
col_name = str(int(df['sub_group'][i]))
df[col_name] = N... | python|arrays|pandas|numpy | 1 |
19,884 | 40,052,290 | Loop for pandas columns | <p>I want to apply kruskal test for several columns. I do as bellow</p>
<pre><code>import pandas as pd
import scipy
df = pd.DataFrame({'a':range(9), 'b':[1,2,3,1,2,3,1,2,3], 'group':['a', 'b', 'c']*3})
</code></pre>
<p>and then the Loop</p>
<pre><code>groups = {}
res = []
for grp in df['group'].unique():
for co... | <p>Your for loops are upside down: the one-column algorithm is your loop invariant with regards to the column you chose. So the column for loop must be the outer loop. In plain English "for each column apply the kruskal algorithm which consists of this group.unique for loop:</p>
<pre><code>groups = {}
res = []
for col... | python|loops|pandas | 1 |
19,885 | 39,502,345 | Compare columns of Pandas dataframe for equality to produce True/False, even NaNs | <p>I have two columns in a pandas dataframe that are supposed to be identical. Each column has many NaN values. I would like to compare the columns, producing a 3rd column containing True / False values; <em>True</em> when the columns match, <em>False</em> when they do not.</p>
<p>This is what I have tried:</p>
<pre><c... | <p>Or you could just use the <code>equals</code> method:</p>
<pre><code>df['new_column'] = df['column_one'].equals(df['column_two'])
</code></pre>
<p>It is a batteries included approach, and will work no matter the <code>dtype</code> or the content of the cells. You can also put it in a loop, if you want.</p> | python|pandas|dataframe | 10 |
19,886 | 39,507,433 | Fill missing values from another Pandas dataframe with different shape | <p>I have 2 tables of different sizes which I would like to merge in the following way in Python using Pandas:</p>
<pre><code>UID Property Date
1 A 10/02/2016
2 B NaN
3 A 10/02/2016
4 C NaN
5 C NaN
6 A 10/02/2016
</code></pre>
<p>Table 1 conta... | <p>First let's merge the two datasets: we don't overwrite the original date:</p>
<pre><code>df_merge = pandas.merge(T1, T2, on='Property')
</code></pre>
<p>then we replace the missing values copying them from the 'DateProxy' field:</p>
<pre><code>df_merge.Date = df_merge.apply(
lambda x: x['Date'] + ' (kept from... | python|pandas|merge | 1 |
19,887 | 39,553,271 | I can load multiple stock tickers from yahoo finance, but I am having trouble adding new columns before it is saved to a csv | <p>The code below starts by uploading data from yahoo finance in pnls. It does this successufly. Then I have code where I want to add columns to the loaded data in pnls. This part is unsuccessful. Finally I want to save pnls to a csv file which it does successfully if the column changes are not in the code.</p>
<p>The... | <p>The line</p>
<pre><code>pnls = {i:dreader.DataReader(i,'yahoo','1985-01-01',datetime.today()) for i in symbols}
</code></pre>
<p>builds a python <code>dict</code> (using <a href="https://stackoverflow.com/questions/14507591/python-dictionary-comprehension">dictionary comprehension</a>). To check this, you can run ... | python|csv|pandas|dataframe | 1 |
19,888 | 43,949,089 | Data frame manipulation with Date | <p>I have 2 data frames as follow:</p>
<p>df1:</p>
<pre><code> id Grade Date
1 78 15 2016-05-23
2 99 12 2015-08-01
</code></pre>
<p>df2: </p>
<pre><code> rate
2015-01-01 1.22
2015-02-01 1.12
...
2015-05-01 1.05
2017-01-01... | <p>If you set the df2 index to a monthly <code>PeriodIndex</code>:</p>
<pre><code>In [11]: df2.index = df2.index.to_period("M")
In [12]: df2
Out[12]:
rate
2015-01 1.22
2015-02 1.12
2016-05 1.32
2015-08 1.23
</code></pre>
<p>Now, you can pull out the rates efficiently with <code>df2.loc</code>:</p>
<pre... | python|date|pandas|datetime | 2 |
19,889 | 44,083,740 | Successfully installed Tensorflow-GPU, After "import tensorflow" nothing will be printed out | <pre><code>Installing collected packages: wheel, six, appdirs, pyparsing, packaging, setuptools, protobuf, werkzeug, numpy, tensorflow-gpu
Successfully installed appdirs-1.4.3 numpy-1.12.1 packaging-16.8 protobuf-3.3.0 pyparsing-2.2.0 setuptools-35.0.2 six-1.10.0 tensorflow-gpu-1.1.0 werkzeug-0.12.2 wheel-0.29.0
(py35... | <p>If I recall correctly import statements don't return anything. So nothing happening after <code>import tensorflow</code> is a good thing as there were no errors to be shown. As you said, using <code>sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))</code> gave you the correct output, showing that t... | python|deep-learning|tensorflow | 1 |
19,890 | 69,451,740 | Group a pandas df on variable columns | <p>I have a dataframe which I want to aggregate as follows: I want to group by col1 and col6 and make a new column for col2 and col3.</p>
<pre><code>col1 col2 col3 col6
a it1 3 f
a it2 5 f
b it6 7 g
b it7 8 g
</code></pre>
<p>I would like the result t... | <p>It is not entirely clear what you are trying to achieve so here are two ideas. First, if you are going to convert to json anyway, you can convert each group to json:</p>
<pre><code>df.groupby(['col1','col6']).apply(lambda d: d.to_json())
</code></pre>
<p>produces</p>
<pre><code>col1 col6
a f {"col1&q... | python|pandas|pandas-groupby|aggregate | 0 |
19,891 | 69,647,801 | My Python Selenium code doesn't work with options | <p>i'm using a selenium code in spyder 3.8 with anaconda. The issue is that it works perfectly when i don't add any option to the driver, it goes to the url and click the thins it has to, but for some reason when i add options it just opens the browser, but doesn't go to the url and can't continue with the code. This i... | <p>The problematic entry in your options is:</p>
<pre><code>"plugins.always_open_pdf_externally": True
</code></pre>
<p>I'd recommend use this one instead:</p>
<pre><code>"plugins.plugins_list": [{"enabled": False, "name": "Chrome PDF Viewer"}]
</code></pre>
<p>It does ... | python|pandas|selenium|webdriver|selenium-chromedriver | 0 |
19,892 | 41,158,045 | What is the meaning of the parameter 3 in the given numpy statement? | <p>The following is a numpy statement.</p>
<pre><code>np.zeros((512,512,3), np.uint8)
</code></pre>
<p>In the above statement what does 3 stand for?</p> | <p>The result will be a 3d array, of shape <code>(512,512,3)</code>. You can name the dimensions what is convenient, or suits the application. The numbers suggest a 512x512 image, with 3 values (RGB) per pixel. The <code>np.uint8</code> <code>dtype</code> is consistent with that.</p>
<p>Strictly speaking the expres... | numpy | 0 |
19,893 | 41,159,512 | How to use Timestamp Data in Building Naive Bayes model in Python | <p>I have a Dataset, with Timestamp as one of the column with the format 09/07/2016 23:58.</p>
<p>I'm trying to apply Naive Bayes on this Data, and i'm facing the below error. Please let me know how to use this Data in my model</p>
<p>ValueError: invalid literal for float(): 12/06/2016 23:59</p> | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with parameter <code>errors='coerce'</code> for convert bad not parseable values to <code>NaT</code>:</p>
<pre><code>df = pd.DataFrame({'date':['12/06/2016 23:59','... | python|python-2.7|pandas|timestamp|naivebayes | 2 |
19,894 | 41,227,876 | Python - mutate row elements using array of indices | <p>given the following array:</p>
<pre><code>import numpy as np
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
</code></pre>
<p>I can create an array of indices:</p>
<pre><code>b = np.array([0, 2, 0, 1])
</code></pre>
<p>and mutate one element from each row using the indices:</p>
<pre><code>a[np.arange(4... | <p>Maybe writing it out more explicitly would help for "readability":</p>
<pre><code>x = np.array([0, 2, 0, 1])
y = numpy.arange(x.size)
a[y, x] += 10
</code></pre>
<p>Otherwise, you are doing it in a very clear and succinct way, in my opinion.</p>
<p>Another option is to use a <code>ufunc</code>:</p>
<pre><code>nu... | python|arrays|numpy | 0 |
19,895 | 53,911,121 | Make output files from different input files | <p>I have multiple files with table like this:</p>
<pre><code>16,15363,623
46,1001,209
79,74241,372
91,68063,105
57,56049,86
</code></pre>
<p>I would like to make one output file for each of this files, that shows
column average, sum, max and minimum.for ex.(output.txt)--max of the first column is : 91. Is it pos... | <p>you can iterate through the files in a folder by using the below code</p>
<pre><code>import pandas as pd
import os
import glob
os.chdir(r'C:folder_path\')
File_list = glob.glob('*.txt')
for file in FileList:
df = pd.read_csv(file,sep=",") #or any other seperator, check docs
df1 = Do Some calculations and sa... | python-3.x|pandas | 1 |
19,896 | 38,397,399 | Alternatives to numpy einsum | <p>When I calculate third order moments of an matrix <code>X</code> with <code>N</code> rows and <code>n</code> columns, I usually use <code>einsum</code>:</p>
<pre><code>M3 = sp.einsum('ij,ik,il->jkl',X,X,X) /N
</code></pre>
<p>This works usually fine, but now I am working with bigger values, namely <code>n = 120... | <p>Note that calculating this will need to do at least ~n<sup>3</sup> × N = 173 billion operations (not considering symmetry), so it will be slow unless numpy has access to GPU or something. On a modern computer with a ~3 GHz CPU, the whole computation is expected to take about 60 seconds to complete, assuming no... | python|numpy|matrix | 5 |
19,897 | 38,059,796 | Can you use if-else statement inside braces for an array in Python? | <p>I'm wondering if there is a nice way to use an if-else statement inside braces of an array in Python to assign values. What I would like is something like:</p>
<pre><code>A = #some 2D array of length m by n, already initialized
A = np.float64(A)
val = someValue #any number, pick a number
A = [[val for j in range(n... | <p>With numpy arrays we try avoid iteration (list comprehension). Sometimes it is needed, but in this case it is not:</p>
<pre><code>In [403]: A=np.arange(16).reshape(4,4)
In [404]: A1=A.astype(np.float64) # better syntax for converting to float
In [405]: A1
Out[405]:
array([[ 0., 1., 2., 3.],
[... | python|arrays|if-statement|numpy | 8 |
19,898 | 66,316,668 | Get value from dataframe based on column Name and row | <p>I have the following dataframe:</p>
<pre><code>d = {
'weekbegin': ['4/11/2019', '11/11/2019'],
'1': [3, 4],
'2': [31, 4],
'12': [3, 4]
}
df = pd.DataFrame(data=d)
</code></pre>
<p>and following inputs:</p>
<pre><code>value = 4
week = '4/11/2019'
</code></pre>
<p>My question:</p>
<p>I am looking for a... | <p>You are close, need for second argumement in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> column name, so use:</p>
<pre><code>out = df.loc[(df['weekbegin'] == week), str(value)]
</code></pre>
<p>If possible <cod... | python|python-3.x|pandas|string|dataframe | 2 |
19,899 | 46,215,414 | Upscaling a numpy array and evenly distributing values | <p>I have a 2 dimensional numpy array representing spatial data. I need to increase its resolution. I also need to evenly distribute values across the space. For example, a value of</p>
<p>5 </p>
<p>would become:</p>
<p>1.25 1.25</p>
<p>1.25 1.25</p>
<p>I've looked at imresize but I don't think the interpolation o... | <p>Simply divide by the number of elements in the block defined by its height and width and then replicate/ expand. To replicate, we can use <code>np.repeat</code> or <code>np.lib.stride_tricks.as_strided</code>.</p>
<p>With <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow... | python|arrays|numpy | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.