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
376,800
63,249,580
Delete Consecutive Values of Specific Number - Python Dataframe
<p>How can you remove consecutive duplicates of a specific value?</p> <p>I am aware of the <code>groupby()</code> function but that deletes consecutive duplicates of any value.</p> <p>See the example code below. The specific value is 2, in which I want to remove duplicates</p> <pre><code>import pandas as pd from iterto...
<p>Doing this with <code>pandas</code> seems overkill unless you are using <code>pandas</code> for other purposes, e.g.:</p> <pre><code>In []: import itertools as it example = [1,1,5,2,2,2,7,9,9,2,2] [x for k, g in it.groupby(example) for x in ([k] if k == 2 else g)] Out[]: [1, 1, 5, 2, 7, 9, 9, 2] </code></pre>
python|python-3.x|pandas|dataframe|itertools
1
376,801
63,046,321
Concatenating two numpy arrays side by side
<p>I need to concatenate two numpy arrays side by side</p> <pre><code>np1=np.array([1,2,3]) np2=np.array([4,5,6]) </code></pre> <p>I need <code>np3</code> as <code>[1,2,3,4,5,6]</code> with the same shape, how to achieve this?</p>
<p>In <code>concatenate</code> you have to pass <code>axis</code> as <code>None</code></p> <pre><code>In [9]: np1=np.array([1,2,3]) ...: np2=np.array([4,5,6]) In [10]: np.concatenate((np1,np2), axis=None) Out[10]: array([1, 2, 3, 4, 5, 6]) </code></pre>
python|arrays|numpy
1
376,802
62,991,016
tensorflow keras model for solving simple equation
<p>I'm trying to understand how to create a simple tensorflow 2.2 keras model that can predict a simple function value:</p> <pre><code>f(a, b, c, d) = a &lt; b : max(a/2, c/3) : max (b/2, d/3) </code></pre> <p>I know this exact question can be reduced to a categorical classification but my intention is to find a good w...
<ol> <li><p>In my honest opinion, you have a pretty deep model, and therefore, you do not have enough data to train. I do not think you will need that much deep architecture.</p> </li> <li><p>Your problem definition is not what I would have done. You actually do not desire to generate the max value at the output, but y...
tensorflow|machine-learning|keras|deep-learning|neural-network
1
376,803
63,234,174
Display full Pandas dataframe in Jupyter without index
<p>I have a pandas dataframe that I would like to pretty-print in full (it's ~90 rows) in a Jupyter notebook. I'd also like to display it without the index column, if possible. How can I do that?</p>
<p>In pandas you can use this</p> <pre><code>pd.set_option(&quot;display.max_rows&quot;, None, &quot;display.max_columns&quot;, None) </code></pre> <p>please use this.</p> <p>Without index use additionally.</p> <pre><code>df.to_string(index=False) </code></pre>
python-3.x|pandas|jupyter-notebook
3
376,804
63,232,970
How to loop through pandas data frame and rename all of the columns?
<p>I have a pandas data frame that has several columns that I would like to rename.</p> <pre><code>+------+--------------------------+--------------------------+--------------------------+ | FIPS | ('Active', '03/22/2020') | ('Active', '03/23/2020') | ('Active', '03/25/2020') | +------+--------------------------+------...
<p>One solution would be to write a function to fix the column names. You can then create a dict comprehension and pass this to <code>DataFrame.rename</code> to fix them. For example, something like:</p> <pre><code>import pandas as pd import re from datetime import datetime def fix_column_name(val): if 'Active' in...
python|pandas
1
376,805
62,978,957
Sliding window for long text in BERT for Question Answering
<p>I've read post which explains how the sliding window works but I cannot find any information on how it is actually implemented.</p> <p>From what I understand if the input are too long, sliding window can be used to process the text.</p> <p>Please correct me if I am wrong. Say I have a text <em><strong>&quot;In June ...
<p>I think there is a problem with the examples you pick. Both <a href="https://github.com/huggingface/transformers/blob/1af58c07064d8f4580909527a8f18de226b226ee/src/transformers/data/processors/squad.py#L273" rel="nofollow noreferrer">squad_convert_examples_to_features</a> and <a href="https://github.com/huggingface/t...
nlp|text-classification|huggingface-transformers|nlp-question-answering|bert-language-model
3
376,806
63,127,668
Pandas "to_datetime" not accepting series
<p>I am new to pandas and am trying to convert a column of strings with dates in the format '%d %B' (01 January, 02 January .... ) to date time objects and the type of the column is <code>&lt;class 'pandas.core.series.Series'&gt;</code> . if i pass in this series in the to_datetime method, like</p> <pre><code>print(pd....
<p>If I understand correctly, you may be facing this issue because there are spaces around the dates in this column. To solve it, use <code>strip</code> before <code>to_datetime</code>. Here's a piece of code that does that:</p> <pre><code>df = pd.DataFrame({'Date': ['30 January ', '31 January ', ' ...
python|pandas|dataframe|time-series
1
376,807
67,895,055
Build a Pandas DataFrame with one unique column of different size
<p>I want to build the following DataFrame:</p> <pre class="lang-py prettyprint-override"><code>num | col1 | col2 a | 1 | 3 | 2 | 4 | 8 | 2 b | 0 | 9 | 4 | 2 | 3 | 1 </code></pre> <p>I tried the following but did not know how of include the column <code>num</code></p> <pre class="l...
<pre><code>col1 = [1, 2, 8, 0, 4, 3] col2 = [3, 4, 2, 9, 2, 1] num = ['a']*3 + ['b']*3 # same as ['a', 'a', 'a', 'b', 'b', 'b'] d = pd.DataFrame({'col1': col1, 'col2': col2}, index=num) </code></pre> <pre><code>&gt;&gt;&gt; d col1 col2 a 1 3 a 2 4 a 8 2 b 0 9 b 4 2 b ...
python|pandas|matrix
0
376,808
67,837,701
How to use sorting in pandas with similar names?
<p>I have used <strong>.sort_values(by = ['Tag'])</strong> it gets the work done but it doesn't sort based on the index and when I used <strong>.sort_index</strong> it works but again the <strong>tag</strong> gets <strong>jumbled</strong>. Any heads up, please.</p> <div class="s-table-container"> <table class="s-table"...
<p>Try this?</p> <pre><code>&gt;&gt;&gt; df.sort_values(['Tag','Index']) Index Tag 5 99 P3010A 6 434 P3010A 2 1122 P3010A 0 1294 P3010A 3 1466 P3010A 7 262 P3010B 4 950 P3010B 1 1638 P3010B </code></pre>
pandas
0
376,809
67,900,834
How to convert the dictionary with one key and a tuple as the key value into a DataFrame?
<p>I have a dictionary like this.</p> <p><code>dict={'good': (5, 3, 5), 'nice': (6, 0, 0), 'very': (8, 3, 4), 'not': (2, 0, 1)}</code></p> <p>I need to convert it into a dataframe such that it looks like this:</p> <pre><code>Variable Positive Neutral Negative good 5 3 5 nice 6 ...
<p>You can pass an index to <code>pd.DataFrame</code> and then take <code>T</code>ranpose:</p> <pre><code>pd.DataFrame(d, index=[&quot;Positive&quot;, &quot;Neutral&quot;, &quot;Negative&quot;]).T </code></pre> <p>or <code>swapaxes</code>:</p> <pre><code>pd.DataFrame(d, index=[&quot;Positive&quot;, &quot;Neutral&quot;,...
python|pandas|dataframe|dictionary|count
2
376,810
67,795,164
Count consecutive occurrence's for column
<p>I am trying to count consecutive occurrence's for Products column. Result should be as shown in &quot;Total counts&quot; column. I tried using groupby with cumsum but my logic could not work</p> <pre><code>+----------+--------------+ | Products | Total counts | +----------+--------------+ | 1 | 3 |...
<p>Use <code>groupby</code> with <code>transform</code> and count,</p> <pre><code>df['Total counts'] = df.groupby('Products').transform('count') </code></pre> <p>Output:</p> <pre><code> Products Total counts 0 1 3 1 1 3 2 1 3 3 2 1 4 ...
python|pandas|numpy
1
376,811
67,728,562
Pandas how to split vlaues of every column based on colon
<p>I am trying to split all the column values and want to retain only second index ie <code>-1</code>, it works with the individual columns like <code>str.split(': ').str[-1]</code> but as being a novice learner I'm not able to apply it for all columns.</p> <p>Indeed I want to retain the values from every column after ...
<p>Try with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow noreferrer"><code>applymap</code></a>:</p> <pre><code>df = df.applymap(lambda x: x.split(': ', 1)[-1]) </code></pre> <p><code>df</code>:</p> <pre><code> LoginShell ExpiryDate U...
python|pandas|dataframe|split
2
376,812
67,784,653
Filter on specific value dataframe pandas/ python
<p>I want to create a function that filter on a specific value in a column of an dataframe(<br /> My dataframe has the follow columns and value:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Zoekterm</th> <th style="text-align: left;">High_bias</th> </tr> </thead...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a> with filtered rows and convert <code>Series</code> to DataFrame by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.res...
python|pandas|dataframe|data-science
1
376,813
67,990,773
Size of input allowed in AllenNLP - Predict when using a Predictor
<p>does anyone has an idea what is the input text size limit that can be passed to the predict(passage, question) method of the AllenNLP Predictors.</p> <p>I have tried with passage of 30-40 sentences, which is working fine. But eventually it is not working for me when I am passing some significant amount of text aroun...
<p>Which model are you using? Some models truncate the input, others try to handle arbitrary length input using a sliding window approach. With the latter, the limit will depend on the memory available on your system.</p>
pytorch|prediction|allennlp
0
376,814
67,704,405
Python/Numpy: Using np.tile to tile 2D array of boolean mask arrays
<p>I have a 2D array of boolean mask arrays:</p> <pre><code>maskArr = [[False, True, False, True], [False, True, True, True], [True, True, False, True]] </code></pre> <p>for which I am trying to use <code>np.tile(maskArr, (3, 1))</code> to get the following output:</p> <pre><code>[ [[False, True, False, True], [Fa...
<p>You can use:</p> <pre class="lang-py prettyprint-override"><code>x = np.tile(maskArr, (3, 1, 1)) print(x) </code></pre> <p>Prints:</p> <pre class="lang-py prettyprint-override"><code>[[[False True False True] [False True True True] [ True True False True]] [[False True False True] [False True True...
python|numpy|multidimensional-array
2
376,815
67,934,526
Column Data in CSV file to h5 format
<p>I am trying to convert a CSV file to h5 format file.</p> <p>I have gone through multiple posts and I have been able to create the h5 file but still unable to pull individual columns from the CSV file and add them to the h5 file, please let me know if there is any solution to this.</p> <p>Essentially I have four colu...
<p>As specified in the <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/user_guide/io.html#hdf5-pytables" rel="nofollow noreferrer">pandas I/O guide, section HDF5 (PyTables)</a>, there are 2 simple functions to store as hdf:</p> <ul> <li><a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference...
python|pandas|csv|hdf5
0
376,816
67,671,601
Add weekday sequentially from one-hot encoded input
<p>I am trying to convert a sparse weekday format, sequentially representing week days, adding contextual information from an additional list;</p> <p>to illustrate:</p> <pre><code>weekdays = [&quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thursday&quot;, &quot;Friday&quot;, &quot;Saturday&quot;, ...
<p>Assuming each <code>employee_name</code> has exactly 7 rows, you can use:</p> <pre><code>weekdays = [&quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thursday&quot;, &quot;Friday&quot;, &quot;Saturday&quot;, &quot;Sunday&quot;] df['weekday'] = df.groupby('employee_name').transform(lambda x: wee...
python|python-3.x|pandas
0
376,817
67,718,791
Training Word2Vec Model from sourced data - Issue Tokenizing data
<p>I have recently sourced and curated a lot of reddit data from Google Bigquery.</p> <p>The dataset looks like this:</p> <p><a href="https://i.stack.imgur.com/q1C1G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q1C1G.png" alt="Data Preview" /></a></p> <p>Before passing this data to word2vec to cre...
<p>After taking gojomo's advice I simplified my approach at reading the csv file and writing to a text file.</p> <p>My initial approach using pandas had yielded some pretty bad processing times for a file with around 12 million rows, and memory issues due to how pandas reads data all into memory before writing it out t...
python|pandas|tokenize|word2vec
1
376,818
67,889,900
How to convert row names into a column in Pandas
<p>I have the following excel dataset:</p> <pre><code> ($/bbl) ($/bbl) ($/bbl) crude_petro crude_brent crude_dubai 1960M01 1.63 1.63 1.63 1960M02 1.63 1.63 1.63 1960M03 1.63 1.63 1.63 </code></pre> <p>What I want to do is to convert the ...
<p>Try with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html#pandas-melt" rel="nofollow noreferrer"><code>melt</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html#pandas-dataframe-sort-index" rel="nofollow noreferrer"><cod...
python|pandas|dataframe
1
376,819
67,711,552
Python: Split pandas dataframe by range of values
<p>I have a simple dataframe in which I am trying to split into multiple groups based on whether the x column value falls within a range.</p> <p>e.g. if I have:</p> <pre><code>print(df1) x 0 5 1 7.5 2 10 3 12.5 4 15 </code></pre> <p>And wish to create a new dataframe, df2, of values of x which are within the range 7-...
<p>You can create a boolean mask for the range (7 &lt; x &lt; 13) by AND condition of (x &gt; 7) and (x &lt; 13). Then create <code>df2</code> with this boolean mask. The remaining entries left in <code>df1</code> being the negation of this boolean mask:</p> <pre><code>thresh_low = 7 thresh_high = 13 mask = (df1['x'] ...
python|pandas|dataframe|pandas-groupby
3
376,820
67,967,625
Create a column with values of a list and depending on another column
<ul> <li>I have a list of paths of different images:</li> </ul> <p><code>img_dir = [img_pathA.1.jpg, img_pathA.2.jpg, img_pathA.3.jpg, img_pathB.1.jpg, img_pathB.2.jpg, .... img_pathZ.3.jpg]</code></p> <ul> <li>And a dataframe with an <code>ID</code> column:</li> </ul> <p><code>df</code>:</p> <div class="s-table-contai...
<p>Create a series from the <code>img_dir</code> list then <code>extract</code> the <code>ID</code> from the corresponding paths and set the extracted <code>ID</code> as the index of the series, then <code>join</code> the dataframe with this series on the column <code>ID</code></p> <pre><code>s = pd.Series(img_dir) s.i...
python|pandas|dataframe|loops|data-manipulation
2
376,821
67,738,487
Pandas-Profiling.to_widgets(): Error displaying widget: model not found
<p>Error screenshot</p> <p><a href="https://i.stack.imgur.com/p0sLi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p0sLi.png" alt="" /></a></p> <p>I've been facing an <strong>intermittent issue with pandas profiling widget</strong> not rendering &amp; it has been going on and off for awhile.</p> <p>...
<p>I had this problem in Kaggle, I think it is related to memory. It happens when I repeat running my notebook a few times, without restarting the kernel.</p> <p>To fix it, I just clicked Run, then Restart and Clear Outputs, and it's working again.</p> <p>I have since then optimized my codes to release memory when don...
widget|pandas-profiling
0
376,822
67,649,606
Error in reverse scaling outputs predicted by a LSTM RNN
<p>I used the LSTM model to predict the future <code>open</code> price of a stock. Here the data was preprocessed and the model was built and trained without any errors, and I used Standard Scaler to scale down the values in the DataFrame. But while retrieving the predictions from the model, when I used the <code>scale...
<p>This is because the model is predicting output with shape (59, 1). But your Scaler was fit on (251, 4) data frame. Either create a new scaler on the data frame of the shape of y values or change your model dense layer output to 4 dimensions instead of 1. The data shape on which scaler is fit, it will take that shape...
python|tensorflow|keras|lstm|recurrent-neural-network
3
376,823
67,871,982
Train a custom Mask RCNN with different image sizes in Google Colab. Unfortunately i can't get it running
<p>currently I'm trying to train a Matterport Mask R-CNN with custom classes and a custom dataset on Colab. I followed this tutorial: <a href="https://github.com/TannerGilbert/MaskRCNN-Object-Detection-and-Segmentation" rel="nofollow noreferrer">https://github.com/TannerGilbert/MaskRCNN-Object-Detection-and-Segmentatio...
<p>You must set width and height value in <code>load_yourdatasetname()</code> by <code>self.add_imge</code> and get in <code>load_mask</code> function</p> <p>Example:</p> <pre><code>class Covid19Dataset(utils.Dataset): def load_covid19(self, dataset_dir, subset): &quot;&quot;&quot;Load a subset of the covi...
python|tensorflow|google-colaboratory
0
376,824
67,654,412
Auto-extracting columns from nested dictionaries in pandas
<p>So I have this nested multiple dictionaries in a jsonl file column as below:</p> <pre><code> `df['referenced_tweets'][0]` </code></pre> <p>producing (<em>shortened output</em>)</p> <pre><code> 'id': '1392893055112400898', 'public_metrics': {'retweet_count': 0, 'reply_count': 1, 'like_count': 2, 'quot...
<p>A couple things to consider here. <code>referenced_tweets</code> holds a list so this line <code>new_df= pd.DataFrame.from_dict(i)</code> is most likely not parsing correctly the way you are entering it.</p> <p>Also, because it's possible there are multiple tweets in that list you are correctly iterating over it but...
python-3.x|pandas|dictionary|twitter|jsonlines
0
376,825
67,726,123
Postgresql batch insert for csv file/dataframe (on GCP)
<p>I have a csv file with two columns, <code>[key, chunk]</code>, which I need to insert to into a SQL db table. (Amplifying info- Postgresql db hosted on GCP, I'm able to select and perform other db operations fine.)</p> <p>My csv file has over 10 million rows. And so, I'm curious what's the best batch insert option a...
<p>You can simply use the <a href="https://cloud.google.com/sql/docs/postgres/import-export/importing#gcloud" rel="nofollow noreferrer">import function in Cloud SQL</a> to load a CSV file in the database. Then, run a query to select the value that you want and to merge them in the target table.</p> <p><em>When you can,...
sql|pandas|postgresql|google-cloud-platform|batch-processing
0
376,826
67,886,396
What is the Vaex command for pd.isnull().sum()?
<p>Someone please give me a VAEX alternative for this code:</p> <pre><code>df_train = vaex.open('../input/ms-malware-hdf5/train.csv.hdf5') total = df_train.isnull().sum().sort_values(ascending = False) </code></pre>
<p>Vaex does not at this time support counting missing values on a dataframe level, only on an expression (column) level. So you will have to do a bit of work yourself.</p> <p>Consider the following example:</p> <pre class="lang-py prettyprint-override"><code>import vaex import vaex.ml import pandas as pd df = vaex.ml...
pandas|dataframe|vaex
2
376,827
67,648,160
What's the fastest way to produce rolling window embeddings in time series data?
<p>I'm interested in transforming a typical time series dataset (one dimension) into a matrix consisting of every possible sequential combination of the original one. My stride is always 1 (might change in the future), window size should change according to preference, overlaps are encouraged and my focus is intraday d...
<p>Group the column <code>values</code> on <code>date</code> then inside a list comprehension iterate over each group and apply the <code>sliding_window_view</code> transformation, then vertically stack all the sliding views corresponding to each group</p> <p>For numpy version &gt;= <code>1.20</code></p> <pre><code>fro...
pandas|datetime|time-series
2
376,828
67,692,862
tensorflow dependencies continuously gives me errors in colab during installation of deepspeech environment
<p>when I run the following command on Google Colab</p> <pre><code>!pip3 install --upgrade pip==20.0.2 wheel==0.34.2 setuptools==46.1.3 !pip3 install --upgrade --force-reinstall -e . </code></pre> <p>Got an error</p> <pre><code> ERROR: pip's dependency resolver does not currently take into account all the packages t...
<p>First do not forget to restart runtime after running your current cell. i.e.</p> <pre><code>!pip3 install folium==0.2.1 !pip3 install --upgrade pip==20.0.2 wheel==0.34.2 setuptools==46.1.3 !pip3 install --upgrade --force-reinstall -e . # Restart Colab after this cell </code></pre> <p><strong>I was getting the same ...
python|tensorflow|google-colaboratory|mozilla-deepspeech
1
376,829
67,605,983
how to read an excel file using pandad pd.read_excel in databricks from /Filestore/tables/ directory?
<p>Hi I am trying to read an excel file that's uploaded to DBX filestore from UI. I can see that file is available under /Filestore/tables directory and I am trying to create a pandas dataframe using the code below</p> <pre><code>import pandas as pd df = pd.read_excel(&quot;/dbfs/FileStore/tables/abc.xlsx&quot;) displa...
<p>The file is not stored as an excel file when you create a table. You access the data via the <a href="https://docs.databricks.com/data/tables.html#language-python" rel="nofollow noreferrer">Spark API</a>.</p> <p>You could also read the table into a koalas dataframe and then convert it to pandas if you don't want to ...
python|pandas|pyspark|databricks
0
376,830
68,011,337
need to add a column together and put the average beneath the column in Pandas
<p>I'm currently trying to add a column together that has two rows to it as such:</p> <p><a href="https://i.stack.imgur.com/q8FXP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q8FXP.png" alt="Housekeeping" /></a></p> <p>Now I just need to add row 1 and 2 together for each column, and I want to appe...
<p>Try this:</p> <pre><code>sub_houseKeeping = pd.DataFrame({'ID':['200650_s_at','1565446_at'], 'phchp003v1':[2174.84972,6.724141107], 'phchp003v2':[444.9008362,4.093883364]}) sub_houseKeeping = sub_houseKeeping.append(pd.DataFrame(sub_houseKeeping.mean(axis=0)).T, ignore_index=True) </code></pre> <p>Output:</p> <pre><...
python|pandas|csv
0
376,831
68,004,473
Compare values in a list to a data frame and if true, amend value to item in data frame
<pre><code>import pandas as pd trade_count = 3 Buyer = [&quot;Company&quot;, &quot;Company&quot;, &quot;Company&quot;] ''' MAPPING = pd.read_excel(r&quot;H:\Metals_tempest\MAPPING.xlsx&quot;, na_filter = False) print(Buyer) # Buyer = pd.DataFrame({'col':Buyer}) # print (df) for i in range (0, trade_count): # Buye...
<p>You can convert <code>MAPPING</code> to a dictionary and use it in a list comprehension:</p> <pre><code>map_dict = MAPPING.set_index(&quot;Ticket&quot;)[&quot;Tempest&quot;].to_dict() Buyer = [map_dict.get(i, i) for i in Buyer] </code></pre>
python|pandas|dataframe
0
376,832
67,916,283
Deeplearning with Python Tensorflow,Keras
<p>I am writing masters thesis about deeplearning and have a problem probably about library.</p> <p>Below is the error:</p> <pre><code>AttributeError: module 'tensorflow.compat.v2' has no attribute '__internal__' </code></pre> <p>Model:</p> <pre><code>import tensorflow from tensorflow import keras from keras impor...
<p>I think that the problem lies in the way you are importing the modules you need. Try to do this way:</p> <pre><code>import tensorflow from tensorflow.keras import models, layers model = models.Sequential() model.add(layers.Dense(32, input_shape=(784,))) model.add(layers.Dense(32)) model.summary() </code>...
python|tensorflow|keras
1
376,833
67,989,744
Pandas replacing values in a column by values in another column
<p>Let's say I have the following dataframe X (ppid is unique):</p> <pre><code> ppid col2 ... 1 'id1' '1' 2 'id2' '2' 3 'id3' '3' ... </code></pre> <p>I have another dataframe which serves as a mapping. ppid is same as above and unique, however it might not contain all X's ppids:</p> <pre><code> ppid v...
<p>Try using <code>map</code> with <code>set_index</code>:</p> <pre><code>df_x = pd.DataFrame({'ppid':['id1','id2','id3'], 'col2':[*'123']}) df_a = pd.DataFrame({'ppid':['id1','id2'], 'val':[*'56']}) df_x['col2'] = df_x['ppid'].map(df_a.set_index('ppid')['val']).fillna(df_x['col2']) </code></pre> <p>Output:</p> <pre>...
python|pandas|dataframe
2
376,834
67,644,774
Force index reset in pandas
<p>Below is how I prepare the DataFrame from a candle list obtained from an API</p> <p>candle list contains the open, high, low, close, volume values as a nested</p> <pre><code>candles = [ [time.time() , random(1000 ,9999) , random(1000 ,9999) ,random(1000 ,9999),random(1000 ,9999),random(1000 ,9999) ] for i in range(1...
<p>Use either</p> <pre><code>return df.reset_index(drop=True) </code></pre> <p>or</p> <pre><code>df.reset_index(drop=True, inplace=True) return df </code></pre> <p>You have used <code>return df.reset_index(drop=True, inplace=True) </code> which is wrong because when <code>inplace=True</code> the method returns None. C...
python|pandas
0
376,835
67,734,217
how to change datetimeindex to just contain date in python
<p>I have a column called date with this values</p> <pre><code>&gt; DatetimeIndex(['2014-02-19'], dtype='datetime64[ns]', freq=None) &gt; DatetimeIndex(['2013-02-29'], dtype='datetime64[ns]', freq=None) &gt; DatetimeIndex(['2018-04-15'], dtype='datetime64[ns]', freq=None) </code></pre> <p>how do i modify the column to ...
<p>Do you mean something like this (not tested)?</p> <pre><code>def fundate(x): return x.strftime(&quot;%Y-%m-%d&quot;) </code></pre> <p>From <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/ref...
python|python-3.x|pandas|datetime|strptime
0
376,836
67,682,674
Filter a numpy array by function
<p>I have a 2D numpy array in the following form:</p> <pre><code>array([[0, 4], [1, 5], [2, 6]]) </code></pre> <p>I want to filter out the rows that their first value is bigger than 1, but I couldn't find a numpy function to do so.</p> <p>I know that I can use <code>filter</code>:</p> <pre><code>np.array(...
<p>There is not <code>numpy</code> interface to do this efficiently with a function. However, in this <em>particular</em> case, you just want something like:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; arr = np.array([[0, 4], ... [1, 5], ... [2, 6]]) &gt;&gt;&gt; arr[arr[:,0] &lt;= 1] arra...
python|numpy
1
376,837
67,803,553
Pandas: tidy multilevel data
<p>I'm trying to get this dataset into a tidy format in pandas.</p> <p><a href="https://i.stack.imgur.com/mbvY2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mbvY2.jpg" alt="enter image description here" /></a></p> <p>I need to melt/reshape this in such a way as to have one <strong>id</strong> colu...
<p>First create <code>MultiIndex</code> by <code>header</code> parameter in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html" rel="nofollow noreferrer"><code>read_excel</code></a> and then reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataF...
python|pandas|dataframe
2
376,838
67,758,456
Merging the column names based on the values to create another column
<p>I have a movies dataset containing various movie genres and whether the movie belongs to that genre or not. E.g.</p> <pre><code>Index Biography Comedy Crime Documentary Drama Family Fantasy 0 0 1 0 0 1 1 0 1 0 1 0 0 0 1 0 2 0 0 0 0 1 0 0 3 0 1 0 0 0 0 0 4...
<p>With matrix multiplication in Python:</p> <pre><code>df.dot(df.columns + &quot; &quot;) </code></pre> <p>to get</p> <pre><code>Index 0 Comedy Drama Family 1 Comedy Family 2 Drama 3 Comedy 4 Comedy Drama 5 Crime Drama 6 Comedy </code></...
python|r|pandas|dataframe|data-preprocessing
2
376,839
67,636,478
Python/Numpy: Vectorizing repeated row insertion in a 2D array
<p>Is it possible to vectorize the insertion of rows?</p> <p>I have a large 2D numpy array <code>arr</code> (below) and a list of <code>indices</code>. For each index of <code>arr</code> in <code>indices</code> I would like to insert the row at that index back into <code>arr</code> row 5 times at that same index.</p> <...
<p>You could use <code>np.repeat</code> for this:</p> <pre><code>indices = [2, 4, 5, 9, 11, 12, 16, 18, 19] rpt = np.ones(len(arr), dtype=int) rpt[indices] = 5 np.repeat(arr, rpt, axis=0) </code></pre>
python|numpy|multidimensional-array|vectorization|masking
3
376,840
67,959,516
How to efficiently find the indices a first array values matching with a second array values?
<p>I have two numpy arrays A and B. A has shape <code>(10000000, 3)</code> and B has shape <code>(1000000, 3)</code>. Both the arrays are XYZ coordinates such that B corresponds to some region of A. I have to find indexes of A which correspond to values B. Right now I am solving as below. I would like some help in opti...
<p>The issue here is not the speed of pure-python code, but the <strong>algorithm</strong> itself. You can use <strong>sorted-arrays</strong> or <strong>hash-tables</strong> to improve the complexity of the algorithm to <code>O(n log n)</code> or even <code>O(n)</code> rather than the slow current <code>O(n^2)</code> s...
python|performance|numpy
4
376,841
67,922,408
Zooming in on Mandelbrot set
<p>I have the following code:</p> <pre><code> # MANDELBROT a = np.arange(-2, 2, 0.01) b = np.arange(-2, 2, 0.01) M_new = new_matrix(a, b) plt.imshow(M_new, cmap='gray', extent=(-2, 2, -2, 2)) plt.show() ## ZOOMING a_2 = np.arange(0.1, 0.5, 0.01) b_2 = np.arange(0.1, 0.5, 0.01) M_new_2 = new_matrix(a_2, b_2) plt.imsh...
<p>I did several changes to you code, mainly respecting the shape of the input arrays.</p> <pre><code>import numpy as np from matplotlib import pyplot as plt def mandelbrot(c: complex): m = 0 z = complex(0, 0) for i in range(0, 100): z = z*z+c m += 1 if np.abs(z) &gt; 2: ...
python|numpy|mandelbrot
1
376,842
67,795,380
Pandas Dataframe Comparison and Copying
<p>Below I have two dataframes, the first being dataframe det and the second being orig. I need to compare <code>det['Detection']</code> with <code>orig['Date/Time']</code>. Once the values are found during the comparion, I need to copy values from <code>orig</code> and <code>det</code> to some final dataframe (<code>f...
<p>You can merge the two dataframes, since you want to use <code>Detection</code> column from the first data frame and <code>Date/Time</code> column from the second dataframe, you can just rename the column of second dataframe while merging since the column name already exits in the first dataframe:</p> <pre class="lan...
python|pandas|dataframe
1
376,843
68,007,293
Plotting with Crosstab and groupby question
<p>I need a help, I am not getting to make this kind of graph using crosstab pandas. Any help please?</p> <p>Dataframe</p> <pre><code>{'nome_munic': {66: 'Ferraz de Vasconcelos', 97: 'São Paulo', 100: 'São José dos Campos', 207: 'Mauá', 249: 'Cajamar', 258: 'Votuporanga', 285: 'Ferraz de Vasconcelos', 290...
<p>IIUC, you can try:</p> <pre><code>df.pivot_table(index='obito', values=['asma', 'cardiopatia','diabetes','doenca_renal','obesidade']).T.plot(kind ='bar' , stacked = True) </code></pre> <p>OUTPUT:</p> <p><a href="https://i.stack.imgur.com/R5X1P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R5X1P....
pandas|matplotlib|seaborn|pivot-table|crosstab
1
376,844
67,717,566
How to create a two-dimensional numpy array from two tif files in python?
<p>I am working in Google Colab. I have imported two tif files with 1000 rows and 1000 columns with the following script:</p> <pre><code>import cv2 green = cv2.imread('green.tif') nir = cv2.imread('nir.tif') </code></pre> <p>I want to create an array which will have a two-dimensional vector in every pixel with the val...
<p>If you want to interlace the two volumes and consider <em>green</em> as channel 1 and <em>nir</em> as channel 2 you can proceed as follows:</p> <pre><code>ch1 = np.ones((2,2,2)) ch2 = np.zeros((2,2,2)) out = np.empty((4,2,2)) out[::2,:,:] = ch1 out[1::2,:,:] = ch2 out = out.reshape((2,2,2,2)) </code></pre> <p>Ou...
python|arrays|numpy|google-colaboratory|tiff
0
376,845
67,660,842
Dirac Delta function with Python
<p>I tried to plot the Dirac Delta rectangular function in Python 2.7 code such that:</p> <p><a href="https://i.stack.imgur.com/QALGy.png" rel="nofollow noreferrer">enter image description here</a></p> <pre><code>from __future__ import division import numpy as np import matplotlib.pyplot as plt def ddf(x,sig): if...
<p>As the error states, you cannot compare single number to an array. Here is a solution for it:</p> <pre><code>def ddf(x,sig): val = np.zeros_like(x) val[(-(1/(2*sig))&lt;=x) &amp; (x&lt;=(1/(2*sig)))] = 1 return val </code></pre> <p>output sample:</p> <p><a href="https://i.stack.imgur.com/5OklX.png" rel="...
python|python-2.7|numpy
3
376,846
68,010,466
Make a dataframe column with names of variables in the for loop
<p>I have an issue with my code. Below is the code snippet:</p> <pre><code>abc = [1, 2, 3, 4] def = [5, 6, 7, 8] for i in [abc, def]: df[str(i)] = i #This is giving an issue </code></pre> <p>I want to make abc and def (list) a column in my dataframe with column name as abc and def (Same as in for loop.</p> <p>Is ...
<p>You can't (easily) do that with your variable declaration. Maybe you can try:</p> <pre><code>cols = {'abc': [1, 2, 3, 4], 'def': [5, 6, 7, 8]} out = pd.concat([df, pd.DataFrame(cols)], axis=&quot;columns&quot;) </code></pre> <pre><code>&gt;&gt;&gt; out xyz abc def 0 A 1 5 1 B 2 6 2 C ...
python|python-3.x|pandas|list|dataframe
1
376,847
67,641,311
Pandas csv parser not working properly when it encounters `"`
<p>Problem statement:</p> <p>Initially what I had</p> <blockquote> <p>I have a CSV file with the below records:-</p> <p>data.csv:-</p> </blockquote> <blockquote> <pre><code> id,age,name 3500300026,23,&quot;rahul&quot; 3500300163,45,&quot;sunita&quot; 3500320786,12,&quot;patrick&quot; 3500321074,41,&quot;Viper&quot;...
<p>You can tell pandas that you don't want double quotes to be treated specially by adding an argument to read_csv:</p> <pre><code> test_data2=pd.read_csv('data.csv', quoting=csv.QUOTE_NONE) </code></pre> <p>to <code>read_csv()</code>. The output will be:</p> <pre><code>In [11]: df Out[11]: id age ...
python|pandas|character-encoding|csv-parser
1
376,848
67,939,673
Get the index corresponding to True boolen values only
<p>After doing some operations, I am getting a dataframe with an index and a column with boolean values. I just need to get those indexes having boolean value to be True. How can I get that? My output is like this: Here, &quot;AC name&quot; is the index as per the output dataframe.</p> <pre><code> AC name Agiaon ...
<p>Considering that the dataframe is <code>df</code>, it would be:</p> <pre class="lang-py prettyprint-override"><code>res = df[df['Vote percentage']].index </code></pre>
python|pandas|dataframe
1
376,849
67,861,486
Passing string into a lambda function
<p>I am trying to automatically generate lambda functions given a list of lists of strings to generate constraints for a <code>scipy.optimize.minimize()</code> routine. I have a <code>list</code> of string pairs, which I need to pass into each lambda function constraint, as so:</p> <pre class="lang-py prettyprint-over...
<p>See <a href="https://stackoverflow.com/questions/37791680/scipy-optimize-minimize-slsqp-with-linear-constraints-fails/37792650#37792650">this answer</a> to a similar question. In your case, the problem is the use of the name <code>pair</code> in the lambda expression. Because of Python's <a href="https://docs.pyth...
python|numpy|lambda|scipy
1
376,850
67,865,519
Comparing two dataframes with some entries missing
<p>I have two dataframes that I want to compare like:</p> <p>df1</p> <pre><code> name | value_1 | value_2 | value_3 0 | A | 2 | NaN | 2 1 | B | 3 | 1 | NaN 2 | C | 5 | 2 | 1 </code></pre> <p>df2</p> <pre><code> name | value_1 | value_2 | value_3 0 | A | NaN | ...
<p>As the error indicates, you can't assign a string value when there are mixed types in the data frame. One workaround is to convert the boolean result data frame to string before assigning <code>missing</code> labels:</p> <pre><code>df1.set_index('name', inplace=True) df2.set_index('name', inplace=True) df = (df1 ==...
python|pandas|dataframe
1
376,851
67,941,087
Create several dataframes with csv files and give them a specific name
<p>The following dataframe etf_list is given:</p> <pre><code>etf_list = pd.DataFrame({'ISIN': ['IE00B4X9L533', 'IE00B0M62Q58', 'LU0292097234', 'IE00BF4RFH31'], 'Name': ['HSBC MSCI WORLD UCITS ETF', 'iShares MSCI World UCITS ETF', 'FTSE 100 Income UCITS ETF 1D', 'iShares MSCI World Small Cap UCITS ETF'], ...
<p>You can <code>exec</code> to use strings as variable names.</p> <pre><code>for i, row in etf_list.iterrows(): if row['Anbieter']=='iShares': ISIN = row['ISIN'] file_name = 'ETF/'+ ISIN + '_' + timestr + '.csv' command_str = f&quot;{ISIN} = pd.read_csv('{file_name}', sep=',',skiprows=2, thousands='...
python|pandas|dataframe
0
376,852
67,650,358
Fill holes holes/area in a binary image using OpenCV
<p>I have below preprocessed rice image. I want to fill the rice with black color and then perform the inverse operation to find contours. I am trying to use Erosion/Dilation operation but not working. Below is the code snippet I am using.</p> <p>First I used shadow removal algorithm then used adaptive thresholding whi...
<p>You can create an HSV mask by using the <a href="https://docs.opencv.org/3.4/d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0aa4a7f0ecf2e94150699e48c79139ee12" rel="nofollow noreferrer"><code>cv2.COLOR_BGR2HSV</code></a> flag in the <a href="https://docs.opencv.org/3.4/d8/d01/group_...
python|numpy|opencv|image-processing|computer-vision
4
376,853
67,653,764
Multiple if conditions pandas
<p>Looking to write an if statement which does a calculation based on if 3 conditions across other columns in a dataframe are true. I have tried the below code which seems to have worked for others on stackoverflow but kicks up an error for me. Note the 'check', 'sqm' and 'sqft' columns are in float64 format.</p> <pre>...
<p>Each condition you code evaluates into a series of multiple boolean values. The combined result of the 3 conditions also become a boolean series. Python <code>if</code> statement cannot handle such Pandas series with evaluating each element in the series and feed to the statement following it one by one. Hence, t...
python|pandas|dataframe
1
376,854
31,709,651
Pandas opposite of fillna(0)
<p>Whereas <code>df.fillna(0)</code> fills all NA/NaN values with 0, is there a function to replace all <strong>non</strong>-NA/NaN values with another value, such as 1?</p> <p>If the values in my DataFrame are variable-length lists then:</p> <ul> <li><code>df.replace()</code> requires that the lists are the same len...
<p>You could use indexing/assignment with <code>df[df.notnull()] = 1</code>. For instance:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([[np.nan, 2, 5], [2, 5, np.nan], [2, 5, np.nan]]) &gt;&gt;&gt; df # example frame 0 1 2 0 NaN 2 5 1 2 5 NaN 2 2 5 NaN &gt;&gt;&gt; df[df.notnull()] = 1 &gt;&gt;&gt; ...
python|pandas|dataframe|nan
4
376,855
31,799,681
How to *extract* latitud and longitude greedily in Pandas?
<p>I have a dataframe in Pandas like this:</p> <pre><code> id loc 40 100005090 -38.229889,-72.326819 188 100020985 ut: -33.442101,-70.650327 249 10002732 ut: -33.437478,-70.614637 361 100039605 ut: 10.646041,-71.619039 \N 440 100048229 4.666439,-74.071554 </c...
<p>@HYRY's answer looks pretty good to me. This is just an alternate approach that uses built in pandas methods rather than a regex approach. I think it's a little simpler to read though I'm not sure if it will be sufficiently general for all your cases (it works fine on this sample data though).</p> <pre><code>df['...
python|regex|pandas
2
376,856
31,705,373
Minimize float format in Pandas df.to_csv()
<p>For large datasets, I would like to encode floats minimally when writing the CSV.</p> <pre><code>0.0 or 1.0 should be written 0 or 1 1.234567 should be written 1.235 123.0 should be written 123 </code></pre> <p><code>DataFrame.to_csv()</code> allows a float_format, but that makes every float look the same, which d...
<p>You could do something hacky like this:</p> <pre><code>def to_str(item): if type(item) in {np.int, np.float64}: return '{:g}'.format(item) else: return item pd.DataFrame({'int': [1, 2], 'float': [1.03, 1.0], 'str': ['a', 'b']}).applymap(to_str) </code></pre> <p>which returns</p> <pre><cod...
python-3.x|pandas
0
376,857
32,114,215
How to calculate the intercept using numpy.linalg.lstsq
<p>After running a multiple linear regression using <code>numpy.linalg.lstsq</code> I get 4 arrays as described in the documentation, however it is not clear to me how do I get the intercept value. Does anyone know this? I'm new to statistical analysis.</p> <p>Here is my model:</p> <pre><code>X1 = np.array(a) X2 = np...
<p>The intersect is the coefficient that corresponds to the column of <code>ones</code>, which in this case is:</p> <pre><code>result[0][6] </code></pre> <p>To make it clearer to see, consider your regression, which is something like:</p> <pre><code>y = c1*x1 + c2*x2 + c3*x3 + c4*x4 + m </code></pre> <p>written in ...
python|arrays|numpy|regression|linear-regression
4
376,858
31,929,645
How to set values of a masked Pandas Series from a different mask
<p>I have a series. I would like to extract some elements from that series using a mask and put them back to same or different locations in the same series using a different mask. Something like this:</p> <pre><code>s = pd.Series(randn(5)) s 0 0.466829 1 -1.821200 2 0.025857 3 0.238267 4 2.192390 dtype: ...
<p>When setting values on a Pandas series, the index is used to align values. So for you example, even though the number of values is the same, the indexes are different, hence the null values. If you want to override this behavior, you can use <code>values</code> to access the underlying array of the Series (ignoring ...
python|pandas
2
376,859
31,785,331
Pandas How to convert from series to a data frame
<p>suppose I have a simple Series like this data frame like this </p> <pre><code>S1 = Series([2.0, 0.816 , 0.2] , [51.0, 50.0 , 0.3]) </code></pre> <p>What us the best way in pandas to convert this Series to a data frame like this</p> <pre><code>pd.DataFrame({ 'mean' : [2.0 , 51.0] , 'median' : [0....
<h2>one method</h2> <p>You can do some index wizardry</p> <pre><code>D1 = S1.to_frame().reset_index().T </code></pre> <p>Now you can map the column names to whatever</p> <pre><code>D1.rename( columns={0:'mean',1:'median',2:'sd'}, inplace=True) # should match the list order in S1 D1.reset_index(drop=True,inplace=Tru...
python|pandas|series
4
376,860
31,701,732
Python (Pandas) updating previous x rows within specified condition
<p>I have data about machine failures. The data is in a pandas dataframe with <code>date</code>, <code>id</code>, <code>failure</code> and <code>previous_30_days</code> columns. The <code>previous_30_days</code> column is currently all zeros. My desired outcome is to populate rows in the <code>previous_30_days</code> c...
<p>I'm a little confused about how your code works (or is supposed to work), but this ought to point you in the right direction and can be easily adapted. It will be much faster by avoiding <code>iterrows</code> in favor of vectorized operations (about 7x faster for this small dataframe, it should be a much bigger imp...
python|pandas
1
376,861
32,126,454
Python 2.7 / Pandas: writing new string from each row in dataframe
<p>In Pandas, I have a dataframe, written from a csv. My end goal is to generate an XML schema from that CSV, because each of the items in the CSV correspond to a schema variable. The only solution (that I could think of) would be to read each item from that dataframe so that it generates a text file, with each value i...
<p>There is a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html" rel="nofollow"><code>to_dict()</code></a> method you may want to consider in this case:</p> <pre><code>In [178]: df.columns = ['table','name','type','value'] [["&lt;%s='%s'&gt;"%(k,v) for k,v in D.items()] for D...
python|python-2.7|pandas|dataframe
0
376,862
32,076,624
Equations containing outer products of vectors
<p><a href="https://i.stack.imgur.com/0XOlk.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0XOlk.gif" alt="enter image description here"></a></p> <p>where x is a column vector. We know from the diagonal elements in A, the value of x entries. But signs of them remains unknown. For example:</p> <pr...
<p>Note that (-x)(-x)^T = (x)(x)^T, so you can't distinguish x from -x. Given that, you can determine the sign pattern (i.e. you can determine whether two elements have the same or opposite signs). In fact, since each row of A is a scalar multiple of x, each row gives you the sign pattern (unless the row is all 0, wh...
python|c++|numpy|matrix|linear-algebra
5
376,863
32,137,320
Append with date_range() in Python
<p>I have a csv file which contains start dates and end dates, with format <code>dd/mm/yy</code>. These are read by :</p> <pre><code>dateparse = lambda x: pnd.datetime.strptime(x, '%d/%m/%y') df = pnd.read_csv('file.csv',sep=';',parse_dates=['StartDate','EndDate'], date_parser=dateparse) </code></pre> <p>A sample of ...
<p>You can chain the ranges together using <code>itertools.chain</code> to create your list of dates:</p> <pre><code>from itertools import chain new_df = pnd.DataFrame(list(chain.from_iterable(pnd.date_range(r["StartDate"],r["EndDate"]) for _,r in df.iterrows())), columns=("Date",)) </code></pre> <p>Output:...
python|date|pandas|append
3
376,864
31,952,560
python: bandpass filter of an image
<p>I have a data image with an imaging artifact that comes out as a sinusoidal background, which I want to remove. Since it is a single frequency sine wave, it seems natural to Fourier transform and either bandpass filter or "notch filter" (where I think I'd use a gaussian filter at +-omega). </p> <p><a href="https:/...
<p>So, one problem here is that your background sinusoid has a period not terribly different from the signal components you are trying to preserve. i.e., the spacing of the signal peaks is about the same as the period of the background. This is going to make filtering difficult.</p> <p>My first question is whether t...
python|numpy|image-processing|filter|convolution
2
376,865
31,975,139
Reshaping Pandas groupby data row values into column headers
<p>I am trying to extract grouped row data from a pandas groupby object so that the primary group data ('course' in the example below) act as a row index, the secondary grouped row values act as column headers ('student') and the aggregate values as the corresponding row data ('score').</p> <p>So, for example, I would...
<pre><code>&gt;&gt;&gt; g.reset_index().pivot('course_id', 'student_id', 'score') student_id 1 2 course_id 101 82.5 65.0 102 77.5 87.5 </code></pre>
python|pandas
10
376,866
31,975,205
Python/Numba: Unknown attribute error with scipy.special.gammainc()
<p>I am having an error when running code using the @jit decorator. It appears that some information for the function scipy.special.gammainc() can't be located:</p> <pre><code>Failed at nopython (nopython frontend) Unknown attribute 'gammainc' for Module(&lt;module 'scipy.special' from 'C:\home\Miniconda\lib\site-pack...
<p>The problem is that <code>gammainc</code> isn't one of the small list of functions that Numba inherently knows how to deal with (see <a href="http://numba.pydata.org/numba-doc/dev/reference/numpysupported.html" rel="noreferrer">http://numba.pydata.org/numba-doc/dev/reference/numpysupported.html</a>) - in fact none o...
python|numpy|scipy|anaconda|numba
7
376,867
31,901,506
Grouping in Pandas
<p>I want to group data in a dataframe I have oo the Column "Count" and by another column "State". I would like to output a list of list, each sub set list would just be the count for each state. </p> <p>example output: [[120,200], [40, 20, 40], ...]</p> <p>120 and 200 would be counts for let's say the State Californ...
<p>It is possible as a one-liner:</p> <pre><code>import pandas as pd df = pd.DataFrame.from_dict({"State": ["ny", "or", "ny", "nm"], "Counts": [100,300,200,400]}) list_new = df.groupby("State"...
python|pandas|group-by|dataframe
1
376,868
32,018,256
converting rows of a single dataFrame column into a single list in python
<p>I have a pandas Series and I would like to covert all the rows of my series into a single list. I have:</p> <pre><code>list1=Series([89.34,88.52,104.19,186.84,198.15,208.88]). Then I have a function which i call: func(list1) def func(list1): list1=list1.values.tolist() print(list1) </code></pre> <p>the print...
<p>Easiest way would be to access the <code>values</code> property of the <code>Series</code> object, like you have in your example.</p> <pre><code>&gt; from pandas import Series &gt; a_series = Series([89.34,88.52,104.19,186.84,198.15,208.88]) &gt; print(a_series.values.tolist()) [89.34, 88.52, 104.19, 186.84, 198.15...
python|pandas
1
376,869
41,656,162
Multi Column Deep Neural Network with TFLearn and Tensorflow
<p>I am trying to build a multi column deep neural network (MDNN) with tflearn and tensorflow. The MDNN is explained in <a href="http://people.idsia.ch/~juergen/nn2012traffic.pdf" rel="nofollow noreferrer">this paper</a>. The part I am struggling with is how I can add two or more inputs together to be fed to tensorflow...
<p>The MDNN explained in the paper individually trains several models using random (but bounded) distortions on the data. Once all models are trained, they produce predictions using an ensemble classifier by averaging the output of all the models on different versions of the data.</p> <p>As far as I understand, the co...
python|numpy|tensorflow|neural-network|tflearn
1
376,870
41,473,112
Replace column values in python
<p>This is hopefully an easy question for someone out there:</p> <p>I have one data frame that looks like this:</p> <pre><code>import pandas as pd names_raw = { 'device_id': [ '1d28d33a-c98e-4986-a7bb-5881d222c9a8','54322099-e76d-4986-afd2-0861e2113a16','ec3a9f9d-8e4d-4986-bea8-c17c361366e9','cc8e247d-4e2e-4986-b...
<p>Try this:</p> <pre><code>df['native_id'] = df.device_id.map(names.set_index('device_id')['native_id']) </code></pre> <p>Or if you don't want to preserve <code>device_id</code> column in the <code>df</code> DF:</p> <pre><code>In [210]: df['native_id'] = df.pop('device_id').map(names.set_index('device_id')['native_...
python|pandas|dataframe|multiple-columns
1
376,871
41,584,420
How to calculate the mean of a column by decade in Python
<p><a href="https://i.stack.imgur.com/WtHTj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WtHTj.png" alt="Image of dataset"></a></p> <p>I am unsure as to how to calculate the mean for a column given specific rows. I need to calculate the mean of the column Mkt-RF by decade, as in the mean from 193...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> by first <code>3</code> chars of first column by <code>str[:3]</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame....
python|pandas|rows|mean
0
376,872
41,244,988
Joining sentences to dataframe
<p>I want to export a dataframe to csv. But on top of it, I would like to print the date of the dataframe to produce the following result in the csv file. How can I join the string sentence to the dataframe so that I can export it together to csv?</p> <pre><code>import pandas as pd import datetime as dt today1=dt.dat...
<p><code>pd.to_csv</code> accepts a filehandle as input. So write your first line, then call <code>to_csv</code> with the same handle:</p> <pre><code>import pandas as pd import datetime as dt today1=dt.datetime.today().strftime('%Y%m%d') df=pd.DataFrame({'A':[1,2],'B':[3,4]}) with open("temp.csv","w") as f: f.wri...
python|pandas
1
376,873
41,288,989
Creating new (more detailed) data frame with Pandas based on index data frame
<p>I apologize for the neophyte question, but I'm having a hard time figuring out Pandas' data frames. I have one data frame with something like</p> <pre><code>df_index: Product Title 100000 Sample main product 200000 Non-consecutive main sample </code></pre> <p>I have another data frame with a more detail...
<p>You should be able to use <code>.isin()</code> as:</p> <pre><code>new_df = df_details[df_details['Product'].isin(df_index['Product']] </code></pre> <p>This will perform a mask looking up only the common indices.</p> <p>EDIT: this works only whether the column has the same string. To solve this you can use <code>s...
python|pandas|dataframe
2
376,874
41,345,289
Getting a random sample in Python dataframe by category
<p>I have a sample list like this: </p> <pre><code>Category| Item --------|------- Animal | Fish Animal | Cat ... | Food | Fish Food | Cake ... | etc... </code></pre> <p>I want to take a random sample of 10 items out of each category, so that the remaining dataframe just has those records. </p> <p>I'...
<p>You have to tell pandas you want to group by category with the <code>groupby</code> method.</p> <pre><code>df.groupby('category')['item'].apply(lambda s: s.sample(10)) </code></pre> <p>If you have less than ten items in a sample but don't want to sample with replacement you can do this.</p> <pre><code>df.groupby(...
python-3.x|pandas
16
376,875
41,590,993
create a new pandas dataframe by taking values from a different dataframe and perforing some mathematical operations on it
<p>Suppose I have a pandas dataframe with 16 columns and approx 1000 rows, the format is like this</p> <pre><code>date_time sec01 sec02 sec03 sec04 sec05 sec06 sec07 sec08 sec09 sec10 sec11 sec12 sec13 sec14 sec15 sec16 1970-01-01 05:54:17 8.50 8.62 8.53 8.45 8.50 8.62 ...
<p>Here's an approach with NumPy -</p> <pre><code># Extract as float array a = df.values # Extract all 16 columns m,n = a.shape # Scaling array s = np.radians(1.40625*(np.arange(79,47,-2))) # Initialize output array and set cosine and sine values out = np.zeros((m,n,2)) out[:,:,0] = a*np.cos(s) out[:,:,1] = a*np.sin...
python|pandas|dataframe
2
376,876
41,285,090
gen_word2vec in tensorflow is not found
<p>As I ran the code (<a href="https://github.com/tensorflow/models/blob/master/tutorials/embedding/word2vec.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/tutorials/embedding/word2vec.py</a>) in my laptop(Mac,python3), I received an error: </p> <pre><code> AttributeError: mod...
<p>Try installing the latest version of TensorFlow.</p>
machine-learning|tensorflow|word2vec
1
376,877
41,642,799
How to overlay data over a "day period" in Pandas for plotting
<p>I have a DataFrame with some (<em>more-sensical</em>) data in the following form:</p> <pre><code>In[67] df Out[67]: latency timestamp 2016-09-15 00:00:00.000000 0.042731 2016-09-15 00:16:24.376901 0.930874 2016-09-15 00:33:19.268295 0.425996 2016-09-15 00:...
<p>Consider the dataframe <code>df</code> (generated mostly from OP provided code)</p> <pre><code>import datetime import matplotlib.pyplot as plt import numpy as np import pandas as pd start_date = datetime.datetime(2016, 9, 15) end_date = datetime.datetime.now() dts = [] cur_date = start_date while cur_date &lt; ...
python|python-2.7|pandas|matplotlib|plot
8
376,878
41,298,791
Implementation of optical flow using CNN by tensorflow
<p>I want to implement <em>FlowNetCorr model</em> in Figure 2 on <a href="https://arxiv.org/abs/1504.06852" rel="nofollow noreferrer">https://arxiv.org/abs/1504.06852</a> , by Tensorflow.</p> <p>Although I know the basic implementation of LeNet or Alexnet, it is hard to write more complex models.</p> <p>I don't kno...
<p>You may consider using this op: <a href="https://www.tensorflow.org/api_guides/python/nn#Convolution" rel="nofollow noreferrer">https://www.tensorflow.org/api_guides/python/nn#Convolution</a></p>
tensorflow
1
376,879
41,328,633
How do I print entire number in Python from describe() function?
<p>I am doing some statistical work using Python's pandas and I am having the following code to print out the data description (mean, count, median, etc).</p> <pre><code>data=pandas.read_csv(input_file) print(data.describe()) </code></pre> <p>But my data is pretty big (around 4 million rows) and each rows has very sm...
<p>Suppose you have the following <code>DataFrame</code>:</p> <h2>Edit</h2> <p>I checked the docs and you should probably use the <code>pandas.set_option</code> API to do this:</p> <pre><code>In [13]: df Out[13]: a b c 0 4.405544e+08 1.425305e+08 6.387200e+08 1 8.792502e+08...
python|pandas
67
376,880
41,247,221
Can inception model be used for object counting in an image?
<p>I have already gone through the image classification part in Inception model, but I require to count the objects in the image. </p> <p>Considering the flowers data-set, one image can have multiple instances of a flower, so how can I get that count?</p>
<p>What you describe is known to research community as <strong>Instance-Level Segmentation</strong>. </p> <p>In last year itself there have been a significant spike in papers addressing this problem.</p> <p>Here are some of the papers:</p> <ul> <li><a href="https://arxiv.org/pdf/1412.7144v4.pdf" rel="noreferrer">htt...
image-processing|tensorflow|deep-learning
5
376,881
41,659,152
Python subscript syntax clarification
<p>Can you clarify what the <code>[:, :5]</code> part of the code does in the following code segment?</p> <pre><code>for i in range(5): weights = None test_inputs = testset[i][:, :5] test_inputs = test_inputs.astype(np.float32) test_answer = testset[i][:, :5] test_answer = code_...
<p>this is explained in the <a href="https://docs.scipy.org/doc/numpy/user/basics.indexing.html" rel="nofollow noreferrer">numpy indexing guide</a> of the manual. this is not standard python syntax.</p> <p>if you have an array <code>a</code>, <code>a[:]</code> returns a view (not a copy; assigning to this will change ...
python|arrays|numpy|syntax
0
376,882
41,416,740
Probability in pandas
<p>I have a simple dataframe like the one mentioned below. </p> <p>How to count the probability of the occurrence of one in <code>Column_1</code> according to the <code>Column_2</code> and <code>Column_3</code> ?</p> <p><code>Column_1</code> is a result (either one or zero).</p> <p><code>Column_2</code> <code>Column...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a>:</p> <pre><code>print (df.pivot_table(index='Column_2', columns='Column_3', values='Column_1', ...
python|pandas
1
376,883
41,661,798
Basic confusion about residuals in python
<p>I am writing some code for a class project that requires me to find the residuals of some data points and a fitted line to test its "fit" </p> <p>I have been given this code: </p> <pre><code>p, residuals, rank, singular_values, rcond = np.polyfit(temp,voltage,degree,full=True) </code></pre> <p>but the residuals i...
<p>Assume you have these data points:</p> <pre><code>np.random.seed(0) x = np.random.randn(10) y = 5*x + np.random.randn(10) </code></pre> <p>In your code, <code>p</code> gives you the coefficients of the fitted function:</p> <pre><code>p, residuals, rank, singular_values, rcond = np.polyfit(x, y, deg=1, full=True) ...
python|numpy
2
376,884
41,356,865
TensorFlow InvalidArgumentError: Matrix size-compatible: In[0]: [100,784], In[1]: [500,10]
<p>I'm new to tensorflow and am following a tutorial. I am getting an error that says: </p> <pre><code>InvalidArgumentError (see above for traceback): Matrix size-compatible: In[0]: [100,784], In[1]: [500,10] [[Node: MatMul_3 = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/repli...
<p>One error lies in this line</p> <pre><code> l2 = tf.add(tf.matmul(data, hidden_2_layer['weights']), hidden_2_layer['biases']) </code></pre> <p>Your second weights variable has dimensions <code>500 x 500</code>, but your <code>data</code> variable was fed with data <code>100x784</code> so multiplication is incompat...
python|tensorflow
6
376,885
41,368,940
Signal handler works in python but not in ipython
<p>I'm attempting to set the numpy print options using a signal handler on the window resize event. Don't want to make the connection until numpy has been imported, and don't want to import numpy automatically at python startup. I've got it almost-working with the code below:</p> <pre><code># example.py import wrapt...
<p>Inspired by <a href="https://stackoverflow.com/a/1988024/5067311">the standard fix for printing large arrays without truncation</a>, I tried setting the line width to infinity. This seems to be working fine both in the REPL and in ipython, so I suggest this workaround:</p> <pre><code>import numpy numpy.set_printopt...
python|numpy|ipython|window-resize
1
376,886
41,651,317
Reinstalling numpy on OS X using pip - "can’t be modified or deleted because it’s required by OS X"
<p>I'm trying to upgrade the <code>numpy</code> library on macOS, but <code>pip</code> doesn't seem to have sufficient permissions to delete numpy. Running `pip install --upgrade pip gives me this traceback:</p> <pre><code>➜ Desktop sudo -H pip install --upgrade numpy Collecting numpy Using cached numpy-1.11.3-cp27...
<p>Was facing the same issue</p> <p>sudo pip install --ignore-installed numpy</p>
python|macos|numpy|pip
15
376,887
41,407,241
Does TensorFlow execute entire computation graph with sess.run()?
<p>For example, when we compute a variable <code>c</code> as <code>result = sess.run(c)</code>, does TF only compute the inputs required for computing <code>c</code> or updates all the variables of the complete computational graph?</p> <p>Also, I don't seem to be able to do this: <code>c = c*a*b</code> as I am stuck w...
<p>Since Python code of TF only setups the graph, which is actually executed by native implementation of all <code>ops</code>, your variables need to be executed in this underlying environment. This happens by executing two ops - for local and global variables initialization:</p> <p><code> session.run(tf.global_variab...
python|machine-learning|tensorflow
0
376,888
41,322,379
Python - Verifying event based on values in dataframe
<p>I've got a dataframe for which I am trying to verify an event based on others values in the dataframe. To be more concrete it's about UFO sightings. I've already grouped the df by date of sighting and dropped all rows with only one unique entry. The next step would be to check when dates are equal whether the city ...
<p>I don't think I'm understanding your problem, but I'll post this answer and we can work from there.</p> <p>The <code>corroborations</code> column counts the number of times we have an observation with the same datetime and city/state combination. So in the example below, the 20th of December has three sightings, bu...
python|pandas|numpy
0
376,889
41,574,536
Running sums based on another column in Pandas
<p>I have a dataframe like the following:</p> <pre><code> col1 col2 0 1 True 1 3 True 2 3 True 3 1 False 4 2 True 5 3 True 6 2 False 7 2 True </code></pre> <p>I want to get a running sum of <code>True</code> values. Whenever I see a <code>False</code> value in <code>c...
<p>You can create a group variable with cumsum on <code>col2</code> and then calculate the sum per group:</p> <pre><code>df.loc[~df.col2, 'col3'] = (df.col1 * df.col2).groupby(by = (~df.col2).cumsum()).cumsum().shift() df.fillna(0) </code></pre> <p><a href="https://i.stack.imgur.com/t2c24.png" rel="nofollow noreferre...
python|pandas
3
376,890
41,241,782
How to implement Pandas GroupBy filter on mixed type data?
<p>Thanks for reading. Apologies for what I am sure is a simple problem to answer.</p> <p>I have some dataframe:</p> <pre><code>df: Entry Found 0 Dog [1,0] 1 Sheep [0,1] 2 Cow "No Match" 3 Goat "No Match" </code></pre> <p>I want to return a new dataframe which contains only entrie...
<p>Instead of using the <code>groupby</code> function, you can call the query such as:</p> <pre><code>df = df[df["Found"] == "No Match"] </code></pre> <p>Thus it will look for the column <code>Found</code> if there are <code>"No Match"</code>, which will be <code>False</code> when it is a list, instead of an error.</...
python|python-2.7|pandas|dataframe|group-by
3
376,891
41,318,471
Too slow for converting to tf.constant when list contains 1000000 elems
<p>What is the best way to do the training. That's too slow! And I don't know why it is that slow. </p> <pre><code>samples_all = tf.constant(samples_all)//more than 1000000 elems labels_all = tf.constant(labels_all) [sample, label] = tf.train.slice_input_producer([samples_all, labels_all]) </code></pre> <p>The sample...
<p>Below an example of loading 2M strings into string variable which takes less than 1 second on my MacBook. Variables are more efficient for large constants than <code>tf.constant</code> which are inlined in the graph. Note that there's also <code>tf.string_input_producer</code> which can handle large lists of strings...
tensorflow
0
376,892
27,451,885
Python Curve Fitting issue
<p>EDIT: First problem solved but I now have a new issue:</p> <p>I am currently doing a curve fit on some data to be input. My function is: </p> <pre><code>def extract_parameters(Ts, ts): def model(t, Ti, Ta, c): return (Ti - Ta)*math.e**(-t / c) + Ta popt, pcov = cf(model, ts, Ts, p0 = (10, 7, 6)) ...
<p>Your parameters to fit are <code>Ti</code>, <code>Ta</code> and <code>c</code>, so don't define <code>Ti</code> first:</p> <pre><code>from scipy.optimize import curve_fit def model(t, Ti, Ta, c): return (Ti - Ta) * np.exp(-t / c) + Ta Ti, Ta, c = 100, 25, 10 # super-low heat-capacity tea! t = np.linspace(0...
python|numpy
1
376,893
27,744,908
computing sum of pandas dataframes
<p>I have two dataframes that I want to add bin-wise. That is, given</p> <pre><code>dfc1 = pd.DataFrame(list(zip(range(10),np.zeros(10))), columns=['bin', 'count']) dfc2 = pd.DataFrame(list(zip(range(0,10,2), np.ones(5))), columns=['bin', 'count']) </code></pre> <p>which gives me this</p> <p>dfc1:</p> <pre><code> ...
<p>First set <code>bin</code> to be index in both dataframes, then you can use <code>add</code>, fillvalue is needed to point that zero shall be used if bin is missing in dataframe:</p> <pre><code>dfc1 = dfc1.set_index('bin') dfc2 = dfc2.set_index('bin') result = pd.DataFrame.add(dfc1, dfc2, fill_value=0) </code></pre...
python|python-3.x|pandas
1
376,894
27,673,654
Dataframe output difference compared to what's supposed to be in the textbook
<p>I have a dataframe,names, containing columns of name, sex births, year etc for "Python for Data Analysis" book. </p> <p>When I type <code>names</code>, it gives me below. </p> <pre><code> name sex births year prop 0 Mary F 7065 1880 0.077643 1 Anna F 2604 1880 0.028618 2 ...
<p>That's what modern <code>pandas</code> should be expected to show, so I don't think there's anything needing to be fixed. If you want something more like that representation, you can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.info.html" rel="nofollow"><code>df.info()</code>...
python|pandas
2
376,895
27,431,578
Analyzing a CSV file using Django Pandas and Pyplot
<p>So I am currently working on a Django web app that allows for users to upload CSV files, analyze those files, and then present a graph back to the client. The CSVs that will inputted are generated from Matlab and all describe the same general type of data, but the formatting of each file is different depending on ho...
<p>You can try to browse through the entire file with a regular <code>open</code> statement and parse your headers dynamically before using panda.</p> <p>For instance:</p> <pre><code>import re import panda as pd raw_data = open('your_file.csv', 'rb').read() rows = re.split('\n', raw_data) for idx, row in enumerate...
python|django|csv|matplotlib|pandas
3
376,896
27,557,406
array operation results differ between interactive and the program
<blockquote> <p>I compare two arrays interactively in iPython, the returns are correct: </p> <p>In[143]: r=np.array([0.,0.04166667, 0.08333333, 0.125, 0.16666667 , 0.20833333 , 0.25, 0.29166667 , 0.33333333 , 0.375, 0.41666667,0.45833333 , 0.5, 0.54166667, 0.58333333 , 0.625, 0.66666667 , 0.70833333 , 0.75, ...
<p>This is an issue with floating point precision; your first and second case are really <strong>not the same</strong>. The <a href="http://floating-point-gui.de/" rel="nofollow">Floating Point guide</a> is a useful resource here. </p> <p>In the first instance, you're populating two arrays from floating point literals...
python|arrays|numpy|operation
1
376,897
27,851,188
Python pandas: Identify Records Based on Multiple Criteria on Multiple Fields
<p>Using IPython (Python 3.4) with pandas: I have a data frame that looks roughly like this (notice the duplicate records per student, sometimes there are 3+ per student):</p> <pre><code>Year Subject Student Score Date 2014 Math 1 34 31-Jan 2014 Math 1 34 26-Jan 2014 ...
<p>If I'm following correctly, I think you can simplify this by sorting on both the score and the date, so that the last element of each group is always the most recent of the highest score. I might do something like</p> <pre><code>&gt;&gt;&gt; df["FullDate"] = pd.to_datetime(df["Year"].astype(str) + "-" + df["Date"]...
python|pandas|dataframe
1
376,898
27,807,272
Building Numpy with Intel Compilers and MKL - CentOS 7
<p>Currently I am attempting to build Numpy-1.9.1for Intel's MKL using the Intel compilers on CentOS 7. I have Intel Parallel XE Studio 2015 C++ and Fortran for Linux installed, and in my terminal I can use both 'icc' and 'ifort' command, they are both found without issue. I have also run:</p> <p><code>$ source /opt...
<p>On Unix/Linux systems, the <code>sudo</code> command (<b>S</b>uper<b>U</b>ser <b>DO</b>) is set up to use the environment variables defined for the <code>root</code> user, not the user running the command. This can lead to problems if you install a program in a non-standard location, then need to run it with superus...
python|linux|numpy|intel-mkl|centos7
1
376,899
27,582,056
How to split DataFrame using some constraint?
<p>Suppose, I have a DataFrame df. I want to split this DataFrame into new DataFrames such that salaries are always increasing </p> <pre><code>&gt;&gt;&gt; DATA = {'id':[1,2,3,4,5], 'salary':[1200,2300,2400,1200,2100] } &gt;&gt;&gt; df = DataFrame(DATA) &gt;&gt;&gt; df id salary 0 1 1200 1 2 2300 2 3 ...
<p>You could do something like</p> <pre><code>&gt;&gt;&gt; grouped = df.groupby((df.salary.diff() &lt;= 0).cumsum()) &gt;&gt;&gt; parts = [g.reset_index(drop=True) for k, g in grouped] &gt;&gt;&gt; for p in parts: ... print(p) ... id salary 0 1 1200 1 2 2300 2 3 2400 id salary 0 4 ...
python|pandas
4