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,200
68,594,682
pandas Wrong number of items passed 6, placement implies 1
<p>I have a df:</p> <pre><code> MinMaleTA 0 888(G2M) 1 888(AAM) 2 888(G2M) 3 888(G2M) 4 456 5 123 </code></pre> <p>I want to add a new column:</p> <p>if the df['MinMaleTA'] contains string &quot;( )&quot;,the value of the new column will be the string inside the &quot;( )&quot;.</p> <p>if the df...
<p>This error has to do with the broadcasting rules related to <code>str.extract</code>.</p> <p>When you run <code>df['MinMaleTA'].str.extract(r'\((.*)\)')</code>, you don't get a <code>pd.Series</code>, you get a <code>pd.DataFrame</code> with columns ranging from 0 to your N number of capture groups. Because you only...
python|pandas|dataframe|numpy
2
373,201
68,658,061
How to convert Python DataFrame column with Excel 5 digit date to yyyy-mm-dd
<p>I'm trying to convert an entire column containing a 5 digit date code (EX: 43390, 43599) to a normal date format. This is just to make data analysis easier, it doesn't matter which way it's formatted. In a series, the DATE column looks like this:</p> <pre><code>1 43390 2 43599 3 43605 4 ...
<p>You are calling the dataframe and assigning it to <code>date_col</code>. If you want to get the value of your first row, for example, use <code>date_col = df.iloc[0]</code>. This will return the value. Timedelta takes an integer value, not Series.</p>
python|excel|pandas|date
0
373,202
68,473,319
pandas group by but keep original index and duplicate aggregate values
<p>I have an integer indexed <code>pd.Series</code> with dtype <code>datetime64[ns]</code> called <code>timestamps</code>. (<code>timestamps</code> is sorted but this shouldn't matter)</p> <p>I would like to calculate another series called <code>first_on_day</code> with the same index and the same dtype that represents...
<p>IIUC, you want:</p> <pre><code>timestamps.groupby(timestamps.dt.date).transform(&quot;min&quot;) </code></pre>
python|pandas
1
373,203
68,603,283
Extract JSON arrays into dataframe columns
<p>I have <code>project.json</code> file, which contains data like this :</p> <pre><code>{&quot;student_id&quot;: &quot;ST0001&quot;, &quot;project&quot;: [{&quot;subject_id&quot;: &quot;S003&quot;, &quot;date_of_submission&quot;: &quot;2021-05-23 20:03:05&quot;}, {&quot;subject_id&quot;: &quot;S004&quot;, &quot;date_o...
<p>you can try with <code>record_path</code> and <code>meta</code> parameters in <code>json_normailze()</code> method:</p> <pre><code>s=pd.read_json('project.json',lines=True).melt()['value'].tolist() df=pd.json_normalize(s,record_path=['project'],meta=['student_id','project_year']) #here data is your json data </code>...
python|pandas|dataframe|json-normalize
0
373,204
68,794,330
How to calculate interdaily stability for signal in Python?
<p>I'm trying to calculate interdaily stability as a feature for machine learning classification in Python. My data is for multiple days - I'm using <a href="https://datasets.simula.no/depresjon/" rel="nofollow noreferrer">this dataset</a> (<a href="https://drive.google.com/file/d/178bPs9fkm2OmelhBOmNEv3Go0rDPmQOL/view...
<p>Looks like your implementation is correct, as i am also trying to quantify the rest-activity rhythm and using calculated score, how feasible is Modelling that time series or not.</p> <p>After, exploration, could simplify <strong>Interdaily stability</strong> quantifies how consistent the activity patterns are, given...
python|pandas|dataframe|time-series|signal-processing
1
373,205
68,859,456
Python: Variable size changed after the return statement
<p>I am trying to use word2vec embedding for a text classification task. However, it is strange that the value returned from the <code>preprocess()</code> function is different from the moment just before it was returned. Does anyone know what is wrong with my code?</p> <pre><code>train_data = [ {'corrected': 'have a...
<p>In this line you are looking for the length of <code>essays</code>:</p> <pre class="lang-py prettyprint-override"><code>print(&quot;X length:&quot; + str(len(essays))) </code></pre> <p>But, <code>X</code> is defined as:</p> <pre class="lang-py prettyprint-override"><code>X = np.vstack(padded_encoded_essays) </code><...
python|tensorflow|nlp|word2vec|dimensions
1
373,206
68,699,341
How to deploy PyTorch in Centos6?
<p>Recently, I want to run some pytorch codes on centos6. However, no matter I perform either &quot;pip install torch&quot; or &quot;conda install torch&quot;, the prompt shows:</p> <pre><code>&gt;&gt;&gt; import torch Traceback (most recent call last): File &quot;&quot;, line 1, in File &quot;XXX/anaconda3/envs/XXX/l...
<p>It's a tough one. You can either downgrade to a very old version of torch ( v0.3.1 as I remember was running ok on Centos 6.5 ), or upgrade to Centos 7. Having 2 version of glibc is hell.</p> <p>If you really need Centos 6 to live with the latest version of torch, try installing glibc into non standard location and ...
python|pytorch|centos6
1
373,207
68,806,420
Pandas uptime to datetime with resets to uptime
<p>I have a main dataframe and several small dataframes (DF_0, DF_1, ...), each one have an uptime column.</p> <p>DF_main:</p> <pre><code> (some columns) uptime 0 . 90094 1 . 90154 2 . 90214 3 . 90274 4 . ...
<p>Assuming a decrease in uptime is a sure indication of a reset, here is a general method to calculate cumulative uptime (ignoring resets and even when the logged values are irregular).</p> <pre><code>import pandas as pd def add_calc_uptime(df, t0=0): # Determine when a reset occurred: resets = df['uptime'].d...
python|pandas
0
373,208
68,567,405
Import both Pandas and Numpy?
<p>For years I've used Pandas on a daily basis and often (but not nearly as frequently) use Numpy. Most of the time I'll do something like:</p> <pre><code>import pandas as pd import numpy as np </code></pre> <p>But there is also the option of using Numpy directly from Pandas:</p> <pre><code>df['value'] = pd.np.where(d...
<p>Using <code>pd.np</code> is deprecated:</p> <pre><code>&lt;ipython-input-631-4160e33c868a&gt;:1: FutureWarning: The pandas.np module is deprecated and will be removed from pandas in a future version. Import numpy directly instead </code></pre> <p>You can check this is the same module:</p> <p><a href="https://githu...
python|pandas|numpy
4
373,209
68,821,107
pandas find all exact 4 consecutive digits from string
<p>I have a large text file that contains the text pattern, from that file I make a pandas data frame like below, from this pattern column I want to select a pattern that contains digits and the length of the <strong>consecutive digits is exactly 4</strong>.</p> <p>For example, <strong>a1234bc5678</strong> is accepted ...
<p>Following your description, you might be looking for</p> <pre><code>(?&lt;!\d)\d{4}(?!\d) </code></pre> <p>See <a href="https://regex101.com/r/AI262e/1/" rel="nofollow noreferrer"><strong>a demo on regex101.com</strong></a>.</p>
python|regex|pandas
4
373,210
68,824,151
I need to pull data from a .txt file that is inconsistent with delimters
<p>I'm currently working on pulling a data set from .txt files. The data set has two types of spacing that are not uniform or consistent. For example one row will be:</p> <pre><code>10 0 1 10 </code></pre> <p>and the next will be:</p> <pre><code>10 0 1 -10 </code></pre> <p>This is giving me errors as using <code>n...
<p>This error is due to the fact that <code>np.loadtxt</code> expects a <code>file path, not a string</code>. The file can be replaced with <code>io.StringIO</code></p> <pre><code>from io import StringIO Raw_02 = open('IEA-15-240-RWT_AeroDyn15_Polar_02.txt', 'r') Raw_02 = StringIO(Raw_02.read().replace(' -', ' -')) da...
python|pandas|numpy
1
373,211
68,565,171
Drop columns of Pandas DataFrame not working as expected
<p>I am using OneHotEncoder to impute categorical values and then removing the old columns with data type as 'object'</p> <pre><code>cv1 = (final_train.dtypes == 'object') cols1 = list(cv1[cv1].index) ohe = OneHotEncoder(handle_unknown = 'ignore', sparse=False) oh_col_train = pd.DataFrame(ohe.fit_transform(final_trai...
<p>Without looking at the rest of the code it looks like cols1 list contains all of the final_train columns.</p>
python|pandas|dataframe|one-hot-encoding
1
373,212
68,502,784
Pandas: concat with duplicated index
<p>I am trying to do <code>concentration</code> for <code>four DataFrames</code>. <code>df</code> has <code>unique index</code> and other <code>3</code> of them has <code>duplicated values</code> in <code>index</code>. Here's my code:</p> <pre><code>import pandas as pd data = {'id':['1','2','3','4','5','6'], '...
<p>IIUC, you can chain the <code>join</code> instead of using <code>concat</code> as you have duplicated index values. If you have only 3 dataframes, you can probably write it fully:</p> <pre><code>df_final = df.join(df1).join(df2).join(df3) print(df_final.head()) # name date_create likesDate dislikesDate DeleteDa...
python|pandas|dataframe|join|concatenation
1
373,213
68,829,290
installing pytorch to one conda evnironment removes existing installation from other conda environments
<p>The <code>pip</code> was installed per each environment and <code>which pip</code> returns proper(and different) location for different conda environments. I am not using any external scripts for the installation. It's vanilla <code>pip install</code> and also tried <code>python -m pip install</code>. Also tried to ...
<p>I still have no idea what is causing this behavior but at least found a workaround - using pip <code>--ignore-installed</code> option:</p> <pre><code>conda activate your_target_env pip install --ignore-installed torch torchvision torchaudio </code></pre> <p>This will not uninstall other versions of pytorch installed...
python|pip|pytorch|conda
0
373,214
68,824,268
How do you create a (sometimes) ragged array of arrays in Numpy?
<p>In Numpy, I want to create an array of integer arrays (or lists). Each individual array is a set of indices. These individual arrays generally have different lengths, but sometimes all have the same length.</p> <p>When the lengths are different, I can create the array as</p> <pre><code>test = np.array([[1,2],[1,2,...
<p>To consistently make an object dtype array, you need to initialize one of the right size, and then assign the list to it:</p> <pre><code>In [86]: res = np.empty(2, object) In [87]: res Out[87]: array([None, None], dtype=object) In [88]: res[:] = [[1,2],[1,2,3]] In [89]: res Out[89]: array([list([1, 2]), list([1, 2, ...
python|numpy
2
373,215
68,727,099
Alternatives to pandas to datetime for large dataframes?
<p>I have a 70M rows <code>dataframe</code>. There is a string field of timestamps. I want to convert them to <code>datetime[ns]</code>. Trying with <code>pd.to_datetime</code> results in 15+ minutes of wait and eventually I have to hit <code>CTRL+C</code>.</p> <p>I looked up various approaches to this in previous ques...
<p>If you are using jupyter notebook you should consider that Jupyter notebook has a default memory limit size.</p>
python|pandas|datetime
0
373,216
68,792,511
Efficient way to merge large Pandas dataframes between two dates
<p>I know there are many questions like this one but I can't seem to find the relevant answer. Let's say I have 2 data frames as follow:</p> <pre><code>df1 = pd.DataFrame( { &quot;end&quot;: [ &quot;2019-08-31&quot;, &quot;2019-08-28&quot;, &quot;2019-09-09&quot;, ...
<p>I've been working with <a href="https://stackoverflow.com/users/7836972/niv-dudovitch">niv-dudovitch</a> and <a href="https://stackoverflow.com/users/3001626/david-arenburg">david-arenburg</a> on this one, and here are our findings which I hope will be helpful to some of you out there... The core idea was to prevent...
python|python-3.x|pandas|dataframe
1
373,217
68,594,858
Automate file reading in Python
<p>I want to write a python script that automatically reads files with the following extensions (csv, tsv, json, xml, xls, xlsx, hdf5, sql) and show the first 100 lines. The only parameter I will give to my script is the path.</p> <p>This is my first try. I can use switch cases instead of if/elif for good practices but...
<p>Just to condense the fruitful comment stack into a self-contained answer.</p> <h3><code>if-elif</code> slightly condensed and converted to function</h3> <pre><code>import os import pandas as pd def read_any(file): if file.endswith('.csv', 'tsv') : df = pd.read_csv(file) elif file.endswith('.json'): ...
python|pandas
2
373,218
36,612,617
How can I convert a list of tuples into a mask?
<ul> <li><p>Imagine that I have a numpy array of shape (720, 1280): </p> <p><code>grid = np.zeros((720, 1280))</code></p></li> <li><p>And then I have a list of tuples that looks like this: </p> <p><code>x_y_pairs_to_activate = [(241, 623), (390, 143), (313, 406)]</code></p></li> </ul> <p>How can I convert that lis...
<p>You need to transpose your coordinates list so that you have all the first-coordinates in one list and all the second-coordinates in another list.</p> <pre><code>x_coords = [c[0] for c in x_y_pairs_to_activate] y_coords = [c[1] for c in x_y_pairs_to_activate] grid[x_coords, y_coords] = 1 </code></pre> <p>Or in mor...
python|numpy|tuples
2
373,219
36,504,929
Python For Loop Iteration Not In Expected Order
<p>Please take a look at the first 2 lines of the following csv file. The first line is the field names, and the second line is the first line of the actual data.</p> <p>I'm trying to iterate through the first line, and then store the values in their original order to an array.</p> <pre><code>age workclass fnlwgt ...
<p>You are reading the csv using a DictReader, which will read the CSV into .. a dict. The keys in a dictionary don't have a fixed order. Have a look at the basic reader method</p> <p><a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow">https://docs.python.org/2/library/csv.html#csv.reader</a...
python|csv|for-loop|numpy
2
373,220
36,407,436
AttributeError: 'str' object has no attribute 'to_datetime'
<p>I have a code that reads an excel data sheet (a table) into a <code>DataFrame</code> and convert a 'date' column (with values e.g. 20150508) into date time,</p> <pre><code>df['date'] = df['date'].astype(str) dates = df['date'].to_datetime() // error occurs </code></pre> <p>I got a error,</p> <pre><code>AttributeE...
<p>There is no <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a> method for <code>Series</code> only for <code>Index</code> objects it's the top-level method you want:</p> <pre><code>dates = pd.to_datetime(df['date']) </code></pre>
python|datetime|pandas|dataframe
6
373,221
36,242,881
Is it possible to train tensorflow on android?
<p>It seems no C++ API to train tensorflow graph and save to pb.So,any way to do that on Android platform? can I build tensorflow workspace with python API on Android devices?</p>
<p>Since you would need to install tensorflow on your android device and then run a python script on your android device, I highly doubt that this is possible.<br> Also, since training is always relatively resource intensive, it does not really make sense to do this on mobile devices. For most problems, you'll even wan...
android|tensorflow
0
373,222
36,525,020
How to filter NA values and add it to a new DataFrame
<p>I have an input dataset in .csv format which I am trying to input in python and do some data analysis. The sample format is given below:</p> <pre><code>col1 col2 col3 col4 col5 1 0 0 1 NA 2 3 5 1 NA 1 1 4 6 NA 7 8 9 1 1 12...
<p>Assuming that after reading it in, your col5 contains real NaNs and not the string NA, you could simply use whether or not they're null to select from <code>df</code>:</p> <pre><code>&gt;&gt;&gt; key = df["col5"].isnull() &gt;&gt;&gt; df_NA = df.loc[key] &gt;&gt;&gt; df_notNA = df.loc[~key] &gt;&gt;&gt; df_NA co...
python|numpy|pandas|dataframe|data-analysis
0
373,223
36,575,776
Data Preprocessing Python
<p>I have a DataFrame in Python and I need to preprocess my data. Which is the best method to preprocess data?, knowing that some variables have huge scale and others doesn't. Data hasn't huge deviance either. I tried with preprocessing.Scale function and it works, but I'm not sure at all if is the best method to proce...
<p>There are various techniques for data preprocessing, you can refer to the ideas in sklearn.preprocessing as potential guidelines to follow. </p> <p><a href="http://scikit-learn.org/stable/modules/preprocessing.html" rel="nofollow">http://scikit-learn.org/stable/modules/preprocessing.html</a> </p> <p>Preprocessing ...
python|pandas|machine-learning
1
373,224
36,583,308
Using scipy to calculate integral over time series data without function
<p>I have time-series data with y-values (around 6000 sample data) without the function in 13 minutes intervall in a csv file. For example: 2016-02-13 00:00:00 ; 0,353 2015-02-13 00:00:13 ; 0,362 ....</p> <p>I want integrate over the range 9 and 14 o'clock. How I can read the values from csv to a np.array(data) ?</p> ...
<p>I had a hard time handling the extra semicolon in your data with <code>np.loadtxt</code>, so here a handwritten import for your data. </p> <pre><code>%matplotlib inline import numpy as np import matplotlib.pyplot as p from matplotlib.dates import strpdate2num, num2date fn="example_data.txt" #2016-02-13 00:00:00 ; ...
python|csv|numpy|scipy
1
373,225
36,534,959
pandas reading csv file encoding error
<p>i have a iso8859-9 encoded csv file and trying to read it into a dataframe. here is the code and error I got.</p> <pre><code>iller = pd.read_csv('/Users/me/Documents/Works/map/dist.csv' ,sep=';',encoding='iso-8859-9') iller.head() </code></pre> <p>and error is </p> <pre><code>UnicodeDecodeError: 'ascii' codec can...
<p>Not possible to see what could be off with you data of course, but if you can read in the data without issues with <code>codecs</code>, then maybe an idea would be to write out the file to UTF encoding(?)</p> <pre><code>import codecs filename = '/Users/me/Documents/Works/map/dist.csv' target_filename = '/Users/me/D...
python|pandas|dataframe
0
373,226
36,366,036
Pandas concat dictionary to dataframe
<p>I have an existing dataframe and I'm trying to concatenate a dictionary where the length of the dictionary is different from the dataframe</p> <pre><code>&gt;&gt;&gt; df A B C 0 0.46324 0.32425 0.42194 1 0.10596 0.35910 0.21004 2 0.69209 0.12951 0.50186 3 0.04901 0.31203 0.11035 4...
<p>Assuming you want to add them as rows:</p> <pre><code>&gt;&gt;&gt; pd.concat([df, pd.DataFrame(test.values(), columns=df.columns)], ignore_index=True) A B C 0 0.46324 0.32425 0.42194 1 0.10596 0.35910 0.21004 2 0.69209 0.12951 0.50186 3 0.04901 0.31203 0.11035 4 0.43104 0.62413 ...
python|dictionary|pandas
5
373,227
36,343,672
Changing an array from (rows, columns) to (rows) in numpy
<p>So I have an array in numpy, python, that looks like this:</p> <pre><code>print array [[1, 2, 3, 4, 5, 6, 7]] </code></pre> <p>However, I want to change this to:</p> <pre><code>print array [1, 2, 3, 4, 5, 6, 7] </code></pre> <hr> <p>The original array was:</p> <pre><code>print array [[ 1] [ 2] [ 3] [ 4] [ ...
<p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ndarray.flatten.html" rel="nofollow">np.flatten</a> on your array:</p> <pre><code>&gt;&gt;&gt; x array([[1], [2], [3], [4], [5]]) &gt;&gt;&gt; x.flatten() array([1, 2, 3, 4, 5]) </code></pre>
python|numpy
2
373,228
36,602,988
How to 'unravel' a dataframe using the values of the rows?
<p>I have a <code>DataFrame</code> that looks like this:</p> <pre><code>class passed failed extra_teaching A11 1 2 0.5 A12 2 1 0.7 </code></pre> <p>I want to 'unravel' the <code>DataFrame</code>, and lose the information about the class ...
<p>Try:</p> <pre><code>def teaching_results(x): num_rows = x.passed.iloc[0] + x.failed.iloc[0] passed = x.passed.iloc[0] * [1] + x.failed.iloc[0] * [0] extra_teaching = num_rows * [x.extra_teaching.iloc[0]] class_code = x['class'].iloc[0] return pd.DataFrame({'pass': passed, 'extra_teaching': extra...
python|pandas
1
373,229
36,492,949
sorting a column with missing values
<p>There are 6 columns of data , 4th column has same values as the first one but some values missing, I would like to know how to sort the 4th column such that same values fall on same row using python. </p> <p>Sample data</p> <pre><code>255 12 0.1 255 12 0.1 256 13 0.1 259 15 0.15 259 15 0.15 272 18 ...
<p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>:</p> <pre><code>print df a b c d e f 0 255 12 0.10 255.0 12.0 0.10 1 256 13 0.10 259.0 15.0 0.15 2 259 15 0.15 272.0 18.0 0.12 3 272 18 0.1...
python|pandas
0
373,230
36,635,983
Pandas sum() TypeError: only length-1 arrays can be converted to Python scalars
<p>I have something like this pandas dataframe called <strong>gps</strong></p> <pre><code> a b label importe 1 x y 1 500.2 2 y z 0 300.4 3 z x 0 200.3 4 x z 2 300.6 5 y y 1 200.7 </code></pre> <p>I want to add on an array the sum of the 'importe's with same label, so:...
<p>is that what you want?</p> <pre><code>In [191]: df.groupby('label').agg({'importe':'sum'}) Out[191]: importe label 0 500.7 1 700.9 2 300.6 </code></pre> <p>or:</p> <pre><code>In [192]: df.groupby('label')['importe'].sum() Out[192]: label 0 500.7 1 700.9 2 300.6 Name: importe, ...
python|arrays|pandas|typeerror
0
373,231
5,146,025
Python/Scipy 2D Interpolation (Non-uniform Data)
<p>This is a follow-up question to my previous post: <a href="https://stackoverflow.com/questions/5124126/python-scipy-interpolation-map-coordinates">Python/Scipy Interpolation (map_coordinates)</a></p> <p>Let's say I want to interpolate over a 2d rectangular area. My variable 'z' contains the data as shown below. E...
<p>Looks like you got it. </p> <p>In your upper code example and in your previous (<a href="https://stackoverflow.com/questions/5124126/python-scipy-interpolation-map-coordinates">linked</a>) question you have <em>structured</em> data. Which can be interpolated using <code>RectBivariateSpline</code> or <code>interp2...
python|numpy|scipy|interpolation
18
373,232
5,177,137
Randomizing an array into two arrays
<p>I have a list of numbers and I need to split into to corresponding arrays of different sizes, but that make up all the combinations of the array splitting up. For example, if I have an array <code>a=[1,2,3,4,5]</code> and I want to split it to one array of size 3 and the other 2. </p> <p>So I was thinking of maki...
<p>This solution should be more efficient for large arrays, as it uses a <code>set</code> to compute the indices for the second array, and pre-allocates memory:</p> <pre><code>import scipy as sp import itertools number = sp.array([53, 64, 68, 71, 77, 82, 85]) len_number = len(number) # number of combinations ncomb =...
python|numpy|scipy
1
373,233
5,465,982
Run Fortran command line program within Python
<p>So I am in a bit of a pickle. I am trying to write plotting and fitting extensions to a Fortran77 (why this program was rewritten in F77 is a mystery too me, btw) code that requires command line input, i.e. it prompts the user for input. Currently the program uses GNUplot to plot, but the GNUplot fitting routine is ...
<p>Can't you just dump the data generated by the Fortran program to a file and then read it from python ?</p> <p>Numpy can read a binary file and treat it as a array. Going from here to matplotlib then should be a breeeze. </p>
python|numpy|scipy|fortran77
2
373,234
5,559,851
Numpy: constructing a 3D array from a 1D array
<p>Assume a 1D array <code>A</code> is given. Is there an easy way to construct a 3D array <code>B</code>, such that <code>B[i,j,k] = A[k]</code> for all i,j,k? You can assume that the shape of B is prescribed, and that <code>B.shape[2] = A.shape[0]</code>.</p>
<pre><code>&gt;&gt;&gt; k = 4 &gt;&gt;&gt; a = np.arange(k) &gt;&gt;&gt; j = 3 &gt;&gt;&gt; i = 2 &gt;&gt;&gt; np.tile(a,j*i).reshape((i,j,k)) array([[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]], [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]] </code></pre>
arrays|numpy
9
373,235
53,036,313
Tensorflow: how to detect audio direction
<p>I have a task: <strong>to determine the sound source location</strong>.</p> <p>I had some experience working with <code>tensorflow</code>, creating predictions on some simple features and datasets. I assume that for this task, there would be necessary to analyze the sound frequences and probably other related data ...
<p>This is typically done with more traditional DSP with multiple sensors. You might want to look into time difference of arrival(TDOA) and direction of arrival(DOA). Algorithms such as GCC-PHAT and MUSIC will be helpful.</p> <p>Issues that you might encounter are: DOA accuracy is function of the direct to reverberant...
tensorflow|audio|direction
3
373,236
53,263,678
Generalized method for rolling or sliding window over array axis
<p>How can I efficiently make an array of sliding windows across an arbitrary axis of a given array? For example, if I have the following array:</p> <pre><code>[[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24] [25 26 27 28 29]] </code></pre> <p>And a window size of 4, I would ...
<p>You can build such an array efficiently, in constant time and and without using any additional memory, using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.lib.stride_tricks.as_strided.html" rel="nofollow noreferrer"><code>numpy.lib.stride_tricks.as_strided</code></a>. The resulting array will b...
python|numpy|sliding-window
3
373,237
52,958,130
Pandas: replace column in dataframe by range function
<p>There is a Unique Key Column in my csv file and it has in every row the value 1. I want to replace them by real unique values (1,2,3,4,5 ....). </p> <p>I try:</p> <pre><code>data=pd.read_csv(csv_file) data['Unique Key'] = data['Unique Key'].replace(1:range(1)) </code></pre> <p>but obviously doesn't work ;(</p>
<pre><code>data['Unique Key'] = np.arange(len(data)) </code></pre> <p>each column in the <code>pd.DataFrame</code> can be replaced/ created by a numpy array of the same length.</p> <p>If you want the keys to start from <code>1</code>, you can do </p> <pre><code>data['Unique Key'] = np.arange(len(data)) + 1 </code></...
python|python-3.x|pandas|numpy
5
373,238
53,192,277
How do we apply the Central Limit Theorem using python?
<p>I've a huge dataset with 271116 rows of data. I normalized the data using the z-score normalization method. I've no idea of knowing if the data actually follows a normal distribution. So I plotted a simple density graph using matplotlib: </p> <pre><code>hdf = df['Height'].plot(kind = 'kde', stacked = False) plt.sho...
<p>Something like:</p> <pre><code>import numpy as np sampleMeans = [] for _ in range(100000): samples = df['Height'].sample(n=100) sampleMean = np.mean(samples) sampleMeans.append(sampleMean) #Now you have a list of sample means to plot - should be normally distributed </code></pre> <p>The mean of the di...
python|pandas|matplotlib|graph|data-analysis
3
373,239
52,922,401
pytorch modify array with list of indices
<p>Suppose I have a list of indices and wish to modify an existing array with this list. Currently the only way I can do this is by using a for loop as follows. Just wondering if there is a faster/ efficient way.</p> <pre><code>torch.manual_seed(0) a = torch.randn(5,3) idx = torch.Tensor([[1,2], [3,2]], dtype=torch.lo...
<p>It's quite simple</p> <pre><code>a[idx[:,0], idx[:,1]] = 1 </code></pre> <p>You can find a more general solution in <a href="https://stackoverflow.com/q/52092230/1714410">this thread</a>.</p>
python|pytorch
1
373,240
53,162,898
Adding background-color to column names and cells based on condition
<p>Is it possible to add background color to column names while also changing cell background colors based on a separate condition?</p> <p>I'm currently able to highlight cells based on a condition, but unsure how to add background color to column names:</p> <pre><code># create dataframe import pandas as pd data = ...
<p>You can use <strong>applymap(mapperFunc, subset=[ColOfInterest])</strong> on your pandas style object, it will call the mapperFunc for each value in the pandas dataframe with the values passed, optionally you can pass selective columns using subset parameter.</p> <h2>Example code:</h2> <pre><code>def color_me(percen...
python|html|pandas|dataframe|pandas-styles
0
373,241
53,193,522
Create class object with a tuple having tensorflow objects
<p>I have a parametersTheta class which creates neural network as follows:</p> <pre><code>class parametersTheta: def __init__(self, weight1, weight2,....): self.weightName1 = weight1 self.weightName2 = weight2 ... self.sess = tf.Session() def makeWorkerTheta(self, param): ...
<p>You can instantiate class with tuple expanded to arguments like this.</p> <pre><code>parametersTheta(*(weight1, weight2, ...)) </code></pre> <p>An asterisk before a tuple expand it to a corresponding arguments list.</p>
python-3.x|oop|tensorflow|low-level-api
1
373,242
53,301,292
Numpy losing precision when converting long int to float
<p>It seems <code>numpy</code> is losing precision on numpy.int64 values when converted to float types.</p> <p>My numpy version is 1.15.4 which <a href="https://github.com/numpy/numpy/pull/8903" rel="nofollow noreferrer">seemed to fix this error</a>.</p> <p>Here is an example:</p> <pre><code>&gt;&gt;&gt; value = 734...
<p>The numpy documentation (<a href="https://docs.scipy.org/doc/numpy-1.15.0/user/basics.types.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.15.0/user/basics.types.html</a>) states that the implementation of float64 only uses 52 bits for the mantissa, and 11 bits for the exponent. This is most lik...
python|numpy
2
373,243
53,075,517
Creating unconventional charts using Python Pandas
<p>I want to create the following chart in python pandas: <a href="https://i.stack.imgur.com/2Bu1r.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Bu1r.jpg" alt="enter image description here"></a></p> <p>in the Tables folder Limits.txt determines the minimum and maximum for every delta_n limit. DUT...
<p><code>matplotlib</code> and <code>bokeh</code> are better options for this. Pandas <code>plot</code> is just <code>matplotlib</code> -- <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow noreferrer">source</a></p> <p>In bokeh, you can plot the bars with <a href...
python|pandas
0
373,244
53,258,755
Frequency of repetitive position in pandas data frame
<p>Hi I am working to find out repetitive position of the following data frame:</p> <pre><code>data = pd.DataFrame() data ['league'] =['A','A','A','A','A','A','B','B','B'] data ['Team'] = ['X','X','X','Y','Y','Y','Z','Z','Z'] data ['week'] =[1,2,3,1,2,3,1,2,3] data ['position']= [1,1,2,2,2,1,2,3,4] </code></pre> <p>I w...
<p>Use <code>diff</code>, and compare against <code>0</code>:</p> <pre><code>v = df.position.diff() v[0] = 0 df['frequency'] = v.ne(0).astype(int) print(df) league Team week position frequency 0 A X 1 1 0 1 A X 2 1 0 2 A X 3 2 ...
python|pandas
1
373,245
53,206,240
merging a excel file and a text file with similar job
<p>I have an excel file that holds a data like this:</p> <pre><code>Name Job Damian Engineer Rose Musician Eric Dancer </code></pre> <p>I want to merge this with a textfile with rows with the same job:</p> <pre><code>25, Engineer 26, Dancer </code></pre> <p>So the final out put would be:</p> <pre><code>N...
<p>Try this:</p> <pre><code>In [1411]: excel_df = pd.read_excel('myexcel.xlsx') In [1412]: excel_df Out[1412]: Name Job 0 Damian Engineer 1 Rose Musician 2 Eric Dancer In [1415]: txt_df = pd.read_csv('hello.txt', header=None) In [1418]: txt_df.columns = ['Age', 'Job'] In [1419]: txt...
python|pandas|csv
1
373,246
53,277,555
Histogram bin size
<p>I have a code like this and I am wondering why my bin size of the two plotted graphs is different?</p> <pre><code>import matplotlib.pyplot as pyplot bins=15 pyplot.rcParams["figure.figsize"] = (10,10) #echte_Ladezeit pyplot.hist(Y_test, bins, alpha=1, label='Y_test; orange Dateien', color='orange', weights = np.o...
<p>Your code contains <code>pyplot.hist(..., bins, ...)</code> where <code>bins = 15</code>. This means 15 bins equally spaced between max and min values. Max and min values are different for two datasets so you get different sets of 15 bins. If you want to get bins of equal width for every dataset then you have at lea...
python|pandas|histogram
3
373,247
53,000,907
Is there a simpler and faster way to get an indexes dict in which contains the indexes of the same elements in a list or a numpy array
<p>Description:</p> <p>I have a large array with simple integers(positive and not large) like 1, 2, ..., etc. For example: [1, 1, 2, 2, 1, 2]. I want to get a dict in which use a single value from the list as the dict's key, and use the indexes list of this value as the dict's value. </p> <p>Question:</p> <p>Is ther...
<p>You can avoid iteration here using vectorized methods, in particular <code>np.unique</code> + <code>np.argsort</code>:</p> <pre><code>idx = np.argsort(a) el, c = np.unique(a, return_counts=True) out = dict(zip(el, np.split(idx, c.cumsum()[:-1]))) </code></pre> <p></p> <pre><code>{1: array([0, 1, 4], dtype=int64)...
python|arrays|numpy|indexing
2
373,248
53,265,095
Sort column in pandas dataframe after rarity of values within groups
<p>I have a pandas dataframe of scraped websites with a website identifier, a text and a label of the websites. A small number of websites have two labels, but since I want to train first a single label classifier, I would like to create a version of the data with only one label for every website (I'm aware that this i...
<p>You can achieve your goal by making the Label Column <strong>Categorical</strong>, then sort by <strong>ID</strong> and <strong>Label</strong> . Let's see it in practice.</p> <pre><code>import pandas as pd df = pd.DataFrame( {'ID': [1,1,1,2,2,3,3], "Label": ["a", "b", "a", "a", "c", "a", "b"], 'T...
python|pandas
0
373,249
53,247,361
How to do left join on several dataframe
<p>I have a several dataframes with the same name. Each dataframe has one row and two columns. One column is common in all of dataframes. I would like to left-join them together. Assuming the name of dataframes is same. I have no plan on differing their names from each other as they are so many of them and I am just pu...
<p>I believe you need for <code>left join</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with list of DataFrames by column <code>col1</code>:</p> <pre><code>dfs = [df1, df2, df3, df4] from functools import reduce df ...
python|pandas|join|left-join
0
373,250
53,133,362
Pandas Data frame group by one column whilst multiplying others
<p>I am using python with pandas imported to manipulate some data from a csv file I have. Just playing around to try and learn something new.</p> <p>I have the following data frame:</p> <p><a href="https://i.stack.imgur.com/QtcEg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QtcEg.png" alt="Imag...
<p>You can use solution without creating new column, you can multiple columns and aggregate by column <code>df['Col1']</code> with aggregate <code>sum</code>, it is <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#dataframe-column-selection-in-groupby" rel="nofollow noreferrer"><em><code>syntactic suga...
python|pandas
2
373,251
53,028,372
TensorFlow GPU failed to load/import
<p>I installed TensorFlow-GPU 1.11.0 and when I try to import it, I'm getting error. I'm stuck at this point. My system specifications are,</p> <ul> <li>Windows 10 64bit</li> <li>GeForce GTX1080 </li> <li>Graphic Driver 385.54</li> <li>Python 3.5.4</li> <li>Cuda Toolkit 9.0</li> <li>CuDNN 7.3</li> <li>Visual Studio 20...
<pre><code> pip install tensorflow --upgrade --force-reinstall </code></pre> <p>This command worked for me previously in a similar case. Hope it helps you.</p>
python|python-3.x|tensorflow|gpu
0
373,252
53,139,404
How to create cummulative sum in dataframe python?
<p>How to create cumulative sum (new_supply)in dataframe python from demand column from table </p> <pre><code>item Date supply demand A 2018-01-01 - 10 A 2018-01-02 - 15 A 2018-01-03 100 30 A 2018-01-04 - 10 A 2018-01-05 - 40 A 2018-01-06 50 50 A ...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.cumsum.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.cumsum</code></a> with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>n...
python|pandas
1
373,253
53,257,034
Pandas: Search if substring contains key in dictionary, and return value
<p>I have a dictionary (key, value) and a dataframe using pandas.</p> <pre><code>mydict = {'KULAR LUMPUR' : 'MY', 'SINGAPORE' : 'SG', 'HONG KONG' : 'HK', 'VIETNAM': 'VN'} </code></pre> <p>and a dataframe with column ['Address']</p> <pre><code> Address ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="noreferrer"><code>str.extract</code></a> by <code>regex</code> with keys of dictionary with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="noreferrer"><code>map</code><...
python|string|pandas|dictionary
5
373,254
52,936,749
What is non-concatenation axis in Pandas?
<p>I am appending a dataframe df1 to a dataframe df2 with both having the same columns but not necessarily in the same order. </p> <pre><code>df = df1.append(df2) </code></pre> <p>I am seeing this warning as a result of the above operation. </p> <p>"FutureWarning: Sorting because non-concatenation axis is not aligne...
<p>It is the other axis—the axis along which you do not concatenate. If you're concatenating along the index (axis=0), then the non-concatenation axis would be 1 (i.e., the columns), and vice versa.</p>
pandas
4
373,255
53,221,015
Pandas: Best way to remove NaN from multiple columns and convert them to int
<p>Suppose I have below CSV data:</p> <pre><code>col1,col2,col3,label ,1,2,label1 3,,4,label2 5,6,7,label3 </code></pre> <p>What is the best way to read this data and convert col1 &amp; col2 which would be float to int.</p> <p>I am able to use <a href="https://stackoverflow.com/questions/50484145/filling-nan-and-con...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="noreferrer"><code>select_dtypes</code></a> with <code>np.number</code>:</p> <pre><code>print (filter_df) col1 col2 col3 label 0 NaN 1.0 2 NaN 1 3.0 NaN 4 label2 2 5.0 6.0 ...
python|pandas
5
373,256
53,071,588
Can't figure out why I'm only getting one value from predict function?
<p>I have built and trained a sequential binary classification model using keras layers. Everything seems to work fine until I start using the <code>predict</code> method. This function starts to give me a weird exponential value rather than probabilities of the two classes. <a href="https://i.stack.imgur.com/Xdpar.png...
<p>Your model only has one output. If your training labels are set to 0 for cat and 1 for dog then that means the network thinks its a cat if the output is <code>[[2.977094e-12]]</code>. If you want the probabilities of the two classes like you were expecting then you need to change the output of your model as follows:...
python|tensorflow|neural-network|keras
2
373,257
53,285,716
Pandas, isin, column of lists
<p>Trying to make a Boolean flag that reads TRUE if one value or another is within a list. The below code is returning a FALSE for row 1 and I am not sure why, could someone help me understand why a FALSE is getting returned for the first row?</p> <pre><code>lists={'someList!':[[1,2,12,6,'ABC'],[1000,4,'z','a','bob']...
<blockquote> <p>Could someone help me understand why a FALSE is getting returned for the first row?</p> </blockquote> <p>This isn't working because <code>.isin(values)</code> returns whether each element in the Series is contained in <code>values</code>.</p> <p>You can use <code>{0, 1}</code> as a set and apply the...
pandas
1
373,258
53,234,779
Pandas dataframe: Find location where value changes from x to y
<p>I am trying to find the points in a dataframe where the data hits a max value, holds it for a time, then drops down again (See image below). </p> <p><a href="https://i.stack.imgur.com/m0McU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m0McU.png" alt="enter image description here"></a></p> <p...
<p>You will want to use the bitwise operator (<code>&amp;</code>) to combine your masks (<code>(data['ESC_Command'] == 1600) &amp; (data['ESC_Command'].shift() &lt; 1600)</code>).</p> <p><code>and</code> is the logical operator and is unable to compare series, hence the <code>ValueError</code>.</p> <hr> <p>Also, you...
python|pandas|dataframe
1
373,259
53,316,739
Assign bucket ranges in power of 2 in a separate column in pandas
<p>I have a column of values like below:</p> <pre><code>col 12 76 34 </code></pre> <p>for which I need to generate a new column with the bucket labels for <code>col1</code> as mentioned below:</p> <pre><code>col1 bucket-labels 12 8-16 76 64-128 34 32-64 </code></pre> <p>Here th...
<p>First get maximal value of power 2 by one of solution from <a href="https://stackoverflow.com/a/14267825">here</a>, create bins by list comprehension, labels by <code>zip</code> and pass it to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></...
pandas|dataframe
7
373,260
53,322,139
LSTM model does not learn a simple pattern
<p>I'm a noob in ML, and tried to write an LSTM model that will process batches of sequences and will detect the following simple pattern: If a sequence starts with an odd number then the target is 0 otherwise it is 1:</p> <p>data:</p> <pre><code>[[[ 1 2 3] [ 2 3 4] [ 3 4 5] [ 4 5 6] [ 5 6 7]] #star...
<p>According to the your comment, I would suggest to change dataset. Try something like:</p> <p>data:</p> <pre><code>[ [1, 3, 5], [2, 4, 6], [3, 5, 7] ] </code></pre> <p>target:<code>[1, 0, 1]</code></p> <p>You should try dataset with a more pronounced pattern in the sequence. In theory, LSTM should per...
python|tensorflow|machine-learning|keras|lstm
0
373,261
53,088,587
Convert max numpy array offset to a tuple?
<p>Is it possible to convert the largest numpy array offset to a tuple?</p> <p>So for example, if "array" was:</p> <pre><code>[[1 2 3 6 8], [2 4 1 1 0], [0 0 0 20 0]] </code></pre> <p>Then the np.max(array) would return 20 and it's position/ offset is array[2][3].</p> <p>Is it possible to turn array[2][3] into tu...
<p>you are looking for unravel_index and argmax</p> <pre><code>import numpy as np a = np.array([[1 2 3 6 8], [2 4 1 1 0], [0 0 0 20 0]]) np.unravel_index( a.argmax() , a.shape) </code></pre>
python|arrays|numpy
3
373,262
53,011,070
How to compare and create empty columns from file?
<p>I have a file that looks like this:</p> <pre><code>id field 1 aa 2 bb 3 cc </code></pre> <p>I have a dataframe with some columns from the above file. I want to use the file and <code>field</code> column, to see if my dataframe has that column, and if not create the column with empty string: <...
<p>Yes, read in the file and create a new dataframe.</p> <p>Assuming you start with a reference dataframe <code>df_ref</code> and a "current dataframe" <code>df</code>, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>pd.DataFram...
python|python-3.x|pandas
1
373,263
53,245,697
what is the difference between `json.loads()` and `.apply(json.loads)`?
<p>I am quite new to coding, and now I am trying to work on TMDB_5000 dataset from kaggle. </p> <p>I ran into a problem when trying to deal with json format data like this.</p> <p><code>[{"cast_id": 242, "character": "Jake Sully", "credit_id": "5602a8a7c3a3685532001c9a", "gender": 2, "id": 65731, "name": "Sam Worthin...
<p>The issue is that your <code>credits</code> variable is a Pandas <code>DataFrame</code> and so <code>credits['cast']</code> is a <code>Series</code>). The <code>json.loads</code> function doesn't know how to deal with data types from <code>pandas</code>, so you get an error when you do <code>json.loads(credits['cast...
python|pandas
2
373,264
53,178,846
My code is very slow. How to optimize it? Python
<pre><code>def function_1(arr): return [j for i in range(len(arr)) for j in range(len(arr)) if np.array(arr)[i] == np.sort(arr)[::-1][j]] </code></pre> <p>An <code>arrarr</code> array is given. It is required for each position <code>[i]</code> to find the <code>arriarri</code> element number in the <co...
<p>You are repeatedly sorting and reversing the array, but the result of that operation is independent of the current value of <code>i</code> or <code>j</code>. The simple thing to do is to pre-compute that, then use its value in the list comprehension.</p> <p>For that matter, <code>range(len(arr))</code> can also be ...
python|arrays|numpy|optimization
1
373,265
53,292,107
When using Pytorch-GPU in Anaconda, is it not necessary to install CUDA?
<p>I found that after installing Pytorch 0.4 GPU version in Anaconda, you don't need to install CUDA locally to call gpu acceleration. When running code, the GPU core can be used at more than 90%.</p> <p>Edit:I used it in Windows 10. Don't know if it works in Linux.</p>
<p>@talonmies</p> <p>Thanks for your url. It seems that pytorch don't need cuda in Windows, since its dependencies are cffi, mkl, numpy, and python.</p> <p>I entered this command <code>conda search -c pytorch pytorch=0.4.0 --info</code> in Anaconda Prompt and it says</p> <pre><code>Loading channels: done pytorch 0.4...
cuda|anaconda|pytorch
1
373,266
53,274,249
How to pad leading zeros to the Time column?
<p>Using <code>'df_dropped'</code>, a data frame, which has a column <code>'Time'</code>. </p> <pre><code>df_dropped['Time'] = df_dropped['Time'].apply(lambda x:'{:0&gt;4}'.format(x)) </code></pre> <p>I don't understand what the <code>'{:0&gt;4}'.format(x)'</code> does. Please explain the construction of this line <c...
<p>It adds 0 character to each elements of data-frame until it reach 4 character. If the element is more than 4 character will do nothing. you can see below example:</p> <pre><code>import pandas as pd df = pd.DataFrame(data=[23, "fsda", 289801, 87], columns=['Time'], index=[0, 1, 2, 3]) df['Time'] = df['Time'].apply(...
python|pandas|dataframe|data-science
2
373,267
53,266,301
Multiple SQL statements in pandas.read_sql
<p>So I have a SQL query with has the following structure:</p> <pre><code>CREATE TEMPORARY TABLE a Select id, time from t1 ; CREATE TEMPORARY TABLE b Select id, views from t2 ; Select a.id, a.time, b.views from a join b on a.id=b.id; </code></pre> <p>Which is saved in a .sql file that I want to read in pd.read_sql(...
<p>You need a "SET NOCOUNT ON" at the top of your script. This will avoid returning the empty result set for number of rows inserted by first 2 inserts.</p>
python|mysql|pandas
0
373,268
52,936,360
How to Remove Integers with Dashes from a list while keeping dashes in objects
<p>I have a list filled with the following strings:</p> <pre><code> list1 = ['01', '02', '03', '04', 05', '101-1', '101-2', 101-3', 'Name1', 'Name2', 'Name3', 'Name-4', 'Name-5', 'Name-6'] </code></pre> <p>I need to remove both the regular integers as well as the integers with dashes in them while keeping the...
<p>(Since this is tagged pandas) You can use <code>str.replace</code> + <code>str.isdigit</code>:</p> <pre><code>s = pd.Series(list1) s[~s.str.replace('-', '', regex=False).str.isdigit()] 8 Name1 9 Name2 10 Name3 11 Name-4 12 Name-5 13 Name-6 dtype: object </code></pre> <p>To get back a list, ...
python|pandas|list
4
373,269
53,059,843
Series. max and idxmax
<p>I tried to get the maximum value as well as the corresponding index of a series-object.</p> <p><code>s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])</code></p> <p>s.max() will return the maximum value whereas s.idxmax() would return the index of the maximal value. Is there a method which allows...
<p>What about a custom function? Something like</p> <pre><code>import numpy as np import pandas as pd s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) def Max_Argmax(series): # takes as input your series values = series.values # store numeric values indexes = series.index # store indexes ...
python|python-3.x|pandas
2
373,270
53,152,656
Plot a function in python
<p>I have to plot this function :</p> <p><a href="https://i.stack.imgur.com/fXJvC.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fXJvC.gif" alt="Function" /></a></p> <p>where</p> <p><a href="https://i.stack.imgur.com/R2cAZ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R2cAZ.gif"...
<p>Ok so here is what you want to do</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # for 3d plotting # constants h = 1.34e-34 m = 1.6e-19 a = 2e-9 # define our function (python standard uses lowercase for funcs/vars) def t(e, u): k2 = np.sqrt(2 * m * (e...
python|numpy|matplotlib
0
373,271
65,696,083
Is there a way to use Plotly express to show multiple subplots
<p>I'm keen to know if there is an equivalent to:</p> <pre><code>import pandas as pd import numpy as np data = pd.DataFrame({'Day':range(10), 'Temperature': np.random.rand(10), 'Wind': np.random.rand(10), 'Humidity': np.random.rand(10), ...
<p>For a plotly express solution:<br> You could use <code>pd.melt()</code> to get all your variables in the same column:</p> <pre><code>import pandas as pd import plotly.express as px df = pd.DataFrame({ 'Day':range(10), 'Temperature': np.random.rand(10), 'Wind': np.random.rand(10), 'Humidity': np.ran...
python|pandas|plotly|plotly-python|plotly-express
6
373,272
65,565,168
Pandas: Conditional joining of column from same dataframe
<p>My goal is to create an excel-vlookup equivalent in python which takes the value of the past month and places it to a new column ['new'] next to the current month.</p> <p>Given the ['id'] as key column, how can I match these two pairs with each other? It appears to me as if it is a merge (left-join) with a condition...
<p>Let us try</p> <pre><code>df['new'] = df.groupby('id').value.shift(-1) df Out[410]: id month value new 0 1 current 123 543.0 1 2 current 234 432.0 2 3 current 345 321.0 3 1 prev1 543 678.0 4 2 prev1 432 789.0 5 3 prev1 321 890.0 6 1 prev2 678 NaN ...
python|python-3.x|pandas|dataframe|numpy
1
373,273
65,756,440
Pandas new column that is sum of last N columns
<p>Using Python 3.7 &amp; Pandas, how can I create a new column that is the sum of the last N columns? There are several questions with this title (example <a href="https://stackoverflow.com/questions/64812644/pandas-create-new-column-with-the-sum-of-last-n-values-of-another-column">here</a>), but they all seem to be r...
<p>Let us try</p> <pre><code>c = df.columns df['last_2'] = df.loc[:,c[-2:]].sum(1) #df['last_3'] = df.loc[:,c[-3:]].sum(1) 0 26 1 15 2 3 3 16 4 19 5 99 6 66 7 5 8 78 dtype: int64 </code></pre>
pandas
1
373,274
65,540,837
Dataframe within a Dataframe - to create new column_
<p>For the following dataframe:</p> <pre><code>import pandas as pd df=pd.DataFrame({'list_A':[3,3,3,3,3,\ 2,2,2,2,2,2,2,4,4,4,4,4,4,4,4,4,4,4,4]}) </code></pre> <p>How can 'list_A' be manipulated to give 'list_B'?</p> <p>Desired output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th>...
<h2><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a></h2> <pre><code>df['list_B'] = df['list_A'].gt(df.groupby('list_A').cumcount()).astype(int) print(df) </code></pre> <p><strong>Output</strong></p...
pandas|list|dataframe
2
373,275
65,658,779
Going through string columns and sort cell values in Pandas
<p>Suppose we have the following dataframe:</p> <pre><code>d = {'col1':['cat; banana','kiwi; orange; apple','melon'], 'col2':['a; d; c','p; u; c','m; a'], 'col3':[4,1,4]} df= pd.DataFrame(d) </code></pre> <p>for all the string columns I want to sort the values alphabetically, I know how to do this column by col...
<p>You can use this trick (unpacking a dataframe and using <code>pd.DataFrame.assign</code>):</p> <pre><code>df.assign(**df.select_dtypes(include='object').applymap(lambda x: '; '.join(sorted(x.split('; '))))) </code></pre> <p>Output:</p> <pre><code> col1 col2 col3 0 banana; cat a; c; d ...
python|python-3.x|pandas
3
373,276
65,752,922
operation of Einstein sum of 3D matrices
<p>The following code indicates that the Einstein sum of two 3D (2x2x2) matrices is a 4D (2x2x2x2) matrix.</p> <pre><code>$ c_{ijlm} = \Sigma_k a_{i,j,k}b_{k,l,m} $ $ c_{0,0,0,0} = \Sigma_k a_{0,0,k}b_{k,0,0} = 1x9 + 5x11 = 64 $ </code></pre> <p>But, c_{0,0,0,0} = 35 according to the result below:</p> <pre><code>&gt;...
<p>The particular element that you are testing, [0,0,0,0] is calculated with:</p> <pre><code>In [167]: a[0,0,:]*b[:,0,0] Out[167]: array([ 9, 26]) In [168]: a[0,0,:] Out[168]: array([1, 2]) In [169]: b[:,0,0] Out[169]: array([ 9, 13]) </code></pre> <p>It may be easier to understand if we reshape both arrays to 2d:</p> ...
numpy|numpy-einsum
1
373,277
65,780,026
Iterating over a df in chunks, based on index
<p>I have the following df:</p> <pre><code>dff=pd.DataFrame(index=[1]*10+[2]*10,data={'mth':list(range(1,11))*2,'pmt':[10,5,3,10,20,4,1,6,5,6]*2,'min_pmt':[5]*10+[4]*10,'Stat':[np.nan]*20,'up':[np.nan]*20,'up_cum':[np.nan]*20}) </code></pre> <p>I have in it 2 different values in the index: customer 1 and customer 2, an...
<p>I would get rid of slicing to save some time. Note that the only rolling parameters are <code>up_cum</code> and <code>f</code>, and I would store them in a dictionary.</p> <pre><code>rolling = dict() # key=customer label, value=(current value of up_cum, value of f) for r, (j,row) in enumerate(dff.iterrows()): u...
python|pandas|for-loop|iteration
1
373,278
65,511,061
wordlcoud from pandas series
<p>I want to create a wordcloud from a pandas dataframe, but only from one column &quot;Finish the sentence: I buy knifes for... (collection, hunting, fun,, safety,..., etc.).</p> <p><a href="https://i.stack.imgur.com/Gl2hS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gl2hS.png" alt="enter image d...
<p>First turn your column into a list</p> <pre><code>words = list(moreuses.values()) </code></pre> <p>Then join the values</p> <pre><code>string_of_words = &quot; &quot;.join(words) </code></pre> <p>Then generate your word cloud</p> <pre><code>wordcloud = WordCloud().generate(string_of_words) </code></pre> <p>Note: Unt...
python|pandas|dataframe|series
1
373,279
65,743,423
Python Regex for a Specific Word
<p>I have the below texts in a column called actions.</p> <pre><code>&quot;Why don't you clean this table : J$CLAB&quot; &quot;http(&quot;J$MANG.create&quot;): 21/01/06 23:24:05 INFO&quot; </code></pre> <p>i would like to extract the words that start with J$... till the end. e.g. J$MANG &amp; add it in a new column.</p...
<p>You can use</p> <pre><code>file['fileName'] = file['action'].str.extract(r'\b(J\$\w*)', expand=False) </code></pre> <p>See the <a href="https://regex101.com/r/5n0dLd/1" rel="nofollow noreferrer">regex demo</a></p> <p><em>Details</em>:</p> <ul> <li><code>\b</code> - a word boundary</li> <li><code>(J\$\w*)</code> ...
python|python-3.x|regex|pandas|extract
1
373,280
65,907,736
Pandas: transform complex numbers column into modulus and argument columns
<h2>Situation</h2> <p>Consider the following example dataframe containing complex numbers:</p> <pre><code>data = [ [np.complex(+1.15208050, -2.48857386), np.complex(-0.85295162, +0.10011025), np.complex(-0.61440517, -1.15813006)], [np.complex(-1.36170542, -0.78118157), np.complex(+1.10912405, +0.87261775), np.c...
<p>Try:</p> <pre><code>df.agg([np.abs, np.angle]) </code></pre> <p>Output (argument is in radiant, you can convert to degree easily)</p> <pre><code> A B C absolute angle absolute angle absolute angle 0 2.742315 -1.137227 0.858806 3.024758 1.311...
pandas|dataframe|numpy|complex-numbers
2
373,281
65,802,059
Pandas Ignore Non-Date Values
<p>I have a column containing a few non-date values but mostly dates.... The non-date values are either blank or '???' strings. I am trying to find the difference between today's date and the listed date but I am getting the following error. How would I adjust this to ignore the non-date values?</p> <p>Error:</p> <pre>...
<p>Let us convert to date first</p> <pre><code>bridge['First Date'] = pd.to_datetime(bridge['First Date'], errors = 'coerce') </code></pre>
python|pandas
3
373,282
65,897,751
Pandas: Sampling columns based on weights
<p>I have a pandas data frame with three columns containing probabilities:</p> <pre><code>Prob0 Prob1 Prob2 0.1 0.6 0.3 0.2 0.1 0.7 </code></pre> <p>I need to generate a column that contains, for each row, the value 0 with probability Prob0, the value 1 with probability Prob1 and the value 2 with probabilit...
<p>Hope I got your point.</p> <p>Sicne I have no information about your factors, I followed your descprition and put 0, 1 and 0.5.</p> <p>Here are three options to create this:</p> <p><strong>Using <code>dot()</code></strong> recommended</p> <pre><code>weights = [0,1,0.5] df['ChoiceProba'] = df.dot(weights) </code></pr...
python|pandas
0
373,283
65,761,728
Learning rate finder for CNNLstm model
<p>I have CNNLstm model as follows.</p> <pre><code> class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d( in_channels=3, out_channels=16, kernel_size=5, ...
<p>One possibility is that instead of expanding the dims in the for loop you could pass the tensor into the forward function of the model and just use .unsqueeze(1) there. Like this</p> <pre><code> print(data.shape) print(data.shape) data = torch.FloatTensor(data) </code><...
pytorch|learning-rate|pytorch-dataloader
0
373,284
65,624,968
can i overriding tesorflow serving method?
<p>I want simply receives text input and tries to return only the label value among the predicted results.</p> <p>Ex. curl -d '{&quot;inputs&quot;:{&quot;test&quot;: [&quot;I am very sad today&quot;]}}' <br /> -X POST http://{location}:predict</p> <p>and I want to get the return value &quot;sad&quot;</p> <p>so I saw <a...
<p>Tensorflow serving via the saved model seems to only provide inference. Therefore, i will have to configure the logic separately by building the server and REST API.</p>
tensorflow|tensorflow-serving
0
373,285
65,796,364
Pandas Dataframe multiple rows with same index
<p>I have a dictionary that looks like this:</p> <pre><code>dict = { &quot;A&quot;: [1,2,3], &quot;B&quot;: [4] } </code></pre> <p>when I try to create a panda Dataframe I use:</p> <p><code>output_df = pd.DataFrame.from_dict(dict, orient='index')</code></p> <p>Output:</p> <div class="s-table-container"> <table clas...
<p>try:</p> <pre><code>df.stack().swaplevel(0,1) </code></pre> <hr /> <pre><code>1 A 1.0 2 A 2.0 3 A 3.0 1 B 4.0 dtype: float64 </code></pre> <hr /> <pre><code>df.stack().swaplevel(0,1).reset_index(level=[1], name='a').reset_index(drop=True) </code></pre> <hr /> <pre><code> level_1 a 0 A ...
python|pandas|dataframe
1
373,286
65,508,791
extracting images and their label one by one from ImageDataGenerator().flow_from_directory
<p>so I imported my dataset(38 classes) for validation using ImageDataGenerator().flow_from_directory</p> <pre><code>valid = ImageDataGenerator().flow_from_directory(directory=&quot;dataset/valid&quot;, target_size=(224,224)) </code></pre> <p>and i wanted to pick each image and its label one by one. For example i want ...
<p>The <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator#flow_from_directory" rel="nofollow noreferrer">documentation</a> might help you with this question. More specifically, the default arguments from <code>tf.keras.ImageDataGenerator.flow_from_directory</code>:</p> <...
python|tensorflow|keras|dataset
0
373,287
65,890,304
Looping Through List And applying to rows in DataFrame where Filter is matched
<p>I am trying to figure out how I can loop through a list of dictionary values and apply the values of dictionaries to the rows in my dataframe that match specific filter conditions. At the moment I tried to solve for this by creating a function with the dataframe and list. Within that function I loop through the list...
<p>It's not necessary to use <code>apply</code>, assign column 'perc' with the refer publish's <code>day_zero_purchase_perc</code>. Then use condition to filter which row to apply.</p> <pre><code>day_zero_purchase_perc = [ {'Facebook': 0.950920245}, {'Google': 0.147138229}, {'Other': 0.187124464} ] benc...
python|pandas
0
373,288
65,581,853
Interpreting the output of a DNN using binary cross entropy as loss
<p>I have a Tensorflow image classification DNN that uses binary crossentropy as its loss and the corresponding label mode binary in the tf.keras.preprocessing.image_dataset_from_directory call. When i train the model and run inference on images the predictions outputs are something like [[-3.5601902]] or [[2.1026382]]...
<p>It is a bit confusing what you are trying to achieve.</p> <p>If you are doing a binary classification ( which I believe you are ), the size of your output layer should not be 'num_classes', it should be 1 with a sigmod for activation function. if you did that, the output 'p' would be the probability of class 1 and 1...
python|tensorflow|machine-learning
0
373,289
65,582,277
Generate multiple line.set_ydata using for cycle (python)
<p>First of all, this is my 1st post in this forum. Usually, I am able to solve my problem by looking into posts in this forum, but in this case, I couldn't find the information. Thank you in advance for your support.</p> <p>I am trying to plot data (voltage and temperature) from multiple ICs of one PCB board. At the ...
<p>Consider storing the lines in an array. Python has some nice list comprehension syntax which would greatly reduce your code size.</p> <p>I would split it into two arrays, one for <code>temp</code> and one for <code>volt</code>.</p> <p>For creating the lines you could do something like this:</p> <pre><code>temp_lines...
python|python-3.x|numpy|matplotlib|animation
0
373,290
65,888,280
Can’t import numpy from an installed jupyter kernel
<p>I have jupyterlab installed in my base conda env. Now, I created another evn and installed its kernel using kernelspec. But, when I attach a notebook to this kernel and try to import numpy, I get DLL load failed while importing _multiarray_umath error.</p> <p>Steps to reproduce the error:</p> <ol> <li><p>Install jup...
<p>I figured it out, I just had to set &quot;CONDA_DLL_SEARCH_MODIFICATION_ENABLE&quot; env variable in the kernel.json as mentioned in <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/troubleshooting.html" rel="nofollow noreferrer">Conda Troubleshooting</a></p>
numpy|jupyter-notebook|jupyter-lab
1
373,291
65,710,149
What is a tensor argument to Normal supposed to mean in Distributions Package of Pytorch?
<p>I understand <code>torch.Normal(loc, scale)</code> is a class corresponding to univariate normal distribution in pytorch. I understand how it works when loc and scale are numbers. The problem is when the inputs to torch.Normal are tensors as opposed to numbers. In that case I do not understand it well. What is the e...
<p>As you said, if <code>loc</code> (<em>a.k.a.</em> <code>mu</code>) and <code>scale</code> (<em>a.k.a.</em> <code>sigma</code>) are floats then it will sample from a <a href="https://en.wikipedia.org/wiki/Normal_distribution" rel="nofollow noreferrer"><strong>normal distribution</strong></a>, with <code>loc</code> as...
python|pytorch|distribution|normal-distribution
0
373,292
65,879,049
MultiOutput Classification with TensorFlow Extended (TFX)
<p>I'm quite new to TFX (TensorFlow Extended), and have been going through the sample <a href="https://www.tensorflow.org/tfx/tutorials/tfx/components_keras#top_of_page" rel="nofollow noreferrer">tutorial</a> on the TensorFlow portal to understand a bit more to apply it to my dataset.</p> <p>In my scenario, instead of ...
<p>Since the label key is optional, maybe instead of specifying it in the TensorflowDatasetOptions, instead you can use <code>dataset.map</code> afterwards and pass both labels after taking them from your dataset.</p> <p>Haven't tested it but something like:</p> <pre class="lang-py prettyprint-override"><code>def _data...
python-3.x|tensorflow|machine-learning|tf.keras|tfx
0
373,293
65,863,819
Tensorflow 2.4 - DLL load failed while importing _pywrap_tensorflow_internal
<p>I use TensorFlow 2.4 on Windows 10 with Python 3.8 (I have Python 3.9 and 3.6 installed too) within a virtual environment <code>ml2u</code> where only TensorFlow 2.4 is installed so far by <code>pip install tensorflow</code>. I get the error messages below by trying to import TensorFlow in a notebook. As recommended...
<p>You might be facing this issue because you are running 32-bit python or 32-bit OS. And also check does your CPU supports AVX instructions.</p> <p>Please take a look at <a href="https://www.tensorflow.org/install/pip#system-requirements" rel="nofollow noreferrer">system requirements</a> and check if you have correct ...
python|c++|python-3.x|tensorflow|dll
0
373,294
65,728,589
Returning filtered dataframe after grouping by counts with a condition
<p>The title is not that explanatory so it's better to describe it. I have a dataframe like this one with 5 columns. The first is an Id the other are attributes. Lke the one displayed below:</p> <pre><code>data = {'id':[5748, 9090, 3627, ....., 9090], 'Attibute1':[val11, val12, val13, .....,val1400000], 'Attib...
<p>Subset using a mask created by <code>transform</code> + <code>count</code>, which broadcasts that groups counts back to every row in the original DtaFrame.</p> <pre><code>gp_cols = ['Attibute1', 'Attibute2', 'Attibute3'] df = df[df.groupby(gp_cols)['id'].transform('count').ge(15)] </code></pre>
python|pandas|pandas-groupby
0
373,295
65,804,051
How do I convert the following in tensorflow version 2
<pre><code>%tensorflow_version 1.x import tensorflow as tf print(tensorflow.__version__) w = tf.Variable(0, dtype = tf.float32) cost = w**2 - 8*w + 16 train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost) init = tf.global_variables_initializer() session = tf.Session() session.run(init) for i in r...
<p>Several changes from TF1 to TF2:</p> <ul> <li>Optimizers are now in the <code>keras</code> module, but there is an alias <code>tf.optimizers</code> that can be used. <code>GradientDescentOptimizer</code> can be replaced by <code>SGD</code> without momentum</li> <li>Session object are not used anymore. Instead, the d...
python-3.x|tensorflow
0
373,296
65,618,577
Sum using loop in python
<p>I have a dataframe and specifically need to find the min, max, and average of the age column using loops. However, try as I might. It just did not work. I hope somebody could help me see where the problem is. Thank you.</p> <p>Here is my code</p> <pre><code>total_age = 0 i=0 max_amount = adult_data[&quot;age&quot;...
<p>The commas at the end of statements indicate <em>tuples</em>. For example, <code>i = i + 1,</code>is the same as <code>i = (i + 1,)</code>, where <code>(i + 1,)</code> is a tuple with one element.</p> <p>So, your code is essentially the same as:</p> <pre><code>for i in range(len(adult_data[&quot;age&quot;])): to...
python|pandas|dataframe
1
373,297
65,561,736
Access multiple items of list
<p>Im currently trying to implement a replay buffer, in which i store 20 numbers in a list and then want to sample 5 of these numbers randomly.</p> <p>I tried the following with numpy arrays:</p> <pre><code>ac = np.zeros(20, dtype=np.int32) for i in range(20): ac[i] = i+1 batch = np.random.choice(20, 5, replace=F...
<p>For a list it is quite easy. Just use the sample function from the random module:</p> <pre><code>import random ac = [i+1 for i in range(20)] sample = random.sample(ac, 5) </code></pre> <p>Also on a side note: When you want to create a numpy array with a range of numbers, you don't have to create an array with zeros...
python|arrays|list|numpy
0
373,298
65,841,249
Python 3D-1D Array multiplication
<p>Alright, so i want to multiply a 3D array and 1D array together and then do summation like in the example below</p> <pre><code>A = [Array([[[100, 100, 100], [100, 100, 100]], [[100, 100, 100], [100, 100, 100]]]), Array([[[200, 200, 200], [200, 200, 200]], ...
<p>Try:</p> <pre><code>A = np.array([np.array([[[100, 100, 100], [100, 100, 100]], [[100, 100, 100], [100, 100, 100]]]), np.array([[[200, 200, 200], [200, 200, 200]], [[200, 200, 200], [200, 200, 200]]])]) Weight = np.array([0.25,0.75]) </...
python|arrays|numpy|multidimensional-array
0
373,299
65,780,011
OSMNX KeyError: 'x' when trying to get_nearest_nodes()
<p>I currently have a process where I</p> <ol> <li>Download Open Street data using ox.geocode_to_gdf()</li> <li>Get the Geopackage edges and nodes using and use gpd.overlay() to edit the edges and nodes based on another map</li> <li>Convert edited edges back to OSMNX as a graph using ox.graph_from_gdfs()</li> </ol> <p>...
<p>I fixed the error by passing the method argument to the get_nearest_nodes(). If you chose the 'kdtree' as the method, you will not have the error.</p> <pre><code>nodes_flood = ox.distance.get_nearest_nodes(g_post_200_Cur_centre, Easting, Northing, method='kdtree') </code></pre> <p>However, I still don't know the rea...
python|geopandas|osmnx
0