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
373,400
53,439,844
Python column datetime subtract datetime
<p>understand that there is many similar question out there on subtraction for pandas column, but my scenario is rather unique</p> <p>I have 2 sets of data which both includes datetime. My program requires me to match this 2 date time therefore I used merge_asof to match to the closest time. After matching the data, I...
<p>IIUC you can use :</p> <pre><code>print (df) EndTime Datetime 0 3/10/2010 0:00:33 3/10/2010 0:00:26 1 3/10/2010 0:01:15 2 3/10/2010 0:01:30 NaN 3 3/10/2010 0:02:09 3/10/2010 0:01:36 4 3/10/2010 0:02:50 NaN 5 3/10/2010 0:05:09 ...
python|pandas|datetime
0
373,401
53,383,002
Pandas - Load dataframe and show all columns
<p>I'm using the NBA Draft dataframe, which can be obtained <a href="https://eimtgit.uoc.edu/prog_datasci_cat/prog_datasci_4/raw/ba658d89bd4e0ae4452ca22b1a077b6a7a2f4bae/data/historical_projections.csv?inline=false" rel="nofollow noreferrer">here</a> and reading it with pandas.</p> <p>When I try to load the csv to Dat...
<p>Do you want to see the whole dataframe in your screen? See if rounding suits your need</p> <pre><code>r.round(2) </code></pre>
python|pandas|python-2.7|dataframe
0
373,402
53,630,179
Pandas - Taking the log of one column with another as base
<p>For example, if I have: </p> <pre><code>A B 2 4 3 5 6 2 </code></pre> <p>I would want a result of:</p> <pre><code>log 2 (4) log 3 (5) log 6 (2) </code></pre> <p>I've tried result = math.log(B, A), however this return an error of: </p> <pre><code>Cannot convert the series to &lt;type 'float...
<p>Be smart about this. Use the properties of log.</p> <pre><code>np.log(df.B) / np.log(df.A) 0 2.000000 1 1.464974 2 0.386853 dtype: float64 </code></pre> <p>This works, provided you understand that the logarithm of B with base A is the same as <code>log B / log A</code> in any base. </p> <p>For reference...
pandas|numpy
2
373,403
53,576,436
Predicting image using triplet loss
<p>I'm new to NN.</p> <p>I built a NN for image understanding using a triplet loss method.</p> <p>And I think that I'm missing some basic knowledge about how to use this method for predicting an image tag.</p> <p>After I have my model built, how should I predict a sample image? Because my model input is a triplet - wha...
<p>If you've trained your <code>embedding_network</code> properly, you now don't need to use triplets any more.<br> Basically, the whole <em>point</em> of the triplet-loss concept is to learn an embedding that is compatible with a pre-defined metric (usually just the Euclidean distance for instance), and then use this ...
python|tensorflow|keras|neural-network
2
373,404
53,490,497
Getting Validation set from Train set by using percentage from groupby() in pandas
<p>Have a train dataset with multi-class target variable <code>category</code></p> <pre><code>train.groupby('category').size() 0 2220 1 4060 2 760 3 1480 4 220 5 440 6 23120 7 1960 8 64840 </code></pre> <p>I would like to get the new validation dataset from the train set by havin...
<p>Groupby and sample should do that for you</p> <pre><code>df = pd.DataFrame({'category': np.random.choice(['a', 'b', 'c', 'd', 'e'], 100), 'val': np.random.randn(100)}) idx = df.groupby('category').apply(lambda x: x.sample(frac=0.2, random_state = 0)).index.get_level_values(1) test = df.iloc[idx, :].reset_index(dr...
python|pandas|group-by|cross-validation|train-test-split
3
373,405
53,489,237
How can you implement Householder based QR decomposition in Python?
<p>I'm currently trying to implement the Householder based QR decomposition for rectangular matrices as described in <a href="http://eprints.ma.man.ac.uk/1192/1/qrupdating_12nov08.pdf" rel="nofollow noreferrer">http://eprints.ma.man.ac.uk/1192/1/qrupdating_12nov08.pdf</a> (pages 3, 4, 5).</p> <p>Apparently I got some ...
<p>There were a bunch of problems/missing details in the notes you linked to. After consulting a <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5684333/pdf/13660_2017_Article_1547.pdf" rel="nofollow noreferrer">few</a> other <a href="https://www.cs.cornell.edu/%7Ebindel/class/cs6210-f12/notes/lec16.pdf" rel="nof...
python|numpy|linear-algebra|numerical-methods|qr-decomposition
7
373,406
53,441,392
converting column item into its own column python
<p>i have a data frame that looks like this</p> <pre><code>column1 column2 rabbit fluffy dog cute cat tabby </code></pre> <p>i would like to make each value in <code>column1</code> into its own column, with values in <code>column2</code> as the observation for that column. </p> <p>So the end result d...
<p>Use <code>DataFrame</code> contructor:</p> <pre><code>df1 = pd.DataFrame([df['column2'].tolist()], columns=df['column1'].tolist()) </code></pre> <p>If more columns:</p> <pre><code>cols = df.pop('column1').tolist() data = df.values.reshape(len(df.columns), -1) df1 = pd.DataFrame(data, columns=cols) </code></pre> ...
python|python-3.x|pandas|multiple-columns
1
373,407
53,548,195
Reading text file with varying number of columns in Python
<p>I am trying to read a <code>.txt</code> file which contains string entries using <code>pandas</code>. Different rows in this file have different number of columns. The file can be found <a href="https://drive.google.com/file/d/1g1n_8Xlg7ssevFf88bokpzg8uHVisY0k/view?usp=sharing" rel="nofollow noreferrer">here</a>.</p...
<p>This chucks a lot of the data (from 695 to 475 lines). But that file is garbage anyways. Best to preprocess it before it comes into python.</p> <pre><code>[ins] In [20]: df = pd.read_csv("/tmp/file.txt", delim_whitespace=True, error_bad_lines=False, warn_bad_lines=False, header=None) ...
python|pandas
1
373,408
53,503,954
how can I parse date time in pandas with a specific format
<p>I have a direct CSV stream from an API that I am using to push data into a database with the following code:</p> <pre><code>def loadData(data, engine) : stream = data.content try: df = pd.read_csv(io.StringIO(stream.decode('utf-8'))) df['Snapshot'] = datetime.datetime.now() if file.split(".")[0] == "S...
<p>Got it to work with the following:</p> <pre><code>def loadData(data, engine) : stream = data.content try: df = pd.read_csv(io.StringIO(stream.decode('utf-8'))) df['Snapshot'] = datetime.datetime.now() df.where(df.notnull(),None) dateCol = [col for col in df.columns if 'Date' in col] for col...
python-3.x|pandas
0
373,409
53,471,855
Why does Keras halt at the first epoch when I attempt to train it using fit_generator?
<p>I'm using Keras to fine tune an existing VGG16 model and am using a fit_generator to train the last 4 layers. Here's the relevant code that I'm working with:</p> <pre><code># Create the model model = models.Sequential() # Add the vgg convolutional base model model.add(vgg_conv) # Add new layers model.add(layers.F...
<p>You have to pass a valid <strong>integer</strong> number to <code>fit_generator()</code> as <code>steps_per_epoch</code> and <code>validation_steps</code> parameters. So you can use as follows:</p> <pre><code>history = model.fit_generator( train_generator, steps_per_epoch=train_generator.samples//train_gene...
python|tensorflow|keras
6
373,410
53,472,132
How do I avoid round-off error in this list?
<p>This list should have x[50] as zero and both sides to be symmetrical, but it is slightly off centre because of what I assume is roundoff error. How can I modify my code to avoid this?</p> <p>Thanks!</p> <pre><code>import numpy as np L=2*np.pi s=101 ds=L/(s-1) svals=np.arange(1,101) x=[0] x[0:s]=((svals-1)*ds)-L/2 ...
<p>Getting precise outputs from floating point operations can be tricky and fiddly. You can get the list you want using <code>np.linspace</code>:</p> <pre><code>x = np.linspace(-np.pi, 0, num=51) x = np.concatenate([x, np.linspace(x[-1] - x[-2], np.pi, num=50)]) print(x) </code></pre> <p>Output:</p> <pre><code>[-3.1...
python|numpy|floating-point|rounding
1
373,411
53,368,978
Match Value and Get its Column Header in python
<p><a href="https://i.stack.imgur.com/2czjh.png" rel="nofollow noreferrer">Sample</a></p> <p>I have 1000 by 6 dataframe, where A,B,C,D were rated by people on scale of 1-10. </p> <p>In SELECT column, I have a value, which in all cases is same as value in either of A/B/C/D.</p> <p>I want to change value in 'SELECT' t...
<p>Gwenersl solution compare all columns without <code>ID</code> and <code>SELECT</code> filtered by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.difference.html" rel="nofollow noreferrer"><code>difference</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pand...
python|pandas
2
373,412
53,398,008
Combine two Pandas series?
<p>I have two Pandas Series, <code>s1</code> and <code>s2</code> that I would like to combine. </p> <pre><code>s1 = pd.Series([2,5,5], index=['a','b','c']) s2 = pd.Series([2,4,7], index=['a','b','d']) </code></pre> <p>This is the result I would like:</p> <pre><code>s3 = pd.Series([4,9,5,7], index=['a','b','c','d']) ...
<p>Seems like <code>add</code> will work here </p> <pre><code>s1.add(s2,fill_value=0) Out[145]: a 4.0 b 9.0 c 5.0 d 7.0 dtype: float64 </code></pre>
python|pandas
5
373,413
53,581,468
Reverse the values of rows in a dataframe
<p>If I have a pandas data frame like this:</p> <pre><code> NaN 2 3 1 7 NaN 4 5 NaN NaN 2 8 0 3 NaN NaN NaN 4 7 9 3 </code></pre> <p>and an array like this:</p> <pre><code> [3, -5, 4] </code></pre> <p>How do I invert the pandas data frame columns in rows that have a negative array value? So tha...
<p>Suppose you want to reverse the second row. Do this based on your condition.</p> <pre><code>df.iloc[1] = df.iloc[1].tolist()[::-1] </code></pre>
python|pandas|python-2.7
0
373,414
53,686,140
Unicode error when trying to remove non-ascii chars
<p>I am parsing csv files and would like to remove non-ascii characters when they appear. Actually, I only need digits, but when I try to remove non-digit characters, I get an <code>UnicodeEncodeError</code>.</p> <p>I have the following function:</p> <pre><code>def remove_non_ascii(text): return ''.join(re.findal...
<p>One possible solution: You need to <code>import string</code> and change the function to</p> <pre><code>setV = set(string.printable) return ''.join(filter(lambda x: x in setV, text)) </code></pre> <p>This would remove all characters not in the set</p> <p>Just noticed you put that you only need digits. Heres a mor...
python|pandas|unicode
1
373,415
53,517,618
Install tensorflow in editable mode
<p>I would like to contribute to the project tensorflow. To do so, I would like to install tensorflow in editable mode. Does someone know how to do it ?</p> <p>Many thanks !</p>
<p>I found it by a simple windows search.</p> <p>For me it was in <code>C:\Users\Dell\Desktop\tf dev\tensorflow\tensorflow\tools\pip_package</code></p> <p>For you it will be in <code>directory in which cloned tensorflow is\tensorflow\tensorflow\tools\pip_package</code>.</p> <p><code>tf dev</code> is where my virtualenv...
tensorflow|installation
0
373,416
53,545,621
How two concatenate two dataframes has only one identical column
<p>I want to concatenate these two dataframes in pandas.</p> <p>df1:</p> <pre><code>Month Date ID 12 01 01 12 01 02 12 02 03 12 02 01 </code></pre> <p>df2:</p> <pre><code>ID Name 01 Jack 02 Lu 03 James </code></pre> <p>new df:</p> <pre><code>Month Date ID Name 12 01 01 Jack 12 01 02...
<pre><code>df1.merge(df2, how='outer', on='ID') </code></pre>
python|pandas
1
373,417
53,696,874
Python getting time difference
<p>I am working in a dataframe in Pandas and I have to get the time difference from datettime grouped by the identifier. Here is the dataframe</p> <pre class="lang-python prettyprint-override"><code> Identifier datetime 0 AL011851 00:00:00 1 AL011851 06:...
<p>You can set same dates in datetimes by:</p> <pre><code>hurricane_df['datetime'] = pd.to_datetime(hurricane_df['datetime'].dt.strftime('%H:%M:%S'), format='%H:%M:%S') print (hurricane_df) identifier datetime 0 AL011851 1900-01-01 00:00:00 1 AL011851 1900-0...
python|database|pandas|datetime|dataframe
0
373,418
53,689,654
Pandas vectorization: Compute the fraction of each group that meets a condition
<p>Suppose we have a table of customers and their spending.</p> <pre><code>import pandas as pd df = pd.DataFrame({ "Name": ["Alice", "Bob", "Bob", "Charles"], "Spend": [3, 5, 7, 9] }) LIMIT = 6 </code></pre> <p>For each customer, we may compute the fraction of his spending that is larger than 6, using the <c...
<p>Groupby does not use vectorization, but it has aggregate functions that are optimized with Cython.</p> <p>You can take the mean:</p> <pre><code>(df["Spend"] &gt; LIMIT).groupby(df["Name"]).mean() df["Spend"].gt(LIMIT).groupby(df["Name"]).mean() </code></pre> <p>Or use <a href="https://pandas.pydata.org/pandas-do...
python|pandas|group-by|vectorization|apply
2
373,419
53,404,251
Reading h5 file
<p>I am a new python user and I want to read the data from a h5 file. The code that I have used to read the data is given below:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import h5py &gt;&gt;&gt; f = h5py.File('file.h5', 'r') &gt;&gt;&gt; list(f.keys()) [u'data'] &gt;&gt;&gt; dset = f[u'data'] &gt;&g...
<p>As @hpaulj mentions, the h5py doc is a good reference. You also need to understand basic HDF5 file concepts. It's a big topic. To get started, review the <a href="https://portal.hdfgroup.org/display/HDF5/Learning+HDF5" rel="nofollow noreferrer">Learning HDF5</a> pages from The HDF Group. I know (from personal experi...
python-3.x|numpy|h5py
0
373,420
53,512,670
how to add 2 Array list into a single pandas dataframe with two seperate column name
<p>Hello guys I have a program that takes two array "Year_Array" and "Month_Array" and generates the output according to conditions. </p> <p>I want to add that both array in a single dataframe with column name year and name so in future I can add that dataframe with other dataframe.</p> <p><strong>Below is the sample...
<p>You can create a Array with the expected output and create a dataframe from it.</p> <p>Edit : added column name to dataframe.</p> <pre><code>Year_Array=[2010,2011,2012,2013,2014] Month_Array=['Jan','Feb','Mar','April','May','June','July','Aug','Sep','Oct','Nov','Dec'] final_Array=[] segment=[1, 1, 3, 5, 2, 1, 1, 1...
python|pandas
2
373,421
53,497,597
Add '+' sign to positive numbers in pandas df
<p>I want to add a "+" to all positive values in my df. </p> <p>Here is my df</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'A':[-1,3,0,5], 'B':[4,5,6,5], 'C':[8,-9,np.nan,7]}) print (df) A B C 0 -1 4 8.0 1 3 5 -9.0 2 0 6 NaN 3 5 5 7....
<p>Use display options instead of converting your floats as strings (which is NOT what you want) :</p> <p>Example : </p> <pre><code>import pandas as pd pd.options.display.float_format = '{:+,.2f}'.format pd.DataFrame({'a': [1.2, -3.4]}) </code></pre> <p>Returns :</p> <pre><code> a 0 +1.20 1 -3.40 </code></pr...
python|pandas|dataframe
7
373,422
53,542,748
Python pandas.readexcel(filepath, header=[0,1]) fails when row 3 has data longer than header length. Any suggestion of fix is welcome
<p>I have defined the first two rows ie 0,1 of my excel(xlsx) as headers. For simplicity the excel file has only one sheet. After the initial two rows there are few data rows in the file. Because of two headers pandas is giving me a multi-indexed data frame which is fine.</p> <pre><code>dataframe = pandas.readexcel(fi...
<p>Normally pandas manages to parse the file correctly. So it's a bit strange.</p> <p>However, note that usecols is 0-indexed. Meaning that if you give it the value of 65, it will parse 0-65=66 columns, giving you the same error. (Although it should input a 66th column with unnamed header)</p> <p>Can you try doing:</...
python|excel|pandas|numpy|dataframe
0
373,423
53,752,155
Standard error of values in array corresponding to values in another array
<p>I have an array that contains numbers that are distances, and another that represents certain values at that distance. How do I calculate the standard error of all the data at a fixed value of the distance? </p> <p>The standard error is the standard deviation/ the square-root of the number of observations. </p> <p...
<p>Does this help?</p> <pre><code>for d in set(key): result.append(np.std[dist[i] for i in range(len(key)) if key[i] == d] / np.sqrt(dist.count(d))) </code></pre>
python|numpy|statistics|standard-error
0
373,424
53,541,366
How to join two dataframes where IDs do not match and create new column to represent what dataframe ID came from?
<p>I have two dataframes like this</p> <p>df1:</p> <pre><code>id column1 column2 1 30 90 2 1 2 </code></pre> <p>df2:</p> <pre><code>id column1 column2 1 30 90 3 1 2 </code></pre> <p>I want to create logic that merges these two dataframes whe...
<p>First <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> DataFrames together:</p> <pre><code>df = (pd.concat([df1, df2], keys=('df1','df2')) .rename_axis(('df_name','idx')) .reset_index(level=1, drop=True) .re...
python|python-3.x|pandas|dataframe
3
373,425
53,404,662
array is (800, ) dimension, each element is (240, ) dimension, how to change to (800, 240)
<p>I have a np array which is (800,) in shape, and each element in this array is (240, ) in shape, how to reshape this array to (800, 240) dimension?</p>
<p>Try with <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.stack.html" rel="nofollow noreferrer">np.stack</a>:</p> <pre><code>np.stack(a) </code></pre>
python|numpy-ndarray
0
373,426
53,449,246
subclassing dataframe with specific columns
<p>I'm trying to create my own class of Dataframe. I would like it has some specific columns when I call it. So I do this:</p> <pre><code>from pandas import DataFrame class MyClass(DataFrame): def __init__(self): super(MyClass, self).__init__(columns=['Class','Conditions']) </code></pre> <p>Howev...
<p>If you want to use the constructor for initialization, you have to pass the arguments to parent <code>__init__</code></p> <pre><code>&gt;&gt;&gt; class MyClass(DataFrame): ...
python|pandas|class|dataframe|subclassing
3
373,427
53,609,909
Pandas - Skip number of rows given in a numpy array
<p>Consider a <code>pandas</code> dataframe, the task is to skip number of rows which are given in a <code>NumPy</code> array.</p> <p>For instance, take this example:</p> <pre><code># NumPy array arr = np.array([2, 5, 1, 3]) arr array([2, 5, 1, 3]) # Pandas dataframe df = pd.DataFrame({'num': [18, 2, 32, 8, 9, 6...
<p>Instead of dropping rows you wish to skip, consider the rows you wish to <em>keep</em>. You can do this with NumPy, utilizing <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="nofollow noreferrer"><code>np.r_</code></a> to combine slices with scalars:</p> <pre><code>idx = arr.cumsum(...
python|pandas|numpy|dataframe|indexing
4
373,428
53,730,187
Getting diagonal of a matrix in numpy and excluding an element
<p>I am trying to get the diagonal elements of a matrix, excluding one diagonal element. If I want the full diagonal elements, I know I can simply do <code>A.numpy.diagonal()</code> where <code>A</code> is a numpy square matrix to get the full array of diagonal elements. But I don't want <code>A[i][i]</code> for some <...
<p>You can achieve the same behavior as <code>diagonal</code> by just using <code>arange</code> for rows and columns. Remove the index you aren't interested in before indexing (as @hpaulj noted in the comments, practically it's faster just to find the diagonal and remove the index afterwards):</p> <hr> <p><strong><e...
python|numpy
3
373,429
53,512,375
pandas plot x data out of order?
<p>using ubuntu 18.04.1 lts python 3.6.7 matplotlib 2.1.1 pandas 0.23.4 and trying to plot the following test data on a line chart. So it should end up as a line left to right with points at 10 50 100 </p> <p><a href="https://i.stack.imgur.com/iXwsY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/...
<p>@Mr.t answered my question. I was using and old version of matplotlib 2.1.1 and the current version IS 3.0.x I applied the update to my system and BINGO!!</p> <p>pip3 install --upgrade matplotlib</p>
python|pandas|plot
0
373,430
17,488,230
Python - creating a histogram
<p>I'm using data of the form: <code>[num1,num2,..., numk]</code> (an array of integers).</p> <p>I would like to plot a histogram of a particular form, which I will use an example to describe.</p> <p>Suppose <code>data = [0,5,7,2,3]</code>. I want a histogram with:</p> <ul> <li>Bins of width 1.</li> <li>x-axis ticks...
<p>histogram usage is e.g. here:</p> <p><a href="http://matplotlib.org/examples/api/histogram_demo.html" rel="nofollow">http://matplotlib.org/examples/api/histogram_demo.html</a></p> <p><a href="http://matplotlib.org/examples/pylab_examples/histogram_demo_extended.html" rel="nofollow">http://matplotlib.org/examples/p...
python|numpy|matplotlib
1
373,431
19,952,290
How to align the bar and line in matplotlib two y-axes chart?
<p>I have a pandas df as below:</p> <pre><code>&gt;&gt;&gt; df sales net_pft sales_gr net_pft_gr STK_ID RPT_Date 600809 20120331 22.1401 4.9253 0.1824 -0.0268 20120630 38.1565 7.8684 0.3181 0.1947 20120930 52.5098 12.433...
<p>Just change the final line to:</p> <pre><code>ax2.plot(ax.get_xticks(), df[['sales_gr','net_pft_gr']].values, linestyle='-', marker='o', linewidth=2.0) </code></pre> <p>You will be all set.</p> <p><img src="https://i.stack.imgur.com/uxkFB.png" alt="enter image description here"></p> <p...
python|matplotlib|pandas
14
373,432
20,048,281
plot from a large data set into several figures
<p>I have a large set of particle position data from a movie made by a detection camera in a physical experiment. The first column just gives the frame number, the second to fourth column is x, y, and z position. Now I would like to plot the x and y position for the first 10 frames, but for each frame in a different fi...
<p><a href="http://matplotlib.org/faq/usage_faq.html" rel="nofollow">http://matplotlib.org/faq/usage_faq.html</a></p> <p>the OO interface of matplotlib allows you to keep track of where you are plotting your lines, it would be something like this:</p> <pre><code>FigList = [ ] # to store the figures for x,y in zip(g,h...
python|numpy|plot
1
373,433
19,962,228
unable to push dataframe into ipython parallel engine
<p>I pushed a pandas dataframe object of 1MM rows and 35 columns into directView of ipython parallel engine. However, I am having trouble pushing this data (or even an empty dataframe) into the engine as my function fails to print the length of the dataframe. Here is a snippet of my code. </p> <pre><code>ipcluster sta...
<p>There is a bug in IPython 0.13 that causes failed serialization of DataFrames. It is fixed in IPython 1.0, so the problem should be resolved by an upgrade. If you can't upgrade for some reason, then you will have to serialize DataFrames yourself, most easily by pickling before handing the object to IPython, and unpi...
python|pandas|ipython|dataframe|ipython-parallel
1
373,434
19,965,508
Trouble with pymc library
<p>I am trying to run the following code:</p> <pre><code>import pymc as pm alpha = 1.0/count_data.mean() #count_data is the variable that holds txtc lambda_1 = pm.Exponential("lambda_1", alpha) lambda_2 = pm.Exponential("lambda_2", alpha) tau = pm.DiscreteUniform("tau", lower=0, upper=n_count_data) </code></pre> <...
<p>I think the OP should accept the answer form Chris Fonnesbeck above. </p> <p>The PyMC installation was trying to find a numpy installation and came across the version from of numpy that shipped with OS X, thus felt it was too outdated to use. It wasn't because that version of numpy was not good - in fact, it was te...
python|numpy|pymc
0
373,435
20,154,303
Pandas read_csv expects wrong number of columns, with ragged csv file
<p>I have a csv file that has a few hundred rows and 26 columns, but the last few columns only have a value in a few rows and they are towards the middle or end of the file. When I try to read it in using read_csv() I get the following error. "ValueError: Expecting 23 columns, got 26 in row 64"</p> <p>I can't see whe...
<p>You can use <code>names</code> parameter. For example, if you have csv file like this:</p> <pre><code>1,2,1 2,3,4,2,3 1,2,3,3 1,2,3,4,5,6 </code></pre> <p>And try to read it, you'll receive and error </p> <pre><code>&gt;&gt;&gt; pd.read_csv(r'D:/Temp/tt.csv') Traceback (most recent call last): ... Expected 5 fiel...
python|csv|pandas|ragged
37
373,436
20,220,698
How to vectorize multiple levels of recursion?
<p>I am a noobie to python and numpy (and programming in general). I am trying to speed up my code as much as possible. The math involves several summations over multiple axes of a few arrays. I've attained one level of vectorization, but I can't seem to get any deeper than that and have to resort to for loops (I belie...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><em>broadcasting</em></a> to make 2d arrays from your 1d index vectors. I haven't tested these yet, but they should work:</p> <p>If you reshape the <code>N</code> to be a column vector, then <code>B1</code> will retu...
python|recursion|numpy|vectorization
2
373,437
15,890,534
Lists of tuples paired with dictionary keys, is this a good method of data classification?
<p>I am new to python, and am setting up a large dataset to work on, and wanted to check and make sure that I am doing this in the most optimized manner possible, which right now I am pretty sure I am not. I have a python dictionary that is currently set up as so. </p> <pre><code>list1 = [1,2],[3,4],[4,5] list2 = [10,...
<p>Use this list comprehension:</p> <pre><code>In [16]: [y[0] for x in listnames for y in l_dict[x]] Out[16]: [1, 3, 4, 10, 30, 50, 100, 300, 400] </code></pre> <p>Above list comprehension is equivalent to:</p> <pre><code>In [26]: lis=[] In [27]: for x in listnames: ....: for y in l_dict[x]: ....: ...
python|numpy|dictionary|dataset|list-comprehension
1
373,438
15,751,348
pivot table subtotals
<p>I have a data frame:</p> <pre><code>product = DataFrame({'_product': ['shoes','dress','cap','shoes','purse','t-shirt','t-shirt','dress','t-shirt'], 'city': ['A','A','A','B','A','A','B','C','A'], 'color':['red','black','black','white','black','green','white','yellow','blue'], ...
<p>I'm not familiar with that operation in Excel, but here're a one-liner to compute subtotals by product.</p> <pre><code>In [43]: pivot_product['subtotals'] = pivot_product[('sum', 'counter')].groupby(level=0).transform(np.sum) In [44]: pivot_product Out[44]: sum ...
python|pandas|pivot-table
1
373,439
15,903,768
Finding "gaps" in data using pandas
<p>I have data about pulications, which contain issn, year, volume and issue. So for example</p> <pre><code>1234-x000, 2013, 1, 2 1234-x000, 2013, 1, 1 1234-x000, 2012, 6, 2 1234-x000, 2012, 6, 1 1234-x000, 2012, 5, 2 .... 4321-yyyy, 2013, 2, 1 4321-yyyy, 2013, 1, 1 4321-yyyy, 2012, 12, 1 4321-yyyy, 2012, 11, 1 .... <...
<p>This isn't a full solution, for example it assumes, that the last volume is always present. But as you asked for a pointer, this should get you going:</p> <pre><code>In [28]: df Out[28]: issn year vol issue 0 1234-x000 2013 1 2 1 1234-x000 2013 1 1 2 1234-x000 2012 6 2 3 1...
python|pandas|time-series
0
373,440
15,670,482
Creating a large database from many files with pandas
<p>I have many files (~2,000,000) generated by another program that I need to extract data from. These files have common indices with a different value for different methods, I am not sure how to phrase this well so here is a three dimensional example:</p> <pre><code>[x1,y1,z1,method1] [x1,y1,z1,method2] [x2,y2,z2,met...
<p>Perhaps concat every file/frame and create a pivot table from the final DataFrame?</p> <pre><code>df1 = pd.read_csv(StringIO("""\ x,y,z,data x1,y1,z1,1 x2,y2,z2,1 """), sep=',') df2 = pd.read_csv(StringIO("""\ x,y,z,data x1,y1,z1,2 x2,y2,z2,2 """), sep=',') df3 = pd.read_csv(StringIO("""\ x,y,z,data x3,y2,z2,3 """)...
python|database|numpy|pandas
1
373,441
15,836,397
cannot get values from numpy array by name
<p>I have the following code where I'm trying to get the values in an array by the name I set.</p> <pre><code>import datetime import numpy as np import matplotlib.finance as finance import matplotlib.mlab as mlab def get_pxing(my_tickers): dt = np.dtype([('sym', np.str_, 6), ('adj_close', np.float32)]) close_...
<p>As the comments say, it seems you are appending a numpy array to a list of arrays. You really want to make a list of tuples, then convert the list of tuples into an array.</p> <p>Try something like this (the changed lines have comments)</p> <pre><code>def get_pxing(my_tickers): dt = np.dtype([('sym', np.str_,...
python|arrays|numpy
0
373,442
15,922,203
Padding large numpy arrays
<p>Another numpy array handling question: I have an approx. 2000³ entries numpy array with fixed size (that I know), containing integers. I want to pad the array with another integer, so that it's surrounded in all dimensions. This integer is fixed for the whole padding process.</p> <pre><code>example (2D) 1-----&gt;0...
<p>You can't add padding in-place because there is no room for it in the memory layout. You can go the other way though: allocate the padded array first, and use a view into it when accessing unpadded data.</p> <pre><code>padded = np.empty((2002,2002,2002)) padded[0] = 0 padded[-1] = 0 padded[:,0] = 0 padded[:,-1] = 0...
python|numpy
1
373,443
15,901,293
Fast value swapping in numpy array
<p>So, this is something, that should be pretty easy, but it seems to take an enormous amount of time for me: I have a numpy array with only two values (example 0 and 255) and I want to invert the matrix in that way, that all values swap (0 becomes 255 and vice versa). The matrices are about 2000³ entries big, so this ...
<p>In addition to @JanneKarila's and @EOL's excellent suggestions, it's worthwhile to show a more efficient approach to using a mask to do the swap. </p> <p>Using a boolean mask is more generally useful if you have a more complex comparison than simply swapping two values, but your example uses it in a sub-optimal way...
python|arrays|numpy
6
373,444
15,927,451
Filter on Pandas DataFrame with datetime columns raises error
<p>I'm setting up a DataFrame with two datetime columns like so:</p> <pre><code>range1 = Series(date_range('1/1/2011', periods=50, freq='D')) range2 = Series(date_range('2/5/2011', periods=50, freq='D')) df1 = DataFrame({'a': rng1, 'b': rng2}, dtype='datetime64[D]') </code></pre> <p>Oddly, asking the dtypes of df1...
<p>only <code>datetime64[ns]</code> dtypes are supported, try w/o the dtype</p> <pre><code>In [9]: df1 = DataFrame({'a': range1, 'b' : range2}) In [10]: df1 In [15]: df1.head() Out[15]: a b 0 2011-01-01 00:00:00 2011-02-05 00:00:00 1 2011-01-02 00:00:00 2011-02-06 00:00:00 2 ...
pandas
2
373,445
15,704,274
adding new column to pandas dataframe with values for particular items?
<p>I have this pandas dataframe:</p> <pre><code>d=pandas.DataFrame([{"a": 1}, {"a": 3, "b": 2}]) </code></pre> <p>and I'm trying to add a new column to it with non-null values only for certain rows, based on their numeric indices in the array. for example, adding a new column "c" only to the first row in <code>d</cod...
<pre><code>In [11]: df = pd.DataFrame([{"a": 1}, {"a": 3, "b": 2}]) In [12]: df['c'] = np.array(['foo',np.nan]) In [13]: df Out[13]: a b c 0 1 NaN foo 1 3 2 nan </code></pre> <p>If you were assigning a numeric value, the following would work</p> <pre><code>In [16]: df['c'] = np.nan In [17]: df.ix[0,...
python|pandas
6
373,446
15,753,916
Get dot-product of dataframe with vector, and return dataframe, in Pandas
<p>I am unable to find the entry on the method <code>dot()</code> <a href="http://pandas.pydata.org/pandas-docs/dev/api.html" rel="noreferrer">in the official documentation</a>. However the method is there and I can use it. Why is this?</p> <p>On this topic, is there a way compute an element-wise multiplication of eve...
<p><code>mul</code> is doing essentially an outer-product, while <code>dot</code> is an inner product. Let me expand on the accepted answer:</p> <pre><code>In [13]: df = pd.DataFrame({'A': [1., 1., 1., 2., 2., 2.], 'B': np.arange(1., 7.)}) In [14]: v1 = np.array([2,2,2,3,3,3]) In [15]: v2 = np.array([2,3]) In [16]...
python|pandas|dataframe|dot-product
12
373,447
12,408,826
Simplify a date in a Dataframe
<p>I'm currently working on a dataframe that has a subscription date for every members. I would like to stats subscriptions per months but default behavior would counts each dates of every month separately.</p> <p>I found a way of doing it modifying the date with slices and setting every dates day on 01 but i would ra...
<p>If your subscription date is a <code>datetime.datetime</code> instance, then you could use (untested) something like (where <code>df</code> is your <code>DataFrame</code>):</p> <pre><code>df.groupby(lambda L: (L.year, L.month)) </code></pre> <p>You'll need to adjust the groupby if the datetime isn't your DataFrame...
python|django|pandas
2
373,448
12,490,657
How can I save this matplotlib figure such that the x-axis labels are not cropped out?
<p>I am running the following snippet of code in the ipython notebook, using the <code>pandas</code> data analysis library along with <code>matplotlib.pyplot</code>.</p> <pre><code>titles = {'gradStat_p3': "P3: Gradiometers", 'magStat_p3': "P3: Magnetometers", 'gradStat_mmn': "MMN: Gradiometers", 'magStat...
<p>You can use <code>fig.tight_layout()</code>.</p> <pre><code>fig, ax = subplots(1,1,1) ax.plot(np.random.randn(5)) ax.set_xticklabels(['this is a very long label', 'b', 'c', 'd', 'e'], rotation=90) fig.tight_layout() fig.savefig('test.pdf') </code></pre>
python|matplotlib|pandas
16
373,449
72,016,514
Clarification on the insert function of panda DataFrames
<p>I have a question, I am trying to get more familiar with python and pandas and I was wondering why this does not work:</p> <p>list_features_countries = [features_AU, features_CA, features_UK, features_US, features_JP, features_DE, features_SW]</p> <pre><code>for x in list_features_countries: x = x.drop(columns=...
<p>The problem with the first variant is the parameter <code>inplace=True</code>. This means that the existing dataframe (x) is changed in place and the call <code>x.drop(... inplace=True)</code> returns None. So x is assigned None at this point, which leads to the error message in the next step.</p> <p>The solution wo...
python|pandas|dataframe|insert
1
373,450
71,853,814
How to check if a combined value of two columns exist in another dataframe in Pandas?
<p>I have multiple dfs with two common columns</p> <p>Sample df</p> <pre><code>user_id and event_date abc | 1st june abc | 2nd June cdf | 15th july dfg | 17th July </code></pre> <p>I want to check if a <code>user_id</code> on a particular <code>event_date</code> in df1 also exists in df2, df3, df4, and df5</p...
<p>I would do it following way, consider simple example:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'x':['A','B','C'],'y':[1,2,3]}) df2 = pd.DataFrame({'x':['C','A','B'],'y':[3,2,1]}) df3 = pd.DataFrame({'x':['A','B','C'],'y':[0,0,0]}) </code></pre> <p>and say you are interested in last row of <code>df1</co...
python|pandas
0
373,451
72,013,059
How to merge two dataframes for updating older one with new one?
<p>I am sorry for being a noob but I can't find a solution for my problem with hours of search.</p> <pre><code>import pandas as pd df1 = pd.read_excel('df1.xlsx') df1.set_index('time') print(df1) df2 = pd.read_excel('df2.xlsx') df2.set_index('time') print(df2) new_df = pd.merge(df1, df2,how='outer') print(new_df) d...
<p>if you perform the join as you have done all you need to do is remove the duplicate rows keeping only the more resent data, <code>drop_duplicates()</code> take the kwarg <code>subset</code> which takes a list of columns and <code>keep</code> which sets which row to keep if there are duplicates in this case we only n...
python|pandas|dataframe|merge
1
373,452
71,979,323
Fancy indexing with image
<p>I have a three channel image (color image) and I want to use fancy indexing to find pixels of a specific color and then manipulate the color value.</p> <p>Let's say I want to change every black pixel (0, 0, 0) to be blue (0, 0, 255)</p> <p>Without fancy indexing it would work like this (and it works):</p> <pre><code...
<p><code>.all()</code> reduce the whole array to 1 scalar value. In your case, you just want to reduce each pixel to a scalar (ie. to reduce values along the last axis). You can do that by specifying the axis:</p> <pre class="lang-py prettyprint-override"><code>image[(image[:, :] == (0, 0, 0)).all(axis=2)] = (0, 0, 255...
numpy|indexing
1
373,453
72,026,123
How to conditionally remove first N rows of a dataframe out of 2 dataframes
<p>I have 2 dataframes as following:</p> <pre><code>d = {'col1': [1, 2, 3, 4], 'col2': [&quot;2010-01-01&quot;, &quot;2011-01-01&quot;, &quot;2012-01-01&quot;, &quot;2013-01-01&quot;]} df = pd.DataFrame(data=d) df col1 col2 0 1 2010-01-01 1 2 2011-01-01 2 3 2012-01-01 3 4 2013-01...
<p>First get minimal <code>datetime</code> in both DataFrames and then filter all rows after this row in both <code>DataFrame</code>s (because is possible some rows are removed from <code>df1</code> or <code>df2</code>) by compare values by <code>both</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/refe...
python|python-3.x|pandas|dataframe
1
373,454
72,128,440
Sorting by two values and keeping the two highest values
<p>I have a problem. I want to create a chart. I want to show the difference between buyer <code>b</code> and seller <code>s</code>. But I want to show only the first 2 countries. Is there an option where I can filter for <code>b</code> and <code>s</code> and get the highest 2?</p> <p>Dataframe</p> <pre class="lang-py ...
<p>You first need to sort your values and then take 2 rows per group:</p> <pre><code>&gt;&gt;&gt; df.sort_values('count', ascending=False).groupby('part').head(2) count country part 3 100 BG s 0 50 DE b 5 40 BG b 2 30 CN s </code></pre>
python|pandas|dataframe|seaborn
3
373,455
71,817,874
Create a data frame that includes all dates between a range for each sku
<p>I am trying to create a data frame that includes all the dates between '1/1/2019' and '28/02/2022', for each of 3 countries and each of 9 SKUs. I am following this approach for days that is working fine:</p> <pre><code>days = pd.DataFrame(pd.date_range(start='1/1/2019', end='28/02/2022',freq='D')) for i in range(26)...
<p>Try <code>days.loc[range(0,10395),'country']= 'Austria'</code></p>
python|pandas|dataframe|loops
0
373,456
72,088,804
How to concat a list of dataframes depending on conditions
<p>I have a list of dataframes:</p> <pre><code>list_df = [df1, df2, df3, df4] </code></pre> <p>And each dataframe looks like this:</p> <pre><code>df1=pd.DataFrame([[2020-02,2020-01],['PC','PC'],[0.6,1.4],[0.5,1.3]], columns=['Date', 'platform', &quot;Day 1&quot;,&quot;Day 7&quot;]) df2=pd.DataFrame([[2020-02,2020-01],...
<p>I think you need:</p> <pre><code> pd.concat([list_df[0], list_df[2]]) pd.concat([list_df[1], list_df[3]]) </code></pre> <hr /> <pre><code>platform_list = [] for _, g in pd.concat(list_df).groupby(['platform']): platform_list.append(g) </code></pre>
python|pandas|dataframe
1
373,457
71,856,208
How do I filter pandas dataframe based on whether the groups contain a certain column value?
<p>I have the following data:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ 'encounter' : [1, 1, 1, 2, 3, 3], 'project_id' : ['A','A','A','B','C','C'], 'datetime' : ['2017-01-18','2017-01-18','2017-01-18','2019-01-18','2020-01-18','2020-01-18'], 'diagnosis' : ['F12','A11','B11'...
<p>Filter <code>diagnosis</code> for <code>F12</code> and get matched <code>encounter</code> values and then again filter original column <code>encounter</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> in <a hre...
python|pandas|filter|group-by
0
373,458
72,027,168
How to integrate a list of dictionaries in a dataframe?
<p>I have a <code>pandas</code> dataframe</p> <pre><code>ID Name Score Score_scale 1 ABC 1 5 2 DEF 2 5 3 GHI 3 5 </code></pre> <p>I need to convert it to the following format</p> <pre><code>ID Name Score 1 ABC [{'score_scale':5, 'score':1}] 2 DEF [{'score_scale':5, 'score':2}] 3 ...
<p>First idea is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>DataFrame.to_dict</code></a>, but nested lists are not created:</p> <pre><code>df['Score'] = df[['Score','Score_scale']].to_dict('records') df = df.drop('Score_scale', 1...
python|pandas|dataframe
4
373,459
71,942,617
Pandas, get all possible value combinations of length k grouped by feature
<p>I have a Pandas dataframe something like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Feature A</th> <th>Feature B</th> <th>Feature C</th> </tr> </thead> <tbody> <tr> <td>A1</td> <td>B1</td> <td>C1</td> </tr> <tr> <td>A2</td> <td>B2</td> <td>C2</td> </tr> </tbody> </table> </div> <p>...
<p>This is probably not that efficient but it works for small scale.</p> <p>First, determine the unique combinations of <code>k</code> columns.</p> <pre class="lang-py prettyprint-override"><code>from itertools import combinations k = 2 cols = list(combinations(df.columns, k)) </code></pre> <p>Then use <code>MultiIndex...
python|pandas
2
373,460
71,874,950
Ctypes and Python 3: A serious callback function problem for my project
<p>This C code shown in below, produces an output containing 7x7 float values by processing a matrix containing 7 x 3 integer values as input. (In fact, the input matrix size may be 7000 x 3. The column number is fixed but the number of rows can change)</p> <pre><code>input 1 0 0 2 1 0 3 1 2 4 0 0 5 4 0 6 4 5 7 5 6 <...
<p><code>numpy</code> arrays are two-dimensional arrays, and not arrays of pointers. Make the following changes:</p> <p>test.c</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #ifdef _WIN32 # define API __declspec(dllexport) #else # define API #endif API float...
python|c|numpy|ctypes
1
373,461
72,013,000
switch value between column based pandas
<p>I have the following data frame:</p> <pre><code> Name Age City Gender Country 0 Jane 23 NaN F London 1 Melissa 45 Nan F France 2 John 35 Nan M Toronto </code></pre> <p>I want to switch value between column based on condition:</p> <pre><code>if Country equal...
<p>I would use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>.loc</code></a> to check the rows where <code>Country</code> contains London or Toronto, then set the City column to those values and use another loc statement to replace London ...
python|pandas
1
373,462
72,028,325
Loading HuggingFace tokenizer from Dropbox (or other cloud storage)
<p>I have a classifying model, and I have nearly finished turning it into a streamlit app.</p> <p>I have the embeddings and model on dropbox. I have successfully imported the embeddings as it is one file.</p> <p>However the call for <code>AutoTokenizer.from_pretrained()</code> takes a <strong>folder</strong> path for v...
<p>To get around this, I uploaded the model to HuggingFace so I could use it there.</p> <p>I.e.</p> <pre><code>tokenizer = AutoTokenizer.from_pretrained(&quot;ScoutEU/MyModel&quot;) </code></pre>
python|huggingface-transformers
0
373,463
71,841,366
Pandas: Joining two Dataframes based on two criteria matches
<p>Hi have the following Dataframe that contains sends and open totals df_send_open:</p> <pre><code> date user_id name send open 0 2022-03-31 35 sally 50 20 1 2022-03-31 47 bob 100 55 2 2022-03-31 01 john 500 102 3 2022-03-31 45 greg 47 20 4 ...
<pre><code>merged_df1 = df_send_open.merge(df_call_cancel, how='left', on=['date', 'user_id']) merged_df2 = df_send_open.merge(df_call_cancel, how='outer', on=['date', 'user_id']).fillna(0) </code></pre> <p>This should work for your 2 cases, one left and one outer join.</p>
python|pandas|dataframe
2
373,464
71,940,457
python changing the numerical values of a string based on calculations within its own string
<p>I'm working with a dataframe with medicinal products and I have to extract the dosage out of the name (string), and later change the original product name with the reduced form of the dosage.</p> <p>Example of what I have:</p> <pre><code>Name 'Prenoxad 2mg/2ml solution for injection pre-filled syringes' </code></pre...
<p>Assuming a DataFrame as input, you can use a custom function with <code>str.replace</code>:</p> <pre><code>def simplify(m): q1, u1, q2, u2 = m.groups() q1, q2 = int(q1), int(q2) if set([u1,u2])&gt;{'mg', 'ml'}: return f'{q1}{u1}/{q2}{u2}' else: q = q1/q2 if int(q) == q: ...
python|pandas|string
1
373,465
71,947,751
LabelEncoding a permutation of combination of columns
<p>I'd like to create class labels for a permutation of two columns using <code>sklearn</code>'s <code>LabelEncoder()</code>. How do I achieve the following behavior?</p> <pre><code>import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder df = pd.read_csv(&quot;data.csv&quot;, sep=&quot;,&...
<p>You can create additional column merging values from 2 columns into one tuple. But <code>LabelEncoder</code> cannot encode the tuples, so additionally you need to get <code>hash()</code> of the tuple:</p> <pre><code>df['AB'] = df.apply(lambda row: hash((row['A'], row['B'])), axis=1) le = LabelEncoder() df['C'] = le....
python|pandas|scikit-learn|permutation|sklearn-pandas
1
373,466
71,795,358
How to accumulate single cells from repeated rows in pandas
<p>This is my first post, and after some problems I fixed them. Point was, I had a CSV which I wanted to modify, relocating a cell only when the next row is repeated, in order to accumulate the values of the repeated values in only one row. If you want to work it several times repeated, you'll have to execute it that s...
<p>I don't understand what you are trying to accomplish. Do you want to drop repeated rows or do you want to add them together/ concatenate the strings.</p> <p>It's also a bit confusing because here:</p> <pre><code>coordenada_repet = df.iloc[index_ni, 1] coordenada_intr = df.iloc[index_i, 2] </code></pre> <p>You are ge...
python|pandas|csv
0
373,467
71,886,717
Airflow upload Pandas dataframe to Redshift table
<p>I would like to use Airflow to populate a table in redshift. The data that I want to insert is in the form of a pandas dataframe, although I could write it to a csv or any other format.</p> <p>I am looking at the documentation for the <a href="https://airflow.apache.org/docs/apache-airflow-providers-amazon/2.4.0/ope...
<p>The redshift operator also defines a hook which gives you access to a SQL engine -- <a href="https://airflow.apache.org/docs/apache-airflow-providers-amazon/2.4.0/_api/airflow/providers/amazon/aws/hooks/redshift/index.html#airflow.providers.amazon.aws.hooks.redshift.RedshiftSQLHook" rel="nofollow noreferrer">https:/...
pandas|airflow|amazon-redshift
0
373,468
72,113,801
Get the position of an element in a list from a pandas dataframe column
<p>I have this dataframe:</p> <pre><code>import pandas as pd data = {'day':[18,18,19,19,20], 'tokens':[['a1','a2','a3','a3'],['a1','a2','a5','a6'],['b1','b2','b3'],['b0','b2','b3'],['c1','c2','c3']]} df = pd.DataFrame(data) </code></pre> <p>Output:</p> <pre><code> day tokens 0 18 [a1, a2, a3, a3] 1 ...
<p>You can try assign each index from the beginning and from the end to <code>postion</code> column first</p> <pre class="lang-py prettyprint-override"><code>df['position'] = df['tokens'].apply(lambda lst: list(zip(range(len(lst)), reversed(range(len(lst)))))) </code></pre> <pre><code>print(df) day token...
python|pandas|dataframe
2
373,469
71,892,802
Pad numpy array so each row is offset by one from the previous row
<p>I am trying to figure out how to pad an array using the pattern shown below:</p> <pre><code> 0000 0 000 00 00 000 0 0000 </code></pre> <p>For example:</p> <pre><code>[[1,2,3], [4,5,6], [7,8,9]] </code></pre> <p>Would become:</p> <pre><code>[[1,2,3,0,0], [0,4,5,6,0], [0,0,7,8,9]] </code></pr...
<p>AFAIK, there is no function that does directly that in Numpy. You can use a loop iterating over the rows, but this solution is inefficient unless the 2D array is huge.</p> <hr /> <h2>Numba solution</h2> <p>One solution to do this very efficiently is to use Numba and trivial loops:</p> <pre class="lang-py prettyprint...
python|numpy|multidimensional-array
3
373,470
71,940,866
Jupyter notebook stuck at plotting a tensor (Tensorflow 2) using matplotlib (CPU going 100%)
<p>I'm following a video tutorial and using matplotlib to plot a tensorflow tensor in a Jupyter Notebook. The cell just stuck and one CPU went 100%.</p> <pre><code>import tensorflow as tf import tensorflow_probability as tfp tfd = tfp.distributions tfb = tfp.bijectors import matplotlib.pyplot as plt # %matplotlib inli...
<p>Firstly, that's not a missing package problem and generally there's no problem in plotting tensors directly. For example you could have done <code>plt.plot(z)</code> without as issue. If you check <code>plt.hist</code> <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hist.html" rel="nofollow nore...
python|tensorflow|matplotlib|jupyter-notebook|tensor
0
373,471
71,799,046
model.fit gives InvalidArgumentError: Graph execution error:
<p>My code is as follows:</p> <pre><code>from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras.preprocessing.image import ImageDataGenerator #import os #os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' model = Sequential() model...
<p>You need to flatten (make sure your output is 1D) your output after the last <code>MaxPooling2D</code> layer before feeding it to your output layer and since you are using <code>categorical_crossentropy</code> as your loss function, you should use a <code>softmax</code> activation function instead of <code>sigmoid</...
python|tensorflow|keras|deep-learning|neural-network
1
373,472
71,933,000
How to use python to merge multiple sheets from an excel file and values from particular cells
<p>I have an excel file with multiple sheets, the actual data I need from each sheet is from cell B7 to F38, how can I merge all the sheets' data into one by using Python?</p>
<p>Collect the data with pandas, then concatenate the contents of the sheets (if they have the same column names) and insert the resulting dataframe somewhere (e.g. on the first sheet), see:</p> <pre><code>import xlwings as xw import pandas as pd path = r&quot;test.xlsx&quot; df_dict = pd.read_excel(path, sheet_name=...
python|excel|pandas|xlwings
0
373,473
72,026,748
How do I extract a list of lists from a Pandas DataFrame?
<p>I have a DataFrame in Pandas:</p> <pre><code>import numpy as np import pandas as pd d = {'Person': [&quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;C&quot;], 'Movies': [&quot;ET&quot;, &quot;Apollo 13&quot;, &quot;12 Angry Men&quot;, &quot;Citizen Kane&quot;]} df = pd.DataFrame(data=d) print df </code></pre> <p>I...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>print(df.groupby(&quot;Person&quot;).agg(list)[&quot;Movies&quot;].to_list()) </code></pre> <p>Prints:</p> <pre class="lang-py prettyprint-override"><code>[['ET'], ['Apollo 13', '12 Angry Men'], ['Citizen Kane']] </code></pre>
python|pandas|list
2
373,474
72,127,302
How do I drop columns in a pandas dataframe that exist in another dataframe?
<p>How do I drop columns in <code>raw_clin</code> if the same columns already exist in <code>raw_clinical_sample</code>? Using <code>isin</code> raised a <code>cannot compute isin with a duplicate axis</code> error.</p> <p>Explanation of the code:</p> <p>I want to merge <code>raw_clinical_patient</code> and <code>raw_c...
<p>You have many ways to do this.</p> <p>For example using <a href="https://pandas.pydata.org/docs/reference/api/pandas.Index.isin.html" rel="nofollow noreferrer"><code>isin</code></a>:</p> <pre><code>new_df1 = df1.loc[:, ~df1.columns.isin(df2.columns)] </code></pre> <p>or with <a href="https://pandas.pydata.org/docs/r...
pandas
0
373,475
72,028,791
Multiply two (ore more) arrays seperately with one factor in a loop - return two seperate arrays
<p>I am trying two multiply two ore more different arrays with one constant factor. For example, I have two arrays from pressure measurement in bar and want to convert every array seperately to Pa by multiplying every row by the factor 1e5. The return should be also two arrays. I thought about a for loop, but I am new ...
<p>NumPy arrays support scalar multiplication (it's a special case of broadcasting). Just directly multiply the array by the constant: <code>p1 *= 1e5</code></p> <p>If you get a <code>UFuncTypeError</code>, it means that your array datatype doesn't match the type of the constant multiplier. For example <code>a = np.arr...
python|arrays|numpy|loops
3
373,476
71,906,340
Relation between columns in pandas DataFrame
<p>Is there a way to synchronize columns in pandas.DataFrame ?</p> <p>For example, let's say I have an Inhabitant (Name, Age), City (Name, Country) and Hobby (Name, Popularity, Type ...). Inhabitant &lt;-&gt; City is [n, 1]. Inhabitant &lt;-&gt; Hobby is [n, 1]. In my example, the [n, 1] relationships are with big N (o...
<p>Here are pros and cons of two possible approaches: 3 dataframes, or 1 denormalized (monolithic) dataframe with a multi-index.</p> <p><em><strong>Separate dataframes for each logical table:</strong></em></p> <p>This is what the code using 3 separate dataframes might look like:</p> <pre class="lang-py prettyprint-over...
python|pandas|dataframe
1
373,477
72,021,614
How to I make a image from numpy array in python?
<p>I want to map each numpy array to a color to create an image. For example: if I have the numpy array: <br></p> <pre><code>[ [0 0 1 3] [0 2 4 5] [1 2 3 6] ] </code></pre> <p>I want to make an image by mapping all values below 3 to blue like</p> <pre><code>[ [blue blue sky-blue green] [blue sky-blue green green] [bl...
<p>You can make a two-color color map. Then make an array with 1 or 0 depending on your condition and pass both to <code>pyplot.imshow()</code>:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap # white and blue color = ListedColormap([(1,1,1), (0,0,1)...
python|image|numpy|matplotlib|plotly
2
373,478
72,126,834
How to place values inside stacked horizontal bar chart using python matplotlib?
<p>I want to create a stacked horizontal bar plot with values of each stack displayed inside it and the total value of the stacks just after the bar. Using python matplotlib, I could create a simple barh. My dataframe looks like below:</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;single&quot;:[168,345,34...
<p>Consider the following approach to get something similar with matplotlib only (I use matplotlib 3.5.0). Basically the job is done with <code>bar</code>/<code>barh</code> and <code>bar_label</code> combination. You may change <code>label_type</code> and add <code>padding</code> to tweak plot appearance. Also you may ...
python|pandas|matplotlib
0
373,479
71,889,357
How to take the mean of each hour for several days independently
<p>I have data taken every 15 minutes each day for a month. I want to find the mean of every hour within each day independently of the other days (so I can't group them by hours and take the mean because it will combine all the days together). <a href="https://i.stack.imgur.com/Ntl5q.png" rel="nofollow noreferrer">Here...
<p>It sounds like you want to <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling" rel="nofollow noreferrer">resample</a> to hourly. Something like <code>df.resample('H').mean()</code> should work.</p>
python|pandas|dataframe|datetime|mean
0
373,480
71,958,197
UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed
<p>I am creating Logistic Regression in Pytorch from scratch. But I am facing an issue when I am updating trainable parameters <code>Weights &amp; biases</code>. This is my implementation,</p> <pre><code>class LogisticRegression(): def __init__(self, n_iter, lr): self.n_iter = n_iter self.lr = ...
<p>Breast cancer dataset features have big range of possible values, from 0.001 to 1000, and big variances too, so it influence gradients (when gradients become too big it leads to instability and later to NaNs). To overcome such dependence it's common practice to normalize data after splitting, for example:</p> <pre><...
python|deep-learning|pytorch|logistic-regression
1
373,481
72,101,987
numpy.savetxt keeps giving an error with 2d list
<p>So I've been coding a 2d list that users can edit in python. At the end of this, I need to save the list into a txt file, then I get the error. This is the bit of code that's problematic:</p> <pre><code>tdlist = [[&quot;trash&quot;,&quot;laundry&quot;,&quot;dishes&quot;],[1,2,3]] items = numpy.array(tdlist) savelis...
<p>There are 2 problems. the format problem is only one of them. You mixed two ways of how to write content to a text file.</p> <p>Either you open the file, write to it, and close it again. Could be done like this:</p> <pre><code>tdlist = [[&quot;trash&quot;, &quot;laundry&quot;, &quot;dishes&quot;], [1, 2, 3]] items =...
python|numpy|typeerror
1
373,482
72,081,808
Optimal conditional joining of pandas dataframe
<p>I have a situation where I am trying to join <code>df_a</code> to <code>df_b</code></p> <p>In reality, these <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer"><code>dataframes</code></a> have shapes: <code>(389944, 121)</code> and <code>(1098118, 60)</code></p> <p...
<p>Use:</p> <pre><code>#for same input df_a = df_a.drop(['handle','followers','following'], axis=1) # print (df_a) #meltying df_b for column website from cols_to_join cols_to_join = ['url', 'web_addr', 'notes'] df2 = df_b.melt(id_vars=df_b.columns.difference(cols_to_join), value_name='website') #because duplicates, re...
python|pandas|join|conditional-statements
1
373,483
72,041,563
Replace column values with NaN if the value on the column next to it is not NaN
<p>I want to replace some strings in a column with NaN but only if the string on the column next to it (same row) is not NaN. (Python)</p> <p>My columns look like this:</p> <pre><code>FOLDER FILE nan 03.jpg services services services services nan 20190129_145625.jpg nan 2019012...
<p>I think you're looking for:</p> <pre><code>df.loc[~df['FOLDER'].isna(), 'FILE'] = np.nan </code></pre> <p>Output:</p> <pre><code> FOLDER FILE 0 NaN 03.jpg 1 services NaN 2 services NaN 3 NaN 20190129_145625.jpg 4 NaN 20190129_1...
python|pandas|dataframe
2
373,484
72,093,762
Explanation of Python's bwlabel,regionprops & centroid functions
<p>In Matlab there is a documentation about how to use bwlabel, region props, and centroid functions. I am wondering how we can use the same things in Python: Let's say in Matlab, we have:</p> <pre><code>[L,num] = bwlabel(img) </code></pre> <p>where L is the integer map, num tells us how many objects exist in the image...
<p>There are two issues with your code:</p> <ol> <li><p><code>shape = phi &gt;= 0</code> creates an object with a hole in it, rather than a circular object. Instead, do <code>shape = phi &lt;= 0</code>.</p> </li> <li><p><code>measure.regionprops_table()</code> has no idea of your coordinate system. All you pass in is t...
python|numpy|matlab|image-processing|scikit-image
0
373,485
72,076,842
Pandas drop rows in consecutive time range and with same pair of features
<p>I have a dataset that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;"></th> <th style="text-align: right;">id1</th> <th style="text-align: right;">id2</th> <th style="text-align: left;">time</th> </tr> </thead> <tbody> <tr> <td style="text-alig...
<pre class="lang-py prettyprint-override"><code>m = df.groupby(['id1', 'id2'], as_index=False)['time'].transform(lambda g: g.diff()).le(pd.Timedelta(minutes=5))['time'] df = df.loc[~(m | m.shift(-1))] </code></pre> <p>Step by step introduction:</p> <p>You can group by <code>id1</code> and <code>id2</code> columns and d...
python|pandas|dataframe|time
3
373,486
72,059,811
How to create a new dataframe column with a set of nested IF rules (apply is very slow)
<h2>What I need</h2> <p>I need to create new columns in pandas dataframes, based on a set of nested if statements. E.g.</p> <pre><code>if city == 'London' and income &gt; 10000: return 'group 1' elif city == 'Manchester' or city == 'Leeds': return 'group 2' elif borrower_age &gt; 50: return 'group 3' else: ...
<p>Try with <code>numpy.select</code>:</p> <pre class="lang-py prettyprint-override"><code>conditions = [df[&quot;city&quot;].eq(&quot;London&quot;) &amp; df[&quot;income&quot;].gt(10000), df[&quot;city&quot;].isin([&quot;Manchester&quot;, &quot;Leeds&quot;]), df[&quot;borrower_age&quot;].gt...
python|pandas|performance|sqlite|numba
4
373,487
72,112,695
How to solve this error in xticks(missing) of scatter plot?
<p>A scatter plot was plotted using matplotlib as below</p> <pre><code> pl.title('Test Case 2.1') pl.scatter(df2['Cross Section'],df2['Distance']) pl.xlabel('Radar cross section [dBsm]') pl.xlim([-35, -45]) pl.ylim(0, 65) pl.ylabel('Distance [m]') pl.xticks(np.arange(-35, -45,5)) pl.yti...
<p>I'm not an expert in radars, so I'm going to assume you know what you are doing. Specifically, with <code>pl.xlim([-35, -45])</code> you are setting a greater (absolute) value on the left, decreasing towards the right.</p> <p>Now, to customize the xticks you are going to use:</p> <pre><code>plt.xticks(np.flip(np.ara...
python|pandas|matplotlib
0
373,488
71,905,854
Vectorizing a Vector-Valued Function
<p>I have the following function:</p> <pre><code>def h_Y1(X, theta): EF = X[0] FF = X[1] j = X[-2] k = X[-1] W = X[2:-2] Sigma = theta[0] sigma_xi2 = theta[1] gamma_alpha = theta[2] gamma_z = np.array(theta[3:]) gW = gamma_z @ W eps1 = EF - gamma_alpha * gW if j == k: ...
<p>You can pass the full <code>gmmarray</code> as the <code>X</code> parameter. Then, instead of looping through each row of <code>gmmarray</code>, you can use vectorized operations on its columns.</p> <p>Something like this:</p> <pre><code>def h_Y1_vectorized(X, theta): EF, FF, W, j, k = np.hsplit(X, [1,2,4,5]) ...
python|numpy|vectorization
2
373,489
72,002,496
The best way to find index of point in nd array in python
<p>I am using Python3 and numpy. I have an nd array like:</p> <pre><code>arr = np.array([[1,2], [3,4],[5,6]]) </code></pre> <p>I want to find position of point for example [3,4]. I am using this</p> <pre><code>idP = [id for id in range(len(arr)) if (arr[id] == [3,4]).all()] </code></pre> <p>what is the best way to do t...
<p>You can do it by:</p> <pre><code>(arr == [3, 4]).all(-1).nonzero()[0] </code></pre> <p>or by using <code>np.isin</code>:</p> <pre><code>np.isin(arr, [3, 4]).all(1).nonzero()[0] </code></pre>
python|numpy
2
373,490
71,808,168
insert line break in python file after a fix number of elements to delimit columns in a csv file
<p>I´ve been struggling a bit to find a way in python to force this file to create a jump to a new line after some number of elements (equal to the number of columns I will need to add which is 12) the CSV currently looks like this. <a href="https://i.stack.imgur.com/GGmDC.png" rel="nofollow noreferrer"><img src="https...
<p>Here is a <code>pandas</code> + <code>numpy</code> approach.</p> <pre><code>import io import numpy as np import pandas as pd data =&quot;&quot;&quot;&quot; D276&quot;,31386,10610,12122021 00:00:47840 85,... &quot;&quot;&quot; df = pd.read_csv(io.StringIO(data), delimiter=&quot;,&quot;, quoting=3, header=None) # re...
python|pandas|csv
0
373,491
71,819,445
Interpolation of datetime data in Python numpy
<p>I have a .csv consisting of two columns, which I have imported as a numpy array. The first column is datetime data with one piece of data every month. The second column is the corresponding value for that month.</p> <p>I want to interpolate the data so as to create new datatime rows for every day and also a corres...
<p>Assuming your <code>Date</code> column is sorted and contains string (not date) values and your <code>Values</code> column contains floats, this is a way to get the interpolated value for every day between the first and last date, assuming <code>DD/MM/YYYY</code> format:</p> <pre><code>import datetime as dt df[[&qu...
python|numpy|scipy|interpolation
0
373,492
72,017,126
GeoPandas .clip() on example from the docs throws TypeError
<p>I am unable to reproduce the <code>.clip()</code>-example from the <a href="https://geopandas.org/en/stable/gallery/plot_clip.html" rel="nofollow noreferrer">GeoPandas docs</a> without error. I suspect it has something to do with my setup, since the same thing worked a few months ago in a different environment and I...
<p>This was a problem with geopandas versions.</p> <p>It turns out that <code>geopandas.GeoDataFrame.clip()</code> did not work the same way in v0.9.0. Checking the docs for the appropriate version of geopandas reveals that back then, clip was not a <code>GeoDataFrame</code>-method but a standalone one, making the solu...
jupyter-notebook|conda|geopandas
1
373,493
71,971,618
How to recombine 3d np array after element-wise operations
<p>I have an np array that looks like this:</p> <pre><code>arr = np.array([ [(1,1), (2,2), (3,3)], [(1,1), (2,2), (3,3)], [(1,1), (2,2), (3,3)] ]) </code></pre> <p>I am doing some element-wise operations which we will simplify as adding 1 to each element.</p> <p>My operations require me to break the array down as such:...
<p>First be careful with your array description:</p> <p>If I copy-n-paste your array, the resulting array displays differently:</p> <pre><code>In [29]: arr = np.array([ ...: [(1,1), (2,2), (3,3)], ...: [(1,1), (2,2), (3,3)], ...: [(1,1), (2,2), (3,3)] ...: ]) ...: In [30]: arr Out[30]: array([[[1,...
python|arrays|list|numpy
0
373,494
71,854,343
Why does Pandas Plot looks different when using csv or xlsx data?
<p>i've got two datasets with the exact same data but they look different when plotted the same way. One is a .xlsx file and one is a .csv file.</p> <p>Here are the two codes: For the CSV:</p> <pre><code>import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt import seaborn a...
<p>I had to convert the &quot;InsuredValue&quot; column to int with the following code:</p> <pre><code>daten.astype({'InsuredValue':'int'}) </code></pre>
python|pandas|dataframe|plot
0
373,495
71,810,396
How to groupby multindexed columns with Pandas while keeping the column structure?
<p>I have a dataframe with multiindexed columns I would like to group by level 0 AND 1. Duplicated columns have values I would like to sum. How can I groupby without dropping the other level ? This is what I have tried but it removes one of the level.</p> <p>Level 0 is dropped.</p> <pre><code>data.groupby(level=1, axis...
<p>you can use this, use the same groupby and set columns later using <strong><a href="https://pandas.pydata.org/docs/reference/api/pandas.MultiIndex.from_tuples.html" rel="nofollow noreferrer"><code>pd.MultiIndex.from_tuples</code></a></strong></p> <pre><code>out = df.groupby(df.columns,axis=1).sum() out.columns = pd....
python|pandas
1
373,496
72,046,528
Handwriting detection with keras : using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution
<p>I've tried to run a code example (hosted on keras.io) regarding the handwriting recognition task. While playing with the code, I faced a TensorFlow-related issue. Please see the relevant code snippet below.</p> <pre><code>def preprocess_image(image_path, img_size=(image_width, image_height)): image = tf.io.read_...
<p>the problem is from tensor flow and it can be solved by simply updating TensorFlow to latest version Also It is recommended to use python 3.5 to 3.8 with TensorFlow. useful link: <a href="https://www.tensorflow.org/install" rel="nofollow noreferrer">TensorFlow installation</a></p>
python|python-3.x|numpy|tensorflow|keras
1
373,497
72,116,739
How do I manually `predict_proba` from logistic regression model in scikit-learn?
<p>I am trying to manually predict a logistic regression model using the coefficient and intercept outputs from a scikit-learn model. However, I can't match up my probability predictions with the <code>predict_proba</code> method from the classifier.</p> <p>I have tried:</p> <pre class="lang-py prettyprint-override"><c...
<p>The <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html" rel="nofollow noreferrer">documentation</a> states that</p> <blockquote> <p>For a multi_class problem, if multi_class is set to be “multinomial” the softmax function is used to find the predicted probability ...
python|numpy|machine-learning|scikit-learn
1
373,498
71,977,731
Python: Fast way for removing black pixel in image
<p>I have an image that contains black pixels. It can be vertical lines but also simple points. I would like to replace these pixels with the average of neighboring pixels (left and right).</p> <p>The left and right neighbors of a black pixel all have a different value from black.</p> <p><a href="https://i.stack.imgur....
<p>In general, for loops on numpy arrays usually cause slowing things, and in most of cases can be avoided by numpy built-in functions. In your case, consider using convolution on the image, see as a reference: <a href="https://stackoverflow.com/questions/30068271/python-get-get-average-of-neighbours-in-matrix-with-na-...
python|numpy|performance
3
373,499
16,708,563
Plotting color pattern graph
<p>I know Stack Overflow is not a code writing service, but I am really stuck with this one and I have no clue how I can draw a map like this:</p> <p><img src="https://i.stack.imgur.com/M9Tgz.jpg" alt="enter image description here"></p> <p>Where the color code is based on the p-value; the smaller the p-value, the bri...
<p>The following script creates a plot in R. It does not exactly look like your example plot, but it can be modified.</p> <pre><code>text &lt;- "Sample1 Sample2 Sample3 Description percentage p-value Percentage p-value Percentage p-value Trendy 0.1585 0 0.1646 1.11E-016 0.2397 6.41E-014 nonTren...
python|r|numpy
1