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
350,500
61,281,287
how to iterate using iterrows() and check for a subset
<p>I would find the rows in a dataframe which contains all of the elements of a tuple and then set a value in a specific column for the corrisponding index of the row</p> <pre><code>for ix, row in df.iterrows(): if set(tuple).issubset(row): df.loc[ix, ['label']] = 1 </code></pre> <p>but I get this error:</...
<p>Use a list comprehension for example with random generated data:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(2) tuples = list(zip(np.random.randint(0, 5, 10), np.random.randint( 10, 15, 10), np.random.randint(20, 30, 10))) data = pd.DataFrame(dict(tups=tuples)) data.head() # tups...
python|pandas|loops|dataframe|hashable
0
350,501
61,363,599
Group a dataframe based on column
<pre><code>df: AAAA BBBB CCCC 1111 17878 2 2 2222 17878 2 3 3333 11777 2 4 4444 11888 5 5 </code></pre> <p>I have a series below:</p> <pre><code>ser: 17878 11777 </code></pre> <p>I want my df to look like thi:</p> <pre><code>df: AAAA BBBB CCCC 1111 17878 2 2 222...
<p>Something like this might work - </p> <pre><code>df = df[df['AAAA'].isin(ser.tolist())] </code></pre>
python|pandas
0
350,502
61,428,473
Tkinter 'module' object is not callable
<p>im getting the above error when i run this code snippet. Im trying to error proof user input by creating an error window when the user enters a value not in a dataframe. the code im running is below</p> <pre><code>import tkinter as tk import tkinter.messagebox import pandas as pd root= tk.TK() def customer_search()...
<p><code>tk.messagebox</code> is a module containing multiple dialogs, you probably want to use <code>tk.messagebox.showerror("Info Title", "Info content")</code>.</p> <p>Other dialogs are <code>showwarning</code> and <code>showinfo</code>, depending on your use case.</p>
python|pandas|tkinter|error-handling
1
350,503
61,398,866
UTC to PST with multiple columns using Python
<p><strong>Background</strong></p> <p>I have a dataframe, df: I would like to convert the date timestamps from UTC to PST in both columns.</p> <pre><code> Connected Ended 3/3/2020 1:00:00 PM 3/3/2020 1:01:00 PM 3/4/2020 4:00:00 PM 3/4/2020 4:05:00 PM </code></pre> <p><stron...
<p>you can try something like this:</p> <pre><code>In [22]: import pandas as pd ...: d = pd.Series(['2020-04-23 19:57:55', '2020-04-23 19:59:46']) ...: d = pd.to_datetime(d) ...: d ...: Out[22]: 0 2020-04-23 19:57:55 1 2020-04-23 19:59:46 dtype: datetime64[ns] In [23]: d_pacific_tz_aware = d.dt.tz...
python|pandas|datetime
0
350,504
61,200,258
pandas bring data from one df to another issue
<p>I have a data set that has a count of duplicates:</p> <pre class="lang-py prettyprint-override"><code>#Count number of injuries by levels for each players levelcount = df.groupby(['Relinquished','Severity']).size().reset_index(name='count') levelcount['DTD'] = '' levelcount['DNP'] = '' levelcount['out indefinitely'...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> with dictionary for new column, append to index by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow nor...
python|pandas
1
350,505
61,587,738
Python: Add index an index value to each array element
<p>I'm trying to measure the precision and recall of a knn algorithm on the Iris dataset without using sklearn or something similar. My idea is to append both the predicted and the true values with an index, like that:</p> <pre><code>id = [i for i in range(1,len(np.asarray(y_pred))+1)] y_pred_id = np.insert(y_pred, 0,...
<p>If I understood correctly, you want an <code>n x 2</code> size matrix after inserting <code>id</code> to <code>y_pred</code>. If so, you can do it in following ways:</p> <p>Option-1: Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow noreferrer">np.reshape</a></p> <...
python|arrays|numpy|indexing|knn
3
350,506
61,550,684
converting a list of pairs in a column into two columns using pandas dataframe
<p>I have a dataframe df with two columns as follows:</p> <pre><code> ID Country_pairs 0 X [(France, USA), (USA, France)] 1 Y [(USA, UK), (UK, France), (USA, France)] </code></pre> <p>I want to output all possible pairs of countries in two columns as follows:</p> <pre><code>ID Country1 Country2 X F...
<p>You are looking for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>.explode()</code></a></p> <pre><code>result = df.explode('Country_pairs') result["Country1"] = result.Country_pairs.apply(lambda t:t[0]) result["Country2"] = result....
python|pandas
1
350,507
61,574,814
Is there a way of fixing the Labels on my line graph?
<p>I have written a simple python code with Spyder to generate a line graph representing Average House price (Y-axis) against the year (x-axis) there are about 600 entries into the data frame for each though as there is data for every month since 1969 to 2019. This has caused the line graphs x-axis to just be a big bla...
<p>So you could do two things:<br> 1) Setting the range</p> <pre><code>matplotlib.pyplot.xticks(range(5)) </code></pre> <p>That would limit the labels on the x-axis.<br> 2) Turning the x-axis label</p> <pre><code>matplotlib.pyplot.xticks(rotation=45) </code></pre>
python|pandas|matplotlib
0
350,508
61,321,777
Rename pandas entries within if-loop
<p>I got a dataframe that looks like that: </p> <pre><code> appended_data ... ... Out[24]: Unnamed: 0 Region GeneID DistanceValue 229676 229676 8.0 69013161 0.972237 229677 229677 8.0 75931496 0.978386 229678 229678 8.0 73424023 0.982667 229679 ...
<h1><code>Series.map</code></h1> <p>If you ever use <code>for i in range(..)</code> as an iterator then alarm bells should go off as Python as a built in iterator which can be accessed via <code>enumerate</code></p> <p>You've not given a minimum example of what layer names is, but it seems like it's a list.</p> <p>we c...
python|pandas
1
350,509
61,352,733
Getting the avarage value from a column in a dataframe if a column contains a string specified in another dataframe
<p>I have a large dataframe (prices) that contains a long description and a price associated to that description. I generated another dataframe (words) that keeps all the unique words that those long descriptions has. What I'm trying to do is to fetch the average price of a particular word from the prices dataframe and...
<p>Easiest would be to use <code>Series.str.extractall</code>, then <code>join</code> the extractions back on the <code>index</code> and finally use <code>GroupBy.mean</code>:</p> <pre><code>matches = ( prices['TEXT'].str.extractall(f'({"|".join(words["WORD"])})') .rename(columns={0:'WORDS'}) .rename_axis(...
python|pandas|dataframe
1
350,510
61,381,736
How to plot 4 graphs in one screen for twinx or twiny method?
<p>I want to plot two y-axis and one x-axis, for only one picture in one graph window i know how to do , but how to change this code to draw 4 pictures in one graph window?</p> <pre><code>ax1 = axes() ax2 = ax1.twinx() x = np.arange(100) y1 = np.random.rand(100) y2 = np.random.rand(100) ax1.plot(x,y1,'-r') ax1.set_y...
<p>Here is a possible way to go about it. I have only twined one axis, but indeed all axis can be treated similarly.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np fig, axarr = plt.subplots(nrows=2, ncols=2) axTx = axarr[0, 0].twinx() x = np.logspace(-1, 1, 100) axarr[0, 0].plot(x, x, linewidth=2, c...
python-3.x|pandas|numpy|matplotlib
2
350,511
61,293,791
Time comparison for data load using pyspark vs pandas
<p>I am new to spark. I assume that when you read data(in my case csv) using spark, it by defaults create multiple tasks and read the file in parallel chunks. I am reading a same file using SqlContext and pandas, apparently the read using spark is taking longer than pandas. Would anyone know if there is a any differenc...
<p>When you run a spark application in <code>local</code> mode it basically means that the Driver and Executor are running in the same JVM and it uses the number of threads that you specify.</p> <p>In this specific case only <code>local</code> has been mentioned and the below table shows what are the different differe...
python|pandas|apache-spark
0
350,512
61,429,200
How do I convert these coordinates to real numbers?
<p>I have something like this in two columns in one dataframe <code>data= pd.read_csv('xxxxxxxxxxxx.dat',delimiter=';',encoding='latin_1')</code> in python Latitude=60°11.7765 Longitude=024°57.3073</p> <p>And I would like to get this:</p> <p>Latitude=60.1177.... Longitude=024.573....</p>
<p>The question you asked seems to want a simple substitution of some char, not a real conversion of coordinates. Thanks to the comments I understood that this ambiguity was due to the fact that you yourself did not have clear how to get the conversion. Among the different type of coordinates we find DDM (degrees deci...
python|coordinates|transform|openstreetmap|geopandas
0
350,513
61,533,291
Is it still necessary to install CUDA before using the conda tensorflow-gpu package?
<p>When I install tensorflow-gpu through Conda; it gives me the following output:</p> <pre><code>conda install tensorflow-gpu Collecting package metadata (current_repodata.json): done Solving environment: done ## Package Plan ## environment location: /home/psychotechnopath/anaconda3/envs/DeepLearning3.6 added ...
<blockquote> <p>Do i now have two versions of CUDA installed and how do I check this?</p> </blockquote> <p>No.</p> <p>conda installs the bare minimum redistributable library components required to support the CUDA accelerated packages they offer. The package name <code>cudatoolkit</code> is a complete misnomer. It is n...
python|tensorflow|cuda|conda|cudnn
8
350,514
68,472,628
Numpy unique: count for values also not in array?
<p>I have an array as so:</p> <pre><code>myarray = [['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']] </code></pre> <p>And for this, <code>np.unique(myarray, return_counts=True)</code> works amazingly and gives me the desired output. However I would then like to apply it row by row, and for it to...
<p>You can use <code>np.unique</code> with <code>return_inverse=True</code> to get what you want:</p> <pre><code>letters, inv = np.unique(myarray, return_inverse=True) inv = inv.reshape(myarray.shape) </code></pre> <p><code>inv</code> is now</p> <pre><code>array([[0, 1, 2], [1, 2, 3], [2, 3, 4]], dtype=in...
python|numpy
2
350,515
68,751,344
My neural network gives an error and I don't know why
<p>I'm relatively new to programming neural networks and have been following a few tutorials about it before deciding to try and learn to program neural networks on my own using what i'd learnt. I've been trying to program a basic neural network just so i can learn how it works, but it keeps giving me an error. I would...
<p>The error is cause <code>Conv2D</code> expects input shape to be of 4 dimensions i.e. [batch_size, height, width, channels]. You can do one thing i.e. reshape your input to the model.</p> <pre><code>X = X.reshape(-1, 28, 28, 1) # incase of single channel (grayscale) # OR X = X.reshape(-1, 28, 28, 3) # incase of RGB ...
python|tensorflow|machine-learning|keras|neural-network
0
350,516
68,516,630
White space not trimming in Pandas dataframe csv export
<p>I'm trying to do a simple strip of all the white space in a column of my dataset, but when I export it out as a CSV, space is still there. Is there any reason that this would be occurring?</p> <pre><code>import pandas as pd excel_path = &quot;testfile.xlsx&quot; data = pd.read_excel(excel_path, usecols=&quot;B,D,E...
<p><a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.strip.html" rel="nofollow noreferrer"><code>.str.strip()</code></a> returns a new Series, it doesn't modify the column in place. So assign that back to the DataFrame column</p> <pre><code>data[&quot;Name&quot;] = data[&quot;Name&quot;].str.strip...
python|pandas
2
350,517
68,634,662
Store same value at rows of column B with identical negative numbers in column A of a pandas dataframe
<p>I have a pandas dataframe that looks like this:</p> <pre><code>import pandas as pd import numpy as np d = {'value1': [1, 2, 3, -4, 5, -1, 7, -2, 4], 'value2': [100, 200, 200, 300, np.nan, np.nan, np.nan, np.nan, np.nan]} df = pd.DataFrame(data=d) df value1 value2 1 100.0 2 200.0 3 200.0 -4 3...
<p>use <code>groupby()</code>+<code>abs()</code>+<code>ffill()</code>:</p> <p>groupby the absolute values of 'value1' column then forward fill the values of 'value2' and finally assign that back to 'value2' column:</p> <pre><code>df['value2']=df.groupby(df['value1'].abs())['value2'].ffill() </code></pre> <p>output of <...
python|pandas|dataframe|numpy
0
350,518
68,643,831
How to use argmax on a numpy array
<p>I'm using Keras deep learning in Python. I have a numpy array that has this shape: [5, 30, 30, 30, 65] I want to perform an argmax along the 5th dimension (65), setting the index of the highest value in each 5th array to 1 and all others to 0. For context, the array is being outputted by a generator model, and I'm u...
<p>To perform the <code>argmax</code> operation on the 5th dimension, you can specify the <code>axis</code> parameter using 0-based counting. <br></p> <p>Therefore, to get the <code>argmax</code> for the 5th dimension you would use: <br> <code>idx = np.argmax(arr, axis=4)[0, 0, 0, 0]</code></p> <p>Then, to covert the 5...
python|machine-learning|numpy-ndarray
1
350,519
68,590,183
how to find TPR and TPR from its labels and probablites to evaluate my model?
<p>I need help regarding the data frame which I have asked in this question <a href="https://stackoverflow.com/questions/68394653/how-to-sort-14-columns-not-by-row-based-on-their-value-not-using-if-condition-in/68395682#68395682">Link</a>. Now I want to evaluate the model to find the total; like finding <code>True Posi...
<p>From your new <code>DataFrame</code> :</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df file set label bbx Atelectasis Cardiomegaly Consolidation Edema Effusion Emphysema Fibrosis Hern...
python|pandas|csv|model
2
350,520
68,562,020
When appending to a list within a dictionary within a Pandas DataFrame, it appends to all dictionaries in column instead of the one I'm pointing to
<p>This is my code</p> <pre><code>import pandas as pd keys = ['phone match', 'account match'] d = {k: [] for k in keys} df = pd.DataFrame(data=[[1,2,3],[4,5,6]],columns=['A','B','C']) df['D'] = [d for _ in range(df.shape[0])] df.at[0, 'D']['phone match'].append(4) </code></pre> <p>But instead of appending only on the...
<p>You need to create multiple <code>dict</code> in order to make each of them have different object ID</p> <pre><code>keys = ['phone match', 'account match'] df = pd.DataFrame(data=[[1,2,3],[4,5,6]],columns=['A','B','C']) df['D'] = [{k: [] for k in keys} for _ in range(df.shape[0])] # Change here df.at[0, 'D']['phone...
python|pandas|dataframe|dictionary|append
1
350,521
68,810,758
Pandas Numbers entered as Text when parsed adds one decimal point and shows data type as float64
<p>when I import a csv file (df=pd.read_csv('File_Name.csv') One of the columns which has numbers entered as text to allow having Zero at the beginning of the number appear as float64 data type, so when I try to get the length of the numbers in that column by typing df['Column_Name'].astyp('str').str.len()) i get 8 cha...
<p>Glad to answer on your question. when you import a csv file, you can add dtype parameter as 'str'.</p> <p>So, you can change the code as below :</p> <pre><code>df = pd.read_csv(&quot;test.csv&quot;, dtype=str) </code></pre> <p>Hope that you get any help from my advice. Thanks.</p>
python|pandas|dataframe|jupyter-notebook
0
350,522
68,790,855
pandas returns a series instead of a dataframe while adding a new column
<p>I am trying to perform a simple operation of creating a new dataframe from an existing dataframe and also trying to add a new column at the same time. However, pandas returns a series instead of a dataframe.</p> <p><code>controls['DESC']=cells1['CEL_DESCRIPTION']</code></p> <p>I get the following error for: <code>pr...
<p>I use this code and don't get an error:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd old = pd.DataFrame({'temp_c': [17.0, 25.0]},index=['Portland', 'Berkeley']) print(old) new = old.copy().assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32) print();print(new) print();print(new.info()) </code...
python|python-3.x|pandas|dataframe
0
350,523
68,644,810
Generate an array of random floats summing to 1 while fixing a few elements in python
<p>I have something like below:</p> <p><code>random_array = np.random.random(10)</code></p> <p><code>scaled_array = random_array/np.sum(random_array)</code></p> <p>This gives me a nice array with random floats that sum to 1. However, I am trying to take this a step further and do the following:</p> <p>For example, <str...
<p>If you want the values before scaling:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np random_array = np.random.random(10) random_array[1] = 0.04 random_array[4] = 0.09 scaled_array = random_array/np.sum(random_array) assert np.isclose(1, scaled_array.sum()) </code></pre> <p>If you want fixe...
python|pandas|numpy
1
350,524
68,744,708
matplotlib scatter plotting with noncontiguous yaxis ticks with datatype as integer
<p><em>My question:</em> while plotting x and y values from a dataframe, if we have y values as discrete numbers say, id_number or category. if we use scatter plot, it will give linearly spaced yaxis ticks which may have large vertical spacing in between the plotted values depending on how much spaced our original valu...
<p>You can do it by replacing <code>ax1.scatter</code> with <a href="https://seaborn.pydata.org/generated/seaborn.stripplot.html" rel="nofollow noreferrer"><code>seaborn.stripplot</code></a>:</p> <pre><code>sns.stripplot(ax = ax1, data = df, x = 'xval', y = 'yval_str', marker = 'o', color = 'white', edgecolor = 'green'...
python|pandas|dataframe|matplotlib|timeline
3
350,525
68,856,572
Python pandas dataframe, how to get the set number
<p>Here is eaxmple:</p> <pre><code>df=pd.DataFrame([('apple'),('apple'),('apple'),('orange'),('orange')],columns=['A']) df Out[5]: A 0 apple 1 apple 2 apple 3 orange 4 orange </code></pre> <p>I want to assign a number next to it, example, apple is the first set of list ['apple','orange'], B column is ...
<p>You can use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.factorize.html" rel="nofollow noreferrer"><code>pd.factorize</code></a> function. This function is used to convert arrays into categorical ones.</p> <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.factorize.html" rel=...
pandas|dataframe
2
350,526
68,729,727
Inconsistent AttributeError: 'str' object has no attribute
<p>I am learning how to create heatmaps from CSV datasets using Pandas, Seaborn and Numpy.</p> <pre><code># Canada Cases Year overview - Heatmap # Read file and separate needed data subset canada_df = pd.read_csv('https://raw.githubusercontent.com/datasets/covid-19/main/data/countries-aggregated.csv', usecols = [0, 1,...
<p>Some of your indexes are not in a date format (2 elements are string, which are the two lasts elements)</p> <pre><code># check the type of the elements in index count = pd.Series(canada_heatmap.index).apply(type).value_counts() print(count) &lt;class 'pandas._libs.tslibs.timestamps.Timestamp'&gt; 110370 &lt;clas...
python|pandas|dataframe|numpy
1
350,527
68,507,350
During the calculation of mean of a column in dataframe that contain missing values
<p>Let's take an example. suppose we have a data frame that has column name &quot;f1&quot;</p> <blockquote> <p>f1 : {2, 4, NaN, 1, NaN, 15}</p> </blockquote> <p>and when we apply mean imputation to it then we write a code like this</p> <pre><code>dataframe['f1'].fillna(dataframe['f1'].mean()) </code></pre> <p>so my dou...
<p>According to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mean.html" rel="nofollow noreferrer">the official documentation of pandas.DataFrame.mean</a> &quot;skipna&quot; parameter excludes the NA/null values. If it was excluded from numerator but denominator this would be excl...
python|pandas|statistics|data-science|missing-data
1
350,528
68,518,002
Using python to solve nested functions (reccurring equations)?
<p>Is it possible to use python to find local maxima/minima for a nested function?</p> <p>For example <code>f(a,b) = a*5 / (a-b)</code> And nesting them -&gt; <code>f( f( f(a, b), b ), b)</code></p> <p>The nesting would need to be dynamically created, for example in a for loop:</p> <pre><code>def f(a,b): return a*5...
<p>First getting your equation is rather simple</p> <pre><code>import sympy a, b = sympy.symbols('a, b') def f(a, b): return a*5 / (a-b) g = a for x in range(3): g = f(g, b) g = sympy.simplify(g) </code></pre> <p>gives</p> <p><a href="https://i.stack.imgur.com/uOKNh.png" rel="nofollow noreferrer"><img src=...
python|python-3.x|numpy|sympy
2
350,529
68,659,965
Getting “no table found” error when web scraping with pandas for OTC Markets screener website
<p>I want to extract various statistics from this website(<a href="https://www.otcmarkets.com/research/stock-screener" rel="nofollow noreferrer">https://www.otcmarkets.com/research/stock-screener</a>). Unfortunately, pandas do not recognize the tables presented. Here is my code:</p> <pre><code>import requests import p...
<p>The page loads the data from external source (URL). You can use this example how to load the data from API and create a dataframe:</p> <pre class="lang-py prettyprint-override"><code>import json import pandas as pd url = &quot;https://www.otcmarkets.com/research/stock-screener/api&quot; data = json.loads(requests.g...
python|pandas|web-scraping|screen-scraping
1
350,530
68,683,256
How to define a column with underline in pandas dataframe?
<p>I would like to differentiate the header and data in pandas dataframe by keeping column names with underline. Or other way to achieve this is to draw a line between column-name and rows in pandas dataframe as shown below. I am running python code with 3.9.2 version in visual studio.</p> <p>Please advise if this can ...
<p>Try using <code>to_markdown</code>:</p> <pre><code>df.to_markdown('./output.txt', index=False, tablefmt='simple') !type output.txt # On windows machine </code></pre> <p>Output:</p> <pre><code> OFFICE NO DAY HOURS DAY RATES ----------- ----------- ----------- 101 8 60 102...
python|pandas|dataframe
1
350,531
68,763,902
Xarrays and calculate for each grid point of WRF output with a condition
<p>I have 10 years output from the WRF climate model. I am looking for an efficient code which for every grid point in the xarray selects only those number of days where T&gt;0 for more than 2 days. For my plots, I want for each month at each grid point the total number of days where T&gt;2 for more than 2 days.</p> <p...
<p>In general it is difficult to support you without a code that generates the issue you are running in.</p> <p>Stackoverflow is not there to help you learn programming. It is there to help find solutions for edge cases and issues.</p> <p>Never mind here are some thoughts for you. xarray is working similar as pandas. S...
python|pandas|python-xarray|weather
0
350,532
68,760,800
Turning a pandas column/series into multiple series
<p>I feel like I should be using a pivot_table here, but I can't seem to get it to work the way I want it to. Here is the data (note: it's a subset of the data):</p> <pre><code> sample_code analyte abundance_ppm 0 85GMC-RM001 Au 0.000 1 85GMC-RM001 Bi 0.000 2 85GMC-RM001 Ag ...
<p>Update,</p> <pre><code>df.pivot_table('abundance_ppm', 'sample_code', 'analyte', aggfunc='sum') # Pick you're aggfunc. 'sum', 'mean', 'first'. </code></pre> <p>Output:</p> <pre><code>analyte sample_code Ag As Au Bi Cd Co Cu Fe Hg Mn Mo Ni Pb Sb Zn 0 85GMC-RM001 0.4...
python|pandas
-1
350,533
68,861,566
Filling null vals in a dataframe
<p>I Have a column like this</p> <p>Jacob</p> <p>NaN</p> <p>NaN</p> <p>Max</p> <p>NaN</p> <p>Prince</p> <p>NaN</p> <p>NaN</p> <p>NaN</p> <p>I want to fill NaN vals like this</p> <p>Jacob</p> <p>Jacob</p> <p>Jacob</p> <p>Max</p> <p>Max</p> <p>Prince</p> <p>Prince</p> <p>Prince</p> <p>Prince</p> <p>Help Please</p>
<p>You can try this one :</p> <pre class="lang-py prettyprint-override"><code>df['col_name'].fillna(method='ffill') </code></pre>
python|pandas|jupyter-notebook|data-analysis|data-cleaning
0
350,534
68,488,719
How to covert comma separated row into a column and save to a file
<p>I need help in converting a row of comma separated values into separate rows and then saved to a file.</p> <p>Example:</p> <pre><code>R1,R2,R3 </code></pre> <p>to</p> <pre><code>R1 R2 R3 </code></pre> <p>This is what I have but all the files I'm creating have the values in one row separated by commas. Just trying ...
<p>Given a CSV file like (no headers)</p> <pre><code>R1,R2,R3 </code></pre> <p><strong>Try:</strong></p> <pre><code>import pandas as pd df = pd.read_csv('test_csv.csv', header=None) df = df.T print(df.T) </code></pre> <p><strong>Outputs:</strong></p> <pre><code> 0 0 R1 1 R2 2 R3 </code></pre>
pandas
1
350,535
68,776,819
group by without making any calculation
<p>I would like to know, if there is a function in which you can group the lines based on a column(like dealer) but without making any account (sum,mean,etc)</p> <p>Example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Dealer</th> <th>city</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>...
<p>Assuming the data frame is named <code>df</code>, you want to sort using `sort_values:</p> <pre><code>df.sort_values(by=['Dealer'], ascending=True, inplace=True) </code></pre> <p>The <code>inplace=True</code> will set the <code>df</code> to be used like this throughout its lifetime, if you don't want to keep the df ...
python|dataframe|pandas-groupby
1
350,536
68,513,604
Issue with reading files from using os.getcwd() on aws ElasticBean Stalk server
<p>My Flask/Dash application reads files <code>/data</code> directory. When I run the application locally, I use <code>os.getcwd()</code> to read the csv file.</p> <pre><code>df = pd.read_csv(os.getcwd() + &quot;/data/file1.csv&quot;) </code></pre> <p>However, when deploying the application to AWS EB instance / server,...
<p>I think you need to connect to the Elastic Beanstalk instance, find the filepath for your 'file1.csv' file, and use an absolute path for that.</p> <p>There are docs for how to connect to the EC2 instance that runs your EB instance <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.ec2conn...
python|pandas|amazon-web-services|flask|amazon-elastic-beanstalk
1
350,537
68,753,027
After install tensorflow in virtualenv, the vscode says the module is not found [ubuntu20.04 ]
<h2>I install tensorflow in virtualenv through pip.</h2> <h3>(my virtual environment's name is "object_venv")</h3> <p><a href="https://i.stack.imgur.com/HF8uF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HF8uF.png" alt="enter image description here" /></a></p> <p>code is like that.</p> <pre><code>...
<p>On visual studio code, you need to make sure that vs code is using the same version of python as your virtual environment. See <a href="https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment" rel="nofollow noreferrer">here for how to change the python version on VS Code</a>.</p>
tensorflow|ubuntu|visual-studio-code|pip|virtualenv
1
350,538
68,629,308
Scaling down a plot when using matplotlib
<p>I've been trying to plot a graph of Epoch vs Accuracy and val_accuracy from a train log I have generated. Whenever I try to plot it, the y-axis starts from 0.93 rather than it being in 0, 0.1 ,0.2... intervals. I'm new at using matplotlib or any plot function.</p> <p>Here's the code for it:</p> <pre><code>import pan...
<p>This has already been discussed <a href="https://stackoverflow.com/questions/3777861/setting-y-axis-limit-in-matplotlib">here. </a>There are a couple of different ways you can do this (using <code>plt.ylim()</code> or making a new variable like <code>axes</code> and then <code>axes.set_ylim()</code>), but the easies...
python|pandas|matplotlib|plot
0
350,539
68,630,924
Error when making predictions using keras .h5 model?
<p>I've trained a CNN model with an image dataset, saved the model with the name <em>classifier.h5</em>. Now, I need to load this model to make predictions. I've implemented code in the following way, but encountering an error <code>_maybe_load_initial_epoch_from_ckpt() takes 2 positional arguments but 3 were given</co...
<p>I don't know what caused the error. But, the following changes have resolved the issue. I removed the Graph part and loaded my model. Now it is showing the result.</p> <pre><code>class_dict = {'Bacterial leaf blight': 0, 'Brown spot': 1, 'Leaf Blast': 2, 'Leaf smut': 3 ...
python|tensorflow|machine-learning|keras|deep-learning
0
350,540
68,636,574
Passing all possible combinations of arguments to function
<p>I have this problem that I thought was a no-brainer, but I am apparently missing the logic behind passing arguments to a function. So, I have this dataframe,</p> <pre><code>id type zone d 0 1 a a1 23 1 1 a b1 45 2 1 a c1 23 3 2 a c1 56 4 2 b a1 7 5 2 b b1...
<p>You have to replace:</p> <pre><code>plt.suptitle(&quot;Accuracy for {} and zone {}&quot;.format(types).format(zone)) </code></pre> <p>by:</p> <pre><code>plt.suptitle(&quot;Accuracy for {} and zone {}&quot;.format(types, zone)) </code></pre> <p>or better:</p> <pre><code>plt.suptitle(f&quot;Accuracy for {types} and zo...
python-3.x|pandas
1
350,541
68,736,011
How to check ALL multi values of dictionary as a condition for pd.dataframe in Python
<p>I have a dictionary:</p> <pre><code>variables = { &quot;key1&quot;: [&quot;v1&quot;], &quot;key2&quot;: [&quot;v2&quot;,&quot;v3&quot;], &quot;key3&quot;: [&quot;v4&quot;,&quot;v5&quot;], } </code></pre> <p>and a dataframe: report_list which has multi columns including col1.</p> <p>...
<p>You can convert the values in the dict to a list with <code>list(variables.values())</code> and filter whether an item in <code>col1</code> is in the list, then convert the filtered dataframe to list to get the desired output:</p> <pre><code>import pandas as pd variables = { &quot;key1&quot;: [&quot;v1&quot...
python|arrays|pandas|string|list
0
350,542
68,846,627
How to create a numpy array filled with average value of a vector
<p>I am not sure how to phrase my question in any way better. Basically, I have three lists of the same length <code>x</code>, <code>y</code> and <code>z</code> and I want to fill a 2D numpy array in the z/y plane with the average of the associated z values.</p> <p>Here is how I can achieve what I wan to do:</p> <pre><...
<p>If I understand correctly what you want to do, maybe a 2D interpolation from <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp2d.html" rel="nofollow noreferrer"><code>scipy.interpolate.interp2d</code></a> is what you are looking for.<br /> You define the interpolation function of...
python|numpy|matplotlib|math|data-visualization
1
350,543
68,562,122
Apply custom function/operator between numpy arrays
<p>There are two arrays and I want to get distance between two arrays based on known individual elements distance.</p> <pre><code>dist = {(4,3): 0.25, (4,1):0.75, (0,0):0, (3,3):0, (2,1):0.25, (1,0): 0.25} a = np.array([[4, 4, 0], [3, 2, 1]]) b = np.array([[3, 1, 0]]) a array([[4, 4, 0], [3, 2, 1]]) b array([[3...
<p>Instead of storing your distance mapping as a <code>dict</code>, use a <code>np.array</code> for lookup (or possibly a sparse matrix if size becomes an issue).</p> <pre><code>d = np.zeros((5, 4)) for (x, y), z in dist.items(): d[x, y] = z </code></pre> <p>Then, simply index.</p> <pre><code>&gt;&gt;&gt; d[a, b] a...
python|numpy
1
350,544
68,493,217
best way to match one column in dataframe to multiple columns in another dataframe
<p>Suppose I have this df1:</p> <pre><code>df1 = pd.DataFrame({'name':['Sara', 'John', 'Christine'], 'email': ['sara@example.com', 'john@example.com', 'Christine@example.com']}) </code></pre> <p>df1:</p> <pre><code> name email 0 Sara sara@example.com 1 John john@example.com...
<p>try:</p> <p>The idea is to merge df1's 'email' on each column of cols(present in df2 named like email)</p> <pre><code>cols=['email_id', 'alternate email', 'alternate email2'] out=(pd.concat([df1.merge(df2,left_on='email',right_on=x) for x in cols]) .drop_duplicates(subset=['name'],ignore_index=True).drop(cols...
python|python-3.x|pandas|dataframe
1
350,545
68,469,185
Applying a custom function to a dataframe column
<p>Is there a way to optimize the below code snipped? I am trying to calculate the value of the current row column using the previous row column value and a period specified in the custom function and a price in the current row column.</p> <pre><code>import pandas as pd class EMA_Period: fast = 8 slow = 17 def ...
<p>Thanks @Mars</p> <pre><code>def calc_ema(df, period=8, col_name='fast'): prev_value = df.iloc[0][col_name] def func2(row): # non local variable ==&gt; will use pre_value from the new_fun function nonlocal prev_value prev_value = prev_value + (2.0 / (1.0 + period)) * (row['close'] - pr...
python|pandas|dataframe
0
350,546
68,795,553
Find index of a row in numpy array
<p>Given m x n numpy array</p> <pre><code>X = np.array([ [1, 2], [10, 20], [100, 200] ]) </code></pre> <p>how to find index of a row, i.e. [10, 20] -&gt; 1?</p> <p>n could any - 2, 3, ..., so I can have n x 3 arrays</p> <pre><code>Y = np.array([ [1, 2, 3], [10, 20, 30], [100, 200, 300] ]) </code></pre> <p>s...
<p>Just in case that the query array contains duplicate rows that you are looking for, the function below returns multiple indices in such case.</p> <pre class="lang-py prettyprint-override"><code>def find_rows(source, target): return np.where((source == target).all(axis=1))[0] looking = [10, 20, 30] Y = np.array...
python|numpy
4
350,547
68,757,767
Group by based on user id and their interactions
<p>Dataset and Notebook file : <a href="https://drive.google.com/drive/folders/14z16wOEjKe299oSxu_wlh5Zr-dfbnXgE?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/drive/folders/14z16wOEjKe299oSxu_wlh5Zr-dfbnXgE?usp=sharing</a></p> <p>Can anyone help me out on this?</p> <p>I have dataframe (named as dfm2)<...
<p>To avoid user_id being set as index, use <code>as_index=False</code> in the <code>groupby</code> like:</p> <pre><code>df_total_questions_attempted = dfm2.groupby(['user_iD'], as_index=False)['question_id'].count() </code></pre> <p>By default the values are sorted on the groupby keys, in case you don't want the value...
python|pandas|pandas-groupby
1
350,548
68,558,061
Python pandas - Finding time duration
<p>I am facing problem while finding the duration. The df is</p> <pre><code>data ={ 'initial_time': ['2019-05-21 22:29:55','2019-10-07 17:43:09','2020-12-13 23:53:00','2018-04-17 23:51:23','2016-08-31 07:40:49'], 'final_time' : ['2019-05-22 01:10:30','2019-10-07 17:59:09','2020-12-13 00:30:10','2018-04-18 01:0...
<p>The problem can be broken down into 3 parts:</p> <ol> <li>convert strings to datetime objects</li> <li>write function that compute duration between 2 datetime objects</li> <li>apply the function to the new column of your dataframe</li> </ol> <hr /> <ol> <li>datetime_object = datetime.strptime('2019-05-21 22:29:55', ...
python|pandas|time|duration
0
350,549
68,739,691
How to use GPU with tensorflow
<p>I'm running in a virtual environment.</p> <p>So basically I have installed tensor flow, and when I run <code>import tensorflow as tf</code> the output I get is.</p> <pre><code>2021-08-11 17:42:31.395050: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'...
<p>I suppose you use Windows (due to the Error message)</p> <p>You have to install NVIDIA CUDA - tensorflow 2.5.x uses 11.2 (see <a href="https://www.tensorflow.org/install/source#gpu" rel="nofollow noreferrer">version Table</a>) also, i would recommend installing CUDNN 8.x too, since some layers (for instance LSTM) wi...
python|tensorflow
0
350,550
68,501,584
Loss increases after 4000 Epochs
<p>I am trying to train a RNN Network for stock price prediction for my Master Thesis. I have additional input values (6), not just the stock prices by itself.</p> <p>Using an LSTM Network with the &quot;optimal&quot; structure based on Hyperparameter Tuning with Keras Tuner, i observed a significant increase in the lo...
<p>Your learning rate (often called alpha) is probably too large. Try to factor the learning rate down and try again.</p>
python|tensorflow|keras|lstm
0
350,551
68,514,887
Delete pandas dataframe NaN rows selectively, grouped by id column which contains duplicates
<p>I have a pandas dataframe like below: <code>user</code> id is a column which can contain duplicates. <code>C1,C2,C3</code> are also columns.</p> <p>I want to delete only those rows which has duplicated <code>user</code> column and have NaN for all values in <code>C1,C2,C3</code> columns for those rows.</p> <p>Expect...
<p>We can create an inclusive mask to keep rows where it is both not a <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>duplicated</code></a> <code>id</code> and cols <code>C1</code>, <code>C2</code>, and <code>C3</code> are <a href="https://pandas.pyd...
python|pandas|dataframe|duplicates
2
350,552
68,455,200
Test for np.nan in row wise function
<p>I have a function that I want to apply to each row of a data frame to create a new column. The value returned from the function will be different if certain columns are NaN. I have several conditions in the function (more complicated than the example below), otherwise, I would use <code>np.where</code>.</p> <p>How d...
<p>Use <code>np.where</code>:</p> <pre><code>&gt;&gt;&gt; df name id position 0 dave 123456.0 NaN 1 hagen NaN 5600.0 </code></pre> <pre><code>df['test'] = np.where(df['id'].isna(), 'missing id', 'has an id') </code></pre> <pre><code>&gt;&gt;&gt; df name id position test...
python|pandas|numpy
1
350,553
68,623,833
Regressor with LSTM layer keeps returning same value
<p>If I run following code, I am getting array of the same values (predicted), as you can see here: <a href="https://i.stack.imgur.com/e3f7a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e3f7a.png" alt="enter image description here" /></a></p> <p>Basically my input to regressor is array of numbers ...
<p>Your model is absolutely overkill for this problem but this is not a issue ! We want to predict a linear function wich can be present with only 2 parameters (predicted = model(x) = param1 + param2 * x). A model with only one neurone (wheight + bias) should be enough. Here your model have 91,251 parameters ! Model us...
tensorflow|machine-learning|keras|neural-network|lstm
2
350,554
68,858,469
How to split JSON row data into multiple columns in Python
<p>I'm trying to find a way to split (flatten) JSON row data into multiple columns in pandas.</p> <p>I have a dataframe which looks like the following:</p> <p><a href="https://i.stack.imgur.com/9v3RL.png" rel="nofollow noreferrer">Current Dataframe</a></p> <p>This is an example of what a row looks like:</p> <p><a href=...
<p>If it's a flat json then you can try :-</p> <p><code>new_df = pd.DataFrame(df['tickers'].tolist())</code></p> <p>The Dataframe constructor takes in a list of dictionary objects and turns the key into columns as default orientation, this is the simplest way if your data is standardized and doesn't have a complex nest...
python|json|pandas|data-wrangling
0
350,555
68,721,056
Extract Acronyms and Māori (non-english) words in a dataframe, and put them in adjacent columns within the dataframe
<p>Regular expression seems a steep learning curve for me. I have a dataframe that contains texts (up to 300,000 rows). The text as contained in <code>outcome</code> column of a dummy file named <code>foo_df.csv</code> has a mixture of English words, acronyms and Māori words. <code>foo_df.csv</code> is as thus:</p> <pr...
<p>You can't magically tell if a word is English/Māori/abbreviation with a simple short regex. Actually, it is quite likely that some words can be found in multiple categories, so the task itself is not binary (or trinary in this case).</p> <p>What you want to do is natural language processing, here are some <a href="h...
python-3.x|regex|pandas|nlp|acronym
1
350,556
68,505,593
How to normalize a nested .json?
<p>So I am using Mapbox web API and have a .json returned. I've been having trouble and difficulties parsing .jsons. One of the challenge I'm having is that the returned .json is nested. Here is the .json:</p> <pre><code>{ &quot;type&quot;:&quot;FeatureCollection&quot;, &quot;query&quot;:[ -73.989, 40...
<p>Add the column <code>query</code> after <code>json_normalize</code>:</p> <pre><code>df.insert(0, 'query', [data['query']] * len(df)) </code></pre>
python|json|pandas|normalize
1
350,557
68,776,834
Panda dataframe : plot histogram with grouping
<p>I have table data available in following format :</p> <pre><code>id value valid 1 0.43323 true 2 0.83122 false 3 0.33132 true 4 0.58351 false 5 0.74143 true 6 0.44334 true 7 0.86436 false 8 0.73555 true 9 0.56534 false 10 0.66234 true ... </code></pre> <p>I am trying to plot a histog...
<p>Try:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt np.random.seed(123) df = pd.DataFrame( { &quot;value&quot;: np.random.random(1000), &quot;valid&quot;: np.random.choice([True, False], p=[0.7, 0.3], size=1000), } ) df[&quot;label&quot;] = pd.cut(df[...
python|pandas|dataframe|histogram
2
350,558
68,833,709
pandas.errors.InvalidIndexError: Reindexing only valid with uniquely valued Index objects
<p>I have two dataframes with unique indexes:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'a':[4,6,3,0], 'b':[5,6,3,9], 'c':[4,3,6,6]}, index=['a1','a2','a3','a4']) df2 = pd.DataFrame({'a':[10,5,13,10], 'b':[52,61,33,19], 'c':[14,23,36,16]}, index=['b1','b2','b3','b4']) </code></pre> <p>However, when I con...
<p>So for purposes of demo'ing what I was doing I posed the above to represent my data (proprietary data) and the challenge I was facing. It turned out that the sample above works so it wasn't a good representation. The actual problem has over 100 dataframes.</p> <p>Anyway I figured the issue was due to some dataframes...
python-3.x|pandas|dataframe
0
350,559
68,695,217
Making an AI model that converts songs into a game level?
<p>I want to create an AI that coverts songs into beatsaber levels (It's a VR game). A beatsaber level can be stored as a array of &quot;blocks&quot; that looks like this:</p> <pre><code>{ &quot;time&quot;: 1.25, &quot;direction&quot;: &quot;up&quot;, &quot;hand&quot;: &quot;right&quot;, &quot;pos_x&quot;: 0, ...
<p>Here is a paper about a very similar AI: <a href="https://arxiv.org/pdf/1703.06891.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1703.06891.pdf</a></p> <p>They use <strong>two</strong> Neural Networks, the first one extracts audio features like Drums and decides when to place blocks <strong>(timing of blocks)...
python|tensorflow|keras|deep-learning|neural-network
1
350,560
68,529,950
is there any solution to convert the raw data into some categorized datasets
<p>I have a data set that has values like Hindi, hindi, hendi, English, Englsh, inglish, inglsh...so on. I want this data set to bifurcate into different datasets which will be having similar kinds of values. for example in this case two datasets; the first is having values Hindi, hindi, hendi and another consists of E...
<p>You can can use <a href="https://docs.python.org/3/library/difflib.html#difflib.get_close_matches" rel="nofollow noreferrer"><code>difflib.get_close_matches</code></a></p> <p>Input:</p> <pre><code>&gt;&gt;&gt; s = pd.Series(['Hindi', 'hindi', 'hendi', 'English', 'Englsh', 'inglish', 'inglsh']) &gt;&gt;&gt; s 0 Hin...
python|pandas|database|numpy|stata
0
350,561
68,608,749
Performant way to fill holes for categorical data?
<p>We have 3D segmentation masks where every class has its own label / ID. For every class we would like to fill holes in the segmentation.</p> <p>For an example, the following matrix:</p> <pre><code>[ [ [ 1, 1, 1, 2, 2, 2 ], [ 1, 1, 1, 2, 2, 2 ], [ 1, 1, 1, 2, 2, 2 ], [ 0, 3, 0, 0, 4, 0 ], [ 3, 3...
<p><code>binary_fill_holes</code> is not very efficiently implemented: it seems to not make use of SIMD instruction and is not parallelized. It is also based on a pretty intensive algorithm (iterative erosion). Since this function is run for each label, your final implementation is very computationally intensive. One s...
python|numpy|scipy
2
350,562
68,594,558
How to efficiently match two pandas data frame with regard to multiple columns?
<p>I have a dataframe df1 with 8M rows and 7 columns. One of the columns (‘ID’) is a sample ID, column A is a binary variable and other 5 columns are float values.</p> <pre><code>df1 = pd.DataFrame(np.random.random_sample((df_1_size, 5)), columns=list('BCDEF')) df1['A'] = np.random.randint(1,3,size=df_1_size) df1['ID']...
<p>This may not be the full solution to your problem but it works for <code>topk = 1</code> 10x faster than the original one.</p> <pre><code>for a_val in df1['A'].unique(): np1 = df1[df1['A'] == a_val][match_based_on].values np2 = df2[df2['A'] == a_val][match_based_on].values similarities = cdist(np2, np1, ...
python|python-3.x|pandas|cosine-similarity
0
350,563
36,422,178
Pandas Dataframe Making a Dataframe from Slicing Time Series
<pre><code>pieces_v = [[sensor_values[i: i + 6]] for i in xrange(4)] </code></pre> <p>So pieces_v looks like this:</p> <pre><code>[[0 -60.244999 1 -51.290001 2 -52.727001 3 -60.962002 4 -51.230000 5 -58.717999 Name: -64.251, dtype: float32], [1 -51.290001 2 -52.727001 3 -60.962002 4 -51.230000 5 ...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p> <pre><code>print pd.concat([pd.Series(sensor_values[i: i + 6].values) for i in xrange(4)], axis=1) 0 1 2 3 0 -60.244999 -51.290001...
python|pandas
0
350,564
36,410,287
Dropping some columns when using to_csv in pandas
<p>I have a data frame which I want to write to tow files, one that contains all of the columns and one that has only a subset of the columns So for this data frame: </p> <pre><code> Out_data Out[9]: A B C D E F 0 354 49985400 10 07 7.140899 0.2...
<p>You should be using <code>columns</code> as the keyword argument, not <code>cols</code>.</p> <pre><code>Out_data.to_csv(filename, mode='w', columns=['A','B','C','D'], index=False) </code></pre>
python|pandas
16
350,565
36,322,081
Efficient way to count the greater than operation for each value itself
<p>I have a numpy vector containing real values. For each value in this vector i want to count the number of values greater than value itself.</p> <p>For example:</p> <pre><code>input: array([1.,2.,3.,1.,1.,0.,10.]) # numpy array output: array([3, 2, 1, 3, 3, 6, 0]) </code></pre> <p>My first idea was:</p> <pre><cod...
<p>One simple way to do this is by using Python's <code>bisect</code> module:</p> <pre><code>import bisect array = [1.,2.,3.,1.,1.,0.,10.] n = len(array) sorted_array = sorted(array) print [n - bisect.bisect(sorted_array, val) for val in array] </code></pre> <p>This creates a sorted copy of the array, and then uses b...
python|numpy|pandas|scipy
4
350,566
36,326,544
python shell import pandas
<p>I have been using pandas and numpy in the iPython Notebook for Python 2.7 and 3.5 without problems for some time. Now I am switching to the Python Shell for some tasks, but when I type <code>import pandas</code> in the shell, I receive the following error:</p> <pre><code>Traceback (most recent call last): File "&...
<p>For some reason your python shell is using different environment variables that your ipython notebook. Could be due to various reasons, maybe you've installed python from the official website, and another distribution such as anaconda (happenned to me for this reason).</p> <p>To check if that interpretation is corr...
python-2.7|shell|python-3.x|pandas
2
350,567
36,461,222
Pandas Rolling_std with Window using all previous row counts
<p>I want to calculate the rolling_std for daily returns, using all records previous to the current row. How do i set the window to use the rolling count of the rows? For example: on <code>04-04</code>. I want to use all rows to calculate, on <code>04-01</code> I want to use all rows with date less than <code>04-01</co...
<p>With pandas 0.18, use the <code>Rolling</code> object. This is a 2-day rolling std:</p> <pre><code>df.rolling(2).std() </code></pre> <p>With prior version, the call would be:</p> <pre><code>df.rolling_std(2) </code></pre> <p>If the goal is to get the function applied from the beginning of the DataFrame down to t...
python|windows|pandas|dataframe
6
350,568
36,421,913
Apply function to masked numpy array
<p>I've got an image as numpy array and a mask for image.</p> <pre><code>from scipy.misc import face img = face(gray=True) mask = img &gt; 250 </code></pre> <p>How can I apply function to all masked elements?</p> <pre><code>def foo(x): return int(x*0.5) </code></pre>
<p>For that specific function, few approaches could be listed.</p> <p><strong>Approach #1 :</strong> You can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow"><code>boolean indexing</code></a> for in-place setting -</p> <pre><code>img[mask] = (i...
python-2.7|numpy|mask
4
350,569
36,321,898
python pandas dataframe: transform a column and append it to the end
<p>I have the following code, trying to transform column v2, and add a new column:</p> <pre><code>df = pd.read_csv('test1.csv') for index, row in df.iterrows(): v4 = myFunction.classify(row['v2']) row['v4'] = v4 row.append(v4) </code></pre> <p>However, the line <code>row.append(v4)</code> doesn't work. Wh...
<p>Can your function accept a column and output a column? If so you do not need to iterate over your df. Just pass in a column and assign the output to v4.</p> <pre><code>v4 = myFunction.classify(df['v2']) df['v4'] = v4 </code></pre> <p>If you function needs individual input then create the column 'v4' first and then...
python|pandas|transformation
1
350,570
36,663,575
Pandas Dataframe drop items where index condition is true
<p>I have a pandas dataframe which contains Dates &amp; Prices</p> <p>Now I have a Pandas Series of the same length of Dates in the above with Dates and a True or False boolean indicating whether I should remove the point.</p> <p>I want to remove the items from the rawdata where condition is true</p> <pre><code>out...
<p>Instead of dropping, select only those rows that should remain:</p> <pre><code>In [83]: idx Out[83]: Date 1990-01-29 False 1990-01-30 True 1990-01-31 True 1990-01-02 False 1990-02-02 False Name: Cond, dtype: bool In [84]: df Out[84]: Price Date 1990-01-29 11.11 1990-01-30 12.01 1990-...
python|pandas
1
350,571
36,502,987
Peak Detection Using the Lomb-Scargle Method
<p>I am trying to get a Python code working that finds peaks in data using the Lomb-Scargle method. </p> <p><a href="http://www.astropython.org/snippets/fast-lomb-scargle-algorithm32/" rel="nofollow noreferrer">http://www.astropython.org/snippets/fast-lomb-scargle-algorithm32/</a></p> <p>Using this method as below,</...
<p>After some digging, it looks like AstroML method is the best. </p> <pre><code>import numpy as np from matplotlib import pyplot as plt from astroML.time_series import lomb_scargle, search_frequencies import pandas as pd df = pd.read_csv('extinct.csv',header=None) Y = df[0] dy = 0.5 + 0.5 * np.random.random(len(df)...
python|numpy|scipy|signal-processing
0
350,572
36,615,883
I am getting a wrong output for numpy.sum
<p>I have the variable X of the type numpy.ndarray</p> <pre><code>X = [[ 0.44381946 0.27899923 0.4949196 ] [ 0.84257149 0.30482022 0.62306499] [ 0.59696025 0.36293078 0.42723482] [ 0.85710666 0.61489953 0.58918237] [ 0.99383178 0.88306841 0.85875682]] </code></pre> <p>When I use numpy.sum(X , axis=1)...
<p>The array is defined incorrectly. You need commas between the elements on each line and also a comma between the numbers in each array row. See below for the proper syntax. </p> <p><strong>Python (saved in file numpyArray.py)</strong></p> <pre><code>import numpy as np X = np.array([[ 0.44381946, 0.27899923, 0.49...
python|numpy
2
350,573
36,373,349
Lists, matrices and dataframes in python
<p>I am working in python and am having problems understanding the relations between lists, numpy arrays and matrices and pandas dataframes.</p> <p>I know the following, to go from a df to a matrix is enough to call as_matrix(). I am now trying to create a numpy matrix from a double list. My list has 3 lists of 891 el...
<p>Your problem is that a item of matrix is ..... a matrix. Since you have only one line, <code>tt==tt[0]</code> and so on. Indexing array is different, <code>ndim(a[0])</code> is more intuitively <code>ndim(a)-1</code>.</p>
python|numpy|matrix
2
350,574
5,184,817
Python: Get item from list based on input
<p>I appreciate this may not be directly possible so I would be interested how you would go about solving this problem for a general case. I have a list item that looks like this, <code>[(array,time),(array,time)...]</code> the array is a numpy array which can have any n by m dimensions. This will look like <code>array...
<p>If I'm understanding your question correctly, you essentially want to select indexes from a list of lists, and create new lists from that selection.</p> <p>Selecting indexes from a list of lists is fairly simple, particularly if you have a fixed number of selections:</p> <pre><code>parts = [(item[pos1], item[pos2]...
python|list|numpy
1
350,575
5,178,055
Curve fitting in python
<p>Hey, I have a set of values for frequency and power spectrum and I have to plot Power spectrum Versus frequency on log scale. Once done, I need to pass the best fit straight line through it.. I get the line on a linear scale.. but when I try to superimpose it onto the freq-power spectrum plot, the resultant plot doe...
<p>Despite the fact that the plot line commands are not correct in your example I assume it is similar to what you actually do.</p> <p>The second plot command plots on a different x range:</p> <pre><code>loglog(yval,zval) # plot yval vs zval loglog(line) # plots range(0,len(line)) vs line </code></pre> <p>Also hav...
python|numpy|matplotlib|curve-fitting
2
350,576
5,446,365
interpolation with python numpy
<p><br> I have an array of samples y, and corresponding x values. Some y-values may be missing and I'd like to use linear interpolation to compute them. What is the best way of doing it with python (I'm using numpy arrays). If you could provide me a sample code that would be great.</p> <p>thanks</p>
<p>See the interpolation method in the numpy documentation that has examples:</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html" rel="noreferrer">http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html</a></p> <p>There are also a more extensive set of methods availabl...
python|numpy|interpolation
9
350,577
5,036,816
Numpy Lookup (Map, or Point)
<p>I have a large numpy array:</p> <pre><code>array([[32, 32, 99, 9, 45], # A [99, 45, 9, 45, 32], [45, 45, 99, 99, 32], [ 9, 9, 32, 45, 99]]) </code></pre> <p>and a large-ish array of unique values in a particular order:</p> <pre><code>array([ 99, 32, 45, 9]) # B </code></pre> <p>How...
<p>Here you go</p> <pre><code>A = array([[32, 32, 99, 9, 45], # A [99, 45, 9, 45, 32], [45, 45, 99, 99, 32], [ 9, 9, 32, 45, 99]]) B = array([ 99, 32, 45, 9]) ii = np.argsort(B) C = np.digitize(A.reshape(-1,),np.sort(B)) - 1 </code></pre> <p>Originally I suggested: </p> <pre><code>D = np.choose(C,ii)....
python|indexing|numpy
8
350,578
5,334,012
Optimizing my Cython/Numpy code? Only a 30% performance gain so far
<p>Is there anything I've forgotten to do here in order to speed things up a bit? I'm trying to implement an algorithm described in a book called Tuning Timbre Spectrum Scale. Also---if all else fails, is there a way for me to just write this part of the code in C, then be able to call it from python?</p> <pre><code>i...
<p>Here are some things that I noticed:</p> <ol> <li>Use <code>t1.shape[0]</code> instead of <code>np.shape(t1)[0]</code> and in so on in other places.</li> <li>Don't use <code>len</code> as a variable because it is a built-in function in Python (not for speed, but for good practice). Use L or something like that.</li...
python|numpy|cython
9
350,579
5,486,226
Rolling median in python
<p>I have some stock data based on daily close values. I need to be able to insert these values into a python list and get a median for the last 30 closes. Is there a python library that does this?</p>
<p>In pure Python, having your data in a Python list <code>a</code>, you could do</p> <pre><code>median = sum(sorted(a[-30:])[14:16]) / 2.0 </code></pre> <p>(This assumes <code>a</code> has at least 30 items.)</p> <p>Using the NumPy package, you could use</p> <pre><code>median = numpy.median(a[-30:]) </code></pre>
python|finance|quantitative-finance|pandas
11
350,580
53,018,648
Create parameter for multidimensional evaluation in Python/Numpy
<p>I have a functional evaluation which has many parameters, and I want to vectorize the evaluation. Something like this:</p> <pre><code> I = 100 J = 34 K = 6 i, j, k = array(range(I)), array(range(J)), array(range(K)) i, j, k = meshgrid(i, j, k) f = myfun(i, j, k) </code></pre> <p>This is excellent, howe...
<p>Your </p> <pre><code>In [116]: i.shape Out[116]: (34, 100, 6) </code></pre> <p>If <code>p.shape</code> is (100,6), then <code>p</code> will broadcast with <code>i,j,k</code> without further change. That is <code>p[None,:,:]</code> expansion is automatic.</p> <p>If you'd used <code>i, j, k = np.meshgrid(i, j, k, ...
python|numpy
0
350,581
52,906,516
Reformatting scraped data using Python Selenium Webdriver.
<p>I want to extract all the names of the brands on the webpage and paste it into an excel (xlsx) file. The code I've used is:</p> <pre><code>browser.get("https://www.bluesign.com/industry/manufacturers/references.html") time.sleep(2) item_list_new=[] link = browser.find_element_by_xpath("//div[@class='defaultMain']")...
<p>Just Use: </p> <pre><code>&gt;&gt;&gt; df_links_list = pd.DataFrame(links_list_dict).T #Transpose </code></pre> <p>for example: </p> <pre><code>&gt;&gt;&gt; a = {"N":["a","b","c","d"]} &gt;&gt;&gt; c = pd.DataFrame(a).T &gt;&gt;&gt;c Out[10]: 0 1 2 3 N a b c d </code></pre> <p>if you need with...
python-3.x|pandas|selenium-webdriver
0
350,582
53,161,726
Python: Drop Pandas row if function returns false, utilizing is _land check through Cartopy
<p>I want to drop a row based on whether the function returns true or not, the function checks whether the latitude and longitude values are on land. I want to drop rows where the lat/long returns false. </p> <p>This is what I have so far but im stuck:</p> <pre><code>def LAND_SHAPE_READER(): land_shp_fname = shpr...
<p>I think the safest way to do this would be to create a new column that stores your IS_LAND value.</p> <pre><code># Apply this function to every row, where x is the row # Save the True/False return value as a column df['IS_LAND_RETURN'] = df.apply(lambda x: IS_LAND(x['Longitude'], x['Latitude']), axis=1) </code></pr...
python|python-3.x|pandas|cartopy
0
350,583
53,274,465
Python rolling assignment based on a regex match
<p>I'm trying to figure out how to do a rolling assignment based on a regex match. I have a dataframe of keys (keys_df) and dataframe of new data coming in (new_df). For each name in the new_df if the name contains any of the substrings in the <code>keys_df.contains</code> column, then assign the <code>parent_id</code...
<p>Using <code>pandas</code> <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>str.extract</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</cod...
python-3.x|pandas
2
350,584
53,344,965
how to remove 0's from a string without impacting other cells in pandas data frame?
<p>I have a data frame which has "0's" and looks as below:</p> <pre><code>df = pd.DataFrame({ 'WARNING':['4402,43527,0,7628,54337',4402,0,0,'0,1234,56437,76252',0,3602], 'FAILED':[0,0,'5555,6753,0','4572,0,8764,8753',9876,0,'0,4579,7514'] }) </code></pre> <p>I want to remove the zeroes from the strings where ...
<pre><code>df = pd.DataFrame({ 'WARNING':['0,0786,1230,01234,0',4402,0,0,'0,1234,56437,76252',0,3602], 'FAILED':[0,0,'5555,6753,0','4572,0,8764,8753',9876,0,'0,4579,7514'] }) df.apply(lambda x: x.str.strip('0,|,0')).replace(",0,", ",") </code></pre> <p>Output:</p> <pre><code> WARNING FAI...
python|pandas
3
350,585
53,065,843
How to sort the columns of a pandas data frame by the values of an index
<p>Is there a possibility to sort the columns of a pandas df by the values of a particular index?</p> <pre><code>price / time load_1 load_2 load_3 load_4 price 50, 68, 23, 12 2018-01-01 00:00:00 12, 65, 37, 8 2018-01-01 00:15:00 13, 54, 112, 6 2018-01-...
<p>If index name is <code>price</code> then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a> with <code>axis=1</code>:</p> <pre><code>print (df.columns) Index(['load_1', 'load_2', 'load_3', 'load_4'], dtype='obj...
python|pandas|sorting|dataframe
4
350,586
53,160,640
Checking when more than one dataframe column has specific values in Python
<p>I have data that is in the form that looks like:</p> <pre><code>Shop Date Produced Lost Output Signal Cornerstop 01-01-2010 0 1 9 1 Cornerstop 01-01-2010 11 1 11 0 Cornerstop ...
<p>Try <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer">Boolean indexing</a>:</p> <pre><code>data[(data['Produced'] == 0) &amp; (data['Lost'] != 0) &amp; (data['Output'] != 0) &amp; (data['Signal'] != 0)] </code></pre>
python|python-3.x|pandas|dataframe|if-statement
1
350,587
53,336,391
Python: how to drop duplicates with duplicates?
<p>I have a dataframe like the following</p> <pre><code>df Name Y 0 A 1 1 A 0 2 B 0 3 B 0 5 C 1 </code></pre> <p>I want to drop the duplicates of <code>Name</code> and keep the ones that have <code>Y=1</code> such as:</p> <pre><code>df Name Y 0 A 1 1 B 0 2...
<p>Use <code>drop_duplicates</code> method, </p> <pre><code>df.sort_values('Y', ascending= False).drop_duplicates(subset=['Name']) </code></pre>
python|pandas
2
350,588
53,263,516
is there a way to change RASA_NLU config from visual c++ 14.0 to MinGW
<p>is there a way to change RASA_NLU config from visual c++ 14.0 to MinGW</p> <p>error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": <a href="http://landinghub.visualstudio.com/visual-cpp-build-tools" rel="nofollow noreferrer">http://landinghub.visualstudio.com/visual-cpp-buil...
<p>Please make sure that <code>C:\MinGW_w64\bin</code> is in your <code>PATH</code> environment variable. Then create a file <code>distutils.cfg</code> in the directory <code>&lt;Python Installation Directory&gt;\Lib\distutils</code> and add the following content:</p> <pre><code>[build] compiler=mingw32 [build_ext] c...
python|tensorflow|rasa-nlu
1
350,589
53,094,100
Errno 13 while Transfer-learning Inception v3
<p>So I just learned python a couple of weeks ago, and I'm new to tensorflow. But I need to fine-tune the inception model. While trying to follow some tutorials, when I finally started to see some light, I got this horrible error that I can´t get rid of. Here is the part of the code that has the error:</p> <pre><code>...
<p>EDIT: You called <code>imread</code> for a directory, which is actually not an image. Are your images in <code>C:\tf_files</code>? If so, use <code>os.listdir()</code> to get ALL (including non-image) files within a directory. So your code (should be) like this: </p> <pre><code>train_dir=r'C:\tf_files' # The direc...
python|tensorflow|matplotlib|deep-learning|conv-neural-network
0
350,590
53,176,928
Loop to perform same upsampling task over several pandas dataframes for logistic regression
<p>I have a series of dataframes containing daily rainfall totals (continuous data) and whether or not a flood occurs (binary data, i.e. 1 or 0). Each data frame represents a year (e.g. df01, df02, df03, etc.), which looks like this:</p> <pre><code>date ppt fld 01/02/2011 1.5 0 02/02/2011 0.0 0 03/02...
<p>Giving you the benefit of the doubt that you're using the same <code>mask</code> syntax in your second code block as in your first, it looks like you may not have any samples to pass in to your <code>resample</code> in one or more of your DFs:</p> <pre><code>df=pd.DataFrame({'date':[1,2,3,4,5,6],'ppt':[1.5,0,2.7,4....
python|pandas|dataframe|scikit-learn
0
350,591
53,183,067
ndarray to table (from step function result)
<p>I am working on survival function, and as an output I get this probability in ndarray</p> <pre><code> array([StepFunction(x=array([ 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, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 4...
<p>Looks like you need to convert a numpy array to an xls file? If so one way would be to get help from Pandas facilities.</p> <pre><code>import pandas as pd ## convert your array into a dataframe df = pd.DataFrame (array) ## save to xlsx file filepath = 'my_excel_file.xlsx' df.to_excel(filepath, index=False) </co...
python|arrays|numpy
0
350,592
53,313,913
How to convert 2D matrix to 3D tensor without blending corresponding entries?
<p>I have data with the shape of <strong>(3000, 4)</strong>, the features are <strong>(product, store, week, quantity)</strong>. Quantity is the target. </p> <p>So I want to reconstruct this matrix to a tensor, without blending the corresponding quantities.</p> <p>For example, if there are 30 product, 20 stores and 5...
<p>If there is no dummies, you just have to carefully sort our data. np.lexsort can do it.</p> <p>Suppose your data looks like <code>data</code>:</p> <pre><code>import numpy as np dims=a,b,c=30,20,5 data=np.array(list(product(*[np.arange(i) for i in dims+(1,)]))) data[:,-1]=np.random.randint(0,100,a*b*c) np.random.sh...
python|tensorflow
2
350,593
53,139,422
3-D Matrix Multiplication in Numpy
<p>I have to multiply two 2-D matrices, <code>bob</code> and <code>tim</code>, in Numpy Python 3.x</p> <p><code>bob.shape</code> gives <code>(2,4)</code></p> <p><code>tim.shape</code> gives <code>(7,4)</code></p> <p>This piece of code gives a 3-D matrix with a shape of <code>(2,7,4)</code></p> <pre><code>np.array([...
<p>See <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="noreferrer">Python Broadcasting</a></p> <pre><code>bob.reshape((2, 1, 4)) * tim.reshape((1, 7, 4)) </code></pre>
python|python-3.x|numpy|matrix|numpy-ndarray
5
350,594
53,119,642
Tensorflow: Determinism of AdamOptimizer when running in CPU
<p>In my application I optimize a neural network using the apply_gradient() and the AdamOptimizer. I noticed that I cannot reproduce the results exactly every time I run my application and it is required in order to compare results. While searching for similar issues I noticed that the issue of non-determinism can be e...
<p>In case some else encounters the same problem, the solution is to set the gate_gradients flag to True in tf.gradients(). Using this you lose parallelism and performance during the calculation and the application of the gradients to the optimizer, but you gain reproducibility.</p>
python|tensorflow
0
350,595
52,969,034
Pandas to_csv correct way to handle UnicodeEncodeError
<p>I'm processing a file csv file with pandas, so, I open it:</p> <pre><code>df = pd.read_csv(my_file, low_memory=False) </code></pre> <p>I'm applying some sanitizing functions, changing some strings to numbers, and then when I want to save the dataframe into a file I do this:</p> <pre><code>df.to_csv(output_file, i...
<p>I had the same issue openning a russian database. Try calling read_csv with encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' (these are some of the various encodings found on Windows).</p> <pre><code>df= pd.read_csv('xxx.csv',encoding ='latin1') </code></pre>
python|python-2.7|pandas|ascii
1
350,596
53,143,418
Check if nodes share a mutual connection in DiGraph
<p>I am working with network data, trying to use a pandas dataframe to describe a networkx DiGraph. I would like rows for every pair in the graph and a column that indicates if there is both an edge <code>(node1,node2)</code> and <code>(node2,node1)</code>--that there is a mutual connection in the graph. </p> <p>I can...
<p>You can use Pandas and Nnumpy for such tasks:</p> <pre><code>x = pd.DataFrame(list(Test.edges()), columns=['a','b']) res = pd.DataFrame( np.unique(np.sort(x.merge(x.rename(columns={'a':'b', 'b':'a'})), axis=1), axis=0), columns=['a','b']) </code></pre> <...
python|pandas|networkx
2
350,597
53,237,197
How to bin data in data frame in pandas
<p>I have a time series data, say machine reading as follows(Say)</p> <pre><code>df['machine_r'] = [1,2,1,5,3,4,5,1,2,3,4,5,7,8,1,2.....] </code></pre> <p>How to change the data frame like following</p> <pre><code>If data in dataframe &lt;= 25 percentile, value = 0.25, if 25p &lt; data &lt;=50p value = 0.50, if ...
<p>You can cast it to float by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow noreferrer"><code>astype</code></a>:</p> <pre><code>df['new'] = pd.cut(df['machine_r'], bins=bins,labels=labels).astype(float) </code></pre> <p>Also better is use <a href="https://pan...
python|pandas|dataframe|statistics
1
350,598
53,187,734
Tensorflow cannot load mnist
<p>I downloaded a copy of mnist data from a random website because the official website was down. Which directory can I put the mnist file for tensorflow's input_data method to pick it up</p>
<p>Maybe this <a href="https://stackoverflow.com/questions/42927841/trouble-reading-mnist-with-tensorflow">Link</a> help you.</p> <p>Another way to use MNIST dataset: some Frameworks like Tensorflow and Keras has this dataset. So you can use this:</p> <pre><code># Import MNIST from tensorflow.examples.tutorials.mnist...
tensorflow|mnist
2
350,599
53,131,311
Starting jupyter lab on mounted drive with tensorflow docker image
<p>On the official Tensorflow website documentation <a href="https://www.tensorflow.org/install/docker" rel="nofollow noreferrer">TF</a>, it details how to install the latest nvidia and tensorflow Docker images. I then mounted my host directory and launch jupyter notebook by:</p> <pre><code>$ docker run -it --rm \ -p...
<p>You could write your own dockerfile which installs all dependencies and is based the tensorflow image. You could for example alter the run command that it changes the directory. Or you create a different image which installs Jupyter hub and starts the Instance on run. You can find a nice explanation on how to creat...
docker|tensorflow|jupyter-notebook|jupyter|jupyter-lab
0