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
8,500
73,256,301
I keep getting ValueError: invalid literal for int() with base 10: ''
<p>here is the code but every time it creates this error. ValueError: invalid literal for int() with base 10: ''</p> <p>Here is the main code. It's for posting a tweet</p> <pre><code>import tweepy import pandas import time import creds latest_tweeet_id =0 appkey= creds.appkey appSecret = creds.appSecret accessToken = ...
<p>The problem is that the file <code>latest.txt</code> is empty. When python reads the file, it gets the empty string, and when it tries to interpret the empty string as an integer it gives you that error.</p> <blockquote> <p>The latest.txt file has only one digit, 1.</p> </blockquote> <p>The error message specificall...
python|pandas|tweepy
2
8,501
73,396,823
How can I extract rows in Dataframe with function?
<p>My dataframe includes list, like this.</p> <pre><code> a b 1 frog [1, 2, 3] 2 dog [4, 5] 3 melon [6, 7, 1] </code></pre> <p>I want to extract rows which b contains specific numbers, so I made this function.</p> <pre><code>def a(_list, _tag): if _tag in _list: return True ...
<p>Here's a way to do what your question asks:</p> <pre class="lang-py prettyprint-override"><code>target = 1 df2 = df.explode('b').b == target df['found'] = df2.groupby(df2.index).sum() &gt; 0 print(df) </code></pre> <p>Output:</p> <pre><code> a b found 0 frog [1, 2, 3] True 1 dog [4, 5] F...
python|pandas|dataframe
0
8,502
35,295,741
Python Pandas. Creating DataFrame with Series does not preserve dtype
<p>I have a use-case which I thought would be quite common, and so I thought this question of mine should be easy to answer for myself, but I couldn't find the answer anywhere. Consider the following.</p> <pre><code>df = pandas.DataFrame({"id": numpy.random.choice(range(100), 5, replace=False), ...
<p><em>Columns</em> of a DataFrame always have a single dtype. (This is because, under the hood, Pandas stores <em>columns</em> of data which have the same dtype in blocks.)</p> <p>When <code>pd.DataFrame</code> is passed a list of Series, it unpacks each Series into a separate row. Since the Series have different d...
python|pandas
4
8,503
35,176,293
How to sum the information at two consecutive positions in a dataframe
<p>I have a pandas dataframe with position,k, y. For example</p> <pre><code>pos k y 123 0.7 0.5 124 0.4 0.1 125 0.3 0.2 126 0.4 0.1 128 0.3 0.6 130 0.4 0.9 131 0.3 0.2 </code></pre> <p>i would like to sum the information at k and y like</p> <pre><code>123 1.1 0.6 125 0.7 0.3 128 0.3 0.6 130 0.7 1.1 </code></pre> <p...
<p>Maybe this is faster than a loop, but it won't sum positions 123 and 124 and then 130 and 131 as I think you expect, because it sums odd positions with its consecutive like 129 and 130, 131 and 132... </p> <pre><code>df = df.set_index('pos') df_odd = df.loc[df.index.values % 2 == 1] df_even = df.loc[df.index.values...
python|pandas
1
8,504
60,290,110
Pandas: Create a table with a “dummy variable” of another table
<p>Let's say I have this dataframes</p> <p>DataFrame A (Products)</p> <pre><code>Cod | Product | Cost | Date ------------------------------- 18 | Product01 | 3.4 | 21/04 22 | Product02 | 7.2 | 12/08 33 | Product03 | 8.4 | 17/01 55 | Product04 | 0.6 | 13/07 67 | Product05 | 1.1 | 09/09 </code></pre> <p>D...
<p>You need to combine the dummies from <code>Products</code> with the dummies from <code>Operations</code>. Start by defining the output columns by using a prefix:</p> <pre class="lang-py prettyprint-override"><code>columns = ['id', 'codoper'] + [f"Product_{cod}" for cod in A['Cod'].unique()] + ['valor'] </code></pre...
python|pandas|dataframe
2
8,505
60,174,899
Creating HDF5 compound attributes using h5py
<p>I'm trying to create some simple HDF5 datasets that contain attributes with a compound datatype using h5py. The goal is an attribute that has two integers. Here are two example of attributes I'd like to create.</p> <p><a href="https://i.stack.imgur.com/EKVNq.png" rel="nofollow noreferrer"><img src="https://i.stac...
<p>To make an array with <code>dt_type</code>, you have to properly nest lists and tuples:</p> <pre><code>In [162]: arr = np.array([(['23','3'],)], dt_type) In [163]: arr Out[163]: array([([23...
python|numpy|hdf5|h5py
2
8,506
65,082,248
('Trying to update a Tensor ', <tf.Tensor: shape=(), dtype=float32, numpy=3.0>)
<p>I am trying to run the example shown here:</p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Optimizer" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Optimizer</a></p> <p>but it gives me this error:</p> <p>i am using linux with python 3</p> <pre...
<p>As suggested by @xdurch0 use tf.Variable instead tf.constant.</p> <p>Please check the working sample code below.</p> <pre><code>import tensorflow as tf import numpy as np var1=tf.Variable(3.0) var2=tf.Variable(3.0) opt = tf.keras.optimizers.SGD(learning_rate=0.1) # `loss` is a callable that takes no argument and r...
python|tensorflow
1
8,507
65,160,023
Any Advice on how to make this CNN training faster?
<p>I have been training a Neural Network for recognizing the differences between a paper with handwriting and a paper with Drawings, My images are all in (3508, 2480) size and I'm using a CNN for the task, the problem is that it is taking ages to train, I have 30,000 data belonging to 2 classes which are separated into...
<p>Your kernel size, 60 by 60, is quite big. Try 3 by 3 kernel or 5 by 5 kernel. It doesn't seem that image size is the problem since you are resizing from (3508, 2480) to (438, 310).</p> <p>Also notice that the number of weights you have is very, very large. It is around 24 million. This is because you are flattening ...
python|tensorflow|machine-learning|keras|deep-learning
0
8,508
65,485,322
How to return multiple columns using apply in Pandas dataframe
<p>I am trying to apply a function to a column of a Pandas dataframe, the function returns a list of tuples. This is my function:</p> <pre><code>def myfunc(text): values=[] sections=api_call(text) for (part1, part2, part3) in sections: value=(part1, part2, part3) values.append(value) return values </co...
<p>The idea here is to set up some data and a function that can be operated on this data to generate three items that we can return. Choosing split and comma-separated values seems to be quick and mirror the function you are after.</p> <pre><code>import pandas as pd data = { 'names' : ['x,a,c','y,er,rt','z,1,ere']} df...
pandas|apply
1
8,509
49,806,961
Matplotlib 2.02 plotting within a for loop
<p>I am having trouble with two things on a plot I am generating within a for loop, my code loads some data in, fits it to a function using curve_fit and then plots measured data and the fit on the same plot for 5 different sets of measured y value (the measured data is represent by empty circle markers and fit by a so...
<ul> <li>You are looping over the rows of <code>only_adam</code>, but index the columns of that array with the loop variable <code>i</code>. This does not make sense and leads to the error shown. </li> <li>The plot that shows the data points has lines in it. Those are the lines shown. You cannot make them smaller by de...
python|python-3.x|numpy|matplotlib|scipy
1
8,510
50,064,719
Testing if value is contained in Pandas Series with mixed types
<p>I have a pandas series, for example: <code>x = pandas.Series([-1,20,"test"])</code>.</p> <p>Now I would like to test if -1 is contained in <code>x</code> without looping over the whole series. I could transform the whole series to string and then test if <code>"-1" in x</code> but sometimes I have -1.0 and sometime...
<p>What about </p> <pre><code>x.isin([-1]) </code></pre> <p>output:</p> <pre><code>0 True 1 False 2 False dtype: bool </code></pre> <p>Or if you want to have a count of how many instances:</p> <pre><code>x.isin([-1]).sum() </code></pre> <p>Output:</p> <pre><code>1 </code></pre>
python|pandas
2
8,511
49,883,862
The .apply() method is not working
<p>So <code>friends</code> is a column with a list in each instance such as <code>df['friends][0] = [id1, id2, ..., idn]</code>. I'm trying to count the number of friends in a separate column such as <code>df['friend_counts'][0] = n</code>. </p> <p>I did the following. I've used this code in other datasets, but for so...
<p>I suggest use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> by <code>dictionary</code> for improve performance:</p> <pre><code>d = {1:'Winter', 2:'Winter', 12:'Winter', 3: 'Spring', .... np.nan:'NA', 'NA':'NA'} df_reviews['seaso...
python-3.x|pandas|apply
0
8,512
50,139,043
How to combine/merge Columns within the same Dataframe in Pandas?
<p>I have a data frame similar to this: </p> <pre><code> 0 1 2 3 4 5 0 1001 1 176 REMAINING US SOUTH 1 1002 1 176 REMAINING US SOUTH </code></pre> <p>What I would like to do is to combine columns 3,4, and 5 to create on column that has all of the data in columns 3,4, and 5...
<p>Use <code>concat</code> + <code>agg</code> </p> <pre><code>pd.concat( [df.iloc[:, :3], df.iloc[:, 3:].agg(' '.join, axis=1)], axis=1, ignore_index=True ) 0 1 2 3 0 1001 1 176 REMAINING US SOUTH 1 1002 1 176 REMAINING US SOUTH </code></pre>
python|pandas|dataframe
1
8,513
50,184,845
Prevent my RAM memory from reaching 100%
<p>I have a very simple python script that reads a CSV file and sorts the rows according to the timestamps. However, the file is large enough (16 GB) that its reading uses ram memory completely. When it reaches 100% (i.e. 64 GB RAM memory), my system completely freezes, and I am forced to restart my computer.</p> <p>H...
<p>Essentially, you have to implement your own out-of-memory sorting.</p> <ol> <li><p>Split your file in two or more pieces with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">Pandas CSV chunker</a>, sort each piece (one piece at a time!), save it into a...
python|pandas|memory|ram
1
8,514
63,837,400
Facebook messenger analysis using jupyter Notebook
<p>I downloaded Facebook messenger data and I'm trying to analyze it. So my goal is to know the number of occurrences of a word in all messages. I converted the JSON file to a pandas Dataframe, and I have a column that contains all the messages. I converted the messages column to a list and I tried to use NLTK to count...
<p>Try:</p> <pre><code>fdist = FreqDist() for words in tok_words: fdist.update(FreqDist(words)) fdist.most_common(5) </code></pre>
pandas|nlp|nltk|tokenize
0
8,515
64,025,109
fill values after condition with NaN
<p>I have a df like this:</p> <pre><code>df = pd.DataFrame( [ ['A', 1], ['A', 1], ['A', 1], ['B', 2], ['B', 0], ['A', 0], ['A', 1], ['B', 1], ['B', 0] ], columns = ['key', 'val']) df </code></pre> <p>print:</p> <pre><code> key val 0 A ...
<p>You can use <code>boolean indexing</code> with <code>cummax</code> to fill <code>nan</code> values:</p> <pre><code>df.loc[df['val'].eq(2).cummax(), 'val'] = np.nan </code></pre> <p>Alternatively you can also use <code>Series.mask</code>:</p> <pre><code>df['val'] = df['val'].mask(lambda x: x.eq(2).cummax()) </code></...
python-3.x|pandas|numpy
6
8,516
63,980,283
Merging MORE THAN two dataframes with pd.merge()
<p>Im trying to merge 4 csv files using pd.merge() based on a specific column ('filename'). I read that merge only works for two dataframes, and to instead try and merge the first two, then the 3rd, and then the 4th, in successive steps. This has ultimately worked, with the following code:</p> <pre><code>combine = pd.m...
<p>May be you can use parameter <code>suffixes</code> in merge to control column names. From the <a href="https://pandas.pydata.org/pandas-docs/version/0.25.2/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">pandas merge documentation</a>:</p> <blockquote> <p>Merge DataFrames df1 and df2 with specif...
python|python-3.x|pandas|merge|jupyter-notebook
1
8,517
47,043,682
extending the notion of missing values in pandas
<p>Suppose I have third party data which has some goofy convention for missing values (in my particular application, they use '-'). Is there some elegant way to tell pandas to extend its notion of missing value?</p>
<p>I think the best way to handle this would be by replacing '-' with np.nan.</p> <pre><code>df.replace('-', np.nan) </code></pre>
python|pandas
2
8,518
32,701,939
pandas resample with function that returns an array
<p>The <code>pd.resample</code> function accepts any function that goes from an array to a number as its <code>how</code> keyword argument (although that's not in the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow">docs</a>). So the following example works w...
<p>Because that fft function changes the shape of the input you can't just apply it directly. Here would be one way to wrap it.</p> <pre><code>In [331]: def wrap_fft(df): ...: return pd.DataFrame({c:np.fft.rfft(df[c]) for c in df}) In [332]: df.groupby(pd.TimeGrouper('10D')).apply(wrap_fft) Out[332]: ...
python|arrays|pandas
1
8,519
32,640,438
Pandas: rolling std deviation/mean by trading days
<p>I am trying to extract the rolling std deviation and mean on trading data by using <code>rolling_*</code> functions of <code>pandas</code>. </p> <p>My data looks like:</p> <pre><code>Tick Trading_day Trade_price VOD 2013-1-2 30.23 VOD 2013-1-2 30.33 VOD 2013-1-2 30.24 VOD 2013-1-5...
<p>Here is the data I'm using in this example:</p> <pre><code>df = pd.DataFrame({'Tick': ['VOD'] * 7 + ['RBS'] * 2, 'Trade_price': [30.23, 30.24, 31.23, 30.23, 30.23, 30.23, 30.23, 14.11, 15.23], 'Trading_day': ['1/2/13', '1/2/13', '1/5/13', '1/5/13', '1/6/13', '1/7/13', '1/8/13',...
python|pandas|trading
3
8,520
38,523,920
Variable shift in Pandas
<p>having two columns A and B in a dataframe: </p> <pre><code> A B 0 1 6 1 2 7 2 1 8 3 2 9 4 1 10 </code></pre> <p>I would like to create a column C. C must have values of B shifted by value of A:</p> <pre><code> A B C 0 1 6 NaN 1 2 7 NaN 2 1 8 7 3 2 9 7 4 1 10 9 </code><...
<p>I'd use help from <code>numpy</code> to avoid the <code>apply</code></p> <pre><code>l = np.arange(len(df)) - df.A.values df['C'] = np.where(l &gt;=0, df.B.values[l], np.nan) df A B C 0 1 6 NaN 1 2 7 NaN 2 1 8 7.0 3 2 9 7.0 4 1 10 9.0 </code></pre> <hr> <p><strong><em>simple time test</...
python|pandas|shift
5
8,521
63,220,132
SQLAlchemy Insert to MySQL DB UnicodeEncodeError for cyrlic data
<p>I use Python.SQLAlchemy with MySQL Database. All code bellow normal work for latin symbols in data, but not work for cyrilic:</p> <blockquote> <p>UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-17: character maps to </p> </blockquote> <p>I added &quot;encoding='utf8', convert_unicode=True&q...
<blockquote> <p>Try adding <code>?charset=utf8mb4</code> to the end of your connection URI. – Gord Thompson</p> </blockquote>
mysql|python-3.x|pandas|encoding|sqlalchemy
6
8,522
63,095,949
Error when trying to read multiple .csv files in Jupyter Notebook using python
<p>I am given a file that contains 1000 .csv files(data0,data1,data2..........,data999) and I need to read all those files. So, I tried it on my own. This was my approach: read data0.csv and perform transpose on it and then loop it through all the data*.csv files and then append them. But I was getting an error. Could ...
<p>I couldn't test this, because you did not provide an example of your file as text. Please try to provide a <a href="https://stackoverflow.com/help/minimal-reproducible-example">minimal reproducible example</a> next time.</p> <p>My solution is a minor variation of <a href="https://stackoverflow.com/questions/20906474...
python|pandas|csv|jupyter-notebook
0
8,523
63,058,307
Tensorflow Dataset Mask Sequence for Evaluation
<h3>Problem:</h3> <p>Given variable-length inputs, the accuracy metric is incorrect because short vectors are padded to longer ones.</p> <p>Using the <code>Masking</code> layer from <code>keras</code> solves this, by applying a mask to all zero values, but because my sequence contains zeros naturally, and super long (5...
<p>Hope this helps. You can see it takes not just input/output, but a second input as well. I'm also using more than 1 output, and so you can pass information in and out of the neural network. I hope you'll feel energized by the customizable nature of this example.</p> <pre><code>import os os.environ['TF_CPP_MIN_LOG_LE...
python|tensorflow|keras
1
8,524
67,994,364
Is there a convenient way to get class-specific Average Precision scores for a TensorFlow Object Detection model?
<p>The TensorFlow Object Detection API has a very convenient way to get performance metrics for trained models (described in their tutorial <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html#evaluating-the-model-optional" rel="nofollow noreferrer">here</a>). Unfortunately, ...
<p>After some more searching, I found a couple solutions.</p> <p><strong>1. Use a different evaluation configuration</strong></p> <p>Simply change the <code>metrics_set</code> value in the <code>*.config</code> file for your model to <code>&quot;pascal_voc_detection_metrics&quot;</code>.</p> <p>The TensorFlow Object De...
python|tensorflow|object-detection-api
1
8,525
41,515,877
How to set index values in a MultiIndex pandas DataFrame?
<p>I have a MultiIndex pandas DataFrame and need to change the level 0 index <em>values</em>. The current DataFrame has a MultiIndex called <code>(test, time)</code>.</p> <p>How do I set the string "Test 4" (in the top level of the index) to be some other string?</p> <p>For extra points, many of my DataFrames will h...
<p>You can pass a dictionary to <code>rename</code> to rename specific values in any index.</p> <pre><code>df.rename(index={'Test4':'something else'}) </code></pre>
python|pandas
6
8,526
41,275,921
NaNs when extracting no. of days between two dates in pandas
<p>I have a dataframe that contains the columns company_id, seniority, join_date and quit_date. I am trying to extract the number of days between join date and quit date. However, I get NaNs.</p> <p>If I drop off all the columns in the dataframe except for quit date and join date and run the same code again, I get wha...
<p>Instead of converting to string, extract the number of days from the timedelta value using the <code>dt</code> accessor.</p> <pre><code>import pandas as pd df = pd.DataFrame({'join_date': ['2014-03-24', '2013-04-29', '2014-10-13'], 'quit_date':['2015-10-30', '2014-04-04', '']}) df['join_date'] =...
python|pandas
2
8,527
27,686,240
Calculate Mahalanobis distance using NumPy only
<p>I am looking for NumPy way of calculating Mahalanobis distance between two numpy arrays (x and y). The following code can correctly calculate the same using cdist function of Scipy. Since this function calculates unnecessary matix in my case, I want more straight way of calculating it using NumPy only.</p> <pre><co...
<p>I think your problem lies in the construction of your covariance matrix. Try:</p> <pre><code>X = np.vstack([xx,yy]) V = np.cov(X.T) VI = np.linalg.inv(V) print np.diag(np.sqrt(np.dot(np.dot((xx-yy),VI),(xx-yy).T))) </code></pre> <p>Output:</p> <pre><code>[ 2.28765854 2.75165028 2.75165028 2.75165028 0. ...
python|numpy
24
8,528
61,531,470
pd.Series.to_list() changing dtype
<p>When I am programming on colab, I keep running into this issue:</p> <p>Here is my df:</p> <pre><code>0 1 0 [2.7436598593417045e-05, 3.731542193080655e-05] 1 [8.279973504084787e-05, 2.145002145002145e-05] 2 [0.00022534319714215346, 0.0002031172259231674] 3 [3.239841667031943e-05, 2.777129...
<p>Try <code>ast.literal_eval</code></p> <pre><code>from ast import literal_eval df[1].map(literal_eval).to_list() [[2.7436598593417045e-05, 3.731542193080655e-05], [8.279973504084787e-05, 2.145002145002145e-05], [0.00022534319714215346, 0.00020311722592316746], [3.239841667031943e-05, 2.7771297808289177e-05], [...
python|pandas|numpy|google-colaboratory
2
8,529
61,239,649
can not update Tensorflow for Conda
<p>I want to update Tensorflow from 1.14 to 2.1.0 but I'm not able to do it.</p> <p>After I had installed it with command</p> <blockquote> <p>conda install -c anaconda tensorflow-gpu</p> </blockquote> <p>print(tensorflow.<strong>version</strong>) shows me that I have version 1.14.0</p> <p>The same after</p> <blo...
<p>You can update Tensorflow by typing this command to the Anaconda Prompt. </p> <pre><code>conda install -c conda-forge tensorflow=2.1.0 </code></pre> <p>Hope this works!</p>
python-3.x|tensorflow|conda
1
8,530
61,215,270
input_shape with image_generator in Tensorflow
<p>I'm trying to use this approach in Tensorflow 2.X to load large dataset that does not fit in memory.</p> <p>I have a folder with X sub-folders that contains images. Each sub-folder is a class.</p> <pre><code>\dataset -\class1 -img1_1.jpg -img1_2.jpg -... -\classe2 -img2_1.jp...
<p>For the benefit of community here i am explaining, how to use <code>image_generator</code> in Tensorflow with input_shape <code>(100, 100, 3)</code> using <code>dogs vs cats</code> dataset </p> <p>If we haven't choose right batch size there is a chance of model struck right after first epoch, hence i am starting my...
tensorflow2.0|tensorflow-datasets
0
8,531
61,289,172
Pandas drop subset of dataframe
<p>Assume we have <code>df</code> and <code>df_drop</code>:</p> <pre><code>df = pd.DataFrame({'A': [1,2,3], 'B': [1,1,1]}) df_drop = df[df.A==df.B] </code></pre> <p>I want to delete <code>df_drop</code> from <code>df</code> without using the explicit conditions used when creating <code>df_drop</code>. I.e. I'm not af...
<p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> both dataframes setting <code>indicator=True</code> and drop those columns where the indicator column is <code>both</code>:</p> <pre><code>out = pd.merge(df,df_dr...
python|pandas|dataframe
3
8,532
68,669,726
How to create rows in a pandas dataframe that are averages of other rows?
<p>Take a dataframe like this one:</p> <pre><code>import pandas as pd info = {'Year': [2010, 2010, 2010, 2010, 2015, 2015, 2015, 2015], 'Country': ['USA', 'Mexico', 'Canada', 'China', 'USA', 'Mexico', 'Canada', 'China'], 'AgeAvg': [40, 44, 45, 49, 45, 46, 50, 52], 'HeightAvg': [68, 65, 67, 68, 6...
<p>Use <code>pd.MultiIndex.from_product</code> to reindex your dataframe and interpolate values:</p> <pre><code>mi = pd.MultiIndex.from_product([df['Country'].unique(), range(df.Year.min(), df.Year.max()+1)]) out = df.set_index(['Country', 'Year']).reindex(mi) out = out.groupby(level=0...
python|pandas|dataframe
1
8,533
68,861,665
Pandas add dataframe to another row-wise by columns setting columns not available in the other as "nan"
<p>Say we have two dataframes, A with columns a,b,c and B with columns a,b,d and some values</p> <p>A =</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>a</th> <th>b</th> <th>c</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>6</td> </tr>...
<p>Use <code>pd.concat([A, B], axis=0, ignore_index=True)</code></p>
python|pandas|dataframe
1
8,534
68,690,917
Colour intensity is changing when stacking numpy image arrays
<p>I am loading an image from <a href="https://github.com/Jimut123/simply_junk/blob/main/image.nii.gz?raw=true" rel="nofollow noreferrer">here</a>, which is saved as .nii.gz. The image opens fine (with a dimension of (497x497)), and when displayed using matplotlib, it shows with correct intensities, as shown below:</p>...
<p>If you scale it as Cristolph and Johan described, the 3-channel plot becomes identical:</p> <pre class="lang-py prettyprint-override"><code>epi_img_data -= epi_img_data.min() epi_img_data /= epi_img_data.max() total_mask = np.stack((epi_img_data,)*3, axis=-1) plt.imshow(total_mask) </code></pre> <p><a href="https:/...
python|numpy|opencv|matplotlib
2
8,535
68,529,258
RTX 3070 compatibility with Pytorch
<blockquote> <p>NVIDIA GeForce RTX 3070 with CUDA capability sm_86 is not compatible with the current PyTorch installation. The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_70.</p> </blockquote> <p>So I'm currently trying to train a neural network but I'm getting this issue. It seems that the...
<p>It might be because you have installed a torch package with cuda==10.* (e.g. <code>torch==1.9.0+cu102</code>) . I'd suggest trying:</p> <pre><code>pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html </code></pre>
deep-learning|pytorch|gpu|nvidia
5
8,536
36,523,861
Can pandas SparseSeries store values in the float16 dtype?
<p>The reason why I want to use a smaller data type in the sparse pandas containers is to reduce memory usage. This is relevant when working with data that originally uses bool (e.g. from <code>to_dummies</code>) or small numeric dtypes (e.g. int8), which are all converted to float64 in sparse containers.</p> <h2>Data...
<p>The <code>SparseArray</code> constructor can be used to convert its underlying <code>ndarray</code>'s dtype. To convert all sparse series in a dataframe, one can iterate over the df's series, convert their arrays, and replace the series with converted versions.</p> <pre><code>import pandas as pd import numpy as np ...
python|pandas|sparse-matrix|type-conversion
1
8,537
53,124,999
mark attendance of the user in dataframe
<p>I have a dataframe in which a user's daily entry and exit is noted, but the user comes at different time each day, for example below is the input user data</p> <pre><code>Date UserID Intime Outtime 2018-06-29 73456 2018-06-29 07:30:54 2018-06-29 15:30:13 2018-06-28 73456 2018-06-28 08:29:23 2018-06-28 ...
<p>Try this:</p> <p>Build the hourly set</p> <pre><code>s = pd.date_range(df1.index[0], df1.index[-1]+pd.DateOffset(1), freq='H') idx = pd.period_range(df1.index[0], df1.index[-1]+pd.DateOffset(1), freq='H') idx = idx[:-1] </code></pre> <p>Find when the index is inside the range of <code>Intime</code> and <code>Outt...
python|pandas|dataframe
2
8,538
53,333,131
Cannot Import Pandas in Python3.6.5
<p>I have installed pandas successfully in Terminal using the command: sudo pip3 install pandas. The installation information is shown as below:</p> <pre><code>Requirement already up-to-date: pandas in ./.local/lib/python3.6/site- packages (0.23.4) Requirement already satisfied, skipping upgrade: python-dateutil&gt;...
<p>Are you using Jupyter Notebook? What happens is, that you might have an virtual evironment, that has no Jupyter Notebook installed. After calling it from your current environment, it goes to the base environemnt and searches for it there. And if the search is succesfull, Jupyter will open, but in another environment...
python|pandas
0
8,539
53,337,769
How to optimize below code to run faster, size of my dataframe is almost 100,000 data points
<pre><code>def encoder(expiry_dt,expiry1,expiry2,expiry3): if expiry_dt == expiry1: return 1 if expiry_dt == expiry2: return 2 if expiry_dt == expiry3: return 3 FINAL['Expiry_encodings'] = FINAL.apply(lambda row: '{0}_{1}_{2}_{3}_{4}'.format(row['SYMBOL'],row['INSTRUMENT'],row['ST...
<p>Give the following a try:</p> <pre><code>FINAL['expiry_number'] = '0' for c in '321': FINAL.loc[FINAL['EXPIRY_DT'] == FINAL['Expiry'+c], 'expiry_number'] = c FINAL['Expiry_encodings'] = FINAL['SYMBOL'].astype(str) + '_' + \ FINAL['INSTRUMENT'].astype(str) + '_' + FINAL['STRIKE_PR'].astype(str) + \ '_' ...
python|pandas|numpy|dataframe
3
8,540
53,090,114
Concatenate 5 unpickle dictionaries without overwriting (data is from CIFAR-10)
<pre><code>def unpickle(file): import pickle with open(file, 'rb') as fo: dict = pickle.load(fo, encoding='bytes') return dict dict1 = unpickle(data_dir1) dict2 = unpickle(data_dir2) dict3 = unpickle(data_dir3) dict4 = unpickle(data_dir4) dict5 = unpickle(data_dir5) </code></pre> <p>Data Format (from CIFAR-10):</...
<p><code>np.concatenate((dict1, dict2, dict3, dict4, dict5), axis=0)</code> should work</p>
python|numpy
0
8,541
65,732,637
Loop a function and bind together Pandas dataframe
<p>I have a function that connects to an SQL database and fetch data from a table. I aim to loop that function over an iterator to make the same query on different tables. The function works, but the for loop below do not return anything. I'm new to Python and I'm sure I miss something fundamental here.</p> <p>Example ...
<p>You need to pass an argument to the function for it to accept and loop over. Also you might want to consider <code>pd.concat</code> so you can assign a variable to your dataframe.</p> <p>So something like this would work and is cleaner:</p> <pre><code>def select_top(year): conn = pyodc.connect() sql_query = ...
python|pandas|for-loop
1
8,542
65,516,014
Python Pandas: Create a nested function to create new cols in final output
<p>I am trying to figure out how to create a function to trigger inner nested function in order to create my desired output. I wish to output a new dataframe with new columns based on different conditions.</p> <p>snippet of code:</p> <pre><code> def func1(df): alist = [] error ={} for i in df.index...
<p>You're setting the new column weirdly</p> <pre><code>df[alist, 'new_col'] = 'some_msg' </code></pre> <p>Just set it directly</p> <pre><code> def func1(df): alist = [] error ={} for i in df.index: if pd.isna([df.at[i, &quot;col_name&quot;]) == True: alist.append[i] d...
python|pandas|dataframe
0
8,543
21,320,405
How to write a pandas Series to CSV as a row, not as a column?
<p>I need to write a <code>pandas.Series</code> object to a CSV file as a row, not as a column. Simply doing</p> <pre><code>the_series.to_csv( 'file.csv' ) </code></pre> <p>gives me a file like this:</p> <pre><code>record_id,2013-02-07 column_a,7.0 column_b,5.0 column_c,6.0 </code></pre> <p>What I need instead is t...
<p>You can just use the DataFrame constructor (rather than to_frame):</p> <pre><code>In [11]: pd.DataFrame(s).T Out[11]: record_id column_a column_b column_c 2013-02-07 7 5 6 </code></pre>
python|csv|pandas
17
8,544
2,572,916
Numpy ‘smart’ symmetric matrix
<p>Is there a smart and space-efficient symmetric matrix in numpy which automatically (and transparently) fills the position at <code>[j][i]</code> when <code>[i][j]</code> is written to?</p> <pre><code>import numpy a = numpy.symmetric((3, 3)) a[0][1] = 1 a[1][0] == a[0][1] # True print(a) # [[0 1 0], [1 0 0], [0 0 0]...
<p>If you can afford to symmetrize the matrix just before doing calculations, the following should be reasonably fast:</p> <pre><code>def symmetrize(a): """ Return a symmetrized version of NumPy array a. Values 0 are replaced by the array value at the symmetric position (with respect to the diagonal),...
python|matrix|numpy
93
8,545
63,487,363
Error when trying to multiply a variable?
<p>I'm trying to multiply a variable to output a weighted value as follows:</p> <pre><code>import numpy as np import pandas as pd data_2017_18.income1_weight = data_2017_18.income1 * data_2017_18.survey_weight </code></pre> <p>I'm receiving the following error message:</p> <p>TypeError: Object with dtype category cann...
<p>Try <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="nofollow noreferrer"><code>Series.astype</code></a>:</p> <pre><code>data_2017_18.income1_weight = data_2017_18.income1.astype(float) * data_2017_18.survey_weight </code></pre>
python|pandas
2
8,546
63,483,588
Python - how to get table id
<p>The HTML is shown as below. How can i get the id=&quot;table_1880381&quot;?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="match" id="table_1880381"&gt;&...
<p>Your html is confusing, but there are a number of ways to get to where you want to go.</p> <p>Try something like:</p> <pre><code>soup.select_one('div.home').attrs['id'].split('_')[1] </code></pre> <p>or</p> <pre><code>soup.select_one('div.time').attrs['id'].split('_')[1] </code></pre> <p>Output, in either case:</p> ...
python-3.x|pandas|beautifulsoup
1
8,547
21,430,938
RGB to XYZ in Scikit-Image
<p>I am trying to convert an image from RGB to XYZ using scikit-image. I found out that there are some differences depending the input type:</p> <pre><code>from numpy import array,uint8 import skimage.color rgb = array([array([[56,79,132],[255,100,70]])]) i1 = skimage.color.rgb2xyz(rgb)#rgb.dtype -&gt;dtype('int32')...
<p>The following code should be self explanatory, but floating point values should have a range in <code>(0, 1)</code>, and integer type have their full range mapped to <code>(0, 1)</code> (for unsigned types) or <code>(-1, 1)</code> (for signed types):</p> <pre><code>&gt;&gt;&gt; from numpy import int32 &gt;&gt;&gt; ...
python|image-processing|numpy|colors|scikit-image
0
8,548
21,828,202
Fast inverse and transpose matrix in Python
<p>I have a large matrix <code>A</code> of shape <code>(n, n, 3, 3)</code> with <code>n</code> is about <code>5000</code>. Now I want find the inverse and transpose of matrix <code>A</code>:</p> <pre><code>import numpy as np A = np.random.rand(1000, 1000, 3, 3) identity = np.identity(3, dtype=A.dtype) Ainv = np.zeros_...
<p>This is taken from a project of mine, where I also do vectorized linear algebra on many 3x3 matrices.</p> <p>Note that there is only a loop over 3; not a loop over n, so the code is vectorized in the important dimensions. I don't want to vouch for how this compares to a C/numba extension to do the same thing though...
python|numpy|transpose|matrix-inverse
7
8,549
21,600,219
how can i remove multiple rows with different labels in one command in pandas?
<p>I have a pandas dataframe that looks like the one below, and I want to drop several labels.</p> <p>What works fine is:</p> <pre><code>df = df[df['label'] != 'A'] </code></pre> <p>or:</p> <pre><code>df = df[(df['label'] != 'A') &amp; (df['label'] != 'B')] </code></pre> <p>However, I have many labels that I want ...
<p>try this:</p> <pre><code>import numpy as np df = df[np.logical_not(df['label'].isin(['A','B']))] </code></pre> <p>or</p> <pre><code>df = df[- df['label'].isin(['A', 'B'])] </code></pre> <p>see <a href="https://stackoverflow.com/questions/14057007/remove-rows-not-isinx">Remove rows not .isin(&#39;X&#39;)</a></p>
python|pandas
0
8,550
24,841,306
Python - Sum 4D Array
<p>Given a <code>4D</code> array <code>M: (m, n, r, r)</code>, how can I sum all the <code>m * n</code> inner matrices (of shape <code>(r, r)</code>) to get a new matrix of shape <code>(r * r)</code>?</p> <p>For example, </p> <pre><code> M [[[[ 4, 1], [ 2, 1]], [[ 8, 2], [ 4, 2]]], ...
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow">einsum</a>:</p> <pre><code>In [21]: np.einsum('ijkl-&gt;kl', M) Out[21]: array([[32, 8], [16, 8]]) </code></pre> <hr> <p>Other options include reshaping the first two axes into one axis, and then...
python|arrays|numpy
5
8,551
24,462,725
How can I do element-wise arithmetic on Numpy matrices?
<p>I am using Numpy's <code>matlib</code> style matrices for a particular algorithm. This means that the multiplication operator <code>*</code> performs the equivalent of an <code>ndarray</code>'s <code>dot()</code>:</p> <pre><code>&gt;&gt;&gt; import numpy.matlib as nm &gt;&gt;&gt; a = nm.asmatrix([[1,1,1],[1,1,1],[1...
<p>You could use <code>np.multiply</code>:</p> <pre><code>&gt;&gt;&gt; a = np.matrix(np.random.rand(3,3)) &gt;&gt;&gt; b = np.matrix(np.random.rand(3,3)) &gt;&gt;&gt; a * b matrix([[ 1.29029129, 0.53126365, 2.12109815], [ 0.99370991, 0.55737572, 1.9167072 ], [ 0.76268194, 0.43509462, 1.48640178]]...
python-3.x|numpy
1
8,552
30,111,884
data type "country" not understood
<p>I am getting the following error for my code: data type "country" not understood. I am relatively new to python and am basically trying to learn how to work with .csv files. I'm using python 3.4 and editor Canopy. I was trying to format the data types of the csv into strings and floats, but as soon as i try to assig...
<p>Looks like the arguments you are passing to numpy.getfromtxt are incorrectly formatted.</p> <p>If you want to pass a value to both names and dtype arguments then you need to specify dtype as a coma separated string: "a200, i4, etc..."</p> <p>Alternatively you can pass a list of tuple ("name", "type") pairs and not...
python|csv|numpy
2
8,553
53,755,046
numpy large integer failed
<p>I recently work on some project Euler problems</p> <h1>Smallest multiple</h1> <h2>Problem 5</h2> <p>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.</p> <p>What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</...
<p>The problem is that the number reached a size that meant that it was no longer representable by ints in Python. If you look <a href="https://docs.scipy.org/doc/numpy/user/basics.types.html" rel="nofollow noreferrer">here</a>, you'll see that ints max out in size around 19 digits (i.e. 2^63 from 63 bits + sign bit) a...
python|numpy|biginteger
1
8,554
53,435,807
Validate Pandas dataframe column based on hierarchy
<p>I have a dataframe like this </p> <pre><code>df1 = pd.DataFrame({'Site': ["S1", "S2", "S3", "S4", "S5", "S6","S7","S8","S9"], 'Sitelink': [" ","S1","S2","S6","S4"," ","S8"," ","S7"], 'level': ["R", "T", "P", "T", "P", "R","T","R","P"], ...
<p>If i understand correctly, you would like to to check if for each row the weight of the site is lower than or equal to the weight of the site marked as the <em>Sitelink</em>. </p> <p>The code for a single row would than be:</p> <pre><code>def is_error(row): if row['Sitelink'] == " ": return 'No Error'...
pandas|dataframe
0
8,555
53,545,350
Do I need a neural network or graph database like neo4j for suggestion engine?
<p>I am building a simple recommendation/suggestion engine for a demo application which maintains a list of people. For each person, it keeps track of their food habits with the following preferences:</p> <ol> <li>Diet type: Vegetarian/non-vegetarian/vegan</li> <li>Cuisine likings: Indian, Mexican, Italian, etc. (a pe...
<p>The easiest way to know which one to choose is to answer this more specific question. Is the data open world or <a href="https://en.wikipedia.org/wiki/Closed-world_assumption" rel="nofollow noreferrer">closed world</a>. </p> <p>If you are an original <a href="https://en.wikipedia.org/wiki/The_Corbomite_Maneuver#Plo...
tensorflow|machine-learning|neo4j
3
8,556
19,964,546
Pandas fuzzy merge/match name column, with duplicates
<p>I have two dataframes currently, one for <code>donors</code> and one for <code>fundraisers</code>. I'm trying to find if any <code>fundraisers</code> also gave donations, and if so, copy some of that information into my <code>fundraiser</code> dataset (donor name, email and their first donation). Problems with my da...
<p>Here's a bit more pythonic (in my view), working (on your example) code, without explicit loops:</p> <pre class="lang-py prettyprint-override"><code>def get_donors(row): d = donors.apply(lambda x: fuzz.ratio(x['name'], row['name']) * 2 if row['Email'] == x['Email'] else 1, axis=1) d = d[d &gt;= 75] if l...
python|pandas|dataframe|fuzzywuzzy|fuzzy-comparison
4
8,557
20,115,312
python pandas applying for loop and groupby function
<p>I am new to python and I am not familiar iterating with the groupby function in pandas I modified the code below and it works fine for creating a pandas dataframe</p> <pre><code>i=['J,Smith,200 G Ct,', 'E,Johnson,200 G Ct,', 'A,Johnson,200 G Ct,', 'M,Simpson,63 F Wy,', 'L,Diablo,60 N Blvd,', 'H,Simpson,63 F Wy,', '...
<h3>Version with loop/generator:</h3> <p>First, we create helper function and group data by <code>Lastname, Address</code>:</p> <pre><code>def helper(k, g): r = len(g) address, lastname = k if r &gt; 2: lastname = 'The {} Family'.format(lastname) elif r &gt; 1: lastname = ' and '.join(...
python|pandas|iteration|grouping
1
8,558
15,626,375
Python/Numpy - Cross Product of Matching Rows in Two Arrays
<p>What is the best way to take the cross product of each corresponding row between two arrays? For example:</p> <pre><code>a = 20x3 array b = 20x3 array c = 20x3 array = some_cross_function(a, b) where: c[0] = np.cross(a[0], b[0]) c[1] = np.cross(a[1], b[1]) c[2] = np.cross(a[2], b[2]) ...etc... </code></pre> <p>I ...
<p>I'm probably going to have to delete this answer in a few minutes when I realize my mistake, but doesn't the obvious thing work?</p> <pre><code>&gt;&gt;&gt; a = np.random.random((20,3)) &gt;&gt;&gt; b = np.random.random((20,3)) &gt;&gt;&gt; c = np.cross(a,b) &gt;&gt;&gt; c[0], np.cross(a[0], b[0]) (array([-0.024691...
python|numpy|cross-product
6
8,559
12,347,797
How can I produce a nice output of a numpy matrix?
<p>I currently have the following snippet:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import numpy from numpy import linalg A = [[1,2,47,11],[3,2,8,15],[0,0,3,1],[0,0,8,1]] S = [[113,49,2,283],[-113,0,3,359],[0,5,0,6],[0,20,0,12]] A = numpy.matrix(A) S = numpy.matrix(S) numpy.set_printoptions(precisi...
<p>If you use numpy 1.8.x you can customize formatting with the <code>formatter</code> parameter. For example, setting:</p> <pre><code>numpy.set_printoptions(formatter={'float': lambda x: 'float: ' + str(x)}) </code></pre> <p>All floats would be printed like <code>float: 3.0</code>, or <code>float: 12.6666666666</cod...
python|numpy|formatting|gedit
4
8,560
71,996,147
How to make a boolean array by checking if the items in an array is in a list?
<p>I'm trying to find every item in an numpy array <code>arr</code> that's also in an arbitrary list <code>lst</code> and replace them, but while <code>arr &gt; 0</code> will generate a boolean array for easy masking, <code>arr in lst</code> only works with all() or any() which isn't what I need.</p> <p>Example input: ...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.isin.html" rel="nofollow noreferrer"><code>numpy.isin</code></a>:</p> <pre><code>a = np.array((1, 2, 3, 4, 5)) lst = [2, 4, 6, 8] a[np.isin(a, lst)] = 0 </code></pre> <p>Gives you an <code>a</code> of:</p> <pre><code>array([1, 0, 3, 0, 5]) <...
python|arrays|list|numpy|boolean
2
8,561
71,860,723
Dynamically update pandas NaN based on field type in django model
<p>I need to save data from csv file to django models. The data comes from external api so I have no control on its structure. In my schema, I allowed all fields to be nullable.</p> <p>This is my script</p> <pre><code> text = f&quot;{path}/report.csv&quot; df = pd.read_csv(text) row_iter = df.iterrows...
<p>Nullable Django models won't take <code>np.nan</code> or other Pandas-compatible <code>not-a-number</code> objects. It expects taking <code>None</code> as in stock Python. When you have <code>nan</code> values, before you save them to Django, just replace them with <code>None</code> to avoid the validation error.</p...
python|django|pandas
0
8,562
55,563,411
How to resample a column by id
<p>I have a dataset like:</p> <pre><code>id date value 1 16-12-1 9 1 16-12-1 8 1 17-1-1 18 2 17-3-4 19 2 17-3-4 20 1 17-4-3 21 2 17-7-13 12 3 17-8-9 12 2 17-9-12 11 1 17-11-12 19 3 17-11-12 21 </code></pre> <p>The only structure above is that...
<p>Weekly sum by id:</p> <pre><code>df['date'] = pd.to_datetime(df['date'], format='%y-%m-%d') df = df.set_index('date') df.groupby('id').resample('W')['value'].agg('sum').loc[lambda x: x&gt;0] </code></pre> <p>Output:</p> <pre><code>id date 1 2016-12-04 17 2017-01-01 18 2017-04-09 21 2...
python|pandas|dataframe|time-series|pandas-groupby
3
8,563
56,831,607
Can tf.keras.layers.xx be used independently from tf.keras.Sequential or Model?
<p>In Tensorflow, many functions from some modules have been deprecated. Those from <code>tf.keras.layers</code> have been recommended. The <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model" rel="nofollow noreferrer">tutorials</a> provide examples of the usage of them by associating them with either <c...
<blockquote> <p>I want to know whether it's possible to use some classes in tf.keras.layers (e.g., Dense, Conv1D, etc.) without using Sequential or Model.</p> </blockquote> <p>Yes, sure it is. We can just 'call' the layer directly by doing something like this, for example:</p> <pre class="lang-py prettyprint-overri...
tensorflow|tf.keras
0
8,564
56,737,647
How to map lists of values to categorical vector
<p>I'm trying to do some clustering on a dataset of videos based on duration. I have a dictionary in which keys are user IDs, and values are a list of float (videos duration), 1 float per video created by the user.</p> <p>Example :</p> <pre><code>videos_per_user = { 63: [15.011667, 21.823333, 29.981667, 10.341667...
<h3><code>searchsorted</code> and <code>bincount</code></h3> <pre><code>b = np.arange(5, 30, 5) # array([ 5, 10, 15, 20, 25]) </code></pre> <p><strong>PLEASE NOTE:</strong> The <code>minlength</code> is what guarantees that all arrays will be of the same length. However, it needs to be set at the actual number of ca...
python|pandas
1
8,565
56,761,609
Classification of time series of variable lengths using 1D CNN in tensorflow
<p>I have a dataset consisting of time series of different lengths. For instance, consider this</p> <pre><code>ts1 = np.random.rand(230, 4) ts2 = np.random.rand(12309, 4) </code></pre> <p>I have 200 sequences in the form of list of arrays </p> <pre><code>input_x = [ts1, ts2, ..., ts200] </code></pre> <p>These time ...
<p>When working with a time series you want to define the input to the NN as <code>(batch_size, sequence_length, features)</code>.</p> <p>Which corresponds to a <code>input_shape=(sequence_length, 4,)</code> in your case. You will have to decide upon a maximum sequence length that you will process for the purposes of ...
python|tensorflow|keras
1
8,566
56,795,389
When saving to csv using pandas, I get two same databases instead of two separate ones
<p>I am doing some exercise as part of a GIS and Python Course that I am undertaking individually through Git. The exercise is analysis of weather data from two weather stations. Their IDs are spelled USAF and have codes: 29980 and 28450. I have created a "selected" dataframe from the existing one and from that one, I ...
<p>You need to modify your code as </p> <pre><code>kumpula_df = selected.loc[selected['USAF']==29980] rovaniemi_df = selected.loc[selected['USAF']==28450] kumpula_df.to_csv("Kumpula.csv", sep=',', float_format="%2f") rovaniemi_df.to_csv("rovaniemi.csv", sep=',', float_format="%2f") </code></pre> <p>Hope this helps!</...
python|pandas|csv|export-to-csv
1
8,567
25,514,903
Pythonian structure?
<p>I'm someone that is semi-well versed in MATLAB, but am trying to move those skills to Python in hopes of future job prospects. For example, when performing machine learning, I enjoy MATLAB because I can make my function clean looking as below for example:</p> <pre><code> main.m ------------ prescreen_fn(directory...
<p>Your question may get closed as being off-topic or too broad, but I think it's a good question if rephrased as "what's the python equivalent of this code". </p> <p>Generally speaking, this is something that a lot of folks coming from matlab get confused by. In python, things are separated into "namespaces" and yo...
python|matlab|numpy
5
8,568
25,992,795
Fastest way to create an array in Python
<p>I want to create a 3D array in Python, filled with -1.</p> <p>I tested these methods:</p> <pre><code>import numpy as np l = 200 b = 100 h = 30 %timeit grid = [[[-1 for x in range(l)] for y in range(b)] for z in range(h)] 1 loops, best of 3: 458 ms per loop %timeit grid = -1 * np.ones((l, b, h), dtype=np.int) 10 ...
<p>The only thing I can think to add is that any of these methods will be faster with the <code>dtype</code> argument chosen to take up as little memory as possible.</p> <p>Assuming you need no more space that <code>int8</code>, the method suggested by @RutgerKassies in the comments took this long on my system:</p> <pr...
python|numpy
2
8,569
66,898,158
Matplotlib barh yticklabels not displayed correctly
<p>I have the below code implemented to save a <code>barh</code> type plot as a .png file.</p> <pre><code> fig, ax = plt.subplots() width=0.5 ind = np.arange(len(df['Count'])) # the x locations for the groups ax.barh(ind, df['count'], 0.8, color=&quot;blue&quot;) ax.set_yticks(ind+width/2) ax.se...
<p>In this line: <code>ax.text(v + 4, i + .1, str(v), color='blue')</code>, you use x,y (position of the text) and add a constant 4, this constant will have different consequences in different plots.</p> <p>You can try this instead:</p> <pre class="lang-py prettyprint-override"><code>ax.text(v + v/4, i + .1, str(v), co...
python|pandas|dataframe|matplotlib
1
8,570
66,950,811
Plot 3d vectors and points on the same plot in python?
<p>I have the following matrix:</p> <pre><code> X = np.array([[1,2],[3,4],[5,6]]) </code></pre> <p>and the following vectors</p> <pre><code>Vecs = np.array([[ 0.70710678, 0.70710678, 0. ], [ 0. , 0. , 1. ], [-0.70710678, 0.70710678, 0. ]]) </code></pre> <p>I want t...
<p>You can use <code>scatter</code> for points and <code>quiver</code> for vectors + experiment with different parameters of <code>view_init</code> to find the best angle:</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(projection='3d') ax.view_init(15, 35) ax.scatter(xs=X[0], ys=X[1], zs=X[2], color='crimson')...
python|numpy|matplotlib|plot|vector
0
8,571
67,023,233
How do I filter out rows based on another data frame in Python?
<p>So I need to filter out rows from one data frame using another dataframe as a condition for it.</p> <p>df1:</p> <pre><code>system code AIII-01 423 CIII-04 123 LV-02 142 </code></pre> <p>df2:</p> <pre><code>StatusMessage Event 123 Gearbox warm up </code></pre> <p>So for this example I n...
<p>Plug and play script for you. If this doesn't work on your regular code, check to make sure you have the same types in the same columns.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df1 = pd.DataFrame( {&quot;system&quot;: [&quot;AIII&quot;, &quot;CIII&quot;, &quot;LV&quot;], &quot;Co...
python|pandas|dataframe|spyder
2
8,572
67,037,249
What is "DataFrame object has no attribute 'ix'" error?
<p>I am just trying to run a simple code which is:</p> <pre><code>from stocker.stocker import Stocker microsoft = Stocker(ticker='MSFT') techm = Stocker(ticker='TECHM', exchange='NSE') </code></pre> <p>And I get this error: <a href="https://i.stack.imgur.com/sGtEx.png" rel="nofollow noreferrer">Error Snippet</a></p> <p...
<p>Accessing rows in pandas DataFrames using <code>.ix</code> has been deprecated for some time now. Check if your <code>stocker</code> module has more recent versions than the one you have.</p>
python|pandas|dataframe
0
8,573
67,038,186
How can i create a column from 2 related columns of lists in python?
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>sampleID</th> <th>testnames</th> <th>results</th> </tr> </thead> <tbody> <tr> <td>23939332</td> <td>[32131,34343,35566]</td> <td>[NEGATIVE,0.234,3.331]</td> </tr> <tr> <td>32332323</td> <td>[34343,96958,39550,88088]</td> <td>[0,312,0.008,0.1,0.2]<...
<p>Here is a commented solution:</p> <pre class="lang-py prettyprint-override"><code>(df.set_index(['sampleID']) # keep sampleID out of the expansion .apply(pd.Series.explode) # expand testnames and results .reset_index() # reset the index .groupby(['sampleID', 'testnames']) # .first() ...
pandas|dataframe
4
8,574
67,118,189
Unable to load pre-trained model checkpoint with TensorFlow Object Detection API
<p>Similar to this question:</p> <p><a href="https://stackoverflow.com/questions/49507040/where-can-i-find-model-ckpt-in-faster-rcnn-resnet50-coco-model">Where can I find model.ckpt in faster_rcnn_resnet50_coco model?</a> (this solution doesn't work for me)</p> <p>I have downloaded the <code>ssd_resnet152_v1_fpn_1024x1...
<p>Try changing the <code>fine_tune_checkpoint</code> path in the config file to something like <code>path_to_folder/ssd_resnet50_v1_fpn_640x640_coco17_tpu-8/checkpoint/ckpt-0</code></p> <p>And in your training command, set the <code>model_dir</code> flag to just point to the model directory, don't include <code>traini...
python|tensorflow|machine-learning|image-segmentation|object-detection-api
1
8,575
66,842,670
Fix mismatching x-ticks
<p>I currently have two Pandas DataFrames that I would like to layer on top of another.</p> <pre><code># Creating plot fig, ax = plt.subplots(figsize=[16, 9]) ax.scatter(italy_df.columns, italy_df.loc['Record high °C'], label = 'Record high °C', color = '#FF0000') ax.scatter(italy_df.columns, italy_df.loc['Record low...
<p>Found an option to achieve my desired result:</p> <p>Using <code>ax.twiny().twinx()</code> I was able to create a secondary x and y axis, on top of which I started plotting.</p> <pre><code># Creating plot fig, ax = plt.subplots(figsize=[16, 9]) ticks = np.arange(0, 366) plt.xticks(ticks) x = pd.to_datetime(covid_p...
python|pandas|matplotlib
0
8,576
47,192,793
Image manipulation, using openCV and numpy. Trying to return an image without the color red
<p>I am trying to take in a image, checking pixel by pixel if there is any red in it. </p> <p>If there is it'll replace it with white. Once it runs through every pixel, it'll return a new image with white instead of red. </p> <p>The following are my attempts: </p> <pre><code>import cv2 import numpy as np def take_o...
<p>When you have <code>OpenCV</code> or <code>numpy</code> at your service, then you probably don't need to write double iterating <code>for</code> loops which are not clean and inefficient as well. Both the libraries have very efficient routines to iterate a n-D array and apply basic operations such as checking equali...
python|numpy|opencv|image-manipulation
1
8,577
47,395,944
SettingWithCopyWarning & Hidden Chaining
<p>I'm getting the SettingWithCopyWarning that suggests that I may have a chaining problem.</p> <blockquote> <p>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead</p> </blockquote> <p>I've read about this at length,...
<p>Found the answer.</p> <p>In the <code>def</code>, I set <code>X = df[]</code> (a dataframe). If I simply add <code>.copy()</code> to <code>df[]</code>, then the warning goes away.</p> <p>E.g. <code>X = df[['column1', 'column2']].copy()</code></p> <p>Benjamin Pryke's article above is very good...</p>
python|pandas|dataframe
1
8,578
47,292,475
Python inaccurate curve fit
<pre><code>Temp k(T) 298 6.66E-63 300 1.48E-62 350 3.58E-55 400 1.25E-49 450 2.57E-45 500 7.30E-42 550 4.90E-39 600 1.12E-36 650 1.11E-34 700 5.72E-33 750 1.75E-31 800 3.49E-30 850 4.92E-29 900 5.17E-28 950 4.24E-25 1000 2.83E-26 </code></pre> <p>Above is the given kinetic data, I am t...
<p>This is a sensitive problem (as is typical when exponentials are involved). For a problem like this, it is important to have a pretty good initial guess for the parameters.</p> <p>If you experiment with the parameters, you'll find that <code>A</code> has to be very small. The default initial guess that is used by...
python-3.x|pandas|scipy|curve-fitting
3
8,579
68,392,447
How to create n copies of every row on dataframe based value in list Python
<p>I have following dataframe</p> <pre><code>| Domain | Description | test.com | some string ..... </code></pre> <p>I have a text augmentation algorithm which accepts a string as input and returns list with <code>10</code> modified strings. Let's call this function <code>def augmentation(text)</code></p> <p>For ever...
<p>I came up with following</p> <pre><code>df['Description'] = df['Description'].apply(augmentation) result = df.assign(Description=df['Description']).explode('Description').reset_index(drop=True) </code></pre>
python|pandas
0
8,580
1,322,380
gotchas where Numpy differs from straight python?
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For exa...
<p>Because <code>__eq__</code> does not return a bool, using numpy arrays in any kind of containers prevents equality testing without a container-specific work around.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.array(range(3)) &gt;&gt;&gt; b = numpy.array(range(3)) &gt;&gt;&gt; a ...
python|numpy
25
8,581
59,418,746
Pandas convert JSON string to Dataframe - Python
<p>i have a json string that need to be convert to a dataframe with desired column name.</p> <pre><code>my_json = {'2017-01-03': {'open': 214.86, 'high': 220.33, 'low': 210.96, 'close': 216.99, 'volume': 5923254}, '2017-12-29': {'open': 316.18, 'high': 316.41, 'low': 310.0, 'close': 311.35, 'volume': 3...
<p>You can also do it this way to get the exact format:</p> <pre><code>pd.DataFrame(my_json).T.rename_axis(columns='Date') Date open high low close volume 2017-01-03 ...
python|json|pandas
3
8,582
59,141,366
Unable to complete this question due to syntax error in the Python code for tensorflow?
<p>The 'return' is outside the function. I have to return the values in tuples. Basically, there are two errors here. Firstly, the 'return' is outside of the function. Secondly, the result did not return as a tuple.</p> <pre><code>def train_mnist(): class myCallback(tf.keras.callbacks.Callback): def on_epoch_end...
<p>The issue was with the indentation and getting the accuracy from the <code>model log</code>. </p> <p>I have modified your code as below and got the intended output. </p> <pre><code>def train_mnist(): class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs): if logs["...
python|tensorflow|machine-learning|syntax-error
0
8,583
59,156,167
Parallelize in Cython without GIL
<p>I'm trying to compute some columns of a <code>numpy</code> array, operating on python objects (<code>numpy</code> array) in a for loop using a <code>cdef</code> function.</p> <p><strong>I would like to do it in parallel.</strong> But not sure how to. </p> <p>Here is a toy example, one <code>def</code> function cal...
<p>You can pass typed memoryview slices (<code>cdef transpose_vector(DTYPE_t[:] vector)</code>) around without the GIL - it's one of the key advantages of the newer typed memoryview syntax over <code>np.ndarray</code>.</p> <p>However,</p> <ul> <li>You can't call Numpy member functions (like transpose) on memoryviews,...
python|numpy|parallel-processing|cython|hpc
2
8,584
44,917,675
How to delete column name
<p>I want to delete to just column name (x,y,z), and use only data.</p> <pre><code>In [68]: df Out[68]: x y z 0 1 0 1 1 2 0 0 2 2 1 1 3 2 0 1 4 2 1 0 </code></pre> <p>I want to print result to same as below.</p> <pre><code>Out[68]: 0 1 0 1 1 2 0 0 2 2 1 1 3 2 0 1 4 2 1 0 ...
<p>In pandas by default need column names.</p> <p>But if really want <code>'remove'</code> columns what is strongly not recommended, because get duplicated column names is possible assign empty strings:</p> <pre><code>df.columns = [''] * len(df.columns) </code></pre> <hr> <p>But if need write <code>df</code> to fil...
python|pandas
36
8,585
44,957,617
Reshaping pandas dataframe with a column containing lists
<p>Let's say I have a dataframe that looks like this:</p> <pre><code>import pandas as pd data = [{"Name" : "Project A", "Feedback" : ['we should do x', 'went well']}, {"Name" : "Project B", "Feedback" : ['eat pop tarts', 'boo']}, {"Name" : "Project C", "Feedback" : ['bar', 'baz']} ...
<p>One option is to reconstruct the data frame by flattening column <em>Feedback</em> and repeat column <em>Name</em>:</p> <pre><code>pd.DataFrame({ 'Name': df.Name.repeat(df.Feedback.str.len()), 'Feedback': [x for s in df.Feedback for x in s] }) # Feedback Name #0 we should do x P...
python|pandas|nltk
4
8,586
45,225,841
Pandas data slicing by column names
<p>I am learning Pandas and trying to understand slicing. Everything makes sense expect when I try to slice using column names. My data frame looks like this:</p> <pre><code> area pop California 423967 38332521 Florida 170312 19552860 Illinois 149995 12882135 New York 141297 19651127 ...
<p>According to <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#slicing-ranges" rel="nofollow noreferrer">documentation</a></p> <blockquote> <p>With DataFrame, slicing inside of [] <strong>slices the rows</strong>. This is provided largely as a convenience since it is such a common operation.</p>...
python|pandas
6
8,587
45,107,528
Groupby and apply pandas vs dask
<p>there is something that I quite don't understand about <code>dask.dataframe</code> behavior. Let say I want to replicate this from pandas</p> <pre><code>import pandas as pd import dask.dataframe as dd import random s = "abcd" lst = 10*[0]+list(range(1,6)) n = 100 df = pd.DataFrame({"col1": [random.choice(s) for i ...
<p>How about using join?</p> <p>This is your dask code with the exception of naming the Series <code>pd.Series(name='col3')</code></p> <pre><code>def fun2(data): if data["col2"].mean()&gt;1: return 2 else: return 1 ddf = df.copy() ddf.set_index("hash",inplace=True) ddf = dd.from_pandas(ddf, n...
python|pandas|group-by|apply|dask
4
8,588
57,212,688
pandas dataframe - Get value from under certain criteria
<pre><code>print df id product_id product_title search_term relevance 0 2 100001 Simpsom Strong anglebracket 3.00 1 3 100001 Simpsom Strong ibracket 2.50 2 16 100005 Delta Vero rainshowerhead 2.33 </code></pre> <p>Let's say I have id = 3 and want the s...
<p>You are doing it the long way. This works:</p> <pre><code>search_term = df.loc[df['id'] == 3, 'search_term'].iloc[0] </code></pre> <p>Any Series can have 0 to many elements. <code>iloc[0]</code> gets the value of the first element in that series. For production, you should check if the series is empty first.</p>
python|python-3.x|pandas
0
8,589
57,072,953
Apply multiple operations on same columns after groupby
<p>I have the following <code>df</code>,</p> <pre><code>id year_month amount 10 201901 10 10 201901 20 10 201901 30 20 201902 40 20 201902 20 </code></pre> <p>I want to <code>groupby</code> <code>id</code> and <code>year-month</code> and then get the group size ...
<p>Use <code>agg</code>:</p> <pre><code>df.groupby(['id', 'year_month']).agg({'amount': ['count', 'sum']}) amount count sum id year_month 10 201901 3 60 20 201902 2 60 </code></pre> <p>If you want to remove the multi-index, use <a href...
python-3.x|pandas|dataframe|pandas-groupby
5
8,590
57,106,574
Is there a Pandas/Numpy implementation of the Monty Hall problem without looping?
<p>This is more of a curiosity exercise...</p> <p>If you've not heard of the The Monty Hall problem, it's explained in this great <a href="https://www.youtube.com/watch?v=4Lb-6rxZxx0" rel="nofollow noreferrer">youtube video</a>.</p> <p>I simulated it in python using numpy:</p> <pre class="lang-py prettyprint-overrid...
<p>Your biggest issue here is vectorizing <code>choice</code> with a mask. That could look something like:</p> <pre class="lang-py prettyprint-override"><code>def take_masked_along_axis(arr, where, index, axis): """ Take the index'th non-masked element along each 1d slice along axis """ assert where.dtype == b...
python|pandas|numpy
2
8,591
45,805,148
How can I compute model metrics during training with canned estimators?
<p>Using Keras, one typically gets metrics (e.g. accuracy) as part of the progress bar for free. Using the example here:</p> <p><a href="https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py" rel="nofollow noreferrer">https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py</a></p> <p>After r...
<p>accuracy is one of the default metrics in canned classifiers. But it will be calculated by Estimator.evaluate call not by Estimator.train. You can create a for loop to do what you want: for ... estimator.train(training_data) metrics = estimator.evaluate(evaluation_data)</p>
tensorflow
0
8,592
46,095,110
gcloud ml-engine local predict --text-instances fails with "Could not parse" error
<p>I'm trying to make the tensorflow boston sample (<a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/tutorials/input_fn" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/tutorials/input_fn</a>) work on google cloudml and I seem to be su...
<p>There are likely two problems.</p> <p>First, it looks as though the graph that you are exporting is expecting tf.Example protos as input, i.e. has a parse_example(...) op in it. The Boston sample does not appear to be adding that op, so I suspect that is part of your modifications.</p> <p>Before showing the code y...
tensorflow|gcloud|google-cloud-ml-engine
0
8,593
22,980,487
Why is the mean smaller than the minimum and why does this change with 64bit floats?
<p>I have an input array, which is a masked array.<br> When I check the mean, I get a nonsensical number: less than the reported minimum value!</p> <p>So, raw array: <code>numpy.mean(A) &lt; numpy.min(A)</code>. Note <code>A.dtype</code> returns <code>float32</code>.</p> <p>FIX: <code>A3=A.astype(float)</code>. A3 is...
<p>If you're working with large arrays, be aware of potential overflow problems!!<br> Changing from 32-bit to 64-bit floats in this instance avoids an (unflagged as far as I can tell) overflow that lead to the anomalous <code>mean</code> calculation. </p>
python|arrays|numpy|floating-accuracy|floating-point-conversion
0
8,594
35,422,583
Iterate through rows of grouped pandas dataframe to create new columns
<p>I'm new to Python and am trying to get to grips with Pandas for data analysis.</p> <p>I wondered if anyone can help me loop through rows of grouped data in a dataframe to create new variables.</p> <p>Suppose I have a dataframe called data, that looks like this:</p> <pre> +----+-----------+--------+ | ID | YearMon...
<p>I have managed to do this without iterating over each row, as I'm not sure what I was trying to do was possible. I had wanted to set up counters or indicators at group level,as is possible in SAS, and modify these row by row. Eg something like</p> <pre><code>Times3Plus=0 if row['Status'] &gt;= 3: Times3Plus +...
python|pandas
1
8,595
28,840,121
Vectorizing a series of CDF samples in Python with NumPy
<p>I am in the process of writing a basic financial program with Python where daily expenses are read in as a table and are turned into a PDF (Probability Density Function) and eventually a CDF (Cummulative Distribution Function) that ranges from 0 to 1 using the build in histogram capability of NumPy. I am trying to ...
<p>If I understood your example correct, the code creates one interpolation object per random number, which is slow. However, the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow">interp1d</a> can take a vector of values to be interpolated. And the starting zer...
python|numpy|scipy
1
8,596
28,713,281
Binarize data frame values based upon a column value
<p>I have a dataframe that looks like this</p> <pre><code>+---------+-------------+------------+------------+ | hello | val1 | val2 | val3 | +---------+-------------+------------+------------+ | 1.024 | -10.764779 | -8.230176 | -5.689302 | | 16 | -15.772744 | -10.794013 | -5.79148 | |...
<p>It would be quicker to test the entire series against the hello series:</p> <pre><code>In [268]: val_cols = [col for col in df if 'val' in col] for col in val_cols: df[col] = df[col] &gt;= df['hello'] df Out[268]: hello val1 val2 val3 0 1.024 False False False 1 16.000 False False False ...
python|pandas
1
8,597
33,157,297
How can I efficiently translate "terrain" numpy array into networkx graph?
<p>I have a 2d boolean numpy array A. Each element is a pixel of the map with True corresponding to terrain, and False corresponding to water. Say, I want to check how many different continents I have, so I want to use networx.number_connected_components(G)</p> <p>I can build the graph G manually iterating over elemen...
<p>To identify and count the number of connected regions, you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.measurements.label.html" rel="nofollow"><code>scipy.ndimage.measurements.label</code></a> (so you don't need networkx). For example,</p> <pre><code>In [73]: x Out[73]: arra...
python|arrays|numpy|data-structures|graph
2
8,598
33,174,848
pandas - Use datetime.time objects as a dtype
<p>I am reading an Excel file that has the following structure:</p> <pre><code> A B 2015-09-05 15:05:32 2015-09-05 19:05:02 </code></pre> <p>I am reading this file using</p> <pre><code>df = pd.ExcelFile(filename).parse(..) </code></pre> <p>When I look at the <code>dtype</code>, of this...
<p>If you just want to join the two, you could join them as strings:</p> <pre><code>df = pd.DataFrame({ 'A' : ['2015-09-05', '2015-09-05'], 'B': ['15:05:32', '19:05:02']}) pd.to_datetime(df.A + ' ' + df.B) </code></pre> <p>Or you could use datetime to combine:</p> <pre><code>import datetime df.apply(lambda x: datet...
python|datetime|pandas|time-series
0
8,599
66,358,850
Is it possible to vertically stack two panda dataframes while maintaining different column names?
<p>Seems kinda simple but havent been able to find a fix for this idea on Google, YouTube, or Stackoverflow.</p> <p>Essentially if one panda df like this:</p> <pre><code>A | B ----- 45| 98 </code></pre> <p>And then another panda df like this:</p> <pre><code>X | Y ------ 67 | 2 </code></pre> <p>Is there a way to struct...
<p>Dataframe is a table-like data structure. It can have multiple indexes, but what's inside is still something unified, meaning that viewing it as just 2 different tables with individual headers is contrary to the idea of what it is.</p> <p>That said, you can make an new upper row filled with NaNs, then make the next ...
python|pandas
0