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
375,800
62,610,336
Python: Implement a column with the day of the week based on the "Year", "Month", "Day" columns?
<p><a href="https://i.stack.imgur.com/psmTm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/psmTm.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/3LnpC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3LnpC.png" alt="enter image description h...
<p>You can do something like this:</p> <pre><code>from datetime import datetime def get_weekday(row): date_str = &quot;{}-{}-{}&quot;.format(row[&quot;Year&quot;], row[&quot;Month&quot;], row[&quot;Day&quot;]) date = datetime.strptime(date_str, '%Y-%m-%d') return date.weekday() df2019[&quot;weekday&quot;...
python|pandas|dataframe|date|weekday
3
375,801
62,658,750
missing values in pandas column multiindex
<p>I am reading with pandas excel sheets like this one:</p> <p><a href="https://i.stack.imgur.com/N5cAI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N5cAI.png" alt="enter image description here" /></a></p> <p>using</p> <pre><code>df = pd.read_excel('./question.xlsx', sheet_name = None, header = [0...
<p>Assuming that you want to have empty strings instead of repeating the first label, you can read the 2 lines and build the MultiIndex directly:</p> <pre><code>df1 = pd.read_excel('./question.xlsx', header = None, nrows=2).fillna('') index = pd.MultiIndex.from_arrays(df1.values) </code></pre> <p>it gives:</p> <pre><co...
python|excel|pandas|multi-index
1
375,802
62,502,285
Install geopandas in Pycharm
<p>Sorry if this is a repeat question, But I am new to Python and trying to install Geopandas in Pycharm. My python version is 3.7.2.</p> <ol> <li>I have tried the conventional way of installing library in pycharm through project interpretor.</li> <li>I have also tried <code>pip install geopandas </code></li> </ol> <p>...
<p>According to <a href="https://geopandas.org/install.html" rel="nofollow noreferrer">Geopandas's own install instructions</a>, the <em>recommended</em> way is to install via <a href="https://conda.io/en/latest/" rel="nofollow noreferrer">conda</a> package manager, which you can obtain by using the <a href="https://ww...
python-3.x|pycharm|gdal|geopandas|fiona
0
375,803
62,814,354
How to insert values ​into a column from another table?
<p>I have two datasets:</p> <p>First dataset:</p> <pre><code>Name ID Alla 3 Peter NaN Sara NaN Maria NaN </code></pre> <p>Second dataset:</p> <pre><code>Name_name ID_ID Alla 3 Peter 4 Sara 5 </code></pre> <p>I need to insert into the missing values ​​of the first table, the I...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a> for replace ...
pandas
1
375,804
62,646,249
Pandas boolean indexing: matching a set
<p>I am trying to figure out how to extract the entries in a Pandas dataframe where the values in one column match a given set. Here is an example:</p> <pre><code>num = 5 df = pd.DataFrame(np.zeros((num,3)),index = np.arange(num),columns = ['ID','color','shape']) df['color'] = ['red','red','blue','blue','yellow'] df['s...
<p>How about <code>isin</code>:</p> <pre><code>df[df.color.isin(colors)] </code></pre> <p>Output:</p> <pre><code> ID color shape 2 7 blue triangle 3 8 blue circle 4 9 yellow circle </code></pre>
python|pandas|indexing
2
375,805
62,894,793
Calculate the cosine distance between two column in Spark
<p>I am using a Python &amp; Spark to solve an issue. I have dataframe containing two columns in a Spark Dataframe Each of the columns contain a scalar of numeric(e.g. double or float) type.</p> <p>I want to interpret these two column as vector and calculate consine similarity between them. Sofar I only found spark li...
<p>You can see <a href="https://github.com/apache/spark/blob/master/examples/src/main/scala/org/apache/spark/examples/mllib/CosineSimilarity.scala" rel="nofollow noreferrer">here</a> a sample that calculates the cosine distance in Scala. The strategy is to represent the documents as a RowMatrix and then use its columnS...
python|numpy|apache-spark
1
375,806
62,872,493
What is the effect of image resize and configuration last dense layers on performance of transfer learning (VGG, ResNet) for classification
<p>I am trying to build a Spam classification model using the <code>tf2.0</code> and <code>Keras</code> for a project. It has to be very good model and I want to improve the accuracy of the model. Spam images can be any Image in the world except a handwritten question or a picture of a question like <a href="https://d...
<p>If you are creating a custom architecture, you can have any dimension as you wish. But for already built architecture, image dimension is fixed. In Keras, you can visit each model from <a href="https://keras.io/api/applications/#:%7E:text=Keras%20Applications%20are%20deep%20learning,They%20are%20stored%20at%20%7E%2F...
tensorflow|keras|deep-learning|neural-network|conv-neural-network
0
375,807
62,608,855
Python: Split String if delimiter is not available using str.split
<p>I am trying to split below data based on | delimiter.if only single value is available in response(no Delimiter), it should go to answers not in Question column of dataframe.</p> <p>Code:</p> <pre><code>answers_df[['Question','answers']] = answers_df.response.str.split(&quot;|&quot;,expand=True) </code></pre> <p>Dat...
<p>Here's a way to do it, the idea of to append <code>None</code> in the front:</p> <pre><code>df['ans2'] = df['ans'].str.split('|').apply(lambda x: [None] + x if len(x) &lt; 2 else x) df[['q1', 'a1']] = df['ans2'].apply(pd.Series) df = df.drop('ans2', axis=1) ans name rating 0 Assortments|5 A...
python|pandas
1
375,808
62,492,971
Split one column into multiple columns in Python
<p>I have a Python dataframe like this with one column:</p> <pre><code>index Train_station 0 Adenauerplatz 52° 29′ 59″ N, 13° 18′ 26″ O 1 Afrikanische Straße 52° 33′ 38″ N, 13° 20′ 3″ O 2 Alexanderplatz 52° 31′ 17″ N, 13° 24′ 48″ O </code></pre> <p>And I want to split it into 3 columns: Train station, ...
<pre><code>df = df.Train_station.str.split(r'(.*?)(\d+°[^,]+),(.*)', expand=True) print(df.loc[:, 1:3].rename(columns={1:'Train_station', 2:'Latitude', 3:'Longitude'}) ) </code></pre> <p>Prints:</p> <pre><code> Train_station Latitude Longitude 0 Adenauerplatz 52° 29′ 59″ N 13° 18′ 26″ O ...
python|pandas|dataframe
5
375,809
62,769,896
Assigning the value to the list from an array
<p>res is list has 1867 value divided into 11 sets with different sets of elements. <code>ex: res[0][:]=147,res[1][:]=174,res[2][:]=168</code> so on <code>total 11 set = 1867 elements</code>.</p> <p><code>altitude=[125,85,69,754,855,324,...]</code> has <code>1867 values</code>. I need to replace the res list values wit...
<p>You need to keep track of the number of elements assigned at each iteration to get the correct slice from <code>altitude</code>. If I understand correctly <code>res</code> is a list of lists with varying length. Here is a possible solution:</p> <pre><code>current_position = 0 for sublist in res: sub_len = len(su...
python-3.x|numpy
1
375,810
62,761,353
How to split dataframe made out of lists into different columns?
<p>I have the following dataframe. All the content in between the inverted commas are in one column. I want to split them into separate columns.:</p> <pre><code>df= 0,&quot;#1 Microwave Oven Sharp 20 Litres, White, R-20AS-W 5.0 out of 5 stars3SAR 199.00 &quot; 1,&quot;#2 Nikai Microwave - ...
<p>Use <code>.str.split</code> with are regex for two more more spaces and parameter <code>expand=True</code>:</p> <pre><code>df[column_name].str.split('\s\s+', expand=True) </code></pre>
python|pandas|dataframe|split
1
375,811
62,882,272
Converting column values to rows
<p>I have a dataset where all values in column <code>B</code> are the same. It looks like this:</p> <pre><code> A B 0 Marble Hill Pizza Place 1 Chinatown Pizza Place 2 Washington Pizza Place 3 Washington Pizza Place 4 Inwood Pizza Place 5 Inwood Pizza Pla...
<p>pandas's <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer">value_counts()</a> does exactly that. It returns a series with the number of occurrences of each value.</p> <p><code>new_df = df[&quot;A&quot;].value_counts()</code></p>
python|pandas|dataframe
2
375,812
62,563,249
Pandas filling nulls with grouby value
<p>I am trying to fill null values for all the numeric type columns in a dataframe.</p> <p>The code below goes through each numeric column and groups by a categorical feature and calculates the median of the target column.</p> <p>We then create a new column that copies over the values if it is present, but if it null, ...
<p>You wrote this : <code>df.loc[df[i].isna(),&quot;JOB&quot;]</code> which will return you a pandas Series, not a key as requested by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_loc.html" rel="nofollow noreferrer">pandas.Index.get_loc</a></p>
python|pandas
0
375,813
62,690,426
ValueError: Tensor conversion requested dtype float32_ref for Tensor with dtype float32
<p><strong>Embedding matrix:</strong></p> <pre><code> def create_embedding_matrix(filepath, word_index, embedding_dim): vocab_size = len(word_index) + 1 # Adding again 1 because of reserved 0 index embedding_matrix = np.zeros((vocab_size, embedding_dim)) with open(filepath) as ...
<p>It was a version mismatch issue. Solved by reinstalling both keras and tensorflow.</p>
python|pandas|numpy|tensorflow|keras
0
375,814
62,572,615
Get numeric part of string column and cast to integer
<p>The question is pretty simple actually, I just couldn't figure it out. There is a Fifa Dataset that I use, and I'd like to convert all <code>weight</code> column to integer. so: first I drop the <code>lbs</code>, then I convert to integer.</p> <pre><code>fifa[&quot;Weight&quot;].head() 0 159lbs ...
<pre><code>&gt;&gt;&gt; fifa Weight 0 159lbs 1 183lbs 2 150lbs 3 168lbs 4 154lbs fifa[&quot;Weight&quot;] = fifa[&quot;Weight&quot;].str.replace(&quot;lbs&quot;, &quot;&quot;) </code></pre> <p>and then</p> <pre><code>fifa[&quot;Weight&quot;] = fifa[&quot;Weight&quot;].astype(float) </code></pre> <p>If you hav...
python|pandas|numpy|dataframe|data-analysis
2
375,815
62,768,722
Kernel is dead and restarting automatically while running a cell for a training a regression model
<p>Iam doing the Bulldozer price calculation problem, using RandomForestRegressor.After removing all the missing values and converting all data into numeric, I try to fit and train the data into a model. The data set is pretty large about 412698 rows × 57 columns and using a 3gb Ram device.</p> <p>here is my code</p> <...
<p>You can use Batch processing when you have more data than your ram can handle. Sklearn is inbuilt with this feature you have to use the <code>warm_start</code> parameter in RandomForestRegressor</p> <p>warm_start, default=False When set to True, reuse the solution of the previous call to fit and add more estimators ...
python|pandas|scikit-learn|jupyter-notebook|regression
0
375,816
62,882,030
Python ImportError: from transformers import BertTokenizer, BertConfig
<p>I am trying to do named entity recognition in Python using BERT, and installed transformers v 3.0.2 from huggingface using <code>pip install transformers</code> . Then when I try to run this code:</p> <pre><code>import torch from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler fro...
<p>Try <code>pip install tokenizers==0.7.0</code></p>
python|python-import|importerror|huggingface-transformers|huggingface-tokenizers
0
375,817
62,882,132
Convert variable of dtype=<U14 to standard list
<p>I'm reading values from a csv using pandas and I've come across a format I've never seen before, to give an example:</p> <p>myval = array('[1.0, 0, 0, 0]', dtype='&lt;U14')</p> <p>I would like to convert myval into a list of integers/ floats, but nothing I try seems compatible with a variable of this datatype. Would...
<p>It is unicode 14 characters, you can try:</p> <pre><code>eval(myval) </code></pre>
python-3.x|pandas
1
375,818
62,490,885
filtering a numpy matrix using a dataframe column which is a boolean column
<p>I have a dataframe where one column is a booelan column, there are n rows in my dataframe. I am trying to use this column to filter a numpy matrix which is n by 30.</p> <blockquote> <p>filtered_matrix = my_matrix[df['my_bool_col'], :]</p> </blockquote> <p>The error I get is</p> <blockquote> <p>IndexError: boolean in...
<p>So the problem is that you want to index a dumpy matrix based on boolean values within a data frame. For this, you could do something like this:</p> <pre><code>filtered_matrix = my_matrix[np.where([df['my_bool_col'].astype(int) == 1), :] </code></pre> <p>Numpy's <code>np.where()</code> method (<a href="https://numpy...
python|pandas|numpy
0
375,819
62,671,542
Issue using BeautifulSoup and reading target URLs from a CSV
<p>Everything works as expected when I'm using a single URL for the URL variable to scrape, but not getting any results when attempting to read links from a csv. Any help is appreciated.</p> <p>Info about the CSV:</p> <ul> <li>One column with a header called &quot;Links&quot;</li> <li>300 rows of links with no space, c...
<p>The problem lies in this part of the code:</p> <pre class="lang-py prettyprint-override"><code>with open(&quot;urls.csv&quot;) as infile: reader = csv.DictReader(infile) for link in reader: res = requests.get(link['Links']) ... </code></pre> <p>After the loop is executed, <code>res</code> will have t...
python|pandas|beautifulsoup
0
375,820
62,885,651
Groupby and frequency count does not return the right value
<p>I am using this code to group companies and to a frequency count. However, the returned result did not group the companies</p> <pre><code>freq = df.groupby(['company'])['recruitment'].size() I got some result similar to this. recruitment company Data Co 3 Data Co 8 Apple Co ...
<p>If the company name look the 'same' then you have whitespace at front or end, I am adding the upper convert all to upper case as well.</p> <pre><code>freq = df.groupby(df['company'].str.strip().str.upper())['recruitment'].size() </code></pre>
python|pandas
0
375,821
62,720,500
How to calculate the difference between grouped row in pandas
<p>I have a dataset with the number of views per article.</p> <p><a href="https://i.stack.imgur.com/W6qFH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W6qFH.png" alt="enter image description here" /></a></p> <p>I'm trying to calculate the additional number of views per day, for each story, so I ca...
<p>Could you give this a shot?</p> <pre class="lang-py prettyprint-override"><code>cols = ['title', 'views'] storyviews = stats[cols].sort_values(by=cols) res = storyviews.set_index('title').groupby('title', sort=False).diff().dropna() </code></pre> <p>Output:</p> <pre><code> views tit...
python|pandas
2
375,822
62,520,199
Elementwise multiplication of pandas dataframe
<p>I know this question has been asked several times, but I tried all the anwers and still don't get the right result. I just want to do an element-wise multiplication of two pandas dataframes, but it always results in messing up the structure of the matrix:</p> <pre><code>x = pd.DataFrame([1,1,1],[2,2,2]) y= pd.DataFr...
<p>You should use: <code>print(x*y.values)</code> instead of <code>print(x*y)</code></p>
python|pandas
3
375,823
62,534,775
Remove rows from dataframe df1 if their columnS valueS exist in other dataframe df2
<p>I tried this :</p> <pre><code>res = df1[~(getattr(df1, 'A').isin(getattr(df2, 'A')) &amp; getattr(df1, 'C').isin(getattr(df2, 'C')))] </code></pre> <p>It works <strong>BUT</strong> the list of columns is variable in this example columns = ['A', 'C'] how can I loop over it to get the above expression dynamically acc...
<p>Use:</p> <pre><code>column_list = [&quot;A&quot;,&quot;C&quot;] df1[(~pd.concat((getattr(df1, col).isin(getattr(df2, col)) for col in column_list), axis=1 )).any(1)] </code></pre> <p>Output:</p> <pre><code> A B C D 1 bar one1 1 2 </code></pre> <p><strong>EDIT</strong></p> <p>The new situation you...
pandas|dataframe|duplicates|compare|multiple-columns
1
375,824
62,587,433
Filter df so values are equal across groups - pandas
<p>I've got a pandas <code>df</code> that contains values at various time points. I perform a groupby of these time points and values. I'm hoping the filter the output so both groups contain values at each time point. If either group does not contain a value at that time point I want to drop that row.</p> <p>Using the ...
<p>If you don't care about which row you drop, you could pick the first n rows in each group where n is the smallest number of rows in any group:</p> <pre><code>df1.groupby('Group').head(df1.groupby('Group')['Val_A'].count().min()) </code></pre> <p>Or, if you only want rows with a value of 'Time' in each group, you cou...
python|pandas
2
375,825
62,472,764
Can't import tensorflow when run script from terminal, even though tensorflow works in jupyter notebook and terminal
<p>TLDR: When I write a small script named toy_model.py and attempt to run it from the command line with</p> <pre><code>py toy_model.py </code></pre> <p>I get an error message complaining about loading tensorflow.</p> <p>However, I am able to use import and use tensorflow in many other settings without any problem, suc...
<p>It sounds like, by invoking <code>python</code>, you are not getting the specific python installation that has tensorflow (or tensorflow in that installation is broken). By default, invoking <code>python</code> will give you the system default (it's the first one in the environment path, so that's the first hit).</p...
python|tensorflow|python-import|importerror|dllimport
2
375,826
62,694,594
How to group dates by month in python
<p>I know I could group if I have object with special key that presents data. But I have some data as index that looks like this</p> <p>This is the index</p> <pre><code>DatetimeIndex(['2000-01-03', '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-10', '2000-01-11', '2000-01-12', ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.idxmax.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.idxmax</code></a> with convert years with months to month periods and select rows by <a href="http://pandas.pydata.org/pandas-docs/stable/reference...
python|pandas|pandas-datareader
1
375,827
62,510,402
How to add multiple data in single Row Column using pandas
<p>I've one DataFrame which is having two column called Brand and con.</p> <pre><code>import pandas as pd cars = {'Brand': ['Honda Civic','Toyota Corolla'], 'Con': [['India','Srilanka'],['India']] } df = pd.DataFrame(cars, columns = ['Brand', 'Con']) print (df) </code></pre> <p>which is giving me</p>...
<p>Use:</p> <pre><code>df.explode('Con').groupby('Con')['Brand'].agg(list).reset_index().reindex(df.columns, axis=1) </code></pre> <p>EDIT:</p> <pre><code>cars = {'Brand': ['Honda Civic','Toyota Corolla'], 'Con': [['India','Srilanka'],['India']] } df = pd.DataFrame(cars, columns = ['Brand', 'Con']) pr...
python|pandas|python-2.7
2
375,828
62,513,777
Pandas: merge dataframes without creating new columns inside a for operation
<p>I'm trying to enrich a dataframe with data collected from an API. So, I'm going like this:</p> <pre><code>for i in df.index: if pd.isnull(df.cnpj[i]) == True: pass else: k=get_financials_hnwi(df.cnpj[i]) # this is my API requesting function, working fine df=df.merge(k,on=[&quot;cnpj&q...
<p>as your joining on a single column and mapping values we can take advantage of the <code>cnpj</code> column and set it to the index, we can then use <code>combine_first</code> or <code>update</code> or <code>map</code> to add your values into your dataframe.</p> <p>assuming <code>k</code> will look like this. If not...
python|pandas|dataframe
1
375,829
62,819,596
Increasing Training/Validation Accuracy for Breast Mammography
<p>I've been training CNN model for binary classification task in order to classify Breast Mammography image patches to Normal and Abnormal. Here is my training plot:</p> <p><a href="https://i.stack.imgur.com/CF8wj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CF8wj.png" alt="enter image descriptio...
<p>Taking a look at the graph, it is mostly possible that the model is performing to its best considering the size of the dataset. Although the performance is not so bad, I would give the following suggestions:</p> <ol> <li>Try a pre-trained model. The pre-trained model mostly works better in small and big datasets. Yo...
tensorflow|machine-learning|keras|deep-learning|conv-neural-network
1
375,830
62,742,948
Comparing elements in two numpy arrays results in a memory address
<p>I'm comparing the individual elements in two numpy arrays. The array elements are integers. I'm using the 'equal_arrays' function to do the comparision but it results in giving me the memory address of the result object:</p> <p>Here is the code:</p> <pre><code> act = actual_direction pre = predicted_directio...
<p>Based on what i understand, you need a way to get an array with True or False values, for each corresponding element from the two matrixes, given they have the same shape? (What I am trying to do is get a comparison for each individual element of the arrays.)</p> <p>If so you can try something to this:</p> <pre><cod...
python-3.x|numpy
2
375,831
62,767,073
Python Update only 1 column from another dataframe on index value
<p>I have 2 dataframes df1 &amp; df2. The df2 dataframes is a subset of df1 I extracted to do some cleaning. Both dataframes can be matched on index. I seen a lot of merges on the site. I don't want to add more columns to df1 and the dataframes are not the same size df1 has 1000 rows and df2 has 275 rows so i don't wan...
<p>Assuming all the indexed in <code>df2</code> exist in <code>df1</code> (which I understand is the case) - the below will suffice:</p> <pre class="lang-py prettyprint-override"><code>df1.loc[df2.index,:]=df2 </code></pre> <p>In case if the above assumption for <code>index</code> won't hold - this is the alternative (...
python|pandas|dataframe
1
375,832
62,839,330
Join or Merge dataframes with different multi-indexes
<p>Apologies in advance for duplicate question, but I have yet to find a solution that works from previous questions.</p> <p>I am unable to join two data-frames with different MultiIndexes. I want to keep all the columns from both data-frames.</p> <p>Given that df1 has ~300k rows and df2 has ~50k rows the join would be...
<p>Well I figured it out. I'm not sure if this is the best way but I just reset the indexes of both data frames and merged on the columns. See code below.</p> <pre><code>df1.reset_index() df2.reset_index() df3 = df1.merge(df2, on=['cust_id', 'path_id']) </code></pre> <p>I then reassigned the indexes afterwards. If ther...
python|pandas|dataframe|multi-index
1
375,833
62,774,428
Slicing Not NaN values in python
<p>I am python newbie and would appreciate some help! I have a dataframe called result in the below format:</p> <pre><code>start end rf1 rf2 rf3 01-01-2008 10-01-2008 nan 12 nan 02-01-2008 11-01-2008 nan 16 nan 03-01-2008 12-01-2008 32 18 18 </code></pre> <p>I want a list of those rfs in each ro...
<p>IIUC you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> having filtered on the <code>rfX</code> columns, <code>groupby</code> the index and build a list from the resulting groups:</p> <pre><code>df.filter(regex...
python|pandas|numpy|slice|nan
4
375,834
62,725,842
Correlation between continuous independent variable and binary class dependent variable
<p>Can someone please tell <strong>if it's correct</strong> to find <code>correlation</code> between a dependent variable that has <code>binary class(0 or 1)</code> and independent variables that have continuous values using pandas <code>df.corr()</code>.</p> <p>I am getting correlation output if I do use it. But <stro...
<p>pearson correlation is for continues data if one is categorical and other is binary, you should use ANOVA to see the relation between variables <a href="https://www.quora.com/How-can-I-measure-the-correlation-between-continuous-and-categorical-variables" rel="nofollow noreferrer">refrence</a></p>
pandas|statistics|correlation
0
375,835
62,815,087
How to get multidimentional array slices in C#, numpy style?
<p>I have</p> <pre><code>int[,,,] arr = new int[5, 6, 7, 8]; // c# arr = np.zeros((5, 6, 7, 8)) # Python </code></pre> <p>A 4d array, with <code>5 * 6 * 7 * 8</code> cells.</p> <p>I want to slice it in c# like in numpy</p> <pre><code>var mySlice = arr[2:4, 0, :2, :]; // Won't work in C#, but looking for a way to do thi...
<p>As far as I know there is no way to do this in c#. Other than writing your own Multidimensional array class.</p> <p>C# 8 introduces ranges and array slicing. But this uses <code>Span&lt;T&gt;</code> to return a slice without needing to copy any values. Multi-dimensional arrays are stored in continuous memory, so a p...
python|c#|arrays|numpy|slice
0
375,836
62,791,055
Delete Column in CSV when element is certain value
<p>I am parsing a large amount of data so I need to delete a column in CSV. I would like to delete a column if it contains 0 and 32800.</p> <p>There is no header too.</p> <p><a href="https://i.stack.imgur.com/sGV6J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sGV6J.png" alt="enter image descriptio...
<p>To delete a column with a specific value, you can try doing this:</p> <pre><code>data.loc[:, ~(data == 0).any()] </code></pre> <p>or this</p> <pre><code>data.drop(columns=data.columns[(data == 0).any()]) </code></pre> <ul> <li><code>(data == 0)</code> alone gives you a dataframe with booleans (whether 0 appears in d...
pandas|dataframe
2
375,837
62,533,013
Why is slope not a good measure of trends for data?
<p>Following the advice of <a href="https://www.emilkhatib.com/analyzing-trends-in-data-with-pandas/" rel="nofollow noreferrer">this post</a> on Analyzing trends in data with pandas, I have used numpy's <code>polyfit</code> on several data I have. However it does not permit me to see when there is a trend and when ther...
<p>The idea is that you compare whether the linear fit shows a significant increase compared to the fluctuation of the data around the fit:</p> <p><a href="https://i.stack.imgur.com/CAMC9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CAMC9.png" alt="Linear fit example" /></a></p> <p>In the bottom p...
python|pandas|numpy|data-analysis
0
375,838
62,527,534
get indices of numpy multidimensional arrays
<pre><code>arr = np.array([[[1,2],[3,4]],[[5,6],[7,8]]]) </code></pre> <p>I'm trying to get the indices of <code>arr</code> when <code>arr==1</code>.</p> <p>I thought this would work but it doesn't give the expected output:</p> <pre><code>&gt;&gt;&gt; np.where(arr==1) (array([0], dtype=int64), array([0], dtype=int64...
<p>If you change arr:</p> <pre><code>arr = np.array([[[1,2],[3,4]],[[1,1],[7,8]]]) </code></pre> <p>and you will get</p> <pre><code>np.where(arr==1) # (array([0, 1, 1]), array([0, 0, 0]), array([0, 0, 1])) </code></pre> <p>it is mean:</p> <pre><code>arr[0][0][0] == 1 arr[1][0][0] == 1 arr[1][0][1] == 1 </code></pre> <p...
python|numpy
1
375,839
62,590,761
An error occured while installing flair and pytorch with pipenv in windows with Pycharm
<p>I am having problems installing the python packages <code>flair</code> and <code>pytorch</code> via <code>pipenv</code> and have not been able to resolve this issue yet. Since I am trying to version my python git repository with <code>Pipfile + Pipfile.lock</code> instead of <code>requirements.txt</code> this is cur...
<p>Try to cleanup the Pipfile and the virtual environment first. It looks like the transitive dependencies and the ones declared in the Pipfile clash.</p> <p>Then try to install torchvision like this:</p> <pre><code>pipenv install torchvision </code></pre> <p>This will install the latest torchvision version and the co...
python|pytorch|pipenv|pipfile|flair
0
375,840
62,735,038
How to identify from a list of list which are the coordinates (x,y) that appear and plasm it into a data frame
<p>I have a list of lists with different coordinates of different images. I want to create a data frame with two columns: coordinates and value being value how many times we can find this pixel (this value has to be 0 if it's not found in the whole list or a concrete number if we can find it x times). What I have done ...
<p>You can use <code>Counter</code> to get all the unique pixels that have a count not equal to 0, then in order to add pixels that also have a count of 0, you can loop through all pixels (0,0)... (max_x, max_y) and compare their count to the Counter object.</p> <pre><code>import numpy as np import pandas as pd from co...
python|python-3.x|pandas|dataframe|coordinates
1
375,841
62,821,289
Python - MemoryError: Unable to allocate for an array with type int64
<p>I'm trying to create a numpy matrix:</p> <pre><code>matrix = np.zeros((242993, 9000000, 13), dtype=int) </code></pre> <p>But I am getting MemoryError:</p> <pre><code>MemoryError: Unable to allocate 207. TiB for an array with shape (242993, 9000000, 13) and data type int64 </code></pre> <p><strong>EDIT: I'm running o...
<p><code>matrix = np.zeros((242993, 9000000, 13), dtype=int)</code> requires 242993x9000000x13x32(bit/int) bits which is essentially 9.1e14 bits or in order of hundreds of Tera bytes. Even if you use dtype of bits this still won't fit into your memory. Depending on your application, you might store it differently or br...
python|python-3.x|numpy|numpy-ndarray
0
375,842
62,760,099
Groupby calculation for only one part of dataframe - Pandas
<p>I am trying to make some calculations using two dataframes and a groupby code. However, I am not able to find the way to make these calculations only when my variable &quot;date_int&quot; is larger or equal than an specific number (e.g., 20180501; equivalent to date &quot;2018-05-01&quot;).</p> <p>In other words the...
<p><strong>Explanation</strong>:</p> <p>The updated code below uses a different approach. Rather than remove data from the <code>DataFrame</code> after it is created, it does not use that data at all. This is done by a <code>mask_it()</code> function. This function can be used to create a <code>boolean</code> <code>mas...
python|pandas|dataframe|pandas-groupby
0
375,843
54,629,100
resample multiple columns with pandas
<p>I want to resample daily stock data into monthly stock data.</p> <pre><code>data = yf.download(['AAPL', 'TSLA', 'FB'], '2018-01-01', '2019-01-01')['Close'] for column in data: data[column].resample('M').last() print(data[column]) print(data) </code></pre> <p>My data:</p> <pre><code> AAP...
<p>You can't resample individual columns and assign it to the same DataFrame variable. You can just apply the resample call to the entire DataFrame:</p> <pre><code>data = yf.download(['AAPL', 'TSLA', 'FB'], '2018-01-01', '2019-01-01')['Close'] data_resampled = data.resample('M').last() print(data) </code></pre>
python|pandas
2
375,844
54,292,672
Pands: Creating dataframe based on keywords from dictionary
<p>I have a dictionary where key is model name and values are keywords. I want to filter every row in a column that string contains one of the keywords that are in the values of dictionary. Matching should be case insensitive. </p> <p>Dictionary looks like this:</p> <pre><code>{'J7 2017': [' J730F', 'amoled'], 'J5 20...
<p>Use dict comprehension with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>str.contains</code></a> and filtering by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boo...
python|pandas|data-science
0
375,845
54,602,610
Simplest way to index within a dimension
<p>I have two tensors <code>x</code> and <code>y</code> that have equal <code>shape</code> in the first <code>k</code> dimensions. The second tensor contains indices to retrieve values from the first along to the last dimension. For a <code>rank</code> of 3, then the output <code>z</code> should be such that <code>z[i_...
<p>Found it! <code>tf.batch_gather</code> and <code>tf.batch_scatter</code>.</p>
python|tensorflow
3
375,846
54,471,306
Gradients and Quiver plots
<pre><code>from scipy import * import matplotlib.pyplot as plt def plot_elines(x_grid, y_grid, potential, field): fig, ax = plt.subplots(figsize=(13, 13)) im_cs = ax.contour(x_grid, y_grid, potential, 18, cmap='inferno') plt.clabel(im_cs, inline=1, fontsize=7) ax.quiver(x_grid[::3, ::3], y_grid[::3, :...
<p>The fact that the transpose gives you the correct plot is by pure coincidence, because the charge is possitionned symmetrical in x and y (i.e. on the 45° line). </p> <p>The real problem comes from the wrong interpretation of <code>numpy.gradient</code>. It will return the gradient axis-wise. The first array for the...
python|numpy|matplotlib
1
375,847
54,595,264
How to best save model and write summary during hyper-parameter tuning?
<p>What is the best approach to save model and write session for each run, during hyperparameter tuning? Currently I have a bunch of models and summaries saved under 'training' and 'validation' directories, and I dunno which is generated from which hyperparameters. It is also hard to identify which model generated the ...
<p>I haven't used any of the tools you mentioned but here's how I implemented the logging of hyperparameters and results.</p> <p>Just create a <code>pandas DataDrame</code> or even a basic dictionary with the hyperparameter names and values. To the same data structure, add the performance metrics obtained using those ...
tensorflow|machine-learning|deep-learning
1
375,848
54,306,002
Groupby by two differents options simultaneously
<p>Good morning.</p> <p>I've a pandas dataframe like the following:</p> <pre><code>df = p f c a 0 1 2 1 16.32 1 1 2 2 48 2 1 2 3 60 3 1 2 4 112 4 1 2 5 52 5 1 3 6 288 6 1 4 7 201 7 1 4 8 52 8 1 4 4 44 9 1 5 7 ...
<p>You need aggregate <code>list</code> and <code>sum</code> first, then call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer"><code>DataFrame.cumsum</code></a>:</p> <pre><code>df = df.groupby('f').agg({'c':list, 'a':'sum'}).cumsum() print (df) ...
python|pandas
1
375,849
54,653,036
assigning multiple values to different cells in a dataframe
<p>This is probably an easy question, but I couldn't find any simple way to do that. Imagine the following dataframe:</p> <pre><code>df = pd.DataFrame(index=range(10), columns=range(5)) </code></pre> <p>and three lists that contain indices, columns, and values of the defined dataframe that I intend to change:</p> <p...
<p>Using <code>.values</code></p> <pre><code>df.values[idx_list,col_list]=value_list df Out[205]: 0 1 2 3 4 0 NaN NaN NaN NaN NaN 1 NaN 9 NaN NaN NaN 2 NaN NaN NaN NaN NaN 3 NaN NaN NaN 7 NaN 4 NaN NaN NaN NaN NaN 5 NaN NaN NaN NaN 8 6 NaN NaN NaN NaN NaN 7 N...
python|pandas|dataframe
1
375,850
54,322,621
Pivot a two-column dataframe
<p><strong>Question</strong></p> <p>I have a dataframe <code>untidy</code></p> <pre><code> attribute value 0 age 49 1 sex M 2 height 176 3 age 27 4 sex F 5 height 172 </code></pre> <p>where the values in the <code>'attribute'</code> column repeat periodically. The des...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot.html" rel="nofollow noreferrer"><code>pandas.pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for ...
python|pandas
3
375,851
54,669,337
Pandas Dataframe: difference between all dates for each unique id
<pre><code>[In 621]: df = pd.DataFrame({'id':[44,44,44,88,88,90,95], 'Status': ['Reject','Submit','Draft','Accept','Submit', 'Submit','Draft'], 'Datetime': ['2018-11-24 08:56:02', '2018-10-24 18:12:02','2018-10-24 08:12:02...
<p>Exactly you are right, first is necessary sorting <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a> with both columns:</p> <pre><code>df = df.sort_values(['id', 'Datetime']) df['Time in Status'] = df.gro...
python|pandas|datetime|dataframe|group-by
2
375,852
54,416,773
How to balance unbalanced data in PyTorch with WeightedRandomSampler?
<p>I have a 2-class problem and my data is unbalanced. class 0 has 232550 samples and class 1 has 13498 samples. PyTorch docs and the internet tells me to use the class WeightedRandomSampler for my DataLoader. </p> <p>I have tried using the WeightedRandomSampler but I keep getting errors.</p> <pre><code> trainrat...
<p>So apparently this is an internal warning, not an error. According to the guys at PyTorch, I can continue coding and not stress about the warning message. </p>
python|machine-learning|pytorch
0
375,853
54,691,288
How can I integrate tensorboard visualization to tf.Estimator?
<p>I have classical TensorFlow code for recognizing handwritten digits <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_with_...
<p>Generally, You just need to specify <code>tf.summary.scalar()</code>, <code>tf.summary.histogram()</code> or <code>tf.summary.image()</code> anywhere in the code. You can use histogram summary in the following way to capture all weights and biases</p> <pre><code>for value in tf.get_collection(tf.GraphKeys.TRAINABLE...
python|tensorflow|conv-neural-network|tensorboard
1
375,854
54,465,153
Using the values of the first row of a matrix as ticks for matplotlib.pyplot.imshow
<p>I have a file like this:</p> <pre><code>820.5 815.3 810.4 2061 2082 2098 2094 2119 2071 2067 2079 2080 2095 2080 2116 2069 2103 2108 </code></pre> <p>and I'm using the following code to open it and plot my data</p> <pre><code>import numpy as np import matplotlib.pyplot as plt im...
<p>If I understood correctly, the issue here is the large number of x-axis ticks. In that case, to have a readable solution, one way is to put the ticks at every <code>n</code>th step. You can additionally choose to rotate them or not as a matter of personal taste. To do so, you can do like following. </p> <p>I just e...
python|python-3.x|numpy|matplotlib|imshow
3
375,855
54,451,746
How to properly use pandas vectorization?
<p>According to <a href="https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6" rel="nofollow noreferrer">an article</a>, the <code>vectorization</code> is much faster than <code>apply</code> a function to a pandas dafaframe column.</p> <p>But I had a somehow special case li...
<p>Check with <code>str</code> in <code>pandas</code></p> <pre><code>df.IP.str.split('.').str[2].astype(int)&gt;100 0 False 1 True 2 False Name: IP, dtype: bool </code></pre> <p>Since you mention <code>vectorize</code></p> <pre><code>import numpy as np np.vectorize(compare3rd)(df.IP.values) array([False, ...
python|pandas|loops|vectorization|apply
1
375,856
54,551,316
Keras extending embedding layer input
<p>A keras sequential model with embedding needs to be retrained starting from the currently known weights.</p> <p>A Keras sequential model is trained on the provided (text) training data. The training data is tokenized by a (custom made) tokenizer. The input dimension for the first layer in the model, a embedding lay...
<p>You can access (get and set) the layer's weights directly as numpy arrays with code like <code>weights = model.layers[0].get_weights()</code> and <code>model.layers[0].set_weighs(weights</code>, where <code>model.layers[0]</code> is your Embedding layer. This way you can store embeddings separately and set known emb...
python|tensorflow|keras|word-embedding
2
375,857
54,426,404
Bokeh DataTable - Return row and column on selection callback
<p>Using an on_change callback, I can get the numerical row index of a selection within a DataTable, in Bokeh. Is it possible to: a) Get the column index b) Get the values of the indexes (column and row headers)</p> <p>Example code:</p> <pre><code>from bokeh.io import curdoc from bokeh.layouts import row, column imp...
<p>The following code uses JS callback to show the row and column index as well as the cell contents. The second Python callback is a trick to reset the indices so that a click on the same row can be detected (tested with Bokeh v1.0.4). Run with <code>bokeh serve --show app.py</code></p> <pre><code>from random import ...
python|pandas|datatable|bokeh
2
375,858
54,688,502
neural network does not learn (loss stays the same)
<p>My project partner and I are currently facing a problem in our latest university project. Our mission is to implement a neural network that plays the game Pong. We are giving the ball position the ball speed and the position of the paddles to our network and have three outputs: UP DOWN DO_NOTHING. After a player has...
<p>That's evil <code>'relu'</code> showing its power. </p> <p>Relu has a "zero" region without gradients. When all your outputs get negative, Relu makes all of them equal to zero and kills backpropagation.</p> <p>The easiest solution for using Relus safely is to add <code>BatchNormalization</code> layers before them:...
python|tensorflow|keras|neural-network|reinforcement-learning
5
375,859
54,285,889
Add new key in dicts in a list whose value is the index
<pre><code>df.at[0, 'A'] = [{'score': 12, 'player': [{'name': 'Jacob', 'score': 2}, {'name': 'Shane', 'score': 5}, ...]}, {'score': 33, 'player': [{'name': 'Cindy', 'score': 4}, ...]}, ...] </code></pre> <p>Say I have a list of n dictionaries for column 'A' in...
<p>Given your data structure, Barmar is probably right that you're stuck with a <code>for</code> loop (which there's nothing wrong with, by-the-by). Here's a couple of potential work-arounds.</p> <h1>A "solution"</h1> <p>The information you're trying to record is redundant, so you probably don't need to bother with i...
python|pandas
2
375,860
54,474,225
Parenthesis on .upper() and .apply(str.upper)
<p>Why do <code>upper</code> in <code>df.apply(df.str.upper)</code> doesn't require a parenthesis, but <code>upper()</code> method requires them as in <code>df.str.upper()</code>?</p> <p>Is there some concept I've miss?</p>
<p>The <code>()</code> means "call this function now".</p> <pre><code>print(str.upper()) </code></pre> <p>Referring to a function without the <code>()</code> does not call the function immediately.</p> <pre><code>map(str.upper) </code></pre> <p>The <code>str.upper</code> function is passed to the <code>map</code> f...
python|pandas
4
375,861
54,508,620
Trying to remove the first row in python fails?
<p>Hi I have some data in csv format.</p> <p>I have some very simple code that is just meant to remove the first row:</p> <pre><code>import numpy as np import pandas as pd data = pd.read_csv("mydata.csv") data = data.drop(data.columns[[0]],axis=0) data.to_csv("mydata2.csv") </code></pre> <p>However when run, I recei...
<p>For future reference, pandas <code>read_csv</code> accept <code>skiprows</code> to help achieve exatly that task, as covered extensively <a href="https://stackoverflow.com/questions/20637439/skip-rows-during-csv-import-pandas">here</a></p>
python|pandas|numpy
1
375,862
54,331,864
Python iterrows() to index and drop rows from Dataframe
<p>I'm iterating over a df and want to drop rows based on a condition. It's like to check the contents of a sting for a character and drop if it does not exist. I have tried the code below, with exceptions. How can I access the third column's iterative row value and check for contains.</p> <pre><code>for index, row in...
<p>Might be quicker to do.</p> <pre><code>df_new = df_new[~df_new.Column_name.str.contains(",")] </code></pre>
python|pandas|dataframe
3
375,863
54,316,919
How to take out a row of a matrix that contains a maximum in each column?
<p>I have a matrix of data with 3 columns : x , y , z : each with lots of rows.</p> <p>I need to find the row that contains the maximum each time for each column and also the same thing for minimums then write all these rows to a dataframe.</p> <p>let's say I have :</p> <pre><code>x= [1,2,4,3] , y= [7,8,6,5] , z= [1...
<p>I am solving this using <code>pandas</code> since you tagged the question with the same. Also, I couldn't match the output you have given. I hope it is a typo. But I have gone by the description you have given ie;<code>xmax,y,z,x2,ymax,z2,x3,y3,zmax,xmin,y4,z4,.....</code></p> <pre><code>df = pd.DataFrame(list(zip(...
python|pandas|numpy|dataframe
1
375,864
54,506,149
INSERT INTO Access database from pandas DataFrame
<p>Please could somebody tell me how should look like insert into the database but of the all data frame in python?</p> <p>I found this but don't know how to insert all data frame called test_data with two figures: ID, Employee_id. </p> <p>I also don't know how to insert the next value for ID (something like nextval)...
<p>Update, June 2020:</p> <p>Now that the <a href="https://pypi.org/project/sqlalchemy-access/" rel="nofollow noreferrer">sqlalchemy-access</a> dialect has been revived the best solution would be to use pandas' <code>to_sql</code> method.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pand...
python|pandas|ms-access|insert|pyodbc
5
375,865
54,556,604
pandas.interval_range for partial interval
<p>I'm using <code>pd.interval_range</code> to generate hourly intervals within a pair of timestamps:</p> <pre><code>In [1]: list(pd.interval_range(pd.Timestamp('2019-02-06 07:00:00'), pd.Timestamp('2019-02-06 08:00:00'), freq='h')) Out[1]: [Interval('2019-02-06 07:00:00', '2019-02-06 0...
<p>Try:</p> <pre><code>start = pd.Timestamp('2019-02-06 07:00:00') end = pd.Timestamp('2019-02-06 09:01:00') interval_1 = pd.interval_range(start, end, freq='h') interval_out = pd.IntervalIndex.from_arrays(interval_1.left.to_series().tolist() +[interval_1.right[-1]], ...
python|pandas
2
375,866
54,671,353
Convert categorical data into dummy set
<p>I'm having data like this:-</p> <pre><code>|--------|---------| | Col1 | Col2 | |--------|---------| | X | a,b,c | |--------|---------| | Y | a,b | |--------|---------| | X | b,d | |--------|---------| </code></pre> <p>I want to convert these categorical data to dummy variables. Since...
<p>I'm almost positive that you're encountering memory issues because <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html#pandas.Series.str.get_dummies" rel="nofollow noreferrer">str.get_dummies</a> returns an array full of 1s and 0s, of datatype <code>np.int64</code>....
python|pandas|scikit-learn|dummy-variable
2
375,867
54,311,923
How to save month-wise mails and aslo divide mails based on time using gmail api and save the output to csv or convert it into df?
<p>This code below gets us the messages count for every 30 days from the time period of message sent.</p> <p><strong>This code gets us:(In-detail)</strong></p> <p>1.Amazon first mail to my mail with a particular phase(here first order).</p> <p>2.Convert that epoch format into time date and using timedelta And gettin...
<p>You will just need to loop through the dates with the interval you want.</p> <p>The code below retrieves the messages of a user from a particular period of time, such as the month messages count.</p> <p>You will need help to automate it to retrieve messages count for every 30 days.</p> <p>For example, this code g...
python|python-3.x|pandas|gmail|gmail-api
2
375,868
54,270,971
The initial state or constants of an RNN layer cannot be specified with a mix of Keras tensors and non-Keras tensors
<p>As we know the decoder takes the encoder hidden states as the initial state ...</p> <pre><code>encoder_output , state_h, state_c = LSTM(cellsize, return_state=True)(embedded_encoder_input) encoder_states = [state_h, state_c] decoder_lstm = LSTM(cellsize, return_state=True, return_sequences=True) decoder_outputs,...
<p>I guess you mixed tensorflow tensor and keras tensor. Although the results of <code>state_h</code> and <code>my_state</code> are tensor, they are actually different. You can use <code>K.is_keras_tensor()</code> to distinguish them. An example:</p> <pre><code>import tensorflow as tf import keras.backend as K from ke...
tensorflow|keras|lstm|encoder-decoder
2
375,869
54,381,559
Pandas Dataframe: to_dict() poor performance
<p>I work with apis that return large pandas dataframes. I'm not aware of a fast way to iterate through the dataframe directly so I cast to a dictionary with <code>to_dict()</code>.</p> <p>After my data is in dictionary form, the performance is fine. However, the <code>to_dict()</code> operation tends to be a performa...
<p>The common guidance is don't iterate, use functions on all rows columns, or grouped rows/columns. Below, in the third code block shows how to iterate over the numpy array whhich is the <code>.values</code> attribute. The results are:</p> <p>Pivot Construction takes: 0.012315988540649414</p> <p>Dataframe iteration ...
python|pandas|dataframe|pivot-table|vectorization
6
375,870
54,294,577
Fast inner product of two 2-d masked arrays in numpy
<p>My problem is the following. I have two arrays <code>X</code> and <code>Y</code> of shape n, p where <strong>p >> n</strong> (e.g. n = 50, p = 10000).</p> <p>I also have a mask <code>mask</code> (1-d array of booleans of size <code>p</code>) with respect to <code>p</code>, of <strong>small</strong> density (e.g. <c...
<p>We can use <code>matrix-multiplication</code> with and without the masked versions as the masked subtraction from the full version yields to us the desired output -</p> <pre><code>inner = X.dot(Y.T)-X[:,mask].dot(Y[:,mask].T) </code></pre> <p>Or simply use the reversed mask, would be slower though for a sparsey <c...
python|numpy
2
375,871
54,586,159
I´m trying to filter data of colums from a Data Frame, but the index names contain white spaces
<p>I`m trying to filter the rows of a Data Frame, but since the index name of the column has white spaces, I've not been able to do it</p> <p>The DDTS Number is the name of the column </p> <p>It worked when there is no spaces</p> <p>data[data3.(DDTS Number) != null]</p> <p>I've tried different syntax but I don't if...
<p>Hi everyone I found the solution. The problem with the method I used was it did not work when the index had spaces in the name so there is another way to get rid of the null values using the following structure:</p> <p>df1 = df[df["ColumnName With Spaces"].notnull()]</p> <p>From here you will filter all the rows i...
python|pandas|filter|row|spaces
0
375,872
54,393,236
Scrape a table iterating over pages of a website: how to define the last page?
<p>I have the following code that works OK:</p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd df_list = [] for i in range(1, 13): url = 'https://www.uzse.uz/trade_results?date=25.01.2019&amp;mkt_id=ALL&amp;page=%d' %i df_list.append(pd.read_html(url)[0]) df = pd.concat(df_list)...
<p>Try with </p> <pre><code>for i in range(1, 100): url = 'https://www.uzse.uz/trade_results?date=25.01.2019&amp;mkt_id=ALL&amp;page=%d' %i if pd.read_html(url)[0].empty: break else : df_list.append(pd.read_html(url)[0]) </code></pre> <hr> <pre><code>page=0 # using whi...
python|python-3.x|pandas|for-loop|web-scraping
2
375,873
54,665,137
How to give a batch of frames to the model in pytorch c++ api?
<p>I've written a code to load the pytorch model in C++ with help of the PyTorch C++ Frontend api. I want to give a batch of frames to a pretrained model in the C++ by using <code>module-&gt;forward(batch_frames)</code>. But it can forward through a single input. <br/> How can I give a batch of inputs to the model?</p>...
<p>You can create a batch of tensors in libtorch using a variety of ways.<br /> Here is one of these ways:<br /> Using Torch::TensorList:<br /> Since <code>torch::TensorList</code> is <code>ArrayRef</code>, you can not directly add any tensors to it, therefore first create a vector of tensors and then create your <code...
c++|pytorch|torch
2
375,874
54,683,598
Pandas not working in python3 but works in python
<p>I tried to run pandas in <code>python3</code>. But I get the following error.</p> <pre><code>user@client3:~/smith/Python$ python3 Python 3.7.0 (default, Oct 3 2018, 21:22:25) [GCC 5.5.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pandas as pd Traceback (mos...
<p>This should work, check it out.</p> <pre><code>pip3 install pandas </code></pre>
python|python-3.x|pandas
1
375,875
54,661,667
Tensorflow seems to be using system memory not GPU, and the Program stops after global_variable_inititializer()
<p>I just got a new GTX 1070 Founders Addition for my desktop, and I am trying to run tensorflow on this new GPU. I am using tensorflow.device() to run tensorflow on my GPU, but it seems like this is not happening. Instead it is using cpu, and almost all of my systems 8GB of ram. Here is my code:</p> <pre><code>import...
<p>Try compare time (GPU vs CPU) with this simple example:</p> <pre><code>import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 def create_model(): model = tf.keras.models.Sequential([ tf.keras.layer...
python|python-3.x|tensorflow|anaconda
1
375,876
54,661,057
Python multidimensional array indexing explanation
<p>Could someone please explain to me what is happening here? I understand what is happening here: <a href="https://docs.scipy.org/doc/numpy-1.15.0/user/basics.indexing.html#index-arrays" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.15.0/user/basics.indexing.html#index-arrays</a>, but do not understand ...
<pre><code>import numpy as np # Line 01 y = np.zeros((3,3)) # Line 02 y = y.astype(np.int16) # Line 03 y[1,1] = 1 # Line 04 x = np.ones((3,3)) # Line 05 t = (1-y).astype(np.int16) # Line 06 print(t) # Line 07 print(x[t]) ...
python|numpy|multidimensional-array|indexing|numpy-ndarray
3
375,877
54,358,239
Faster method to multiply column lookup values with vectorization
<p>I have two Dataframes, one contains values and is the working dataset (postsolutionDF), while the other is simply for reference as a lookup table (factorimportpcntDF). The goal is to add a column to postsolutionDF that contains the product of the lookup values from each row of postsolutionDF (new column name = num_p...
<p>I'm not sure how to do this in native pandas, but if you go back to numpy, it is pretty easy.</p> <p>The <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html" rel="nofollow noreferrer">numpy.interp</a> function is designed to interpolate between values in the lookup table, but if the inpu...
python|pandas|numpy|dataframe
0
375,878
54,613,854
Merge dataframes by left join SQL & Pandas
<p>I made two tables into a MySQL database using Python. The following SQL code is to perform join on two tables in the database. How can I do the same by writing equivalent python code?</p> <p>MySQL code:</p> <pre><code>SELECT A.num, B.co_name, A.rep_name FROM A JOIN B ON A.num=B.no </code></pre> <p>Desired Pytho...
<p>I managed to resolve by enclosing my query with appropriate apostrophes: </p> <pre><code>sql = '''SELECT A.num, B.co_name, A.rep_name FROM A LEFT JOIN B ON A.num=B.no ''' df_merged = pd.read_sql(sql, con=cnx) </code></pre>
python|mysql|sql|pandas|merge
1
375,879
54,445,893
conda list returning run-time error Path not Found after installing PyTortch
<p>Recently I tried to install Pytrotch using the command<br> <code>conda install pytorch torchvision cuda100 -c pytorch</code></p> <p>To verity the package installed correctly I ran <code>conda list</code> in the anaconda prompt and got the following error:</p> <p><code>RuntimeError: Path not found: C:\Users\[na...
<p>AS @P.Antoniadis said, this is an ongoing issue. And removing 'Sphinx-1.5.6-py3.6.egg' folder is the suggested workaround.</p> <p><a href="https://github.com/conda/conda/issues/8156#issuecomment-458777849" rel="nofollow noreferrer">https://github.com/conda/conda/issues/8156#issuecomment-458777849</a></p>
python|anaconda|conda|pytorch
1
375,880
54,583,860
Mask last three bits in a numpy array
<p>I have a numpy 2D array with the following unique values:</p> <pre><code>[ 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 128 129 131 132 133 134 135 136 137 138 139 140 141 142 143 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 255] </code></pre> <p>I want to mask those values i...
<p>Assuming that by:</p> <blockquote> <p>mask those values in the numpy 2D array, where <strong>ANY</strong> of the last 3 bits of the value are 1</p> </blockquote> <p>you mean &quot;<strong>select</strong> those elements in which any of the three least significant bits are nonzero&quot;, you could do:</p> <pre><code>m...
python|numpy
1
375,881
73,825,623
Stream data using tf.data from cloud object store other than Google Storage possible?
<p>I've found <a href="https://www.tensorflow.org/datasets/gcs" rel="nofollow noreferrer">this</a> nice article on how to directly stream data from Google Storage to tf.data. This is super handy if your compute tier has limited storage (like on KNative in my case) and network bandwidth is sufficient (and free of charge...
<p>I'm not sure how this is implemented in the library, but it should be possible to access other object store systems in a similar way.</p> <p>You might need to extend the current mechanism to use a more generic API like the S3 API (most object stores have this as a compatibility layer). If you do need to do this, I'd...
tensorflow|kubernetes|serverless|knative
0
375,882
73,711,194
oracle sql query and export excel and send email not shown persian and shown as question mark pandas python
<p>oracle sql query and export excel and send email not shown persian and shown as question marks</p> <pre><code> connection = cx_Oracle.connect(user_db,password_db,dsn_tns) df = pd.read_sql(query,con=connection) attach_file_name = filename+'_'+timestr+'.xlsx' df.to_excel(attach_file_name,sheet_name=&quot;report...
<p>it is solved by reading query by encoding utf-8 from cx_orcale and change the engine of excel writer to xlswriter and set encoding</p> <pre><code>con = cx_Oracle.connect(user_db,password_db,dsn_tns,encoding=&quot;UTF-8&quot;) df = pd.read_sql(indict.datasources.Query, con=con) df.to_excel(attach_file_name, sheet_nam...
python|pandas|cx-oracle|smtplib
1
375,883
73,573,453
Extract a new dataframe
<p>I have the following data set :</p> <p><img src="https://i.stack.imgur.com/ZUP7q.png" alt="enter image description here" /></p> <p>and I want to extract a new dataframe of the following form :</p> <p><img src="https://i.stack.imgur.com/UnY3h.png" alt="enter image description here" /></p> <p>I tried this code but I g...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df.pivot(index='Country', columns='Year', values='Life expectancy').reset_index() </code></pre>
python|pandas|dataframe
0
375,884
73,687,094
Networkx: create weighted graph from pandas
<p>I am trying to create a weighted graph in <code>networkx</code>, but am facing problems when indicating the weight. My code</p> <pre><code>import pandas as pd import networkx as nx dictt = {&quot;from&quot; :[&quot;A&quot;, &quot;B&quot;, &quot;C&quot;], &quot;to&quot;:[&quot;B&quot;, &quot;D&quot;, &quot;A&quot;],}...
<p>Was using the wrong <code>networkx</code> function, here the correct code:</p> <pre><code>dictt = { &quot;from&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;], &quot;to&quot;: [&quot;B&quot;, &quot;D&quot;, &quot;A&quot;]} distmat = pd.DataFrame.from_dict(dictt) distmat[&quot;weight&quot;] = [1, 2, 4] d = distm...
python|pandas|networkx
0
375,885
73,532,344
ImportError: cannot import name 'notf' from 'tensorboard.compat'
<p><strong>i am training stylegan2-ada-pytorch from google colab with my custom images however on trying to perform the initial training i get the above error from tensorboard</strong></p> <pre><code>cmd = f&quot;/usr/bin/python3 /content/stylegan2-ada-pytorch/train.py --snap {SNAP} --outdir {EXPERIMENTS} --data {DATA}...
<p>solved it by uninstalling jax and reinstalling the cuda version of iy</p> <pre><code>!pip uninstall jax jaxlib -y !pip install &quot;jax[cuda11_cudnn805]==0.3.10&quot; -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html </code></pre> <p>And then changed the torch version to 1.8.1</p>
pytorch|tensorboard|stylegan
0
375,886
73,698,975
How to export dataframe from google collaboration as .h5?
<p>I'm trying to export dataframe in <code>.h5</code> format from Google Colab, the package I'm using to do downstream analysis reads in that format so would like it to export in that specific file format.</p> <p>I know to export it into csv file format you do:</p> <pre><code>from google.colab import drive drive.mount(...
<p>You need to use <code>to_hdf</code> method:</p> <pre><code>from google.colab import drive drive.mount('drive') adata.to_hdf('adata.h5', key='adata') !cp adata.h5 &quot;drive/My Drive/&quot; </code></pre>
python|pandas|dataframe|google-colaboratory
2
375,887
73,585,169
How can I make broadly applicable code that fills missing elements differently according to the variable type?
<p>I am supposed to fill missing values of a lot of CSV files. Normally, those have almost the same variables.</p> <p>Here are the conditions that I should satisfy.</p> <ol> <li>If the value type is numeric I should fill -1 to the missing value.</li> <li>If the value type is character I should fill m to the missing val...
<p>From the description you posted, this function might help:</p> <pre><code>def filldefault(series): series.fillna('m' if type(series.iloc[0]) == str else -1, inplace = True) </code></pre> <p>Perhaps you can iterate something like that over the columns in your dataframe.</p>
python|pandas|fillna
1
375,888
73,609,732
Loading resnet50 prettrianed model in PyTorch
<p>I want to use resnet50 pretrained model using PyTorch and I am using the following code for loading it:</p> <pre><code> import torch model = torch.hub.load(&quot;pytorch/vision&quot;, &quot;resnet50&quot;, weights=&quot;IMAGENET1K_V2&quot;) </code></pre> <p>Although I upgrade the torchvision but I receive the...
<p>As per the latest definition, we now load models using torchvision library, you can try that using:</p> <pre class="lang-py prettyprint-override"><code>from torchvision.models import resnet50, ResNet50_Weights # Old weights with accuracy 76.130% model1 = resnet50(weights=ResNet50_Weights.IMAGENET1K_V1) # New weigh...
python|deep-learning|pytorch
1
375,889
73,652,452
Python dataframe returning closest value above specified input in one row (pivot_table)
<p>I have the following DataFrame, <code>output_excel</code>, containing inventory data and sales data for different products. See the DataFrame below:</p> <pre><code> Product 2022-04-01 2022-05-01 2022-06-01 2022-07-01 2022-08-01 2022-09-01 AvgMonthlySales Current Inventory 1 BE37908 1500 1400 ...
<p>You could try as follows:</p> <pre><code># create list with columns with dates cols = [col for col in df.columns if col.startswith('20')] # select cols, apply df.gt row-wise, sum and subtract 1 idx = df.loc[:,cols].gt(df2['Security Stock'], axis=0).sum(axis=1).sub(1) # get the correct dates from the cols # if the ...
python|pandas|dataframe|pivot-table|np.argsort
1
375,890
73,579,932
How to change monthly table into one column with date index?
<p>I downloaded the Broad Dollar Index from FRED with the following format:</p> <pre><code> DATE RTWEXBGS 0 2006-01-01 100.0000 1 2006-02-01 100.2651 2 2006-03-01 100.5424 3 2006-04-01 100.0540 4 2006-05-01 97.8681 .. ... ... 194 2022-03-01 111.2659 195 2022-04-01 111....
<p>Something like this(didn't take column=<code>Annual</code> into account),</p> <pre><code>df ### Year Jan Feb Mar Apr May Jun Jul Aug \ 0 2022 0.07480 0.07871 0.08542 0.08259 0.08582 0.09060 0.08525 NaN 1 2021 0.01400 0.01676 0.02620 0.04160 0.04993 0.05391 ...
pandas|dataframe
1
375,891
73,602,436
Using a Knowledge Distillation model to run predictions and check classification metrics
<p>I am running the Keras example on knowledge distillation from the <a href="https://keras.io/examples/vision/knowledge_distillation/" rel="nofollow noreferrer">keras example</a> and my question is: The resulting compressed model that I can use to do predictions is the distiller or the student model? And in such case,...
<p>The &quot;compressed&quot; model is the student model. The <code>Distiller</code> is just the wrapper for training the student to try and mimic the teacher, as opposed to training the student to try and estimate the ground-truth labels.<br /> The page you linked has a section comparing the distillation results to t...
python|tensorflow|machine-learning|keras
0
375,892
73,733,427
Pandas: Cosine similarity for each rows
<p>I have dataframe:</p> <pre><code>import pandas as pd data = [['apple', 'one', 0.0, [0.047668457, -0.04888916]], ['banana', 'two', 0.0 , [0.0287323, -0.037841797] ], ['qiwi', 'three', 0.0, [0.031051636, -0.05227661]], ['orange', 'one', 1.0, [0.0020618439, -0.055389404]], ['mango', 'two', 1.0, [0.0030326843, -...
<p>You can use <code>cdist</code> from <code>scipy.spatial.distance</code>:</p> <pre><code>from scipy.spatial.distance import cdist vecs = df['vec'].to_list() pd.DataFrame(1 - cdist(vecs, vecs, metric='cosine'), index=df['word'], columns=df['word']) </code></pre> <p>Output:</p> <pre><code>word ...
python|pandas|cosine-similarity
2
375,893
73,524,464
Converting the comma separated values in a cell to different rows by duplicating the other column contents into every row Python
<p>I have a dataset</p> <pre><code>Name Type Cluster Value ABC AA,BB AZ,YZ 15 LMN CC,DD,EE LM,LM,LM 20 </code></pre> <p>with many other columns.</p> <p>I want to convert it to a dataframe like:</p> <pre><code>Name Type Cluster Value TypeSubset ClusterSubset...
<p><code>assign</code> new columns and <code>explode</code> in parallel.</p> <pre><code>(df.assign(TypeSubset=df['Type'].str.split(','), ClusterSubset=df['Cluster'].str.split(',') ) .explode(['TypeSubset', 'ClusterSubset']) ) </code></pre>
python-3.x|pandas|dataframe|data-preprocessing
1
375,894
73,608,058
Python: Iterate over values in a series and replace with dictionary values when key matches series value
<p>I'm trying to iterate over a column in a dataframe and when the value matches a key from my dictionary it should then replace the value in another column with the value of the matching key.</p> <pre><code> df = pd.DataFrame({'id': ['123', '456', '789'], 'Full': ['Yes', 'No', 'Yes'], 'Cat':['','','']}) cats = ...
<p>For filtered values in column use <code>dict.get</code>:</p> <pre><code>mask = df.Full == 'Yes' df.loc[mask, 'Cat'] = df.loc[mask, 'id'].apply(lambda x: cats.get(x, '')) print (df) id Full Cat 0 123 Yes A 1 456 No 2 789 Yes C </code></pre> <p>If no match in dict is possible create <code>None</code...
python|pandas|dictionary
1
375,895
73,557,055
Exponents in python: df**x vs df.pow(x)
<p>Just out of curiosity, what is the difference between <code>df**x</code> and <code>df.pow(x)</code>?</p> <p>Having a dataframe <code>df</code> with a column named <code>values</code> you can either do: <code>df.values ** 2</code> or <code>df.values.pow(2)</code> to compute the entire column to the power of 2. I unde...
<p>From the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pow.html" rel="nofollow noreferrer">pandas docs</a>:</p> <blockquote> <p>Equivalent to dataframe ** other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rpow.</p> </blockquote> <...
python|pandas
1
375,896
73,760,714
Converting Python code to pyspark environment
<p>How can I have the same functions as shift() and cumsum() from pandas in pyspark?</p> <pre><code>import pandas as pd temp = pd.DataFrame(data=[['a',0],['a',0],['a',0],['b',0],['b',1],['b',1],['c',1],['c',0],['c',0]], columns=['ID','X']) temp['transformed'] = temp.groupby('ID').apply(lambda x: (x[&quot;X&quot;].shi...
<p>Pyspark have handle these type of queries with Windows utility functions. you can read its documentation <a href="https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.Window.html" rel="nofollow noreferrer">here</a></p> <p>Your pyspark code would be something like this :</p> <pre><cod...
pandas|pyspark|group-by|shift|cumsum
1
375,897
73,797,165
Same numpy version [Colab and Raspberry pi]:: BUT 'ImportError: numpy.core.multiarray failed to import'
<p>I'm trying to use the trained multiclass classification model (model trained and saved from colab) into Raspberry pi 4.</p> <p>In colab:</p> <pre><code>import sys print(sys.version) </code></pre> <p>prints <code>3.7.14 (default, Sep 8 2022, 00:06:44) [GCC 7.5.0]</code>. Similarly,</p> <pre><code>import tensorflow ...
<p>I solved it by saving my classification model into <code>TensorflowLite</code> as <a href="https://www.tensorflow.org/lite/models/convert/convert_models" rel="nofollow noreferrer">follows</a>:</p> <pre><code># Convert the model. converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.con...
python|numpy|google-colaboratory|tensorflow2.0|raspberry-pi4
0
375,898
73,529,481
numpy-based spatial reduction
<p>I'm looking for a flexible fast method for computing a custom reduction on an np.array using a square non-overlapping window. e.g.,</p> <pre><code>array([[4, 7, 2, 0], [4, 9, 4, 2], [2, 8, 8, 8], [6, 3, 5, 8]]) </code></pre> <p>let's say I want the <code>np.max</code>, (on a 2x2 window in this c...
<p>With the max (or other function supporting axis), you can just reshape the array:</p> <pre><code>a.reshape(a.shape[0]//2, 2, a.shape[1]//2, 2).max(axis=(1,3)) </code></pre> <p>In general, you can reshape, swap the axis, flatten the 2x2 into a new axis <code>4</code>, then work on that axis.</p>
python|numpy|scipy|rasterio
3
375,899
73,547,066
Python Pandas: Going through a list of cycles and making point of interest
<p>To explain my problem easier I have created a dataset:</p> <pre><code>data = {'Cycle': ['Set1', 'Set1', 'Set1', 'Set2', 'Set2', 'Set2', 'Set2'], 'Value': [1, 2.2, .5, .2,1,2.5,1]} </code></pre> <p>I want to create a loop that goes through the &quot;Cycle&quot; column and marks the max of each cycle with the ...
<p>Using <code>numpy.select</code> and <code>groupby.transform</code>:</p> <pre><code>g = df.groupby('Cycle')['Value'] df['POI'] = np.select([df['Value'].eq(g.transform('max')), df['Value'].eq(g.transform('min'))], ['A', 'B']) # if you want 0 as default value (not '0') df['...
python|pandas|max
4