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
6,500
64,474,626
How to load data in tensorflow from subdirectories
<p>I have a subset of ImageNet data contained in sub-folders locally, where each sub-folder represents a class of images. There are potentially hundreds of classes, and therefore sub-folders, and each subfolder can contain hundreds of images. Here is an example of this structure with a subset of folders. I want to trai...
<p>You can use <code>tf.keras.preprocessing.image_dataset_from_directory()</code>.</p> <p>Your directory structure would be something like this but with many more classes:</p> <pre><code>main_directory/ ...class_a/ ......a_image_1.jpg ......a_image_2.jpg ...class_b/ ......b_image_1.jpg ......b_image_2.jpg </code></pre>...
tensorflow|keras|subdirectory|tensorflow-datasets|loaddata
3
6,501
49,172,050
Efficient way of writing multiple conditions for filtering data using loc or iloc
<p>I have written the code like below to filter out the records from the column named 'Document Type' which contains around 25 categorical values.</p> <pre><code>salesdf.loc[(salesdf['Document type'] != 'AVC') &amp; (salesdf['Document type'] != 'CC') &amp; (salesdf['Document type'] != 'CDI') &amp; (salesdf['Document...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow noreferrer"><code>isin</code></a> with inverted condition by <code>~</code>:</p> <pre><code>salesdf[~salesdf['Document type'].isin(['AVC', 'CC','CDI', 'BSX','BTR','FAF'])] </code></pre> <p><strong...
python|pandas|pandas-loc
3
6,502
49,305,174
fast way to stack vectors into a matrix in Python
<p>I want to stack 100k vector of the same lentgh (500) into a single matrix in python but it takes too much time.</p> <p>here is my code:</p> <pre><code>stacked = all_vectors[0] for i in range(1,100000): stacked = np.column_stack((stacked ,all_vectors[i])) </code></pre> <p>Do you know how to make this quicker?<...
<p>You should get the answer you want with</p> <pre><code>stacked = np.column_stack(all_vectors[:100000]) </code></pre> <p>There appears to be no difference between that and</p> <pre><code>stacked = np.array(all_vectors[:100000]).transpose() </code></pre> <p>as you can see from this interactive session:</p> <pre><...
python|loops|numpy|matrix|vector
3
6,503
59,036,924
In python is there a way to delete parts of a column?
<p>I want to trim the values of a pandas data frame. For example, I have the following:</p> <pre><code> A B C 33344-10 5555-78 999902 3444441 5555679 2334 2334 5555 3344 </code></pre> <p>And I would like the result to be:</p> <pre><code>A B C 3334 5555 ...
<p>slice each column in a loop as below</p> <pre class="lang-py prettyprint-override"><code>columns = df.columns for column in columns: df[column] = df[column].astype(str).str[:4] df </code></pre> <p>which gives you the following output</p> <pre><code> A B C 0 3334 5555 9999 1 3444 5555 23...
python|pandas|dataframe
5
6,504
58,664,914
How do I split multiple columns?
<p>I would like to split each of columns in dataset.</p> <p>The idea is to split the number between "/" and string between "/" and "@" and put this values to the new colums.</p> <p>I tried sth like this :</p> <pre><code>new_df = dane['1: Brandenburg'].str.split('/',1) </code></pre> <p>and then creating new columns...
<p>As I understood, you want to extract <strong>two parts</strong> from each cell. E.g. from <em>ES-NL-10096/1938/X1@hkzydzon.dk/6749</em> there should be extracted:</p> <ul> <li><em>1938</em> - the number between slashes,</li> <li><em>X1</em> - the string between the second slash and <em>@</em>.</li> </ul> <p>To to ...
python|pandas|split
1
6,505
70,170,844
Pandas JSON Normalize - Choose Correct Record Path
<p>I am trying to figure out how to normalize the nested JSON response sampled below.</p> <p>Right now, <code>json_normalize(res,record_path=['data'])</code> is giving me MOST of the data I need but what I would really like is the detail in the &quot;session_pageviews&quot; list/dict with the attributes of the data lis...
<p>You can try to apply the following function to your json:</p> <pre><code>def flatten_nested_json_df(df): df = df.reset_index() s = (df.applymap(type) == list).all() list_columns = s[s].index.tolist() s = (df.applymap(type) == dict).all() dict_columns = s[s].index.tolist() while len...
python|pandas|json-normalize
2
6,506
70,301,937
How do I filter specific number using `np.where`
<p>Case</p> <p><a href="https://i.stack.imgur.com/vBA4e.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vBA4e.jpg" alt="enter image description here" /></a></p> <p>so I have an array like these, and how do I extract the green number from the array?</p> <p>The output that I wanted :</p> <pre><code>[11...
<p>Hope I answered your question..</p> <pre><code>array = np.array( [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) filter1 = array[:, [0, 2, 4]] filter2 = filter1[[0, 2, 4], :].fl...
python|numpy
0
6,507
70,137,421
Removing the index when appending data and rewriting CSV using pandas
<p>I have a script that runs on a daily basis to collect data. I record this data in a CSV file using the following code:</p> <pre><code>old_df = pd.read_csv('/Users/tdonov/Desktop/Python/Realestate Scraper/master_data_for_realestate.csv') old_df = old_df.append(dataframe_for_cvs, ignore_index=True) old_df.to_csv('/Use...
<p>Did you try</p> <pre><code>to_csv(index=False) </code></pre>
python|pandas
1
6,508
55,682,800
Selecting from one dataframe using values from a second dataframe
<p>I have two dataframes with the same index and columns:</p> <pre><code>In: import pandas as pd import numpy as np import random df1 = pd.DataFrame({'A' : [ random.random(), random.random(), random.random()], 'B' : [ random.random(), random.random(), random.random()], 'C' : [ ran...
<p>If same index and columns in both DataFrmes, is possible use indexing with mask from <code>df2</code> with <code>2d array</code> created by <code>to_numpy</code> or <code>values</code>:</p> <pre><code>#pandas 0.24+ a = df1.to_numpy()[df2 == 6] #oldier pandas versions #a = df1.values[df2 == 6] print (a) [0.754941 0....
python|pandas|selection|mask
4
6,509
39,892,684
How can I format the index column(s) with xlsxwriter?
<p>I'm using <strong>xlsxwriter</strong> and the <strong>set_column</strong> function that format the columns in my excel outputs. </p> <p>However, formatting seems to be ignored when applied to the index column (or index columns in case of multi index). </p> <p>I've found a workaround, so far is to introduce a fake ...
<p>The pandas <code>ExcelWriter</code> overwrites the <code>XlsxWriter</code> formats in the index columns. To prevent that, change the pandas <code>header_style</code> to <code>None</code></p> <pre><code>header_style = {"font": {"bold": True}, "borders": {"top": "thin", "ri...
python|excel|pandas|xlsxwriter
2
6,510
39,732,126
Using Pandas groupby methods, find largest values in each group
<p>By using Pandas groupby, I have data on how much activity certain users have on average any given day of the week. Grouped by user and day, I compute max and mean for several users in the last 30 days.</p> <p>Now I want to find, for every user, which day of the week corresponds to their daily max activity, and what...
<p>I'd first do a <code>groupby</code> on <code>'userID'</code>, and then write an <code>apply</code> function to do the rest. The <code>apply</code> function will take a <code>'userID'</code> group, perform another <code>groupby</code> on <code>'weekday'</code> to do your aggregations, and then only return the row th...
pandas
5
6,511
44,116,689
Siamese Model with LSTM network fails to train using tensorflow
<p><strong>Dataset Description</strong></p> <p>The dataset contains a set of question pairs and a label which tells if the questions are same. e.g.</p> <blockquote> <p>"How do I read and find my YouTube comments?" , "How can I see all my Youtube comments?" , "1"</p> </blockquote> <p>The goal of the model is to i...
<p>This is a common problem with imbalanced datasets like the recently released Quora dataset which you are using. Since the Quora dataset is imbalanced (~63% negative and ~37% positive examples) you need proper initialization of weights. Without weight initialization your solution will be stuck in a local minima and i...
tensorflow|lstm|recurrent-neural-network
2
6,512
69,482,458
Am I mislabeling my data in my neural network?
<p>I'm working on an implementation of EfficientNet in Tensorflow. My model is overfitting and predicting all three classes as just a single class. My training and validation accuracy is in the 99% after a few epochs and my loss is &lt;0.5. I have 32,000 images between the three classes (12, 8, 12).</p> <p>My hypothesi...
<p>Well first off you are writing more code than you need to. In train_ds and val_ds you did not specify the parameter label_mode. By default it is set to 'int'. Which means your labels will be integers. This is fine if your compile your model using loss=tf.keras.losses.SparseCategoricalCrossentropy. If you had set</p>...
python|tensorflow|deep-learning|neural-network|multilabel-classification
1
6,513
69,528,805
How to send a Python Dataframe through an E-mail?
<p>I'm having trouble sending my DataFrame through an e-mail. The DataFrame looks fine whenever I export it or print it. Through an e-mail however, it looks messed up.</p> <p>Of course, I've tried the <code>to_html</code> option that Pandas offers. And also the <code>build_table</code> from the <code>pretty_html_table<...
<p>You are currently sending the email in plain text format, which makes it impossible to ensure the column spacing is correct unless the recipient happens to view their emails in a plain text reader.</p> <p>To ensure the table is spaced correctly you have to send an HTML email - see the <a href="https://docs.python.or...
python|pandas|dataframe|email
1
6,514
54,144,408
Repeatedly execute same code before/after statements/code blocks
<p>I am filtering some data in a <code>pandas.DataFrame</code> and want to track the rows I loose. So basically, I want to</p> <pre><code>df = pandas.read_csv(...) n1 = df.shape[0] df = ... # some logic that might reduce the number of rows print(f'Lost {n1 - df.shape[0]} rows') </code></pre> <p>Now there are multipl...
<p>You could write a "wrapper-function" that wraps the filter you specify:</p> <pre><code>def filter1(arg): return arg+1 def filter2(arg): return arg*2 def wrap_filter(arg, filter_func): print('calculating with argument', arg) result = filter_func(arg) print('result', result) return result w...
python|python-3.x|pandas
0
6,515
53,987,380
How does torch.empty calculate the values?
<p>Every time I run <code>torch.empty(5, 3)</code> I get one of those two results:</p> <pre><code>&gt;&gt;&gt; torch.empty(5, 3) tensor([[ 0.0000, 0.0000, 0.0000], [ 0.0000, 0.0000, 0.0000], [ 0.0000, 0.0000, 0.0000], [ 0.0000, -0.0000, 0.0...
<p><a href="https://pytorch.org/docs/stable/torch.html#torch.empty" rel="nofollow noreferrer"><code>torch.empty</code></a> returns "a tensor filled with uninitialized data."</p> <p>If you want to have a tensor filled with zeros, use <a href="https://pytorch.org/docs/stable/torch.html#torch.zeros" rel="nofollow norefer...
python|numpy|pytorch|torch
4
6,516
54,059,953
I can't adapt my dataset to VGG-net, getting size mismatch
<p>I’m trying to implement the pre-trained VGG net to my script, in order to recognize faces from my dataset in RGB [256,256], but I’m getting a “size mismatch, m1: [1 x 2622], m2: [4096 x 2]” even if i'm resizing my images it doesn't work, as you can see my code work with resnet and alexnet.</p> <p>I've tryed resizin...
<p>The error comes from this line:</p> <pre><code>model_conv.fc = nn.Linear(4096, 2) </code></pre> <p>Change to:</p> <pre><code>model_conv.fc = nn.Linear(2622, 2) </code></pre>
python-3.x|pytorch|vgg-net|transfer-learning
0
6,517
38,285,774
How to save a csv file so iPython shell can open and use it?
<p>I'm a newbie to Python. I'm having trouble opening my csv file in the iPython shell, although I can open my file in Spyder just find. How can I save a csv, or any other file, properly to be used by both Spyder and iPython?</p> <p>For example, I tried opening up and reading a file</p> <pre><code>DATA_data = open('D...
<p>A <code>csv</code> file is plain text, so almost any code can read it. With <code>ipython</code> you can read it with shell command, with Python read, or with numpy or pandas.</p> <p>The first issue knowing where the file is located. That's a file system issue - what's directory. In <code>ipython</code> you can ...
python|python-2.7|csv|pandas|ipython
1
6,518
66,249,826
list of stings into list of integers
<p>How to convert multiple columns where each row contains a list of strings to rows containing lists of integers?</p> <p>From this state</p> <pre><code>index column_1 column_2 column_3 column_4 column_5 column_6 0 ['1','1'] ['7','6'] ['1','3'] 7 2 ['5','1'] </code></pre> <...
<p>Here is a solution that converts that dataframe to a 2D list, performs the necessary conversion to integers, and converts back to dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({'column_1':[['1','1']], 'column_2':[['7','6']], 'column_3':[['1','3']], 'column_4':[7], 'column_5':[2]...
python-3.x|pandas
0
6,519
66,192,403
How to get time values as strings, during read_excel execution?
<p>i have to parse ODF-format turnstile's data file. In the file are employees entry/out time values in HH:MM:SS (like a 141:59:30).<br /> <a href="https://drive.google.com/file/d/1j0EEraI-JbfXKoaliXi_LV85S3_nIAk5/view?usp=sharing" rel="nofollow noreferrer">link to sample file on GoogleDrive</a></p> <p>My attempts to o...
<p>You can pass a dictionary to the dtype parameter where you input your column name as the key, and the data type as the value.</p> <p>Could look something like this :</p> <pre><code>df = pd.read_excel(filename, engine=&quot;odf&quot;, skiprows=3, dtype={'time_col':str}) </code></pre> <p><strong>UPDATE</strong></p> <p...
python|pandas|datetime|ods
0
6,520
66,121,576
How to actually save a csv file to google drive from colab?
<p>so, this problem seems very simple but apparently is not. I need to transform a pandas dataframe to a csv file and save it in google drive.</p> <p>My drive is mounted, I was able to save a zip file and other kinds of files to my drive. However, when I do:</p> <pre><code>df.to_csv(&quot;file_path\data.csv&quot;) </co...
<ol> <li><p>First of all, mount your Google Drive with the Colab:</p> <p><code>from google.colab import drive</code></p> <p><code>drive.mount('/content/drive')</code></p> </li> <li><p>Allow Google Drive permission</p> </li> <li><p>Save your data frame as CSV using this function:</p> <p><code>import pandas as pd</code><...
pandas|csv|save|google-colaboratory|drive
1
6,521
65,961,796
Loop and Accumulate Sum from Pandas Column Made of Lists
<p>Currently, my Pandas data frame looks like the following</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Row_X</th> </tr> </thead> <tbody> <tr> <td>[&quot;Medium, &quot;High&quot;, &quot;Low&quot;]</td> </tr> <tr> <td>[&quot;Medium&quot;]</td> </tr> </tbody> </table> </div> <p>My intenti...
<p>We can do:</p> <pre><code>mapper = {'Medium' : 5, 'High' : 10} </code></pre> <hr /> <pre><code>df['Row_Y'] = [sum([mapper[word] for word in l if word in mapper]) for l in df['Row_X']] </code></pre> <p>If <strong>pandas version &gt; 0.25.0</strong> We can use</p> <pre><code>df['Ro...
python|pandas
4
6,522
58,237,439
How do I apply CountVectorizer to each row in a dataframe?
<p>I have a dataframe say df which has 3 columns. Column A and B are some strings. Column C is a numeric variable. <a href="https://i.stack.imgur.com/kRXs9.png" rel="nofollow noreferrer">Dataframe</a></p> <p>I want to convert this to a feature matrix by passing it to a CountVectorizer.</p> <p>I define my countVector...
<p>Try this:</p> <pre><code>import pandas as pd from sklearn.feature_extraction.text import CountVectorizer A = ['very good day', 'a random thought', 'maybe like this'] B = ['so fast and slow', 'the meaning of this', 'here you go'] C = [1, 2, 3] pdt_items = pd.DataFrame({'A':A,'B':B,'C':C}) cv = CountVectorizer() ...
python|pandas|dataframe|scikit-learn|countvectorizer
1
6,523
69,077,375
How to identify dummy data in pandas and delete?
<p>Is there a way to identify the dummy data in a dataframe and delete them? In my data below, there are random characters in each column that I need to delete.</p> <pre><code>import pandas as pd import numpy as np data = {'Name' : ['Tom', 'AABBCC', 'Joseph', 'Krish', 'XXXX', 'John', 'U'], 'Address1': ['High S...
<p>have you investigated your data? Are always the &quot;good data&quot; a combination of lowercase and uppercase characters? If so you could make a function to find those dummy data, for example:</p> <pre><code>if text.lower() == text or text.upper() == text: # text is dummy </code></pre>
python|pandas
0
6,524
44,566,744
Pandas DataFrame: convert WKT into GeoJSON in a new column using Lambda function
<p>I have some data in this format:</p> <pre><code>Dep Dest geom ---- ---- ----- EDDF KIAD LINESTRING(3.961389 43.583333, 3.968056 43.580.... </code></pre> <p>Which contains flight trajectories. The geom column contains the coordinates in WKT format. It is possible to convert them...
<p>Try changing the following line: </p> <pre><code>df['geojson'] = df['geom'].apply(lambda x: json.dumps(wkt.loads(x['geom'] ))) </code></pre> <p>into this one:</p> <pre><code>df['geojson'] = df['geom'].apply(lambda x: json.dumps(wkt.loads(x))) </code></pre> <p>This produce the desired results:</p> <pre><code>f...
python|pandas|lambda|geojson|wkt
3
6,525
44,492,753
How to use pandas in google cloud data flow?
<p>Are there any methods to use pandas, numpy for doing transformations in google cloud data flow?</p> <p><a href="https://cloud.google.com/blog/big-data/2016/03/google-announces-cloud-dataflow-with-python-support" rel="nofollow noreferrer">https://cloud.google.com/blog/big-data/2016/03/google-announces-cloud-dataflow...
<p>Dataflow or Beam do not currently have transforms that use Numpy or Pandas. Nonetheless, you must be able to use them without much trouble.</p> <p>If you give more info about your use case, we can help you figure it out.</p>
pandas|google-cloud-dataflow|apache-beam
0
6,526
44,788,581
Find half of each group with Pandas GroupBy
<p>I need to select half of a dataframe using the <code>groupby</code>, where the size of each group is unknown and may vary across groups. For example:</p> <pre><code> index summary participant_id 0 130599 17.0 13 1 130601 18.0 13 2 130603 16.0 13...
<p>IIUC, you can use index slicing with size //2 inside of lambda:</p> <pre><code>df.groupby('participant_id').apply(lambda x: x.iloc[:x.participant_id.size//2]) </code></pre> <p>Output:</p> <pre><code> index summary participant_id participant_id 13 ...
python|pandas|pandas-groupby|split-apply-combine
8
6,527
61,134,674
Is there any problem in performance if I use 'categorical_crossentropy' as loss function just to classify to objects?
<p>I'm training a CNN to classify dogs and cats and I'm using 'categorical_crossentropy' as loss function because at beginning I had three classes, but at the end I decided to use just two, and I didn't have the opportunity to change the loss function. My prolem here is that I don't have the computer where I was workin...
<p>The answer is no, it is not a problem.</p> <p>You can use <code>binary_crossentropy + Dense(1,activation='sigmoid')</code> or <code>categorical_crossentropy + Dense(2,activation='softmax')</code>.</p> <p>The performance of your model should not be affected at all.</p>
tensorflow
0
6,528
61,088,788
How to speed up process when apply a function in Python
<p>I have a function peak_value which takes two iuputs area and data and returns a new column in data with potential peaks as output. I actually want to apply this peak value function on list of dataframes e.g data = [df1, df2, df3...dfn2] each dataframe has respective value of area e.g area = [a1, a2, a3.....an]. I ha...
<p>If it's possible to run your solution in parallel, then I think <a href="https://joblib.readthedocs.io/en/latest/" rel="nofollow noreferrer">Joblib</a> is a viable solution. </p> <p>I tried it myself and I like it a lot. The amount of modifications needed for this to work is really low.</p> <p>Here's an example ab...
python|python-3.x|pandas|python-2.7|scipy
-1
6,529
61,180,155
Add additional column in merged csv file
<p>My code merges csv files and removes duplicates with pandas. Is it possible to add an additional header with values to the single merged file?</p> <p>The additional header should be called <code>Host Alias</code> and should correspond to <code>Host Name</code></p> <p>E.g. <code>Host Name</code> is <code>dpc01n1</...
<p><strong>Something like this should work:</strong></p> <pre><code>import pandas as pd combo = pd.DataFrame({ 'Start Time' : [1,2,3], 'epoch' : [1,2,3], 'Host Name': ['dpc01n1','dpc02n1','dpc00103n1'], 'Db Alias' : [1,2,3], 'Database' : [1,2,3], 'Db Host' : [1,2,3...
python|pandas|csv
1
6,530
61,078,252
Comparing two data frames with a given tolerance range
<p>I have two dataFrame with same number of columns and same rows size. I'm comparing the the first row in df1 with the first row in df2, and the 2nd row in df1 with the 2nd row in df2 and so on, to see how many feature differences are there. This code is working ok but it cosiders the exact match.</p> <pre><code>Df1:...
<p><strong>Try using <code>np.isclose()</code> :</strong></p> <pre><code>differences = np.zeros(len(df1)) for i in df1: differences += np.where(~np.isclose(df1[i],df2[i],atol = 5),1,0) print(differences) </code></pre> <p><strong>Output:</strong></p> <pre><code>[0. 3. 0.] </code></pre>
python|arrays|pandas|comparison
1
6,531
71,526,796
Cleaning data in Panda
<p><strong>Background</strong> I load data into Panda from a csv/xlsx file created by a text-to-data app. While saving time, the auto-read is only so accurate. Below I have simplified a load to illustrate a specific problem I struggle to sort:</p> <pre><code>import pandas as pd from tabulate import tabulate df_is = {&...
<p>Please try this:</p> <pre><code>import pandas as pd import numpy as np f_is = {&quot;Var&quot;:[&quot;Sales&quot;,&quot;Gogs&quot;,&quot;Op prof&quot;,&quot;Depreciation&quot;,&quot;Net fin&quot;,&quot;PBT&quot;,&quot;Tax&quot;,&quot;PAT&quot;], &quot;2021&quot;:[100,-50,50,-10,-5,35,&quot;&quot;,&quot;&quot;], &quo...
pandas|database|data-cleaning
0
6,532
71,480,457
Pandas Column Split but ignore splitting on specific pattern
<p>I have a Pandas Series containing Several strings Patterns as below:</p> <pre><code>stringsToSplit = ['6 Wrap', '1 Salad , 2 Pepsi , 2 Chicken Wrap', '1 Kebab Plate [1 Bread ]', '1 Beyti Kebab , 1 Chicken Plate [1 Bread ], 1 Kebab Plate [1 White Rice ...
<p>You can use a regex with a negative lookahead:</p> <pre><code>s.str.split(r'\s*,(?![^\[\]]*\])').explode() </code></pre> <p>output:</p> <pre><code>0 6 Wrap 1 1 Salad 1 2 Pepsi 1 ...
python|pandas|string|split
1
6,533
71,531,749
Passing the name of a pandas dataframe column to a function
<p>I'm trying to write a function that takes the name of a column and splits the dataframe based on the values of that column. I have the following</p> <p><code>df_split = df[df.a == 1]</code></p> <p>I'm trying to implement the following idea</p> <pre><code>def f(df,column_name): df_split = df[df.column_name == 1] <...
<p>Please change the function to following:</p> <pre><code>def f(df,column_name): df_split = df[df[column_name] == 1] return df_split </code></pre> <p>df.column_name will work only if the dataframe really have a column labelled as <code>column_name</code> so don't use it inside the function</p>
python|pandas|dataframe
2
6,534
42,158,198
R equivalent of Python's np.dot for 3D array
<p>I am translating some code from Python to R involving 3D matrices. Which is tricky as I know very little Python or matrix algebra. Anyhow in the Python code I have a matrix dot.product as follows: <code>np.dot(A, B)</code>. Matrix A has dimension (10, 4) and B is (2, 4, 2). (These dimensions may vary but always wil...
<p>We can do this with <code>aperm()</code> and <code>tensor::tensor</code>. Using @SandipanDey's example.</p> <p>Set up arrays (you need <code>aperm</code> to get the appropriate B, which I call B2 here):</p> <pre><code>A &lt;- matrix(0:39,ncol=4,byrow=TRUE) B &lt;- array(0:15,dim=c(2,4,2)) B2 &lt;- aperm(B,c(2,1,3)...
python|arrays|r|numpy|matrix
6
6,535
42,434,095
How to recover 3D image from its patches in Python?
<p>I have a 3D image with shape <code>DxHxW</code>. I was successful to extract the image into patches <code>pdxphxpw</code>(overlapping patches). For each patch, I do some processing. Now, I would like to generate the image from the processed patches such that the new image must be same shape with original image. Coul...
<p>This will do the reverse, however, since your patches overlap this will only be well-defined if their values agree where they overlap</p> <pre><code>def stuff_patches_3D(out_shape,patches,xstep=12,ystep=12,zstep=12): out = np.zeros(out_shape, patches.dtype) patch_shape = patches.shape[-3:] patches_6D = ...
python|python-2.7|numpy|image-processing
5
6,536
69,851,198
I get AttributeError: module 'pandas' has no attribute 'DataFrame' when using pd.DataFrame
<p>Im working in Jupyter and all of a sudden pandas won´t create a dataframe for me. The name of the notebook is &quot;Cálculo_Energía_gases&quot;, I don´t think there is a name conflict.</p> <p>This is the code:</p> <pre><code>df_energía_gases = pd.DataFrame(columns = [&quot;Presión (Pa)&quot;,&quot;rpm&quot;,&quot;Q ...
<p>You probably have a file called <code>pandas.py</code> in the same directory. When you import a module python will first search the directory you are in and then will check your python path for other modules. Delete or rename the <code>pandas.py</code> and everything should work.</p>
python|pandas|dataframe
0
6,537
69,829,101
Simple gradient descent optimizer in PyTorch not working
<p>I'm trying to implement a simple minimizer in PyTorch, here is the code (<code>v</code> and <code>q</code> and <code>v_trans</code> are tensors, and <code>eta</code> is 0.01):</p> <pre><code>for i in range(10): print('i =', i, ' q =', q) v_trans = forward(v, q) loss = error(v_trans, v_target) q.requi...
<p>Here is a simple example of finding a zero (or local minimum) of a function (in this case <a href="https://i.stack.imgur.com/LL5p5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LL5p5.png" alt="function" /></a>).</p> <pre class="lang-py prettyprint-override"><code># the loss function def mse(Y, ...
python|optimization|pytorch|gradient|gradient-descent
0
6,538
69,708,228
Numpy add one array to another one
<p>Let</p> <pre><code>A = np.array([]) B = np.array([1,2]) C = np.array([&quot;hey&quot;]) D = np.array([]) </code></pre> <p>I'm looking for a function which can append the arrays B,C,D to A. But not the values, the whole array:</p> <p>So A should look like this:</p> <pre><code>A = np.array([[1,2],[&quot;hey&quot;],[]...
<p>Appends are not done in-place in numpy, since it operates on fixed buffers. Since your lists are ragged and inhomogenous, you can do:</p> <pre><code>A = np.array([B, C, D]) </code></pre> <p>The dtype will automatically be <code>object</code> in this particular case, and the result will be an array of arrays.</p> <p>...
python|arrays|numpy|multidimensional-array
1
6,539
69,692,572
loop through a list and compare each item with another whole list
<p><strong>Table 1</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Date</th> <th style="text-align: center;">Prescribed</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">16-05-2017</td> <td style="text-align: center;">Amlodipine [ Amlodipine |...
<p>IIUC, you want to extract the drug names from the <code>table2['Name']</code> and then use that as a comparison list to find if ANY of those occur in the table1['Prescription'].</p> <p>If this is what you want, then try this -</p> <ol> <li>Use vectorized <code>str</code> functions like <code>replace</code>, <code>sp...
python|pandas|loops
1
6,540
43,409,488
Custom Loss Function in TensorFlow for weighting training data
<p>I want to weight the training data based on a column in the training data set. Thereby giving more importance to certain training items than others. The weighting column should not be included as a feature for the input layer.</p> <p>The Tensorflow documentation holds an <a href="https://www.tensorflow.org/api_guid...
<p>I believe i found the answer:</p> <pre><code> weight_tf = tf.range(features.get_shape()[0]-1, features.get_shape()[0]) loss = tf.losses.softmax_cross_entropy(target, logits, weights=weight_tf) </code></pre> <p>The weight is the last column in the features tensorflow.</p>
python|machine-learning|tensorflow
1
6,541
72,346,940
Pandas : Getting a cumulative sum for each month on the last friday
<p>I got a dataframe which look like this :</p> <pre><code>date_order date_despatch date_validation qty_ordered 2019-01-01 00:00:00 2019-11-01 00:00:00 2019-13-01 00:00:00 4.15 2019-01-01 00:00:00 2019-12-01 00:00:00 2019-14-01 00:00:00 5.9 2019-02-01 00:00:00 201...
<p>With an example df with <code>qty_ordered</code> always 1 (so we can easily keep track of the result):</p> <pre><code>import pandas as pd df = pd.DataFrame({'date_order': pd.date_range('2019-01-01', '2019-03-01')}) df['qty_ordered'] = 1 print(df) </code></pre> <pre><code> date_order qty_ordered 0 2019-01-01 ...
python|pandas|datetime
0
6,542
72,454,832
How to update column value of a data frame from another data frame matching 2 columns?
<p>I have 2 dataframes, and I want to update the score of rows with the same 2 column values.</p> <p>How can I do that?</p> <p>df 1:</p> <pre><code>DEP ID | Team ID | Group | Score 001 | 002 | A | 50 001 | 004 | A | 70 002 | 002 | A | 50 002 ...
<p>Here's a way to do it:</p> <pre class="lang-py prettyprint-override"><code>df1 = df1.join(df2.drop(columns='DEP ID').set_index(['Team ID', 'Group']), on=['Team ID', 'Group']) df1.loc[df1.Result.notna(), 'Score'] = df1.Result df1 = df1.drop(columns='Result') </code></pre> <p>Explanation:</p> <ul> <li>modify df2 so it...
python|pandas
1
6,543
72,285,947
Python convert array dimensions with numpy
<br> I have a JPG image with a shape of (1, 48, 48, 3), <br> I want to convert it to the shape of (1, 48, 48, 1) How can I do it ? <p>Please help</p>
<p>thank you all! I solve it with</p> <p>img = img.mean(axis=-1) <br> img = np.expand_dims(img, axis=3)</p>
python|numpy|image-processing
-1
6,544
72,147,193
How to customize general error messages of numpy?
<p>I am writing a <code>Vector</code> and <code>Matrix</code> classes that use <code>numpy</code> in the backend in order to abstract some common methods and calculations (specifically, physics calculations, but it's irrelevant). I would like to intercept common errors that may occur with the usage of these classes in ...
<p>If you mean you want to access the stack trace by,</p> <blockquote> <p>but the exception doesn't contain information about why it was raised.</p> </blockquote> <p>you can use <code>print(traceback.format_exc())</code> under the <code>catch</code> statement. Also you'll have to import <code>import traceback</code>.</...
python|numpy
0
6,545
50,379,132
Format x-axis tick labels to seams like the default pandas plot
<p>I'm trying to set my plot xticks to similar to the pandas dataframe default format.</p> <p>I've been trying to set using the plt.set_xticklabels functions, but did not succeed. </p> <pre><code>fig, axarr = plt.subplots(len(stations), 2, figsize=(10,11)) plt.subplots_adjust(bottom=0.05) hPc3.plot(use_index=True, su...
<p>Matplotlib <a href="https://matplotlib.org/api/dates_api.html" rel="nofollow noreferrer">dates</a> api provides plenty of convenience functions and classes to represent and convert date and time data.</p> <p>You can reproduce <code>pandas</code> style using a simple combination of <code>DateFormatter</code>, <code>...
python|pandas|matplotlib
0
6,546
45,335,993
compare string got error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
<p>I am trying to use <code>if</code> condition to update some values in a column using the following code:</p> <pre><code>if df['COLOR_DESC'] == 'DARK BLUE': df['NEW_COLOR_DESC'] = 'BLUE' </code></pre> <p>But I got the following error:</p> <pre><code>ValueError: The truth value of a Series is ambiguous. Use a.e...
<p>To answer your immediate question, the problem is that the expression <code>df['COLOR_DESC'] == 'DARK BLUE'</code> results in a Series of booleans. The error message is telling you that there is no one unambiguous way to convert that array to a single boolean value as <code>if</code> demands.</p> <p>The solution is...
python|pandas
1
6,547
45,527,853
Python pandas - Filter a data frame based on a pre-defined array
<p>I'm trying to filter a data frame based on the contents of a pre-defined array.</p> <p>I've looked up several examples on StackOverflow but simply get an empty output.</p> <p>I'm not able to figure what is it I'm doing incorrectly. Could I please seek some guidance here?</p> <pre><code>import pandas as pd import ...
<p>Managed to that using <code>filter</code> function -> <code>.filter(items=pre_defined_arr )</code></p> <pre><code>import pandas as pd import numpy as np csv_path = 'history.csv' df = pd.read_csv(csv_path) pre_defined_arr = ["A/B", "C/D", "E/F", "U/Y", "R/E", "D/F"] distinct_count_column_headers = ['Entity'] dist...
python|pandas
0
6,548
62,861,470
Numpy 2D array indexing with indices out of bounds
<p>I found a substantial bottleneck in the following code:</p> <pre><code>def get_value(matrix, index): if (index[0] &gt;= 0 and index[1] &gt;= 0 and index[0] &lt; matrix.shape[0] and index[1] &lt; matrix.shape[1]): return matrix[index[0], index[1]] return DEFAULT_VAL </code></pre> <p>Gi...
<p>The code you have shown</p> <pre><code>def get_values(matrix, indices): return matrix[indices[:,0], indices[:,1]] </code></pre> <p>is the best you can do given that <code>indices</code> is a tuple with two values.</p> <p>You should rather look at the optimal way to call the above method. I suggest if you can, ra...
python|numpy|optimization|matrix-indexing
1
6,549
62,876,594
Pandas filter, group-by and then transform
<p>I have a pandas dataframe, which looks like the following:</p> <pre><code> df = a b a1. 1 a2 0 a1 0 a3 1 a2 1 a1 1 </code></pre> <p>I would like to first filter b on <code>1</code> and then, group by <code>a</code> and...
<p>Check with get the condition apply to <code>b</code> then <code>sum</code></p> <pre><code>df['b'].eq(1).groupby(df['a']).transform('sum') Out[103]: 0 2.0 1 1.0 2 2.0 3 1.0 4 1.0 5 2.0 Name: b, dtype: float64 </code></pre>
python-3.x|pandas|pandas-groupby
2
6,550
62,504,167
How to convert from frequency domain to time domain in python
<p>I know this is basic for signal processing, but, I am not sure what is wrong about my approach. I have a signal that behaves as damped sine signal with a sampling frequency of 5076Hz and 15,000 number of samples. I found from the following website how to convert a signal from a time domain to frequency domain and ma...
<p>There are several issues:</p> <ul> <li>You are using <code>np.fft.fft</code>, which is a complex-valued discrete Fourier transform, containing frequencies up to twice the Nyqvist frequency. The frequencies above the Nyqvist frequency can be interpreted equivalently as negative frequencies. You are indeed using a fre...
python|numpy|scipy|signal-processing|fft
0
6,551
62,754,767
TF.Keras SparseCategoricalCrossEntropy return nan on GPU
<p>Tried to train UNet on GPU to create binary classified image. Got nan loss on each epoch. Testing of loss function always produces nan-return.</p> <p>Test case:</p> <pre><code>import tensorflow as tf import tensorflow.keras.losses as ls true = [0.0, 1.0] pred = [[0.1,0.9],[0.0,1.0]] tt = tf.convert_to_tensor(true)...
<p>I had the same issue. My loss was a real number if I trained on CPU. I tried upgrading the TF version, but it didn't fix the problem. I finally fixed my issue by reducing the y dimension. My model output was a 2D array. When I reduced it to 1D, I managed to get a real loss on GPU.</p>
python|tensorflow|keras
2
6,552
54,400,171
How to use list in Snakemake Tabular configuration, for describing of sequencing units for bioinformatic pipeline
<p>How to use a list in Snakemake tabular config.</p> <p>I use Snakemake Tabular (mapping with BWA mem) configuration to describe my sequencing units (libraries sequenced on separate lines). At the next stage of analysis I have to merge sequencing units (mapped .bed files) and take merged .bam files (one for each samp...
<p>What about this below? </p> <p>I have excluded the Samples.yaml as I think it is not necessary given your sample sheet. </p> <p>In rule <code>samtools_merge_bam</code> you collect all unit-bam files sharing the same SampleSM. These unit-bam files are created in <code>map_paired_end</code> where the lambda expressi...
python|pandas|bioinformatics|pipeline|snakemake
0
6,553
54,652,103
Updating a pandas column with a dictionary lookup
<p>Have a dataframe, df:</p> <pre><code>import pandas as pd import numpy as np i = ['dog', 'cat', 'rabbit', 'elephant'] * 3 df = pd.DataFrame(np.random.randn(12, 2), index=i, columns=list('AB')) </code></pre> <p>...and a lookup dict for column B:</p> <p><code>b_dict = {'elephant': 2.0, 'dog': 5.0}</code></p> <p>H...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where()</code></a> to replace only where condition matches and retain the rest:</p> <pre><code>df['B']=np.where(df.index.isin(b_dict.keys()),df.index.map(b_dict),df.B) </code></pre>
pandas
3
6,554
73,791,808
For loops through pandas dataframes for state and country
<p>I am trying to get the state location from zip codes when they are in the US. The code below is what I am using importing a csv with zip codes and country. I am getting repeating state for the first zip code in the dataframe. I tried .append on the state, country but am still just getting the return of the first row...
<pre><code>df['state']=state df['country']=country </code></pre> <p>overwrite the whole column.</p> <p>You can use .apply() instead. Put your code in a function and you can do something like that:</p> <pre><code>def zip_to_state_country(zip_code): # your logic here return zip_code[0], zip_code[1] # returns jus...
python|pandas|dataframe|geopy
0
6,555
71,166,405
Getting ValueError: All arrays must be of the same length while reshaping tensor for Bidirectional LSTM
y_pred length returns 13, y_test length returns 13 as well however y_pred.reshape(-1) returns 130. y_pred argument expects one argument, how do I reshape it back to 13? <pre><code>from keras.layers import Dense, Dropout,Activation, LSTM,Bidirectional from keras.models import Sequential import tensorflow as tf BLS...
<p>Look at your model's summary and the parameters of your <code>LSTM</code> layer. You are using an input shape of <code>(10,1)</code> meaning you have 10 timesteps and for each timestep you have 1 feature. At least that is what you are telling this layer. Note that this has nothing to do with number of samples you ha...
python|tensorflow|keras|lstm|bidirectional
0
6,556
71,252,199
Tricky distance matrix calculation and how to cleverly avoid out of bounds
<p>I have the layout of a warehouse with racks and aisles where items are picked from locations on the racks while traversing the aisles:</p> <p><a href="https://i.stack.imgur.com/5EPFv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5EPFv.png" alt="" /></a></p> <p>I want to compute a distance matrix...
<p>In your comment, you stated that the last point is (330,31), which is inconsistent with your linspace. The biggest mistake is that you are iterating over the individual axes, whilst you should iterate over all combinations of the coordinates. I separated out the distance calculation and the matrix generation, becaus...
python|numpy
1
6,557
71,226,303
Interpolating data for missing values pandas python
<p><a href="https://i.stack.imgur.com/OzCUQ.png" rel="nofollow noreferrer">enter image description here</a>[enter image description here][2]I am having trouble interpolating my missing values. I am using the following code to interpolate</p> <pre><code>df=pd.read_csv(filename, delimiter=',') #Interpolating the nan valu...
<p>Try this, assuming the <strong>first</strong> column of your csv is the one with date strings:</p> <pre class="lang-py prettyprint-override"><code>df = pd.read_csv(filename, index_col=0, parse_dates=[0], infer_datetime_format=True) df2 = df.interpolate(method='time', limit_direction='both') </code></pre> <p>It theor...
python|pandas|dataframe|interpolation|nan
0
6,558
52,283,402
H5 Hexadecimal data
<p>When I load a .h5 file into the spyder environment using h5py, I no longer see the hexadecimal data that was in the original file. </p> <p>Does Python convert the hex information to uint8 automatically?</p>
<p>HDF5 does not store hexadecimal data, only numbers and characters. The <a href="https://support.hdfgroup.org/HDF5/doc/RM/PredefDTypes.html" rel="nofollow noreferrer">documentation of HDF5</a> lists the supported datatypes.</p> <p>What you interpret as hexadecimal data is <em>very likely</em> integer data. You can h...
python|python-2.7|numpy|hdf5|h5py
1
6,559
60,646,621
How to use tensorflow's ncf model to predict?
<p>Hi I'm new to tensorflow and neural networks. Trying to understand the <a href="https://github.com/tensorflow/models/tree/master/official/recommendation" rel="nofollow noreferrer">ncf recommendation model</a> in tensorflow's official models repo. </p> <p>My understanding is that you build a model with input layers ...
<p>If you're new to TensorFlow and deep learning, this recommendations project is probably not a good place to start. The code is not documented and the architecture might be a confusing to follow along.</p> <p>Anyway, to answer your questions, the model does not take single inputs to make predictions. Looking at the c...
python|tensorflow|neural-network|recommendation-engine|tensorflow-model-garden
0
6,560
60,429,490
Dataframe groupby into one column
<p>I would like to know how can i do this simply :</p> <p>i have a <code>DataFrame</code> with <code>4</code> columns, i want to <code>group by</code> the <code>3</code> first columns, get the result of the 4 based on the 3 others and create a column with a <code>''.join</code> of the 3 columns name.</p> <p>An exampl...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with flatten columns by <code>f-string</code>s:</p> <pre><code>df = df.pivot_table(index='MONTH', columns=['P...
python|pandas|dataframe
0
6,561
72,674,054
lambda function with if statement to return mode
<p>I want to get the most repeated value of a column but I also want to add a condition that picks the 2nd highest value if the most repeated item is 'None'. for example:</p> <p>item_name = [apple, orange, orange, None, None, None] In this case I want the code to return &quot;orange&quot; as the most used item.</p> <p>...
<p><code>mode</code> ignores null value by default:</p> <blockquote> <p><strong>dropna</strong> : bool, default True</p> <p>Don't consider counts of NaN/NaT.</p> </blockquote> <p>You can use:</p> <pre><code>df['most_used_item'] = (df.groupby('user_id')['item_name'] .transform(lambda x: x.mode(...
python|pandas|function|lambda|mode
0
6,562
59,702,785
what does dim=-1 or -2 mean in torch.sum()?
<p>let me take a 2D matrix as example:</p> <pre><code>mat = torch.arange(9).view(3, -1) tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) torch.sum(mat, dim=-2) tensor([ 9, 12, 15]) </code></pre> <p>I find the result of <code>torch.sum(mat, dim=-2)</code> is equal to <code>torch.sum(mat, dim=0)</code> and ...
<p>A tensor has multiple dimensions, ordered as in the following figure. There is a forward and backward indexing. Forward indexing uses positive integers, backward indexing uses negative integers.</p> <p>Example:</p> <p>-1 will be the last one, in our case it will be dim=2</p> <p>-2 will be dim=1</p> <p>-3 will be dim...
python|pytorch
22
6,563
59,872,711
How can I use two pandas dataframes to create a new dataframe with specific rows from one dataframe?
<p>I am currently working with two sets of dataframes. Each set contains 60 dataframes. They are sorted to line up for mapping (eg. set1 df1 corresponds with set2 df1). First set is about 27 rows x 2 columns; second set is over 25000 rows x 8 columns. I want to create a new dataframe that contains rows from the 2nd dat...
<p>You can use list comprehension with flatten for indices:</p> <pre><code>rng = [x for a, b in df.values for x in range(int(a)-1, int(b))] print (rng) [2, 3, 4, 7, 8, 9, 10] </code></pre> <p>And then filter by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollo...
python|pandas|dataframe
1
6,564
59,799,890
utf-8 and skipinitialspace within a line
<p>I'm recently using pandas to read dataframe from a CSV file. Upon calling the reading the Csv file I also have to include 'utf-8' in order to not get the following error</p> <pre><code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x84 in position 19: invalid start byte </code></pre> <p>So I go and modify th...
<p>I had a similair problem when working with lots of diferent <code>txt</code> files, I developed a small program to parse 50 lines of my file and detect the encoding using chardet.</p> <p>it's bettter to use more lines as suggested by anky_91 so use 1000 or more.</p> <pre><code>from pathlib import Path import chard...
python|pandas|utf-8
1
6,565
32,235,229
Pandas: Drop leading rows with NaN threshold in dataframe
<p>I have a Pandas Dataframe with intermittent NaN values:</p> <pre><code>Index Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 1991-12-31 100.000 100.000 NaN NaN NaN NaN NaN NaN 1992-01-31 98.300 101.530 NaN NaN NaN NaN NaN NaN ...
<p>You just need <code>df[(df.irow(0).isnull().sum()&gt;5):]</code></p> <p>When the 1st row has more than 5 <code>nan</code>, <code>df.irow(0).isnull().sum()&gt;5</code> is <code>True</code> and <code>df[(df.irow(0).isnull().sum()&gt;5):]</code> is simply <code>df[1:]</code>: the 1st row is omitted.</p> <p>To address...
python|numpy|pandas|dataframe
3
6,566
40,390,068
Python pandas: Find values in one column that fall within range in another column
<p>I have a pandas dataframe that contains payroll information from the years 2013 through 2016. Each row describes the amount of money the employee earned in a single year. It looks like this:</p> <p><strong>Name, Year, Amount</strong></p> <p>"Bill Smith", "2014", "$20,000"</p> <p>"John Jones", "2014", "$10,000"</p...
<p>This should work:</p> <pre><code>workers = df[df.Year&lt;2015].Name.unique() mew_workers_data = df[~df.Name.isin(workers)] </code></pre>
python|pandas
0
6,567
40,394,874
How to find common elements inside a list
<p>I have a list l1 that looks like [1,2,1,0,1,1,0,3..]. I want to find, for each element the indexes of elements which have same value as the element.</p> <p>For eg, for the first value in the list, 1, it should list out all indexes where 1 is present in the list and it should repeat same for every element in the lis...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>numpy.unique</code></a>, which can return the inverse too. This can be used to reconstruct the indices using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel...
python|pandas|dataframe
1
6,568
18,400,955
Python and Pandas - column that "count direction" and show "average until now"
<p>I have a DataFrame that contain price (of a stock) at the end of specific minute.</p> <p><em>DF columns are:</em></p> <ul> <li>minute_id: 0-1440, 0 for midnight, 480 for 8:00 AM (60*8) </li> <li>price:stock price at the end of the minute </li> <li>change: price change from prev. minute </li> <li>direction: directi...
<p>OK, After a lot of "playing around" I've got something that works for me.</p> <p>It might be done in a little more "Pandastic" way, but this is a reasonable way to get it done.</p> <p>I want to thanks <em>Andy Hayden</em>, <em>Jeff</em> and <em>Phillip Cloud</em> for pointing out to the "10 minutes to pandas" It d...
python|pandas
4
6,569
62,014,890
how to count positive and negative numbers of a column after applying groupby in pandas
<p>have the following dataframe:</p> <pre><code> token name ltp change 0 12345.0 abc 2.0 NaN 1 12345.0 abc 5.0 1.500000 2 12345.0 abc 3.0 -0.400000 3 12345.0 abc 9.0 2.000000 4 12345.0 abc 5.0 -0.444444 5 12345.0 abc 16.0 2.200000 6 6789.0 xyz 1.0 NaN 7 67...
<p>Use:</p> <pre><code>g = df.groupby('name')['change'] counts = g.agg( pos_count=lambda s: s.gt(0).sum(), neg_count=lambda s: s.lt(0).sum(), net_count=lambda s: s.gt(0).sum()- s.lt(0).sum()).astype(int) </code></pre> <p>Result:</p> <pre><code># print(counts) pos_count neg_count net_count name ...
python|pandas
3
6,570
61,989,827
Is there a way to use apply() to create two columns in pandas dataframe?
<p>I have a function returning a tuple of values, as an example:</p> <pre><code>def dumb_func(number): return number+1,number-1 </code></pre> <p>I'd like to apply it to a pandas DataFrame</p> <pre><code>df=pd.DataFrame({'numbers':[1,2,3,4,5,6,7]}) test=dumb_df['numbers'].apply(dumb_func) </code></pre> <p>The re...
<pre><code>df[['number_plus_one', 'number_minus_one']] = pd.DataFrame(zip(*df['numbers'].apply(dumb_func))).transpose() </code></pre> <p>To understand, try taking it apart piece by piece. Have a look at <code>zip(*df['numbers'].apply(dumb_func))</code> in isolation (you'll need to convert it to a list). You'll see how...
python|pandas|apply
1
6,571
61,688,764
Keras CNN: Incompatible shapes [batch_size*2,1] vs. [batch_size,1] with any batch_size > 1
<p>I am Fitting a Siamese CNN with the following structure: </p> <pre><code>def get_siamese_model(input_shape): """ Model architecture """ # Define the tensors for the three input images A_input = Input(input_shape) B_input = Input(input_shape) C_input = Input(input_shape) # C...
<p>Mentioning the solution in this (Answer) section even though it is present in the Comments section, for the benefit of the community.</p> <p>For the above code, with <code>batch_size &gt; 1</code>, it is resulting in error, </p> <pre><code>InvalidArgumentError: Incompatible shapes: [4,1] vs. [2,1] [[node los...
python-3.x|tensorflow|image-processing|keras|conv-neural-network
0
6,572
58,091,879
Whats the difference between frombuffer and fromiter in numpy?Why and when to use these
<p>frombuffer and fromiter both are used for the numpy array creation.But why to these function</p>
<p><strong>frombuffer -:</strong> this is use to <strong>explain</strong> a buffer as a 1-dimensional array.</p> <p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.frombuffer.html" rel="nofollow noreferrer">Full explain</a></p> <p>eg -:</p> <pre><code>&gt;&gt;&gt; s = b'hello world' &gt;&gt;&gt; ...
numpy|numpy-ndarray
2
6,573
58,114,048
How to import tensorflow in javascript? Import in file, served by local http-server
<p>I'm following this tutorial: <a href="https://codelabs.developers.google.com/codelabs/tfjs-training-classfication/index.html#2" rel="noreferrer">https://codelabs.developers.google.com/codelabs/tfjs-training-classfication/index.html#2</a></p> <p>I have set up a local HTTP-server, and that work and the app is running...
<p>you don't need to import the tfjs libraries if they are loaded as modules</p> <p>in the html file put:</p> <pre><code>&lt;html&gt; &lt;meta content="text/html;charset=utf-8" http-equiv="Content-Type"&gt; &lt;head&gt; ... &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.5.2"&gt;&lt;/script&g...
javascript|node.js|tensorflow|tensorflow.js
2
6,574
58,072,185
Pytorch:Apply cross entropy loss with custom weight map
<p>I am solving multi-class segmentation problem using u-net architecture in pytorch. As specified in <a href="https://arxiv.org/abs/1505.04597" rel="nofollow noreferrer">U-NET</a> paper, I am trying to implement custom weight maps to counter class imbalances.</p> <p>Below is the opertion which I want to apply - <a h...
<p>Your <code>final_train_loader</code> provides you with an input image <code>data</code> and the expected pixel-wise labeling <code>target</code>. I assume (following pytorch's conventions) that <code>data</code> is of shape B-3-H-W and of <code>dtype=torch.float</code>.<br> More importantly, <code>target</code> is o...
deep-learning|pytorch|image-segmentation|semantic-segmentation|unet-neural-network
2
6,575
34,362,193
How to explicitly broadcast a tensor to match another's shape in tensorflow?
<p>I have three tensors, <code>A, B and C</code> in tensorflow, <code>A</code> and <code>B</code> are both of shape <code>(m, n, r)</code>, <code>C</code> is a binary tensor of shape <code>(m, n, 1)</code>.</p> <p>I want to select elements from either A or B based on the value of <code>C</code>. The obvious tool is <c...
<p><strong>EDIT:</strong> In all versions of TensorFlow since 0.12rc0, the code in the question works directly. TensorFlow will automatically stack tensors and Python numbers into a tensor argument. The solution below using <code>tf.pack()</code> is only needed in versions prior to 0.12rc0. Note that <code>tf.pack()</c...
tensorflow
15
6,576
34,212,429
Convert a long string into a matrix, cleaning it
<p>I have a large text file which is just a very long string. It is a huge block of text. </p> <p>The original maker of this file tried to make this a "matrix" by setting <code>\n</code> tabs after a certain count of letters. </p> <pre><code>string = "adfajdslfkajsddf&amp;&amp;adfadfladfsjdfl\nadk...fhaldkfjahsdf" </...
<p>You can do this a couple of way, you can check each char seeing if it is alphanumeric:</p> <pre><code>stg = "abcde123]\nefghi456}\njk{lmn789" import numpy as np arr = np.array([ch for line in stg for ch in line if ch.isdigit() or ch.isalpha()]) </code></pre> <p>Or if all the junk is punctuation you can <code>str....
python|regex|string|numpy|matrix
2
6,577
37,111,877
creating a variable within tf.variable_scope(name), initialized from another variable's initialized_value
<p>Hey tensorflow community,</p> <p>I am experiencing unexpected naming conventions when using variable_scope in the following setup:</p> <pre><code>with tf.variable_scope("my_scope"): var = tf.Variable(initial_value=other_var.initialized_value()) </code></pre> <p>In the above, it holds that </p> <pre><code>oth...
<p>You might want to use <code>tf.get_variable()</code> instead of 'tf.Variable`.</p> <pre><code>with tf.variable_scope('var_scope', reuse=False) as var_scope: var = tf.get_variable('var', [1]) var2 = tf.Variable([1], name='var2') print var.name # var_scope/var:0 print var2.name # var_scope/var2:0 wi...
tensorflow
3
6,578
36,806,745
Data transformation for machine learning
<p>I have dataset with SKU IDs and their counts, i need to feed this data into a machine learning algorithm, in a way that SKU IDs become columns and COUNTs are at the intersection of transaction id and SKU ID. Can anyone suggest how to achieve this transformation.</p> <p>CURRENT DATA</p> <pre><code>TransID SKUID...
<p>In <code>R</code>, we can use either <code>xtabs</code></p> <pre><code>xtabs(COUNT~., df1) # SKUID #TransID 31 32 33 34 # 1 1 2 1 0 # 2 2 0 0 -1 </code></pre> <p>Or <code>dcast</code></p> <pre><code>library(reshape2) dcast(df1, TransID~SKUID, value.var="COUNT", fill=0) # TransID 31 32 33 ...
r|python-2.7|numpy|pandas|graphlab
4
6,579
36,721,673
Pandas dataframe add columns with automatic adding missing indices
<p>I have the following 2 simple dataframes.</p> <p>df1:</p> <p><a href="https://i.stack.imgur.com/nwlQT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nwlQT.png" alt="df1"></a></p> <p>df2:</p> <p><a href="https://i.stack.imgur.com/IjM0r.png" rel="nofollow noreferrer"><img src="https://i.stack.i...
<p>Use <code>concat</code> refer to this <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">documentation</a> for detailed help.</p> <p>And here is an example based on the documentation:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], ...
python|pandas|dataframe
1
6,580
54,754,927
Find index of all elements numpy arrays
<p>I am using the <code>numpy</code> <code>searchsort()</code> function to find the index of <code>numpy</code> array. It is working only for some arrays. What is it that is going wrong (implementation below)?</p> <pre><code>import numpy as np #specify the dtype in RV RV = np.array([ np.array([0.23, 2.5, 5.0, 7.1])...
<p>By default, the <code>array</code> argument of <code>searchsorted()</code> must be a <strong>sorted</strong> one. Therefore the solution is:</p> <p>Use <code>numpy.sort()</code> to sort it in advance:</p> <pre><code>np.sort(RV[2]).searchsorted(r[:,2]) </code></pre> <p>Or use the <code>sorter</code> argument:</p> ...
python|python-3.x|numpy|indexing
0
6,581
54,778,734
Remove partial duplicate row using column value
<p>I'm trying to clean data where there is a lot of partial duplicate only storing the first row of data when the key in Col A has duplicate.</p> <pre><code> A B C D 0 foo bar lor ips 1 foo bar 2 test do kin ret 3 test do 4 er ed ln pr </code></pre> ...
<p>In your case how would you say partial duplicate? Please provide complicate example. In the above example instead of Col A duplication you could try Col B.</p> <p>Expected output could be obtained from this following snippet,</p> <pre><code>print (df.drop_duplicates(subset=['B'])) </code></pre> <p><strong>Note: S...
python|pandas
0
6,582
54,919,376
How to convert csv into nested json in python pandas?
<p>I have a csv like this:</p> <pre><code> Art Category LEVEL 2 LEVEL 3 LEVEL 4 LEVEL 5 Location 0 PRINTMAKING VISUAL CONTEMPORARY 2D NaN NaN NaN 1 PAINTING VISUAL CONTEMPORARY 2D NaN NaN NaN 2 AERIAL VISUAL CONTEMPORARY 2D PHOTOGRAPHY AERIAL NaN 3 WILDLIFE VISUAL CONTEMPO...
<p>for convert values of <code>tags</code> to lists without <code>NaN</code>s use:</p> <pre><code>df['tags'] = df.filter(like='LEVEL').apply(lambda x: x.dropna().tolist(), axis=1) #alternative, should be faster #df['tags'] = [[y for y in x if isinstance(y, str)] for x in # df.filter(like='LEVEL').value...
python|json|pandas|csv
2
6,583
54,806,726
Flatten nested dictionary using Pandas
<p>I would like to flatten a nested dictionary. A solution for such a problem was suggested here: <a href="https://stackoverflow.com/a/41801708/8443371">https://stackoverflow.com/a/41801708/8443371</a>. Problem: I would like to obtain a keys identical to the keys in the last layer only. For an input:</p> <pre><code>d ...
<p>Here's my solution in pure python for the dictionary you've provided:</p> <pre><code>d = {'a': 1, 'c': {'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} def flatten_dict(dic): result = {} for key in dic.keys(): if isinstance(dic[key], dict): result.update(flatten_dic...
python|pandas|python-2.7
2
6,584
27,923,768
Optimizing pairwise calculation of distances an array for a given shift
<p>I have an array containing millions of entries. I would like to calculate a another vector, containing all of the distances, for pairs of entries, that are shifted by a certain number delta in the array.</p> <p>Actually I'm using this:</p> <pre><code>for i in range(0, len(a) - delta): difs = numpy.append(difs...
<p>You could just slice <code>a</code> using <code>delta</code> and then subtract the two subarrays:</p> <pre><code>&gt;&gt;&gt; a = np.array([1,5,7,7,2,6]) &gt;&gt;&gt; delta = 2 &gt;&gt;&gt; a[delta:] - a[:-delta] array([ 6, 2, -5, -1]) </code></pre> <p>This slicing operation is likely to be very quick for large a...
python|arrays|performance|python-2.7|numpy
2
6,585
28,227,147
Numpy matrix row stacking
<p>I have 4 arrays (all the same length) which I am trying to stack together to create a new array, with each of the 4 arrays being a row. </p> <p>My first thought was this:</p> <pre><code>B = -np.array([[x1[i]],[x2[j]],[y1[i]],[y2[j]]]) </code></pre> <p>However the shape of that is <code>(4,1,20)</code>.</p> <p>To...
<p><code>np.vstack</code> takes a sequence of equal-length arrays to stack, one on top of the other, as long as they have compatible shapes. So in your case, a tuple of the one-dimensional arrays would do:</p> <pre><code>np.vstack((x1[i], x2[j], y1[i], y2[j])) </code></pre> <p>would do what you want. If this statemen...
python|arrays|numpy
2
6,586
73,347,474
Pandas - Sum for each unique word
<blockquote> <p>Updated. Instead of <code>dict</code> data, I change for a <code>dataframe</code> as input</p> </blockquote> <p>I'm analyzing a DataFrame with approximately 10,000 rows and 2 columns.</p> <p>The criteria of my analysis is based on whether certain words appear in a certain cell.</p> <p>I believe I will ...
<p>You can <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>explode</code></a>, <a href="https://pandas.pydata.org/doc...
python|pandas|group-by
2
6,587
73,463,070
np.fromfile returns blank ndarray
<p>I'm supposed to troubleshoot an open-source Python 2.7 code from GitHub that for some reason, cannot import the binary file correctly. I traced the problem to the following definition, which supposedly imports a binary file (.dat) into an ndarray (rawsnippet) with the following code</p> <pre><code> def update_raw...
<pre><code>In [225]: datatype=np.dtype([('i', np.int16), ('q', np.int16)]) ...: S = 2500 </code></pre> <p>Make an empty file:</p> <pre><code>In [226]: !touch empty.txt </code></pre> <p>Load with this, or any dtype, produces an (0,) shape file:</p> <pre><code>In [227]: np.fromfile('empty.txt', dtype=datatype) Out[2...
python|numpy|fromfile
1
6,588
73,188,883
How to filter and process on a dataframe for some different conditions and combine them without using for loop?
<p>I have a dataframe of logs of orders for anything and a list of times. at moment t, each order can be active or deactive and it can calculate such as below:</p> <pre><code>create_time &lt;= t &lt; response time </code></pre> <p>I want to calculate sum of active orders value for each item at each moment that are in m...
<p>Preprocessing data, make sure the comparability of time-related columns.</p> <pre><code>moment_list = ['08:00:00', '08:30:00', '9:00:00', '09:30:00', '10:00:00'] moment_series = pd.Series(moment_list) moment_series = pd.to_datetime(moment_series, format='%H:%M:%S').dt.time moment_series ### 0 08:00:00 1 08:30:...
python|pandas|dataframe|performance|group-by
1
6,589
67,473,229
How to compute 2D cumulative sum efficiently
<p>Given a two-dimensional numerical array <code>X</code> of shape <code>(m,n)</code>, I would like to compute an array <code>Y</code> of the same shape, where <code>Y[i,j]</code> is the cumulative sum of <code>X[i_,j_]</code> for <code>0&lt;=i_&lt;=i, 0&lt;=j_&lt;=j</code>. If <code>X</code> describes a 2D probability...
<p>A <strong>kernel splitting</strong> method can be applied here to solve this problem very efficiently with only two <code>np.cumsum</code>: one vertical and one horizontal (or the other way since this is symatric).</p> <p>Here is an example:</p> <pre class="lang-py prettyprint-override"><code>x = np.random.randint(0...
python|performance|numpy|probability|cdf
3
6,590
67,369,710
Fill up columns in dataframe based on condition
<p>I have a dataframe that looks as follows:</p> <pre><code>id cyear month datadate fyear 1 1988 3 nan nan 1 1988 4 nan nan 1 1988 5 1988-05-31 1988 1 1988 6 nan nan 1 1988 7 nan nan 1 1988 8 nan nan 1...
<p>Do you want this?</p> <pre><code>def backword_fill(x): x = x.bfill() x = x.ffill() + x.isna().astype(int) return x df.fyear = df.groupby('id')['fyear'].transform(backword_fill) </code></pre> <p><strong>Output</strong></p> <pre><code> id cyear month datadate fyear 0 1 1988 3 ...
python|pandas
2
6,591
67,503,869
Pandas: Holding on to an output until a change happens in parameter X
<p>I am trying to identify different phases in a process. What I basically need to create is the following:</p> <ul> <li>When Parameter A &gt; certain value: Output = Phase 1; keep this value until:</li> <li>Parameter B reaches a certain value, then Output = Phase 2</li> </ul> <p>This is of course quite easy to program...
<p>The basic problem you are trying to solve is to implement a <a href="https://en.wikipedia.org/wiki/Hysteresis" rel="nofollow noreferrer">hysteresis</a> (i.e. where a state depends on history).</p> <p>Aside from that, the logic to capture intervals of <code>a</code> and <code>b</code> can be expressed using <code>pd....
python|pandas
0
6,592
34,570,177
Tensorflow: List of Tensors for Cost
<p>I am trying to work with LSTMs in Tensor Flow. I found a tutorial online where a set of sequences is taken in and the objective function is composed of the last output of the LSTM and the known values. However, I would like to have my objective function use information from each output. Specifically, I am trying to ...
<p>In your code, <code>losses</code> is a Python list. TensorFlow's <a href="https://www.tensorflow.org/versions/master/api_docs/python/math_ops.html#reduce_mean" rel="nofollow"><code>reduce_mean()</code></a> expects a single tensor, not a Python list.</p> <pre><code>losses = tf.reshape(tf.concat(1, losses), [-1, size...
python|list|machine-learning|tensorflow
3
6,593
34,564,906
Calculating the number of consecutive periods that match a condition
<p>Given the data in the <code>Date</code> and <code>Close</code> columns, I'd like to calculate the values in the <code>ConsecPeriodsUp</code> column. This column gives the number of consecutive two-week periods that the <code>Close</code> value has increased.</p> <pre><code>Date Close UpThisPeriod Co...
<p>This can be done by adapting the <code>groupby</code>, <code>shift</code> and <code>cumsum</code> trick described in the Pandas Cookbook, <a href="http://pandas.pydata.org/pandas-docs/stable/cookbook.html#grouping" rel="nofollow">Grouping like Python’s itertools.groupby</a>. The main change is in dividing by the len...
python|pandas
0
6,594
60,271,690
Why my test accuracy falls when i use more epochs for training my CNN
<p>I have a problem with my CNN. I trained my model for 50 epochs (BN, Dropouts used) and i got test accuracy 92%. After that i trained my exact same network again but for 100 epochs, with just the same tuning and generalization techniques, and my test set's accuracy fell to 79%. Due to my small data set i used data a...
<p>This is what is referred to as "overfitting." If your network had better test performance at 50 epochs, you may want to stop there.</p> <p>In this case it is likely due to having a small data set for which the network will be unable to find general patterns which fit all cases. Instead it is fitting to small recurr...
python|tensorflow|keras|conv-neural-network
1
6,595
59,992,439
Pandas subtract column values only when non nan
<p>I have a dataframe <code>df</code> as follows with about 200 columns:</p> <pre><code>Date Run_1 Run_295 Prc 2/1/2020 3 2/2/2020 2 6 2/3/2020 5 2 </code></pre> <p>I want to subtract column <code>Prc</code> from columns <code>Run_1 Run_295 Run_300</code> ...
<p>Three steps, <code>melt</code> to unpivot your dataframe</p> <p>Then <code>loc</code> to handle assignment</p> <p>&amp; <code>GroupBy</code> to reomake your original df.</p> <p>sure there is a better way to this, but this avoids loops and <code>apply</code> </p> <pre><code>cols = df.columns s = pd.melt(df,id_v...
pandas|python-3.5
1
6,596
60,327,350
Is there a way to append a list in a pandas dataframe?
<p>I have a column in a pandas <code>dataframe</code> <code>dfr</code> in which there is a empty list. When I try to append it, the entire column is changed. </p> <p>Below is the code attached.</p> <pre><code>N = 10 Nr = list(range(10)) dfr = pd.DataFrame(Nr,columns = ['ID']) dfr['Assignment'] = [[]] * dfr.shape[0] f...
<p>As mentioned by @AMC, the reason why this is happening is that the lists in your dataframe cells are identical. As a result, when you are iterating over the dataframe cells every time you are appending a number to the same list. Therefore, I suggest you to create one list per cell as follow:</p> <pre><code>for i i...
python|pandas
0
6,597
65,067,446
Custom loss function not improving with epochs
<p>I have created a custom loss function to deal with binary class imbalance, but my loss function does not improve per epoch. For metrics, I'm using precision and recall.</p> <p>Is this a design issue where I'm not picking good hyper-parameters?</p> <pre><code>weights = [np.array([.10,.90]), np.array([.5,.5]), np.arra...
<p>Since there is no MWE present it's rather difficult to be sure. In order to be as educative as possible I'll lay out some observations and remarks.</p> <p>The first observation is that your custom loss function has really small values i.e. <code>~10e-8</code> throughout training. This seems to tell your model that p...
tensorflow|machine-learning|keras|deep-learning
2
6,598
65,191,690
How to speedup the groupby.filter() operation?
<p>I have the following code with groupby function</p> <pre><code> order_diff = order.groupby(&quot;CD_QTY&quot;).filter( lambda x: x[&quot;BOX_ID&quot;].nunique() &gt; 1 ) </code></pre> <p>But the filter function is very slow</p> <p>I would like to use the transform or map function. But the result with both tran...
<p>My rule of thumb is that any pandas function that take a custom lambda will be slowed down significantly due to looping and hence perfomance-limited by the GIL.</p> <p>If you care about speed, use vectorized functions as much as possible:</p> <pre><code># Some mock data n = 10_000 np.random.seed(42) cd_qty = np.ran...
python|pandas|pandas-groupby
3
6,599
50,219,044
Why variables and constants are operations in TensorFlow?
<p>Intuitively, I expected an operation to be something that takes an input and modifies it (add, substract, divide, square root...). In fact, that's the definition of operation I found on the Internet. Then, <strong>why variables and constants are also operations in TensorFlow?</strong></p>
<p>TensorFlow generalizes your definition of operation as <em>something that takes zero or more inputs and produces zero or more outputs</em>. Concretely, a <a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/Operation" rel="nofollow noreferrer">TensorFlow Operation</a> is defined as:</p> <blockquote>...
tensorflow
2