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 |
|---|---|---|---|---|---|---|
366,300 | 51,079,543 | Pandas groupby apply vs transform with specific functions | <p>I don't understand which functions are acceptable for <code>groupby</code> + <code>transform</code> operations. Often, I end up just guessing, testing, reverting until something works, but I feel there should be a systematic way of determining whether a solution will work.</p>
<p>Here's a minimal example. First let... | <p>I believe, in the first place, that there is some room for intuition in using these functions as they can be very meaningful.</p>
<p>In your first result, you are not actually trying to <em>transform</em> your values, but rather to <em>aggregate</em> them (which would work in the way you intended).</p>
<p>But gett... | python|pandas|dataframe|pandas-groupby | 19 |
366,301 | 50,726,622 | tensorflow 1.8 gpu installing only on anaconda environment | <p>installing tensorflow-gpu version on windows through conda environment (steps followed as in <a href="https://www.tensorflow.org/install/install_windows" rel="nofollow noreferrer">https://www.tensorflow.org/install/install_windows</a> )is successful , but after exiting the environment the package is not available.</... | <p>Anaconda is a Python distribution, and Conda is the package manager for Anaconda. </p>
<p>The issue is when you are installing tensorflow, you are installing it inside a Conda environment. This means it will only work in that environment. In order to use it outside the environment, you either need to install it via... | python|tensorflow|anaconda|python-3.6 | 2 |
366,302 | 50,880,183 | Combining columns in Pandas based on column header | <p>I'm needing to merge columns in a dataframe.</p>
<p>The headers will have a similar name with a different suffix, e.g. </p>
<pre><code>A1 | A2 | A3 | B1 | B2 | B3
</code></pre>
<p>I want to end up with all of them merged:</p>
<pre><code>A | B
</code></pre>
<p>I have this line that successfully merges a defined... | <p>You can use the df.columns attribute to find the relevant columns</p>
<pre><code>a_cols = [col for col in df.columns if col[0] == 'A']
</code></pre>
<p>then use that list as the input for your apply function</p>
<pre><code>df['A'] = df[a_cols].apply(' '.join, axis=1)
</code></pre> | python|pandas | 1 |
366,303 | 50,782,911 | Why the network gives the same results for each Input in test? | <p>My network transposes an image, with size 62*71, to a vector of 124 outputs. In the test, I got the same output for each input. I checked 4000 cases.</p>
<p>I cannot seem to signify the problem because the learning seems to be fine, there is an improvement of the error and get a relatively low error.</p>
<p>Someon... | <p>The metric behind a picture is clearly defined. The values of an image often ranges from 0-1 or 0-255. For CNN's you should normalize your input values (0-1).</p>
<p>Thus you have to be careful with your weight initialization. For example, if your have a bias of 0.6 and a value of 0.6, you get a 1.2 as image value ... | python-3.x|tensorflow|neural-network|conv-neural-network | 0 |
366,304 | 50,812,361 | Create matrix with labels on every cell by interval | <p>I have bins and data for filling observation matrix:</p>
<pre><code>a = array([0., 14., 29., 43., 58., 72., 86., 101., 115., 130., 144.])
b = array([10, 26, 36, 48, 64, 71, 91, 105, 123, 133, 141])
</code></pre>
<p>The result that I expect: </p>
<pre><code> 0-13 14-28 29-42 43-57 58-71 72-85 86-100 101-11... | <h3>cut + get_dummies</h3>
<p>Here's one way:</p>
<pre><code>import numpy as np
import pandas as pd
a = np.array([0., 14., 29., 43., 58., 72., 86., 101., 115., 130., 144.])
b = np.array([10, 26, 36, 48, 64, 71, 91, 105, 123, 133, 141])
df = pd.DataFrame({'Values': b})
df['Range'] = pd.cut(df['Values'], a)
d... | python|python-3.x|pandas|numpy | 2 |
366,305 | 50,888,221 | ValueError: Layer leaky_re_lu_1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.layers.convolutional.Conv3D'> | <p>I want to save the value of the convolution in a variable conv1 and then apply the value of conv1 in leaky relu activation function.</p>
<p><strong>Error :</strong></p>
<pre><code>ValueError: Layer leaky_re_lu_1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.layers.convoluti... | <p>You are mixing Keras <a href="https://keras.io/getting-started/sequential-model-guide/" rel="nofollow noreferrer"><code>Sequential</code></a> and <a href="https://keras.io/getting-started/functional-api-guide/" rel="nofollow noreferrer"><code>Functional</code></a> APIs.</p>
<p><strong>Code with <code>Sequential</co... | python|tensorflow|keras|deep-learning|convolutional-neural-network | 3 |
366,306 | 50,866,894 | Reduce number of objects a pretrained Tensorflow model detects | <p>I am using <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb" rel="nofollow noreferrer">this code</a> for object detection and it outputs 100 boxes even though in most pictures there are 0-5 objects. The detection takes 5 seconds on a 250X250 image. W... | <p>Logically it would, i cant say exactly by how much. You can retrain the model to only fewer objects that you are interested in. For training you will also specify objects interested in a file with extension *.pbtxt which has list of objects specified.</p>
<p>Few Links which talk about retraining in detail
<a href="... | tensorflow|object-detection | 0 |
366,307 | 51,083,070 | Cython: Invalid use of fused types, type cannot be specialized | <p>I have the following MCVE:</p>
<pre><code>import numpy as np
cimport numpy as np
cimport cython
from cython cimport floating
def func1(floating[:] X_data, floating alpha):
if floating is double:
dtype = np.float64
else:
dtype = np.float32
cdef floating[:] prios = np.empty(12, dtype=... | <p>Let's start with a smaller reproducer:</p>
<pre><code>%%cython
import numpy as np
from cython cimport floating
def func1(floating[:] X_data):
C = np.empty(12, dtype=np.int_32)
func2(X_data, C)
cpdef func2(floating[:] X_data, int[:] C):
pass
</code></pre>
<p>It doesn't compile. </p>
<p>One important ... | python|numpy|cython|cythonize | 4 |
366,308 | 50,781,103 | Using ssd_random_crop_pad operation in Tensorflow's Object Detection API | <p>I am using Tensorflow's Object Detection API to train an Inception SSD object detection model on Cloud ML Engine and I want to use the various <code>data_augmentation_options</code> as mentioned in the <a href="https://github.com/pkulzc/models/blob/gcp-ready-1.2/research/object_detection/protos/preprocessor.proto" r... | <p>As mentioned <a href="https://github.com/tensorflow/models/issues/4489#issuecomment-396045212" rel="nofollow noreferrer">here</a>, you need a different way to prepare the proto text. Please provide more details for your further question.</p> | tensorflow|object-detection|object-detection-api|data-augmentation | 1 |
366,309 | 51,032,625 | Shared Layers, Different Models | <p>I have two Keras models (functional API) sharing some layers. I m wondering if I train the first model, will the second one get its shared layers' weights updated automatically or should I load the weights manually.</p>
<p>I know from the <a href="https://keras.io/getting-started/functional-api-guide/" rel="nofollo... | <p>When you train the first model, the weights from the shared layers will be updated automatically in every other model. Consider the following example:</p>
<pre><code>x = Input(shape=(input_dim,))
encoder = Dense(output_dim)(x)
decoder = Dense(input_dim)(encoder)
autoencoder = Model(input=x, output=decoder)
supervi... | python|tensorflow|keras | 6 |
366,310 | 50,983,782 | How to filter Pandas rows based on last/next row? | <p>I have two data sets from different pulse oximeters, and plot them with pyplot as displayed below. As you may see, the green data sheet has alot of outliers(vertical drops). In my work I've defined these outlayers as non-valid in for my statistical analysis, they are must certainly not measurements. Therefore I argu... | <p>have a look at <a href="https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.shift.html" rel="nofollow noreferrer">pandas.DataFrame.shift</a>. This is a column-wise operation that shifts all rows in a given column to another row of another column:</p>
<pre><code># original df
x1 ... | python|pandas|numpy | 3 |
366,311 | 50,768,538 | Indices not in range, running LSTM model on sequence data | <p>I am new to Keras and Neural networks. I need to implement and LSTM model on my data set.</p>
<p>My data set consists of sequences like this:</p>
<p>52 53 54 55 66 67 58 59 60
68 69 70 58 59 60
68 71 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 4... | <p>You're almost there, it's just that you are trying every combination it seems until works without thinking about what the values are. Here are 2 changes that would aid your problem:</p>
<ol>
<li>It should be <code>Embedding(nb_features+1, ..., input_length=max_len)</code> because you count number of unique indices ... | python|tensorflow|neural-network|keras|lstm | 0 |
366,312 | 50,992,771 | Train multiple keras/tensorflow models on different GPUs simultaneously | <p>I would like to train multiple models on multiple GPUs at the simultaneously from within a jupyter notebook. I am working on a node with 4GPUs. I would like to assign one GPU to one model and train 4 different models at the same time. Right now, I select a GPU for one notebook by (e.g.):</p>
<pre><code>import os
os... | <p>If you want to train models on different cloud GPUs (e.g. GPU instances from AWS), try this library:</p>
<pre><code>!pip install aibro==0.0.45 --extra-index-url https://test.pypi.org/simple
from aibro.train import fit
machine_id = 'g4dn.4xlarge' #instance name on AWS
job_id, trained_model, history = fit(
model=... | python|tensorflow|keras|jupyter-notebook | 0 |
366,313 | 50,671,270 | How to use airflow for orchestrating simple pandas etl python scripts? | <p>I love the idea of airflow but I'm stuck in the basics. Since yesterday I have airflow running on a vm ubuntu-postgres solution. I can see the dashboard and the example data :)) What I want now is to migrate an example script which I use to process raw to prepared data. </p>
<p>Imagine u have a folder of csv files.... | <p>I'd use the <code>PythonOperator</code>, put the whole code into a Python function, create one Airflow task and that's it. </p>
<p>It would also be possible to put the loading of the csv files in a function and the database writing as well, if it is neccessary to split those steps. All this would be put in one sing... | python|pandas|etl|airflow|airflow-scheduler | 5 |
366,314 | 51,106,441 | Is there a better method than mapping str to float then mapping to int? | <p>I need to merge two data frames. In df_A the key is an int. In df_B the key is a string ending in .0 e.g. '10003.0'.</p>
<p>I would like to convert the string in df_B to an int for merging. Is there a better way than mapping twice as seen below?</p>
<pre><code>df_B['key'].map(float).map(int)
</code></pre>
<p>The ... | <p>You can using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a></p>
<pre><code>pd.to_numeric(df_B['key'],downcast='integer')
</code></pre> | python|pandas | 5 |
366,315 | 50,692,765 | which version of yolo should i choose for my laptop? | <p>So I have a laptop that has <strong>GTX1050ti</strong> and the cpu is <strong>i7 7700hq</strong> and I'm very curious about which version should I choose so it can fit the performance of my laptop and also can <strong>YOLO</strong> predict image or just real-time detection? </p> | <p>The performance of various yolo models on <code>Pascal Tital X</code> is given on the <a href="https://pjreddie.com/darknet/yolo/" rel="nofollow noreferrer">darknet website</a>.</p>
<p><a href="https://i.stack.imgur.com/GbUN7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GbUN7.png" alt="enter i... | tensorflow|yolo|darknet | 0 |
366,316 | 50,890,859 | Pandas resampling from months to weeks | <p>I am attempting to downsample monthly data to weekly data and have a time series dataframe of months that looks like this:</p>
<pre><code> qty
PERIOD_NAME
2017-09-01 49842.0
2017-10-01 27275.0
2017-11-01 29159.0
2017-12-01 51344.0
2018-01-01 19103.0
2018-02-01 23570.0
2018-03-01 45139.0
2018-04-... | <p>You need adjust your output a little bit by using <code>cumsum</code> with <code>groupby</code></p>
<pre><code>s=df.resample('W').mean()
s.groupby(s.qty.notnull().cumsum()).qty.transform(lambda x : x.sum()/len(x))
Out[166]:
PERIOD_NAME
2017-09-03 12460.50
2017-09-10 12460.50
2017-09-17 12460.50
2017-09-24... | python|pandas | 3 |
366,317 | 50,672,356 | matplotlib: customised x-axis ticks for cdf of datetime values | <p>I have a cdf of datetime list. After running the following code, where <code>objDate</code> is a list of datetime values (format: %Y-%m-%d), I get the cdf with ticks on x axis showing every second year in the range of values. How can I get customized labels for ticks along x-axis by specifying: <br><br>
1. the range... | <p>As for the second question, you may use <code>matplotlib.dates</code> locators and formatters. Those work fine in the case of a <code>hist</code>.</p>
<pre><code>import matplotlib.pyplot as plt
plt.rcParams['axes.axisbelow'] = True
import matplotlib.dates as dates
import numpy as np; np.random.seed(42)
import panda... | python|pandas|matplotlib|cdf | 2 |
366,318 | 50,922,868 | PAI tutorial example failed to run. With '[ExitCode]: 177' | <p>I was following the PAI job <a href="https://github.com/Microsoft/pai/blob/master/job-tutorial/README.md" rel="nofollow noreferrer">tutorial</a>.</p>
<p>Here's my job's config:</p>
<pre><code>{
"jobName": "yuan_tensorflow-distributed-jobguid",
"image": "docker.io/openpai/pai.run.tensorflow",
"dataDir": "hdfs... | <p>Normally you need look into the logs of all workers especially the first exited container to see what happens there because any container exited will cause Launcher to stop the job earlier, thus you could see the "EXIT signal received in yarn container" message in application diagnostic content.</p> | tensorflow|openpai | 0 |
366,319 | 51,081,166 | Using TensorFlow to predict a number using three or more input numbers | <p>I'm very new to using TensorFlow in Python, and need to solve a problem which seems fairly straightforward, but I can't find anything helpful online to even point me in the right direction.</p>
<p>Essentially, I have a dataset containing sets of four integer variables - let's call them a, b, c and x. I'd like to be... | <p>This is a <a href="https://en.wikipedia.org/wiki/Regression_analysis" rel="nofollow noreferrer"><strong>regression</strong></a> problem (i.e. predicting a continuous value), not a categorisation problem (labelling from a set of discrete values).</p>
<p>The tensorflow docs have a number of <a href="https://www.tensor... | python|tensorflow | 4 |
366,320 | 51,108,063 | Proper way to extend Python class | <p>I'm looking to extend a Panda's DataFrame, creating an object where all of the original DataFrame attributes/methods are in tact, while making a few new attributes/methods available. I also need the ability to convert (or copy) objects that are already DataFrames to my new class. What I have seems to work, but I fee... | <p>If you just want to add methods to a <code>DataFrame</code> just monkey patch before you run anything else as below.</p>
<pre><code>>>> import pandas
>>> def foo(self, x):
... return x
... ... | python|pandas|class|inheritance | 1 |
366,321 | 50,678,117 | Create df from list (fill up to nth number value into one columns then continue..) in pandas | <p>Would like to create the the df from a list that first 5 value should be in column a, then the next 5 value in another column etc, anyone have any idea? Below is the code. Thank you.</p>
<pre><code>print (test_1)
['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', 1279', '1228', '1299', '1162', '1285', '10... | <p>You can use <code>reshape(5,-1).T</code> where <code>-1</code> represent the new axis:</p>
<pre><code>df = pd.DataFrame(np.array(li).reshape(5,-1).T, columns = list("abcde"))
</code></pre>
<p>Do not use <code>list</code> as variable name. </p> | python|pandas | 2 |
366,322 | 51,076,980 | Optimizing iteration over pandas dataframe | <p>I was creating a dictionary (named data) using two columns of Data Frame (named sales_product ) using 'Sales Ord Id'(column name) as key and then inserting matching 'Prod ID'(column name)
to matching key list in dictionary.
But this program is taking nearly 6 hours to execute, so can anyone suggest any way make this... | <p>You should try to use pandas <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby</a>. It groups a dataframe's data by a column values and lets you work with these groups. It should work faster. </p>
<pre><code>import pandas as pd
sales_pr... | python|python-3.x|pandas|dataframe | 0 |
366,323 | 50,882,133 | Can you train the Tensorflow Object Detection API to detect parts of an object? | <p>I have set up the Tensorflow Object Detection API and I want to start training my own models. I have my training images ready and I am ready to start creating label XML's.</p>
<p>I want to train the model to recognise lots of different parts of a bicycle. So wheels, wheel axles, seat, handlebars, individual pedals,... | <p>You can achieve this. Your problem statement is like any object detection model which is capable of detecting individual objects like the COCO model which can detect up to 90 objects like cat, dog, car, bicycle etc., Although in your case these are parts of the of same bigger object(bicycle), its possible using same... | tensorflow|machine-learning|object-detection|object-detection-api | 0 |
366,324 | 51,059,863 | Why pcov in optimize.curve_fit is a two by two matrix and which value corresponds to intercept | <p>I'm trying to understand perr in the following code which is a matrix with dimensions(2,2).I was expecting it as a matrix with dimensions(1,2). Can you please explain which value correspond to slope and which value correspond to intercept. Documentation says that diagonals are the variance in the parameters(slope,in... | <p>Parameters are represented in the result in the same order that the optimized function takes them. Since line is defined as <code>line(x, m, b)</code>, <code>popt</code> contains the estimates in the order <code>[m, p]</code>.</p>
<p>The <code>pcov</code> (or <code>perr</code> in the example) that <code>curve_fit</... | python|numpy|scipy | 2 |
366,325 | 50,725,848 | Display printed output while code is still running in C++ QT | <p>I wrote a C++ tensorflow code which is working just as expected (using Cmake & make). But when executing the same code on QT Creator (using qmake), the code is not printing the output while it's still running. So we see no output till the execution is completed. Once its done executing, it then prints all the ou... | <p><code>std::cout</code> is buffered. Use <code>std::flush</code> to flush it or use <code>std::cerr</code> (which is unbuffered).</p> | c++|qt|tensorflow | 1 |
366,326 | 50,788,148 | Create empy pandas DataFrame with DateTimeIndex for random time delta values | <p>Im trying to create an empty <code>DataFrame</code> for which I will then constantly be appending rows to using the time stamp when the data arrives as index.</p>
<p>This is to code I have so far:</p>
<pre><code>import pandas as pd
import datetime
df = pd.DataFrame(columns=['a','b'],index=pd.DatetimeIndex(freq='s'... | <p>Set up empty with <code>pd.to_datetime</code></p>
<pre><code>df = pd.DataFrame(columns=['a','b'], index=pd.to_datetime([]))
</code></pre>
<p>Then do this</p>
<pre><code>df.loc[pd.Timestamp('now')] = pd.Series([1, 2], ['a', 'b'])
df
a b
2018-06-10 20:52:52.025426 1 2
</code></pre> | python|pandas|dataframe | 12 |
366,327 | 50,911,268 | Comparing the rows of a column in python | <p>I have the below data frame </p>
<hr>
<pre><code>df=
city code qty year
hyd 1 10 2016
hyd 2 12 2016
pune 2 15 2016
pune 4 25 2016
hyd 1 10 2017
hyd 3 12 2017
pune 1 15 2017
pune 2 25 2017
... | <pre><code># Get a list of all year, this way we know how many columns to make and which columns to mark as N
all_years = df.year.unique()
def my_func(x):
# Function to create new year_... rows
# Get the city and code names
city, code = x.name
# This function will return a pandas.DataFrame
out = ... | python-3.x|pandas | 1 |
366,328 | 50,960,830 | Cannot load torchvision despite it being installed | <p>I have installed pytorch and torchvision using:</p>
<pre><code>conda install pytorch-cpu -c pytorch
pip install torchvision
</code></pre>
<p>when I try to run the following in spyder:</p>
<pre><code>import torch
import torchvision
import torchvision.transforms as transforms
</code></pre>
<p>I get:</p>
<pre><cod... | <p>Fixed by running:</p>
<pre><code>conda install pytorch-cpu -c pytorch
pip install torchvision
</code></pre>
<p>Deleting the PIL and pillow folders in site-packages, then running:</p>
<pre><code>pip install pillow
</code></pre> | python|pip|pytorch | 4 |
366,329 | 50,955,427 | How to get rid of nested for loops in Python code? | <p>I have 1 year of satellite measurements of the electrons (the instrument was measuring every 4 seconds). This array is called 'electrons'. I also have the corresponding times in format datetime.datetime (called 'time'). I want to average electrons array to get a mean value for every minute instead of every 4 seconds... | <p>Whenever you have a problem regarding iteration, think of <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow noreferrer"><code>itertools</code></a>.</p>
<pre><code>from itertools import product
dmax=np.array([[31,28,31,30,31,30,31,31,30,31,30,31]]).T
for month in range (1,13):
for day, ho... | python|loops|numpy|for-loop|parallel-processing | 3 |
366,330 | 50,682,896 | Applying function to pandas dataframe | <p>I have a pandas dataframe called 'tourdata' consisting of 676k rows of data. Two of the columns are latitude and longitude.</p>
<p>Using the reverse_geocode package I want to convert these coordinates to a country data.</p>
<p>When I call :</p>
<pre><code>import reverse_geocode as rg
tourdata['Country'] = rg.sea... | <p>The search method expects a list of coordinates. To obtain a single data point you can use "get" method.</p>
<p>Try :</p>
<pre><code>tourdata['country'] = tourdata.apply(lambda x: rg.get((x['latitude'], x['longitude'])), axis=1)
</code></pre>
<p>It works fine for me :</p>
<pre><code>import pandas as pd
tourdata ... | python-3.x|pandas|geocoding | 1 |
366,331 | 20,807,212 | in ggplot for python specify global xlim in facet_wrap | <p>I'm using <a href="https://pypi.python.org/pypi/ggplot" rel="nofollow noreferrer">ggplot for python</a> (still only version 0.4 so that may be the issue).
However I wish to plot create a facet-wrapped histogram, and have each facet share the same xlim. The command I use seems to apply the xlim only to the last of t... | <pre><code>p = ggplot(aes(x="price"), data=diamonds) + geom_histogram()
p + facet_wrap("cut", scales="free_y")
print(p)
</code></pre>
<p>I suspect that setting a different limit than the one which is automatically computed is currently not possible, as the limit is only applied to the last plot (Bug: <a href="https://... | matplotlib|pandas|python-ggplot | 0 |
366,332 | 20,651,045 | selecting columns equal to a field in pandas dataframe | <p>My Pandas DataFrame looks like this:</p>
<pre><code>0 STUN
1 Webex
2 PPP
3 MyVideo
4 Icecast
5 PPSTREAM
6 FTP
7 SPDY
8 Thunder/Webthunder
9 IRC
10 ... | <p>You can use the isin Series method on a column:</p>
<pre><code>df[df[column_name].isin(['HTTP', 'SSH'])]
</code></pre>
<p>An alternative is to check for either being equal (most likely this will be faster):</p>
<pre><code>df[(df[column_name] == 'HTTP') | (df[column_name] == 'SSH'])]
</code></pre> | python|pandas|dataframe | 4 |
366,333 | 20,815,758 | Installing python module bottleneck error | <p>I'm trying to install the bottleneck python module and I'm getting the following error:</p>
<p>$ pip install bottleneck</p>
<pre><code>In file included from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1728:0,
from /usr/lib/python2.7/dist-packages/numpy/core/include/num... | <p>I have two very similar machines, same version of Python, NumPy, Cython, etc, one produces the same error yo mention, the other installs Bottleneck 0.60 fine. </p>
<p>With the problem machine, I was able to install 0.70 without any issues, but I don't know what the problem was with 0.60.</p>
<p>The install process... | python|numpy|cython | 0 |
366,334 | 20,505,312 | Replace column values in pandas multiindexed dataframe | <p>I want to make a conditional replacement based on the first index value in my pandas dataframe. If I have a dataframe such as: </p>
<pre><code>from pandas import *
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = zip(*... | <p>You could use <code>.loc</code>:</p>
<pre><code>>>> data.loc["bar", "c1"]
second
one 0.369406
two 0.691445
Name: c1, dtype: float64
>>> data.loc["bar", "c1"] = -999
>>> data
c1 c2
first second
bar one -999.000000 0.30215... | python-2.7|pandas|multi-index | 3 |
366,335 | 20,614,536 | pandas.DataFrame.describe() vs numpy.percentile() NaN handling | <p>I noticed a difference in how pandas.DataFrame.describe() and numpy.percentile() handle NaN values. e.g.</p>
<pre><code>import numpy as np
import pandas as pd
a = pd.DataFrame(np.random.rand(100000),columns=['A'])
>>> a.describe()
A
count 100000.000000
mean 0.499713
std ... | <p>For your edited use case, I think I'd stay in <code>pandas</code> and use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.quantile.html" rel="nofollow"><code>Series.quantile</code></a> instead of <code>np.percentile</code>:</p>
<pre><code>>>> df = pd.DataFrame(np.random.rand(10... | python-2.7|numpy|pandas|percentile | 4 |
366,336 | 20,414,272 | Generate heatmap image of lines | <p>I have this graph, which contains a lot of lines defined by 2 points. Now I would like to generate a heatmap. The result should be something similar to <a href="http://docs.ggplot2.org/current/geom_raster.html" rel="nofollow noreferrer">http://docs.ggplot2.org/current/geom_raster.html</a>, except the heat of each ce... | <p>This sounds like what you want:</p>
<p><a href="https://stackoverflow.com/questions/99353/how-to-test-if-a-line-segment-intersects-an-axis-aligned-rectange-in-2d">How to test if a line segment intersects an axis-aligned rectange in 2D?</a></p>
<p>In particular the top answer: <a href="https://stackoverflow.com/a/2... | python|numpy|heatmap|scivis | 1 |
366,337 | 33,168,871 | mapping two numpy arrays | <p>I have two numpy arrays A and B.</p>
<pre><code>A = np.array ([[ 1 3] [ 2 3] [ 2 1] ])
B = np.array([(1, 'Alpha'), (2, 'Beta'), (3, 'Gamma')]
</code></pre>
<p>How can I map A with B in order to get something like:</p>
<pre><code>result = np.array ([[ 'Alpha' 'Gamma'] [ 'Beta' 'Gamma'] ['Beta' 'Alpha'] ])... | <p>You can use a dictionary and a list comprehension :</p>
<pre><code>>>> d=dict(B)
>>> np.array([[(d[str(i)]),d[str(j)]] for i,j in A])
array([['Alpha', 'Gamma'],
['Beta', 'Gamma'],
['Beta', 'Alpha']],
dtype='|S5')
</code></pre> | python|numpy | 2 |
366,338 | 33,395,024 | Joining two pandas dataframes | <p>I see this is commonly asked, but I'm struggling with the solution to my specific needs.</p>
<p>Eg,</p>
<pre><code> Frame1
countryName var1 var2 var3 var4
USA ... ... ... ...
UK ... ... ... ...
NZ ... ... ... ...
JAP ... | <p>IIUC then you want to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html#pandas.DataFrame.pivot" rel="nofollow"><code>pivot</code></a> <code>Frame2</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging" rel="nofol... | python|join|pandas | 3 |
366,339 | 33,151,463 | How to bin time in a pandas dataframe | <p>I am trying to analyze average daily fluctuations in a measurement "X" over several weeks using pandas dataframes, however timestamps/datetimes etc. are proving particularly hellish to deal with. Having spent a good few hours trying to work this out my code is getting messier and messier and I don't think ... | <ul>
<li>The correct way to bin a <code>pandas.DataFrame</code> is to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="noreferrer"><code>pandas.cut</code></a></li>
<li>Verify the date column is in a <code>datetime</code> format with <a href="https://pandas.pydata.org/pandas-... | python|pandas|datetime|pandas-groupby | 13 |
366,340 | 33,272,411 | Is there an online source of complete documentation on Pandas objects/classes (besides reading its code)? | <p>Today, I was looking for a long time on the page <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html</a> , trying to find something very simple: an attribute or method that would retrieve the ... | <p>Read <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="nofollow"><em>10 minutes to pandas</em></a>. The <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html#viewing-data" rel="nofollow">third section</a> makes use of the .index attribute.</p>
<p>See also the <a href="http://pandas.pyd... | pandas | 1 |
366,341 | 33,435,953 | Is it possible to append to an xarray.Dataset? | <p>I've been using the <code>.append()</code> method to concatenate two tables (with the same fields) in pandas. Unfortunately this method does not exist in <code>xarray</code>, is there another way to do it?</p> | <p>Xarray doesn't have an append method because its data structures are built on top of NumPy's non-resizable arrays, so we cannot append new elements without copying the entire array. Hence, we don't implement an <code>append</code> method. Instead, you should use <a href="http://xarray.pydata.org/en/stable/generated/... | python|numpy|pandas|python-xarray | 32 |
366,342 | 33,173,429 | Changing point color on matplolib and basemap not working | <p>I am having some issue with getting my data onto a map with Basemap and having those points change in color. I have read many different things online about how to do this, but I still get a map with no points. Here is my code:</p>
<pre><code>import pandas as pd
import numpy as np
import pickle
from IPython.displa... | <p>Problem solved! </p>
<p>It turns out that this is described in <a href="https://stackoverflow.com/questions/28107404/map-scatter-on-basemap-not-displaying-markers">`map.scatter` on basemap not displaying markers</a> (although I was not searching for the right terms when I googled in here). Here is the change that... | python|pandas|matplotlib|matplotlib-basemap | 0 |
366,343 | 33,261,397 | pandas: calculate time difference between df columns | <p>I have two df columns with string values:</p>
<pre><code>df['starttime'] df['endtime']
0 2015-10-06 18:35:33 0 2015-10-06 18:35:58
1 2015-10-08 17:51:21.999000 1 2015-10-08 17:52:10
2 2015-10-08 20:51:55.999000 2 ... | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">Convert the date <em>strings</em> to <code>pandas.Timestamps</code></a>:</p>
<pre><code>df['starttime'] = pd.to_datetime(df['starttime'])
df['endtime'] = pd.to_datetime(df['endtime'])
</code></pre>
<p>Then take t... | pandas|dataframe|difference|timedelta | 3 |
366,344 | 33,205,260 | How to detect a laser line in an image using Python | <p>What's the quickest most reliable method of detecting a roughly horizontal red laser line in an image using Python? I'm working on a small project related to 3d laser scanning, and I need to be able to detect the laser in an image in order to calculate distance from its distortion.</p>
<p>To start, I have two image... | <p>First enter the color that is the laser and leaves only the red color (in this case). Then apply the same effects and check the result.</p>
<p>In this case, you will have a much less polluted result.
<a href="http://i.stack.imgur.com/ZCVCS.png" rel="nofollow">Result</a></p>
<p>A problem is encountered in analyzing... | python|image|numpy|image-processing | 2 |
366,345 | 33,504,424 | Pandas DataFrame from Dictionary with Lists | <p>I have an API that returns a single row of data as a Python dictionary. Most of the keys have a single value, but some of the keys have values that are lists (or even lists-of-lists or lists-of-dictionaries).</p>
<p>When I throw the dictionary into pd.DataFrame to try to convert it to a pandas DataFrame, it throws a... | <p>This works if you pass a list (of rows):</p>
<pre><code>In [11]: pd.DataFrame(data)
Out[11]:
DC? building occupants
0 True White House Barack
1 True White House Michelle
2 True White House Sasha
3 True White House Malia
In [12]: pd.DataFrame([data])
Out[12]:
DC? building ... | python|pandas | 31 |
366,346 | 33,200,025 | Can't import cv2; "DLL load failed" | <p>I really didn't want to start my own question with this because it seems to be a common error here. However, having wasted hours on this now and having followed every thread I could find, none of the given answers have sorted this for me.</p>
<p>So my only option is to provide all the information I can about my set... | <p>In my situation, when using Pycharm to import cv2, it returned <strong><em>ImportError: DLL not found</em></strong>. However, using python intepreter to import I got <strong>*ImportError: ... not a win32 DLL ... *</strong> instead. So, in this situation, I had to download Visual C++ 2015 redistribution package and p... | python|windows|opencv|numpy|windows-10 | 10 |
366,347 | 33,336,176 | Crashing RAM using memmap in Oja rule | <p>I am using oja's rule on dataset of size 400x156300. It seems to crash my RAM. I am not sure what is causing this. Please help.
I have 12 GB of RAM.
Tried using memmap but still crashing!!</p>
<pre><code>#convert memmap and reduce precision
[num_sample,num_feat]=train_data.shape
filename = path.join(mkdtemp(), 'tra... | <p>This issues was related to the inefficient memory usage for the Oja algorithm. It was fixed in the NeuPy version 0.1.4. Closed ticket you can find here: <a href="https://github.com/itdxer/neupy/issues/27" rel="nofollow noreferrer">https://github.com/itdxer/neupy/issues/27</a></p> | python|numpy|machine-learning|numpy-memmap|neupy | 0 |
366,348 | 33,442,071 | %run vs. copy/paste discrepancy in function containing global commands in python | <p>Below is an import function for reading in a .csv file into python. I use the global command to create a global variable "data" and read the .csv file into the "data" variable for the user to use. </p>
<p>If I copy/paste the code into my client, it works just fine. However, when I "read" the file containing the cod... | <p><strong>test.csv</strong></p>
<pre><code>Les1,Les2,Les3
2,4,4
3,3,3
1,5,3
2,4,3
</code></pre>
<p>Code</p>
<pre><code>import pandas as pd
def dat():
file = raw_input('Enter your .csv file: ')
global data
try:
data = pd.read_csv(file)
print data
print "\nI've created the follow... | python|csv|pandas | 0 |
366,349 | 9,619,541 | Calculate Hitting Time between 2 nodes using NetworkX | <p>I would like to know if i can use <code>NetworkX</code> to implement hitting time? Basically I want to calculate the hitting time between any 2 nodes in a graph. My graph is unweighted and undirected. If I understand hitting time correctly, it is very similar to the idea of PageRank. </p>
<p>Any idea how can I impl... | <p>You don't need <code>networkX</code> to solve the problem, <code>numpy</code> can do it if you understand the math behind it. A undirected, unweighted graph can always be represented by a [0,1] adjacency matrix. <code>nth</code> powers of this matrix represent the number of steps from <code>(i,j)</code> after <code>... | python|numpy|graph-theory|networkx|pagerank | 15 |
366,350 | 9,022,656 | TypeError: unhashable type: 'numpy.ndarray' | <p>From a text file containing three columns of data I want to be able to just take a <code>slice</code> of data from all three columns where the values in the first column are equal to the values defined in <code>above</code>. I then want to put the slice of data into a new array called <code>slice</code> (I am using ... | <p>Your variable <code>energies</code> probably has the wrong shape:</p>
<pre><code>>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback... | python|numpy | 51 |
366,351 | 9,413,216 | Simple Digit Recognition OCR in OpenCV-Python | <p>I am trying to implement a "Digit Recognition OCR" in OpenCV-Python (cv2). It is just for learning purposes. I would like to learn both KNearest and SVM features in OpenCV. </p>
<p>I have 100 samples (i.e. images) of each digit. I would like to train with them.</p>
<p>There is a sample <code>letter_recog.py</code>... | <p>Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).</p>
<p><strong>1)</strong> My first question was ab... | python|opencv|numpy|computer-vision|ocr | 591 |
366,352 | 9,214,971 | cmap.set_bad() not showing any effect with pcolor() | <p>I'm trying to use pcolor on a masked array. I would like masked elements
to show up in a special color. I have written some code, but it does not
seem to work:</p>
<pre><code>import matplotlib as mpl
import matplotlib.pyplot as plt
from numpy import linspace
from numpy.random import randn
from numpy.ma import mask... | <p>The docs for <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.pcolormesh" rel="noreferrer">pcolormesh</a> say:</p>
<blockquote>
<p>Masked array support is
implemented via cmap and norm; <strong>in contrast</strong>, pcolor() simply does not
draw quadrilaterals with masked color... | python|numpy|matplotlib | 10 |
366,353 | 6,040,160 | Anyone have experience using the Nessi Python Network Simulator? | <p>I am working on creating a simulation for the selective-reject ARQ protocol for my networking class. I found a great network simulator, written in python called Nessi:
<a href="http://jer.iict.ch/logiciels" rel="nofollow">http://jer.iict.ch/logiciels</a></p>
<p>The one problem is that it seems Nessi relies on an ol... | <p>It is possible to run it in Snow Leopard.</p>
<p>Use a package management system like fink to install the dependencies required for this package, I think most of the dependencies can be installed using fink like(psyco, numpy, matplotlib,wxpython), you have to experiment with newer version of python to see how it go... | python|numpy | 0 |
366,354 | 5,742,241 | How to plot a set of points in python? | <p>I have a set of points created through a python program which belongs to different clusters. I would like to plot it on a graph so that points in different clusters should be plotted with different colours.</p>
<p>UPDATE</p>
<p>In my case I have a univariate data ( marks of a test). Looking for a way to plot it. <... | <p>you can use <a href="http://matplotlib.sourceforge.net/" rel="noreferrer">matplotlib</a>. I'm not sure to understand exactly your need, but it could be something like this :</p>
<pre><code>from pylab import *
for (x, y) in clusters:
plot(x, y, '+')
show() # or savefig(<filename>)
</code></pre> | python|numpy|scipy | 8 |
366,355 | 66,357,334 | python pandas - Check if partial string in column exists in other column | <p>Take a sample dataset:</p>
<p><code>df = pd.DataFrame([['Mexico', 'Chile'], ['Nicaragua', 'Nica'], ['Colombia', 'Mex']], columns = ["col1", "col2"]) </code></p>
<p>The dataframe looks like this:</p>
<p>I have two columns. I want to check to see if the values in column two exist in column one. Thi... | <p>This looks like an expensive operation. You can try:</p>
<pre><code>df['col2'].apply(lambda x: 'Yes' if df['col1'].str.contains(x).any() else 'No')
</code></pre>
<p>Output:</p>
<pre><code>0 No
1 Yes
2 Yes
Name: col2, dtype: object
</code></pre> | python|pandas|dataframe | 2 |
366,356 | 66,746,326 | setting the first element value with iloc | <pre><code>import pandas as pd
import numpy as np
df=pd.DataFrame({"item":['a','a','a','b'],"item1":['b','d',np.nan,'c']})
</code></pre>
<p>The content of df</p>
<pre><code> item item1
0 a b
1 a d
2 a NaN
3 b c
</code></pre>
<p>I want to change the second element value of ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_loc.html" rel="nofollow noreferrer"><code>Index.get_loc</code></a> for position of column <code>item</code>, so possible set value in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" ... | pandas | 0 |
366,357 | 66,543,973 | Validation check Excluding VAT, VAT and Total giving error | <p>I have the following df:</p>
<pre><code>ExclBTW BTW Totaal
NaN NaN 750.0
</code></pre>
<p>I'm trying to do some validation checks on the ExcludingBTW (=VAT), VAT and Total.
The following code is used:</p>
<pre><code>#validation check
df1.loc[:, ['ExclBTW', 'BTW','Totaal']] = df[['ExclBTW', 'BTW','Totaal... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> per all columns and then <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p>
<pre><c... | python|pandas|dataframe | 1 |
366,358 | 66,654,424 | Imputing values into a dataframe based on another dataframe and a condition | <p>Suppose I have the following dataframes:</p>
<pre><code>df1 = pd.DataFrame({'col1':['a','b','c','d'],'col2':[1,2,3,4]})
df2 = pd.DataFrame({'col3':['a','x','a','c','b']})
</code></pre>
<p>I wonder how can I look up on <code>df1</code> and make a new column on <code>df2</code> and replace values from <code>col2</code... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a>:</p>
<pre><c... | python|pandas | 2 |
366,359 | 66,538,393 | Issue with removing duplicates in pandas dataframe | <p>Edit: This has been solved thanks to fsl, duplicated where removed and the issue was the index that needed to be reseted.</p>
<p>I have this dataframe:</p>
<pre><code> Ubicacion lat lon
0 a 19.28034 -99.17121
1 b 19.28333 -99.17535
2 c 19.28028 -99.16887
3 a 19.28034 ... | <p>IIUC, go with <code>reset_index</code> or simply pass <code>ignore_index=True</code>:</p>
<pre><code>df = df.drop_duplicates(keep='first').reset_index(drop=True)
# or
df = df.drop_duplicates(keep='first', ignore_index=True)
</code></pre>
<p>Output:</p>
<pre><code> Ubicacion lat lon
0 a 19.28... | python|pandas|dataframe | 1 |
366,360 | 66,418,472 | Pandas Grouper - Specify End Date Which Has No Data | <p>I have a dataframe of daily values like this:</p>
<pre><code> orderdate id total noitems dt
4241 2021-02-21 15:21:11.905304 30266 19.95 1 2021-02-21 15:21:11.905304
4244 2021-02-22 03:17:17.666482 30269 34.91 2 2021-02-22 03:17:17.666482
4246 2021-02-22 22:48:06... | <p>If datetimes are consecutive you can add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> by minimal and custom maximal by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range... | python|pandas | 1 |
366,361 | 66,482,235 | Python Pandas Memory Loss | <p>I have got some python/pandas memory-loss-issue when reading pickle files (in a loop) or parquet files.
I tried to analyse by using the memory profiler. Results are the following:</p>
<pre><code>Filename: /home/ubuntu/work/a4lbs/src/analyze/load.py
Line # Mem usage Increment Occurences Line Contents
======... | <p>Pandas' <code>memory_usage()</code> function is not a reliable measure of memory usage. At a minimum you want <code>deep=True</code> argument to it, but even then it might not track all memory.</p>
<p>As an alternative to <code>memory_profiler</code>, you might try <a href="https://pythonspeed.com/fil" rel="nofollow... | python|pandas|jupyter-notebook | 1 |
366,362 | 66,514,737 | Python - Group by dates | <p>looking to speed up this task .... it works, just slowly.</p>
<pre><code> #split csv file into two groups.
for index, row in tqdm(df.iterrows(), total=df.shape[0]):
date_time_obj = datetime.datetime.strptime(row["date"], '%Y-%m-%d')
if date_time_obj <= datetime.datetime.strptime(&quo... | <p>To speed it up you can do it in a vectorized form (without <code>iterrows</code>):</p>
<pre><code>df = pd.DataFrame({'date': pd.date_range('2020-03-08', '2020-03-14')})
df['group'] = pd.to_datetime(df['date']) <= pd.to_datetime('2020-03-11')
df['month'] = df['date'].dt.month
df
</code></pre>
<p>Output:</p>
<pre>... | python|pandas|csv|date|time | 0 |
366,363 | 66,370,453 | Getting count of unique values in pandas Dataframe when there is a list object in a column | <p>So basically I am trying to analyse instagram accounts. I have scraped intagram using selenium and created a datafram which includes links to the post, number of likes and hashtags used. So in the data frame i have included list object in a cloumn and i awant to find the count of unique hashtags used in total.<br />... | <p>Here is one way using <code>Counter</code>:</p>
<pre><code>from collections import Counter
arr = df['hashtags'].apply(pd.Series).values.ravel() # Consolidate all hashtags
count_dict = Counter(arr)
</code></pre> | python|pandas|dataframe|instagram|data-analysis | 2 |
366,364 | 66,750,007 | Comparing two columns to get value for third column | <p>I have problem comparing two columns from two different excels to fill in values to another column in the first excel.</p>
<p>I have two excel files:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>con_job</th>
<th>idContractor</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>... | <p>I would use the Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">merge</a> function to do this. Here is how:</p>
<pre><code>df1.merge(df2, how='left', left_on='con_job', right_on='job')
</code></pre> | python-3.x|pandas | 2 |
366,365 | 66,692,148 | format all columns of a dataframe | <p>Hi i am looking for a solution how to format all columns or a selection by position (column 0 and 1)</p>
<pre><code>import pandas as pd
d = {'value': [20, 10, -5, ],
'min': [0, 10, -10,],
'max': [40, 20, 0]}
df = pd.DataFrame(data=d)
#df = df.astype(float).map("{:,.2f} €".format) # style to €, ... | <p><code>applymap()</code> and <strong>f-string</strong> works</p>
<pre><code>d = {'value': [20, 10, -5, ],
'min': [0, 10, -10,],
'max': [40, 20, 0]}
df = pd.DataFrame(data=d)
df.applymap(lambda x: f"{x:,.2f} €")
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th ... | python|pandas | 3 |
366,366 | 66,747,965 | Looping through a list of dataframes to create different plots | <p>I have a list of dataframes:</p>
<pre><code>list=[mean_ave,rmse_ave,bias_ave,
std_ave,std_diff_ave,trend_ave,trend_diff_ave,
corr_mean,ano_rmsd]
</code></pre>
<p>For each of those dataframes I would like to produce a heatmap as shown in the example below.</p>
<pre><code>f, ax = plt.su... | <p>One remark, first: <code>list</code> is not the best choice of name, use df_list or dfs, for instance (or any other name less ambiguous).</p>
<p>You could try this:</p>
<pre><code>f, axs = plt.subplots(len(df_list), 1, figsize=(8, 12))
for i, df in enumerate(list_df):
sns.heatmap(
df,
cmap='RdBu',
a... | pandas|for-loop|plot | 0 |
366,367 | 66,381,173 | Python - Concatenate multiple columns based on the value of each column | <p>Need to create a new column that concatenate multiple columns based on the value of each column. For example, input:</p>
<pre><code>s1 s2 s3
1 0 0
1 1 0
0 1 2
</code></pre>
<p>Output:</p>
<pre><code>s1 s2 s3 col
1 0 0 s1
1 1 0 s1, s2
0 1 2 s2, s3
</code></pre>
<p>Basically I need t... | <p>Create mask for compare values greater like <code>0</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.gt.html" rel="nofollow noreferrer"><code>DataFrame.gt</code></a> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dot.html"... | python|pandas | 5 |
366,368 | 66,551,819 | how to use more three channels input in train_datagen | <p>I am trying to apply Keras for images with more than three spectral channels. I noticed that <code>train_datagen</code> handles images with three channels based on color_mode='rgb'. Is there any way to increase the number input channels or are there any alternative methods?</p>
<pre><code>img_train_generator = train... | <p>You can have 1, 3 or 4 channels. See the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator#flow_from_directory" rel="nofollow noreferrer">docs</a>.</p>
<blockquote>
<p><strong>color_mode</strong> One of "grayscale", "rgb", "rgba". Defaul... | python|tensorflow|keras | 1 |
366,369 | 66,652,047 | table extraction: adding column with file name and path of origin file to df | <p>i need to extract the same table out of multiple docx report documents.
In the list <code>'targets_in_dir'</code> I have stored all the file names with paths in the format</p>
<pre><code>'C:\directory\subdirectory\filename1.docx'
</code></pre>
<p>The code below perfectly grabs the table out of the document and corre... | <p>Meanwhile I found a solution myself with the following line of code. i just add <code>str</code></p>
<pre><code>df['report'] = str(targets_in_dir[1])
</code></pre> | python|pandas|docx | 0 |
366,370 | 66,494,976 | How to use list comprehension for nested for loops in PySpark | <p>I intend to use difflib.SequenceMatcher() on the below PySpark data frames.</p>
<pre><code>tech.show()
+-----------------------------+----------------------+
| concat_tech |Vendor_product |
+-----------------------------+----------------------+
|AWS Cloud Administration |AWS Cloud Map ... | <p>You are trying to compare each element from dataframe <code>tech</code> with each element from dataframe <code>techno</code>. The result of such an operation is a <a href="https://spark.apache.org/docs/3.0.1/api/python/pyspark.sql.html#pyspark.sql.DataFrame.crossJoin" rel="nofollow noreferrer">crossJoin</a>. Unless ... | python-3.x|pandas|for-loop|pyspark|list-comprehension | 1 |
366,371 | 66,592,506 | How to suppress all autograph warnings from Tensorflow? | <p>I'm getting a warning which I cannot find a solution to.
Apparently this:</p>
<pre class="lang-py prettyprint-override"><code>import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # or any {'0', '1', '2'}
import tensorflow as tf
os.environ['AUTOGRAPH_VERBOSITY'] = '1'
</code></pre>
<p>is not enough to stop this annoyi... | <p>Try this:</p>
<pre><code>tf.autograph.set_verbosity(0)
</code></pre>
<p>If that doesn't work, perhaps the <code>logging</code> module could be of help here:</p>
<pre><code>import logging
logging.getLogger("tensorflow").setLevel(logging.ERROR)
</code></pre> | python|python-3.x|tensorflow|keras | 9 |
366,372 | 66,533,510 | Numpy producing different random numbers despite seed | <p>I had a problem with NumPy producing different random numbers despite seeding.</p>
<p>code:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import random
random.seed(1234)
vec = np.random.normal(0, 1, size=6)
print(vec)
</code></pre>
<p>As I had set the seed, I expected <code>vec</code> to ... | <p>My mistake was the following:<br />
I set the seed of <code>random</code>, not of <code>np.random</code>!</p>
<p>When setting the seed of the NumPy random number generator, everything works as expected:</p>
<pre><code>import numpy as np
np.random.seed(1234)
vec = np.random.normal(0, 1, size=6)
</code></pre>
<p><co... | python|numpy | 2 |
366,373 | 66,736,103 | Issue retrieving ValueError: `decode_predictions` expects a batch of predictions | <p>I have the following code took it from Github to run a pre-trained model mobilenet_v2 <a href="https://github.com/vvigilante/mobilenet_v2_keras/blob/master/mobilenet_v2_keras.py" rel="nofollow noreferrer">https://github.com/vvigilante/mobilenet_v2_keras/blob/master/mobilenet_v2_keras.py</a>
and trying to run it, how... | <p>This function is meant to transform a vector of 1,000 probabilities into a category of the ImageNet dataset, which has 1,000 categories. Your final layer has 100 categories, so the function is confused. You could do this:</p>
<pre><code>model=MobileNetv2((224, 224, 3), 1000)
</code></pre>
<p>If it makes sense accord... | python|tensorflow|machine-learning|keras|pre-trained-model | 1 |
366,374 | 66,752,635 | How to expand a range of values stored in two cells (start and end in two colums) to rows (longer version) in Python Pandas | <p>Please help or suggest, I would like to automate this process in Pandas or any other module in Python such that I can do further processing. I already have a VBA script but it takes forever in Excel, I hope a python script will be quicker.</p>
<p>The current dataframe looks like this
df_original ={
'TOWN_NAME':['ZAK... | <pre><code>>>> df
a b from to
0 c d 1 5
1 e f 8 12
</code></pre>
<p>You can <code>.reindex()</code> with <code>.repeat()</code> to expand the rows and <code>.groupby().cumcount()</code> to add the <code>exp</code> column.</p>
<pre><code>df = df.reindex(df.index.repeat(df['to'] + 1 - df['fr... | python|pandas|dataframe | 0 |
366,375 | 66,725,601 | Min-max scaling query | <p>Getting error for the below code.</p>
<p>I am trying to perform min-max scaling for only one feature of the dataframe:</p>
<pre><code>from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
train_df['training_credits']= scaler.fit_transform(train_df['training_credits']).reshape(1,-1)
test_df['training... | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>scaler.fit_transform(train_df[['training_credits']].values)
</code></pre>
<p>or</p>
<pre class="lang-py prettyprint-override"><code>scaler.fit_transform(train_df['training_credits'].values.reshape(-1,1))
</code></pre> | python|pandas|scikit-learn | 4 |
366,376 | 66,443,260 | Why are some pandas aggregation functions in quotes and others not? | <p>I have a line of code in a colleague's module which works, but which I do not understand:</p>
<pre class="lang-python prettyprint-override"><code>grouped_frame = frame.groupby(['user_id']).agg({'total': ['first', list]})['total'].reset_index()
</code></pre>
<p>If I replace <code>'first'</code> with <code>first</code... | <p>Please see this <a href="https://stackoverflow.com/questions/60890498/pandas-apply-difference-if-function-name-is-in-quotes-or-not/69725116#69725116">answer</a></p>
<p>in short:<br />
<code>'first'</code> (with quotes) means, <code>agg()</code> will search for a function named <code>first</code> belonging to a <code... | pandas | 1 |
366,377 | 66,536,963 | Dice loss working only when probs are squared at denominator | <p>I'm experiencing an interesting and frustrating issue with the Dice loss used in image segmentation with Unet.</p>
<p>I have to segment images in two classes: background and region of interest. The region of interest is typically 4% of the pixels of the whole image. Images are about 1600x1600 pixels.
I found the Dic... | <p>Milletari et al. already explain this when they propose this in <a href="https://arxiv.org/pdf/1606.04797.pdf" rel="nofollow noreferrer">the paper of V-Net</a>. They suggest that the ROI may only occupy a very small region of the whole scan, which is likely to be biased towards the background. Since you say your ROI... | deep-learning|computer-vision|pytorch|image-segmentation|loss-function | 0 |
366,378 | 66,449,745 | Pandas: how to get index value of non-unique index | <p>I have a data frame with a date time index where index values are non unique (see last two index values).</p>
<p>I would like to get the next valid index value given a time delta of +5 seconds from the first index value. In the case below, the first index value = '2018-12-03 08:00:00.410' and adding 5 seconds to tha... | <pre><code>df.index[df.index.duplicated()].tolist()
</code></pre> | pandas|datetime|indexing|pandas-resample | 0 |
366,379 | 66,646,740 | How do I select a range of two numpy indices? | <p>I have a simple numpy array, and I want to make a separate array that takes every two elements per two indices</p>
<p>For example:</p>
<pre><code>x = np.arange(0,20)
print(x)
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
</code></pre>
<p>My goal is to get an array of</p>
<pre><code>[2 3 6 7 10 11 14... | <p>You can simply do this using the traditional <code>start:stop:step</code> convention without any modulo by reshaping your array, indexing, and then flattening it back. Try this -</p>
<ol>
<li>By reshaping it to (-1,2) you create bi-gram sequence</li>
<li>Then you simply start from 1 and step 2 times</li>
<li>Last yo... | python|arrays|numpy|jupyter|slice | 3 |
366,380 | 66,506,557 | Converting lists in a column into an array | <p>I have a dataframe with 2 columns and would like to convert the entries of one of the columns, called "Features", which are as a list of numbers, into an array-like object. I have tried different numpy function by dealing directly with the column and putting the result of the operation into a new column bu... | <p>This doesn't rely on a loop, but I think it will do what you want.</p>
<p>I took the liberty to create a test dataframe:</p>
<pre><code>d1 = {'id': [1, 2, 3],
'features': [[1, 2, 3], [5, 6, 3,], [9, 2, 9]]}
df1 = pd.DataFrame(data=d1)
</code></pre>
<p>here we convert the features to a numpy array:</p>
<pre><co... | arrays|pandas|list|dataframe|numpy | 0 |
366,381 | 66,383,559 | Compare unordered DataFrame compare value based on comparison and create a new column | <p>I have 2 DataFrames (PreServices, PostServices) each DataFrame contains Windows services and their running status at a given time.</p>
<p>How does Data look like?</p>
<ol>
<li>there is no order of how services names are listed</li>
<li>PostServices may or not have Names that are in PreServices</li>
<li>PostServices ... | <p>The following code snippet will get your desired output:</p>
<pre><code>def create_final_status(row):
if row['Name'] in PostServices['Name'].values:
if row['State'] == PostServices[PostServices['Name'] == row['Name']]['State'].item():
return True
else:
return PostServices[... | python|pandas | 1 |
366,382 | 66,614,252 | Is there a way I can count bounces from a ball in OpenCV? | <p>I made a ball tracking program using this guide: <a href="https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/" rel="nofollow noreferrer">https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/</a></p>
<p>I wanted to ask if there is a way I can tell how many bounces a ball makes in a certa... | <p>I set up a simulation to show what I was talking about in the comments. Basically, every time the camera takes a picture (whatever fps your camera runs at) you can get the ball's position. Using that position you can estimate velocity (change in position divided by time). If there's a sudden change in the direction ... | python|c++|numpy|opencv|computer-vision | 6 |
366,383 | 66,531,061 | is there way to get numbers from list | <p>it is a weird situation.
The table get id contacts.
I am now get ticket trace which contains several ids here and I want to sum their contacts in total.</p>
<p><img src="https://i.stack.imgur.com/6kVxR.png" alt="enter image description here" /></p>
<p>I am trying to make id and contacts into dictionary but I am havi... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a> and then aggregate sum:</p>
<pre><code>df1 = (df.explode('ticket_trace_list')
.groupby('ticket_trace_list', as_index=False)['Contacts'].sum())
</... | python|pandas|dataframe|data-preprocessing | 3 |
366,384 | 66,665,589 | How to vectorize loss for a LSTM doing sequential Language modelling | <p>So I have an assignment involving Language Modelling and I passed all the unit tests but my code is too slow to run. I think it's because of the way I compute my loss. The formula we're given is the following:
<a href="https://i.stack.imgur.com/q80rJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com... | <pre class="lang-py prettyprint-override"><code>B = batch_size
T = sequence_length (padded)
N = vocab_size
if type(mask_b) == torch.bool:
mask = mask.view(-1) # (B, T) -> (B*T,)
else:
mask = mask.bool().view(-1) # (B, T) -> (B*T,)
log_probas = log_probas.view(-1, N) # (B, T, N) -> (B*T, N)
targets = t... | python|numpy|deep-learning|pytorch | 1 |
366,385 | 66,635,552 | keras: Assessing the ROC AUC of multiclass CNN | <p>I am using <code>keras</code> Sequential() API to build my CNN model for a 5-class problem. Since accurary is not a good metric for a multiclass problem, I have to assess other metrics measure to evaluate my model. Currently, I use <code>sklearn</code>'s <code>confusion_matrix</code> and <code>classification_report<... | <p>Another way to plot the ROC curve of the multiclass classifier is shown below. Let's walk with a toy problem, CIFAR10, a multiclass data set, consist of 10 different classes.</p>
<pre><code>import tensorflow as tf
import numpy as np
(x_train, y_train), (_, _) = tf.keras.datasets.cifar10.load_data()
# train set / ... | python|tensorflow|keras|roc|auc | 6 |
366,386 | 66,662,474 | Python3.6 on Cygwin can't install modules | <p>I am trying to run a program on cygwin that uses "import numpy as np" and other modules.
when I try to compile the program on cygwin (using python3.6) I get an error message that the module is not found <a href="https://i.stack.imgur.com/YE5K2.png" rel="nofollow noreferrer">enter image description here</a>... | <p>Numpy is already provided as Cygwin packages, there is no need to install with pip
but you need to install with setup. After that</p>
<pre><code>$ cygcheck -c python36
Cygwin Package Information
Package Version Status
python36 3.6.13-1 OK
$ cygcheck -c python36-numpy
Cygwin Pac... | python|numpy|cygwin|python-module | 1 |
366,387 | 66,635,577 | Choosing bach size and learning rate for large datastet | <p>The dataset has around 2.5 million rows, and I'm using a 80/20 train test split.
I read some answers here and some papers regarding this which suggest batch sizes of 32 or 64. But wouldn't that be extremely small relative to the size of the dataset?
I previously trained with a bath size of10000 and LR of 1e-2 but di... | <p>You did not specify which framework do you use. TensorFlow, for example, has a callback like <a href="https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ReduceLROnPlateau" rel="nofollow noreferrer">ReduceLROnPlateau</a>. It reduces learning rate when the metric has stopped improving. The main parameter is... | machine-learning|neural-network|pytorch|data-science | 0 |
366,388 | 66,625,103 | Python - calculate de total amount or sells each month | <p>I have a dataframe with several OrderId, Date of sale, product taht was sale and so on.
I am currently trying to calculate the month in which were sold less Motorcycles.</p>
<p>This is the code I wrote, trying with group by to calculate the total amount sold en each month:</p>
<pre><code>Motorcycles =sales_data.loc[... | <p>Ignoring warnings, your column <code>ORDERDATE</code> seems to contain an index instead of a date. Type of indexes being: 'Int64Index'</p>
<p>Why? Because it takes the first column, 'ORDERID' instead of <code>ORDERDATE</code>
Precise which column (a.k.a. key) you want to use and you should be good to go.</p>
<pre><c... | python|pandas-groupby|pandas-resample | 0 |
366,389 | 66,458,457 | How to how to read grayscale mask image using numpy? | <p>I was going through someones code on semantic segmentation try to learn some techniques but I could figure out one particular section which I will really need an explanation
Here is the entire function</p>
<pre><code>def DataGen():
img_ = []
mask_ = []
c1 = []
y1 = []
for i in range(len(image_)):... | <p>I have figure it long since so I decided to answer it ... may be it will help a others.</p>
<p>`target[:, :, 1][np.where(mask == 149)] = 1</p>
<p>target[:, :, 0][np.where(mask == 76)] = 1
`</p>
<p>This "np.where(mask == 149)" can simply be remove and replace with any integer value as an index. The author c... | python|image|numpy|semantic-segmentation | 0 |
366,390 | 66,373,862 | Can Pandas output inferred schema for a CSV file? | <p>Is there a method I can use to output the inferred schema on a large CSV using pandas?
In addition, any way to have it tell me with that type if it is nullable/blank based off the CSV?
File is about 500k rows with 250 columns.</p>
<p>With my new job, I'm constantly being handed CSV files with zero format documentati... | <p>Is it necessary to load the whole csv file? At least you could use the read_csv function if you know the separator or doing a cat of the file to know the separator. Then use the .info():</p>
<pre class="lang-py prettyprint-override"><code>df = pd.read_csv(path_to_file,...)
df.info()
</code></pre> | python|pandas|csv|data-science|data-wrangling | 1 |
366,391 | 66,356,579 | Jupyter is not finding the "iris" file | <p>I'm new at programming and I'm trying to import the Iris.csv datafile, so I downloaded it at Kaggle and the inserted this code in Jupyter Notebook:</p>
<pre><code>import pandas as pd
iris = pd.read_csv("../Iris.csv")
</code></pre>
<p>and the following error occurs:</p>
<pre><code>FileNotFoundError: [Errno ... | <p>The best practice for reading a CSV file in python is to add <strong>"r"</strong> before the directory, as mentioned in the example below.</p>
<pre><code>import pandas as pd
iris = pd.read_csv(r"../Iris.csv")
</code></pre>
<p>In Python, backslash is used to signify special characters. r stands fo... | python|python-3.x|pandas|jupyter-notebook|anaconda | 0 |
366,392 | 66,735,198 | Reading a particular column from a csv | <p>I am currently trying to read in a csv file for the purpose of creating a budget from a stament and I want to group similar items eg fuel etc. So id like to get the values from column E (aka column 5). store these values in a list and pair them with cost and then group in to lumps eg fuel. So far for simply trying... | <p>Correct the column name to</p>
<pre><code>temp=pd.read_csv("statement.csv",usecols=['Transaction Description'])
</code></pre>
<p>and try again</p> | python|pandas|dataframe|csv | 0 |
366,393 | 66,405,159 | Python Pandas Working with Timedelta then saving it to csv | <p>I am trying to transition my reports that are currently automated with VBA to python.
But since i work with lots of durations on my exports I have a problem.</p>
<p>If i want to do some measures with this data that is in "%H:%M:%S" format I have to convert it using:</p>
<p><code>df['Duration'] = pd.to_time... | <p>Time Delta is difference between 2 dates/time so that's why it saves data as</p>
<pre><code>0 days 00:09:17.000000000
</code></pre>
<p>If you want to save data as <code>00:09:17.000000000</code> then
After you run</p>
<pre><code>df['Duration'] = pd.to_timedelta(df['Duration'])
</code></pre>
<p>then convert its <cod... | python|pandas|timedelta | 1 |
366,394 | 66,474,313 | Pandas: Cant Insert Pivot Table information into a different Sheet | <p>I have a code where I convert a txt to xlsx, then add a column with formulas and then I want to create a Pivot Table with that information in a different Sheet. The code works without errors but it creates and empty Sheet instead of a Sheet with information.</p>
<p>So the code looks like this:</p>
<pre><code>import ... | <p><code>with</code> automatically closes the file, so there is no need to try to save it manually. It is also not needed to create the second sheet prior to writing it. Removing <code>writer.save()</code> and moving <code>wb.save(path)</code> up will make the code work.</p>
<pre><code>#Writing the formula column
wb = ... | python|excel|pandas|pivot-table|pandas.excelwriter | 0 |
366,395 | 66,601,365 | I add file names into dataframe but it adds only the same name | <p>I have a lot of csv files to open and I need to add an extra column with name of those files. For example I have x.csv, y.csv, z.csv and etc. Inside csv file it looks like below:</p>
<pre><code>X Z
1 3
4 5
4 6
</code></pre>
<p>And it should look like this</p>
<pre><code> X Z name
1 3 x
4 5 x
4 6 ... | <p>Your <code>os.listdir</code> is wrong. <code>os.listdir</code> returns a list of files in the directory. You should be using <code>os.basename</code> or <a href="https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.name" rel="nofollow noreferrer"><code>pathlib.Path.name</code></a></p>
<p>With pathlib:</p>... | python|pandas|csv|for-loop|glob | 2 |
366,396 | 66,352,872 | pandas dataframe with pathlib Path filtering | <p>I am trying to filter a dataframe like the following by its path and the paths items:</p>
<pre class="lang-py prettyprint-override"><code>
from pathlib import Path
import pandas as pd
lst = [('100', Path('/root/sub1/nameA.txt'), 'some_type'),
('101', Path('/root/sub1/nameB.txt'), 'some_type'),
('102',... | <p>On another platform I was pointed to the <strong><a href="https://github.com/drivendataorg/pandas-path" rel="nofollow noreferrer">pandas-path</a></strong> project, which I want to link here as another approach for anybody who might have the same problem, I had. The project provides a <a href="https://pandas.pydata.o... | python|pandas|dataframe|pathlib | 1 |
366,397 | 66,614,938 | Iterating over Dataframe columns to plot Histogram | <pre><code>%matplotlib inline
for column in df.columns:
if df[column].dtype =="int64":
df[column].hist(title=column)
else:
df[column].plot(kind="bar", title=column)
AttributeError: 'Rectangle' object has no property 'title'
</code></pre>
<p>I would like to print Histogram whether the dtype ... | <p>Try to slice your columns at start and you need subplot/subplots to plot multiple graphs</p>
<pre><code>import seaborn as sns
numeric_columns = df.select_dtypes(include=['int64','float64']).columns
n_rows = 2
n_cols= 2
for i, column in enumerate(df.columns,1):
plt.subplot(n_rows,n_cols,i)
if column in nume... | python|pandas|types|data-visualization|histogram | 0 |
366,398 | 66,390,583 | Loop over common files in multiple folders | <p>How could I find files with the same filename in multiple folders, and then perform the same operations?</p>
<pre><code>def findCommonDeep(path1, path2):
return set.intersection(*(set(os.path.relpath(os.path.join(root, file), path) for root, _, files in os.walk(path) for file in files) for path in (path1, path2)... | <p>As you've tagged pandas, let's use <code>pandas</code> and <code>pathlib</code> to return a dictionary of files with similar names:</p>
<pre><code>from pathlib import Path
import pandas as pd
def return_similair_files(start_dir : str) -> dict:
all_files = Path(start_dir).rglob('*.csv')
df = pd.DataFrame... | python|python-3.x|pandas | 1 |
366,399 | 66,369,886 | Python: how can I merge two dataframes on two column keys? | <p>I tried to merge two dataframes on two column keys using merge function but it returns with NaN for some rows. I am not sure what's wrong. Could you please advise what's the issue? Thank you!</p>
<p>df1</p>
<pre><code> VR Ccy_1 Ccy_2 Qualifier Ccy_Gp1 Ccy_Gp2
0 2.864298e+08 BRL KRW BRLKRW... | <p>You may try something like that to remove the whitespaces from the column 'Ccy_Gp1' in df2 before doing the merge :</p>
<pre><code>df2['Ccy_Gp1'] = df2['Ccy_Gp1'].map(lambda x: x.lstrip())
</code></pre> | python|pandas|merge | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.