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,500
61,000,954
parallelize loop over dataframe itertuples() rows using joblib
<p>I want to iterate over a data frame using <code>itertuples()</code>, the common way to do this:</p> <pre><code>for row in df.itertuples(): my_funtion(row) # do something with row </code></pre> <p>However now I wish to do the loop in parallel using joblib like this (which seems very straightforward to me):</p> <p...
<p>I think that dask.org satisfies my needs related with this post (following @monkut suggestion). This is an example:</p> <pre><code>import dask.dataframe as dd sd = dd.from_pandas(some_df, npartitions=40) sr = pd.Series([1,1.8,2.8,3.8,4.8,5.8]) ['col1','col2','col3','col4','col5']) # this is a meta sample of the ou...
python|pandas|joblib
1
375,501
60,806,301
Check if multi index is in two dataframes
<p>I have two dataframes with columns of state and regionname, and I'm trying to see if df2 is in df1, and add that column to df3</p> <pre><code>df1= +--------------+------------+------+ | State | RegionName | Data | +--------------+------------+------+ | New York | New York | 123 | | Jacksonville | Flo...
<p>Let us do </p> <pre><code>df1['IsIn2']=df1[['State','RegionName']].apply(tuple, axis=1).\ isin(df2[['State','RegionName']].apply(tuple, axis=1)).\ astype(int) </code></pre>
python|pandas|dataframe|isin
0
375,502
60,976,819
Beautiful soup extracting rows and data
<p>I am using Beautiful soup to pull some data from a internal site. The code provided on the links work for 4 columns of my data. There is one more data tagged as th.How can i get th on the same row with all tds. <a href="https://stackoverflow.com/questions/50633050/scrape-tables-into-dataframe-with-beautifulsoup">Scr...
<p>Solutions using library SimplifiedDoc.</p> <pre><code>from simplified_scrapy import SimplifiedDoc html = ''' &lt;table&gt; &lt;tr&gt; &lt;td&gt;Manager ID&lt;/td&gt; &lt;th&gt;Process&lt;/th&gt; &lt;td&gt;Defect Count&lt;/td&gt; &lt;td&gt;Transaction&lt;/td&gt; &lt;td&gt;DPMO&lt;/td&gt; &lt;/tr&gt; &lt;tr role = 'r...
pandas|beautifulsoup
0
375,503
61,039,197
Convert one dimensional arrays in a pandas dataframe to numbers
<p>Values of a pandas dataframe contain one dimensional arrays and i would like to convert into floats without the "[]" . Tried this but does not work . How can [0.5142399408894116] be converted to 0.5142399408894116</p> <pre><code>dfPredictions = pd.DataFrame(data = dff, dtype='float') </code></pre>
<p>Use the index operator [] on the array:</p> <pre><code>[0.5142399408894116][0] = 0.5142399408894116 </code></pre> <p>If you need to apply this to a dataframe row, use the explode method:</p> <pre><code>df = pd.DataFrame({'col': [[0.5142399408894116], [0.1423994088941165], [0.4239940889411651]]}) df col 0...
arrays|pandas|dataframe|scalar
0
375,504
61,052,538
Renaming multiple column values in Pandas
<p>I have customer reviews stored in a Pandas column 'Sentiment'. This is the result of <code>data['Sentiment'].unique()</code>:</p> <pre><code>array(['Negative', 'Positive', '?', 'Neutral', 'nan', 'positive', 'neutral', 'negative', 'Neg', 'ppos', 'ne'], dtype=object) </code></pre> <p>I am trying to group the ...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer">numpy.select</a>. Pass conditions as the first argument, the values corresponding to conditions as second and the default value which doesn't match any condition.</p> <pre><code>import numpy as np conditi...
python|pandas|replace|rename
3
375,505
61,046,262
How can I element-wise 2 Tensors with different dimensions with Broadcasting?
<p>I have a tensor called <code>inputs</code> with a <code>size</code> of <code>torch.Size([20, 1, 161, 199])</code> and another <code>mask</code> with a size of <code>torch.Size([20, 1, 199])</code>. I want to multiply them together.</p> <p>I tried:</p> <pre><code>masked_inputs = inputs * mask[..., None] </code></pr...
<p>This did it:</p> <pre><code>masked_inputs = inputs * mask.unsqueeze(2) </code></pre>
python|pytorch|tensor
0
375,506
60,812,563
Modifying the values of one column adding a word after the original value
<p>I have a pandas dataframe and I would like to modify the values of my first column adding before or after the original value the string " name ". How is the best way to do that.</p> <p>Here my dataframe :</p> <pre><code>df protein_name LEN Start End 0 Ribosomal_S9: 121 0 121 1 Ribosomal_S8...
<p>Add string with space by <code>+</code> and variable <code>name</code>:</p> <pre><code>name = 'Name' df['protein_name'] = name + ' ' + df['protein_name'] print (df) protein_name LEN Start End 0 Name Ribosomal_S9: 121 0 121 1 Name Ribosomal_S8: 129 121 250 2 Name Ribosomal...
python|pandas|dataframe
4
375,507
60,876,053
equivalent python and pandas operation for group_by + mutate + indexing column vectors within mutate in R
<p>Sample data frame in Python:</p> <pre><code>d = {'col1': ["a", "a", "a", "b", "b", "b", "c", "c", "c"], 'col2': [3, 4, 5, 1, 3, 9, 5, 7, 23]} df = pd.DataFrame(data=d) </code></pre> <p>Now I want to get the same output in Python with pandas as I get in R with the code below. So I want to get the change in pe...
<p>You don't want <code>transform</code> here. <code>transform</code> is typically used when your aggregation returns a scalar value per group and you want to broadcast that result to all rows that belong to that group in the original DataFrame. Because <code>GroupBy.pct_change</code> already returns a result indexed l...
python|pandas|pandas-groupby
2
375,508
61,031,425
Python Dataframe column of dates - change format to yyyy-mm-dd
<p>df['date'] is the column I am working with. </p> <p>The data is in the 'date' column is in the day/month/year format, like this: 7/12/2019. How would I modify this column to give me Year-month-day, or 2019-07-12? </p> <p>This is what I have tried, but still is not working: df['date'] = pd.to_datetime(str(df['date...
<p>Try:</p> <pre><code>df.loc[:,'date'] = pd.to_datetime(df.loc[:,'date'], format="%d/%m/%yyyy") </code></pre> <p>Let me know if it works!</p> <p>EDIT #1</p> <p>Since, the "date" column has mixed formats, try:</p> <pre><code>def date_format(df): for index, row in df.iterrows(): try: df.loc[...
python|pandas
1
375,509
61,067,132
Why is my custom loss (categorical cross-entropy) not working?
<p>I am working on some kind of framework for myself built on top of Tensorflow and Keras. As a start, I wrote just the core of the framework and implemented a first toy example. This toy example is just a classic feed forward network solivng XOR.</p> <p>It's probably not necessary to explain everything around it but ...
<p>You're creating a tuple of tensors for shape. That might not work. </p> <p>Why not just this?</p> <pre><code>labels = tf.keras.backend.batch_flatten(y_true) y_pred = tf.keras.backend.batch_flatten(y_pred) </code></pre> <p>The standard <code>'categorical_crossentropy'</code> loss does not perform any kind of flatt...
tensorflow|keras
1
375,510
61,081,125
Opening txt data files from url in Python
<p>I'm trying to open some data from a URL but it gives me problems and errors I don't know how to deal with. My goal is to get two arrays of data, one for time input and another for some kind of variable. This is what I've tried:</p> <pre><code>url = "https://github.com/giulio99/Relazione-FFT/blob/master/dati%20giuli...
<p>you are downloading the wrong file! you want the raw file, not the html page.<br> notice the <code>raw</code> button on that page, it will gives you the address:<br> <code>https://raw.githubusercontent.com/giulio99/Relazione-FFT/master/dati%20giulio/datilunghiquad_b.txt</code></p>
python-3.x|pandas|url
1
375,511
61,167,710
Extracting table from a website using Pandas
<p>Hi I wanted to extract a table from the url = '<a href="http://www.nativeplant.com/plants/search/input" rel="nofollow noreferrer">http://www.nativeplant.com/plants/search/input</a>' I proceeded with using Pandas in Python 3</p> <pre><code>import requests import pandas as pd url = 'http://www.nativeplant.com/plant...
<p>I don't know how to do this pd.read_html()... Moreover, when i try a simple get request with your URL no table element are returned. I bieleve this is why simple pd.read_html doesn't work.</p> <p>However,</p> <p>When U click on "UpdateList" Button, this triggers a get request for data. (F12 -> Network -> Html)</p>...
python|pandas|web|screen-scraping
0
375,512
61,147,694
No module named 'tensorflow.python.keras.engine.base_layer_v1' in python code with tensor flow keras
<p>hi i'm doing this code in google colab and i have this error <strong>No module named 'tensorflow.python.keras.engine.base_layer_v1' in python code with tensor flow keras</strong></p> <p>i did use tensorflow.keras instead of keras since i use tensorflow v=2.1.0 and keras v=2.3.0-tf</p> <pre><code>i tried both tenso...
<p>I had similar error while working with gaborNet-CNN. I tired following and it worked in my case.</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from tqdm import tqdm import keras from keras import backend as K from keras import activations, initializers, regularizers, constraints, metrics fro...
python|tensorflow|deep-learning|google-colaboratory|tf.keras
2
375,513
61,080,410
CNN accuracy y-axis range
<p>I have trained my CNN model and attained the accuracy-graph, where I saved the training epochs using pickle.</p> <p>When I code the graph, I get the the y-axis range from 0 to 1. How is it possible to have the range from 0-100 with the already saved pickle values.</p> <pre><code>from keras.models import Sequential...
<p>You can multiply the list value .i.e. 'val_accuracy' by 100. Code is given below,</p> <pre><code>val_accuracy = [i * 100 for i in history.history['val_accuracy']] plt.plot(val_accuracy) plt.title('Model Accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['Val Accuracy'], loc='upper left') plt.show() <...
python-3.x|tensorflow|keras|conv-neural-network
1
375,514
61,065,013
Loop through rows and columns of different data sets in Python
<p>I am new to Python and am struggling to loop through the rows and columns of two different datasets, to generate an array of values.</p> <p>I have two dataframes (parameterMatrix and growthRates); one shows an array of species and the strengths of their interactions, and the other shows the growth rate of each spec...
<p>Start by storing your species in a list:</p> <pre><code>species = ["herbivores", "youngScrub", "matureScrub", "sapling", "matureTree", "grassHerbs"] </code></pre> <p>Then you can loop over this list instead of manually typing out each one:</p> <pre><code>new_array = [] for outer_index, outer_animal in enumerate(...
python|pandas|loops|dataframe
2
375,515
60,965,602
Pandas assign group numbers for each time bin
<p>I have a pandas dataframe that looks like below.</p> <pre><code>Key Name Val1 Val2 Timestamp 101 A 10 1 01-10-2019 00:20:21 102 A 12 2 01-10-2019 00:20:21 103 B 10 1 01-10-2019 00:20:26 104 C 20 2 01-10-2019 14:40:45 10...
<p>Here is an example without <code>loop</code>. The main approach is round up seconds to specific ranges and use <code>ngroup()</code>.</p> <pre><code>02-10-2019 09:04:12 -&gt; 02-10-2019 09:04:11 02-10-2019 09:04:14 -&gt; 02-10-2019 09:04:11 02-10-2019 09:04:20 -&gt; 02-10-2019 09:04:11 02-10-2019 09:04:21 -&gt; 02-...
python|pandas|numpy|timestamp|grouping
1
375,516
60,987,813
Python: SettingWithCopyWarning
<p>Having read this <a href="https://www.stackoverflow.com/a/42773096/4487805">answer</a>, I tried to do the following to avoid <code>SettingWithCopyWarning</code>. </p> <p>So I did below. Yet it still generates the warning below. What have I done wrong ? </p> <pre><code>df_filtered.loc[:,'MY_DT'] = pd.to_datetime(df...
<p>Probably <code>df_filtered</code> is a sub dataframe of other one (<code>df</code>?).</p> <p>This warning means that you try to change <code>df_filtered</code> which is a slice of <code>df</code>, and it will not change <code>df</code>.</p> <p>In order to avoid this warning you can try to copy the slice:</p> <pre...
python|pandas
1
375,517
60,911,532
Pandas could not be able to read given CSV file correctly
<p>I tried below code but could not be able to correct dataframe. Please let me know the correct code to read CSV file using pandas.</p> <p>CSV file:<a href="https://drive.google.com/file/d/1cxnRl9Jz7RTWg5hddZdT7eLExs5dq_Cf/view" rel="nofollow noreferrer">CSV File</a></p> <p>My Code:</p> <pre><code>import pandas as ...
<p>Try this:</p> <pre><code>df = pd.read_csv("Data 8199 2391 6_6_2019 13_39_02.csv", delimiter="\t", skiprows=68, encoding="utf-16", index_col=0) print(df.head()) </code></pre> <p><strong>Output:</strong></p> <pre><code> Time 101 &lt;RoomTemperature&gt; (C) ... 319 &lt;DU5&...
python|pandas
1
375,518
61,017,835
How can I speed up this nested loop using pandas?
<p>I am new to python and pandas. I am trying to assign new session IDs for around 2270 users, based on the time difference between the timestamps. If the time difference exceeds 4 hours, I want a new session ID. Otherwise, it would have to remain the same. In the end, I want a modified data frame with the new session ...
<p>Filtering the whole dataframe for each user is <code>O(users*sessions)</code>, and it's not needed since you need to iterate over the whole thing anyway.</p> <p>A more efficient approach would be to instead iterate over the dataframe in one pass, and store the temporary variables (counter, location of previous row,...
python|pandas|nested-loops
0
375,519
60,819,387
Is there any way to merge csv files directly when import into pandas?
<p>I have 35 csv files and i want to merge all the files together on 'Id' column. Is there any way to merge all? I can manually do like this by uploading each file and then defining into datafame</p> <pre><code>pd.merge(df_c1, df_c2, on='uuid') </code></pre> <p>But curious if there is any smart way?</p>
<p>credit to @cs95 for <a href="http://stackoverflow.com/questions/53645882/pandas-merging-101">Pandas Merging 101</a></p> <pre><code>### read / create data frames df_c1 = pd.DataFrame({'uuid': ['A', 'B', 'C', 'D'], 'valueA': np.random.randn(4)}) df_c2 = pd.DataFrame({'uuid': ['B', 'D', 'E', 'F'], 'valueB': np.ran...
python|pandas|csv|dataframe|merge
1
375,520
61,078,946
How to Get Reproducible Results (Keras, Tensorflow):
<p>To make the results reproducible I've red more than 20 articles and added to my script maximum of the functions ... but failed. </p> <p>In the official source I red there are 2 kinds of seeds - global and operational. May be, the key to solving my problem is setting the operational seed, but I don't understand wher...
<p>As a reference from the documentation<br> Operations that rely on a random seed actually derive it from two seeds: the global and operation-level seeds. This sets the global seed.</p> <p>Its interactions with operation-level seeds are as follows:</p> <ol> <li>If neither the global seed nor the operation seed is se...
tensorflow|keras|neural-network|tensorflow2.0
8
375,521
60,843,310
Bug in numpy.shape()?
<p>I am playing with day 10 of the <a href="https://adventofcode.com/2019/day/10" rel="nofollow noreferrer">2019 advent of code challenge</a> and found <code>np.shape()</code> behaving weirdly right at the start:</p> <pre><code>In [45]: import numpy as np file = open('Day10.data') astermap = file.read() print(astermap...
<p>When you convert a list of lists into a numpy array, it only makes it all a numpy array if the inner lists are of the same length. Otherwise, it makes an array of python lists.</p> <p>Example:</p> <p>Running <code>np.array(list(map(list,(" asdf fdsa".split()))))</code> returns:</p> <pre><code>array([['a', 's', 'd...
python|numpy
0
375,522
61,024,276
How to implement a custom cost function in keras?
<p>I have a following cost function= argmin L1+L2 , where L1 is Mean Squared Error and L2 is -λ Summation( Square((y) x (z) )) where y is the predicted output image and z is the given input image to model. Elementwise multiplication of y and z and then taking square of it. λ is a trade off parameter between L1 and L2....
<p>To break your question part by part</p> <blockquote> <p>where L1 is Mean Squared Error </p> </blockquote> <p>Thus, <code>L1 = np.square(np.subtract(y_true,y_pred)).mean()</code></p> <blockquote> <p>L2 is -λ Summation( Square((y) x (z) )) where y is the predicted output image and z is the given input image ...
python|python-3.x|tensorflow|keras|deep-learning
0
375,523
61,134,924
train on multiple devices
<p>I have know that TensorFlow offer Distributed Training API that can train on multiple devices such as multiple GPUs, CPUs, TPUs, or multiple computers ( workers) Follow this doc : <a href="https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras" rel="nofollow noreferrer">https://www.tensorflow.org/t...
<p>As per my knowledge, Tensorflow only supports CPU, TPU, and GPU for distributed training, considering all the devices should be in the same network.</p> <p>For connecting multiple devices, as you mentioned you can follow <a href="https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras" rel="nofollow ...
tensorflow|machine-learning|distributed-training
1
375,524
60,767,017
ImportError: DLL load failed while importing aggregations: The specified module could not be found
<p>I am new to Python and currently having trouble when <strong>importing</strong> some libraries.</p> <p>I am using Python 3.8.</p> <p>I have installed Pandas in the CMD using "pip install pandas"</p> <p>If i go to Python folder i see that Pandas is installed:</p> <p>C:\Users\VALENTINA\AppData\Local\Programs\Pytho...
<p>I was facing the same problem. I am using <code>python 3.7.5</code>. By default <code>pip install pandas</code> command install version 1.0.3. So i revert to version 1.0.1.</p> <pre><code>pip uninstall pandas pip install pandas==1.0.1 </code></pre> <p>Now it is working without error. You may try it.</p>
python|pandas|visual-studio-code
24
375,525
60,977,414
Getting complex coefficients in nearest SPD matrices
<p>I am writing a python 3.7 program and I need to get symmetric positive-definite matrices.</p> <p>I used this code to get the nearest SPD (all eigenvalues have to be > 0) :</p> <p><a href="https://stackoverflow.com/questions/43238173/python-convert-matrix-to-positive-semi-definite?noredirect=1&amp;lq=1">Python: con...
<p>In fact, using the package geomstats, I found a solution.</p> <p>This is exclusively for SPD matrices.</p> <p>There is a function to directly compute the riemannian exponential, and even one to compute <code>A**t</code> for <code>A</code> SPD and <code>t</code> real.</p> <p>I recommend using the last version of g...
python|numpy|matrix
0
375,526
60,908,529
Pulling data from a queue in background thread in python process
<p>Assuming you are processing a live stream of data like this:</p> <p><a href="https://i.stack.imgur.com/YsP92.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YsP92.png" alt="async_loading_of_queued_data_in_python_process"></a></p> <p>What would be the best way to have a background <code>Thread</c...
<p>Write an update function and periodically run a background thread. </p> <pre><code>def update_data(data): pass </code></pre> <pre><code>import threading def my_inline_function(some_args): # do some stuff t = threading.Thread(target=update_data, args=some_args) t.start() # continue doing stuff ...
python|pandas|multithreading|asynchronous|queue
2
375,527
71,737,532
python pandas : building a recommender (question)
<p><em><strong>Hello and welcome to this post, i really appreciate your help</strong></em></p> <p>i'm building a food recommender, and i came accross two questions that are making me stuck :</p> <p>As you can see my dataset has a column of &quot;Ingredients&quot;, and columns for nutritional values such as sodium, prot...
<p>In row 3 in Ingredients column the value is a list, so you have to unpack them first</p>
python|pandas|dataframe|indexing
0
375,528
71,753,163
Can't manage to open TensorFlow SavedModel for usage in Keras
<p>I'm kinda new to TensorFlow and Keras, so please excuse any accidental stupidity, but I have an issue. I've been trying to load in models from the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md" rel="nofollow noreferrer">TensorFlow Detection Zoo</a>, bu...
<p>Since you are new to Tensorflow (and I guess deep learning) I would suggest you stick with the API because the detection zoo models best interface with the object detection API. If you have already downloaded the model, you just need to export it using the exporter_main_v2.py script. This article explains it very we...
tensorflow|keras
0
375,529
71,606,580
Append row in pandas without iterrows()
<p>Given the pandas dataframe with three loans, I need to add to the dataframe the payments, where the payment amount is total loan amount / number of payments. If seq = 0, is the loan amount, else seq is the payment number. I can do this with <code>iterrows()</code> however the dataframe is very large and I would lik...
<p>Update:</p> <pre><code>df_pay = df.iloc[df.index.repeat(df['payments'])]\ .eval('amount = amount / payments')\ .assign(payments=0) df_pay['seq'] = df_pay.groupby('id').cumcount() + 1 pd.concat([df, df_pay], ignore_index=True) </code></pre> <p>Output:</p> <pre><code> id seq amount paymen...
python|pandas
1
375,530
71,560,363
Pandas: Plotting / annotating from DataFrame
<p>There is this boring dataframe with stock data I have:</p> <pre><code>date close MA100 buy sell 2022-02-14 324.95 320.12 0 0 2022-02-13 324.87 320.11 1 0 2022-02-12 327.20 321.50 0 0 2022-02-11 319.61 320.71 0 1 </code></pre> <p>Then I am plotting the...
<p>You can query the data frame for sell/buy and scatter plot:</p> <pre><code>fig, ax = plt.subplots() df.plot(x='date', y=['close', 'MA100'], ax=ax) df.query(&quot;buy==1&quot;).plot.scatter(x='date', y='close', c='g', ax=ax) df.query(&quot;sell==1&quot;).plot.scatter(x='date', y='close', c='r', ax=ax) </code></pre> <...
python|pandas|matplotlib
1
375,531
71,508,824
How to handle hidden-cell output of 2-layer LSTM in PyTorch?
<p>I have made a network with a LSTM and a fully connected layer in PyTorch. I want to test how an increase in the LSTM layers affects my performance.</p> <p>Say my input is (6, 9, 14), meaning batch size 6, sequence size 9, and feature size 14, and I'm working on a task that has 6 classes, so I expect a 6-element one-...
<p>The hidden state shape of a multi layer lstm is <code>(layers, batch_size, hidden_size)</code> <a href="https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html" rel="nofollow noreferrer">see output LSTM</a>. It contains the hidden state for each layer along the 0th dimension.</p> <p>In your example you convert ...
python|pytorch|time-series|lstm|sequence
1
375,532
71,460,510
What is tensor flows row reduction algorithm?
<p>I'm wondering what tensor flow uses to perform row reduction. Specifically when I call <code>tf.linalg.inv</code> what algorithm runs? Tensorflow is open source so I figured that it would be easy enough to find but I find myself a little lost in the code base. If I could just get a pointer to the implementation of t...
<p>The op uses LU decomposition with partial pivoting to compute the inverses. For more insighton tf.linalg.inv algorithm please refer to this link: <a href="https://www.tensorflow.org/api_docs/python/tf/linalg/inv" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/linalg/inv</a></p> <p>-</p> <p>I...
algorithm|tensorflow|open-source
0
375,533
71,570,565
Python apply element-wise operation between to series where every element is a list
<p>I have to series, where every element of the series is a list:</p> <pre><code>s1 = pd.Series([[1,2,3],[4,5,6],[7,8,9]]) s2 = pd.Series([[1,2,3],[1,1,1],[7,8,8]]) </code></pre> <p>And I want to calculate element-wise <code>sklearn.metrics.mean_squared_error</code>, so I will get:</p> <pre><code>[0, 16.666, 0.33] </co...
<p>First of all, you can't construct the Series like that, it will throw an error. What you probably meant was this:</p> <pre><code>s1 = pd.Series([[1,2,3],[4,5,6],[7,8,9]]) s2 = pd.Series([[1,2,3],[1,1,1],[7,8,8]]) </code></pre> <p>With these Series, you have a few options. You can use zip to create an object in which...
python|pandas|dataframe|data-science|series
1
375,534
71,486,368
Build a pandas Dataframe from multiple "Counter" Collection objects
<p>I am working with sequence DNA data, and I would like to count the frequency of each letter (A,C,G,T) on each sequence in my dataset.</p> <p>For doing so, I have tried the following using <code>Counter</code> method from <code>Collections</code> package, with good results:</p> <pre><code>df = [] for seq in pseudomon...
<p>Make a series out of each, and use <code>pd.concat</code> with <code>axis</code>, and tranpose:</p> <pre><code>df = pd.concat([pd.Series(c) for c in l], axis=1).T </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df C A G T 0 2156779 1091782 2143630 1090617 1 2101448 1055877 2...
python|pandas|dataframe|counter
2
375,535
71,634,307
Why does it shows "fatal: Too many arguments."?
<p>I am trying to clone the repo at my folder but I am getting this error although I succeed to create folder labeling in folder named Tesnsorflow but then it's giving me this error <strong>fatal: Too many arguments.</strong> instead of clone the repo</p> <pre><code>LABELIMG_PATH = os.path.join('Tensorflow', 'labelimg'...
<p>I don't know that strange syntax for executing shell command from Python.</p> <p>But the URL should be be definitively ONE argument, not three</p> <pre><code>https: // github.com/tzutalin/labelImg // not good https://github.com/tzutalin/labelImg // should be better :-) </code></pre>
python-3.x|git|tensorflow|jupyter-notebook
1
375,536
71,676,189
pandas, update dataframe values ​with a not in the same format dataframe
<p>i have two dataframes. The second dataframe contains the values ​​to be updated in the first dataframe. df1:</p> <pre><code>data=[[1,&quot;potential&quot;],[2,&quot;lost&quot;],[3,&quot;at risk&quot;],[4,&quot;promising&quot;]] df=pd.DataFrame(data,columns=['id','class']) id class 1 potential 2 lost 3 at ris...
<p>We can use <code>DataFrame.update</code></p> <pre><code>df = df.set_index('id') df.update(df2.set_index('id')) df = df.reset_index() </code></pre> <p>Result</p> <pre><code>print(df) id class 0 1 potential 1 2 new 2 3 at risk 3 4 loyal </code></pre>
python|pandas|dataframe
1
375,537
71,638,571
Extract a subset given two dates from a python dataframe with timezone date format
<p>I have the following dataframe:</p> <pre><code>| ID | date | |---------------------|--------------------------------| | 1 | 2022-02-03 22:01:12+01:00 | | 2 | 2022-02-04 21:11:21+01:00 | | 3 | 2022-02-05 11:...
<p>You can change the <code>start_date</code> &amp; <code>end_date</code> to timezone aware before passing the parameter to the function as below.</p> <pre><code>import pytz start_date = pytz.utc.localize(start_date) end_date = pytz.utc.localize(end_date) </code></pre>
python|pandas|datetime
0
375,538
71,722,041
Different array dimensions causing failure to merge two images into one
<p><a href="https://i.stack.imgur.com/0w1TF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0w1TF.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/ICQ8A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ICQ8A.png" alt="enter image description here" />...
<p>You can manually add a row/column with a color of your choice to match the shapes. Or you can simply let cv2.resize handle the resizing for you. In this code I show how to use both methods.</p> <pre><code>import numpy as np import cv2 img1 = cv2.imread(&quot;image_home.png&quot;) img2 = cv2.imread(&quot;image_away....
python|arrays|numpy
2
375,539
71,624,121
Remove rows from DataFrame when X, Y coordinates are within a threshold distance of another row
<p>I'm trying to remove rows from a DataFrame that are within a Euclidean distance threshold of other points listed in the DataFrame. So for example, in the small DataFrame provided below, two rows would be removed if a <code>threshold</code> value was set equal to 0.001 (1 mm: <code>thresh = 0.001</code>), where <cod...
<p>Let's try it with this one. Calculate the Euclidean distance for each pair of (X,Y), which creates a symmetric matrix. Then mask the upper half; then for the lower half, filter out the rows where there is a value less than <code>thresh</code>:</p> <pre><code>import numpy as np m = np.tril(np.sqrt(np.power(df[['X']]....
python|pandas|dataframe
2
375,540
71,731,100
Pandas Groupby Syntax explanation
<p>I am confused why A Pandas Groupby function can be written both of the ways below and yield the same result. The specific code is not really the question, both give the same result. I would like someone to breakdown the syntax of both.</p> <pre><code>df.groupby(['gender'])['age'].mean() df.groupby(['gender']).mean(...
<blockquote> <p>It reads as if you are calling the <code>.mean()</code> function on the age column specifically. The second appears like you are calling <code>.mean()</code> on the whole groupby object and selecting the age column after?</p> </blockquote> <p>This is exactly what's happening. <code>df.groupby()</code> r...
python|pandas|syntax|pandas-groupby
2
375,541
71,512,400
sentiment analysis of a dataframe
<p>i have a project that involves determining the sentiments of a text based on the adjectives. The dataframe to be used is the adjectives column which i derived like so:</p> <pre><code>def getAdjectives(text): blob=TextBlob(text) return [ word for (word,tag) in blob.tags if tag == &quot;JJ&quot;] dataset['ad...
<p>Try this:</p> <pre><code>dataset = dataset.explode(&quot;adjectives&quot;) </code></pre> <p>Note that <code>[]</code> will result in a <code>np.NaN</code> row which you might want to remove beforehand/afterwards.</p>
python|pandas
0
375,542
71,513,521
How to get reverse diagonal from a certain point in a 2d numpy array
<p>Let's say I have a n x m numpy array. For example:</p> <pre><code>array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]) </code></pre> <p>Now I want both diagonals intersection with a certain point (for example (1,2) which is 8). I already know that I can get the ...
<p>You can use <code>np.eye</code> to create a diagnal line of 1's, and use that as a mask:</p> <pre><code>x, y = np.nonzero(a == 8) k = y[0] - a.shape[0] + x[0] + 1 nums = a[np.eye(*a.shape, k=k)[::-1].astype(bool)][::-1] </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; nums array([16, 12, 8, 4]) </code></pre> ...
python|numpy
1
375,543
71,580,656
How to merge the results of an API call inside a loop to a pandas data frame?
<p>Hi apologies for the noob question...</p> <p>I have written some code:</p> <pre><code>with RESTClient(key) as client: from_ = &quot;2020-01-09&quot; to = &quot;2021-01-10&quot; for i in all_tickers: ticker = i['ticker'] r = client.stocks_equities_aggregates(ticker, 1, &quot;day&quot;, f...
<p>With the line below, you're overwriting the variable <code>df</code> with every loop in your <code>for i in all_tickers</code> for loop:</p> <pre><code>df = pd.DataFrame(r.results, columns=[&quot;t&quot;, &quot;v&quot;, &quot;vw&quot;, &quot;o&quot;, &quot;c&quot;, &quot;h&quot;, &quot;l&quot;, &quot;n&quot;]) </cod...
python|pandas|jupyter-notebook|polygon.io
1
375,544
71,646,596
Compute metrics/loss every n batches Pytorch Lightning
<p>I'm trying to use Pytorch lighning but I don't have clear all the steps. Anyway I'm trying to calculate the train_loss (for example) not only for each step(=batch) but every n bacthes (i.e. 500) but I'm not sure how to compute it (compute, reset etc). I tried this approach but this is not working. Can you help me? t...
<ol> <li>Write your custom logger following (<a href="https://pytorch-lightning.readthedocs.io/en/stable/extensions/logging.html#make-a-custom-logger" rel="nofollow noreferrer">https://pytorch-lightning.readthedocs.io/en/stable/extensions/logging.html#make-a-custom-logger</a>). The one I present here stores the values ...
python|pytorch|pytorch-lightning
1
375,545
71,545,135
How to append rows with concat to a Pandas DataFrame
<p>I have defined an empty data frame with:</p> <pre><code>insert_row = { &quot;Date&quot;: dtStr, &quot;Index&quot;: IndexVal, &quot;Change&quot;: IndexChnge, } data = { &quot;Date&quot;: [], &quot;Index&quot;: [], &quot;Change&quot;: [], } df = pd.DataFrame(data) df = df.append(insert_row, ign...
<p>Create a dataframe then <code>concat</code>:</p> <pre><code>insert_row = { &quot;Date&quot;: '2022-03-20', &quot;Index&quot;: 1, &quot;Change&quot;: -2, } df = pd.concat([df, pd.DataFrame([insert_row])]) print(df) # Output Date Index Change 0 2022-03-20 1.0 -2.0 </code></pre>
python|pandas|dataframe
7
375,546
71,668,874
Protobuf compatibility error when running Kedro pipeline
<p>I have a Kedro pipeline that I want to run through a Python script, I think I have the minimum necessary code to do this, but everytime I try to run the pipeline through the script, I get a compatibility error regarding the protobuf version, but when I run the pipeline through the terminal it runs without problems. ...
<p>I faced a similar problem with kedro. This helped:</p> <pre><code>pip install --upgrade &quot;protobuf&lt;=3.20.1&quot; </code></pre>
python|docker|tensorflow|protocol-buffers|kedro
1
375,547
71,468,110
pandas extract first row column value equal to 1 for each group
<p>I have df:</p> <pre><code>date id label pred 1/1 1 0 0.2 2/1 1 1 0.5 1/1 2 1 0.9 2/1 2 1 0.3 </code></pre> <p>I want for each id, get the first row when label column equal to 1. for example desire df:</p> <pre><code>date id label pred 2/1 1 1 ...
<p>First filter only rows with <code>label=1</code> and then remove duplicates per <code>id</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="noreferrer"><code>DataFrame.drop_duplicates</code></a>:</p> <pre><code>df1 = df[df['label'].eq(1)].drop_dup...
python|pandas
5
375,548
71,789,096
how to pad sequences in a tensor slice dataset in TensorFlow?
<p>I have a tensor slice dataset made from two ragged tensors.</p> <p>tensor_a is like: <code>&lt;tf.RaggedTensor [[3, 3, 5], [3, 3, 14, 4, 17, 20], [3, 14, 22, 17]]&gt;</code></p> <p>tensor_b is like: <code>&lt;tf.RaggedTensor [[-1, 1, -1], [-1, -1, 1, -1, -1, -1], [-1, 1, -1, 2]]&gt;</code></p> <p>(Same index, same l...
<p>You could try something like this:</p> <pre><code>import tensorflow as tf tensor_a = tf.ragged.constant([[3, 3, 5], [3, 3, 14, 4, 17, 20], [3, 14, 22, 17]]) tensor_b = tf.ragged.constant([[-1, 1, -1], [-1, -1, 1, -1, -1, -1], [-1, 1, -1, 2]]) dataset = tf.data.Dataset.from_tensor_slices((tensor_a, tensor_b)) max_l...
python|tensorflow|padding|ragged-tensors
0
375,549
71,481,088
How to use rolling function to compare the elements
<p>I want to use <code>pandas</code> <code>rolling</code> function to compare whether the first element is smaller than the second one. I think the following codes should work:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame(data=np.random.randint(0,10,10), c...
<p>Replacing the x[n] with x.iloc[n] should work (using positional indexing)</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame(data=np.random.randint(0,10,10), columns=['temperature']) df['increasing'] = df.rolling(window=2).apply(lambda x: x.iloc[0] &lt; x.ilo...
python|pandas
1
375,550
71,561,374
Pandas df get previous row value
<p>I have a pandas dataframe with null values:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>fecha</th> <th>code</th> <th>Place</th> <th>dato1</th> <th>porcentaje_dato1</th> <th>dato2</th> <th>dato3</th> <th>porcentaje_dato3</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>2...
<p>Here's my approach.</p> <pre class="lang-py prettyprint-override"><code># Sort dataframe df = (pd.read_csv(data) .sort_values(['Place','fecha'] .reset_index()) # Fill missing values for dato2 with dato1 df['dato2'] = df.dato2.fillna(df.dato1) # Calculate the aggregate, store in separate df df_agg =...
python|pandas|dataframe
0
375,551
71,774,433
Im trying to plot 2 lines in one graph that exist in the same column using matplotlib
<p>the values exist in one column and I would like to display them both on the same graph rather than an 2 separate ones <a href="https://i.stack.imgur.com/g1YB0.png" rel="nofollow noreferrer">https://i.stack.imgur.com/g1YB0.png</a> <a href="https://i.stack.imgur.com/Uyal5.png" rel="nofollow noreferrer">https://i.stack...
<pre class="lang-py prettyprint-override"><code>plt.plot(x, y) plt.plot(x2, y2) </code></pre>
python|pandas|matplotlib
0
375,552
71,675,197
building mask for 2d array by index
<p>Consider the following mask:</p> <pre class="lang-py prettyprint-override"><code>def maskA(n): assert((n % 2) == 0) sample_arr = [False, False] bool_arr = np.random.choice(sample_arr, size=(n, n)) # print(bool_arr.shape) for i in range(n): for j in range(n): if (i &gt;= n//2...
<p>You can use indexing to assign values instead of using for-loops.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def maskA(n): assert((n % 2) == 0) bool_arr = np.full((n, n), True) bool_arr[0:int(n/2), 0:int(n/2)] = False bool_arr[int(n/2):n, int(n/2):n] = False return ...
python|numpy
1
375,553
71,763,939
typecast/transform each element of list of lists to appropriate type
<p>I am looking for a way to typecast or transform each element of this list of lists, to the appropriate type.</p> <p>The list needs to be inserted in a SQL database, so every first element of the list of lists might be typecasted to a <code>str</code>, the second to a <code>str</code>, the third to a <code>float</cod...
<p>I think you could get it to work faster if you use Pandas:</p> <pre class="lang-py prettyprint-override"><code> arr = [[&quot;myfirstcolumn&quot;, &quot;second&quot;, &quot;3&quot;, &quot;False&quot;, &quot;20200102&quot;], [&quot;myfirstcolumn&quot;, &quot;second&quot;, &quot;2&quot;, &quot;True&quot;, &quot...
python|algorithm|numpy
3
375,554
71,672,635
Automate creating subtables based on values of one column
<p>Suppose i have a df with a column X with the following unique values ('A', 'B', 'C')</p> <p>I want to create a function that will create dataframes containing only the items for such unique value of column X. How best to do this?</p> <p>I would usually write line of codes by filtering it but I want to know how best ...
<p>Try this:</p> <pre><code>sub_dfs = [df[df['X']== i] for i in list(df['X'].unique())] </code></pre>
python|pandas
1
375,555
71,634,924
Copy and split row by if cell condition it met - Pandas Python
<p>I am trying to overcome the issue when I have a cell with specific char(';') which I would like to copy the same line with the amount if splitters that specific cell in specific col got. For example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Index</th> <th>Name</th> <th>Age</th> <t...
<p>Possible solution is the following:</p> <pre><code>import pandas as pd # set data and create dataframe data = {&quot;Name&quot;: [&quot;David&quot;, &quot;Oshir&quot;], &quot;Age&quot;: [45, 32], &quot;Car&quot;: [&quot;Honda;Subaru&quot;, &quot;BMW&quot;]} df = pd.DataFrame(data) df = df.assign(Car=df['Car'].str....
python|pandas|dataframe|duplicates
1
375,556
71,443,753
Pandas Drop duplicates, reverse of subset
<p>I want to drop duplicates on my dataframe. I know I can use <code>subset</code> to type out all columns I want to perform it on, however I have 50+ columns. Is there a way to include all columns and exclude a subset?</p> <p>For example include column B,C,D,E,G,H,I, etc. and exclude A and F.</p> <p>Something like: <c...
<p>Maybe this could be an approach for you (List comprehension)?</p> <pre><code>df = pd.DataFrame({ 'A': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'], 'B': ['cup', 'cup', 'cup', 'pack', 'pack'], 'F': [4, 4, 3.5, 15, 5] }) df.drop_duplicates(subset=[val for val in df.columns if val != &quot;A&quo...
pandas
1
375,557
71,511,129
Write a function that takes as input a list of these datetime strings and returns only the date in 'yyyy-mm-dd' format
<p>i want to write a function that takes as input a list of these datetime strings and returns only the date in 'yyyy-mm-dd' format.</p> <p>This is the dataframe</p> <pre><code>twitter_url = 'https://raw.githubusercontent.com/Explore-AI/Public-Data/master/Data/twitter_nov_2019.csv' twitter_df = pd.read_csv(twitter_url...
<p>You can try using regex:</p> <pre><code>new_date_list = [] </code></pre> <p>and then inside the loop:</p> <pre><code>new_date_list.append(re.findall(r&quot;^\d{4}(-|\/)(0[1-9]|1[0-2])(-|\/)(0[1-9]|[12][0-9]|3[01])$&quot;,date)) </code></pre>
python|pandas|datetime
1
375,558
71,590,935
Sample Pandas dataframe based on multiple values in column
<p>I'm trying to even up a dataset for machine learning. <a href="https://stackoverflow.com/questions/56191448/sample-pandas-dataframe-based-on-values-in-column">There are great answers</a> for how to sample a dataframe with two values in a column (a binary choice).</p> <p>In my case I have many values in column <code>...
<p>IIUC, you could <code>groupby</code> on the condition whether &quot;x&quot; is 0 or not and <code>sample</code> the smallest-group-size number of entries from each group:</p> <pre><code>g = df.groupby(df['x']==0)['x'] out = g.sample(n=g.count().min()).sort_index() </code></pre> <p>(An example) output:</p> <pre><code...
python|python-3.x|pandas|dataframe|pandas-groupby
2
375,559
71,612,775
if condition not meet, leave blank python code
<p>how should we write the code that tell python to leave empty cell in dataframe when the condition is not meet?</p> <p>I tries &quot; &quot; like excel but it does not work. I tried 'space' also not work either.</p> <p>eg. np.where((df['Adj Close']&gt; df['signal']), 1, 'what should be the sign here? ' )</p> <p>Thank...
<p>If need empty numeric value use missing value <code>NaN</code>:</p> <pre><code>np.where(df['Adj Close']&gt; df['signal'], 1, np.nan) </code></pre>
python-3.x|pandas|dataframe
1
375,560
71,491,932
Why I get "RuntimeError: CUDA error: the launch timed out and was terminated" when using Google Cloud compute engine
<p>I have a Google cloud compute engine with 4 Nvidia K80 GPU and Ubuntu 20.04 (python 3.8). When I try to train the yolo5 model, I get the following error:</p> <pre><code>RuntimeError: CUDA error: the launch timed out and was terminated CUDA kernel errors might be asynchronously reported at some other API call,so the ...
<p>We are also running CUDA in the Google Cloud and our server restarted roughly when you posted your question. While we couldn't detect any changes, our service couldn't start due to &quot;RuntimeError: No CUDA GPUs are available&quot;. So there are some similarities, but also some differences.</p> <p>Anyway, we opted...
google-cloud-platform|pytorch|google-compute-engine|nvidia|yolo
1
375,561
71,488,685
How can I properly format a pandas dataframe into JSON?
<p>I have this function that takes in a JSON, transforms it to a pandas dataframe, does a calculation and attempts to return it in proper json form.</p> <p>Here's what the function looks like:</p> <pre><code>def run(data): try: start_time = datetime.datetime.now() ret_columns = [&quot;operat_flight_...
<p>Add <code>orient='records'</code> to your <code>to_json()</code> call:</p> <pre><code> return {&quot;data&quot; : json.loads(df[ret_columns].to_json(date_format=&quot;iso&quot;, orient=&quot;records&quot;)), &quot;predictions&quot; : predictions, &quot;elapsed_time_ms&quot; : elapsed_time_ms } </code></pre>
json|pandas
0
375,562
71,577,370
Convert pandas column of json-like strings to DataFrame
<p>I have the following DataFrame that I get &quot;as-is&quot; from an API:</p> <pre><code>df = pd.DataFrame({'keys': {0: &quot;[{'contract': 'G'}, {'contract_type': 'C'}, {'strike': '560'}, {'strip': '10/1/2022'}]&quot;, 1: &quot;[{'contract': 'G'}, {'contract_type': 'P'}, {'strike': '585'}...
<p>You could use <code>ast.literal_eval</code> (built-in) to convert the dict strings to actual dicts, and then use <code>pd.json_normalize</code> with <code>record_path=[[]]</code> to get the objects into a table format:</p> <pre><code>import ast new_df = pd.json_normalize(df['keys'].apply(ast.literal_eval), record_pa...
python|pandas
2
375,563
71,664,909
How to load a model using Tensorflow Hub and make a prediction?
<p>This should be a simple task: Download a model saved in tensorflow_hub format, load using tensorflow_hub, and use..</p> <p>This is the model I am trying to use (simCLR stored in Google Cloud): <a href="https://console.cloud.google.com/storage/browser/simclr-checkpoints/simclrv2/pretrained/r50_1x_sk0;tab=objects?page...
<p>As @Frightera pointed out, there was an error with the input shapes. Also the error on &quot;Attempt 2&quot; was solved by allowing for memory growth on the selected GPU. &quot;Attempt 3&quot; still does not work, but at least there are two methods for loading and using a model saved in /hub format:</p> <pre><code>i...
tensorflow|deep-learning|tensorflow-hub
0
375,564
71,616,860
Passing pandas subset of dataframe to lambda function
<p>I am trying to pass a subset of my dataframe rows — conditioned with <code>'rating_count' &gt; m</code> — to the 'weighted_rating' function. However, the passed data contains only the 'user_id' column while it's expected to contain several other columns. As the result I receive the <code>KeyError</code> on the line ...
<p>I assume you want to apply <code>weighted_rating()</code> to each row of the dataframe <code>final_data</code>. In order to do that, you need to pass <code>axis=1</code> to apply() method.</p> <pre><code>final_data['weighted_rating'] = final_data[final_data['rating_count'] &gt;= m].apply(lambda x: weighted_rating(x)...
python|pandas|dataframe
0
375,565
71,640,405
I'm unable to convert my Src IP column into type integer using Python
<p>I am currently attempting to apply <code>int</code> to this column type, but it's throwing me an error.</p> <pre><code>int(ipaddress.IPv4Address(df['Src IP'])) </code></pre> <p>My error traceback is:</p> <pre><code>AddressValueError: Expected 4 octets in '0 172.27.224.251\n1 172.27.224.251\n2 172.27...
<p>Use:</p> <pre><code>df['new'] = df['Src IP'].map(ipaddress.IPv4Address).astype(int) print(df) # Output Src IP new 0 172.27.224.251 2887508219 1 172.27.224.251 2887508219 2 172.27.224.250 2887508218 3 172.27.224.251 2887508219 4 172.27.224.250 2887508218 22619 17...
python|pandas|ip-address|data-conversion
0
375,566
71,546,900
Weird `glibc==2.17` conflict when trying to conda install tensorflow 1.4.1
<p>I'm trying to create a new conda enviornment with tensorflow (GPU), version 1.4.1 with the following command <code>conda create -n parsim_1.4.1 python=3 tensorflow-gpu=1.4.1</code>.</p> <p>However, it prints a weird conflict:</p> <pre><code>$ conda create -n parsim_1.4.1 python=3 tensorflow-gpu=1.4.1 Collecting pack...
<p>Conda's error reporting <a href="https://stackoverflow.com/a/69137255/570918">isn't always helpful</a>. Mamba is sometimes better, and in this particular case it gives:</p> <pre class="lang-bash prettyprint-override"><code>Looking for: ['python=3', 'tensorflow-gpu=1.4.1'] conda-forge/linux-64 ...
python|tensorflow|conda
4
375,567
71,709,830
Pandas function for showing aggfunc at every level
<p>Let's propose I have a pivot table that looks like this:</p> <pre><code>pd.pivot_table( data, columns=['A','B','C'], values='widgets', aggfunc='count' ).T </code></pre> <pre><code>[Column] Count A B C 1 D 2 E F 3 G 4 H I J 5 K L 6 </code></pre> <p>What I want is:</p> <pre><code...
<p>Make sure index levels are named:</p> <pre><code>df = pd.DataFrame( {'Count': [1, 2, 3, 4, 5, 6]}, pd.MultiIndex.from_tuples([ ('A', 'B', 'C'), ('A', 'B', 'D'), ('A', 'E', 'F'), ('A', 'E', 'G'), ('H', 'I', 'J'), ('H', 'K', 'L') ], names=['One', 'Two', 'Thre...
pandas|pandas-groupby|data-visualization|pivot-table
2
375,568
71,549,342
How to read .dta into Python
<p>I want to read data from <a href="http://fmwww.bc.edu/ec-p/data/wooldridge/401k.dta" rel="nofollow noreferrer">http://fmwww.bc.edu/ec-p/data/wooldridge/401k.dta</a>. I tried below,</p> <pre><code>import pandas as pd import pyreadstat as pyreadstat dataframe, meta = pyreadstat.read_dta(&quot;http://fmwww.bc.edu/ec-p...
<pre><code>import requests import pyreadstat url = 'http://fmwww.bc.edu/ec-p/data/wooldridge/401k.dta' def download_file(url): local_filename = url.split('/')[-1] with requests.get(url, stream=True) as r: r.raise_for_status() with open(local_filename, 'wb') as f: for chunk in r.ite...
python|python-3.x|pandas
1
375,569
71,592,500
performing function in for loop help? python
<p>Hello everyone I'm in the final step of my program to send in calendar but I can't seem to get my for loop to perform the function over the list. It only reads for 1 of the 3 in list. Here is my code below.</p> <pre><code>Order List = ['0730049','4291200','1830470'] for eachId in Order_List: **Code to create orders...
<p><code>df_list</code> isn't a list of all the filenames. You're overwriting it with just one filename each time through the loop.</p> <p>Use a list comprehension to get all of them.</p> <pre><code>df_list = [f'OrderId_{eachId}.xlsx' for eachId in Order_List] </code></pre> <p>But you may not even need that variable, j...
python|pandas|dataframe|for-loop
2
375,570
71,465,356
Making a column with differences between 2 other column
<p>I already started a similar topick, but few essential novelties are brought in. We have two columns: &quot;333, 444, 555&quot;, and &quot;333A, 444, 555B&quot;, and we need to get a column shewing &quot;A, n/a, B&quot;, i.e. difference in values between the two.</p> <pre><code>one= '' for h in str(column1): if h...
<p>IIUC, use <code>difflib</code>:</p> <pre><code>from difflib import ndiff diff = lambda x: ''.join(c[-1] for c in ndiff(x['Col1'], x['Col2']) if c[0] == '+') df['Col3'] = df.astype({'Col1': str, 'Col2': str}).apply(diff, axis=1) print(df) # Output Col1 Col2 Col3 0 333 333A A 1 444 444 2 555 55...
python|pandas
0
375,571
71,585,905
Python - pandas: create a separate row for each recurrence of a record
<p>I have date-interval-data with a &quot;periodicity&quot;-column representing how frequent the date interval occurs:</p> <ul> <li>Weekly: same weekdays every week</li> <li>Biweekly: same weekdays every other week</li> <li>Monthly: Same DATES every month</li> </ul> <p>Moreover I have a &quot;recurring_until&quot;-colu...
<p>First of all preprocess:</p> <pre><code>df.set_index(&quot;id&quot;, inplace=True) df[&quot;from&quot;], df[&quot;to&quot;], df[&quot;recurring_until&quot;] = pd.to_datetime(df[&quot;from&quot;]), pd.to_datetime(df.to), pd.to_datetime(df.recurring_until) </code></pre> <p>Next compute all the periodic <code>from</cod...
python|pandas
0
375,572
71,573,477
Import numpy can't be resolved ERROR When I already have numpy installed
<p>I am trying to run my chatbot that I created with python, but I keep getting this error that I don't have numpy installed, but I do have it installed and whenever I try to install it it tells me that it is already installed. The error reads <code>&quot;ModuleNotFoundError: No module named 'numpy'&quot;</code></p> <...
<p>I fixed the problem by deleting a python folder that was in the root directory of C:/ which caused installing the package to be ignored and not be installed in the correct directory which is in C:/Users/</p>
python|numpy
0
375,573
71,752,250
How could I generate a 2D array from a known slope and aspect value?
<p>Given a dummy heightmap (or digital elevation model) stored as a Numpy array like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt line = np.flip(np.arange(0, 10)) dem = np.tile(line, (10, 1)) </code></pre> <p>I can calculate its slope and aspect like this:</p> <pre><code>x, y = np.gradient(d...
<p>Since <code>gradient</code> assumes a step size of 1, the general formula for making a line with <code>N</code> points and a given <code>slope</code> and <code>offset</code> is</p> <pre><code>slope * np.arange(N) + offset </code></pre> <p>What you call Slope is the magnitude of the gradient, given as an angle. What ...
python|numpy|matplotlib|numpy-ndarray|heightmap
1
375,574
71,569,202
For loop optimization to create an adjacency matrix
<p>I am currently working with graph with labeled edges. The original adjacency matrix is a matrix with shape [n_nodes, n_nodes, n_edges] where each cell [i,j, k] is 1 if node i and j are connected via edge k.</p> <p>I need to create a reverse of the original graph, where nodes become edges and edges become nodes, so i...
<p>Echoing the comments above, this graph representation is almost certainly cumbersome and inefficient. But that notwithstanding, let's define a vectorized solution without loops and that uses tensor views whenever possible, which should be fairly efficient to compute for larger graphs.</p> <p>For clarity let's use <...
python|for-loop|optimization|graph|pytorch
2
375,575
71,630,995
How to boxplot different columns from a dataframe (y axis) vs groupby a range of hours (x axis) using plotly
<p>Good morning,</p> <p>I'm trying to boxplot the 'columns' from 1 to 6 vs the 'ElapsedTime(hours)' column with the use of plotly library.</p> <p>Here is my dataframe :</p> <pre><code>+------------+----------+----------+---------+----------+----------+---------+----------+--------------------+ | Date | Time |...
<p>Here are some suggestions.</p> <ol> <li><p>Merge the Date and Time columns into a DateTime column:</p> <pre><code>import pandas as pd da = pd.DataFrame() da['Date'] = [&quot;29/07/2021&quot;, &quot;29/07/2021&quot;, &quot;29/07/2021&quot;, &quot;30/07/2021&quot;, &quot;30/07/2021&quot;, &quot;30/07/2021&quot;, &quo...
python|pandas|dataframe|plotly|boxplot
0
375,576
42,349,903
Combine layer chrominance with image luminance
<p>I have read this <a href="http://hi.cs.waseda.ac.jp/~iizuka/projects/colorization/data/colorization_sig2016.pdf" rel="nofollow noreferrer">Colorization paper</a> and it said:</p> <blockquote> <p>The output layer of the colorization network consists of a convolutional layer with a Sigmoid transfer function that ...
<p>Ok, I tried to implement it by using <strong>Skimage</strong> library to make a tensor of image chrominance values and compine it with the luminance by the same method.</p>
python|tensorflow
0
375,577
42,247,104
How to create graphs of relative frequency from pandas dataframe
<p>I know that it's possible to create a histogram from a pandas dataframe column with matplotlib.pyplot using the code:</p> <pre><code>df.plot.hist(y='Distance') </code></pre> <p>Which creates a graph like this:</p> <p><a href="https://i.stack.imgur.com/rP4E2.png" rel="nofollow noreferrer"><img src="https://i.stack...
<p>Try this: </p> <pre><code>orders = [{'number': 1029,'brand':'XPTO','qty':50}, {'number': 3233,'brand':'ABCD','qty':50}, {'number': 5455,'brand':'XPTO','qty':50}, {'number': 1234,'brand':'ABCD','qty':50}, {'number': 7654,'brand':'TXWZ','qty':50}, {'number': 8765,'brand':'XPTO','qty':50}...
python|python-3.x|pandas|matplotlib
3
375,578
42,449,469
Applying a Month End Trading Calendar to Yahoo API data
<p>This is my first post, and I am new to Python and Pandas. I have been working on piecing together the code below based on many questions and answers I have viewed on this website. My next challenge is how to apply a month end trading calendar to the code below so that the output consists of month end "Adj Close" val...
<p>I'd use <code>asfreq</code> to sample down to business month</p> <pre><code>import datetime as dt #set start and end dates for data we are using import pandas as pd import numpy as np import pandas_datareader.data as web # how I grab data from Yahoo Finance API. Pandas is popular data analysis library. start = dt...
python-3.x|pandas
0
375,579
42,543,602
How to use python to pivot the data in a table from many rows to only 4 rows
<p>I have data in a csv like this : </p> <pre> Month YEAR AZ-Phoenix CA-Los Angeles CA-San Diego CA-San Francisco CO-Denver DC-Washington January 1987 59.33 54.67 46.61 50.20 February 1987 59.65 54.89 46.87 49.96 64.77 </pr...
<p>You can simply add the columns you want to preserve to the index, stack, then reset the index. </p> <pre><code>df.set_index(['Month','YEAR']).stack(dropna=False).reset_index() </code></pre> <p><strong>Demo</strong></p> <pre><code>&gt;&gt;&gt; df Month YEAR AZ-Phoenix CA-Los Angeles CA-San Diego CA-S...
python|csv|pandas|dataframe
3
375,580
42,255,729
Tensorflow Error: ValueError: Shapes must be equal rank, but are 2 and 1 From merging shape 1 with other shapes
<p>I am trying to use tensorflow for implementing a dcgan and have run into this error:</p> <pre><code>ValueError: Shapes must be equal rank, but are 2 and 1 From merging shape 1 with other shapes. for 'generator/Reshape/packed' (op: 'Pack') with input shapes: [?,2048], [100,2048], [2048]. </code></pre> <p>As far as ...
<p><code>linear(z, self.gen_dimension * 8 * sample_H16 * sample_W16, 'gen_h0_lin', with_w=True)</code> would be return the tuple <code>(tf.matmul(input_, matrix) + bias, matrix, bias)</code>.</p> <p>Therefore, <code>self.z_</code> is assigned by the tuple, not the only one tf tensor.</p> <p>Just change <code>linear(z...
python|tensorflow|artificial-intelligence
6
375,581
42,400,962
how to filter rows that satisfy a regular expression via pandas
<p>I'm trying to figure out a way to to select only the rows that satisfy my regular expression via Pandas. My actual dataset, data.csv, has one column(the heading is not labeled) and millions of row. The first four rows look like:</p> <pre><code>5;4Z13H;;L 5;346;4567;;O 5;342;4563;;P 5;3LPH14;4567;;O </code></pre> <...
<p>One way is to read the csv as pandas dataframe and then use str.contains to create a mask column</p> <pre><code>df['mask'] = df[0].str.contains('(\d+[A-Z]+\d+)') #0 is the column name df = (df[df['mask'] == True]).drop('mask', axis = 1) </code></pre> <p>You get the desired dataframe, if you wish, you can reset ind...
python|regex|pandas|nlp
3
375,582
42,406,724
numexpr: temporary variables or repeated sub-expressions?
<p>If the same sub-expression appears in multiple places within one <em>numexpr</em> expression, will it be recalculated multiple times (or is numexpr clever enough to detect this and reuse the result)? </p> <p>Is there any way to declare temporary variables within a numexpr expression? This would have two aims: </p> ...
<p>Yes, if a sub-expression is repeated within a numexpr expression, it will not be recalculated. </p> <p>This can be verified by replacing <code>numexpr.evaluate(expr)</code> with <code>numexpr.disassemble(numexpr.NumExpr(expr))</code>.</p> <p>For example, the expression <code>"where(x**2 &gt; 0.5, 0, x**2 + 10)"</c...
python|numpy|optimization|refactoring|numexpr
3
375,583
42,570,498
Pandas conditions across multiple series
<p>Lets say I have some data like this:</p> <pre><code>category = pd.Series(np.ones(4)) job1_days = pd.Series([1, 2, 1, 2]) job1_time = pd.Series([30, 35, 50, 10]) job2_days = pd.Series([1, 3, 1, 3]) job2_time = pd.Series([10, 40, 60, 10]) job3_days = pd.Series([1, 2, 1, 3]) job3_time = pd.Series([30, 15, 50, 15]) ...
<p>Put <em>days</em> and <em>time</em> in two data frames with column positions correspondence maintained, then do the calculation in a vectorized approach:</p> <pre><code>import pandas as pd time = pd.concat([job1_time, job2_time, job3_time], axis = 1) ​ days = pd.concat([job1_days, job2_days, job3_days], axis = 1...
python|pandas|series
1
375,584
42,579,731
Tensorflow Convnet Strange Softmax Output
<p>The output for my Convnet has been very unusual. When imprinted out the output vector of the forward propagation results, it was perfectly [0, 0, 0, 1], constant for an entire label in the dataset. I suspect there's an error in my construction.</p> <pre><code>import os import sys import tensorflow as tf import Inpu...
<p>The main issue lies in the fact that Softmax is called twice.</p> <p>Softmax was called in the forward_propagation part of the code, and that was placed in the Tensorflow cross entropy code, which already contains a softmax, hence causing an anomaly in the outputs.</p>
python|machine-learning|tensorflow|neural-network
0
375,585
42,245,818
Calculate percentages for subgroups in pandas dataframe
<p>I have a dataframe df:</p> <pre><code> VID SFID SFReps 0 0000F0DD 000C5AF6 9 1 0000F0DD 000E701F 16 2 0000F0DD 00481C04 1 3 0000F0DD 004DCD04 1 4 0000F0DD 006CD213 1 5 0000F0DD 00889D31 9 6 0000AAAA 00F8733A 4 7 0000AAAA 00FDD591 1 8 ...
<p>You can divide by new <code>Series</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> and <code>sum</code> for same index as original <code>df</code>:</p> <pre><code>print (df.groupby('VID'...
python|pandas|dataframe
4
375,586
42,136,290
Counting the occurrence of one dataframe column as a substring in another?
<p>I'm new to python and have found answers for counting hardcoded substrings in a df column but am unable to find an answer when using another df column as input. Is this possible with pandas? </p> <p>It's quite messy but essentially my dataframe is:</p> <pre><code>ID Info 3457 &lt;type1&gt;&lt;stats&gt;&lt;/id&...
<p>You can try one of these </p> <pre><code>df = pd.DataFrame({'name':['bernard','Samy','yyy'],'digit':[2,3,3],'SearchID':['be','xx','Sam']}) print df for ID in df['SearchID']: print ID, '\n', df.name.str.count(ID) Searchstr = df['SearchID'].str.cat(sep='|') print df.apply(lambda x: x['name'].count(x['SearchID']...
python|python-2.7|pandas|substring
0
375,587
42,509,878
what is the difference between sampled_softmax_loss and nce_loss in tensorflow?
<p>i notice there are two functions about negative Sampling in tensorflow to compute the loss (<strong>sampled_softmax_loss</strong> and <strong>nce_loss</strong>). the paramaters of these two function are similar, but i really want to know what is the difference between the two?</p>
<p>Sample softmax is all about selecting a sample of the given number and try to get the softmax loss. Here the main objective is to make the result of the sampled softmax equal to our true softmax. So algorithm basically concentrate lot on selecting the those samples from the given distribution. On other hand NCE loss...
tensorflow|sampling
3
375,588
42,248,341
How to count and sum entries per each group?
<p>This is the dataframe:</p> <pre><code>GROUP TIME EVAL AAA 20 0 AAA 22 0 AAA 21 1 AAA 20 0 BBB 20 0 </code></pre> <p>I want to see how many entries belong to each grouping and how many entries have <code>EVAL</code> equal to 1 in each grouping. I have almost finished the code, ...
<p>Using the <code>Time</code> column itself, we can calculate both number of records and mean time for each group. This can be achieved by sending a list ['mean','count'] for the aggregation. we could find the sum of <code>Eval</code> for each group as well.</p> <pre><code> print(data.groupby(['Group']).agg({'Time':...
python|pandas
1
375,589
42,357,499
Scatter plot of Multiindex GroupBy()
<p>I'm trying to make a scatter plot of a GroupBy() with Multiindex (<a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby-with-multiindex" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby-with-multiindex</a>). That is, I want to plot one of the labels on th...
<p>+1 to Vaishali Garg. Based on his comment, the following works: <code> df_mean = df['RMSD'].groupby([df['Sigma'],df['Epsilon']]).mean().reset_index() plt.scatter(df_mean['Sigma'], df_mean['Epsilon'], s=100.*df_mean['RMSD']) </code></p>
pandas
1
375,590
42,215,933
Apply 'wrap_text' to all cells using openpyxl
<p>I have a Pandas dataframe that I am writing out to an XLSX using openpyxl. Many of the cells in the spreadsheet contain long sentences, and i want to set 'wrap_text' on all the contents of the sheet (i.e. every cell).</p> <p>Is there a way to do this? I have seen openpyxl has an 'Alignment' option for 'wrap_text', ...
<p>I have been using openpyxl>=2.5.6. Let us say we want to wrap text for cell A1, then we can use the below code.</p> <pre><code>from openpyxl.styles import Alignment ws['A1'].alignment = Alignment(wrap_text=True) </code></pre>
python|pandas|openpyxl
33
375,591
42,273,078
Python Function does not work
<p>I have got the following df:</p> <pre><code>df = pd.DataFrame(columns=['mbs','Wholesale Data Usage'], index=['x','y','z']) df.loc['x'] = pd.Series({'mbs':32, 'Wholesale Data Usage':36}) df.loc['y'] = pd.Series({'mbs':64, 'Wholesale Data Usage':62}) df.loc['z'] = pd.Series({'mbs':256, 'Wholesale Data Usage':277}) </...
<p>I am not sure if this is what you want, the result is not zero now. (I changed the | symbol to "or")</p> <pre><code>def calculate_costs(row): mbs = row.loc['mbs'] wdu = row.loc['Wholesale Data Usage'] print(mbs,wdu) ac = 0 if wdu &gt;= mbs: print("Hej") if mbs == 32 or mbs == 64:...
python|function|pandas
1
375,592
42,514,444
How do you Merge 2 Series in Pandas
<p>I have the following:</p> <pre><code>s1 = pd.Series([1, 2], index=['A', 'B']) s2 = pd.Series([3, 4], index=['C', 'D']) </code></pre> <p>I want to combine <code>s1</code> and <code>s2</code> to create <code>s3</code> which is:</p> <pre><code>s3 = pd.Series([1, 2, 3, 4], index=['A', 'B', 'C', 'D']) </code></pre> ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferrer"><code>concat()</code></a>, it automatically executes an outer join:</p> <pre><code>pd.concat([s1, s2]) </code></pre> <p>result:</p> <pre><code>A 1 B 2 C 3 D 4 dtype: int64 </code></pre>
python|pandas|series
5
375,593
69,897,012
how to stack two columns
<p>I have a df as this:</p> <pre><code> C CF NO FROMNODENO TONODENO 1 1 2 582.551074 0 2 1 809.018213 0 </code></pre> <p>and I would like to obtain this:</p> <pre><code> new value NO FROMNODENO T...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename_axis.html" rel="nofollow noreferrer"><code>DataFrame.rename_axis</code></a> for rename last level with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferre...
pandas|stack|pivot-table
2
375,594
69,886,734
Pandas replacing the entries and NaNs with the average of first two entries
<p>This is a very strange dataset that I do not know how to preprocess as following example:</p> <pre><code>Year, ID, feature1, feature2, target1 2008, 1, 10, 20, 5 2008, 1, 12, 25, 6 2008, 1, NaN, NaN, 4 2008, 1, NaN, NaN, 7 2008, 1, NaN, NaN, 3 2008, 1, NaN,...
<p>Try with <code>transform</code> <code>mean</code></p> <pre><code>g = df.groupby(['Year','ID']) df['feature1'] = g['feature1'].transform('mean') df['feature2'] = g['feature2'].transform('mean') </code></pre>
python|pandas
1
375,595
69,757,795
How can i use if statement on for loop output from the excel datas
<p>I am new in Pandas, I want to use if conditional operator to the printed loop output from excel</p> <pre><code>for i in range(0,10,3): line = df.loc[i].to_numpy() print(line[0], line[1],line[2],line[3],line[4],line[5],line[6],Line[7],Line[8]) </code></pre> <p>Output:</p> <pre><code>Year N1 N2 N3 N4 N5 N6 N7 ...
<p>The idea of working with pandas is not to use for loops to go through the rows, and neither to convert the rows to NumPy arrays. Rather, use pandas functionalities to do so. In this case, we can get only the row where Year is 58 by doing:</p> <pre><code>df[df.Year == 58] </code></pre> <p>or</p> <pre><code>df.query('...
python|pandas|numpy
1
375,596
69,846,953
I´m trying to implement: np.maximum.outer in Python 3x but I´m getting this error: NotImplementedError
<p>I have a matrix like this:</p> <pre><code>RCA = pd.DataFrame( data=[ (1,0,0,0), (1,1,1,0), (0,0,1,0), (0,1,0,1), (1,0,1,0)], columns=['ct1','ct2','ct3','ct4'], index=['ind_1','ind_2','ind_3','ind_4','ind_5']) </code></pre> <p>I´m trying to calculate:</p> <pre><code>norms = RCA.sum() nor...
<pre><code>In [181]: RCA Out[181]: ct1 ct2 ct3 ct4 ind_1 1 0 0 0 ind_2 1 1 1 0 ind_3 0 0 1 0 ind_4 0 1 0 1 ind_5 1 0 1 0 In [182]: norms = RCA.sum() In [183]: norms Out[183]: ct1 3 ct2 2 ct3 3 ct4 1 dtype: int64 In [184]: np.maximum.out...
python|python-3.x|numpy|matrix
1
375,597
69,815,642
Add a suffix number after each iteration when writing pandas data frame to excel file
<p>I'm performing calculations on a double for loop that has a unique list of products and unique list of customers. I want to write out each pandas data frame of the product/customer combo to an excel file and add a number each time by 1. So essentially something like</p> <pre><code> for product in product_list: ...
<p>You could easily add some sort of counter like this.</p> <pre class="lang-py prettyprint-override"><code> cnt = 0 for product in product_list: for customer in customer_list: dataframe = data[(data.Product==product) &amp; (data.Customer==customer)] # read to excel file: cn...
python|pandas
0
375,598
69,666,481
How to check string in string with not exact same values?
<p>I'm working with Pandas. I need to create a new column in a dataframe according to conditions in other columns. I try to look for each value in a series if it contains a value (a condition to return text).This works when the values are exactly the same but not when the value is only a part of the value of the series...
<p>IIUC:</p> <pre><code>df2 = pd.DataFrame(data={'Symptom':[&quot;I am something&quot;, 'I am not', 'Something 2']}) if df2[&quot;Symptom&quot;].str.contains('Something').any(): print(&quot;yes&quot;) else: print(&quot;no&quot;) </code></pre> <p><code>OUTPUT: YES</code></p> <p>And If you do the following:</p> ...
python|pandas|string|dataframe|conditional-statements
1
375,599
69,789,339
How to count the number of days since a column flag?
<p>I have a dataframe defined as follows. I'd like to count the number of days (or rows) when the <code>input</code> column changes from 1 to 0:</p> <pre><code>import pandas as pd df = pd.DataFrame({'input': [1,1,1,0,0,0,1,1,1,0,0,0]}, index=pd.date_range('2021-10-01', periods=12)) # I can mark the p...
<p>We can create a boolean Series only where <code>input</code> <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>eq</code></a> <code>0</code> then <a href="https://stackoverflow.com/q/40802800/15497888">group by consecutive values</a> and take the <a href="htt...
python|pandas
0