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
15,200
58,450,394
Drop all rows in all columns in pandas dataframe if the value in the column row is zero
<p>I want to drop all rows that are zero in the "feet" column.</p> <pre><code>df['feet'] = df['feet'][(df != 0).all(1)] dataset.info() </code></pre> <p>the above code gives such a result:</p> <pre><code>col1 8640 non-value object col2 8640 non-value object col3 8640 non-value object col4 8640 non-value object feet...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p> <pre><code>df1 = df[df['feet'] != 0] </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.quer...
python|pandas
2
15,201
58,303,648
How do I loop through a Pandas DataFrame and call a function on each cell
<p>I'm using the following code to rate text</p> <pre><code>import textstat import pandas as pd test_data = ("""Jonathan pushed back the big iron pot and stood up. There were no bears. But up the path came his father, carrying his gun. And with him were Jonathan's Uncle James and his Uncle Samuel, his Uncle John and ...
<p>Apply is here to do the job in pandas DataFrame and Series.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html</a></p> <p>And you can find some examp...
python|pandas|dataframe
2
15,202
58,604,843
how to use column of tokenized sentences to further tokenize into words
<p>i have tokenized a text in a column into a new column 'token_sentences' of sentence tokens. i want to use 'token_sentences' column to create a new column 'token_words' containing tokenized words.</p> <p>df i am using</p> <pre><code>article_id article_text 1 Mar...
<pre><code>from nltk.tokenize import word_tokenize def join(token_sentences): return " ".join(token_sentences) new_df = df['token_sentences'].apply(join).apply(word_tokenize) </code></pre> <p>new_df will be your token sentences then add this df to your df like join function for joining your sentences i didn't rea...
python|pandas|nlp
0
15,203
58,536,852
Selecting a subset based on multiple slices in pandas/NumPy?
<p>I want to select a subset of some pandas DataFrame columns based on several slices. </p> <pre><code>In [1]: df = pd.DataFrame(data={'A': np.random.rand(100), 'B': np.random.rand(100), 'C': np.random.rand(100)}) df.head() Out[1]: A B C 0 0.745487 0.146733 0.594...
<p>A bit late, but it might also help others:</p> <pre><code>pd.concat([df.loc[sl, ['B', 'C']] for sl in [slice(1, 4), slice(42, 44)]]) </code></pre> <p>This also works when your are dealing with other slices, e.g. time windows.</p>
python|pandas|numpy|indexing|slice
1
15,204
58,206,062
Why is Python eval returning same object for Keras regularizer?
<p>I am trying to convert strings (which I read from a JSON) to arguments that can be used by Keras layers. However when I find that all the regularizer objects created by the eval function are the same. </p> <pre><code>a = eval('l1(0.1)') b = eval('l2(0.1)') c = eval('l1_l2(0.1)') print(a,b,c) </code></pre> <p>gives...
<p><code>L1L2</code> stores both <code>l1</code> and <code>l2</code>; on the regularizer, run, for example:</p> <pre class="lang-py prettyprint-override"><code>print(model.layers[1].kernel_regularizer.__dict__) # {'l1': array(0., dtype=float32), 'l2': array(1., dtype=float32)} </code></pre> <p>To access one or the ot...
python|tensorflow|keras|eval
1
15,205
58,444,047
Create choropleth function for Plotly not working
<p>Hi I am following the plotly tutorial to plot all the US counties. However, I keep getting an error saying: The create_choropleth figure factory requires the plotly-geo package. I have already installed plotly-geo using pip but it is still giving me this error. Any help would be greatly appreciated! I have attached ...
<p>Ended up fixing it by moving file over to google drive and running on Google Collaboratory.</p>
python|numpy|plotly|geo|choropleth
0
15,206
68,888,750
Using iloc for indexing
<p>Here is my dataset:</p> <p><a href="https://i.stack.imgur.com/EdDuAm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EdDuAm.png" alt="enter image description here" /></a></p> <p>I want to put in the column 'Solicitud de personacion' if its values are zero the values in the column 'Solicitud de per...
<p>Use <code>where</code>:</p> <pre><code>df['Solicitud personacion'] = df['Solicitud de personacion_'].where(df['Solicitud personacion'].eq(0), df['Solicitud personacion']) </code></pre>
python|pandas|indexing|uilocalnotification
1
15,207
69,172,431
Python Pandas - Convert dataframe into json
<p>I have this pandas.dataframe:</p> <pre><code> date. pid value interval 0 2021-09-05 00:04:24 1 5.554 2021-09-05 00:00:00 1 2021-09-05 00:06:38 1 4.359 2021-09-05 00:05:00 2 2021-09-05 00:06:46 1 18.364 2021-09-05 00:05:00 3 2021-09-05 00:04:24 2 15.554 2021-09...
<p>Create helper column with <code>pid</code>, convert to <code>MultiIndex Series</code> and last crate nested dictionary:</p> <pre><code>s = (df.assign(new = 'pid' + df['pid'].astype(str)) .groupby(['interval','new'])[['date','pid','value']] .apply(lambda x : x.to_dict(orient= 'records'))) d = {level: s...
python|pandas
3
15,208
69,005,495
apply to a rolling window function loses column names
<p>I have a function that takes a <code>dataframe</code>:</p> <pre><code>def max_dd(df): print(df) return None </code></pre> <p>If I <code>print df.head()</code> before passing it to <code>max_dd</code>, it looks like this:</p> <pre><code>print(df.head()) Close Date 2010-08-10 7.95 2010-08-11 ...
<p><a href="https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.apply.html" rel="nofollow noreferrer"><code>Rolling.apply</code></a> func does not receive a DataFrame as parameter but a Series:</p> <pre><code>def max_dd(df): print(df) print(type(df)) return None new = df.rollin...
python|pandas|rolling-computation
1
15,209
68,874,736
How to modify a tsv-file column with Python
<p>I have a GFF3 file (mainly a TSV file with 9 columns) and I'm trying to make some changes in the first column of my file in order to overwrite the modification to the file itself.</p> <p>The GFF3 file looks like this:</p> <pre><code>## GFF3 file ## replicon1 ## replicon2 replicon_1 prokka gene 0 15 . @ ....
<p>You can use <code>re.sub</code> with pattern that starts with <code>^</code> (start of the string) + use lambda function in <code>re.sub</code>. For example:</p> <pre class="lang-py prettyprint-override"><code>import re # change only first column: r = re.compile(r&quot;^(.*?)(?=\s)&quot;) in_char = &quot;_&quot; o...
python|pandas|dataframe|argparse|python-re
0
15,210
69,082,542
Function parameter passing in Python
<p>The following code represents an attempt at a minimal, reproducible example which compiles and runs as expected.</p> <pre><code>import numpy as np from sklearn import model_selection as skms N = 20 ftr = np.linspace(-10,10,num=N) # ftr values tgt = 2*ftr**2 -3 + np.random.uniform(-2,2,N) # tgt =func(ftr) (train_...
<p><code>np.poly1d</code> returns a <code>callable</code> object. That is, it can be called like a function (i.e. it is a function). Objects in Python are callable if they have a <code>__call__()</code> function.</p> <p>By calling <code>model_one(test_ftr)</code>, you are actually calling <code>model_one.__call__(test_...
python|numpy|scikit-learn
1
15,211
60,977,205
Modifying validation function for single image instead of Tencrop
<p>I have a <code>PublicTest</code> function that runs every epoch for validation and there is a <code>transform test</code> variable that transforms the validation data as above:</p> <pre><code> transform_test = transforms.Compose([ transforms.TenCrop(cut_size), transforms.Lambda(lambda crops: torch.stack(...
<p>Nevermind guys, I figured out just like this:</p> <pre><code>def PublicTest(epoch): global PublicTest_acc global best_PublicTest_acc global best_PublicTest_acc_epoch net.eval() PublicTest_loss = 0 correct = 0 total = 0 for batch_idx, (inputs, targets) in enumerate(PublicTestloader): ...
python-3.x|pytorch
0
15,212
71,590,919
Trying to remove all rows without a numeric value in a column
<p>I have been trying to remove all rows from a dataframe based on the condition that a column doesn't have a numeric value(int, float, etc..)</p> <p>This is what I tried but it's not working...</p> <pre><code>city_df = city_df[city_df[&quot;city_latitude&quot;].isnumeric()] </code></pre> <p>Does anyone know how to mak...
<p>You can try with a little tweak in the code:</p> <pre><code>city_df = city_df[city_df['city_latitude'].map(lambda x: str(x)).str.isnumeric().fillna(True)].dropna(subset=['city_latitude']) </code></pre> <p>Based on this data:</p> <pre><code> city_latitude 0 36.35665 1 39.174503 2 NaN 3 ...
python|pandas
1
15,213
71,559,875
Converting dataframe to array including on certain columns
<p>I am looking to create an array that contains only some of the columns in a dataframe I have. Below is what Ive come up with so far however is is not in the format i want, being a numpy array.</p> <pre><code>df = pd.read_csv(f'./data_2009.csv') target = df[['loan_default']] </code></pre> <p>Additionally, I wish fo...
<p>Once you have the dataframe that only includes the columns you want you can call <code>.to_numpy()</code>. In your case it would be:</p> <pre><code>df = pd.read_csv(f'./data_2009.csv') target = df[['loan_default']].to_numpy() </code></pre> <p>To ensure the shape is (500,) you can call: <code>target.reshape(500)</co...
python|arrays|pandas|dataframe|multiple-columns
0
15,214
42,264,848
Pandas DataFrame How to query the closest datetime index?
<p>How do i query for the closest index from a Pandas DataFrame? The index is DatetimeIndex</p> <pre><code>2016-11-13 20:00:10.617989120 7.0 132.0 2016-11-13 22:00:00.022737152 1.0 128.0 2016-11-13 22:00:28.417561344 1.0 132.0 </code></pre> <p>I tried this:</p> <pre><code>df.index.get_loc(df.index[0], method='nea...
<p>It seems you need first get position by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html" rel="noreferrer"><code>get_loc</code></a> and then select by <code>[]</code>:</p> <pre><code>dt = pd.to_datetime("2016-11-13 22:01:25.450") print (dt) 2016-11-13 22:01:25.450000 print (...
pandas|dataframe
66
15,215
42,395,827
How to create a custom connected neural network using tensorflow?
<p>I want to create a network that has specific fixed connections between layers. For example, <a href="https://i.stack.imgur.com/tFGBJ.png" rel="nofollow noreferrer">Sparsely connected neural network</a></p> <p>I tried looking into functions in Tensorflow, but I only found dense networks with regularizers, which does...
<p>You can always find a workaround. Let's say a layer does <code>y = xW</code> (<code>Wx</code> is also correct) but you want some of the entries in <code>W</code> always be zeros. You can do it column-wise:</p> <p>For column <code>i</code> (or element <code>i</code> since <code>y</code> is a vector) of the output, <...
tensorflow|neural-network
2
15,216
69,720,923
Create a column by iterating on another column
<p>I have two columns, one with an ID and the orhter with transaction dates.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">ID</th> <th>Date</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td>2019-04-30</td> </tr> <tr> <td style="text-align:...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for counter with add <code>1</code> with cast to strings, so possible add <code>Order_</code>:</p> <pre><code>df['Type'] = 'Order_' + df.groupb...
pandas|loops|date
0
15,217
69,905,644
confused about runtime of differents methods for distance of (2-d) points
<p>Recently I am working on a tower-defense game in python (3.7). In the code of this game I have to check the distance between different 2-d points alot. So I wanted to check what the fastest methods for completing this task are.</p> <p>I am not firm about the particular norm. The 2-norm seems like natural choice, but...
<h2>For game development, you probably need to implement <a href="https://gameprogrammingpatterns.com/spatial-partition.html" rel="nofollow noreferrer">spatial partitioning</a> when you need to frequently query what objects are near another.</h2> <p>The rest of this answer will deal with the numpy behaviour observed. F...
python|python-3.x|numpy|execution-time
0
15,218
69,788,695
How to represent a signal on negative X Axis
<p>first I would like to say it is my first time using Matplotlib and Numpy so I will be wrong about what I am talking about and this code is definitely super messy, Thank you.</p> <p>I have got this signal, and I am trying to get a graph of its Magnitude Spectrum my problem is that I cant seem to represent its negativ...
<p>Here you go:</p> <pre><code>axs[0, 0].magnitude_spectrum(s, Fs=Fs, color='C1', sides= 'twosided') </code></pre> <p><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.magnitude_spectrum.html" rel="nofollow noreferrer">Reference</a></p>
numpy|matplotlib
1
15,219
72,268,973
Pandas GroupBy error occurs only in large dataset
<p>I use such code to select rows with max value in gropus:</p> <pre><code>set_f = set.loc[set.reset_index().groupby(['Scan Number'])['dda246displmils'].idxmax()] </code></pre> <p>and this works perfectly fine with dataset od ~1M rows but i get this error when try to group 38M rows:</p> <p><em>KeyError: 'Passing list-l...
<p>Problem is you want select original index values by new created by <code>reset_index</code>, so raise error.</p> <p>Solution is reassign back before <code>loc</code>:</p> <pre><code>df = set.reset_index() set_f = df.loc[df.groupby(['Scan Number'])['dda246displmils'].idxmax()] </code></pre>
pandas|group-by
0
15,220
72,145,709
How to get pandas to return the row index on which a CSV read error occurs
<p>I have a CSV: <code>'1\n2\na'</code>. If I read it with something like <code>pd.read_csv(io.StringIO('1\n2\na'), names=['A'], dtype={'A': 'float'})</code> specifying that the first column has a type of integer, how can I get the row index at which the error occurred?</p> <p>Pandas raises <code>ValueError</code> but ...
<p><strong>Just a thought</strong></p> <blockquote> <p>Why not get help from regex? .</p> </blockquote> <p>You'll have manual labour on your hand to fill in the missing records still though:</p> <pre><code>import pandas as pd import io df = pd.read_csv(io.StringIO('1\n2\na'), names=['A'], dtype={'A': 'str'}) df.A = df...
python|pandas|csv
0
15,221
72,239,474
Calculate value based on previous value and multiplication
<p>I am trying to do something which is very simple in excel, but I cant seem to find the way the way to do it in python. I want to calculate the next value in a dataframe, based on the current value + percentage, similar to the excel version:</p> <p><a href="https://i.stack.imgur.com/95tJC.png" rel="nofollow noreferre...
<p>You can use <code>cumprod</code> for this type of operations. Add a <code>shift</code> and <code>fillna</code> to make the first value remains unchanged:</p> <pre><code>df = pd.DataFrame({&quot;Date&quot;: pd.date_range(&quot;1-1-1980&quot;, &quot;1-12-1980&quot;, freq=&quot;D&quot;)}) df[&quot;Value&quot;] = 105 # ...
python|pandas|dataframe
3
15,222
50,265,728
Linking one feature column to another feature column
<p>I'm new to TensorFlow and am trying to perform binary classification on my dataset. Essentially, I'm trying to predict whether an item is "attractive" or "not attractive".</p> <p>I've simplified my training set to look something like that:</p> <pre><code>lamp; 20cm; description: lightbulb, switch; attractive...
<p>Re 1., TF supports csv just fine</p> <p>For 2 and 3, you should look at <a href="https://www.tensorflow.org/guide/feature_columns" rel="nofollow noreferrer">the documentation for tf feature columns</a>.</p>
tensorflow|classification
1
15,223
50,580,408
Pandas merge and grouby
<p>I have 2 pandas dataframes which looks like below. </p> <pre><code>Data Frame 1: Section Chainage Frame R125R002 10.133 1 R125R002 10.138 2 R125R002 10.143 3 R125R002 10.148 4 R125R002 10.153 5 Data Frame 2: Section Chainage 1 2 3 4 5 6 7 8 R125R002 10...
<p>You can first aggregate by each 5 rows with define functions in dictionary:</p> <pre><code>d = {'Section':'first','Chainage':'first','1':'sum','2':'max', '8':'mean'} df22 = df2.groupby([np.arange(len(df2.index)) // 5], as_index=False).agg(d) print (df22) Section Chainage 1 2 8 0 R125R002 10.133 0 0 0...
python|pandas|merge|group-by
1
15,224
50,348,504
python3 numpy: too many indices for array
<p>I have a value, just like:</p> <pre><code>a = np.array({'a':1}) </code></pre> <p>Then, I want to get the dict from a. But error happens when I use a[0]:</p> <pre><code>IndexError: too many indices for array </code></pre> <p>I have a look at the shape of a:</p> <pre><code>&gt;&gt;&gt; a.shape () </code></pre> <...
<p>You should create your array with list;</p> <pre><code>a = np.array([{'a':1}]) </code></pre>
python|arrays|numpy
2
15,225
45,372,670
How to broadcast third dimension in tensorflow?
<p>I have a sobel filter </p> <pre><code>sobel_x = tf.constant([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], tf.float32) </code></pre> <p>I want to get a depth of 64. The shape is momentarily [3,3,1], but it should result in [3,3,64]. </p> <p>How do to that? With the following line, I get shape errors.</p> <pre><code>tf.ti...
<p>The reason you cannot broadcast is that the third dimension does not exist, and so you actually have a rank 2 tensor.</p> <pre><code>&gt;&gt;&gt; sess.run(tf.shape(sobel_x)) array([3, 3], dtype=int32) </code></pre> <p>We can solve this problem by reshaping the tensor first.</p> <pre><code>&gt;&gt;&gt; sobel_x = t...
tensorflow
1
15,226
45,405,393
Using .plot() functionality of pandas dataframe in a script
<p>I have a pandas data frame wit the following properties:</p> <p>Name: df_name, </p> <p>Concerned Column: col1</p> <p>If I want to plot a column, I can execute the following code in python shell(>>>) or ipython notebook.</p> <pre><code>&gt;&gt;&gt;df_name['col1'].plot(kind='bar') </code></pre> <p>However, I want...
<p>I think, you need to import matplotlib.pyplot and to use show method like in example.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df_name=pd.DataFrame([1,2,3]) df_name[0].plot(kind='bar') plt.show() </code></pre>
python|python-3.x|pandas|dataframe
0
15,227
45,527,722
what's the purpose of newly added api `tf.contrib.data`
<p>Before this api, I always prepare dataset in several steps following the official tutorial:<br> 1.write samples to tfrecord file<br> 2.read it out with a reader as string<br> 3.decode the string to tensors<br> 4.batch</p> <p>So what's the purpose of introducing this new api? what's the difference between it and que...
<p>It's a newer approach designed to address some of the shortcomings of queue based approach. You can see the motivating discussion <a href="https://github.com/tensorflow/tensorflow/issues/7951" rel="nofollow noreferrer">here</a></p> <p>Developer's guide for using Dataset API is <a href="https://github.com/tensorflow...
python|tensorflow|deep-learning|tensorflow-datasets
0
15,228
62,623,901
numpy is not installing in Pycharm. Need experts to help me out
<p>I tried using GUI of pycharm. I went to Settings&gt;Interpreter&gt;add(+)</p> <p>I installed numpy using pip install numpy in my CMD. It installs successfully but I it is not showing in my pycharm interpreter.</p>
<p>If you created a project in Pycharm with default settings, it will create a virtual enviroment for your spesific project. To install Numpy you can simply click on &quot;File -&gt; Settings -&gt; Project: Project Name -&gt; Project Interpreter and press the &quot;+&quot; icon. Search for Numpy and click on &quot;inst...
python|numpy|pycharm
0
15,229
62,807,519
Python Data Manipulation - pd.apply
<p>I'm running into an issue trying to create a new column from existing columns. I've found that the .apply works but it is ungodly slow. Unfortunately, there isn't anybody at my company that is familiar with Python. Is there a more efficient way to do the following?</p> <p>Data set is pretty large - 35 columns, 10M+ ...
<p>pandarallel might solve your problem. It makes pandas function to do the job in multicores instead of single core**(parallelizing the task)**.</p> <p>Read through this -</p> <p><a href="https://towardsdatascience.com/pandaral-lel-a-simple-and-efficient-tool-to-parallelize-your-pandas-operations-on-all-your-cpus-bb5f...
python|pandas|new-operator
0
15,230
62,627,680
Pandas: add indicator for duplicate on columns
<p>Here is a pandas DF with columns A, B, C, D</p> <pre><code> A B C D 0 1 2 1.0 a 1 1 2 1.01 a 2 1 2 1.0 b 3 3 4 0 b 4 3 4 0 c 5 1 2 1 c 6 1 9 1 c </code></pre> <p>How can I add a column to show duplicates from other rows with constraint...
<p>My original answer required <code>N**2</code> iterations for <code>N</code> rows. The answer by sammywemmy loops over <code>permutations(..., 2)</code>, which is essentially a loop over <code>N*(N-1)</code> combinations. The answer by warped is more efficient because it starts with a quicker matching on the A and B ...
python|pandas|duplicates|apply
1
15,231
62,885,922
logical_not used for 1,0 rather than True, False in boolean array
<p>I want to get the inverse of all components in an array containing a certain number of <code>0</code> and <code>1</code>. When I use <code>numpy.logical_not</code> it returns <code>False</code> and <code>True</code> instead:</p> <pre><code>import numpy as np a=np.array([1,0,0]) b=np.logical_not(a) print b </code></p...
<pre><code>1 - a </code></pre> <p>Just use arithmetic operators instead of logical operators.</p>
python|numpy|boolean|logical-operators
3
15,232
54,407,634
Pandas concat similar DataFrames and Series
<p>I have a list of Dataframes, all with the same columns. Occaisionally, a DataFrame has only one row, and is, hence, a Series. When I try to concatenate this list with <code>pd.concat</code>, where there was a Series, it puts what I want to be the columns in the index. See below for a minimal working example.</p> <p...
<pre><code>thing2 = pd.DataFrame(thing2).transpose() pd.concat([thing1, thing2, thing3]) </code></pre> <p>In your case <code>transpose()</code> will set <code>Pandas Series</code> index as colums and then you can concate easily.<br> Documentation here : <a href="https://pandas.pydata.org/pandas-docs/stable/reference/a...
python|pandas|concatenation
2
15,233
73,780,250
Python Pandas - What is Pandas version of replace or append while working with multiple values?
<p>I have a dataframe where I am creating a new data frame using .str.contains. This is working okay, however I am then trying to find data and then add 'NEW' to the front however the way I am doing it is creating 'NEWX|Y|Z&quot; when I want 'NEWX' where it finds X and 'NEWY' where it finds Y etc.</p> <pre><code>substr...
<p>IIUC, use capture group:</p> <pre><code>s = pd.Series([&quot;Xsomething&quot;, &quot;Ythatthing&quot;, &quot;WhatZ&quot;, &quot;Nothing&quot;]) s.str.replace(&quot;(%s)&quot; % &quot;|&quot;.join(&quot;XYZ&quot;), &quot;NEW\\1&quot;, regex=True) </code></pre> <p>Output:</p> <pre><code>0 NEWXsomething 1 NEWYtha...
python|pandas|dataframe
0
15,234
73,808,929
Create a new column in pandas that is based on two other columns of bools
<p>I have a dataframe df that has two columns consisting of bools.</p> <pre><code>df['trial'] df['subscribe'] </code></pre> <p>I want to create a new column <code>df['without_trial']</code> that is true when <code>df['subscribe']</code> is true and <code>df['trial']</code> is false, and false otherwise.</p> <p>How can ...
<p>If you have pure boolean columns as input, use the AND (<code>&amp;</code>) and NOT (<code>~</code>) operators:</p> <pre><code>df['without_trial'] = df['trial'] &amp; ~df['subscribe'] </code></pre> <p>If you potentially have mixed values use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.eq.html...
python|pandas
2
15,235
73,834,673
Calculation of rolling speed in a PandasDataframe
<p>I have the following challenge: I have a PandasDataframe with information about a unique ArucoID, a unique frameID and associated coordinates in a coordinate system. For example like this:</p> <pre><code># import pandas library import pandas as pd # lst_of_dfs = [] # dictionary with list object of values data1 = { ...
<p>I'll assume you want to compute specific mechanical speeds for each device and trial.</p> <h3>Preparing dataset</h3> <p>Let's start with your raw data:</p> <pre><code>import numpy as np import pandas as pd data1 = { 'ArucoID' : [910, 910, 910, 910, 910, 898, 898, 898, 898, 898, 912, 912, 912, 912, 912], 'Su...
python|pandas
0
15,236
71,155,640
Pandas: Mean of a column between change of condition in second column
<p>Say I have the following dataframe:</p> <pre><code>import pandas as pd import numpy as np data = np.random.randint(1, 10, size=(10,2)) df = pd.DataFrame(data, columns=['x1', 'x2']) df['switch'] = [1,1,0,0,1,1,0,0,1,1] index_ = pd.date_range('2022-01-17 13:00:00', periods=10, freq='5s') df.index = index_.rename('Ti...
<p>You could use <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>groupby</code>+<code>agg</code></a> with a custom group:</p> <pre><code>df2 = df.reset_index() df2['Time'] = pd.to_datetime(df2['Time']) (df2[df2['switch...
python-3.x|pandas
1
15,237
71,292,087
How to stack tensors without using tf.stack?
<p>Is there any way to merge Tensors in Tensorflow? For example: I have 128 Tensor shape all are <strong>(40, 10)</strong>, Now, I want merge them to shape(128, 40, 10). I can't use <em><code>*tf.stack([Tensor1, Tensor2, Tensor3, ...])*</code></em> directly.</p> <p>So, Is there any function that can help achieve this?<...
<p>Use <code>tf.expand_dims</code> with <code>tf.concat</code>:</p> <pre><code>import tensorflow as tf x1 = tf.expand_dims(tf.random.normal((40, 10)), axis=0) x2 = tf.expand_dims(tf.random.normal((40, 10)), axis=0) x3 = tf.expand_dims(tf.random.normal((40, 10)), axis=0) x4 = tf.expand_dims(tf.random.normal((40, 10)), ...
python|tensorflow|tensor
1
15,238
52,112,771
How to display weights and bias of the model on Tensorboard using python
<p>I have created the following model for training and want to get it visualized on Tensorboard: </p> <pre><code>## Basic Cell LSTM tensorflow index_in_epoch = 0; perm_array = np.arange(x_train.shape[0]) np.random.shuffle(perm_array) # function to get the next batch def get_next_batch(batch_size): global ind...
<p>I think the easiest way to visualize weights on Tensorboard is to plot them as histograms. For instance, you could log your layers as follows.</p> <pre><code>for i, layer in enumerate(layers): tf.summary.histogram('layer{0}'.format(i), layer) </code></pre> <p>Once you have created a summary for each layer or v...
python|python-3.x|tensorflow|tensorboard
5
15,239
52,343,206
Find same values from 2 df columns python
<p>I have two different dfs with the following columns:</p> <pre><code>col1 col2 0 programming 0 programming 1 chess 1 python 2 leadership 2 leadership 3 abba 4 games </code></pre> <p>I want to find what percentag...
<pre><code>&gt;&gt;&gt; df1 = pd.DataFrame(["programming", "chess", "leadership"], columns=["col1"]) &gt;&gt;&gt; df2 = pd.DataFrame(["programming", "python", "leadership", "abba", "games"], columns=["col2"]) </code></pre> <p>To find which values of <code>df1['col1']</code> are in <code>df2['col2']</code> use <code>is...
python|pandas|dataframe
1
15,240
52,265,961
How to ignore NaN in the dataframe for Mann-whitney u test?
<p>I have a dataframe as below.</p> <p><a href="https://i.stack.imgur.com/lmquE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lmquE.jpg" alt="enter image description here"></a></p> <p>I want p-value of Mann-whitney u test by comparing each column. As an example, I tried below.</p> <pre><code>fro...
<p>you can use <code>df.dropna()</code> you can find extensive documentation here <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow noreferrer">dropna</a></p> <p>As per your example, the syntax would go something like this:</p> <pre><code>mannwhitneyu(df['A']....
python|pandas|static|scipy|nan
3
15,241
52,253,821
Remove outliers by group based on IQR
<p>I have a df that contains the following variables:</p> <ul> <li>pp (participant)</li> <li>condition</li> <li>rt (reaction time)</li> </ul> <p>(as well as a whole bunch of other stuff).</p> <p>I want to trim outliers based on the iqr criterion. However, I want to do so per condition, per pp.</p> <p>I figure a sol...
<p>You could do something like this:</p> <pre class="lang-python prettyprint-override"><code># define a function to filter out your data def filter_condition(grped_df): if some_condition: return grped_df[some_condition] return grped_df grouped = df.groupby(by=['pp','condition']) # use apply to pass ...
python|pandas|pandas-groupby|outliers
1
15,242
60,751,762
How to deal with null row appended at the end of windows generated csv?
<p>I wrote a function to deal with the null values in the csv before passing it to a forecasting model</p> <pre><code>if do_nulls_exist == True: print('found a null value') null_rows = pd.isnull(data) print('######### ORIGINAL ROWS THAT NEED UPDATING ##############') print(null_rows) # Need to add ...
<p>Before passing CSV to forecast model you can apply <strong>dropna()</strong> function on Dataframe. It will delete all null row's</p> <pre><code> df = df.dropna() </code></pre> <p>Refe Link :<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferre...
python|pandas
0
15,243
60,668,178
Getting an error when try to substract : Operands could not be broadcast together with shapes (2,) (2,3)
<p>i got error when try to run my code below:</p> <pre><code>def h(x): global w return sum(np.transpose(w)*x) raise NotImplementedError() def cost_func_linreg(X, y): m = len(y) for i in range(1, m+1): X_i = np.power(X, i) c= np.sum(np.square(h(X_i) - y)) return (1/(2*m))*c ...
<p>It is not exactly clear, what you want to have as a result, but try replacing <code>sum</code> with <code>np.sum</code> in h(x):</p> <pre><code>def h(x): global w return np.sum(np.transpose(w)*x) </code></pre> <p>At least it gives no error :)</p>
python|numpy|linear-regression
1
15,244
60,689,709
Vectorizing with Pandas
<p>I have a pandas dataframe like below:</p> <pre><code> MSuite TCase KWord 0 MS1 Nan Nan 1 NaN T1 NaN 2 NaN NaN K1 3 NaN NaN K4 4 NaN NaN K8 5 NaN NaN V3 6 NaN T2 NaN 7 NaN NaN K7 8 NaN NaN K12 9 NaN NaN ...
<p>You can try of using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer">string contain</a> along with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer">string extrac...
python|pandas|dataframe|vectorization
2
15,245
60,462,468
Stacking arrays of unequal shape
<pre><code> `print(np.array([arr[2:4], arr[3:5]])) # same shape` </code></pre> <p>I can do stacking in the above cases to get a 3d array so that I can train LSTM network. But I have array of 2d arrays of unequal length. Like: `</p> <pre><code>print(np.array([arr[:2], arr[:3]])) [array([[0, 1], [2, 3]]) array(...
<p>For LSTM input, to batch your sequences you need the same size of mini-batches. For that you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html#numpy-pad" rel="nofollow noreferrer"><code>np.pad</code></a> to make it each same size. Usually you will pad with zero.</p> <pre class="la...
arrays|numpy|numpy-ndarray
0
15,246
72,835,235
How to create a DataFrame from a API json dictionary with nested dictionaries?
<p>I have the following code which will load data from a <a href="https://developer.edamam.com/food-database-api" rel="nofollow noreferrer">food database API</a>:</p> <pre class="lang-py prettyprint-override"><code>import requests import pandas as pd url = &quot;https://api.edamam.com/api/nutrition-data?app_id=aba8273...
<pre class="lang-py prettyprint-override"><code># Create DataFrame from data dictionary: # - set_index(0) makes the keys (column 0) the index values # - .T takes the transpose and makes the index the columns # .reset_index(drop=True) resets index to 0 (1 row DataFrame) and drops old index df = pd.DataFrame(data.items()...
python|json|pandas|dictionary
0
15,247
72,817,492
Drop rows with conditions in PySpark Pandas API
<p>I would like to know how to do that using PySpark Pandas API.</p> <p>This is Pandas version:</p> <pre><code>indexNames = dfObj[ (dfObj['Age'] &gt;= 30) &amp; (dfObj['Age'] &lt;= 40) ].index dfObj.drop(indexNames , inplace=True) </code></pre> <p>But I would like to do that using PySpark Pandas API.</p> <p>Could you p...
<p>You should follow this guide initially:</p> <p><a href="https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/pandas_pyspark.html#pandas" rel="nofollow noreferrer">https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/pandas_pyspark.html#pandas</a></p> <p>example will look l...
python|pandas|pyspark|conditional-statements|drop
0
15,248
72,732,028
Pandas copying header names changes blank headers to unamed
<p>so I have a csv file that has the headers I need for my dataframe.<br /> So what I am doing is loading both the header file and my data file and copying the headers to my data array, I then save the data array to csv.</p> <p>here's my code:</p> <pre><code>loader = pd.read_csv('Resources/Headers.txt', sep='\t', heade...
<p>You can rename them before saving if the col starts with <code>Unnamed</code>:</p> <pre><code>loader = pd.read_csv('Resources/Headers.txt', sep='\t', header=[0, 1, 2]) ndf = pd.DataFrame(data=data, columns=loader.columns.get_level_values(2) ndf.columns = loader.columns ndf.columns = ['' if col.startswith('Unnamed')...
python|pandas|numpy
1
15,249
59,732,308
How to create multiple additional columns from dataframe and add to the same dataframe
<p>Trying to parse 'date' column into 'month', 'day', 'hour' and 'minute' and then add them as separate columns to the same dataframe:</p> <pre><code>import pandas as pd d = {'date':[pd.Timestamp('2019-03-01 00:05:01'), pd.Timestamp('2019-04-02 07:11:00'), pd.Timestamp('2019-05-03 10:25:00')]...
<p>Looks like you want</p> <pre><code>df1['month'], df1['day'], df1['hour'], df1['minute'] = (df1.date.dt.month, df1.date.dt.day, df1.date.dt.hour, df1.date.dt.minute) </code></pre> <hr> <pre><code>print(df1) date foo month day hour minute 0 2019-03-01 ...
python|pandas
1
15,250
59,566,618
Numpy Vectorization to improve performance
<p>I am currently trying to vectorize my code to decrease its processing time and while trying a broadcasting error occured.</p> <p>I have two vectors, <code>TDOA_values</code> with a shape of (200,) and <code>__frequency_bins__</code> with a shape of (257,).</p> <p>Now I want to use the elements of these vectors to ...
<p>You need to use np.newaxis:</p> <pre><code># array(m x n) = array(m x 1) * array(1 x n) import numpy as np Rxx12 = 1 # TODO, not specified in the question TDOA_values = np.random.random(200) __frequency_bins__ = np.random.random(257) temp_gcc_results = np.zeros((len(TDOA_values), len(__frequency_bins__))) temp_gcc...
python|numpy
1
15,251
59,828,365
How do I get my output which is json converted in a dataframe format?
<p>Im new to python and trying to format my output from an API:</p> <p>The output dataframe is:</p> <pre><code>**data** Out[8]: b'[{"date":"2020-01-19","stats":[{"metrics":{"blocks":5,"bounce_drops":6,"bounces":16,"clicks":278,"deferred":8,"delivered":1453,"invalid_emails":6,"opens":2502,"processed":155,"requests":14...
<p>Here's a way to do:</p> <pre><code>from pandas.io.json import json_normalize # lets say d is your list containing dict f = json_normalize(d) # reshape the data cols = ['blocks','bounce_drops','bounces'] df = f['stats'].apply(lambda x: pd.Series(x[0]))['metrics'].apply(pd.Series)[cols] blocks bounce_drops bo...
python|json|pandas|typeerror
0
15,252
59,826,152
Confused about calculation of convolutional layer shapes
<p>I am new in this forum and I have started studying the theory of CNN. It is probably a stupid question but I am confused about the calculation of the CNN outputs shape. I am following a course on Udacity and in one of the tutorials they provide this CNN architecture.</p> <pre class="lang-py prettyprint-override">...
<p>It misses the definition of the forward pass and one can guess there is a 2x2 pooling after each <code>conv</code> layer. Hence, the pooling implies a subsampling each time (see the comments) and the 32x32 images becomes 16x16 after <code>conv1</code> (+ 2x2 pooling), 8x8 after <code>conv2</code> (+ 2x2 pooling) and...
python|deep-learning|pytorch|conv-neural-network
1
15,253
61,926,038
the result of parsing JSON on different columns
<p>I am having trouble using json_normalize, when I apply them to the following python code:</p> <pre><code>json ={ 'id': 146731073, 'id_str': '146731073', 'indices': [17, 28], 'name': 'Chris jeday', 'screen_name': 'ChrisJeday'} pd.json_normalize(json,'screen_name') </code></pre> <p>get tokkenized r...
<p>You can get a Series like this:</p> <pre><code>screen_names = pd.json_normalize(json).screen_name print(type(screen_names)) print(screen_names) [Out]: &lt;class 'pandas.core.series.Series'&gt; 0 ChrisJeday Name: screen_name, dtype: object </code></pre>
python|json|pandas
0
15,254
61,860,533
Permute values pandas dataframe
<p>I have a dataframe with name of persons in the index and name of fruits in columns, and the values are the distance from person to fruit. Like this</p> <pre><code>(index) apple orange lemon grape John 22.3 13.1 14.9 8.8 Mike 12.1 14.2 11.3 5.3 Kevin 9.13 14.9 3.3 22.3 Leon ...
<p>Assuming that you need each fruit to be picked by a different person, you can use <code>itertools</code> to evaluate all possible combinations of name and fruit, but this will be intractable for larger problems. </p> <p>A typical solution is to use <a href="https://en.wikipedia.org/wiki/Integer_programming" rel="no...
python|pandas|numpy
0
15,255
54,987,035
Tensorflow - How to split batches between GPUs for predicting on trained models?
<p>I'm using models I didn't create but modified (from this repo <a href="https://github.com/GeorgeSeif/Semantic-Segmentation-Suite" rel="nofollow noreferrer">https://github.com/GeorgeSeif/Semantic-Segmentation-Suite</a>)</p> <p>I have trained models and can use them to predict well enough but I want to run entire fol...
<p><code>tf.device</code> only applies when building the graph, not executing it, so wrapping <code>session.run</code> calls in a device context does nothing.</p> <p>Instead I recommend you use <a href="https://deepmind.com/blog/tf-replicator-distributed-machine-learning/" rel="nofollow noreferrer">tf replicator</a> o...
python|tensorflow
0
15,256
54,930,925
How to split values in cells for plotting
<p>I am having trouble trying to plot my current dataframe. I currently have values like this in the cells of my dataframe:</p> <pre><code> (test, 5) </code></pre> <p>'test' should be on the x-axis of my plot. The number '5' is the count for the number of times 'test' occurs. Therefore the bar for test should be of ...
<p>I would format your data to an array and work with that. </p> <p>Something like this:</p> <pre><code>import pandas as pd data = [ [('test',5), ('test2', 20), ('test3', 500), ('test4', 2), 'company'], [('notest',89), ('notest2', 220), ('notest', 50), ('notest4', 32), 'residental']] names = ['one', 'two', '...
python|pandas|matplotlib
0
15,257
49,488,614
How to use Keras with GPU?
<p>I've successfully installed TensorFlow with GPU. When I run the following script I get this result:</p> <pre><code>from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) </code></pre> <blockquote> <p>C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\platform\cpu_...
<p>You don't have to explicitly tell to Keras to use the GPU. If a GPU is available (and from your output I can see it's the case) it will use it.</p> <p>You could also check this empirically by looking at the usage of the GPU during the model training: if you're on Windows 10 you only need to open the task manager an...
python|tensorflow|keras|gpu
11
15,258
49,388,555
Set default value as numpy array
<p>I have a class MyClass which stores an integer <code>a</code>. I want to define a function inside it that takes a numpy array <code>x</code> of length <code>a</code>, but I want that if the user does not pass in anything, <code>x</code> is set to a random array of the same length. (If they pass in values of the wron...
<p>As a rule of thumb, comparisons of anything and <code>None</code> should be done with <code>is</code> and not <code>==</code>.</p> <p>Changing <code>if x == None</code> to <code>if x is None</code> solves this issue.</p> <pre><code>class MyClass(): def __init__(self, a): self.a = a def function(se...
python|arrays|numpy|default-value
4
15,259
67,590,069
Python: MemoryError (scripts runs sometimes)
<p>I have a script which sometimes runs successfully, providing the desired output, but when rerun moments later it provides the following error:</p> <pre><code>numpy.core._exceptions.MemoryError: Unable to allocate 70.8 MiB for an array with shape (4643100, 2) and data type float64 </code></pre> <p>I realise this ques...
<p>Python is a garbage collected language. <a href="https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)#Disadvantages" rel="nofollow noreferrer">Garbage collection is non-deterministic</a>. This means that peak memory usage may be different each time a program is run. So the first time you run the progr...
python|numpy|memory|out-of-memory
1
15,260
67,250,482
Efficient groupby when rows of groups are contiguous?
<h1>The context</h1> <p>I am looking to apply a <code>ufuncs</code> (<code>cumsum</code> in this case) to blocks of contiguous rows in a time serie, which is stored in a panda DataFrame. This time serie is sorted according its DatetimeIndex.</p> <p>Blocks are defined by a custom DatetimeIndex.</p> <p>To do so, I came u...
<p><code>group_by</code> is clearly not the fastest solution here because it should either use a <strong>slow sort</strong> or <strong>slow hashing operations</strong> to group the values.</p> <p>What you want to implement is called a <strong>segmented cumulative sum</strong>. You can implement this quite efficiently u...
python|pandas|pandas-groupby
1
15,261
67,290,240
Name stacked bars after legend entry on Pandas/Matplotlib
<p>I have a stacked bar chart that works really well for what I'm looking for. My problem is handling the labels.</p> <p>I can label every single stacked bar after its value (number), but I'm looking to label it after its name (on the legend).</p> <p>Does anyone have an idea on how to solve this?</p> <p>ps.: Unfortunat...
<p>Based on Dex answer I came up with a solution. Using patches, it will get every single bar from the chart. The bars are ordenated by rows. So if you have a 4x3 dataframe:</p> <pre><code> zero um dois 0 a b c 1 d e f 2 g h i 3 j k l </code></pre> <p>bars.patches will have e...
pandas|matplotlib|charts|stacked
1
15,262
60,276,194
Plot several graphs in Pytorch tensorboard
<p>I am training a dynamic neural network, meaning that each epoch I tweak the architecture and get a different computational graph. I want to plot the graph for each epoch using tensorboard, but when I use SummaryWriter.add_graph() at the end of each epoch it simply overwrites the previous one.</p> <p>Any ideas how t...
<p>Instead of using the &quot;tag&quot; feature, you can use the &quot;run&quot; feature. To do so, you have to open tensorboard from a directory within which you stored your summaries in distinct sub-directories.</p> <p>In your example, you could save the summary of the first epoch at the directory &quot;<em>tensorboa...
pytorch|tensorboard
0
15,263
60,140,744
Split up time series per year for plotting
<p>I would like to plot a time series, start Oct-2015 and end Feb-2018, in one graph, each year is a single line. The time series is <code>int64</code> value and is in a <code>Pandas DataFrame</code>. The date is in <code>datetime64[ns]</code> as one of the columns in the DataFrame.</p> <p>How would I create a graph f...
<p>You can achieve this by:</p> <ol> <li>extracting the year from the date</li> <li>replacing the dates by the equivalent without the year</li> <li>setting both the year and the date as index</li> <li>unstacking the values by year</li> </ol> <p>At this point, each year will be a column, and each date within the year ...
python-3.x|pandas|time-series
3
15,264
59,960,543
Exact visual matches between common columns in dataframes not matching on merge
<p>I am trying to merge two dataframes on a common column, &quot;long_name&quot;. But the merge is not happening for some names, even what look like visually exact matches, (ie &quot;Lionel Andrés Messi Cuccittini&quot; (df1) to &quot;Lionel Andrés Messi Cuccittini&quot; (df2)) when I merge on &quot;long_name&quot;:</p...
<p>Are you sure it is not just a case of a misspelled name?</p> <p><code>df</code> lists the <code>long_name</code> as <code>Lionel Andrés Messi Cuccittini</code>, whereas <code>df1</code> lists it as <code>Lionel Andrés Messi Cuccitini</code>. I notice <code>df</code> has 2 <code>t</code>'s in <code>Cuccittini</code>...
python|string|pandas|dataframe|merge
0
15,265
65,074,702
Product of two Tensors
<p>I want to multiply two tensors namely fx and px. but it gives this error (<code>InvalidArgumentError: cannot compute Mul as input #1(zero-based) was expected to be a float tensor but is a double tensor [Op:Mul]</code>). The code is as follows</p> <pre><code>x_l = -2.0 x_h = 4.0 h = (x_h - x_l) / M x = np.arange(x_...
<p>Numpy arrays get interpreted as double tensors by tensorflow. In your case specifying that <code>x_tensor</code> is of dtype <code>tf.float32</code> is sufficient.</p> <pre><code>x_tensor = tf.Variable(x.reshape(-1, x.shape[0], 1), dtype=tf.float32) </code></pre>
python|tensorflow
1
15,266
65,272,528
Counting how many times an ID appears within subsequent 180 days
<p>I have a pandas dataframe that includes these columns:</p> <pre><code>REF_ID REPORT_DATE_RAW 12345 2019-02-21 20:53:00 </code></pre> <p>I want to look at each particular <code>REF_ID</code> and whether or not it has been reported more than one time within 180 subsequent days from <code>REPORT_DATE_RAW</...
<p>Use:</p> <pre class="lang-py prettyprint-override"><code>(df.set_index('REPORT_DATE_RAW').groupby('REF_ID') .apply(lambda x: (x[::-1].rolling('180d').count() &gt; 1)[::-1].astype(int)) ) </code></pre> <p>where the <code>[::-1]</code> notation makes a forward <code>rolling</code> approach.</p> <hr /> <p>Note: Pandas...
python|python-3.x|pandas|datetime|time-series
1
15,267
65,085,766
Set list to subset of pandas dataframe
<p>I wish to set a list of lists in a column (say &quot;B&quot;) for a subset of rows. Suppose my dataframe (df) looks like below:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np np.random.seed(42) df = pd.DataFrame({&quot;A&quot;: np.random.randn(5)}) idx = df[&quot;A&quot;]...
<p>You can use <code>at</code> method, for example</p> <pre><code>my_list = [np.random.rand(5).tolist() for _ in range(6)] test_df = pd.DataFrame({'A':np.random.randint(-1,1,6)}) idx = np.where(test_df['A'] &lt; 0)[0] test_df['B'] = np.random.rand(len(my_list)).astype('object') for ind in idx:test_df.at[ind,'B'] = my...
pandas|dataframe
1
15,268
65,335,413
Tensorflow tf.data.Dataset error when using map function | KeyError
<p>I am working on my capstone project. Basically, I am trying to build a recommendation system for amazon beauty products. The dataset is a <strong>TensorFlow dataset</strong>.</p> <h2>Some Source code that works just fine</h2> <pre><code> data=tfds.load('amazon_us_reviews/Beauty_v1_00', split='train') type: tensorf...
<p>You are missing the &quot;data&quot; key when accessing the dictionary.</p> <p>This should fix it :</p> <pre><code>data = data.map(lambda x: { &quot;customer_id&quot;: x[&quot;data&quot;][&quot;customer_id&quot;], &quot;product_id&quot;: x[&quot;data&quot;][&quot;product_id&quot;], &quot;star...
python|tensorflow|dictionary|tensorflow-datasets|keyerror
0
15,269
49,964,995
Tensorflow speed-up prediction
<p>I have a problem regarding prediction performance. What I do is I repeatedly call <code>test_predictions</code> op in Python loop and put all its return values into the list. The code looks like this:</p> <pre><code>predictions = [] for _ in trange(args.num_batches): predictions.extend(sess.run(model.test_predi...
<p>There is no such thing as "switching between Python and TF code". If the GPU is idle a lot, that means your fetching of the data (images?) to run the predictions on takes a long time and the GPU has to wait a lot for the data to arrive.</p> <p>Try implementing pre-fetching.</p> <p>Alternatively, if you have enough...
python|tensorflow|machine-learning
0
15,270
64,092,285
Pandas - Merge nearly duplicate rows filtering the last timestamp
<p>I have a two pandas dataframe with several rows that are near duplicates of each other, except for one value, which is timestamp value. My goal is to merge these dataframes into a single dataframe, and for these nearly repeat rows, get the row with the last timestamp.</p> <p>Here is an example of what I'm working wi...
<p>You can append the second dataframe to the first one, sort the dataframe using timestamp and then drop duplicates.</p> <pre><code>df_merged = df1.append(df2, ignore_index = True) df_merged = df_merged.sort_values('created_at') df_columns = df_merged.columns.tolist() df_columns.remove('created_at') df_merged.drop_dup...
python|pandas|dataframe
1
15,271
64,102,336
How to return specific review data when specified productID is given in pandas dataframe
<p>I'm trying to return review data for a specific productID. I have successfully returned multiple columns with the below syntax:</p> <pre><code> #display productID and review text df1 = df[['asin', 'reviewText']] </code></pre> <p>I have successfully returned all data for a given productID with below syntax:</...
<p>Apart from the above answer, I also use df.query very frequently. Syntax:</p> <pre><code>dfSub = df.query('asin==&quot;0739079891&quot;')[['asin', 'reviewText']] </code></pre>
python|pandas|dataframe
0
15,272
64,113,696
Practical meaning of output in simple recurrent neural network
<p>I am trying to learn RNN model. Here is the model I built:</p> <pre class="lang-py prettyprint-override"><code>N = 3 # number of samples T = 10 # length of a single sample D = 3 # number of features K = 2 # number of output units X = np.random.randn(N, T, D) # Make an RNN M = 5 # number of hidden units i = tf.kera...
<p>You should pay attention to the model.</p> <p>After the <code>RNN</code> layer you used a <code>Dense</code> layer where the output dimension is 2! So the size of the output you get by running the <code>model.predict()</code> is fine.</p> <p>If you wish it to have other dimensions alter the output size of the <code>...
tensorflow|machine-learning|keras|recurrent-neural-network
1
15,273
63,985,554
Finding Occurrences SUM using Dataframe
<p>I have a data frame and I need to group by at least one occurrence greater than 0 and I need to sum it to last occurance. My code is below</p> <pre><code>data = {'id': [7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], 'timeatAcc': [0,0,0,0,0,0,0,0,1,1,1,0,0,1,1,0,0,1,1,1,...
<p>Let's try <code>groupby().diff()</code>:</p> <pre><code>df['Occurences'] = df.groupby('id')['timeatAcc'].diff(-1).eq(1).astype(int) </code></pre> <p>Output:</p> <pre><code> id timeatAcc Occurences 0 7 0 0 1 7 0 0 2 7 0 0 3 7 0 ...
python|pandas|dataframe
1
15,274
64,124,333
Reading XLSX data from subfolders on desktop
<p>I am trying to read an excel file into a dataframe using pandas and jupyter notebook from subfolder on my desktop. The file is on my desktop in a folder called 'Data', subfolder 'KN-Data', subfolder 'New-Files', file name &quot;Customers.xlsx&quot;.</p> <p>Here is the code I am trying:</p> <pre><code>df_customers = ...
<p>Try using double backslash instead of single forward slash. I always use double backslash and it works for me.</p> <p>This is how ur code should look like:</p> <pre><code>df_customers = pd.read_excel (r&quot;C:\\Users\\Zach\\Desktop\\Data\\KN-Data\\New-Files\\Customers.xlsx&quot;) </code></pre>
python|excel|pandas|jupyter-notebook|readfile
0
15,275
47,025,365
How to make a dataframe with one key to multiple list values to a dictionary in python?
<p>I have a dataframe like this</p> <pre><code>ID A B 1 3 5 1 4 2 1 0 4 2 2 1 2 4 5 2 9 3 3 2 1 3 4 6 </code></pre> <p>I tried code to convert them from other posts in stackoverflow</p> <pre><code>df.set_index('ID').T.to_dict('list') </code></pre> <p...
<pre><code>In [150]: df.groupby('ID')['A','B'].apply(lambda x: x.values.tolist()).to_dict() Out[150]: {'1': [[3, 5], [4, 2], [0, 4]], '2': [[2, 1], [4, 5], [9, 3]], '3': [[2, 1], [4, 6]]} </code></pre>
python|pandas|dictionary|dataframe|pandas-groupby
4
15,276
63,027,001
Computing excess returns
<p>I would like to compute the excess returns of dataframe of stock returns, where excess returns are defined as the difference between the stock returns and the market, where market it represented by the ticker SPY. Below is min-example</p> <pre><code>dict0 = {'date': [1/1/2020,1/1/2020,1/1/2020,1/2/2020,1/2/2020,1/2/...
<p>The last line of code where you do set_index, you should assign the dataframe back to itself or do it inplace. Remaining you can do it as follows:</p> <pre><code>def func(row): date, asset = row.name return df.loc[(date, asset), 'returns'] - df.loc[(date, 'SPY'), 'returns'] dict0 = {'date': ['1/1/2020', '...
python|pandas|finance
1
15,277
62,932,191
Expected conv2d_19_input to have 4 dimensions Error in CNN via Python
<p>I have a problem about solving dimension in prediction method of CNN. Before defining train and test data based on image , I posed a CNN model. After the process has been done, I fitted the model. When I predict the value by using model, It throws an error here.</p> <p>How can I fix it ?</p> <p>Here are my code bloc...
<p>The <code>predict</code> method is missing the batch dimension from your input. Modify your prediction like so:</p> <pre><code>import numpy as np &lt;--- import numpy S = 64 directory = os.listdir(test_forged_path) print(directory[3]) print(&quot;Path : &quot;, test_forged_path + &quot;/&quot; + directory[3]) im...
python|pandas|keras|conv-neural-network
2
15,278
62,945,672
create rows if missing in pandas df
<p>Current data :</p> <pre><code> |ID | DT | STATE | V| |1 | 201901 | PA | 1| |1 | 201902 | PA | 6| |2 | 201902 | PA | 3| |1 | 201902 | CA | 3| |2 | 201901 | CA | 1| </code></pre> <p>I want to create rows with all combinations of <code>ID</code>, <code>DT</code> and <code>STATE</code>...
<p>You can do <code>MultiIndex</code> index then <code>reindex</code></p> <pre><code>idx=pd.MultiIndex.from_product([df.ID.unique(),df.DT.unique(),df.STATE.unique()]) df=df.set_index(['ID','DT','STATE']).reindex(idx,fill_value=0).reset_index() df level_0 level_1 level_2 V 0 1 201901 PA 1 1 1 ...
python|python-3.x|pandas|dataframe
3
15,279
63,011,755
ERROR: Could not find a version that satisfies the requirement tensorflow-addons<0.8.0,>=0.7.1 (from rasa) (from versions: none)
<p>I tried to install Rasa, with the command: <code>pip3 install rasa</code>. However, I came up against an error about tensorflow, which is not automatically installed. Then I used command: <code>pip3 install tensorflow</code>, unfortunately, an error appeared: ERROR: Could not find a version that satisfies the requir...
<p>There is a <a href="https://github.com/tensorflow/addons#python-op-compatility" rel="nofollow noreferrer">version compatibility section</a> on TensorFlow Addons which states what combinations of [Python version | Tensorflow Version | Tensorflow Addons Version] is possible.</p> <p>In your case, TensorFlow addons 0.7....
python|tensorflow
4
15,280
61,531,750
Pandas how to get distinct rank when the you dont have unique counts
<p>I have a pandas dataframe and I only want the top 10 <code>count</code> from each device. I figured an easy way to do this is create a new column called <code>rank</code> and then anything with a rank greater than 10 i can remove. Here is the data:</p> <pre><code> p_dt device namestr co...
<p>You should consider using <code>method=first</code> in your <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rank.html" rel="nofollow noreferrer"><code>rank</code></a> method.</p> <pre><code>df.groupby('deviceproduct', sort=False)['count'].rank(ascending=False, method='first') </...
python|python-3.x|pandas
1
15,281
53,026,158
Clean np array of NaN while deleting entries in other array accordingly
<p>I have two numpy arrays, one of which contains about 1% NaNs.</p> <pre><code>a = np.array([-2,5,nan,6]) b = np.array([2,3,1,0]) </code></pre> <p>I'd like to compute the mean squared error of <code>a</code> and <code>b</code> using <code>sklearn</code>'s <a href="http://scikit-learn.org/stable/modules/generated/skl...
<p>You can simply use vanilla NumPy's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.nanmean.html" rel="nofollow noreferrer"><code>np.nanmean</code></a> for this purpose:</p> <pre><code>In [136]: np.nanmean((a-b)**2) Out[136]: 18.666666666666668 </code></pre> <p>If this didn't exist, or you reall...
numpy|scikit-learn|nan|idioms|mean-square-error
2
15,282
53,062,854
draw rgb spectrum in python/numpy
<p>I'm new to Python and i need to draw a RGB spectrum as a numpy array. For me it's clear that i need to rise the RGB values across the dimensions to get the spectrum.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt spectrum = np.zeros([255,255, 3], dtype=np.unit8) #init the array #fill the array ...
<p>Not sure if this is the result you'd like, but you could define the arrays for the RGB values yourself (see <a href="https://en.wikipedia.org/wiki/File:HSV-RGB-comparison.svg" rel="nofollow noreferrer">HSV-RGB comparison</a>). I've used <a href="https://pillow.readthedocs.io/en/4.0.x/reference/Image.html" rel="nofol...
python|numpy
1
15,283
52,940,773
How to resolve a latitude/longitude to a polygon in postgis
<p>I have a list of 13000 places (with latitude and longitude) --- in table : place. I have a list of 22000 polygons ---- in another table called place_polygon. I need to try and resolve the pois to the polygons that they belong to.</p> <p>This is the query that I wrote : </p> <pre><code>select * from stg_place.plac...
<p>First of all use geography type for your data instead of lat long columns. Why geography, not geometry? Because you use SRID=4326 and with geography type, it will be much easier if you want for example calculate distance in meters then with geometry type which will calculate in degrees for this SRID.</p> <p>To crea...
postgis|geopandas
2
15,284
65,596,522
LSTM for time-series prediction failing to learn (PyTorch)
<p>I'm currently working on building an LSTM network to forecast time-series data using PyTorch. I tried to share all the code pieces that I thought would be helpful, but please feel free to let me know if there's anything further I can provide. I added some comments at the end of the post regarding what the underlying...
<p>Once I used <a href="https://pytorch.org/docs/stable/tensor_view.html" rel="nofollow noreferrer">Tensor View</a> to reshape the mini-batches for the features in training and the validation set, the issue was resolved. As a side note, <code>view()</code> enable fast and memory-efficient reshaping, slicing, and elemen...
python|machine-learning|deep-learning|pytorch|lstm
1
15,285
63,697,913
Variable.assign(value) on Multi-GPU with Tensorflow 2
<p>I have a model that works perfectly on a single GPU as follows:</p> <pre class="lang-py prettyprint-override"><code>alpha = tf.Variable(alpha, name='ws_alpha', trainable=False, dtype=tf.float32, aggregation=tf.VariableAggregation.ONLY_FI...
<p>Simple fix, as per <a href="https://github.com/tensorflow/tensorflow/issues/34203" rel="nofollow noreferrer">tensorflow issues</a></p> <pre class="lang-py prettyprint-override"><code>alpha = tf.Variable(alpha, name='ws_alpha', trainable=False, dtype=tf.floa...
multi-gpu|tensorflow2
1
15,286
63,593,826
Python Employee heirarchy recursive function Error: # construct an ordered dict to store the result
<p>df</p> <pre><code>Employee Id Manager ID 1 3 2 1 3 4 4 NULL 5 NULL 6 7 7 5 and so on </code></pre> <p>So, 4 and 5 emp id are CXOs. Heirarchies expected output:(manager to employees under him)</p> <pre><code>1...
<p>The problem is that you are assigning a built-in type</p> <pre><code>list </code></pre> <p>to your variable</p> <p>Check for yourself</p> <pre><code>type([1,2,3,4]) </code></pre> <p>You need to assign some list to a variable, preferably not shadowing built-in types, such as list, and then call a function with that a...
python|pandas|list
0
15,287
63,594,350
Issue comparing pandas dates with Python dates
<p>This is a python code that I wrote but cannot find where I am doing wrong.I hope someone can help me here in debugging this code Code:</p> <pre><code>tx_data['InvoiceDate'] = pd.to_datetime(tx_data['InvoiceDate']) tx_uk = tx_data.query(&quot;Country=='United Kingdom'&quot;).reset_index(drop=True) #create 3month an...
<p>Python <code>datetime</code> types and Numpy datetimes (used by pandas) are not the same. So you need to convert your <code>datetime.datetime</code> in a <code>numpy.datetime64</code> to fix the issue.</p> <pre><code>tx_3m = tx_uk[(tx_uk.InvoiceDate &lt; numpy.datetime64(&quot;2011-6-1&quot;)) &amp; (tx_uk.InvoiceDa...
python|pandas|datetime
0
15,288
72,087,430
Find rank of column relative to other rows
<pre><code>df = pd.DataFrame({'Alice': [4,15,2], 'Bob': [9,3,5], 'Emma': [4,7,19]}) </code></pre> <p>I can find who got the highest score in each round with</p> <pre><code>df.idxmax(1) &gt; 0 Bob 1 Alice 2 Emma dtype: object </code></pre> <p>But I would like to find <strong>in which place Bob finished<...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rank.html" rel="nofollow noreferrer"><code>rank</code></a>:</p> <pre><code>df.rank(axis=1, method='first', ascending=False) </code></pre> <p><em>NB. check the methods to find the one that better suits your need:</em></p> <blockquote>...
pandas
2
15,289
71,926,392
Classify DataFrame rows based on the 3 most recent columns
<p>I have a pandas DataFrame, each column represents a quarter, the most recent quarters are placed to the right, not all the information gets at the same time, some columns might be missing information</p> <p>I would like to add at the end of the DataFrame another column called Criteria:</p> <ul> <li>If the 3 most rec...
<p>IIUC, you can <code>stack</code> and use a custom <code>groupby</code> function:</p> <pre><code>df['Criteria'] = np.where(df.stack().groupby(level=0) .apply(lambda s: s.tail(3).ge(10).all()), 'Y', 'N') </code></pre> <p><em>NB. B is &quot;N&quot; as 2021Q3 is &lt;...
python|pandas|dataframe
2
15,290
71,922,413
Split a pandas dataframe into train and test. Then convert into pivot while having same row names(strings) and column names (strings)
<p>Below is the sample dataset:</p> <pre><code>| * |reviewerID |asin |overall| |---|---------------| --------- | ----- | |0 |A2HD75EMZR8QLN |0700099867 |1.0 | |1 |A3UR8NLLY1ZHCX |0700099867 |4.0 | |2 |A1INA0F5CWW3J4 |0700099867 |1.0 | |3 |A1DLMTOTHQ4AST |0700099867 |3.0 | |4 |A361M14PU2GUEG |...
<p>Have you tried to use <strong>train_test_split</strong> of <strong>sklearn</strong>:</p> <pre><code>from sklearn.model_selection import train_test_split df = pd.read_csv(r&quot;\Dataset\pump_sensor_data\sensor.csv&quot;) X_df_train, X_df_test = train_test_split(df, test_size=0.2, shuffle=False) </code></pre>
python|pandas|scikit-learn
-1
15,291
55,441,948
Pandas: replace values in column if they apprear in another column - with values from a third one
<p>I have a somewhat complicated action I need to perform. I have a dataframe: lets call it df1, with column "a". some of its values appear in df2 - another dataframe, in a column called "b". if a certain value is in "b" in df2, I would like to replace them with a values from df3, column "c", in a row number same as th...
<p>You can create dictionary by <code>b</code> and <code>c</code>, only necessary same lengths and unique values of <code>b</code> and then <code>map</code> values of <code>a</code> by <code>get</code> for possible specify default value:</p> <pre><code>d = dict(zip(b, c)) out = [d.get(x, constant) for x in a] print (...
python|pandas
0
15,292
55,356,609
How to open the excel file creating from pandas faster?
<p>The excel file creating from python is extremely slow to open even the size of file is about 50 mb.</p> <p>I have tried on both pandas and openpyxl.</p> <pre class="lang-py prettyprint-override"><code>def to_file(list_report,list_sheet,strip_columns,Name): i = 0 wb = ExcelWriter(path_output + '\\' + Name +...
<h1>idiom</h1> <p>Let us rename <code>list_report</code> to <code>reports</code>. Then your <code>while</code> loop is usually expressed as simply: <code>for i in range(len(reports)):</code></p> <p>You access the <code>i</code>-th element several times. The loop could bind that for you, with: <code>for i, report in enu...
python|excel|python-3.x|pandas
0
15,293
47,246,942
How to use datetime field froma dataframe in linregress scipy?
<p>When I try to <code>linregress</code> the <code>Date</code> and <code>Close</code> field from a <code>dataframe</code> I keep getting the <code>error</code>.</p> <blockquote> <p>Traceback (most recent call last): File &quot;&quot;, line 1, in File &quot;C:\Python34\lib\site-packages\scipy\stats_stats_mstats_common....
<p>Scipy can only do linear regression over numerical values; it does not know how to handle dates. The best way to proceed is probably to convert your dates to numbers (e.g. number of days, number of seconds, etc. as appropriate). Here is an example:</p> <pre><code>import pandas as pd import numpy as np data = pd.Da...
python|numpy|scipy
6
15,294
47,311,266
Update pandas dataframe based on matching columns of a second dataframe
<p>I have two pandas dataframes (<strong>df_1</strong>, <strong>df_2</strong>) with the same columns, but in one dataframe (<strong>df_1</strong>) some values of one column are missing. So I want to fill in those missing values from <strong>df_2</strong>, but only when the the values of two columns match.</p> <p>Here ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> for <code>Multiindex</code> in both <code>DataFrame</code>s and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.co...
python|pandas|dataframe|nan|data-science
3
15,295
47,441,863
Selecting entries from slices with Numpy
<p>Suppose that we have array A of shape (3, 10, 10) and array B of shape (10, 10). Each element of B is index of an element along first axis of A. How can I create array C using operations where <code>C[i, j] = A[B[i,j], i, j]</code>?</p>
<p>Use advanced indexing and broadcasting:</p> <pre><code>import numpy as np L, M, N = 3, 8, 10 A = np.arange(L)[:, None, None] + 10*np.arange(M)[:, None] + 100*np.arange(N) B = np.random.randint(0, L, (M, N)) m, n = np.ogrid[:M, :N] C = A[B, m, n] np.all(C%10 == B) # True </code></pre>
python|numpy|indexing
1
15,296
68,377,991
Column assigned into a pd.DataFrame is duplicated in another pd.DataFrame
<p>I have the following peace of code:</p> <pre><code>predictions_dict['AE'] = predictions_df errors_dict['AE'] = (train_with_nan_df.iloc[1:] - predictions_dict['AE']) errors_dict['AE']['MSE'] = np.nanmean(np.power(errors_dict['AE'], 2), axis=1) </code></pre> <p>I am using dictionaries to store the predictions and erro...
<p>Simple answer, I had defined the dictionaries as follow:</p> <pre><code>errors_dict = predictions_dict = dict() </code></pre> <p>I thought that it created 2 independent empty dictionaries, but it doesn't seem this way. I just changed it to:</p> <pre><code>errors_dict = dict() predictions_dict = dict() </code></pre>
python|pandas
0
15,297
68,243,701
I am Curious on how should I approach to get the JSON to Pandas
<p>I'm trying to write code to use data to generate a report. Instead of iterating through the dictionary, I wanted to use Pandas this time.</p> <p>So, the first issue I faced was null in the data. I corrected it using <code>json.loads()</code>.</p> <p>I am trying to understand how can I get the nested JSON to Pandas.<...
<p>I suspect your problem is the comma after the } in the line before the ],</p> <p>There is no following element, so the comma is not correct.</p> <p>Remove that and try again.</p> <pre><code>{ &quot;Scans&quot;: [ { &quot;Targets&quot;: [ { &quot;Id&quot;: &...
python|python-3.x|pandas|dataframe
0
15,298
68,380,796
Why the first iteration is more time-consuming in pytorch?
<p>I'm trying to calculate how much time our model takes in every iteration.</p> <p>I'm using pytorch.</p> <p>Here is the code.</p> <pre><code>for i, (inp, gt) in enumerate(test_loader): inp = torch.zeros((1,3,224,224)).cuda() print('The %d-th iteration' % (i)) time_start = time.clock() with torch.no_...
<p>The first <code>.cuda</code> call will allocate memory on the GPU which will be used again by the consecutive iterations. This is certainly the reason why the first iteration takes longer. You may try to force-release the allocated memory (with <a href="https://pytorch.org/docs/stable/generated/torch.cuda.empty_cach...
python|pytorch
0
15,299
57,043,401
What is the difference between the properties "kernel_initializer" and "kernel" in layers.Dense?
<p>In the <a href="https://www.tensorflow.org/api_docs/python/tf/layers/Dense?hl=en" rel="nofollow noreferrer">documentation</a> on the TensorFlow website for <code>tf.layers.Dense</code>, it lists <code>kernel_initializer</code> and <code>kernel</code> as its properties. From what I understand, the <code>kernel_initia...
<p>In short, you can use <code>kernel_initializer</code> for <em>shortcut</em> initializations as zeros, ones, random_normal etc (you can see the full list <a href="https://www.tensorflow.org/api_docs/python/tf/keras/initializers" rel="nofollow noreferrer">here</a>). </p> <p><code>kernel</code> will accept a set weigh...
python|tensorflow
0