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
13,400
72,043,288
Add total values of categories on top of relative abundance bars, Python
<p>I am working with a relative abundance plot like this: <a href="https://i.stack.imgur.com/Xqzbu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xqzbu.png" alt="Image, relative abundance plot" /></a></p> <p>But need help with displaying the total amount of the values of the categories on top of eac...
<p>The total value is obtained before calculating the relative values of the data frames. Annotate with a list of those total values and a list of the retrieved labels for the x-axis of the graph. The coordinate basis for the annotation is data-based.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt ...
python|pandas|matplotlib
1
13,401
47,298,293
Accessing Tasmanian Sparse Grid from python using PyUblas, Boost.Python and py_tsg. Type mismatch in arguments for make_global_grid
<p>I'm using <a href="http://rncarpio.github.io/py_tsg/" rel="nofollow noreferrer">py_tsg</a> to call the sparse grid generator, Tasmanian (written in C++) from Python. The py_tsg website indicates I need PyUblas and Boost.Python as prequisites. I've got that all setup and am running the first example problem given t...
<p>I discovered that Tasmanian provides a Python wrapper to their C++ library in versions 4.0 or later. If you are running into a similar problem, check the Tasmanian documentation and use TSG 4.0 or later...</p>
python|c++|numpy|boost
0
13,402
68,129,728
For loop KeyError: 4675 when making corpus from Pandas dataframe
<p>I've tried to make corpus from Pandas dataframe (with shape (14454, 9)). However, whenever the range exceeds 10k, the for loop return KeyError: 4675 , yet works well for 10k below.</p> <pre><code># getting the entire text # this works fine corpus=&quot; &quot; for i in range(0,998): corpus= corpus+ ' ' + df[&qu...
<p>Just need to use iloc function</p> <pre><code>#getting the entire resume text corpus=&quot; &quot; for i in range(0,14454): corpus= corpus+ ' ' + df[&quot;Cleaned_Resume&quot;].iloc[i] </code></pre> <p>sr for my newbie but still keep as someone might need it</p>
pandas|dataframe|keyerror|corpus
0
13,403
68,256,650
Load xls files with pandas is failed
<p>I am trying to load an xls file with pandas using:</p> <pre><code>pd.read_excel(fi_name, sheet_name=None, engine=None) </code></pre> <p>But i get this error:</p> <pre><code>&quot;XLRDError: Workbook is encrypted&quot; </code></pre> <p>But file is not encrypted, i can open it with excel, and read file's text with tik...
<p>I guess ,I found something for your problem:</p> <pre class="lang-py prettyprint-override"><code>import msoffcrypto file = msoffcrypto.OfficeFile (open ('encrypted.xls', 'rb')) # read the original file file.load_key (password = 'VelvetSweatshop') # Fill in the password, if it can be opened directly, the default pas...
python|excel|pandas|xlrd|apache-tika
2
13,404
56,961,855
Numpy: Setting n last elements of mantissas in double array
<p><strong>Question</strong></p> <p>Suppose we are given a numpy array <code>arr</code> of doubles and a small positive integer <code>n</code>. I am looking for an efficient way to set the <code>n</code> least significant entries of each element of <code>arr</code> to <code>0</code> or to <code>1</code>. Is there a <c...
<p><em>"I am looking for an efficient way to set the n least significant entries of each element of arr to 0 or to 1."</em></p> <p>You can create a view of the array with data type <code>numpy.uint64</code>, and then manipulate the bits in that view as needed.</p> <p>For example, I'll set the lowest 21 bits in the ma...
python|numpy|floating-point|rounding
2
13,405
45,950,264
Reshape array in squares like an image
<p>I would like to reshape an array in python (a numpy array at first) in a way that each element at the first index becomes a square/quadrant in that array, not the regular reshaping that takes all elements in a row.</p> <p>It's a reshape + reorganize.</p> <p>And of course, the fastest/better way of doing it :)</p> <p...
<p>You need <code>reshape</code> + <code>transpose/swapaxes</code> + <code>reshape</code>:</p> <pre><code>X.reshape(4,2,3,2,3).swapaxes(1,2).reshape(12,2,2,3) </code></pre> <p>gives:</p> <pre><code>array([[[[ 111., 112., 113.], [ 121., 122., 123.]], [[ 211., 212., 213.], [ 221., 222...
python|sorting|numpy|image-processing|reshape
2
13,406
50,890,074
Replace value in dataframe column, if other 'better' value exists elsewhere
<p>I have a dataframe structured roughly as follows (it's a list of event participants; the pool is small enough that we can assume that a repeating value refers to the same person):</p> <pre><code>id_1 id_2 id_3 ... year name country 1_c 2_a 3_a 2011 John France 1_b 2_a 3_c 2010 Jill UK 1_c 2_...
<p>One <em>non-vectorised</em> solution is possible via <a href="http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>pd.DataFrame.apply</code></a>. This is just a thinly veiled loop. We cycle through each row. If the country is unknown we:</p> <ul> <...
python|python-2.7|pandas|dataframe
2
13,407
66,603,925
standardize company names in pandas dynamically
<p>i have a dataframe with company names</p> <p>df:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>company_name</th> </tr> </thead> <tbody> <tr> <td>abc Inc</td> </tr> <tr> <td>abc Inc Bolingbrook</td> </tr> <tr> <td>enterprise badh Shah</td> </tr> <tr> <td>enterprise Financial</td> </tr> ...
<p>Firstly create a function that do this for you:-</p> <pre><code>def func(val): val=val.split(' ',2) if len(val)==1: return val[0] else: return ' '.join([val[0],val[1]]) </code></pre> <p>Now just make use of <code>apply()</code> method:-</p> <pre><code>df['standardized_company_name']=df['c...
python-3.x|pandas|text-processing|fuzzywuzzy
2
13,408
66,403,564
Add many 1-D array to dataframe as a row?
<p>I am new to python and I want to know how to add many 1-D array to dataframe as a row. I have look into the previous question <a href="https://stackoverflow.com/questions/58292901/add-a-1-d-numpy-array-to-dataframe-as-a-row">here</a> but it is a bit different in my case. Here is the code:</p> <pre><code>df = pd.Data...
<p>You need to reassign <code>df</code>:</p> <p>this:</p> <pre class="lang-py prettyprint-override"><code>df = df.append(pd.DataFrame(arr.reshape(1,-1), columns=list(df)), ignore_index=True) </code></pre> <p>The complete code then becomes:</p> <pre class="lang-py prettyprint-override"><code...
python|arrays|pandas|dataframe|numpy
1
13,409
57,327,752
How to correctly group columns?
<p>I have a Data Frame with this columns:</p> <pre><code>DF.head(): Email Month Year abc@Mail.com 1 2018 abb@Mail.com 1 2018 abd@Mail.com 2 2019 . . abbb@Mail.com 6 2019 </code></pre> <p>What I want to do is to get the total of email adresses in each mo...
<p>It depends what need.</p> <p>If need exclude missing values or missing values not exist in <code>Email</code> column, your solution is right, use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.count.html" rel="nofollow noreferrer"><code>GroupBy.count</code></a>:</p> ...
python|pandas|dataframe|group-by|multiple-columns
3
13,410
57,379,734
Dask dataframe apply giving unexpected results when passing local variables as argument
<p>When calling the <code>apply</code> method of a dask <code>DataFrame</code> inside a for loop where I use the iterator variable as an argument to <code>apply</code>, I get unexpected results when performing the calculation later. This example shows the behavior:</p> <pre class="lang-py prettyprint-override"><code>i...
<p>This turns out to be a duplicate after all, see <a href="https://stackoverflow.com/questions/46720983/incompatibility-of-apply-in-dask-and-pandas-dataframes">question on stackoverlow</a> including another work-around. A more detailed explanation of the behavior can be found in the corresponding <a href="https://gith...
python|pandas|scope|apply|dask
1
13,411
57,719,942
What's the problem of 'error code 3221225501' during running tensorflow codes
<p>I try to run the keras codes with tensorflow backend. But it caused "ImportError: DLL load failed with error code 3221225501". It seems not sloved by others..</p> <p>I just install python 3.7.4 in CPU enviroment and install the tensorflow with edition:tensorflow-1.13.1-cp37-cp37m-win_amd64.whl. And it is sucessful...
<p>Please check if your CPU supports AVX Instructions. </p> <p>If it does not support AVX instructions, then you should use TF version 1.5 or earlier versions. </p> <p>From TF 1.6 and above, TF binaries uses AVX instructions. </p> <p>Please refer to below link for more information. </p> <p><a href="https://stackove...
python|tensorflow|keras
0
13,412
73,040,053
How to apply sentiment analysis model on text column all at once in a dataframe?
<p>I am using <a href="https://huggingface.co/oliverguhr/german-sentiment-bert" rel="nofollow noreferrer">germansentiment</a> to test the sentiments of german tweets (text) in a dataframe (df).</p> <p>I am using the following code to do so:</p> <pre><code>from germansentiment import SentimentModel model = SentimentMode...
<p>You could check if all your tweets are unique. If they are not, I would suggest to encode only the unique ones and use this as a lookup table to fill your dataframe.</p> <p>Otherwise you could also use a <code>lambda</code> instead of your <code>for loop</code>. Depending on the use case, it can be quicker.</p> <p>I...
python|pandas
1
13,413
51,546,415
Replace value in one dataframe with value in another if three columns match
<p>I have two data arrays as seen below. </p> <p>I need to look at only A and B values and match the f_code (F in Data2) and b_ID (B in Data2). If they match, I replace the 'value' in Data1 with the A or B value for that row in Data2. So I want to end up with a new Data1 with the 'value' column reflecting the numbers ...
<p>Clean your second <code>DataFrame</code> a bit, that way you can then merge them together and replace the Value column when those three columns match. The important step here is <code>.stack()</code> which will make it so that a row in <code>df2</code> represents a distinct <code>Species, Facility, Boiler</code> com...
python|pandas|find|compare
1
13,414
71,008,288
How can I fill a column with values that are computed between two dates in pandas, with a delay of one row, if I have repeating dates?
<p>I have this dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Position</th> <th>TrainerID</th> </tr> </thead> <tbody> <tr> <td>2017-09-03</td> <td>4</td> <td>1788</td> </tr> <tr> <td>2017-09-16</td> <td>5</td> <td>1788</td> </tr> <tr> <td>2017-10-14</td> <td>1</td>...
<p>You could use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer"><code>rolling</code></a> with the Date index a datetime:</p> <pre><code>df['Date'] = pd.to_datetime(df['Date']) df['Win%'] = ( df.set_index('Date') .rolling('1000d') # last 1000 days [...
python|pandas
1
13,415
51,758,770
add an op tensorflow debugging
<p>I would like to know how you can print out the values of the input tensor when adding a new op to tensorflow for debugging purposes. I have been following the tutorial with cuda_op_kernel.cc as follows:</p> <pre><code>#include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #includ...
<p>I figured out why. Input.data() is a pointer onto address in the GPU. The stream executor has evidently already put it there. Attempting to dereference on CPU is bad. </p>
c++|tensorflow
0
13,416
35,976,556
Numpy percentages along axis in 2d array
<p>I have a matrix of counts, </p> <pre><code>import numpy as np x = np.array([[ 1,2,3],[1,4,6],[2,3,7]]) </code></pre> <p>And I need the percentages of the total along axis = 1: </p> <pre><code>for i in range(x.shape[0]): for j in range(x.shape[1]): x[i,j] = x[i,j] / np.sum(x[i,:]) </code></pre> <p>In ...
<pre><code>x /= x.sum(axis=1, keepdims=True) </code></pre> <p>Altough <code>x</code> should have a floating point dtype for this to work correctly. </p> <p>Better may be:</p> <pre><code>x = np.true_divide(x, x.sum(axis=1, keepdims=True)) </code></pre>
python|arrays|numpy
12
13,417
36,062,713
How to plot a deadband for a simple sine wave using python
<p>I am using the below codes so as to plot the dead band for a sine wave so that the dead band appears on the x axis as y=0. The output is minimized by the value of upper limit[y-0.5] and the lower limit.The dead band needs to be displayed here.Could any one help me in this. </p> <pre><code>import matplotlib.pyplot a...
<p>I guess you should work with vectorized values, so try this</p> <pre><code>import matplotlib.pyplot as plt import numpy as np LL = -0.5 UL = 0.5 x=np.linspace(-20,20,100) y=np.sin(x) # plot original sine plt.plot(x,y) # zero output value for the dead zone y[(y&gt;=LL) &amp; (y&lt;=UL)] = 0 y[y&gt;UL] -= UL y[...
python|numpy|matplotlib
1
13,418
37,402,773
Tensorflow importing issue mac
<p>I followed the instruction as </p> <pre><code> https://www.tensorflow.org/versions/r0.8/get_started/os_setup.html#on-macosx </code></pre> <p>for mac installation. </p> <p>After installation I navigate to python and tried to import Tensorflow and got following problems. </p> <pre><code> (...
<p>This seems to be an issue with pyenv. Following <a href="https://github.com/python-pillow/Pillow/issues/1753#issuecomment-195987865" rel="nofollow noreferrer">these instructions</a> should clear things up.</p> <blockquote> <p>Reverting the change to pyenv will get existing built extension modules working again, but ...
python|macos|tensorflow|deep-learning
2
13,419
37,553,651
plotting multiple pandas series with different length in one chart
<p>I have 10 Panda Series in all with different length, now I want to plot all 10 as box-plots in one chart where x-axis shows the series name.</p> <p>This would be a standard operation as described <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html" rel="nofollow">here</a> if all series had the s...
<p>The differing length series will not be a problem. Pandas will automatically fill in the missing values with NA.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd np.random.seed(100) s1 = pd.Series(np.random.randn(5)) s2 = pd.Series(np.random.randn(10)) s3 = pd.Series(np.random....
python|pandas
7
13,420
37,318,554
Python pandas tensor access is extremely slow
<p>I am creating a huge tensor with millions of <em>word triples</em> and their counts. For example, a <em>word triple</em> is a <code>(word0, link, word1)</code>. These word triples are collected in a single dictionary where values are their respective counts, e.g. <code>(word0, link, word1): 15</code>. Imagine I have...
<p>Please, check my solution - I optimized something in calculations (hope without mistakes :))</p> <pre><code># sample of data df = pd.DataFrame({'word0': list('aabb'), 'link': list('llll'), 'word1': list('cdcd'),'counts': [10, 20, 30, 40]}) # caching total count total_cnt = df['counts'].sum() # two series with sum...
python|pandas
2
13,421
41,705,764
numpy.sum() giving strange results on large arrays
<p>I seem to have found a pitfall with using <code>.sum()</code> on <code>numpy</code> arrays but I'm unable to find an explanation. Essentially, if I try to sum a large array then I start getting nonsensical answers but this happens <em>silently</em> and I can't make sense of the output well enough to Google the cause...
<p>On Windows (on 64-bit system too) the default integer NumPy uses if you convert from Python ints is 32-bit. On Linux and Mac it is 64-bit.</p> <p>Specify a 64-bit integer and it will work:</p> <pre><code>d = np.arange(200000, dtype=np.int64).sum() print('d is {}'.format(d)) </code></pre> <p>Output:</p> <pre><cod...
python|python-2.7|numpy
6
13,422
41,962,022
Apply function to dataframe column element based on value in other column for same row?
<p>I have a dataframe:</p> <pre><code>df = pd.DataFrame( {'number': ['10', '20' , '30', '40'], 'condition': ['A', 'B', 'A', 'B']}) df = number condition 0 10 A 1 20 B 2 30 A 3 40 B </code></pre> <p>I want to apply a function to each element within the number co...
<p>As the question was in regard to the <strong>apply</strong> function to a dataframe column for the same row, it seems more accurate to use the pandas <code>apply</code> funtion in combination with <code>lambda</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'number': [10, 20 , 30, 40], 'condition': ['...
python|pandas|numpy
13
13,423
42,073,861
Why the matrix inversion function in numpy and scipy returns different results with big quadratic matrices?
<p>Lets say I define a big quadratic matrix (e.g. <strong>150x150</strong>). One time it is a numpy array (matrix <strong>A</strong>), one time it is a scipy sparse array (matrix <strong>B</strong>).</p> <pre><code>import numpy as np import scipy as sp from scipy.sparse.linalg import spsolve size = 150 A = np.zeros(...
<p>The answer to your headline question is: Because of your unfortunate choice of example matrices. Let me elaborate.</p> <p>Machine precision is limited, therefore floating point arithmetic will rarely be 100% accurate. Just try</p> <pre><code>&gt;&gt;&gt; np.linspace(0, 0.9, 10)[1:] == np.linspace(0.1, 1, 10)[:-1] ...
python|numpy|matrix|matrix-inverse
2
13,424
8,183,239
Better way to find existence of arrays in list of arrays
<p>I am a newbie to Python and trying out different ways to optimize and simplify my code.</p> <p>I have a list of arrays(necessarily in this format) initially empty, which I need to update with arrays, making sure that duplicate entries are not added.</p> <p>Right now I am doing it the following way, which is the on...
<blockquote> <p><strong>Edit:</strong> I see from your comment that you're using numpy arrays. I've never used numpy so I have no idea how they work with sets.</p> </blockquote> <p>One option would be to use a <code>set</code>. <a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset" rel="nofo...
python|optimization|numpy|arraylist|unique
1
13,425
37,977,118
Pandas: Set first 2 hours of every group to NaN
<p>I am trying to clean my data by setting 'value' to NaN for the first 2 hours of every 'state' group.</p> <p>My dataframe looks like this:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; rng = pd.date_range('1/1/2016', periods=6, freq='H') &gt;&gt;&gt; &gt...
<p>Find all <code>indexes</code> by first <code>2H</code>, then change <code>index</code> to <code>Multiindex</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.swaplevel.html" rel="nofollow"><code>swaplevel</code></a> for matching <a href="http://pandas.pydata.org/pandas-docs/stabl...
python|python-3.x|pandas|indexing
1
13,426
37,958,706
In Tensorflow, what is the difference between a tensor that has a type ending in _ref and a tensor that does not?
<p>The docs say:</p> <blockquote> <p>In addition, variants of these types with the _ref suffix are defined for reference-typed tensors.</p> </blockquote> <p>What exactly does this mean? What are reference-typed tensors and how do they differ from standard ones?</p>
<p>A reference-typed tensor is <strong>mutable</strong>. The most common way to create a reference-typed tensor is to define a <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/state_ops.html#Variable" rel="noreferrer"><code>tf.Variable</code></a>: defining a <code>tf.Variable</code> whose initial value...
tensorflow
16
13,427
31,243,002
Higher order local interpolation of implicit curves in Python
<p>Given a set of points describing some trajectory in the 2D plane, I would like to provide a smooth representation of this trajectory with local high order interpolation. </p> <p>For instance, say we define a circle in 2D with 11 points in the figure below. I would like to add points in between each consecutive pair...
<p>This is called parametric interpolation.</p> <p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splprep.html" rel="nofollow noreferrer">scipy.interpolate.splprep</a> provides spline approximations for such curves. This assumes you know the <em>order</em> in which the points are on the...
python|numpy|scipy|gis|interpolation
5
13,428
64,508,786
Reorganizing pandas dataframe turning Column into new Header, Original Header to be part of multiindex with a prexisting Column
<p>I have been tasked with reorganizing a fairly large data set for analysis. I want to make a dataframe where each employee has a list of Stats associated with their Employee Number ordered based on how many periods they have been with the company. The data does not go all the way back to the start of the company so s...
<ol> <li>You can <code>.melt</code> and then <code>.unstack</code> the dataframe.</li> <li>Finish up up with some multiindex column clean up using <code>.droplevel</code> and passing <code>axis=1</code> to drop unnecessary levels on columns rather than the default <code>axis=0</code>, which would drop index columns. Yo...
python|pandas|dataframe|merge|pivot
3
13,429
64,473,124
Getting unique values and casting to a string
<p>How would I get the unique non-null values for the below data frame and cast it to a string? For example:</p> <pre><code>import pandas as pd df=pd.DataFrame([{'id': 1, 'language': 'en'}, {'id': 1}, {'id': 1, 'language': 'fr'}, {'id': 1, 'language': 'en'}]) </code></pre> <p>I want to get:</p> <pre><code> subs 1...
<pre><code>df.dropna().groupby('id')['language'].unique().reset_index().rename(columns={'language':'subs'}) </code></pre> <p>Desired result</p> <pre><code> id subs 0 1 [en, fr] </code></pre>
python|pandas
1
13,430
47,659,354
How to read .mod files using Python
<p>I have a file with extension <strong>.mod.</strong> That file contains fields and data under each field, just like every csv files do. I need to read this .mod file using Python.</p> <p>Please suggest me a way out in Python using Pandas or any other package that could help me with this.</p> <p>Thanks!</p>
<p>On Windows 10, using Python 3.6, I could successfully open the file and read the first line:</p> <pre><code>with open('09nested.mod') as f: print(f.readlines()[0]) // File: 09nested.mod &gt;&gt;&gt; </code></pre>
python|pandas|file-io
1
13,431
58,863,272
Making comparison between dataframe rows for dropping
<p>In my dataframe, I have a type of data that can be seen below:</p> <pre><code>product_no part_no level 1 1_1 1 1 1_2 1 1 1_3 2 1 1_4 1 1 1_5 1 1 1_6 2 1 1_7 1 2 ...
<p>EDIT: After @ALollz answer it made me remember the pandas <code>.shift()</code> function, so you can do this all from your DataFrame. Pandas works faster if you think of working with columns than rows.</p> <pre><code>## Create Dummy data and dataframe level=[1, 1, 2, 1, 1, 1, 2] part_no=['1_1', '1_2', '1_3', '2_1',...
python|pandas|dataframe
3
13,432
58,650,334
How to filter an array of object in Python?
<p>I have a collection called project, this collection contain different documents, and every document contain an array of object called data. </p> <p><a href="https://i.stack.imgur.com/7OwY8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7OwY8.png" alt="enter image description here"></a></p> <p>I want to ...
<p>There's no code here, so I have to make some guesses:</p> <ul> <li>I'm going to assume all your data is already in its own array, extracted from whatever form it originally came in. If it needed to be collected from multiple documents, I assume that's already done </li> <li>I assume each object has a key "projectA...
python|pandas|mongodb
4
13,433
58,797,656
I want to count the Specific number in each column in Pandas DataFrame?
<p>I want to count the number of times either of the specific values <strong>4</strong> &amp; <strong>5</strong> appear in each column of a pandas DataFrame, proportionately.</p> <p><strong>Given this dataframe as input:</strong></p> <pre><code>| A | B | C | D | E | |---|---|---|---|---| | 3 | 3 | 1 | 2 | 1 | | 5 | 5...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html" rel="nofollow noreferrer"><code>DataFrame.isin</code></a> for get mask, for count values use <code>sum</code> and for ratio use <code>mean</code>, last for one row DataFrame add <a href="http://pandas.pydata.org/pandas...
python|pandas|count
3
13,434
70,205,779
Uploading 2 individual files via Flask for Python Processing
<p>started playing with Flask and am looking to convert a few easy python scripts to be able to run through a web interface. Mostly data tweaking tools.</p> <p>So, most of the tools that I have running through the command line use 2 spreadsheets and then perform operations between them using pandas (look for difference...
<p>After doing some research and going over the code I managed to make it work by adding an additional request.files for the additional file name.</p> <p>I still have to incorporate what to do with the files, as this code is basically from the flask upload tutorial - but here is what is working now.</p> <p>py file</p> ...
python|pandas|flask
1
13,435
70,367,854
save dataframe containing lists as csv file
<p>I have created DataFrame as the following</p> <pre><code>df = pd.DataFrame({'name': imgname, 'pose': pose}) </code></pre> <p>where imgname is a list of string such as ['image1','image2' ...] the pose is a list of list such as pose = [array([ 55.77614093, 8.45208199, 2.69841043, 2.17110961]), array([ 66.6123621...
<p>For <code>pose</code>, you probably do not mean <code>array</code>s as list of list. Your code would work if you remove the <code>array</code> part -</p> <pre><code>import pandas as pd imgname = ['image1','image2'] pose = [[ 55.77614093, 8.45208199, 2.69841043, 2.17110961],[6.61236215, 5.87653161, -31.70704038,...
python|pandas|export-to-csv
0
13,436
70,121,863
Condition is ignored using .where() in Pandas
<p>I'm trying to calculate the Bonus Pay given to our Courier's based on their <code>Success Rate</code> which is based off the number of <code>Eligible</code> orders they've successfully delivered.</p> <p>Here's my code:</p> <pre><code>from openpyxl import load_workbook import pandas as pd df = pd.read_excel(r'path\f...
<p>Is the problem with the order of .mul and .where?</p> <p>This worked when I tried to reproduce:</p> <p><code>df['Bonus'] = df['Eligible'].where(df['Success Rate'] &gt;= 95).mul(1.2)</code></p>
python|pandas
1
13,437
70,054,689
Fix CNN overfitting
<p>I'm using the CNN and MobileNet models to build a model to classify sign language to alphabet letters based on an images data set. So, it is a multi-class classification model. However, after compiling and fitting the model. I got a high accuracy (98%). But when I want to visualize the confusion matrix I got really ...
<p>there is some tricks to help with orver fitting problem:</p> <ol> <li>Adding <a href="https://www.tensorflow.org/tutorials/images/data_augmentation" rel="nofollow noreferrer">data augmentation</a>, this method will slightly transform each time the input with rotation, random croping, etc. and the model will see more...
tensorflow|machine-learning|keras|deep-learning|conv-neural-network
2
13,438
56,060,841
How to get only required columns in Python script while parsing the data from Json File
<p>I am trying to write a python script . As per the requirement I have around 400 columns which will be coming as per of multiple arrays in JSON file.</p> <p>I am using Pandas library and python version 3.6. I may get more columns than 400 column from the JSON file. How can i restrict the unwanted columns and I want ...
<p>there is a way to read specific columns from csv using pandas :</p> <pre><code>import pandas as pd cols= ['col1', 'col2', 'col3'] df = pd.read_csv('JsonFile.csv', skipinitialspace=True, usecols=cols) #save to output df.to_csv('output.csv',Index=False) </code></pre> <p>or you could specify the columns when you ar...
python|arrays|json|pandas|dataframe
0
13,439
56,403,627
In pytorch, how to fill a tensor with another tensor?
<p>I'm looking for a way to expand the size of an image by adding 0 values to the right &amp; lower edges of it. My initial plan is to use nn.padding to add the edge, until I encounter this error:</p> <pre><code> File "/home/shared/virtualenv/dl-torch/lib/python3.7/site-packages/torch/nn/functional.py", line 2796, in...
<p>the only way I know is:</p> <pre><code>with torch.no_grad(): # assuming it's for init val = torch.distributions.MultivariateNormal(loc=zeros(2), scale=torch.eye(2)) w.data = val </code></pre> <p>but I doubt it's recommended.</p> <p>Answering the <strong>title</strong> of the question.</p>
pytorch|tensor
1
13,440
56,403,699
How to create a tuple of corresponding elements of a 2D numpy array in an efficient way
<p>I have two 2D numpy arrays, one for latitude, another for longitude.</p> <pre><code>a = [ [1, 2, 3, 4], b = [ [a, b, c, d], [1, 2, 3, 4], [a, b, c, d], [1, 2, 3, 4], [a, b, c, d], [1, 2, 3, 4] ] [a, b, c, d] ] </c...
<p>solution without numpy</p> <pre><code>from itertools import chain output2 = [list(zip(i,j)) for i,j in zip(a,zip(*b))] output1 = list(chain.from_iterable(output2)) </code></pre>
python|numpy
2
13,441
55,596,244
Replace the values in the column with the results
<p>I want to replace the values from the column in a dataset with the results for the values in the column. Example: My data set has</p> <pre><code>id tslot A 1 2014-11-02 22:45:00 89 1 2014-10-26 09:15:00 762 1 2014-10-26 11:00:00 25 1 2014-10-26 11:15:00 762 1 2014-10-26 12...
<p>Define the function to be run on column-<code>A</code></p> <p>Then use <code>apply</code> method to apply it to entire column using a lambda function.</p> <p>Example:</p> <pre><code>def your_function(x): # x is individual value from desired column # operate on x here. For eg. square(x) return x**2 df...
python|pandas
0
13,442
64,791,159
Why is pandas ewm passed with times so slow?
<p>Suppose I have the following data:</p> <pre><code>import pandas as pd import numpy as np import datetime as dt idx = pd.date_range(&quot;2010/01/01&quot;, &quot;2020/01/01&quot;, freq='1T') n = len(idx) data = pd.DataFrame({'A': np.random.random(n), 'B': np.random.random(n), 'C': np.random.random(n)}, index=idx) <...
<p>I have noted the same thing, don't know why. The timedelta method is about 4000 times slower on my laptop. The two methods will not produce the same result if the time steps are not uniform though, see below</p> <pre class="lang-python prettyprint-override"><code>import pandas as pd import numpy as np import datetim...
python|pandas|numpy|moving-average
0
13,443
39,694,324
Does TensorFlow support binary/boolean tensors with type: 1 bit?
<p>Does TensorFlow support boolean tensors where every element occupies just 1 bit (not 8) ? Can I define large tensors ~100 MB ?</p> <p>Where can I read about it ?</p> <p>Couldn't find anything searching on Internet, thats why I'm asking.</p>
<p>Tensorflow DT_BOOL tensors map to the underlying C++ bool type, which does not take 1 bit of memory.</p> <p>You can implement your own operations on a Variant dtype, but it requires quite a bit of C++ coding.</p>
machine-learning|binary|boolean|tensorflow|bit
1
13,444
39,479,185
pandas - Changing the format of a data frame
<p>I have a data frame which is of the format:</p> <pre><code>level_0 level_1 counts 0 back not_share 1183 1 back share 1154 2 back total 2337 3 front not_share 697 4 front share 1073 5 front total 1770 6 left not_share 4819 7 left share 5097 8 left total 991...
<p>Use <code>groupby</code> and <code>sum</code></p> <pre><code>df.groupby(['level_0', 'level_1']).counts.sum().unstack() </code></pre> <p><a href="https://i.stack.imgur.com/IeXuV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IeXuV.png" alt="enter image description here"></a></p>
python|pandas|dataframe|pivot
4
13,445
39,474,936
How to convert the data as following in python?
<p>I have some data in the following format in a csv file.</p> <pre><code> Id Category 1 A 2 B 3 C 4 B 5 C 6 d </code></pre> <p>I'd like to convert it into the below format and save it another csv file</p> <pre><code>Id A B C D E 1 1 0 0 0 0 2 0 1 0 ...
<p>Try with <code>pd.get_dummies()</code></p> <pre><code>&gt;&gt; df = pd.read_csv(&lt;path_to_file&gt;, sep=',', encoding='utf-8', header=0) &gt;&gt; df Id Category 0 1 A 1 2 B 2 3 C 3 4 B 4 5 C 5 6 d &gt;&gt; pd.get_dummies(df.Category) </code>...
python|python-3.x|pandas|text-processing|spyder
2
13,446
44,341,430
Number of features of the model must match the input. Model n_features is 20 and input n_features is 4
<p><a href="https://i.stack.imgur.com/RmBat.png" rel="nofollow noreferrer">enter image description here</a>I am getting this error while I'm using random forest classifier. Here is my code:</p> <pre><code>import quandl, math import numpy as np import pandas as pd import matplotlib.pyplot as plt from ma...
<p>Use the same trained vectorizer for both train and test data. In the second time if you again fit the data then it will turn it into a vector based on only this new data.</p> <pre><code>X1 = vectorizer.fit_transform(train['question']) t1= vectorizer.transform(corpus) </code></pre>
python|machine-learning|scikit-learn|random-forest|sklearn-pandas
0
13,447
44,231,072
Possible tensorflow cholesky_solve inconsistency?
<p>I am trying to solve a linear system of equations using <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/math_ops/matrix_math_functions#cholesky_solve" rel="nofollow noreferrer">tensorflow.cholesky_solve</a> and I'm getting some unexpected results.</p> <p>I wrote a script to compare the output of ...
<p>I think it's a bug. Notice how the result doesn't even depend on the <code>RHS</code>, unless <code>RHS = 0</code>, in which case you get <code>nan</code> instead of <code>0</code>. Please report it on GitHub.</p>
tensorflow|linear-algebra|matrix-inverse
1
13,448
44,267,025
Using XGBoost to predict importance or percentage based on inputs
<p>I am working on interpreting my XGBoost model. Take for example, the two datasets <code>trainInput</code> and <code>trainOutput</code> below, respectively:</p> <pre><code>df.trainInputs input1 input2 input3 0 1 0 0 1 1 1 0 2 0 1 1 .. df.trainOutputs output 0 ...
<p>If you want to get the result probability (percentage score for each element), use <code>predict_proba</code> instead of <code>predict</code>.</p>
python|pandas|machine-learning|xgboost
4
13,449
44,305,253
How to fix AttributeError: 'DataFrame' object has no attribute 'assign' with out updating Pandas?
<p>I am trying merge multiple files based on a key ('r_id') and rename the column names in the output with the name of the files. I could able to do every thing except renaming the output with the file names. I have the following error probably caused by the old version of Pandas. Does any one know how to fix this wit...
<p>You need change <code>exp</code> as column name for rename:</p> <pre><code>def merge_files(files, **kwargs): dfs = [] for f in files: dfs.append( pd.read_csv(f, sep='\t', usecols=['r_id', 'exp'], index_col=['r_id']) .rename(columns={'exp':os.path.splitext(os.path.basename(f...
pandas|merge|concat
2
13,450
69,658,244
Converting DataFrame XYZ to Geopandas LineString
<p>I have DataFrame as shown below</p> <pre><code>gdf = gpd.GeoDataFrame(geo_df, geometry=gpd.points_from_xy(geo_df.x.astype(float),geo_df.y.astype(float))) x y z station geometry 651669.5725 4767831.32 -74.46883723 Loc1 POINT (651669.5725 4767831.32) 651529.8717 47678...
<ul> <li>your sample data does not contain <strong>lomdrivename</strong> so have used <strong>station</strong></li> <li>almost same technique as your code, using <strong>geometry</strong> of 3D points to generate LINESTRING</li> <li>output shows this has worked by showing both lines and individual line</li> </ul> <pre>...
geopandas|shapely
1
13,451
69,445,027
Iteratively merge panda columns with new column names
<p>Assume I am merging a panda data frame iteratively in a loop but after two or three iterations panda repeat the column name for example consider the following example where I am merging the columns iteratively but without loop for simplicity:</p> <pre><code>A= {'Name':['A','B','C'],'GPA':[4.0,3.80,3.70], 'School':['...
<p>Try changing the <code>suffixes</code> argument to a tuple of <code>('_z', '_t')</code>:</p> <pre><code>B = pd.merge(comb, comb, on=['Name','GPA']) C = pd.merge(B, comb, on=['Name','GPA']) D = pd.merge(C, comb, on=['Name','GPA'], suffixes=('_z', '_t')) </code></pre> <hr /> <pre><code>&gt;&gt;&gt; D Name GPA Schoo...
python|pandas|loops|merge
1
13,452
69,520,967
how to get the slope of multiple columns in Python data frame
<p>I have the below data frame that carries 4 columns of scores. how do I find the slope of these 4 scores for each individual ID in my data frame?</p> <pre><code>ID t1 t2 t3 t4 a 1 2 3 4 b 3 2 1 c 4 2 1 2 d 2 3 4 5 e 0 2 3 4 </code></pre> <p>I would like the slope be appen...
<p>you can use <code>sklearn</code> (or probably <code>scipy</code>) for this. Example:</p> <pre><code>import sklearn model = sklearn.linear_model.LinearRegression() def get_coeff(row, model=model): # fit a row assuming points are separated by unit length and return the slope. row = row.copy().dropna() ...
python|pandas
0
13,453
69,572,576
Pandas - numpy and multiple conditions
<p>I am not too good about that yet but I dont know how to make this work:</p> <pre><code># Import pandas library import pandas as pd import numpy as np # initialize list of lists data = [[1, 0], [4, 0], [8, 0]] # Create the pandas DataFrame df = pd.DataFrame(data, columns=['Value', 'Test']) df['Test'] = np.where(df['...
<p>OK, i was missing brackets ... should be like this:</p> <pre><code>df['Test'] = np.where((df['Value'].astype(int) &gt;= 3) &amp; (df['Value'].astype(int) &lt;= 7), 1, 2) </code></pre>
pandas|numpy|conditional-statements
0
13,454
54,177,131
Trying to load multiple json files and merge into one pandas dataframe
<p>I am trying to load multiple json files from a directory in my Google Drive into one pandas dataframe.</p> <p>I have tried quite a few solutions but nothing seems to be yielding a positive result. </p> <p>This is what I have tried so far</p> <pre><code>path_to_json = '/path/' json_files = [pos_json for pos_json i...
<p>There were a few challenges working with the JSON files you provided and then some more converting them to dataframes and merging. This was because the keys of the JSON's were not strings, secondly, the arrays of the resulting "valid" JSONS were of different length and could not be converted to dataframes directly a...
python|json|pandas
4
13,455
38,427,615
vectorize NumPy triple product on 2D array
<p>I am trying to vectorize the following triple product operation on an <code>N x N</code> array called <code>p</code> below:</p> <pre><code>for j in range(len(p)): for k in range(len(p)): for l in range(len(p)): h[j, k, l] = p[j, k] * p[k, l] * p[l, j] - p[j, l] * p[l, k] * p[k, j] </code></p...
<p>Simply porting over those loop iterators as string notations, we would have an <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>einsum</code></a> based solution like so -</p> <pre><code>h = np.einsum('jk,kl,lj-&gt;jkl',p,p,p) - np.einsum('jl,lk,kj-&gt;jkl',p,p,p) ...
python|arrays|numpy|vectorization|numpy-einsum
4
13,456
66,128,017
sjoin 'contains'/'within' seems to be returning a bunch of incorrect rows
<p>I'm trying to figure out which of a bunch of lat/lon points fall within a certain region of the ocean by using a geopandas sjoin. But what I'm finding is that if I use an sjoin by 'within' or, equivalently, 'contains' - I end up with this weird set of points that are all bounded by the top and bottom latitudes of t...
<p>Well, it looks like this may actually be an issue in pygeos. I uninstalled pygeos and the regular geopandas is able to run the sjoin correctly.</p>
geopandas
0
13,457
66,004,655
Drop values with Type(int) in columns
<p>I have two columns (CL1 &amp; CL2):</p> <p><a href="https://i.stack.imgur.com/FYCIl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FYCIl.png" alt="enter image description here" /></a></p> <h3>my goal:</h3> <p>I would drop the values with type Integer from column CL1 with <em>for loop</em>.</p> <h...
<p>If there are mixed values - strings, floats and integers is possible test type by <code>isinstance</code> and filter all values without integer type:</p> <pre><code>df = pd.DataFrame({ &quot;CL1&quot;: ['Hello', 12, 'World', 12.23], }) df = df[~df.CL1.map(lambda x: isinstance(x, int))] print (df) CL1 0...
python|pandas
2
13,458
66,191,554
What is the most efficient way to read a large CSV file ( 10 M+ records) located on S3 (AWS) with Python?
<p>I've been trying to find the fastest way to read a large csv file ( 10+ million records) from S3 and do a couple of simple operations with one of the columns ( total number of rows and mean). I have ran a couple of tests, and the fastest so far was creating a dask dataframe, but I am wondering if there is any other...
<p>This line</p> <pre><code>dfp = df.compute() </code></pre> <p>is an antipattern for dask. You split up the load, btu then you form a single large dataframe in memory by concatenation. You would do better to compute what you want on the original chunks (note that <code>len</code> is special in python, so this is less ...
python|pandas|csv|amazon-s3|dask
0
13,459
66,093,600
ValueError: Unknown label type: 'unknown' - sklearn
<p>This is my dataframe:</p> <p><img src="https://i.stack.imgur.com/XTpbh.png" alt="df.head()" /></p> <p>First I tried to rescale it using MinMaxScaler:</p> <pre><code>array = df.values X = array[:,1:5] Y = array[:,5] from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range = (0, 1)) rescaled...
<p><code>LogisticRegression</code> is not for regression, it's used for classification problem.</p> <p>If you want to use <code>LogisticRegression</code>, the <code>y</code> variable must be a classification class (for example: 0, 1, 2, 3), and not a continuous variable as you have.</p> <p>You should use <code>LinearRe...
python|scikit-learn|sklearn-pandas
1
13,460
52,584,849
performing function on values in dataframe and replacing
<p>I want to perform a function on every value in a column of a pandas data frame and replace the old value with the new one. for example, going through every value in the column and replacing it with the value plus one. I have been trying things like the code below but it is not replacing the values.</p> <pre><code>f...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a>:</p> <pre><code>df = pd.DataFrame({'src':['192.168.0.1','192.168.0.10', '']}) print (df) src 0 192.168.0.1 1 192.168.0.10 2 ...
python|pandas|dataframe
3
13,461
52,869,351
Selecting entries from a big pandas dataframe is slow
<p>I have two pandas dataframes: One with premium customers, <code>df_premium_customer</code> and one with all sold items, <code>df_sold</code>, that has as columns "customerID"(containing the ID's of premium customers as well as others),"ArticleID", "Date"and several others. </p> <p>This is how <code>df_premium_cust...
<p>I believe that your issue is coming from pandas. In general, pandas is very slow. You might get some speedup by using merge or groupby method, but i'm not even sure. I believe one easy way to get a speedup is to do it all in numpy. I think the line </p> <pre><code>cust_index = df_sold.index[df_sold['CustomerID'] ==...
python|html|pandas|performance
1
13,462
46,530,720
Keep top N values of each row in a dataframe within groups of column indices
<p>I'm having trouble finding an elegant solution to this problem (there might not be one).</p> <p>I have the following example DataFrame:</p> <blockquote> <p>np.random.seed(0)</p> <p>df = pd.DataFrame(np.random.randn(10,10)).abs()</p> </blockquote> <pre><code> 0 1 2 3 4 ...
<p>Here's one way -</p> <pre><code>def keeptopN_perkey(df, zones, N=2): a = df.values indx = zones.values() r = np.arange(a.shape[0])[:,None] for i in indx: b = a[:,i] L = np.maximum(len(i)-N,0) if L&gt;0: idx = np.argpartition(b, L, axis=1)[:,:L] # or n...
python|performance|pandas|numpy|dataframe
5
13,463
58,493,521
Approximate numerically the jacobian of a vector
<p>I have to find the Jacobian of the function</p> <pre class="lang-py prettyprint-override"><code>def f(x): return np.array([ np.sin(x[0]) + 0.5 * (x[0] - x[1])**3 - 1.0, 0.5 * (x[1] - x[0])**3 + x[1] ]) </code></pre> <p>One of the requirements is if dx is not specified, I need to set it to ...
<p>There are a few things going wrong in your code:</p> <ul> <li><code>f0</code> is a function, not a np.array.</li> <li><code>dx=np.atleast_1d(N)</code> doesn't make sense to me.</li> <li>You set J in every iteration as the zero matrix.</li> </ul> <p>Here's a way how you could do it:</p> <pre><code>import numpy as ...
python|numpy|scipy
0
13,464
58,273,919
DataFrame.groupby.apply() with lambda functions
<p>I have a dataframe as follows:</p> <pre class="lang-none prettyprint-override"><code>Datetime Value -------------------------------------------- 2000-01-01 15:00:00 10 2000-01-01 16:00:00 12 2000-01-01 17:00:00 14 2000-01-01 18:00:00 16 2000-01-02 15:00:00 13 2000-01-02 16:0...
<p>IIUC, this is what you need.</p> <pre><code>df['Datetime']=pd.to_datetime(df['Datetime']) df['NewColumn'] = (df.groupby(pd.Grouper(freq='D', key='Datetime'))['Value'] .apply(lambda x: x - df.loc[x.loc[df['Datetime'].dt.hour == 16].index[0],'Value'])) df.loc[df['Datetime'].dt.hour &lt; 16, 'NewColumn'] = '-' print(...
python|pandas|dataframe
1
13,465
58,411,025
How to pick multiple rows' value of dataframe according to multiple cells?
<p>I have a data frame of (user_id,session_id,items1), each user has multiple sessions, I want to pick each session individually for each user to compare its items, I used list of list but it return 0. how to get that? </p> <p><a href="https://i.stack.imgur.com/cydSt.png" rel="nofollow noreferrer">Dataframe</a></p> <...
<p>For efficiency let's order the list by user</p> <pre><code> # order to get a list df.sort_values(by=['user_id']) </code></pre> <p>Then we use comprehesion lists to get all items associated to a session and user.</p> <pre><code> itPerSession = [] #output list # loop to extract the in...
python|pandas|nested-loops
0
13,466
58,221,470
Is this classification model overfitting?
<p>I am performing a url classification (phishing - nonphishing) and I plotted the learning curves (training vs cross validation score) for my model (Gradient Boost). </p> <p><strong>My View</strong></p> <p>It seems that these two curves converge and the difference is not significant. Tt's normal for the training set...
<p>Firstly, in your graph there are 8 different models.</p> <p>It's hard to tell if one of them is overfitting because overfitting can be detected with a "epoch vs performance (train / valid)" graph (there would be 8 in your case).</p> <p>Overfitting means that, after a certain number of epochs, as the number of epoc...
machine-learning|scikit-learn|classification|text-classification|sklearn-pandas
1
13,467
58,490,863
Efficiently convert large Pandas DataFrame columns from float to int
<p>This is different from <a href="https://stackoverflow.com/questions/41550746">error using astype when NaN exists in a dataframe</a> because I need to keep the NaN values, so I've chosen to use the experimental <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.arrays.IntegerArray.html" rel="n...
<p>Find the columns you need to typecast to each type then do it all at once for each type.</p> <h3>Sample Data</h3> <pre><code>import pandas as pd import numpy as np np.random.seed(10) df = pd.DataFrame(np.random.choice([1, 2, 3.3, 5000, 111111, np.NaN], (3,9)), columns=[f'col{i}' for i in range(...
python|pandas|dataframe
2
13,468
44,708,685
Build Select widget in Bokeh using data frames
<p>I have a data frame df with column "location" (few cells with no value) -</p> <pre><code>location US India US Japan US India </code></pre> <p>I want to create a Single Selection Widget using bokeh with the values contained in Location column. I am writing below code -</p> <pre><code>location = Select(title="Loc...
<p>You need to convert your pandas series into a list.</p> <pre><code>options=df["location"].unique().tolist() </code></pre>
python|pandas|data-visualization|bokeh
0
13,469
44,478,781
Rolling Unique Sum for 3 previous months in python
<p>The following is the dataset I am looking at.</p> <pre><code>Input:- Date Name 01/01/2017 A 01/03/2017 B 02/05/2017 A 03/17/2017 C 04/08/2017 D 05/10/2017 B 06/12/2017 D Output:- Date Unique Count Jan 2017 2 Feb 2017 2 Mar 2017 3 Apr 2017 3 May 2017 3 Jun 2017 2...
<p>Try:</p> <pre><code>months = pd.to_datetime(d.loc[:, "Date"]).dt.to_period("M") out = pd.DataFrame([ (month, len(d.loc[(-2 &lt;= months - month) &amp; (months - month &lt;= 0), "Name"].unique())) for month in months.unique()]) </code></pre>
python|python-3.x|pandas
2
13,470
60,836,588
How to fix a Parse Error in Pandas read csv in python?
<p>how to fix this python error (pandas lib). why does it happen? please help</p> <pre><code>import pandas as pd url='https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_daily_reports/03-23-2020.csv' data = pd.read_csv(url) data.describe() </code></pre> <blockquote> <p>ParserErr...
<p>You may try this adress </p> <pre><code>url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/03-23-2020.csv" </code></pre>
python|pandas
0
13,471
61,122,481
Count and find pattern in 2D array in python
<p>I have this data below:</p> <pre><code>data = np.array([[1, 0,-1, 0, 0, 1, 0,-1, 0, 0, 1], [1, 1, 0, 0,-1, 0, 1, 0, 0,-1, 0], [1, 0, 0, 1, 0, 0,-1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0]]) </code></pre> <p>i want to calculate how many <code>0</code> in eac...
<pre><code>data = np.array([[1, 0,-1, 0, 0, 1, 0,-1, 0, 0, 1], [1, 1, 0, 0,-1, 0, 1, 0, 0,-1, 0], [1, 0, 0, 1, 0, 0,-1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0]]) a = data </code></pre> <hr> <p>Counting consecutive zeros in each row:<br> Numpy and Python loop(s...
python|arrays|numpy
2
13,472
61,154,274
pandas convert big int to string avoid scientific notation
<p>i have a dataframe from a csv file that loads with pandas.read_csv() method, looks like:</p> <pre><code> id col 0 1151377158377549824 row0 1 1151346166619103232 row1 2 1151737502769827840 row2 </code></pre> <p>types of columns is:</p> <pre><code>df.dtypes out: id float64 col object...
<p>you can convert to Int64 and then to string:</p> <pre><code>df['id'] = df['id'].astype("Int64").astype(str) df </code></pre> <p>output:</p> <p><a href="https://i.stack.imgur.com/vIoao.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vIoao.png" alt="enter image description here"></a></p>
python|pandas
1
13,473
71,671,902
Using tkinter compare multiple csv and display the matching
<p><strong>New to Tkinter</strong></p> <p>I have a json file which contains some Firewall-rules, then convert it into two different csvs. As the firewall-rules have two different sets with ARules.csv and YRules.csv Don't want to merge it because of the requirement.</p> <p>Then using splunk we pull the stats which will ...
<pre><code>import pandas as pd import csv import json,os from tkinter import * import tkinter as tk from tkinter import messagebox from tkinter.filedialog import askopenfilename from tkinter.filedialog import asksaveasfile def import_csv_data(): global v,csvData csv_file_path = askopenfilename() v.set(csv_...
python|pandas|tkinter
0
13,474
71,772,409
Series not showing up on plots
<p>I've been trying to work through the code in this function and cannot get my series to show up on my plots. Possibly there is an easier way to do this. In each plot I want display each of the 7 entities, in a time series with 1 indicator.</p> <p>I'm struggling with how to group values by both year, and country. I am...
<p><strong>EDIT</strong></p> <p>I have re-written this answer to be more clear and concise.</p> <p>This is a clever bit of code! I found the problem, it was with <code>xlim</code>. As the years are strings, not integers, the x-axis is index-based, not integer-based. This means that when you pass the range between 19...
python|pandas|plot
1
13,475
71,757,193
Python: Dataframe loop repeats by only one element
<p>When I run the code and output it, I notice that the messages for the third item in the list are output three times in a row. With the previous and subsequent elements from the list it works problem los. Can anyone help me with this, or does anyone know how to at least remove such duplicates?</p> <pre><code>Nachrich...
<p>Your code included some issues regarding lower and upper case e. g. <code>nachrichten</code> vs. <code>Nachrichten</code>. Python is case-sensitive though.</p> <p>To answer your question, you could use <code>drop_duplicates()</code> to eliminate duplicates based on <code>'Title'</code>.</p> <p>This yields:</p> <pre>...
python|pandas|dataframe|google-news
0
13,476
42,566,423
Pandas MemoryError with read_sql_query
<p>I am trying to read 2.7 million rows into Pandas Dataframe but running into memory issues (I guess). The strange part is when I monitor the RAM usage on the server python uses maximum 1.5 GB of the free 8 GB (Total RAM on the server is 16 GB).On the same setup, it can read up to a million rows easily. </p> <p>What ...
<p>Just like Paul suggested upgrading python 2.7 32-bit to 64-bit worked. I am not completely sure why it worked, but compiling Cython code with 64-bit python is difficult with Microsoft Visual C++ Compiler for Python. So had to remove the Cython code.</p>
python|python-2.7|pandas|memory
0
13,477
43,298,240
How to sum the values in a specific column of a .txt file starting at row 2
<p>I am trying to sum all of the values under the column "Packets" obviously I want just the integers and not the string "Packets" so it would have to start at row 2. The output should equal 9 in this case. For the case of Packets its column id is [7]. </p> <p>CODE:</p> <pre><code>import os from scipy import * from m...
<p>You are very near to your goal. Just add every packet to a variable as following.</p> <pre><code>packets = 0 infile = open('E:\sample.txt') for line in infile.readlines()[1:] packets += int(line.split()[7]) # As, packet column in 5th print("Packets:"+str(packets)) infile.close() </code></pre> <p>It will let yo...
python|numpy
1
13,478
72,221,972
How to solve (NaN error) when given column specific name
<p>I have many text files include data as follow:</p> <pre><code>350.0 2.1021 0.0000 1.4769 0.0000 357.0 2.0970 0.0000 1.4758 0.0000 364.0 2.0920 0.0000 1.4747 0.0000 371.0 2.0874 0.0000 1.4737 0.0000 </code></pre> <p>I need to give each column a specific name (Ex:a,b,c,d,e)</p> ...
<p>You can define columns while reading from CSV file.</p> <pre><code>data = pd.read_csv(file_name, names=columns_list) </code></pre>
python-3.x|pandas|dataframe|python-import|read.csv
0
13,479
72,354,062
How to solve this using numpy vectorization
<p>I have a really big input numpy array, and a dictionary. The dictionary dictates what the values in the numpy array should be updated to. I can do it using a for loop but it is very time consuming, can I use numpy vectorization to solve this?</p> <p>Input:</p> <pre><code>arr_to_check = numpy.array([['A', 20],['B', 1...
<p>Here is a way to do what you've asked (<strong>UPDATED</strong> to simplify the code).</p> <p>A few notes first:</p> <ul> <li>numpy arrays must be of homogeneous type, so the numbers you show in your question will be converted by numpy to strings to match the data type of the labels (if pandas is an option, it might...
python|numpy|vectorization
1
13,480
50,456,087
pandas way to get list of indexes using iloc?
<p>I have data sorted the way I want. I'm about to put in something like:</p> <pre><code>series_data = [] for count,x in enumerate(df): series_data.append(list(range(count))) df['up_to_row'].iloc(count)= series_data </code></pre> <p>so the column would be:</p> <pre><code>df['up_to_row'] = Series([0], [0,1], [0...
<p>Using <code>cumsum</code> , Notice it will convert number in list to str , not int anymore.</p> <pre><code>df['up_to_row']=np.arange(len(df)) (df['up_to_row'].astype(str)+',').cumsum().str[:-1].str.split(',') Out[211]: 0 [0] 1 [0, 1] 2 [0, 1, 2] 3 [0, 1, 2, 3] Name: up_to_row, dtype: ...
python|pandas|vectorization
1
13,481
50,305,976
Is array.count() orders of magnitude slower than list.count() in Python?
<p>Currently I am playing with Python performance, trying to speed up my programs (usually those which compute heuristics). I always used lists, trying not to get into <code>numpy</code> arrays.</p> <p>But recently I've heard that Python has <a href="https://docs.python.org/3/library/array.html" rel="nofollow noreferr...
<blockquote> <p><em>where's the catch?</em></p> </blockquote> <h2>The initial test, as proposed above does not compare apples to apples:</h2> <p>not mentioning the <a href="/questions/tagged/python-2.7" class="post-tag" title="show questions tagged &#39;python-2.7&#39;" rel="tag">python-2.7</a>, where <strong><code...
python|arrays|numpy|count
1
13,482
45,679,857
Ignoring bad rows of data in pandas.read_csv() that break header= keyword
<p>I have a series of very messy *.csv files that are being read in by pandas. An example csv is:</p> <pre><code>Instrument 35392 "Log File Name : station" "Setup Date (MMDDYY) : 031114" "Setup Time (HHMMSS) : 073648" "Starting Date (MMDDYY) : 031114" "Starting Time (HHMMSS) : 090000" "Stopping Date (MMDDYY) : 031115...
<p>Here's one approach, making use of the fact that <code>skip_rows</code> accepts a callable function. The function receives only the row index being considered, which is a built-in limitation of that parameter. </p> <p>As such, the callable function <code>skip_test()</code> first checks whether the current index i...
python|pandas|csv
3
13,483
45,462,825
How do I create a new Pandas Dataframe Column with data from another column
<p>I have a Pandas dataframe created from a dict of lists. I want to split up those entries under the dates and create a new column called 'Story'. </p> <pre><code> 2017-01-31 2017-02-01 Gates, Bill. [[SPGC-14075, 0.5]] [0] Jobs, Steve. [[...
<p>You can try using the <code>.apply()</code> method as follows (assuming that your DataFrame is in a variable called <code>df</code>):</p> <pre><code>df['Story'] = df['2017-01-31'].apply(lambda x: x[0][0]) df['2017-01-31'] = df['2017-01-31'].apply(lambda x: x[0][1]) df['2017-02-01'] = df['2017-02-01'].apply(lambda x...
python|pandas
0
13,484
45,452,786
Python variable should not change, but it changed?
<p>I have a strange behavior with a variable in the following code. </p> <p>Why is the output of w3 at the end the same as w2? Its never been changed in the code, but in the end it has the same value as w2?</p> <pre><code>import numpy as np inpt = np.array([[1]]) w1 = np.random.random((1,1)) w2 = np.random.random((...
<p><code>w3</code> is just a reference to <code>w2</code> so it will reflect the change in <code>w2</code> when you update <code>w2</code></p>
python|numpy
0
13,485
62,606,147
How to reshape the array to (X,1,3) to (X,3)
<p>I have data which is list with len of 5000</p> <p>I have changed the list into numpy array. I got the numpy array with shape(5000,1,3)</p> <p>I need to reshape this to shape(5000,3)</p> <p>Can i directly change list with<br /> <code>array([[0.3, 0.3 0.3]], dtype=float32),</code><br /> <code>array([[0.3 , 0.3, 0.3 ]]...
<p>The most intuitive <em>Numpy</em> method to get rid of dimensions of size <em>1</em> is <em>squeeze</em>.</p> <p>So you can run:</p> <pre><code>b = np.squeeze(a) </code></pre>
python|arrays|numpy
0
13,486
62,473,311
error reindex from a duplicate axis in groupby
<p>by = "B" block has duplicated indices both in case1 and case2, </p> <p>why case1 work but case2 does not.</p> <p>case1</p> <pre><code>df1 = pd.DataFrame({"a":[0,100,200], "by":["A","B","B"]}, index=[0,1,1]) df1.groupby("by").diff() # result is okay </code></pre> <p>case2</p> <pre><code>df2 = pd.DataFrame({"a...
<p>Your problem is solved by turning off the <strong>sort</strong> property of groupby.</p> <pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame({&quot;a&quot;:[0,100,200], &quot;by&quot;:[&quot;C&quot;,&quot;B&quot;,&quot;B&quot;]}, index=[0,1,1]) df1.groupby(&quot;by&quot;, sort=False).diff() print(df1...
python|pandas|pandas-groupby
1
13,487
73,794,884
Apply conditional formatting in Excel using pandas does not work
<p>I have spent hours trying all possible pandas style methods for conditional formatting for Excel sheet but none of them worked... I have a dataframe like this below.</p> <pre><code> Category Month Sales Margin Margin_Rate 0 TV July 50000 10354.64 0.207093 1 Stero...
<p>There are a few issues in your code:</p> <ul> <li>typo in &quot;background&quot;</li> <li>your function should return <code>''</code> or <code>None</code> if no style is applied, not <code>&quot;background-color:&quot;</code></li> <li>you should export the return of <code>df.style.applymap</code>, not <code>df</code...
python|excel|pandas
2
13,488
73,814,341
extract week columns from date in pandas
<p>I have a dataframe that has columns like these:</p> <pre><code>Date earnings workingday length_week first_wday_week last_wdayweek 01.01.2000 10000 1 1 02.01.2000 0 0 1 ...
<p>I first changed the format of your <code>date</code> column as <code>pd.to_datetime</code> couldn't infer the right date format:</p> <pre><code>df.Date.str.replace('.', '-', regex=True) df.Date = pd.to_datetime(df.Date, format='%d-%m-%Y') </code></pre> <p>Then use <code>isocalendar</code> so that we can work with we...
pandas|dataframe|time-series
3
13,489
73,807,658
Eliminate for loop when indexing into array
<p>I have two arrays: <code>vals</code> has shape (N,m) where N is ~1 million, and m is 3. The values are floats I have another array <code>indices</code> with shape <code>(N,4)</code>. All values in <code>indices</code> are row indices in <code>vals</code>. (Additionally, unlike the example here, every row of <code>in...
<p>You actually can replace the entire <code>aug = ...</code> line with</p> <pre><code>aug = vals[indices] </code></pre> <p>That will produce the same result:</p> <pre><code>np.array_equal( np.stack([vals[indices[x]] for x in range(N)]), vals[indices] ) # True </code></pre>
python|numpy|nearest-neighbor|kdtree
1
13,490
73,799,061
Format Data using panadas groupBy such that it groups by one column
<p>I have the data in below format in an csv :-</p> <p><a href="https://i.stack.imgur.com/5dxl7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5dxl7.png" alt="enter image description here" /></a></p> <p>However, the format in which I required is below :-</p> <p><a href="https://i.stack.imgur.com/bgR...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> with create dictionaries filled by list:</p> <pre><code>def grouping(): df = pd.read_csv(&quot;final_data_6.csv&quot;) df['n'] = [x for x in...
python-3.x|pandas|group-by
0
13,491
73,554,770
Pandas - combine two lines into one (simplify)
<p>I have two lines of code that I want to simplify into one:</p> <pre><code>df1 = df[df.column1.isin(values) == False] df2 = df1[df1.column2.isin(values) == False] </code></pre> <p>Preferably, I don't want to have to create df2 at all.</p>
<p>For avoid <code>df1</code> chain both conditions by <code>&amp;</code> for bitwise <code>AND</code>, instead compare by <code>False</code> invert mask by <code>~</code>:</p> <pre><code>df2 = df[~df.column1.isin(values) &amp; ~df.column2.isin(values)] </code></pre>
python|pandas
4
13,492
73,756,788
pandas count consecutive values in a column
<p>There is my data after comparing two dataframes:</p> <pre><code>frames = [9,12,14,15,16,17,18,22,23,24,25,30] df1 = [75,75,75,75,75,75,75,75,75,75,75,75] df2 = [*[0]*len(df1)] d = {'frames':frames,'a':df1, 'b':df2} df = pd.DataFrame(d) </code></pre> <p>I need to count consecutive frames, count starts after two conse...
<p>You can use <code>diff()</code> to check for a sequence and <code>shift()</code> to skip extra matches.</p> <pre><code>df['c'] = ((s := df.frames.diff().eq(1)) &amp; s.shift(1)).astype(int) print(df) </code></pre> <pre class="lang-none prettyprint-override"><code> frames a b c 0 9 75 0 0 1 12 ...
python|pandas|numpy
2
13,493
73,692,323
Convert np.ndarray of tuples (dtype=object) into array with dtype=int
<p>I need to convert np arrays (short) of tuples to np arrays of ints.</p> <p>The most obvious method doesn't work:</p> <pre><code># array_of_tuples is given, this is just an example: array_of_tuples = np.zeros(2, dtype=object) array_of_tuples[0] = 1,2 array_of_tuples[1] = 2,3 np.array(array_of_tuples, dtype=int) Val...
<p>It looks like placing the tuples into a pre-allocated buffer of fixed size and dtype is the way to go. It seems to avoid a lot of the overhead associated with computing sizes, raggedness and dtype.</p> <p>Here are some slower alternatives and a benchmark:</p> <ul> <li><p>You can cheat and create a dtype with the req...
python|numpy
3
13,494
71,310,950
How to change the data format to one column and export as csv in Python and Pandas
<p>The picture is just an example and I hope to change this data(str type) to one column (float type) and save as csv in Python. Pandas or Numpy may help but I don't know how to do that. Could someone help me please? Thank you very much.</p> <p><a href="https://i.stack.imgur.com/mZ62m.png" rel="nofollow noreferrer">dat...
<p>To convert as float, you just need to use <code>astype</code> method in your dataframe, and to save it as csv you just need to use <code>to_csv</code> method for your dataframe.</p> <p>Here's the example of your case:</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;String_type&quot;:[&quot;2.1&quot;,&qu...
python|pandas|database|numpy
0
13,495
71,165,093
PyTorch high-dimensional tensor through linear layer
<p>I have a tensor of size (32, 128, 50) in PyTorch. These are 50-dim word embeddings with a batch size of 32. That is, the three indices in my size correspond to number of batches, maximum sequence length (with 'pad' token), and the size of each embedding. Now, I want to pass this through a linear layer to get an outp...
<p>In the <code>nn.Linear</code> <a href="https://pytorch.org/docs/stable/generated/torch.nn.Linear.html" rel="nofollow noreferrer">docs</a>, it is specified that the input of this module can be any tensor of size <code>(*, H_in)</code> and the output will be a tensor of size <code>(*, H_out)</code>, where:</p> <ol> <l...
pytorch
2
13,496
71,237,853
Sort index at a level and per partitioning by earlier levels
<p>I'm using pandas to count the different types or errors and correct predictions for different (machine learning) models, in order to display confusion matrices.</p> <p>A particular order of the prediction and ground truth labels makes sense, for example by putting the majority class 'B' first.</p> <p>However, when I...
<p>You might want to use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> method.</p> <h2>Code:</h2> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd # Create a sample dataframe errors = pd....
pandas|dataframe|python-3.7
1
13,497
52,371,472
Is it possible to write json chunk by chunk with pandas
<p>I've got a web server (tornado), and want to serialize a large dataframe to json but chunk by chunk, not creating the whole json string then sending it.</p> <p>Is that possible ?</p>
<p>The http server (tornado) implements so this works :</p> <pre><code>import tornado.ioloop import tornado.web impot pandas as pd df=pf.DataFrame({"test":[1,2,3,4]}) class MainHandler(tornado.web.RequestHandler): def get(self): df.to_json(self) </code></pre>
python|json|pandas
0
13,498
52,072,528
Array.mean(axis = 1) with a loop
<p>I have an array with 1000 rows and 10 colums (price_list). With the command </p> <pre><code>price_list.mean(axis = 1) </code></pre> <p>I performed the mean for each row. How can I use a loop to perform the same computation? Thank you very much.</p> <p>Example:</p> <pre><code>In: price_list Out: array([[ 88.11862...
<p>First I create a fake <code>price_list</code>:</p> <pre><code>import numpy as np price_list = np.random.rand(10,1000) price_list.mean(axis = 1) #&gt; array([0.49730006, 0.48494404, 0.4948243 , 0.49762745, 0.49727592, #&gt; 0.50856465, 0.4993344 , 0.49325429, 0.4938947 , 0.50599995]) </code></pre> <p>Now, we ca...
python|python-3.x|numpy
0
13,499
52,266,003
Reduce memory usage of a line of code that uses numpy
<p>I am using the <code>python</code> library: </p> <p><a href="https://github.com/ficusss/PyGMNormalize" rel="nofollow noreferrer">https://github.com/ficusss/PyGMNormalize</a></p> <p>For normalizing my datasets (<code>scRNAseq</code>) and the last line in the library's file <code>utils.py</code>:</p> <p><a href="ht...
<p>If all elements of <code>matrix</code> are >=0, then you can do:</p> <pre><code>np.percentile(matrix[np.any(matrix, axis = 1)], p, axis = 0) </code></pre> <p>This uses the fact that any float or integer other than <code>0</code> is interpreted as <code>True</code> when viewed as a boolean (which <code>np.any</code...
python|numpy|memory
2