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
3,600
53,323,388
Pandas - Pipe Delimiter exists in Field Value causing Bad Lines
<p>I am using Pandas to import a text file like so:</p> <pre><code>data = pd.read_csv('filepath.txt', sep='|', quoting=3, error_bad_lines=False, encoding='latin1', low_memory=False) </code></pre> <p>I'm getting an error on 1 line because the field value has a Pipe found within it. When it attempt...
<p>I think the easiest way would be to remove any instance of "||" then use pandas. An example of this would be:</p> <pre><code>import pandas as pd from io import StringIO buffer= StringIO() with open(r'filepath.txt', 'r') as f: for line in f.readlines(): if "||" not in line: buffer.write(lin...
python|pandas
0
3,601
52,910,283
Drop the index position of a second array based on the first
<p>I am trying to program this in python. Suppose I have the arrays:</p> <p>A = [0, 1, 1, 1, 1, 2, 2, 3]</p> <p>B = ['A', 'A', 'A', 'E', 'E', 'D', 'D', 'C']</p> <p>I want to drop the corresponding element in array B, based on the index position of the dropped element in A. For example, if I drop 0 in A:</p> <p>A = ...
<p>In python, there are some arrays such as in numpy but these elements you pointed are lists, you can delete these elements using the del operator and if you want to do that in an automated manner you can build a function to compute it properly, such as:</p> <pre><code>def removeFromBothLists(a, b, idx): del a[id...
python|numpy
2
3,602
53,147,045
convert time (without date) to Matplotlib num with date2num()
<p>I have a dataframe df like this:</p> <p><a href="https://i.stack.imgur.com/NOOIs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NOOIs.png" alt="enter image description here"></a></p> <pre><code> datetime duration 0 2018-10-08 13:30:00 03:00 1 2018-10-08 16:40:00 00:11 ...
<p>Guess your duration format is %H:%M. first of all, change your column format to datetime. </p> <pre><code>import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, date2num df['datetime'] = pd.to_datetime(df.datetime) df["duration"] = pd.to_datetime(df["duration"],format="%H:%...
python|pandas|matplotlib
0
3,603
65,777,425
replacing special characters in a numpy array with blanks
<p>I have a list of lists (see below) which has ? where a value is missing:</p> <pre><code>([[1,2,3,4], [5,6,7,8], [9,?,11,12]]) </code></pre> <p>I want to convert this to a numpy array using np.array(test), however, the ? value is causing an issue. What I want to do is replace the ? with blank space '' and then co...
<p>Use list comprehension:</p> <pre><code>matrix = ... new_matrix = [[&quot;&quot; if not isinstance(x,int) else x for x in sublist] for sublist in matrix] </code></pre>
python|arrays|numpy|special-characters
2
3,604
65,699,661
Pandas Dataframe: Removing rows but they are still in value_counts()
<p>I have this dataframe train_info with a column artist.</p> <p>I decided to remove the rows corresponding to the artists from this list:</p> <pre class="lang-py prettyprint-override"><code>lst = [&quot;Alekos Kontopoulos&quot;, &quot;James Ward&quot;] </code></pre> <p>After removing them i check that there are no rec...
<p>It seems some whitespaces, so first remove them:</p> <pre><code>train_info.artist = train_info.artist.str.strip() </code></pre> <p>And then for remove rows with values in list <code>lst</code> use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><c...
python|pandas|dataframe|machine-learning
1
3,605
65,599,445
Mentioning cell where Pandas Dataframe gets inserted in Google Sheet
<p>I have a data frame of 100 rows that I am trying to split into multiple Dataframes as per the below code:</p> <pre><code>for m in df['month'].unique(): temp = 'df_{}'.format(m) vars()[temp] = finance_metrics[df['month']==m] </code></pre> <p>This gives me 5 new Dataframes as below:</p> <pre><code>df_January ...
<p>This should work. You can pass cell address as a tuple too.</p> <pre><code>offset = 0 for m in df['month'].unique(): temp = finance_metrics[df['month']==m] wks.set_dataframe(temp, (4+offset, 1)) offset += len(temp) </code></pre>
pandas|google-sheets|pygsheets
0
3,606
65,848,733
variables changing after a function call in python
<p>Ive been working on some code recently for a project in python and im confused by the output im getting from this code</p> <pre><code>def sigmoid(input_matrix): rows = input_matrix.shape[0] columns = input_matrix.shape[1] for i in range(0,rows): for j in range(0,columns): input_matrix...
<p>Inside <code>sigmoid</code>, you're changing the value of the matrix passed as parameter, in this line:</p> <pre><code>input_matrix[i,j] = ... </code></pre> <p>If you want to prevent this from happening, create a copy of the matrix before calling <code>sigmoid</code>, and call it like this: <code>sigmoid(copy_of_wei...
python|function|numpy
1
3,607
65,644,796
How to delete a row if value include plural form of the words?
<p>Delete a row if value include the plural form of the words and only if exists the single form of word too, for example DataFrame contains 'test' and 'tests' or 'company' and 'companies', that is will be delete 'tests' and 'companies'. And next I want to apply another rules word formation <a href="https://www.crownac...
<p>How about:</p> <pre><code>import nltk nltk.download('wordnet') from nltk.stem import WordNetLemmatizer wnl = WordNetLemmatizer() d0 = [{'word':'test', 'count':22}, {'word':'tests', 'count':11},{'word':'company', 'count':2},{'word':'companies', 'count':5}, {'word':'debris', 'count':5}] def not_plural(word):...
pandas|parsing
1
3,608
65,566,325
Sentence comparison: how to highlight differences
<p>I have the following sequences of strings within a column in pandas:</p> <pre><code>SEQ An empty world So the word is So word is No word is </code></pre> <p>I can check the similarity using fuzzywuzzy or cosine distance. However I would like to know how to get information about the word which changes position from a...
<p>Assuming you're using jupyter / ipython and you are just interested in comparisons between a row and that preceding it I would do something like this.</p> <p>The general concept is:</p> <ul> <li>find shared tokens between the two strings (by splitting on ' ' and finding the intersection of two sets).</li> <li>apply ...
python|pandas|cosine-similarity|fuzzywuzzy|sentence-similarity
2
3,609
65,627,665
Rewritning if condition to speed up in python
<p>I have following piece of code with if statement within a function. When I run it would take long time and it is a way to rewrite if condition or a way to speed up this sample code?</p> <pre><code>import numpy as np def func(S, R, H): ST = S * R if ST &lt;= - H: result = - H elif ST &gt;= - H and...
<p>If you want your functions parameters still available you would need to use boolean indexing in a creative way and replace your function with that:</p> <pre><code>from time import time import numpy as np ran = np.arange(-10, 10, 1) s = 2 r = 3 st = s * r def func(S, R, H): ST = S * R if ST &lt;= - H: ...
python|python-3.x|numpy|if-statement|cpu-speed
2
3,610
2,831,516
"isnotnan" functionality in numpy, can this be more pythonic?
<p>I need a function that returns non-NaN values from an array. Currently I am doing it this way:</p> <pre><code>&gt;&gt;&gt; a = np.array([np.nan, 1, 2]) &gt;&gt;&gt; a array([ NaN, 1., 2.]) &gt;&gt;&gt; np.invert(np.isnan(a)) array([False, True, True], dtype=bool) &gt;&gt;&gt; a[np.invert(np.isnan(a))] array...
<pre><code>a = a[~np.isnan(a)] </code></pre>
arrays|numpy|python|nan
172
3,611
63,524,400
Export a pandas data frame into a csv file ('list' object has no attribute 'to_csv')
<p>Hello I'm trying to export a pandas dataframe in a csv file but I got no clue how to do it. And I got this error 'list' object has no attribute 'to_csv'</p> <pre><code> import pandas pandas.set_option('display.max_rows', None) pandas.set_option('display.max_columns', None) pandas.set_option('display.width', None) pa...
<p>You have a list of dataframes instead of the dataframe. You can either to save each one of them using <code>.to_csv()</code> method or use <code>pd.concat(player_results, axis=0)</code> to concatenate them and then save it.</p>
python|pandas|dataframe|export-to-csv
1
3,612
24,709,108
Python pandas, How could I read excel file without column label and then insert column label?
<p>I have lists which I want to insert it as column labels. But when I use read_excel of pandas, they always consider 0th row as column label. How could I read the file as pandas dataframe and then put the list as column label</p> <pre><code> orig_index = pd.read_excel(basic_info, sheetname = 'KI12E00') 0.619159...
<p>Pass <code>header=None</code> to tell it there isn't a header, and you can pass a list in <code>names</code> to tell it what you want to use at the same time. (Note that you're missing a column name in your example; I'm assuming that's accidental.) </p> <p>For example:</p> <pre><code>&gt;&gt;&gt; df = pd.read_ex...
excel|pandas
46
3,613
24,877,871
Python error importing module pandas "name 'GET' is not defined"
<p>I have the most updated numpy, httplib2, pytz, Cython, python-dateutil &amp; numexpr</p> <p>And newest pandas build</p> <p>But I'm flummoxed! The following code gives the following rather cryptic error. What is it trying to tell me?</p> <pre><code>import pandas print "ok pandas" </code></pre> <p>error:</p> <pre...
<p><em>Solution by furas and OP.</em></p> <p>I had an old file called <code>google.py</code>. Just renamed/deleted it and problem was solved.</p> <p>Probably python uses this file when it imports <code>from google.appengine.api</code>.</p>
python|pandas|installation|package
0
3,614
53,596,692
Pandas: after slicing along specific columns, get "values" without returning entire dataframe
<p>Here is what is happening: </p> <pre><code>df = pd.read_csv('data') important_region = df[df.columns.get_loc('A'):df.columns.get_loc('C')] important_region_arr = important_region.values print(important_region_arr) </code></pre> <p>Now, here is the issue: </p> <pre><code>print(important_region.shape) output: (5...
<p>So here is how you can slice the dataset with specific columns. <code>loc</code> gives you access to the grup of rows and columns. The ones before <code>,</code> represents rows and columns after. If a <code>:</code> is specified it means all the rows.</p> <pre><code>data.loc[:,'A':'C'] </code></pre> <p>For more u...
python|pandas
1
3,615
53,616,055
Python: Name and 'Content' of variable needed in same function
<p>The variables in <code>Queries</code> contain each contain an SQL-Query. For example <code>DF_Articles = 'Select * from Article_Master'</code>. For this reason the <code>pd.read_sql_query</code> part of my function works.</p> <p>What doesn't work: I want to create and store CSV-files named after the Query, each con...
<p>I would make the collector variable a dictionary.</p> <pre><code>Queries = {"DF_TripHeader" : DF_TripHeader, "DF_Articles" : DF_Articles} </code></pre> <p>Now you can iterate over this like:</p> <pre><code>for name, query in Queries.items(): ... </code></pre> <p>If you feel that declaring the query and then ...
python|python-3.x|pandas
2
3,616
53,492,660
Using psycopg2 to COPY to table with an ARRAY INT column
<p>I created a table with a structure similar to the following:</p> <pre><code>create table some_table ( id serial, numbers int [] ); </code></pre> <p>I want to copy a pandas dataframe in an efficient way, so I don't want to use the slow <code>to_sql</code> method, so, following <a href="https://stack...
<blockquote> <p>This code doesn't throw an error, but It doesn't write anything to the table.</p> </blockquote> <p>The code works well if you commit the transaction:</p> <pre><code>cursor.close() connection.commit() </code></pre>
python|python-3.x|postgresql|pandas|psycopg2
4
3,617
20,262,448
How to write to an existing excel file without breaking formulas with openpyxl?
<p>When you write to an excel file from Python in the following manner:</p> <pre><code>import pandas from openpyxl import load_workbook book = load_workbook('Masterfile.xlsx') writer = pandas.ExcelWriter('Masterfile.xlsx') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) data_filter...
<p>Openpyxl 1.7 contains several improvements for handling formulae so that they are preserved when reading. Use <code>guess_types=False</code> to prevent openpyxl from trying to guess the type for a cell and 1.8 includes the <code>data_only=True</code> option if you want the values but not the formula.</p> <p>Want to...
python|excel|pandas|openpyxl
4
3,618
20,219,254
How to write to an existing excel file without overwriting data (using pandas)?
<p>I use pandas to write to excel file in the following fashion:</p> <pre><code>import pandas writer = pandas.ExcelWriter('Masterfile.xlsx') data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2']) writer.save() </code></pre> <p>Masterfile.xlsx already consists of number of different tabs. However, it does...
<p>Pandas docs says it uses openpyxl for xlsx files. Quick look through the code in <code>ExcelWriter</code> gives a clue that something like this might work out:</p> <pre><code>import pandas from openpyxl import load_workbook book = load_workbook('Masterfile.xlsx') writer = pandas.ExcelWriter('Masterfile.xlsx', engi...
python|excel|python-2.7|pandas
185
3,619
15,887,815
Pylab is not installing on my macbook
<p>MITX 6.00 pylab is not installing on my macbook running mountain lion running python 2.7.3. I have tried installing it multiple times but I can not get it to work. I have posted the error message below but am not sure what it is telling me to do. If you could explain this error and how I fix it that would be great.<...
<p>You should try 64bit version of this Enthought.</p>
python|macos|numpy|osx-mountain-lion
1
3,620
72,090,856
Where is the interp function in numpy.core.multiarray located?
<p>The <a href="https://github.com/numpy/numpy/blob/v1.22.0/numpy/lib/function_base.py#L1432-L1570" rel="nofollow noreferrer">source code</a> for <a href="https://numpy.org/doc/stable/reference/generated/numpy.interp.html" rel="nofollow noreferrer"><code>numpy.interp</code></a> calls a <a href="https://github.com/numpy...
<p>The <code>interp</code> Python function of <code>numpy.core.multiarray</code> is exported in <a href="https://github.com/numpy/numpy/blob/3a17c9698451906018856972e9aa08c9b626aa9c/numpy/core/src/multiarray/multiarraymodule.c#L4445" rel="nofollow noreferrer">multiarraymodule.c</a>. It is mapped to <code>arr_interp</co...
python|numpy
2
3,621
71,850,977
Set value in pandas multiindex dataframe
<p>I'm trying to set a value in a cell of a pandas multi index dataframe using the suggestions in <a href="https://stackoverflow.com/questions/23108889/set-value-multiindex-pandas">this post</a>. But because I have a datetime as the index, I can't seem to access the particular cell. Is there an efficient way to do this...
<p>you can use <strong>iloc</strong> or <strong>loc</strong> functions to access and modify any cell across the dataframe</p> <pre><code>y.iloc[2,4]=45 #for purple, goat alpha </code></pre> <p>or</p> <pre><code>y.loc[&quot;2021-08-03&quot;,(&quot;purple&quot;,&quot;goat&quot;,&quot;alpha&quot;)]=45 </code></pre>
python|pandas|dataframe|indexing
0
3,622
71,983,115
get values for potentially multiple matches from an other dataframe
<p>I want to fill the 'references' column in df_out with the 'ID' if the corresponding 'my_ID' in df_sp is contained in df_jira 'reference_ids'.</p> <pre><code>import pandas as pd d_sp = {'ID': [1,2,3,4], 'my_ID': [&quot;my_123&quot;, &quot;my_234&quot;, &quot;my_345&quot;, &quot;my_456&quot;], 'references':[&quot;&qu...
<pre><code>ref_df = df_sp[[&quot;ID&quot;,&quot;my_ID&quot;]].set_index(&quot;my_ID&quot;) df_out.references = df_out[&quot;Related elements_my&quot;].apply(lambda x: &quot;,&quot;.join(list(map(lambda y: &quot;&quot; if y == &quot;&quot; else str(ref_df.loc[y.strip()].ID), x.split(&quot;,&quot;))))) df_out[[&quot;ID&q...
python|pandas|dataframe
2
3,623
72,092,727
Error in tring to print a dataframe /np array as plt
<p>Iam trying to print some dataframe in a matplotlib pcolor:</p> <pre><code>import pandas as pd df = pd.read_excel(&quot;/content/aluminum.xlsx&quot;) data=df.to_numpy(na_value=0) data=data[1:10001,1:17] fig = plt.figure(figsize=(3, 4)) plt.pcolor(data, cmap='seismic') #plt.pcolor(data, cmap='seismic') </code></pre...
<p>So just in case someone else has the same problem as me. I did knot know the content of the Excel file exactly and as others pointed out: there was a string inside the File. <code>data=df.to_numpy(dtype=float,na_value=0)</code> produced the Error: <code>ValueError: could not convert string to float: 'Note: '</code> ...
python|numpy|matplotlib
0
3,624
71,812,077
How to define model input and outputs in tensorflow keras?
<p>I'm trying to create a model what should have nx8x8 input and 8x8 output or like below 64 units output, but don't know how to create it to make it work. I'm trying with the below code:</p> <pre><code>model = tf.keras.Sequential() input = tf.keras.layers.Flatten(input_shape=(8,8), name='input') model.add(input) mid...
<p>You need to add one more instance to your <code>train_output</code>. You have two samples on your <code>train_input</code> but only one label. You need the same amount of labels as instances of input. This solves your cardinality issue.</p> <p>However your data is formatted in a very strange way, I'm pretty sure you...
python|tensorflow|keras|tensorflow2.0
0
3,625
16,837,946
Numpy, a 2 rows 1 column file, loadtxt() returns 1row 2 columns
<pre><code>2.765334406984874427e+00 3.309563282821381680e+00 </code></pre> <p>The file looks like above: 2 rows, 1 col numpy.loadtxt() returns</p> <pre><code>[ 2.76533441 3.30956328] </code></pre> <p>Please don't tell me use array.transpose() in this case, I need a real solution. Thank you in advance!!</p>
<p>You can always use the reshape command. A single column text file loads as a 1D array which in numpy's case is a row vector.</p> <pre><code>&gt;&gt;&gt; a array([ 2.76533441, 3.30956328]) &gt;&gt;&gt; a[:,None] array([[ 2.76533441], [ 3.30956328]]) &gt;&gt;&gt; b=np.arange(5)[:,None] &gt;&gt;&gt; b array(...
python|numpy
7
3,626
22,244,383
Pandas: df.refill, adding two columns of different shape
<p>I have a csv file with these entries</p> <pre><code>Timestamp Spread 34200.405839234 0.18 34201.908794218 0.17 ... </code></pre> <p>CSV File available <a href="https://www.dropbox.com/s/qfoa3t924ttpa5x/stockA.csv" rel="nofollow">here</a></p> <p>I imported the csv file as follow:</p> <pre><code>df = pd.read...
<p>You just need to set the index first, otherwise what you were doing was correct. You can't directly add a Series of datetimes (e.g the <code>df.Time</code>) and and index range. You want a union (so you can be explicity and use <code>.union</code> or convert to an index, which '+' does by default between 2 indexes)....
python|pandas
3
3,627
17,886,994
ZeroDivisionError: float division by zero when computing standard deviation
<p>I've isolated a problem in my script that is occurring due to this attempt at a standard deviation calculation using scipy's .tstd function,</p> <pre><code> sp.stats.tstd(IR) </code></pre> <p>where my <code>IR</code> value is <code>0.0979</code>. Is there a way to get this to stop (I assume) rounding it to zero? I...
<p>The method <code>tstd</code> computes the square root of sample variance. The sample variance differs from the population variance by the factor <code>n/(n-1)</code> which is necessary to make sample variance an unbiased estimator for the population variance. This breaks down for n=1, which is understandable because...
python|numpy|floating-point|scipy|divide-by-zero
0
3,628
55,239,152
Pandas Apply with condition
<p>I have customers duplicates with different status because there is a row for each customer subscription/product. I want to generate a <code>new_status</code> for the customer and for it to be 'canceled', every subscription status must be 'canceled' together.</p> <p>I used:</p> <pre><code>df['duplicated'] = df.grou...
<p>Compare column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>Series.eq</code></a> for <code>==</code> and use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow nor...
python|pandas|apply|pandas-loc
2
3,629
9,785,514
numpy ndarray hashability
<p>I have some problems understanding how numpy objects hashability is managed.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; class Vector(np.ndarray): ... pass &gt;&gt;&gt; nparray = np.array([0.]) &gt;&gt;&gt; vector = Vector(shape=(1,), buffer=nparray) &gt;&gt;&gt; ndarray = np.ndarray(shape=(1,),...
<p>I get the same results in Python 2.6.6 and numpy 1.3.0. According to <a href="http://docs.python.org/glossary.html#term-hashable">the Python glossary</a>, an object should be hashable if <code>__hash__</code> is defined (and is not <code>None</code>), and either <code>__eq__</code> or <code>__cmp__</code> is define...
python|numpy
8
3,630
10,154,922
Constrained Linear Regression in Python
<p>I have a <a href="http://en.wikipedia.org/wiki/Linear_regression" rel="noreferrer">classic linear</a> regression problem of the form:</p> <p><code>y = X b</code></p> <p>where <code>y</code> is a <em>response vector</em> <code>X</code> is a <em>matrix</em> of input variables and <code>b</code> is the vector of fit ...
<p>You mention you would find Lasso Regression or Ridge Regression acceptable. These and many other constrained linear models are available in the <a href="http://scikit-learn.org/">scikit-learn</a> package. Check out the <a href="http://scikit-learn.org/dev/modules/classes.html#module-sklearn.linear_model">section o...
python|numpy|scipy|mathematical-optimization|linear-regression
10
3,631
56,463,354
Multiplying arrays of different shapes
<p>I essentially need to multiply two arrays of different sizes.</p> <p>I have two datasets that can be thought of like tables of points that describe an algebraic equation. In other words, I have two arrays corresponding to x and y values for one data set and two arrays corresponding to x and y values for the other d...
<p>The below code will fix your error for attempt 2.</p> <pre><code>################################ attempt2 ################ ###x is an array of x-values associated with interpolation for i in x: for j in x_vals: if i==j: k = interpolation*y_vals print(k) </code><...
python|arrays|numpy
0
3,632
56,473,288
Replace certain columns in Dataframe with null
<p>I want to remove a certain columns based on high null values. In few columns there is a value(in this case "Select) which is equivalent to null. I want to replace this with null so that i can calculate the null % and removes columns accordingly.</p> <pre><code>Lead Profile City Select Select Select ...
<p>to replace <code>value</code> with nulls:</p> <pre><code>df['col'] = df['col'].replace('value', np.nan) </code></pre> <p>otherwise to directly return only columns which have less than <code>N</code> times the <code>Select</code> values, you can use this:</p> <pre><code>df2 = df[[col for col in df.columns if len(d...
python|python-3.x|pandas
1
3,633
66,911,494
How to filter the rows of a dataframe based on the presence of the column values in a separate dataframe and append columns from the second dataframe
<p>I have the following dataframes:</p> <p>Dataframe 1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Fruit</th> <th style="text-align: center;">Vegetable</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">Mango</td> <td style="text-align: center;...
<p>You can do this in two steps:</p> <ol> <li><p>Mask your dataframe1 such that it only contains rows where both fruit and vegetable exits in dataframe2.Item</p> </li> <li><p>Use <code>Series.map</code> to obtain the values associated with the remaining rows, and add them together to get the combination price.</p> </li...
python|pandas|dataframe
1
3,634
66,933,457
Plot 3D graph using Python
<p>I trying to plot a graph of a function <code>f(x, y) = x**x*y</code>, but I'm getting an error:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D def f(x,y): return x**x*y x = np.arange(-4.0, 4.0, 0.1) y = np.arange(-4.0, 4.0, 0.1) z = f(x, y) X, Y, Z = n...
<p>You can try:</p> <pre class="lang-py prettyprint-override"><code>X, Y = np.meshgrid(x, y) Z = f(X, Y) </code></pre> <p>The <a href="https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html" rel="nofollow noreferrer"><code>meshgrid</code></a> function returns <em>coordinate matrices from coordinate vector...
python|numpy|matplotlib
2
3,635
67,097,400
How do I write consecutive times to a text file without listing all times, only the final range?
<p>I am currently writing datetimes to a txt file. It currently looks like this:</p> <pre><code>2021-01-01 06:52:00 , 2021-01-01 06:54:00 , 2021-01-01 06:55:00 , 2021-01-01 06:56:00 , 2021-01-01 06:57:00 , 2021-01-01 06:59:00 , 2021-01-01 07:01:00 , </code></pre> <p>I would instead like it to be displayed as a list of ...
<p>Your print statement in <code>for t in time_list_array:</code> includes <code>'\n'</code>. This creates a new line every time. You want to write 2 time values on the same line THEN add <code>'\n'</code> at the end. You need a small modification to the loop and the write format. Something like this:</p> <pre><code>fo...
python-3.x|numpy|datetime|txt
0
3,636
66,936,107
Sample dataframe by value in column and keep all rows
<p>I want to sample a Pandas dataframe using values in a certain column, but I want to keep all rows with values that are in the sample.</p> <p>For example, in the dataframe below I want to randomly sample some fraction of the values in <code>b</code>, but keep <strong>all</strong> corresponding rows in <code>a</code> ...
<p>I really doubt that <code>isin</code> is slow:</p> <pre><code>uniques = df.b.unique() # this maybe the bottle neck samples = np.random.choice(uniques, replace=False, size=int(0.16*len(uniques)) ) # sampling here df[df.b.isin(samples)] </code></pre> <p>You can profile the steps above. In case <code>samples=...</cod...
python|pandas|dataframe|sample
1
3,637
67,026,402
Plotting really slow on 300k row dataset
<p>I'm doing an EDA on a 320k rows dataset, 30 columns.</p> <p>I'd like to display the distribution of variables so I try basic stuff like</p> <p>`</p> <pre><code>for col in df.select_dtypes(&quot;object&quot;): plt.figure() df[col].value_counts().plot.pie(autopct='%1.1f%%') plt.show() </code></pre> <p>`</p...
<p>Instead of plotting pies of value counts, you could start by looking at indicators given by <code>df[col].describe()</code> for each column. It will give a much faster and much more complete overview of your data.</p> <p>Then, if you want a visual overview, of course it depends on your data and what you are trying t...
python-3.x|pandas|matplotlib|seaborn
1
3,638
67,087,445
Pandas.to_datetime() A value is trying to be set on a copy of a slice from a DataFrame
<p>I have not received this copy warning with other functions and I have not found a way to address it.</p> <p>Here is my code:</p> <pre><code>div_df.loc[:,&quot;Ann.Date&quot;] = pd.to_datetime(div_df.loc[:,&quot;Ann.Date&quot;], format='%d %b %Y') /volume1/homes/id/venv/lib/python3.8/site-packages/pandas/core/indexi...
<p>As mentioned in the discussion in comments, the root cause is probably your dataframe <code>div_df</code> is built from a slice of another dataframe. Most commonly, we either solve this kind of SettingWithCopyWarning problem by using <code>.loc</code> or using <a href="https://pandas.pydata.org/docs/reference/api/p...
python|python-3.x|pandas
0
3,639
47,534,715
Get Nearest Point from each other in pandas dataframe
<p>i have a dataframe:</p> <pre><code> routeId latitude_value longitude_value r1 28.210216 22.813209 r2 28.216103 22.496735 r3 28.161786 22.842318 r4 28.093110 22.807081 r5 28.220370 22.503500 r6 28.220370 22.503500 r7 ...
<p>We can use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="noreferrer"><code>scipy.spatial.distance.cdist</code></a> or multiple for loops then replace min with routes and find the closest i.e</p> <pre><code>mat = scipy.spatial.distance.cdist(df[['latitude_value...
python|pandas|numpy|dataframe
10
3,640
47,376,642
array python split str (too many values to unpack)
<p>Array python split str (too many values to unpack)</p> <pre><code>df.timestamp[1] Out[191]: '2016-01-01 00:02:16' #i need to slept these into to feature split1,split2=df.timestamp.str.split(' ') Out[192]: ValueErrorTraceback (most recent call last) &lt;ipython-input-216-bbe8e968766f&gt; in &lt;module&gt;() ----&...
<p>Use the <code>str[index]</code> since you are splitting the series, the output will also be a series and not two different lists in pandas. </p> <pre><code>df = pd.DataFrame({'timestamp':['2016-01-01 00:02:16','2016-01-01 00:02:16'] }) split1,split2 = df.timestamp.str.split(' ')[0], df.timestamp.str.split(' ')[1...
python|pandas
1
3,641
11,432,728
Print from specific positions in NumPy array
<p>I am new to NumPy and I have created the following array:</p> <pre><code>import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) </code></pre> <p>and I am wondering if there is a way to print a number from a specific position in the array.</p> <p>Let's say I wanted to print number 7, and ONLY number 7. Would ...
<p>From <a href="http://www.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c" rel="nofollow">tentative NumPy tutorial</a></p> <pre><code>&gt;&gt;&gt; b array([[ 0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]]) &gt;&gt;&...
python|arrays|multidimensional-array|numpy
4
3,642
10,884,668
Two-sample Kolmogorov-Smirnov Test in Python Scipy
<p>I can't figure out how to do a Two-sample KS test in Scipy.</p> <p>After reading the documentation <a href="http://docs.scipy.org/doc/scipy-0.7.x/reference/generated/scipy.stats.kstest.html" rel="noreferrer">scipy kstest</a></p> <p>I can see how to test where a distribution is identical to standard normal distribu...
<p>You are using the one-sample KS test. You probably want the two-sample test <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ks_2samp.html" rel="noreferrer"><code>ks_2samp</code></a>:</p> <pre><code>&gt;&gt;&gt; from scipy.stats import ks_2samp &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; ...
python|numpy|scipy|statistics|distribution
153
3,643
68,146,847
How to create interaction variable between only 1 variable with all other variables
<p>When using the SciKit learn <code>PolynomialFeatures</code> package it is possible to do the following:</p> <ol> <li>Take features: <code>x1</code>, <code>x2</code>, <code>x3</code></li> <li>Create interaction variables: <code>[x1, x2, x3, x1x2, x2x3, x1x3]</code> using <code>PolynomialFeatures(interaction_only=True...
<p>You could just make them yourself no? PolynomialFeatures doesn't do anything particularly innovative.</p>
python|pandas|numpy|scikit-learn
0
3,644
68,344,978
Logits and labels must be broadcastable: logits_size=[29040,3] labels_size=[290400,3]
<p>I am using this code:</p> <pre><code>import tensorflow as tf import numpy as np from tensorflow.keras.layers import Dense, LSTM, Input, Conv2D, Lambda from tensorflow.keras import Model def reshape_n(x): x = tf.compat.v1.placeholder_with_default( x, [None, 121, 240, 2]) return x i...
<p>Using <code>tensorflow-gpu==2.3.0</code> and <code>numpy==1.19.5</code>, when I run your code, I observe no errors, exit code is <code>0</code>. My python version is <code>Python 3.8.6</code>, in case that matters as well.</p> <p>The displayed model summary is</p> <pre><code>Model: &quot;functional_1&quot; _________...
deep-learning|lstm|tensorflow2.0|tf.keras
1
3,645
68,375,295
How to use if statement in pandas to round a column
<p>My data frame looks like this.</p> <pre><code> a d e 0 BTC 31913.1123 -6.5% 1 ETH 1884.1621 -18.8% 2 USDT 1.0 0.1% 3 BNB 294.0246 -8.4% 4 ADA 1.0342 -14.3% 5 XRP 1.1423 -10.5% </code></pre> <p>On column d, I want to round the floats in column d to a whole number if ...
<p><a href="https://stackoverflow.com/a/31173785/7116645">https://stackoverflow.com/a/31173785/7116645</a></p> <p>Taking reference from above answer, you can simply do like following</p> <pre class="lang-py prettyprint-override"><code>df['d'] = [round(x, 2) if x &gt; 10 else x for x in df['d']] </code></pre>
python|pandas|dataframe
0
3,646
68,340,032
Dataframe_image OsError: Chrome executable not able to be found on your machine
<p>I am trying to run my script in <strong>Databricks</strong> using <strong>dataframe_image</strong> library to style my table and later save this as .png file and getting an error <em>OsError: Chrome executable not able to be found on your machine.</em> Per <a href="https://pypi.org/project/dataframe-image/" rel="nof...
<p>For a Debian based os:</p> <pre><code>apt install chromium-chromedriver </code></pre> <p>Solved it for me.</p> <p><a href="https://github.com/dexplo/dataframe_image/issues/6" rel="nofollow noreferrer"> Chrome executable error #6 </a></p>
python|pandas
0
3,647
68,197,673
raise ValueError("Shapes %s and %s are incompatible" % (self, other)) ValueError: Shapes (None, 15) and (None, 14) are incompatible
<p>I was working speech emotion recognition project. it works one week ago and i upgraded anaconda but the code I used to run no longer works. i couldnt find the problem it gives the error in the title. my code is:</p> <pre><code># New model model = Sequential() model.add(Conv1D(256, 8, padding='same',input_shape=(X...
<p>The issue is with the network output shape. Since the labels have shape</p> <p><code>(b, 15) where b = 9031 for train and 3011 for test </code></p> <p>the final dense layer in the network should also have 15 neurons. Update the final layer to be</p> <p><code>model.add(Dense(15)</code></p> <p>and it should work fine....
python-3.x|tensorflow|machine-learning|deep-learning|librosa
0
3,648
59,315,138
How to get words from output of XLNet using Transformers library
<p>I am using Hugging Face's Transformer library to work with different NLP models. Following code does masking with XLNet. It outputs a tensor with numbers. How do I convert the output to words again? </p> <pre><code>import torch from transformers import XLNetModel, XLNetTokenizer, XLNetLMHeadModel tokenizer = XLN...
<p>The output you have is a tensor of size 1 by 1 by vocabulary size. The meaning of the nth number in this tensor is the estimated <a href="https://en.wikipedia.org/wiki/Logit" rel="nofollow noreferrer">log-odds</a> of the nth vocabulary item. So, if you want to get out the word that the model predicts to be most li...
nlp|masking|transformer-model|language-model|huggingface-transformers
2
3,649
59,366,199
is there a way to convert h2oframe to pandas dataframe
<p>I am able to convert dataframe to h2oframe but how can I convert back to a dataframe? If this is possible not can I convert it to a python list?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import h2o df = pd.DataFrame({'1': [2838, 3222, 4576, 5665, 5998], '2': [1123, 3228, 3587, 5678, 64...
<p>There is an H2OFrame method called <a href="http://docs.h2o.ai/h2o/latest-stable/h2o-py/docs/frame.html#h2o.frame.H2OFrame.as_data_frame" rel="noreferrer"><code>as_data_frame()</code></a> but <code>h2o.as_list()</code> also works.</p> <pre><code>data_as_df = data.as_data_frame() </code></pre>
python|pandas|h2o
19
3,650
59,310,550
Can't figure out HTML file path formatting
<p>I am trying to send a link to a location on our servers via email, but I can't get the HTML portion of the link to work.</p> <p>This is my file path-- P:\2. Corps\PNL_Daily_Report</p> <p>What I've tried--</p> <pre><code>newMail.HTMLBody ='&lt;a href="file://///P:\2.%20Corps\PNL_Daily_Report"&gt;Link Anchor&lt;/...
<p>According to <a href="https://blogs.msdn.microsoft.com/ie/2006/12/06/file-uris-in-windows/" rel="nofollow noreferrer">this article</a> on MSDN Blog, your <code>href</code> should be:</p> <pre><code>&lt;a href="file:///P:/2.%20Corps/PNL_Daily_Report"&gt;Link Anchor&lt;/a&gt; </code></pre> <p>Windows path is a signi...
python|html|pandas|win32com
0
3,651
59,201,268
How to plot duplicates legends in Matplotlib
<p>I have a Pandas dataframe with duplicated legends (yLabels) and each of them with a different value (yValues). The problem is that when I plot this dataframe using Matplotlib, all the duplicated legends are grouped - and this is not my intention. I have to show duplicated legends, each of them with its specific valu...
<p>IIUC, you are looking for something like this:</p> <pre><code>yLabels = ['ABC', 'ABC', 'ABC'] ### these must appear 3x in the legends yValues = [-0.15, 0.00, 0.23] df = pd.DataFrame({'x': yLabels, 'Goal': [0, 0, 0], 'y': yValues}) plt.scatter(df.index, df["y"]) plt.xticks(d...
python|pandas|matplotlib
0
3,652
44,839,265
Vectorized implementation of a function in pandas
<p>This is my current function:</p> <pre><code>def partnerTransaction(main_df, ptn_code, intent, retail_unique): if intent == 'Frequency': return main_df.query('csp_code == @retail_unique &amp; partner_code == @ptn_code')['tx_amount'].count() elif intent == 'Total_value': return main_df.query...
<p>First use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#brief-primer-on-merge-methods-relational-algebra" rel="nofollow noreferrer">left join</a>.</p> <p>Then <...
python|database|pandas|dataframe|vectorization
2
3,653
44,914,651
Memory Usuage Between Data Types in Python
<p>I'm trying to figure out why an int8 uses more memory than a float data type. Shouldn't it less since it should only be using 1 byte of memory. </p> <pre><code>import numpy as np import sys In [32]: sys.getsizeof(np.int8(29.200)) Out[32]: 25 In [33]: sys.getsizeof(np.int16(29.200)) Out[33]: 26 In [34]: sys.getsi...
<p>Using <code>getsizeof</code> on isolated <code>np.types</code> like this isn't very informative.</p> <p><code>np.int8(...)</code> is an object that includes not just the data byte, but various numpy attributes. It's similar to a <code>np.array(123, dtype=int8)</code>. In other words the array overhead is larger t...
python|python-3.x|numpy
4
3,654
44,958,677
Looping over one pandas column to match values with index of another dataframe
<p><code>Exp</code> is one <code>DataFrame</code> with <code>datetime</code> <code>object</code></p> <pre><code> Exp 0 1989-06-01 1 1989-07-01 2 1989-08-01 3 1989-09-01 4 1989-10-01 </code></pre> <p><code>CL</code> is the <code>Dataframe</code> with <code>Index</code> as <code>DateTime Object</cod...
<p><strong>Edit</strong>: updated with commenters suggestion.</p> <p>You need to do LEFT JOIN:</p> <pre><code>Exp = pd.DataFrame( pd.to_datetime(['1989-06-01', '1989-07-01', '1989-08-01', '1989-09-01', '1989-10-01']), columns=['Exp']) </code></pre> <p>gives:</p> <pre><code> Exp 0 1989-06-01 1 198...
python|pandas
2
3,655
44,991,353
Proportion distribution of column values by date
<p>I am trying to get the proportion of each category in the data set by day, to be able to plot it eventually.</p> <p>Sample (daily_usage):</p> <pre><code> type date count 0 A 2016-03-01 70 1 A 2016-03-02 64 2 A 2016-03-03 38 3 A 2016-03-04 82 4 A ...
<p>if you just want to have your new column in your dataframe you can do the following:</p> <pre><code>df['ratio'] = (df.groupby(['type','date'])['count'].transform(sum) / df.groupby('date')['count'].transform(sum)) </code></pre> <p>However, it has nearly been 20 mins now that I'm trying to figure out what you're try...
python|python-3.x|pandas
1
3,656
57,212,884
Check if a dataframe column contains a particular value
<p>I'm trying to use an if-else statement to check if a dataframe column 'vi' contains a value, then extract the value in the next corresponding row. The dataframe contains 2 columns, 'j' and 'vi'</p> <pre><code>if G_df['vi']== vi: new_j = G_df.loc['j'].item() </code></pre> <p>gives the is error: ValueError: ...
<p>The value of <code>G_df['vi']== vi</code> is a Series. You cannot use it in an <code>if</code> statement. Also, <code>if</code> statements should be avoided in Pandas. Here's what you are looking for:</p> <pre><code>df.loc[df['vi'] == vi, 'j'] </code></pre> <p>This expression gives you all values from the column <...
python-3.x|pandas|dataframe
1
3,657
56,983,818
Getting a subset of 2D array given indices of center point
<p>Given a 2D array and a specific element with indices (x,y), how to get a subset square 2D array (n x n) centered at this element?</p> <p>I was able to implement it only if the size of subset array is completely within the bounds of the original array. I'm having problems if the specific element is near the edges or...
<p>Here's how I would do this:</p> <pre><code>def fixed_size_subset(a, x, y, size): ''' Gets a subset of 2D array given a x and y coordinates and an output size. If the slices exceed the bounds of the input array, the non overlapping values are filled with NaNs ---- a: np.array 2D ...
python|python-3.x|numpy
2
3,658
57,076,123
List of dictionaries - Function with list index is out of range
<p>I am trying to loop through a variable of nested dictionaries (a JSON Google Maps output). The code below worked on a smaller output, but now it is returning an error. </p> <p>The var geocode_result has a length of <code>28376</code>.</p> <pre><code>lat_long_list = [] def geocode_results_process(x): f...
<p>I see a few issues with the code that you have written:</p> <ol> <li>The <code>lat_long_list = []</code> should be inside the function definition.</li> <li>you are running multiple for loops inside the function which is not necessary</li> </ol> <p>With python, you can make the code much more readable by doing some...
python|pandas
1
3,659
57,227,450
Python optimizing reshape operations in nested for loops
<p>I am looking for help in finding a more pythonic/broadcasting way to optimize the two following array reshaping functions:</p> <pre><code>import numpy def A_reshape(k,m,A): """ Reshaping input float ndarray A of shape (x,y) to output array A_r of shape (k,y,m) where k,m are user known dimensions ...
<p>Try:</p> <pre><code>def A_reshape(k,m,A): A2 = A.reshape(k,m,-1) A2 = np.moveaxis(A2, 2, 1) return A2 </code></pre> <p>Assume that A's shape is (x,y). Initially, the first dimension is expanded:</p> <p><code>(x,y) -&gt; (k,m,y)</code></p> <p>Next, the axis of size y is moved from position 2 to positi...
python|python-3.x|numpy|optimization|reshape
2
3,660
57,166,569
Csv file incorrectly loading in pandas csv
<p>I have csv which I'm trying to load using <code>pd.read_csv</code>. However some lines of file are read as one column, while others are correctly read into separate columns. I think the problem is with rows that contain quotes but i dont want to remove them.</p> <p>I tried using quotechar but it does not help</p> ...
<p>This is not an answer, just to clarfiy. What do you get, if you execute this code:</p> <pre><code>import io raw=""" 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14 a,br,c,,,,d,e,0,False,False,False,"bs,C",19/07/2018 23:25:12,27/05/2018 23:09:21 a,b,c,,,,d,e,2,False,False,False,U D,19/07/2011 11:21:02,18/07/2011 12:21:00 """ df=...
python|pandas|csv
0
3,661
11,747,125
Python numpy: Convert string in to numpy array
<p>I have following String that I have put together:</p> <pre><code>v1fColor = '2,4,14,5,0,0,0,0,0,0,0,0,0,0,12,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,15,6,0,0,0,0,1,0,0,0,0,0,0,0,0,0,20,9,0,0,0,2,2,0,0,0,0,0,0,0,0,0,13,6,0,0,0,1,0,0,0,0,0,0,0,0,0,0,10,8,0,0,0,1,2,0,0,0,0,0,0,0,0,0,17,17,0,0,0,3,6,0,0,0,0,0,0,0,0,0,7,5,0,0,0,2...
<p>You have to split the string by its commas first:</p> <pre><code>NP.array(v1fColor.split(","), dtype=NP.uint8) </code></pre>
python|vector|numpy|trigonometry
11
3,662
11,794,935
Pandas DataFrame Apply
<p>I have a Pandas <code>DataFrame</code> with four columns, <code>A, B, C, D</code>. It turns out that, sometimes, the values of <code>B</code> and <code>C</code> can be <code>0</code>. I therefore wish to obtain the following:</p> <pre><code>B[i] = B[i] if B[i] else min(A[i], D[i]) C[i] = C[i] if C[i] else max(A[i...
<p>A combination of boolean indexing and apply can do the trick. Below an example on replacing zero element for column C.</p> <pre><code>In [22]: df Out[22]: A B C D 0 8 3 5 8 1 9 4 0 4 2 5 4 3 8 3 4 8 5 1 In [23]: bi = df.C==0 In [24]: df.ix[bi, 'C'] = df[bi][['A', 'D']].apply(max, axis=1) In...
python|pandas
8
3,663
28,506,414
How to interpret this array indexing in numpy?
<p>I wanted to interpret array indexing in the following code snippet. What does <code>State[t,Con]</code> mean, where <code>Con</code> itself is an array?</p> <pre><code>for t in range(T): # 0 .. T-1 State[t+1] = Bool[:, sum(Pow * State[t,Con],1)].diagonal() </code></pre> <p>And <code>Con</code> is given as bel...
<p><code>Con</code> is a <code>(N,K)</code> array of integers.</p> <p><code>State</code> presumably is <code>(T,N)</code> array.</p> <p><code>State[t,Con]</code> will be a <code>(N,K)</code> array of values selected from the <code>t</code> row of <code>State</code>. Since <code>Con</code> has repeats, some values of...
python|numpy
1
3,664
51,012,614
How to iterate through two data frames in python
<p>I have two Data frames <code>df1</code>( having columns C1,C2,etc) and <code>df2</code>(having columns S1,S2,etc)<br> I want to iterate through each column of both the Data Frames.<br> Currently I am doing the following thing: </p> <pre><code>df3=pd.Dataframe([]) for index1,row1 in df1.iterrows(): for index2,r...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow noreferrer"><code>merge</code></a> first, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> function and last fi...
python|python-3.x|pandas|dataframe
1
3,665
33,396,637
Randomly place n elements in a 2D array
<p>I need a boolean or binary numpy array size <code>(m,m)</code> with <code>n</code> True values scattered randomly. I'm trying to make a random grid pattern. I will have a <code>5x5</code> array with <code>3</code> True values over it and will sample at those points only.<br> Using random.choice I sometimes get mor...
<p>You could use <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html" rel="nofollow"><code>np.random.choice</code></a> with the optional argument <code>replace</code> set as <code>False</code> to have <strong><code>unique random</code></strong> IDs from <code>0</code> to <code>m*m-...
python|arrays|numpy|random
4
3,666
9,566,592
Find multiple values within a Numpy array
<p>I am looking for a numpy function to find the indices at which certain values are found within a vector (xs). The values are given in another array (ys). The returned indices must follow the order of ys.</p> <p>In code, I want to replace the list comprehension below by a numpy function.</p> <pre><code>&gt;&gt; imp...
<p>For big arrays <code>xs</code> and <code>ys</code>, you would need to change the basic approach for this to become fast. If you are fine with sorting <code>xs</code>, then an easy option is to use <code>numpy.searchsorted()</code>:</p> <pre><code>xs.sort() ndx = numpy.searchsorted(xs, ys) </code></pre> <p>If it i...
python|numpy
22
3,667
66,502,174
Read group of rows from Parquet file in Python Pandas / Dask?
<p>I have a Pandas dataframe that looks similar to this:</p> <pre><code>datetime data1 data2 2021-01-23 00:00:31.140 a1 a2 2021-01-23 00:00:31.140 b1 b2 2021-01-23 00:00:31.140 c1 c2 2021-01-23 00:01:29.021 d1 d2 2021-01-23 00:02:10.540 e1 e2 2021-01-23 00...
<p>One solution is to index your data by time and use <code>dask</code>, here's an example:</p> <pre class="lang-py prettyprint-override"><code>import dask import dask.dataframe as dd df = dask.datasets.timeseries( start='2000-01-01', end='2000-01-2', freq='1s', partition_freq='1h') df print(len(df))...
python|pandas|dask|parquet|dask-dataframe
3
3,668
66,667,256
Groupby show max value and corresponding label - pandas
<p>I'm trying to group specific values and return the max value of a separate column. I'm also hoping to return the corresponding label this max value is associated with. Using below, I'm grouping values by <code>Item, Group, Direction</code> and the max value is determined from <code>Value</code>. I'm hoping to return...
<p>Try with <code>Groupby.transform</code> and <code>df.pivot</code>:</p> <pre><code>In [270]: df['max_value'] = df.groupby(['Item','Group','Direction'])['Value'].transform('max') In [279]: df[df.max_value.eq(df.Value)].pivot('Item', ['Group', 'Direction', 'Label'], 'Value') Out[279]: Group Red Green Red ...
python|pandas
1
3,669
66,501,770
How to force tensorflow and Keras run on GPU?
<p>I have TensorFlow, NVIDIA GPU (CUDA)/CPU, Keras, &amp; Python 3.7 in Linux Ubuntu. I followed all the steps according to this tutorial: <a href="https://www.youtube.com/watch?v=dj-Jntz-74g" rel="nofollow noreferrer">https://www.youtube.com/watch?v=dj-Jntz-74g</a></p> <p>when I run the following code of:</p> <pre><co...
<p>To tensorflow work on GPU, there are a few steps to be done and they are rather difficult.</p> <p>First of compatibility of these frameworks with NVIDIA is much better than others so you could have less problem if the GPU is an NVIDIA and should be in this <a href="https://developer.nvidia.com/cuda-gpus" rel="nofoll...
python|tensorflow|keras|deep-learning|gpu
0
3,670
57,705,385
How to highlight dataframe based on another dataframe value so that the highlighted dataframe can be exported to excel
<p>I have two dataframes of lets say same shape, need to compare each cell of dataframes with one another. If they are mismatched or one value is null then have to write the bigger dataframe to excel with highlighting cells where mismatched or null value was true.</p> <p>i calculated the two dataframe differences as a...
<p>you can do something like:</p> <pre><code>def myfunc(x): c1='' c2='background-color: red' condition=x.eq(df2) res=pd.DataFrame(np.where(condition,c1,c2),index=x.index,columns=x.columns) return res df1.style.apply(myfunc,axis=None) </code></pre> <hr> <p><a href="https://i.stack.imgur.com/abI04....
python|pandas|dataframe
2
3,671
57,468,278
How to convert a list to dataframe with multiple columns?
<p>I have a list 'result1' like this:</p> <pre><code>[[("tt0241527-Harry Potter and the Philosopher's Stone", 1.0), ('tt0330373-Harry Potter and the Goblet of Fire', 0.9699), ('tt1843230-Once Upon a Time', 0.9384), ('tt0485601-The Secret of Kells', 0.9347)]] </code></pre> <p>I want to convert it into three colu...
<p>You can try to redifine your input:</p> <pre><code>[elt1.split('-') + [elt2] for elt1, elt2 in result1[0] ] </code></pre> <p>Full example:</p> <pre><code>result1 = [[("tt0241527-Harry Potter and the Philosopher's Stone", 1.0), ('tt0330373-Harry Potter and the Goblet of Fire', 0.9699), ('tt1843230-Once Upon a ...
python|pandas|list|dataframe
4
3,672
57,302,227
Convert a datetime index to sequential numbers for x value of machine leanring
<p>This seems like a basic question. I want to use the datetime index in a pandas dataframe as the x values of a machine leanring algorithm for a univarte time series comparisons.</p> <p>I tried to isolate the index and then convert it to a number but i get an error.</p> <pre><code>df=data["Close"] idx=df.index df.in...
<p>First select column <code>Close</code> by double <code>[]</code> for one column <code>DataFrame</code>, so possible add new column:</p> <pre><code>df = data[["Close"]] df["x"] = np.arange(1, len(df) + 1) print (df) Close x Date 2014-03-31 0.9260 1 2014-04-01 0.9269 2 2014-04-02 0...
python|pandas
0
3,673
57,438,392
Rearranging axes in numpy?
<p>I have an ndarray such as</p> <pre><code>&gt;&gt;&gt; arr = np.random.rand(10, 20, 30, 40) &gt;&gt;&gt; arr.shape (10, 20, 30, 40) </code></pre> <p>whose axes I would like to swap around into some arbitrary order such as</p> <pre><code>&gt;&gt;&gt; rearranged_arr = np.swapaxes(np.swapaxes(arr, 1,3), 0,1) &gt;&gt;...
<p>There are two options: <a href="https://numpy.org/doc/stable/reference/generated/numpy.moveaxis.html" rel="noreferrer"><code>np.moveaxis</code></a> and <a href="https://numpy.org/doc/stable/reference/generated/numpy.transpose.html" rel="noreferrer"><code>np.transpose</code></a>.</p> <ul> <li><h2><code>np.moveaxis(a...
python|numpy
28
3,674
57,349,762
ValueError: Merge keys contain null values on left side Pandas
<p>Edit: I have two datasets, df1 and df2. df1 looks something like this:</p> <pre><code> EXECUTION_TS HR 0 5/6/2019 9:20 127 1 5/6/2019 9:21 126.5 2 5/6/2019 9:22 130 3 5/6/2019 9:23 114 ... ... ... </code></pre> <p>and df2 looks something ...
<p>The code below should work (based on the data presented above). If the concern is about the depth of the datetime object, then you may have to format both to same depth &amp; then merge</p> <pre><code>df1= pd.merge(df1,df2, on=['EXECUTION_TS'],how='outer') </code></pre>
python|pandas
0
3,675
43,860,199
python module for trace/chromatogram analysis
<p>Is there a python module that integrates simple chromatogram/trace analysis algorithms? I am looking for baseline correction, peak detection and peak integration functionality for simple time-courses (with data stored in numpy arrays). </p> <p>I spent quite some time searching now and there doesn't seem to be any w...
<p>I'm not sure what analysis you are conducting but have you looked at <a href="https://github.com/gmrandazzo/PyLSS" rel="nofollow noreferrer">PyLSS</a> ?</p> <p>It can (and I quote from the documentation):</p> <blockquote> <blockquote> <blockquote> <p>PyLSS is able to compute:</p> <blockquo...
python|numpy|module|scipy
0
3,676
43,638,851
Pandas histogram plot with kde?
<p>I have a Pandas dataframe (<code>Dt</code>) like this:</p> <pre><code> Pc Cvt C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 0 1 2 0.08 0.17 0.16 0.31 0.62 0.66 0.63 0.52 0.38 1 2 2 0.09 0.15 0.13 0.49 0.71 1.28 0.42 1.04 0.43 2 3 ...
<p>You want to first plot your histogram then plot the kde on a secondary axis.</p> <p><a href="https://stackoverflow.com/help/mcve"><em>Minimal and Complete Verifiable Example <strong>MCVE</em></strong></a></p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame(np.ra...
python|pandas|histogram|kernel-density
8
3,677
43,534,956
Why is tf.Variable uppercase but tf.constant lowercase?
<p>There is a little hard to guess why the case (I mean, upper case versus lower case) of constructors for variable, placeholder and constant is not the same, as below: <code>tf.Variable()</code>, <code>tf.placeholder()</code>, <code>tf.constant()</code>.</p> <p>What is the inherent difference between the variable me...
<p><a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/constant_op/constant_value_tensors#constant" rel="noreferrer"><code>tf.constant()</code></a> and <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/io_ops/placeholders" rel="noreferrer"><code>tf.placeholder()</code></a> are nodes in t...
tensorflow
17
3,678
43,758,625
Working with columns in pandas
<p>This is a part of the table which I have:</p> <pre><code>type n_b sp 2 sp 2 sp 3 avn 2 avn 4 avn 3 psp 1 psp 3 psp 5 ... </code></pre> <p>Also I have a data set:</p> <pre><code>d = pd.Series({'sp':['98,00', '0,00', '68,00'], 'psp':['17,00', '7,60', '14,30'], 'avn':['15,...
<p>It seems you're almost there. You've now got:</p> <pre><code>df Out[758]: type n_b c_t 0 sp 2 [98,00, 0,00, 68,00] 1 sp 2 [98,00, 0,00, 68,00] 2 sp 3 [98,00, 0,00, 68,00] 3 avn 2 [15,00, 10,00, 4,30] 4 avn 4 [15,00, 10,00, 4,30] 5 avn 3 [15,00, 10,00, 4,30] 6 ...
python|pandas|dataframe
1
3,679
43,792,961
Understanding the while loop in Tensorflow
<p>I am using the <a href="https://www.tensorflow.org/api_docs/python/" rel="noreferrer">Python API for Tensorflow</a>. I am trying to implement the <a href="https://www.sfu.ca/~ssurjano/rosen.html" rel="noreferrer">Rosenbrock function</a> given below without the use of a Python loop:</p> <p><a href="https://i.stack.i...
<p>This can be achieved using the <code>tf.while_loop()</code> and standard <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="noreferrer">tuples</a> as per the second example in the <a href="https://www.tensorflow.org/api_docs/python/tf/while_loop" rel="noreferrer">documentation...
python|optimization|while-loop|tensorflow
16
3,680
72,909,832
Use GeoPandas / Shapely to find intersection area of polygons defined by latitude and longitude coordinates
<p>I have two GeoDataFrames, <em>left</em> and <em>right</em>, with many polygons in them. Now I am trying to find the total intersection area of each polygon in <em>left</em>, with all polygons in <em>right</em>.</p> <p>I've managed to get the indices of the intersecting polygons in <em>right</em> for each polygon in ...
<p>I fixed it by using the EPSG:6933 projection instead, which is an area preserving map projection and returns the area in square metres (EPSG:4326 does not preserve areas, so is not suitable for area calculations). I could just change my GDF to this projection using</p> <pre><code>gdf.to_crs(espg=6933) </code></pre> ...
python|geospatial|geopandas|shapely
3
3,681
72,929,172
Confusing indexer of pandas
<p>I found the bracket indexer([]) very confusing.</p> <pre><code>import pandas as pd import numpy as np aa = np.asarray([[1,2,3],[4,5,6],[7,8,9]]) df = pd.DataFrame(aa) df </code></pre> <p>output</p> <pre><code> 0 1 2 0 1 2 3 1 4 5 6 2 7 8 9 </code></pre> <p>Then I tried to index it with []</...
<p>In pandas, if you want to select values by numeric index, you use <code>iloc</code>. a dataframe has 2 axes, so to select a specific cell you have to specify both axes (row and column). see the code.</p> <pre><code>df.iloc[0,0] # this should return the value 1 df.iloc[0,:] # this returns the first row df.iloc[:,0] #...
pandas
1
3,682
73,099,155
How to avoid repetition into list while building dataset
<p>I am trying to create the following dataset:</p> <pre><code>multiple_newbooks = {&quot;Books'Tiltle&quot;:[&quot;American Tabloid&quot;, 'Libri che mi hanno rovinato la vita ed Altri amori malinconici', '1984' ], 'Authors':['James Ellroy', 'Daria Bignardi', 'George Orwell'], ...
<p>If I understand you correctly, you don't want to repeat writing the strings. You can use for example <code>*</code> to repeat the string:</p> <pre class="lang-py prettyprint-override"><code>multiple_newbooks = { &quot;Books'Tiltle&quot;: [ &quot;American Tabloid&quot;, &quot;Libri che mi hanno ro...
python|pandas|list|dataset|repeat
1
3,683
70,583,392
Is it possible to do interpolation over 4d data?
<p>I am trying to implement <a href="https://www.cs.cmu.edu/%7Eaayushb/Video-ViSA/video_visa_paper.pdf" rel="nofollow noreferrer">this</a> paper. I have to try to interpolate the latent code of an autoencoder, as mentioned in the paper. The latent code is the encoded input of an autoencoder. The shape of the latent cod...
<p>Scipy has a couple of 2D interpolation routines, depending on the spacing of the (x, y):</p> <ul> <li>If your data is on a regular grid, try <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RectBivariateSpline.html#scipy.interpolate.RectBivariateSpline" rel="nofollow noreferrer">scipy....
python|numpy|multidimensional-array|interpolation|spatial-interpolation
1
3,684
70,406,194
ValueError: not enough values to unpack (expected 3, got 0)
<p>I am writing a pytorch sentiment analysis model. I would like to use my own dataset with torchtext. <a href="https://github.com/bentrevett/pytorch-sentiment-analysis" rel="nofollow noreferrer">https://github.com/bentrevett/pytorch-sentiment-analysis</a> I try to modify above repository with torchtext.</p> <pre><code...
<p><code>torchtext.data.TabularDataset.splits</code> expects the keyword argument <code>fields</code> to be a list of tuples of <code>(str, torchtext.data.Field)</code>. You can fix your code by passing a list with appropriate ordering of values of your current <code>fields</code> dictionary.</p>
python|nlp|pytorch|sentiment-analysis
0
3,685
70,480,036
How can I return a Pandas DataFrame, if the row is between certain weekday and time?
<p>I'm trying to make a trading bot, that will be only running during the CME Bitcoin futures open and close. Sunday through Friday, from 5 p.m. to 4 p.m. Central Time (CT). However, I want the bot running, starting from 5 p.m. Friday to 4 p.m. Sunday. I want the bot running at all time during that period, even outside...
<p>Use the code below:</p> <pre><code># Initialize your min_time and max_time values df[df['time'] &gt; min_time and df['time'] &lt; max_time] </code></pre>
python|pandas|datetime
0
3,686
42,673,175
pandas df.mean for multi-index across axis 0
<p>How do you get the mean across axis 0 for certain mult-index <code>(index_col [1])</code>? I have</p> <p>df:</p> <pre><code> 1 2 3 h a 1 4 8 h b 5 4 6 i a 9 3 6 i b 5 2 5 j a 2 2 2 j b 4 4 4 </code></pre> <p>I would like to create df1 - mean of 2n...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> by second level with <code>mean</code>:</p> <pre><code>print (df.groupby(level=1).mean()) 1 2 3 a 4.000000 3.000000 5.333333 ...
python|pandas|dataframe
4
3,687
42,790,280
Gradient descent optimization for multivariate scalar functions
<p>I attempted to test my gradient descent program on rosenbrock function. But no matter how I adjusted my learning rate (<code>step</code> argument), precision (<code>precision</code> argument) and number of iterations (<code>iteration</code> argument), I couldn't get a very close result.</p> <pre><code>import numpy ...
<p>Your method is vulnerable to overshoot. In a case with instantaneously high gradient, your solution will jump very far. It is often appropriate in optimization to refuse to take a step when it fails to reduce cost.</p> <h1>Linesearch</h1> <p>Once you have chosen a direction by computing the gradient, search <em>alon...
python|numpy|optimization|scipy|gradient-descent
2
3,688
42,594,695
How to apply a function / map values of each element in a 2d numpy array/matrix?
<p>Given the following numpy matrix:</p> <pre><code>import numpy as np mymatrix = np.matrix('-1 0 1; -2 0 2; -4 0 4') matrix([[-1, 0, 1], [-2, 0, 2], [-4, 0, 4]]) </code></pre> <p>and the following function (sigmoid/logistic):</p> <pre><code>import math def myfunc(z): return 1/(1+math.exp(-z...
<p>Apparently, the way to apply a function to elements is to convert your function into a vectorized version that takes arrays as input and return arrays as output.</p> <p>You can easily convert your function to vectorized form using <code>numpy.vectorize</code> as follows:</p> <pre class="lang-py prettyprint-override"...
numpy
73
3,689
27,056,016
Numpy get elements by incrementing the index of element
<pre><code>import numpy as np a = np.array([1,2,13,7,3,5]) index = a == 13 print a[index+1] </code></pre> <p>The expected result is 7. How to get?</p>
<h3>Foreword</h3> <p>My proposed solutions are a generalization of the OP question, because the OP array had just an occurrence of the number <code>13</code> and here I treat the possibility of having more than a single occurrence.</p> <p>All my solutions except one are based on the idea of the circularity of a list ...
numpy
1
3,690
27,100,431
len(n) x len(m) array in NumPy
<pre><code>n = ' AAADDDEEE' m = ' AADDDEB' </code></pre> <p>How to create numpy of dimensions len(n) x len(m) where n is the first row, m is first column and all the other entries are empty</p> <p>i.e.</p> <pre><code> A A A D D D E E E A [][][][][][][][][] A [][][][][][][][][] D [][][][][][][][][] D [][][][][][][]...
<pre><code>&gt;&gt;&gt; arr = np.empty((len(m), len(n)), dtype=str) &gt;&gt;&gt; arr.fill('') &gt;&gt;&gt; arr[0] = list(n) &gt;&gt;&gt; arr[:,0] = list(m) &gt;&gt;&gt; arr array([['A', 'A', 'A', 'D', 'D', 'D', 'E', 'E', 'E'], ['A', '', '', '', '', '', '', '', ''], ['D', '', '', '', '', '', '', '', ''], ...
python|arrays|numpy|matrix
2
3,691
27,219,916
New column with column name from max column by index pandas
<p>I want to create a new column with column name for the max value by index.</p> <p>Tie would include both columns.</p> <pre><code> A B C D TRDNumber ALB2008081610 3 1 1 1 ALB200808167 1 3 4 1 ALB200808168 3 1 3 1 ALB200808171 2 2 5...
<p>you can do:</p> <pre><code>&gt;&gt;&gt; f = lambda r: ','.join(df.columns[r]) &gt;&gt;&gt; df.eq(df.max(axis=1), axis=0).apply(f, axis=1) TRDNumber ALB2008081610 A ALB200808167 C ALB200808168 A,C ALB200808171 C ALB2008081710 D dtype: object &gt;&gt;&gt; df['best'] = _ &gt;&gt;&gt; df ...
python|pandas
3
3,692
26,947,447
How can I get Numpy to give an array of lists instead of tuples?
<p>When I make a numpy array out of my data, I get (as expected) a list of lists, but when I declare data types for them, I get what appears to be a list of tuples, which is no good. This is a problem because numpy seems to think that the first array is a 2D array, while the second is a 1D array (it gives its <code>.sh...
<p>As @Ashwini commented, these are neither lists of lists nor lists of tuples, they're both numpy arrays. You can still access "columns" (actually called "fields", here) and "rows" (actually called "records") from that new array. I don't recommend converting it to a list of anything.</p> <pre><code>a = np.array(mte...
python|arrays|numpy
2
3,693
27,105,676
Numpy: Multiply a matrix with an array of vectors
<p>I'm having a hard time getting into numpy. What I want in the end is a simple quiver plot of vectors that have been transformed by a matrix. I've read many times to just use arrays for matrices, fair enough. And I've got a meshgrid for x and y coordinates</p> <pre><code>X,Y = np.meshgrid( np.arange(0,10,2),np.arang...
<p>You can either do matrix multiplication "manually" using NumPy broadcasting like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt X,Y = np.meshgrid(np.arange(-5,5), np.arange(-5,5)) a = np.array([[0.5, 0], [0, 1.3]]) U = (a[0,0] - 1)*X + a[0,1]*Y V = a[1,0]*X + (a[1,1] - 1)*Y Q = plt.quive...
numpy|scipy
6
3,694
25,115,080
Python - 'numpy.float64' object is not callable using minimize function for alpha optimization for Simple Exponential Smoothing
<p>I'm getting the TypeError: 'numpy.float64' object is not callable error for the following code:</p> <pre><code>import numpy as np from scipy.optimize import minimize def ses(data, alpha): fit=[] fit.append(alpha*data[1] + (1-alpha)*data[0]) for i in range(2, len(data)): fit.append(data[i]*alph...
<p>Its hard to tell exactly what the problem is here. I assume that <code>minimize</code> is actually <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.minimize.html" rel="nofollow">Scipy's minimize</a>. </p> <p>If so the first argument should be a function. Instead, you are passing th...
python|optimization|numpy|scipy|minimize
1
3,695
30,718,231
Aggregating lambda functions in pandas and numpy
<p>I have an aggregation statement below:</p> <pre><code>data = data.groupby(['type', 'status', 'name']).agg({'one' : np.mean, 'two' : lambda value: 100* ((value&gt;32).sum() / reading.mean()), 'test2': lambda value: 100* ((value &gt; 45).sum() / value.mean())}) </code></pre> <p>I continue to get key errors. I have b...
<p>You need to specify the column in <code>data</code> whose values are to be aggregated. For example,</p> <pre><code>data = data.groupby(['type', 'status', 'name'])['value'].agg(...) </code></pre> <p>instead of </p> <pre><code>data = data.groupby(['type', 'status', 'name']).agg(...) </code></pre> <p>If you don't ...
python|numpy|pandas|lambda
44
3,696
19,437,474
get the last row of a pandas DataFrame, as an iterable object
<p>I want to return an iterable object that consists of the values in the last row of a pandas DataFrame. This seems to work, though it's kind of verbose:</p> <pre><code>data.tail(1).itertuples(index=False).next() # get the first item when iterating over the last 1 items as a tuple, # excluding the index </code></p...
<p>Access the underlying array with the <code>.values</code> attribute and unpack it into the builtin <code>iter</code> function.</p> <pre><code>In [29]: df = pd.DataFrame([['a', 'b'], ['c', 'a']], columns=['A', 'B']) In [30]: df Out[30]: A B 0 a b 1 c a In [31]: gen = iter(*df.tail(1).values) In [32]: nex...
python|pandas|dataframe
3
3,697
12,884,362
vstack numpy arrays
<p>If I have two ndarrays:</p> <pre><code>a.shape # returns (200,300, 3) b.shape # returns (200, 300) numpy.vstack((a,b)) # Gives error </code></pre> <p>Would print out the error: ValueError: arrays must have same number of dimensions</p> <p>I tried doing <code>vstack((a.reshape(-1,300), b)</code> which ki...
<p>You don't specify what final shape you actually want. If it's (200, 300, 4), you can use <code>dstack</code> instead:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.random.random((200,300,3)) &gt;&gt;&gt; b = np.random.random((200,300)) &gt;&gt;&gt; c = np.dstack((a,b)) &gt;&gt;&gt; c.shape (2...
numpy
0
3,698
29,033,245
Time dependent data in Mayavi
<p>Assuming I have a 4d numpy array like this: <code>my_array[x,y,z,t]</code>.</p> <p>Is there a simple way to load the whole array into Mayavi, and simply selecting the <code>t</code> I want to investigate for?</p> <p>I know that it is possible to animate the data, but I would like to rotate my figure "on the go".</...
<p>It is possible to set up a dialogue with a input box in which you can set <code>t</code>. You have to use the traits.api, it could look like this:</p> <pre><code>from traits.api import HasTraits, Int, Instance, on_trait_change from traitsui.api import View, Item, Group from mayavi.core.ui.api import SceneEditor, Ml...
python|numpy|multidimensional-array|mayavi
1
3,699
33,706,301
Running seq2seq model error
<p>I am trying to run the code in this <a href="http://tensorflow.org/tutorials/seq2seq/index.md" rel="nofollow">tutorial</a>. </p> <p>When I try to run this command:</p> <pre><code>sudo bazel run -c opt tensorflow/models/rnn/translate/translate.py -- -- data_dir ../data/translate/ </code></pre> <p>I get the follo...
<p>It seems there are a lot of mistakes in the Tensorflow tutorial.. I was able to run it by removing the .py, and adding an extra -- before the options like:</p> <p>bazel run -c opt tensorflow/models/rnn/translate/translate -- --data_dir /home/minsoo/tensorflowrnn/data</p> <p>the directory part should be changed acc...
tensorflow
0