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
360,900
60,630,798
Matching DataFrames based on column value being a subset
<p>Suppose I have two pandas DataFrames:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd source_df = pd.DataFrame.from_dict({"Total": [315.59, 241.17, 165.87], "Label": ["id|1234", "id|2345", "id|2333"]}) Total Label 0 315.59 id|1234 1 241...
<p>First use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a> (pandas 0.25+) by lists of <code>Labels</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split...
python|pandas
1
360,901
60,732,061
Dataframe compare two elements with function
<p>I have the following boolean function which compares two values, with a few fallbacks:</p> <pre><code>def __score_bool(a, b, default_element_value_if_null=None, default_score_if_any_element_is_null=None): if (default_element_value_if_null is not None): if (a is None): a = default_element...
<p>IIUC, you can do:</p> <pre><code>df['score_name'] = df['name'].apply(__score_bool, b='thomas') </code></pre>
python|python-3.x|pandas|dataframe
2
360,902
60,545,627
Can't get y-axis on matplotlib histogram to display the right numbers
<p>So I have this simple DataFrame which i am trying to plot a histogram with</p> <pre><code> Hour Count Average Count 2 6 4 0.129032 4 7 1 0.032258 1 12 9 0.290323 3 16 3 0.096774 0 20 2022 65.225806 </code></pre> <p>What...
<p>Are you looking for something like this? 'df' is the name of the dataframe.</p> <pre><code>df.plot(x='Hour', y = 'Averag Count', kind='bar') </code></pre> <p><strong>Output</strong></p> <p><a href="https://i.stack.imgur.com/f0Dss.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f0Dss.png" alt="e...
pandas|matplotlib
1
360,903
60,388,229
How to visualize CIFAR10 images as matrices
<p>I am currently trying to work with CIFAR10 images. I have the following snippet</p> <pre><code>import tensorflow as tf from tensorflow.keras import datasets,layers,models import matplotlib.pyplot as plt (train_images,train_labels),(test_images,test_labels)=datasets.cifar10.load_data() #train_images,test_images=trai...
<p>train_images variable have batch of images and images are numpy metrics and slicing works same for all metrics in numpy.</p> <p>Dimensions comes as [batch, rows, columns, channels].</p> <p>To get first image you will print: <code>print(train_images[0].shape)</code> and it will output (32, 32, 3).</p> <p>To get fi...
tensorflow|slice|conv-neural-network
1
360,904
60,589,572
How can I apply the same set of values at various positions in a larger array, specified by masks?
<p>I have a 2D array <code>Y</code> of dimensions <code>N x N</code>, and an array of <code>K</code> binary masks <code>X</code>, each of dimensions <code>M x M</code> (so, <code>X</code> has shape <code>K x M x M</code>). Each binary mask in <code>X</code> has exactly one <code>N x N</code> patch of ones, and the rest...
<p>Try this:</p> <pre><code>X[X == 1] = np.tile(Y.flatten(), X.shape[0]) </code></pre>
python|arrays|python-3.x|numpy|mask
2
360,905
60,565,017
trying to load a weight file containing 2 layers into a model with 0 layers
<p>I used tf2.0 to write a vae model,and after I used the callbacks to save the model weight. But afeter i use the load_weights, it said trying to load a weight file containing 2 layers into a model with 0 layers. I used more solutions to solve it, but these failure. this is my train code</p> <pre><code>vae = VAE(5529...
<p>I was able to solve this problem by running the model once.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>vae(tf.ones(shape=INPUT_SHAPE)) vae.load_weights(filepath=FIL...
python|tensorflow|machine-learning|keras|deep-learning
0
360,906
60,724,348
tf.contrib.layers.optimize_loss not working in version 2.1 Is there any replacement I can use for it?
<pre><code>with tf.control_dependencies(update_ops): train_op = tf.contrib.layers.optimize_loss( loss=loss, global_step=global_step, learning_rate=params['lr'], optimizer=(params['optimizer']), update_ops=update_ops, clip_gradients=params['clip_gradients'], su...
<p>You can replace it with optimize_loss in tf_slim.</p> <pre><code>import tf_slim as slim train_op = slim.optimize_loss(...) </code></pre> <p><a href="https://github.com/google-research/tf-slim/blob/77b441267e27359e94a641b906f07afc25f69b13/tf_slim/layers/optimizers.py#L58" rel="nofollow noreferrer">Here is the link of...
tensorflow2.0
0
360,907
60,580,508
TensorFlow 2.0 - Learning Rate Scheduler
<p>I am using Python 3.7 and TensorFlow 2.0, I have to train a neural network for 160 epochs with the following learning rate scheduler:</p> <p>Decreasing the learning rate by a factor of 10 at 80 and 120 epochs, where the initial learning rate = 0.01.</p> <p>How can I write a function to incorporate this learning ra...
<p>The <code>tf.keras.callbacks.LearningRateScheduler</code> expects a function that takes an epoch index as input (integer, indexed from 0) and returns a new learning rate as output (float):</p> <pre><code>def scheduler(epoch, current_learning_rate): if epoch == 79 or epoch == 119: return current_learning...
python-3.x|deep-learning|tensorflow2.0|learning-rate
2
360,908
60,728,875
Geopandas each row different crs?
<p>I have different shape files which contain polygons on a different coordinate system. When I merge them into a GeoDataFrame the crs attribute is not set. It is a way to set for each row in my GeoDataFrame a different crs? </p> <p>I have found a postgis way SRID=312;POINTM(-126.4 45.32 15) but I'm not sure if it wor...
<p>GeoPandas does not support different CRS for different rows. The geometry column of a GeoDataFrame can only have a single CRS.</p>
python|geopandas
1
360,909
60,711,698
How is dot notation implemented in pandas DataFrame?
<p>In a pandas DataFrame, you can get/set existing column data by simply using:</p> <pre><code>df.column_name </code></pre> <p>Understandably, it has limitations (restrictions on names, doesn't work if column doesn't exist).</p> <p>How do they actually implement this? I was expecting them to use <code>__getattr__</c...
<p>I did a bit more digging and found the answer in <code>generic.py</code>: it indeed uses <code>__getattr__</code> and <code>__setattr__</code>:</p> <pre><code>def __getattr__(self, name: str): &quot;&quot;&quot;After regular attribute access, try looking up the name This allows simpler access to columns for ...
python|pandas|dataframe
2
360,910
60,478,912
Android CameraX stuck with two use cases
<p>I'm novice in Android development (more Python and ML engineer) but wanted to try this example from TensorFlow: <a href="https://github.com/tensorflow/examples/tree/master/lite/examples/model_personalization" rel="nofollow noreferrer">TF Lite Transfer Learning.</a></p> <p>I succesfully run it on Android Studio but ...
<p>This <a href="https://github.com/tensorflow/examples/blob/master/lite/examples/model_personalization/android/app/build.gradle" rel="nofollow noreferrer"><code>build.gradle</code></a> uses a rather old version; migrate to version <code>1.0.0-beta01</code>.</p>
android|android-studio|tensorflow|machine-learning|android-camerax
1
360,911
60,533,828
Convert multiple columns in Python dataframe to yyyy/mm/dd with both excel numerical and normal datetime values
<p>I need to be able to select a couple columns from an Excel file in a dataframe to apply a standard date time format (yyyy/mm/dd). The data is (unfortunately) in a mixture of Excel numerical (ex. 43799) and standard date format (ex. 11/30/2019). I am using the read_excel method from pandas, and would prefer not to us...
<p>You will need to parse the column multiple times with the different formats. <code>combine_first</code> will allow you to select the date that matches properly. Excel date is days since 1900-01-01, so we need to change that to an integer first. </p> <pre><code>for col in ['Date_1', 'Date_2', 'Date_3']: d1 = pd....
python|excel|pandas
2
360,912
60,365,076
Tensorflow - Better way to expand Tensor to 3D
<p>I have input Tensors of 0-3 dimensions and always want to output to a 3D Tensor (for use with a <code>tf.einsum</code> function where I can't use broadcasting), with the axis being filled from inside out. Is there a better way for me to do this than the following (ugly) conditional? I read through <code>tf.expand_di...
<p><code>tf.expand_dims</code> is convenient when you want to add one dimension. </p> <p><code>tf.newaxis</code> is convenient when you want to add multiple dimensions in one operation (instead of calling tf.expand_dims multiple times).</p> <p><strong>Modified Code -</strong> </p> <pre><code>import tensorflow as tf ...
python|tensorflow2.0
0
360,913
60,581,677
experimental_list_devices attribute missing in tensorflow_core._api.v2.config
<p>Am using tensorflow 2.1 on Windows 10. On running</p> <pre><code>model.add(Conv3D(16, (22, 5, 5), strides=(1, 2, 2), padding='valid',activation='relu',data_format= &quot;channels_first&quot;, input_shape=input_shape)) </code></pre> <p>on spyder, I get the this error:</p> <pre><code>{ AttributeError: module 'tensorf...
<p>I found the answer here - <a href="https://github.com/keras-team/keras/issues/13684" rel="noreferrer">https://github.com/keras-team/keras/issues/13684</a>. I had the same issue for <code>load_model()</code> from keras under Anaconda:</p> <blockquote> <p>AttributeError: module 'tensorflow_core._api.v2.config' has ...
python|tensorflow|keras|spyder
15
360,914
60,397,308
How to load features and labels from dataframe
<p>I'm trying to use keras with tensorflow to train a network. I've my own digit dataset of myanmar language. I'm trying to develop myanmar digits recognition using neural network using python. I've train.csv file which has a header with format label,pixel0,...,pixel783. I used pandas to load dataframe. But I want to s...
<p>If I get you right, you are loading your header in your dataframe and you want the header to be separated from the actual data. That would be easy with</p> <p>Suppose you have a data-array with header line and this becomes your dataframe</p> <pre><code>a=np.array([['a','b','c'],[1,2,3],[4,5,6],[7,8,9]]) df=pd.Data...
python|pandas
0
360,915
60,753,771
Exclude dates based on a list from a pandas dataframe
<p>I have a dataframe with a <code>pd.to_datetime</code> column df, where the column day is: df['Date'].dt.day:</p> <pre><code>Day 01.01.2020 02.01.2020 ... </code></pre> <p>And I have another dataframe with a <code>pd.to_datetime</code>column closeddays:</p> <pre><code>Closed 01.01.2020 31.01.2020 </code></pre> <p...
<p>You could try this - </p> <pre><code>df = df[~(df['Date'].isin(closeddays['Closed'].dt.date.tolist()))] </code></pre>
python|pandas
0
360,916
60,562,621
Python pandas difference of specific rows in groupby
<p>I have a pandas dataframe</p> <pre><code>df = pd.DataFrame({'Firm': ['Firm1','Firm1','Firm1','Firm1','Firm1','Firm1','Firm2','Firm2','Firm2','Firm2','Firm2','Firm2'],'Location' : ['Country1', 'Country1', 'Country1', 'Country2', 'Country2', 'Country2','Country1', 'Country1', 'Country1', 'Country2', 'Country2', 'Coun...
<p>Using <code>DataFrame.where</code>, <code>Series.isin</code>, <code>GroupBy.diff</code> and <code>Series.fillna</code>:</p> <p>First we convert all <code>Curr1</code> to <code>NaN</code> with <code>where</code>, then we groupby on <code>Firm</code> and <code>Location</code> and calculate the difference in <code>Val...
python|pandas|group-by|transform|apply
2
360,917
60,478,147
Simple for loop itration dictionary python
<p>Following are the two columns(Table is given below) and apply simple for loop so that values that matches other column should appear in front of it.</p> <p><code> miles type year 12 ford 2015 13 amc 2016 14 toyota 2014 15 ford 2013 </code></p> <pre><code>modelclass=set(d['type'] for d in mpg) miles...
<p>If your data is a list of dicts then </p> <pre><code>mpg = [ {'mpg' : 12, 'model': 'ford', 'year' : 2015 }, {'mpg' : 13, 'model': 'amc', 'year' : 2016 }, {'mpg' : 14, 'model': 'toyota', 'year' : 2014 }, {'mpg' : 15, 'model': 'ford', 'year' : 2013 }, ] list(map(lambda x: (x['model'], x['mpg']), mpg...
python|python-3.x|pandas|csv
0
360,918
60,460,567
How to plot based upon unique column values?
<p>I'm a beginner learning to use python to do data visualizations. I found a really cool data set by the UN it is formatted like this:</p> <pre><code>Afghanistan 1975 2127 Afghanistan 1985 3509 Afghanistan 1995 1243 Afghanistan 2005 1327 Albania 1975 4595 Albania 1985 7880 Albania 1995 2087 Albania ...
<h1>Given your data</h1> <ul> <li>Setup imports and dataframe</li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # plot parameters plt.style.use('seaborn') plt.rcParams['figure.figsize'] = (16.0, 10.0) data = {'country': ['Afghanistan',...
python-3.x|pandas|matplotlib|seaborn
0
360,919
60,367,598
Python equivalent of SetConstant ( Eigen )
<p>What is the meaning of set.constant ? I have a program that i need to write in python without using creating a new class. Is there an equivalent of it in python or numpy specifically ?</p>
<p>Python doesnt use constants.</p> <p>To use a variable outside the current scope you can use:</p> <pre><code>global var var = </code></pre>
python|numpy|class|matrix|eigen
0
360,920
60,730,827
Find similar phrases in a column in Pandas
<p>I am using Pandas to work on a dataframe that has a column with the name of companies.</p> <p>For each company name, several versions of it are available. df is an example:</p> <pre><code>df = pd.DataFrame({'id':['a','b','c','d','e','f'],'company name':['name1', ' Name1 LTD', 'name1, ltd.','name 1 LT.D.',' name2 p...
<p>One of the things I've done is use regex or a function that processes the raw strings that strips out all the extra like ltd and arbitrary special characters. Then create a processed string that is their "true name" and create an index of id's based on the "true name".</p> <p>Or you can use fuzzywuzzy to find the d...
python|pandas|mapping|similarity
1
360,921
60,354,579
Need help in row operations in pandas
<p>My dataframe looks like this : </p> <pre><code> SNP A B S1 S2 S3 S4 S5 S6 S7 0 rs123 T C 001 100 100 100 001 100 100 2 rs126 G A 010 100 010 100 010 100 010 </code></pre> <p>I want the output as : </p> <pre><code> SNP A B S1 S2 S3 S4 S5 S6 S7 0 rs123 T C C...
<p>Add three summations as new columns to the dataframe:</p> <pre><code>df["B+B"] = df["B"] + df["B"] df["A+B"] = df["A"] + df["B"] df["A+A"] = df["A"] + df["A"] </code></pre> <p>Iterate over the columns and apply the logic like below:</p> <pre><code>for i in range(1, 8): df[f"S{i}"][df[f"S{i}"] == "001"] = df["...
python|pandas|machine-learning
0
360,922
60,568,664
why does tolist converted array not append in python mulitprocessing?
<p>I would like to change a numpy array in multiprocessing fuunction. So I converted it to manager.list and gave to the subprocess. The changes (append) which are made in the subprocess did not return to the original list. It works with another list with which I execute the same changes except for the fact that base li...
<p>Look at this:</p> <pre><code> lst1 = manager.list() lst1 = np.array(a).tolist() </code></pre> <p>The first statement makes <code>lst1</code> a <code>Manager</code> list. But the second statement replaces it with an ordinary list, it's no longer a <code>Manager</code>.</p> <p>You should create the list firs...
python|arrays|list|numpy|multiprocessing
1
360,923
60,563,075
Using column values as column names in dataframe
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame([{'animal': 'dog', 'years':10}, {'animal': 'dog', 'years':5}, {'animal': 'cat', 'years':3}, {'animal': 'cat', 'years':7}]) </code></pre> <p>giving me: </p> <pre><code> animal years 0 dog...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for counter per <code>animal</code> and reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_inde...
pandas
2
360,924
60,584,140
percentile of the last value of a row
<p>I am trying to get the percentile value for the last value in each row and store it in a different column. But unable to (new to python). What i have been able to achieve is the percentile value of each row through indexing. But not my desired output.</p> <p>Following the code:</p> <pre><code>df = pd.DataFrame(np....
<p>Try:</p> <pre><code>def perc_func(r): x = r last_val = x[-1] min_val = x.min() max_val = x.max() percentile = ((last_val - min_val) / (max_val - min_val) * 100) return percentile df['Per'] = df.apply(lambda row:perc_func(row), axis=1) </code></pre>
python|pandas|dataframe
1
360,925
60,735,424
Sort a dictionary in a column in pandas
<p>I have a dataframe as shown below.</p> <pre><code>user_id Recommended_modules Remaining_modules 1 {A:[5,11], B:[4]} {A:2, B:1} 2 {A:[8,4,2], B:[5], C:[6,8]} {A:7, B:1, C:2} 3 {A:[2,3,9], B:[8]} {A:5, B:1} 4 ...
<p>It is possible, only need python 3.6+:</p> <pre><code>def f(x): #https://stackoverflow.com/a/613218/2901002 d1 = {k: v for k, v in sorted(x['Remaining_modules'].items(), key=lambda item: item[1])} L = d1.keys() #https://stackoverflow.com/a/21773891/2901002 d2 = {key:x['Recommended_modules'][key]...
pandas|pandas-groupby
3
360,926
60,538,137
Using Regex for extracting Usernames from Twitter Data
<p>I am trying to extract names from Twitter text with the help of regex. But, despite the pattern the value returned is none, which not exactly the case. Where my code has wrong, I have no idea. I am using jupyter lab.</p> <p>Sample text is pd.Series <code>full_text</code></p> <pre><code>0 RT @SeamusHughes: The T...
<p>You can do much more simply with the code below</p> <pre><code>df.A.str.extract(r"(@\w+)") #A is the column name </code></pre> <p><strong>Output</strong></p> <pre><code> 0 0 @SeamusHughes 1 @WFaqiri 2 @DavidCornDC 3 @DavidCornDC 4 @billroggio 5 @billroggio 6 @KFILE </code></pre> <p>If you want o...
python|regex|pandas|series
1
360,927
60,554,339
Find Distance to Nearest Zero in NumPy Array
<p>Let's say I have a NumPy array:</p> <pre><code>x = np.array([0, 1, 2, 0, 4, 5, 6, 7, 0, 0]) </code></pre> <p>At each index, I want to find the distance to nearest zero value. If the position is a zero itself then return zero as a distance. Afterward, we are only interested in distances to the nearest zero that is ...
<p><strong>Approach #1 :</strong> <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="noreferrer"><code>Searchsorted</code></a> to the rescue for linear-time in a vectorized manner (before numba guys come in)!</p> <pre><code>mask_z = x==0 idx_z = np.flatnonzero(mask_z) idx_nz = ...
python|numpy
10
360,928
60,697,816
Calculate percent return over certain time frame for each group
<p>I have a pandas dataframe that contains daily price data for thousands of stocks. I'd like to calculate the percent change in the stock price for each stock over different time frames. Right now, I am putting all the stock symbols in a list and looping through my data frame with a standard "for loop" to calculate th...
<p>Not sure if you ever found a faster way since March, but here's an option assuming all the symbols have the same amount of data.</p> <p>build dataframe with 1000 symbols; 7500 dates, and 7500 values</p> <pre><code>symbols = ['A'+ str(i) for i in range(1,1001)] df_hold_list = [] for s in symbols[0:1001]: my_dict ...
python|pandas|pandas-groupby
0
360,929
60,380,808
drop function returning KeyError | Pandas
<p>I'm studying for a Data Science Olympiad competition and i have ran into a little problem. All ive done is converted values in a row with values ranging 2-8 into good or bad using a bin, then i used the label encoder to make them 1 or 0</p> <p>when running this code:</p> <pre><code>import pandas as pd import numpy...
<p>Actually there is a mistake in you python code , drop function takes columns names as a list not the column itself just try below code it should work fine</p> <pre><code>#create our feature ad result sets y = data["quality"] X = data.drop(["quality"], axis=1) </code></pre> <p>and one more thing before dropping you...
python|python-3.x|pandas|machine-learning|scikit-learn
2
360,930
60,689,003
AttributeError: ‘NoneType’ object has no attribute ‘register_forward_hook’
<p>I’m trying to register a forward hook function to the last conv layer of my network. I first printed out the names of the modules via:</p> <pre><code>for name, _ in model.named_modules(): print(name) </code></pre> <p>Which gave me "0.conv" as the module name. However, when I tried to do the following, the abov...
<p>Your modules are stored in an hierarchical way. To get to <code>'0.conv'</code>, you need to</p> <pre class="lang-py prettyprint-override"><code>models._modules["0"]._modules.get("conv").register_forward_hook(hook_feature) </code></pre>
python|python-3.x|pytorch
0
360,931
60,715,575
Pandas how to fill sequence of rows with the previous value in dataframe
<p>Suppose i have this datarame</p> <pre><code>df =pd.DataFrame([[1, 1, 0, 3], [1, 1, 1, 4], [1, 1, 3, 6], [2, 1, 0, 0], [2, 1, 3, 6]], columns=["id","code","date","count"]) </code></pre> <p>Output:</p> <pre><code> id code date count 0 1 1 0 3 1 1 1 1 4 2 1 1 ...
<p>In your case, a combination of <code>pivot</code> and <code>stack</code>:</p> <pre><code>(df.pivot_table(index=['id','code'], columns='date', values='count') .reindex(np.arange(4), axis=1) .ffill(1) .stack() .reset_index(name='count') ) </code></pre> <p>Output:</p> <pre><...
python|pandas|dataframe
4
360,932
60,396,753
How do I specify the "model_config_file" variable to tensorflow-serving in docker-compose?
<p>I will preface this by saying that I am inexperienced with docker and docker-compose. I am trying to convert my <code>docker run ...</code> command to a <em>docker-compose.yml</em> file, however, I cannot get the <em>models.config</em> file to be found.</p> <p>I am able to correctly run a tensorflow-serving docker ...
<p>So I have come across a solution elsewhere that I haven't found on any threads/posts/etc that talk about tensorflow/serving, so I will post my answer here.</p> <p>Adding those options underneath a <code>command</code> section, as follows, works.</p> <pre><code>version: '3.3' services: server: image: tensorfl...
docker|tensorflow|docker-compose|tensorflow-serving
9
360,933
60,665,572
Jupyter Notebook: Putting the numbers on top of the Bar
<p>I am new in Jupyer Notebook/Python. Can i ask what script should I add if I want my numbers, to be also placed on top of the bars? <a href="https://i.stack.imgur.com/bMhzo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bMhzo.png" alt="enter image description here"></a></p> <p>please see image be...
<p>If you are looking for something like this... <a href="https://i.stack.imgur.com/qEg7n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qEg7n.png" alt="enter image description here"></a></p> <p>here is a sample code taken from <a href="https://web.archive.org/web/20170228011551/http://matplotlib.o...
python|pandas|matplotlib
0
360,934
60,521,768
Group by at Row level in Pandas
<p>I'm a newbie to Python-Pandas. I've sample dataset like</p> <pre><code>PRODUCT REGION COUNTRY MEASURE Month_ID QTY P1 West UK M1 Mon_1 200 P1 West UK M2 Mon_1 150 P1 East JAPAN M1 Mon_1 100 P1 East JAPAN M2 ...
<p>You can create new DataFrame by aggregate <code>sum</code>, then for correct sorting is added last duplicated index with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a>, so after <a href="http://pandas....
python|python-3.x|pandas
3
360,935
60,623,442
Drop NaN values but not the entire column
<p>Given this pandas df:</p> <pre><code>Col A. Col B. Col C. 1 a 12 2 s 21 NaN s Nan 7 a Nan </code></pre> <p>I would like to get this:</p> <pre><code>Col A. Col B. Col C. 1 a 12 2 s 21 7 s ...
<p>You can try:</p> <pre><code>out = (pd.DataFrame.from_dict(df.stack().groupby(level=1).agg(list) .to_dict(),orient='index').T) print(out) </code></pre> <hr> <pre><code> Col A. Col B. Col C. 0 1 a 12 1 2 s 21 2 7 s None 3 None a None </code></pre>
python-3.x|pandas
1
360,936
60,417,627
Preserve full surname, get initials of first name (and middle name if some) in pandas column
<p>I have a pandas Dataframe with a column expressing the surname and name of several tennis players like the following one:</p> <pre><code> | Player | |---------------------| 0 | 'Roddick Andy' | 1 | 'Federer Roger' | 2 | 'Tsonga Jo Wilfred | </code></pre> <p>I want to keep the full s...
<p>Here's an approach with <code>str.extractall</code> and <code>groupby</code>:</p> <pre><code>(df.Player .str.extractall('(?P&lt;Surname&gt;\w*)\s(?P&lt;Name&gt;\w*)') .groupby(level=0) .agg({'Surname':'first', 'Name': lambda x: x.str[0].add('.').sum() }) .agg(' '.join, axis=1) ) </code></pre...
python|string|pandas
3
360,937
60,403,735
How to calculate the covariance matrix of 3d numpy arrays?
<p>I have a matrix <code>A</code>, shaped <code>(N, D, 4)</code>. First I calculate <code>A</code> transposed, <code>A_t</code>. I want to calculate the product of <code>A_t</code> times <code>A</code>. I want the resulting matrix to be shaped <code>(D, D)</code>, and the product of the matrices be like if the last vec...
<p>Let's walk through the operations you are attempting and see what we can do to simplify them. For starters, you can write</p> <pre><code>A_t = np.swapaxes(A, 0, 1) </code></pre> <p>This is equivalent to</p> <pre><code>A_t = np.transpose(A, [0, 1, 2]) </code></pre> <p>or</p> <pre><code>A_t = A.transpose([0, 1, 2...
python|numpy|matrix|multiplication
1
360,938
60,713,684
parsing dataframe columns containing functions
<p>Python/pandas newbie here. The csv file I'm trying to work with has been populated with data that looks something like this:</p> <pre><code>A B C D Option1(item1=12345, item12='string', item345=0.123) 2020-03-16 1.234 Option2(item4=123, it...
<p>As long as your functions always have the same arguments, this should work.</p> <p>You can read the csv with (if separators are 2 or more spaces, that's what I get when I paste your question example):</p> <pre><code>df = pd.read_csv('test.csv',sep='[\s]{2,}', index_col=False, engine='python') </code></pre> <p>If ...
python|pandas|dataframe|parsing
1
360,939
72,806,552
How to merge multiple data frame columns in pandas by using index?
<p>I have six pandas data frames like the following. I want to join them by using the id column, which is the index. In the following, I have provided an example with three data frames.</p> <pre><code>df1 = id cnt1 A000 10 A001 20 A002 30 A010 10 A050 55 ...................
<p>IIUC, you want <code>pd.concat</code> on columns</p> <pre class="lang-py prettyprint-override"><code>all_df = pd.concat([df1, df2], axis=1).fillna(0) </code></pre> <pre><code>print(all_df) cnt1 cnt2 id A000 10.0 10.0 A001 20.0 0.0 A002 30.0 0.0 A010 10.0 20.0 A050 55.0 0.0 A317 20.0 0.0 A316 ...
python|python-3.x|pandas|dataframe
2
360,940
72,592,606
Python & Pandas: How can I create new smaller data frames from my large data frame in a (for) loop?
<p>I have a large data frame (51 rows x 51 columns) where the first column are the X-values and the other 50 columns are Y-values of 50 mathematical functions.</p> <p>Something like this:</p> <pre><code>x y1 y2 y3 ... y49 y50 0 1 0.5 20 200 0 1 2 0.1 5 199 0 2 3 -0.2 10 198 1 3 ...
<p>You can use a list comprehension to generate the columns to retain for each smaller DataFrame:</p> <pre class="lang-py prettyprint-override"><code>[df[[&quot;x&quot;, f&quot;y{i + 1}&quot;]] for i in range(50)] </code></pre> <p>The first two elements are:</p> <pre class="lang-py prettyprint-override"><code> x y1 ...
python|pandas|dataframe
2
360,941
72,706,250
How to filter one dataframe with the nearest time to another?
<p>For this project, I have two dataframes one called <strong>df1</strong> and another called <strong>df2</strong>. These dataframes are not the same size (don't think that matters).</p> <p>Each of them have a <em><strong>datetime</strong></em> in the first column. What I am trying to do is:</p> <p>I want to make a new...
<p>If I understand correctly, I believe this gives you what you're looking for.</p> <pre><code>df1['df2_idx'] = df1.Date.apply(lambda x: [(abs(df2['Date'] - x)).idxmin()][0]) df3 = df2.reindex(df1['df2_idx'], axis=0).reset_index().drop(['df2_idx'], axis=1) </code></pre> <p>The first line just finds the row in <code>df2...
python|pandas|dataframe|datetime
0
360,942
72,499,576
How to show data with different number of columns Pandas?
<p>I load CSV document with different number of columns. Therefore I got this error:</p> <pre><code>Expected 12 fields in line 29, saw 13 </code></pre> <p>To avoid this error I use the hack <code>names=range(24)</code></p> <pre><code>df = pd.read_csv(filename, header=None, quoting=csv.QUOTE_NONE, dtype='object', sep=da...
<p>You can have the number of columns using <code>len(df.columns)</code> but if you only want to convert a pandas df to a dictionary then there are already many built-in methods as given below,</p> <pre><code> df = pd.DataFrame({'col1': [1, 2], 'col2': [0.5, 0.75]},index=['row1', 'row2']) df col1 col2 ...
python|pandas
1
360,943
72,775,728
How to ensure model dimensions in Keras Autoencoder?
<p>I'm trying to generate an autoencoder architecture with Keras, but I'm having problems ensuring that the dimensions from the first and last layers remain the same; I must take into account that the input shape is not a squared matrix (and It can change from time to time)</p> <p>How can I create a model for an arbitr...
<p>Because of the downsampling and upsampling created by the MaxPooling and UpSampling layers, you should always try to make your your input a multiple of the stride. Since a stride of 2 is very common, most folks use powers of 2 (2, 4, 8, ..., 128, 256, ...) I'm actually surprised hat it works for an input shape of <c...
python|tensorflow|keras|conv-neural-network|autoencoder
0
360,944
72,630,716
Overwrite sheets saving and the other sheets on excel
<p>i made a script that compare datas form diferent sheets, all godd, now i want to add this updates sheet instead of the old one on the entire excel and keeping the other sheets.</p> <pre><code>import numpy as np import pandas as pd from timestampdirectory import createdir import openpyxl from openpyxl import workboo...
<p>The easiest way to achieve that would be to overwrite the entire excel sheet, for example like this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd # create dataframe from excel file df = pd.read_excel( '2022-06-15-Usage-SvnAnalysis.xlsx', engine='openpyxl', sheet_name='UserDeta...
python|pandas|pycharm|openpyxl|openxml
1
360,945
72,539,121
Convert certain column on a dataframe to a dict
<p>i want to have DF below from 3 columns to 1 column and convert the remaining to a dict</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>Library TaskName Number Group 1...
<p>Let us do</p> <pre><code>df['dict_col'] = df[['TaskName','Number']].apply(lambda x : x.to_dict(),axis=1) df Out[462]: Library TaskName Number dict_col 0 Group1 A 1 {'TaskName': 'A', 'Number': 1} 1 Group2 B 2 {'TaskName': 'B', 'Number': 2} 2 Group3 C ...
pandas|dictionary|arraylist
1
360,946
72,774,878
tfds.features.text.SubwordTextEncoder.load_from_file UnicodeDecodeError
<p>I am working with tfds.features.text.SubwordTextEncoder and create a dictionary with Ukrainian and Russian symbols.</p> <pre class="lang-py prettyprint-override"><code>import tensorflow_datasets as tfds text = ['я тут', 'привет', 'вітання'] tokenizer = tfds.features.text.SubwordTextEncoder.build_from_corpus( t...
<p>I found the solution:</p> <pre class="lang-py prettyprint-override"><code>corpus = [] with open('tokenizer.tf.subwords', 'r', encoding='utf-8') as f: for inx, line in enumerate(f): if inx &gt; 1: sent = line.lower().strip() sent = sent.replace('\n', '') sent = re.sub(r&quot;[^...
python|tensorflow|jupyter-notebook|decode|tensorflow-datasets
0
360,947
72,826,427
Remove a specific URL from data frame
<p>In Python I've a dataframe that contains in a column two comma separated URLS (<a href="https://pippo.it" rel="nofollow noreferrer">https://pippo.it</a>, <a href="https://pluto.it" rel="nofollow noreferrer">https://pluto.it</a>) and another column where the urls I want to remove from all the dataframe are stored. Ho...
<p>You may try replacing using a regex:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;urls&quot;] = df[&quot;urls&quot;].str.replace(r'(?:,\s*)?https?://pluto.it(?:,\s*)?', '', regex=True) </code></pre> <p>Here is a <a href="https://regex101.com/r/lWbNGH/1" rel="nofollow noreferrer">regex demo</a> showin...
python|regex|pandas|dataframe|url
0
360,948
72,562,855
What should I think about when writing a custom loss function?
<p>I'm trying to get my toy network to learn a sine wave.</p> <p>I output (via tanh) a number between -1 and 1, and I want the network to minimise the following loss, where <code>self(x)</code> are the predictions.</p> <pre><code>loss = -torch.mean(self(x)*y) </code></pre> <p>This should be equivalent to trading a stoc...
<p>If I understand you correctly, I think that you were trying to maximize the unnormalized correlation between the network's prediction, <code>self(x)</code>, and the target value <code>y</code>.</p> <p>As you mention, the problem is the convexity of the loss wrt the model weights. One way to see the problem is to con...
pytorch|loss-function
1
360,949
72,717,778
why my pytorch model summy has no parameters?
<p>im beginer of pytorch.<br /> I want to auto encoder model similar to U-Net. <br /> so I make below code, and see summary using <code>pytorch_model_summary</code> but the result told me model have any parameters...</p> <p>why my model have any parameters??</p> <pre><code>class unet_like(nn.Module): def __init__(s...
<p>Your model definition must go in the initializer of your module class: <code>__init__</code>, while the <code>forward</code> handles the inference logic of that module. The PyTorch layers you are using are module <em><strong>classes</strong></em>, they need to be initialized before being use for inference. Unlike fr...
python|deep-learning|neural-network|pytorch|torch
0
360,950
72,794,777
Received incompatible tensor at flattened index 4 from table 'uniform_table'
<p>I'm trying to adapt the TensorFlow Agents tutorial to a custom environment. It's not very complicated and meant to teach me how this works. The game is basically a 21x21 grid with tokens the agent can collect for a reward by walking around. I can validate the environment, the agent, and the replay buffer, but when...
<p>I got stuck with a similar issue, the reason for it is that, you are using tensorflow environment as the parameter of the <code>PyDriver</code> to collect the data. Tensorflow environment adds a batch dimension to all the tensors that it produces, therefore, each <code>time_step</code> generated will have an additio...
python|tensorflow|keras|agent
0
360,951
72,810,015
Python: cumulative sum of column based on unique values
<p>I have a DataFrame with columns as follows</p> <pre><code>df: account PnL date 2022-01-01 1 100 2022-01-01 2 30 2022-01-02 1 -5 2022-01-02 2 10 2022-01-03 1 10 2022-01-03 2 5 </code></pre> <p>I want to get a DataFrame with a column contai...
<pre><code>df['cumulative_PnL'] = df.groupby('account')['PnL'].cumsum() </code></pre>
python|pandas|dataframe|cumulative-sum
3
360,952
72,551,185
Comparing two pandas Series where elements are comma-separated strings with vector operation
<p>I am creating a custom comparison algorithm for the recordlinkage Python library. My function takes two pandas Series as arguments, where each element of the series is a list of one or multiple phone numbers. So an example of the series would look like this:</p> <pre><code>series1 = pd.Series([ &quot;1234567890,0987...
<p>Look at my code below, I've simplified it to the maximum :)</p> <p>I'm using a different module tan you to find Levenshtein distance, but it's tiny and fast.</p> <pre><code>import pandas as pd df = ({'A':[&quot;1234567890&quot;,&quot;5555555555&quot;,&quot;0987654321&quot;], 'B':[&quot;1237654890&quot;,&quo...
python|pandas|duplicates|record-linkage
0
360,953
72,628,304
Dealing with XSLB Excel files and download on sharepoint
<p>I connected to SharePoint to my Cloud Environment Directory and downloaded it to my current directory.</p> <pre><code>file_url = &quot;&quot;&quot;/sites/XXXXXX/Shared%20Documents/General/new_name/train_data.xlsx&quot;&quot;&quot; response = File.open_binary(ctx, file_url) response.raise_for_status() import pathli...
<p>Try the latest xlsb2xlsx package on PyPI:</p> <pre><code>pip install xlsb2xlsx python -m xlsb2xlsx /directory_with_xlsb_file </code></pre> <p>Then you can use <code>pandas</code> with something like:</p> <pre><code>import pandas as pd df = pd.read_excel('your_filepath.xlsx') </code></pre> <p>And work with the <code>...
python-3.x|excel|pandas|sharepoint|xlsb
0
360,954
72,721,520
How can you wrap a C++ function with SWIG that takes in a Python numpy array as input without explicitly giving a size?
<p>I have a library of C++ classes that I am building a Python interface for using SWIG. Many of these classes have methods that take in a double* array or int* array parameter without inputting a size. For example, there are many methods that have a declaration like one of the following:</p> <pre><code>void func(doubl...
<p>One way I can think of is to suppress the &quot;no size&quot; version of the function and extend the class to have a version with a throw-away dimension variable that uses the actual parameter in the class.</p> <p>Example:</p> <p><strong>test.i</strong></p> <pre class="lang-cpp prettyprint-override"><code>%module te...
python|c++|numpy|swig
0
360,955
72,589,889
Train YOLO with height = 320 and width = 320
<p>I am training my object detection model with two classes using YOLOV3. In the config file of yolov3.cfg its default <strong>height = 416 and width = 416</strong>. Now I want to train it with <strong>height = 320 and width = 320</strong> so I made these changes and started my training but this is giving me average lo...
<p>So YOLOV3 has a default height and weight of 416. So to get 320 I have changed it in the .tflite model instead of .cfg.</p>
object-detection|tensorflow-lite|yolo
0
360,956
72,498,161
Pytorch Model trained with Lightining has loss stuck at a baseline
<p>I am building a model for the CIFAR10 dataset.</p> <p>My model starts with a high loss but only goes to 2.3. Given there are 10 classes and it's logs natural for the loss, it's only giving 10% accuracy (ln(10)=~2.3). I am switching from keras/tensorflow and am lost to what I am doing wrong. Any help/advice/resources...
<p>I change some of your code, and after 15 epochs, I get a <code>0.866 in loss</code>.</p> <p>For the CIFAR10 dataset, you do not need to create a large network. (This large network needs more time to train. Maybe, for this reason, the loss of your network slowly decreases.)</p> <pre><code># !pip install pytorch_light...
python|machine-learning|deep-learning|pytorch|pytorch-lightning
1
360,957
72,587,118
Calculate Monthly Average price and plot using Plotly
<p>I have a Dataframe which contains sold house prices in two areas over a daily period from Oct 2021 till today.</p> <p>I want to find the average house price per month and plot a graph using plotly to see if prices are going down or up in each area.</p> <p><strong>Sample DataFrame:</strong></p> <pre><code>DateSold ...
<p>Your DateTime column does not have a frequency or periodicity. Even if it were the case, you wouldn't need to convert to <code>PeriodIndex</code>. You can group by using the month/month_name of the <code>DateSold</code> column as follows:</p> <pre class="lang-py prettyprint-override"><code># convert object to dateti...
python|pandas|plotly-python
0
360,958
72,595,843
How to calculate and print pearson correlation coefficient as a metric in keras model?
<p>I have a keras model that I am trying to do regression with. I want to print the correlation between y's predicted by the model and the actual y's after each epoch. The model.fit() function only prints train and validation loss by default. How would I go about implementing this custom metric?</p> <pre><code>model = ...
<p>I figured out a way myself! The only problem I have with this solution is the way I have used to calculate the size of a minibatch, it looks pretty ugly and I don't know if there is a better way to do it.</p> <pre><code>class CorrelationMetric(keras.metrics.Metric): def __init__(self, name=&quot;correlation&quo...
python|tensorflow|machine-learning|keras|tf.keras
1
360,959
72,570,759
Vectorized creation of shapely Polygons from GeoPandas DataFrame
<p>I have a GeoDataFrame with a point geometry. From the point geometry, I want to define a square polygon geometry in a quite straightforward manner.</p> <p>Given a point, the point should be the left bottom corner in a square with sides 250 units of length. I.e, left bottom corner is the current point, right bottom c...
<p>Your implementation is close, but you can't call shapely.geometry.Polygon with an array of points - it can only be done one at a time. So the trick is to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply</code></a> to call Polygon on every...
python|geopandas|shapely
2
360,960
72,507,589
how to create and fill a new column based on conditions in two other columns?
<p>How can I create a new column and fill it with values based on the condition of two other columns?</p> <p>input:</p> <pre><code> import pandas as pd import numpy as np list1 = ['no','no','yes','yes','no','no','no','yes','no','yes','yes','no','no','no'] list2 = ['no','no','no','no','no','yes','yes','n...
<p>Try this:</p> <pre><code>df[&quot;E&quot;] = np.nan # Use boolean indexing to set no-yes to placeholder value df.loc[(df[&quot;A&quot;] == &quot;no&quot;) &amp; (df[&quot;B&quot;] == &quot;yes&quot;), &quot;E&quot;] = &quot;PL&quot; # Shift placeholder down by one, as it seems from your example # that you want X t...
python|pandas|conditional-statements|calculated-columns
1
360,961
72,502,958
Setting conditionals to a certain column in the csv file I uploaded
<p>I have a column in my csv file that consists of 273 different values. I am trying to set conditionals so that I can label them high or low that way I can then plot them on a basemp. The picture I attached is what I am trying to create with my own data. If anyone has any advice or tips it would really help. I am a fi...
<p>This pythonic code snippet is a way to create a new column of high and low based on the column of interest (COI) in your dataframe. Then you can run further visualization on that. It uses numpy.</p> <pre><code>import numpy as np df['High or Low'] = np.where( df['COI'] &gt;= 12, &quot;High&quot;, np.where( d...
python|pandas
0
360,962
72,765,118
How to add colmun with order number based on rules to DataFrame?
<p>suggested below questions don't sove my problem, because I want to add ordering based on rules. Suggested question don't answer to that. And question is not a duplicate. I have a DataFrame and I need to add a 'new column' with the order number of each value. I was able to do that, but I wonder: 1- is there a more co...
<p>you can do as well by reseting indexes:</p> <pre><code>np.random.seed(42) df2=pd.DataFrame(np.random.randint(1,10, 10), columns=['numbers']) df2=df2.sort_values('numbers').reset_index(drop=True) #reset indexes df2.reset_index(inplace=True) #put value of new indexes (+1) in ord column df2['ord']=df2['index']+1 #clean...
python|pandas|dataframe
1
360,963
72,634,853
Python dataframe tranpose a single value from every nth row into a new column
<p>I have these alternating rows of times, and I want the times side by side, the Name and Value column are always redundant so the only value I am interested in preserving is the Time column by transposing those values a new column. But I can't quite figure out how to do this gracefully</p> <p>Before:</p> <div class="...
<p>here is a solution that works with your example. In df1 you have the output</p> <pre><code>import pandas as pd df=pd.DataFrame({ &quot;Name&quot;:[&quot;Q&quot; ,&quot;Q&quot; ,&quot;Q&quot; ,&quot;Q&quot; ,&quot;P&quot; ,&quot;P&quot;], &quot;Time&quot;:[&quot;09:15&quot;, &quot;09:16&quot;, &quot;09:18&...
python|pandas|dataframe|numpy
0
360,964
72,803,285
Remove all strings with less than n characters from data frame with exception (Python)
<p><strong>Input</strong></p> <pre><code>data = {'ID':[1,2,3,4,5,6,7], 'Column_A':['This', 'Is', 'A','Test', '• ', '•', '•test']} df_in = pd.dataframe(data) </code></pre> <p><strong>Output</strong></p> <pre><code>data = {'ID':[1,4,5,6,7], 'Column_A':['This', 'Test', '• ', '•', '•test']} df_out = pd.dataframe(data) </...
<pre><code>import pandas as pd data = {'ID':[1,2,3,4,5,6,7], 'Column_A':['This', 'Is', 'A','Test', '• ', '•', '•test']} df_in = pd.DataFrame(data) # here is the condition you are looking for df_in = df_in[(df_in['Column_A'].str.len() &gt; 3) | (df_in[&quot;Column_A&qu...
python|pandas|dataframe
3
360,965
72,506,356
How to save dataframe value in excel/csv
<p>i am trying to save outlook email body content to dataframe then to csv/excel, we usually get prices from vendor for different indices in tabular format, i tried using Body_content = message.HTMLBody but didnt work as intented.</p> <p>Thus i am ok with using Body_content = message.Body and print (df.To_string()). No...
<p>You can export the <code>dataFrame</code> to excel</p> <p><code>df.to_excel(&quot;output.xlsx&quot;, index=False) </code></p> <p>or CSV -</p> <p><code>df.to_excel(&quot;output.csv&quot;, index=False) </code></p>
python|pandas|dataframe|outlook|win32com
2
360,966
72,689,463
Adding a full stop to text when missing
<p>How to add a full stop to a text please? I am not able to get the desired combined text.</p> <pre><code># Import libraries import pandas as pd import numpy as np # Initialize list of lists data = [['text with a period.', '111A.'], ['text without a period', '222B'], ['text with many periods...', '...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.where.html?highlight=where#pandas.Series.where" rel="nofollow noreferrer"><code>where</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.cat.html" rel="nofollow noreferrer"><code>cat</code></a>:</p> <p...
python|pandas|dataframe|numpy|text
1
360,967
72,681,770
How to find lines in a 2d numpy array?
<p>I have a <strong>2D numpy array</strong> and I want to <strong>find boundary points of both horizontal and vertical lines</strong>.</p> <pre><code>gray_img = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 255, 255, 255, 255, 255, 255, 255, 0], [0, 255, 255, 255, 255, 255, 255, 2...
<p>vertical lines:</p> <pre><code>m = np.diff(gray_img, 1, 0) # get discrete difference along the 0-axis m = np.argwhere(m != 0) # get indices where value is not zero m = m[np.lexsort(m.T)] # sort indices first 1-column then 0-column m[::2,0] += 1 # </code></pre> <p>output:</p> <pre><code>[[ 1 ...
python|numpy|opencv|image-processing|computer-vision
4
360,968
72,815,342
Multiple sets of coefficients from logistic regression
<p>I am using ScikitLearn and am very new to data mining. I usually get one set of coefficients but this time I got 3 sets of coefficients. How can I convert it to a single coefficient or make it meaningful?</p>
<p>Could you mention which more sets of coefficients you are obtaining?</p> <p>The number of coefficients is related to the number of variables that the regressor has.</p>
pandas|scikit-learn|logistic-regression
0
360,969
72,825,417
How to share the weights or parameters between encoders for ALBERT implementation, pytorch?
<p>I've tried to implement the ALBERT model. I want to ask that how to share the weights or parameters between encoders for ALBERT implementation, in Pytorch?</p> <pre><code> self.encoder = MySequential( *[EncoderBlock( hidden_size, num_head, self.use_leakyrelu, ...
<p>You'll need to define it yourself, i.e. something like</p> <pre class="lang-py prettyprint-override"><code>class LayerRepeater(torch.nn.Module) def _init__(self, ...): self.layer = Layer(...) def forward(*inputs: Tensor, num_repeats: int) -&gt; Tensor: output = inputs for _ in num_repeat...
parameters|pytorch|bert-language-model
0
360,970
72,805,437
Take the names from a condition on another column pandas
<p>I have data set similar to this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Date</th> </tr> </thead> <tbody> <tr> <td>Name1</td> <td>Q3 2022</td> </tr> <tr> <td>Name1</td> <td>Q2 2022</td> </tr> <tr> <td>Name2</td> <td>Q2 2022</td> </tr> <tr> <td>Name3</td> <td>Q2 2022...
<p>If I understand correctly, I think you can just use <code>drop_duplicates</code> to remove multiple mentions of <code>Name</code>.</p> <pre><code># Create some dummy data d = {'name': ['a', 'b', 'c', 'b', 'd'], 'year': [2022, 2022, 2022, 2021, 2020]} df = pd.DataFrame(data=d) df name year 0 a 2022 1 b 2...
python|pandas
0
360,971
72,495,201
How do I generate the following in pandas?
<p>I have a data frame like :</p> <pre><code>+----+----+--------+-------+--------+ | p | a | col1 | col2 | col3 | +----+----+--------+-------+--------+ | p1 | a1 | MANGO1 | APPLE | GUAVA | | p2 | a2 | MANGO2 | APPLE | GRAPES | | p3 | a2 | MANGO1 | APPLE | ORANGE | | p1 | a1 | MANGO2 | APPLE | KIWI | | p2 | a2...
<p>You can use <code>melt</code> first to flatten your dataframe then <code>pivot_table</code> to reshape your dataframe:</p> <pre><code>out = (df.melt(['p', 'a']).assign(variable='YES') .pivot_table('variable', ['p', 'a'], 'value', fill_value='NO', aggfunc='first') .rename_axis(columns=None).reset_in...
python|pandas|dataframe
1
360,972
72,685,832
Include JSON section numbers as columns in a df while converting JSON to DF
<p>I have a nested JSON as follows:</p> <pre><code>{ &quot;group&quot;: { &quot;groupname&quot;: &quot;grp1&quot;, &quot;groupid&quot;: 1, &quot;city&quot;: &quot;London&quot; }, &quot;persons&quot;: { &quot;0&quot;: { &quot;name&quot;: &quot;john&quot;, &quot;age&quot;: 12, &quo...
<p>If I understand you correctly you want to create two dataframes: one for groups and the second for persons:</p> <pre class="lang-py prettyprint-override"><code>data = [ { &quot;group&quot;: {&quot;groupname&quot;: &quot;grp1&quot;, &quot;groupid&quot;: 1, &quot;city&quot;: &quot;London&quot;}, &q...
python|json|pandas
1
360,973
72,535,778
Aggregate records by year and compute bar chart
<p>I would like to aggregate records by year in a dataframe and create (and save) a barchart for each of them.</p> <p>Using my rudimentary python I create a dictionary grouping by year</p> <pre class="lang-py prettyprint-override"><code>dd = [x for _, x in df.groupby('year')] </code></pre> <p>The result is a dictionary...
<p>I guess you need to create a new figure every time, also, why don't you just loop through the <code>groupby</code>:</p> <pre><code>for title, data in df.groupby('year'): fig, ax = plt.subplots() data['Journal Type'].value_counts().plot(kind='bar', title=title, ax=ax) fig.savefig(f'{title}.png') plt.c...
python|pandas
0
360,974
72,817,360
Pandas: Combine DataFrame with a vector - pairwise rows
<p>My first question here! I have two DataFrames:</p> <pre><code>df1 = pd.DataFrame({&quot;A&quot;:[1,0,1,2,1],&quot;B&quot;:[2,2,1,0,1],&quot;C&quot;:[1,1,1,2,1],&quot;D&quot;:[2,1,2,1,1]}) df1 A B C D 0 1 2 1 2 1 0 2 1 1 2 1 1 1 2 3 2 0 2 1 4 1 1 1 1 </code></pre> <pre><code>df2 = pd.DataFr...
<p>Try this:</p> <pre><code>df1 = pd.DataFrame({&quot;A&quot;:[1,0,1,2,1],&quot;B&quot;:[2,2,1,0,1],&quot;C&quot;:[1,1,1,2,1],&quot;D&quot;:[2,1,2,1,1], 'E': [1,1,2,2,2]}) df2 = pd.DataFrame({&quot;A&quot;:[1],&quot;B&quot;:[2],&quot;D&quot;:[4]}) col = list(set(df1.columns) - set(df2.columns)) df2[col] = np.NaN df =...
python|pandas|dataframe
1
360,975
72,512,097
How can I separate one row from a data set but repeat in each line some of the variables?
<p>I have a dataset where each row contains information that needs to be separated and printed in different rows, but I need to keep the name of the company on each newly printed row:</p> <p>example dataset These are the headers:</p> <pre><code>company | marketing_budget | marketing_remaining | finance_budget | finance...
<p>You could use the Python package <code>pandas</code> to build the table. And also using list comprehension, and <code>list.split()</code> method to process the data</p> <pre><code>import pandas as pd d='''company | marketing_budget | marketing_remaining | finance_budget | finance_remaining | sales_budget | sales_re...
python|pandas|dataframe
3
360,976
72,520,070
How to scale y-axis for histogram pandas plot?
<p>I have data for a whole year with an interval of fifteen minutes and want to create a histogram counting hours and not fifteen minutes.</p> <h2>Toy example code</h2> <p>I have following toy example code</p> <pre><code>import pandas as pd import seaborn as sns import matplotlib.pyplot as plt df = pd.read_csv(r&quot;...
<p>Here is my take on your interesting question.</p> <p>I don't know of a way to rescale the y-axis after having plotted the dataframe, but you can rescale the dataframe itself.</p> <p>For instance, in the following toy dataframe, with an interval of measure of 15 minutes, 9 values are comprised between 35 and 40:</p> ...
python|pandas|histogram
1
360,977
72,805,327
Pandas: Apportioning parent row value to child rows
<p>I have a dataset where the parent rows are followed by child rows. Lets say, the parent row has details of a package and the child rows have details of the products in the package.</p> <p><a href="https://i.stack.imgur.com/tTWtr.png" rel="nofollow noreferrer">enter image description here</a></p> <p>The parent row ha...
<p>You can try <code>groupby</code> and <code>transform</code></p> <pre class="lang-py prettyprint-override"><code>m = df['P'].eq(df['package']) df['out'] = (df.groupby(m.cumsum()) ['price'].transform(lambda col: col.item()/(len(col)-1)) .mask(m, pd.NA)) </code></pre>
python|pandas
0
360,978
72,613,282
How to remove duplicates in .xlsx and move values to new column with pandas
<p>I have .xlsx sheet with multiple entries: <a href="https://i.stack.imgur.com/jlesi.png" rel="nofollow noreferrer">Entries</a></p> <p>what I try to achieve: <a href="https://i.stack.imgur.com/15DuO.png" rel="nofollow noreferrer">result</a></p> <p>Therefore I am really stuck. I have tried <code>df.drop_duplicates()</c...
<p>My strategy was to create and then join 2 dataframes with the index set to the <code>Trigger</code> column. One dataframe contains only the <code>Trigger</code>, <code>To</code>, and <code>From</code> columns, while the other dataframe has the <code>Trigger</code>, <code>Category</code>, and <code>Description</code>...
python|pandas|dataframe|xlsx
0
360,979
72,767,159
How to solve ValueError in LSTM input?
<p>I have the training and testing <code>numpy</code> arrays in the following shapes</p> <pre><code>TrainX = (1234, 50, 50) Type: &lt;class 'numpy.ndarray'&gt; # 1234 arrays of 50 by 50 floats TrainY = (1234, 2) Type: &lt;class 'numpy.ndarray'&gt; # TrainY was one column of binary class 0 or 1. Converted it through to_...
<p>The log suggests that the problem is in your <code>class_weight</code> argument. According to <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit" rel="nofollow noreferrer">the docs</a>, this argument should be</p> <blockquote> <p>Optional <strong>dictionary</strong> mapping class indices (integer...
python|numpy|tensorflow|keras|neural-network
2
360,980
72,825,963
Keras: Siamese Model with VGG16 is stuck at 50% accuarcy
<p>I´m trying to create a Siamese model with <code>Keras</code> which learns to recognize differences in Mel-Spectrograms. The dataset I´m using is the ESC-50 dataset. I split it in training files (40 classes a 40 files) and test files (5 classes a 40 files). I generate positive and negative pairs. I generate Mel-Spect...
<p>I could change that by changing the last activation function from sigmoid to relu:</p> <pre><code>#Output Layer outputs = Dense(1, activation=&quot;relu&quot;)(distance) </code></pre>
python|tensorflow|keras
0
360,981
72,817,047
`numpy.random.normal` generates different numbers on different systems
<p>I'm comparing the numbers generated with <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.normal.html" rel="nofollow noreferrer"><code>np.random.normal</code></a> on two different systems (details see below) with the following code (I'm using the legacy <a href="https://numpy.org/doc/sta...
<p>Given that the differences are all so small, it suggests that the underlying bit-generators are doing the same things. It's just to do with differences between the underlying math library.</p> <p>NumPy's <a href="https://github.com/numpy/numpy/blob/b0b523ec0980e46ca735ce96c7c976c4fdd28424/numpy/random/src/legacy/le...
python|linux|numpy|random|numpy-random
3
360,982
72,807,824
How to turn this list into a data frame? I would like to know how to do this in python?
<p>I have a list in python which is showing like this just below. I would like to turn it into a data frame. I tried it: <strong>pd.DataFrame(myList)</strong>, however the <strong>'origins' column</strong> stores a <strong>list</strong>, however I would like to store the <strong>origin and quantityLeads keys</strong> i...
<p>If you have more than one element in &quot;origins&quot; you may first explode, create &quot;origin&quot;, &quot;quantityLeads&quot; and then decide what to do with rest of the dataframe.</p> <pre><code>df = pd.DataFrame(myList) df = df.explode('origins') df[['origin', 'quantityLeads']] = pd.DataFrame(df['origins']....
python|pandas|dataframe|data-science|helper
1
360,983
72,669,424
Defining a specific loop in Python
<p>I am trying to define a loop where at <code>t=1</code>, <code>sigma(1)=v(0)*1+1</code>. In other words, I want <code>sigma</code> at the current time step to take <code>v</code> of the previous time step. <code>v</code> is related to <code>sigma</code> through <code>v=sigma*R</code>.</p> <p>The current and desired o...
<p>I get expected result only if I use</p> <pre><code> if t == 0: sigma = v*t + 1 else: sigma = v*t </code></pre> <p>but I don't know if this is what you expected - you show what you want for <code>t = 1</code> but you start calculations with <code>t = 0</code>. Maybe all your calculations are wr...
python|numpy
1
360,984
72,636,013
Efficiently find the indices of shared values (with repeats) between two large arrays
<h4> Problem description</h4> <p>Let's take this simple array set</p> <pre><code> # 0,1,2,3,4,5 a = np.array([1,1,3,4,6]) b = np.array([6,6,1,3]) </code></pre> <p>From these two arrays I want to get the indices of all possible matches. So for number <code>1</code> we get <code>0,2</code> and <code>1,2</code...
<p><strong>NOTE:</strong> this post is now superseded by the faster alternative sort-based solution.</p> <p>The dict based approach is an algorithmically efficient solution compared to others (I guess Polars should use a similar approach). However, the <strong>overhead of CPython</strong> make it a bit slow. You can sp...
python|arrays|numpy|performance
3
360,985
72,818,330
Seeking missing element in an array in Python
<p>I have an array <code>I</code> with <code>shape=(10,2)</code>. I want to probe this array for missing <code>j=1</code>. By missing, I mean there are no indices with <code>j=1</code>. As is evident from <code>I</code>, there are indices with <code>j=2,3,4,5,6,7</code>.</p> <p>For the purpose of notation, in <code>[0,...
<p>If you want to check single index then you can use code from @ArrowRise comment.</p> <pre><code>if 1 not in I[:,1]: return '1 is missing' </code></pre> <hr /> <p>If you want to get all missing indexes then you can use <code>set()</code> for this.</p> <p>You can convert second column to set</p> <pre><code>set1 = set(...
python|numpy
1
360,986
72,606,083
Getting next index after allocate max value index using Python
<p>I have the following array which consists of 10 values:</p> <pre><code>values = [5,4,15,2,7,1,0,25,9,6] </code></pre> <p>And I want to find the maximum value as index and subtract the next index from it, so the output should be the range between the two indices, I tried to do the below code:</p> <pre><code>start= 0 ...
<p>I think that this code should accomplish what you're looking for:</p> <pre><code>values = [5,4,15,2,7,1,0,25,9,6] max_val = np.max(values) idx = list(np.where(values == max_val)[0])[0] max_val = values[idx] value = max_val - values[idx+1] print(value) </code></pre> <p>This will output 16 for this example.</p>
python|arrays|list|numpy|max
0
360,987
72,776,330
Apply a Function per Row of Sub Groups of the Data **Above** the Current Row
<p>Assume I have data in the form (As a Pandas' Data Frame):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Index</th> <th>ID</th> <th>Value</th> <th>Div Factor</th> <th>Weighted Sum</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>2</td> <td>1</td> <td></td> </tr> <tr> <td>2</td...
<p>This should do what you're asking:</p> <pre class="lang-py prettyprint-override"><code>df1 = df[['ID', 'Value']].set_index('ID', append=True).unstack(-1) df2 = df1.fillna(0).cumsum() / df1.notnull().astype(int).cumsum() df['Weighted Sum'] = df2.mean(axis=1) </code></pre> <p>(Simplification of the last line based on ...
python|pandas|dataframe|performance
1
360,988
72,799,494
PyG: Remove existing edges from prediction matrix
<p>I'm currently working on a recommender system using PyG. The edges are defined as follows:</p> <pre><code>edge_index = tensor([[ 0, 0, 0, ..., 9315, 9317, 9317], [ 100, 448, 452, ..., 452, 1, 307]], device='cuda:0')} </code></pre> <p><code>edge_index[0]</code> containing the indexes for a s...
<p>Since you want to index <code>recs</code> on both axes simultaneously a straight implementation is to to vectorize your for loop as:</p> <pre><code>&gt;&gt;&gt; recs[edge_index[0], edge_index[1]] = 0 </code></pre> <p>Which you can improve by splitting <code>edge_index</code> with <em><code>tuple</code></em>:</p> <pr...
python|pytorch|recommendation-system|pytorch-geometric
0
360,989
72,547,478
Keras to Pytorch -> troubles with layers and shape
<p>I am in the process of converting a Keras model to PyTorch and would need your help.</p> <p>Keras Code:</p> <pre class="lang-py prettyprint-override"><code>def model(input_shape): input_layer = keras.layers.Input(input_shape) conv1 = keras.layers.Conv1D(filters=16, kernel_size=3, padding=&quot;same&quot;)(in...
<p>My Current Code is:</p> <pre class="lang-py prettyprint-override"><code>class Net(nn.Module): def __init__(self): super(Net,self).__init__() self.conv1 = nn.Conv1d(256,128,1) self.batch1 = nn.BatchNorm1d(128) self.avgpl1 = nn.AvgPool1d(1, stride=1) self.fc1 = nn.Linear(128...
python|tensorflow|keras|pytorch|conv-neural-network
1
360,990
72,591,479
How to correctly update column of filtered dataframe in pandas avoiding chained indexing
<p>I'm working on a pandas dataframe. The first thing is to filter and create a new dataframe<code>(df1)</code> from the original dataframe<code>(df)</code> based on number that i specify in <code>num_posts column</code> and <code>user column is user1</code>, then next step is to update the <code>num_posts</code> to an...
<p>If it helps, try this:</p> <pre><code>#df1 = df.loc[(df['num_posts'] == 4)].copy() df1 = df.loc[(df['num_posts'] == 4) &amp; (df['user'] == 'user1')].copy() </code></pre> <p>description <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.copy.html" rel="nofollow noreferrer">here</a><...
python|pandas|dataframe
2
360,991
59,533,975
Counting number of occurrences when grouping by two columns
<p>Suppose I have a pandas dataframe like below:</p> <pre><code>df = pd.DataFrame() df["person"] = ["p1", "p2", "p1", "p3", "p3", "p2", "p2", "p1", "p3", "p1", "p1", "p2", "p2", "p1", "p3", ] df["type"] = ["a", "a", "a", "a", "b", "a", "a", "b", "b", "b", "a", "a", "b", "a", "b",] df["value"] = np.random.random(...
<p>Just change it to</p> <pre><code>df["counter"] = df.groupby(["person", "type"], as_index = False)['value'].transform("count") </code></pre> <p>and you'll get</p> <pre><code> person type value bin counter 0 p1 a 0.134629 0.0-0.25 4 1 p2 a 0.997557 0.75-1.0 4 2 p1...
python|pandas
1
360,992
59,682,482
Applying calculations to filtered values in Pandas DataFrame
<p>I am new to Pandas.</p> <p>Consider this my DataFrame:</p> <p><strong>df</strong></p> <pre><code>Search Impressions Clicks Transactions ContainsBest ContainsFree Country Best phone 10 5 1 True False U...
<p>First part of solution should be:</p> <pre><code>#removed unnecessary column Search and added ContainAll column filled Trues df1 = df.drop('Search', 1).assign(ContainAll = True) #columns for tests cols1 = ['Impressions','Clicks','Transactions'] cols2 = ['ContainsBest','ContainsFree','ContainAll'] print (df1[cols2...
python|pandas|dataframe
1
360,993
59,787,312
Is there any code which can segregate the different data types to different arrays?
<pre><code>horse.dtypes surgery object age object hospital_number int64 rectal_temp float64 pulse float64 respiratory_rate float64 temp_of_extremities object peripheral_pulse object mucous_membrane objec...
<p>I'm not sure if I understand your question correctly but the following code would give the result you gave as an example, i.e. a list of all column names of the same data type:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd # create bogus data o1 = object() o2 = object() i1 = 2 f1 = 5. ho...
python|pandas|numpy|machine-learning|types
0
360,994
59,819,916
Complete days in data from a DataFrame grouped by group by
<p>I have this Dataframe: <a href="https://i.stack.imgur.com/peX67.jpg" rel="nofollow noreferrer">DataFrame</a> I applied df.groupby ('site') to classify data by this feature.</p> <pre><code> grouped = Datos.groupby('site') </code></pre> <p>After classifying it I want to complete, for all records, the "date" column...
<p>I had to do quiet the same thing for a project: Maybe it's not the best solution for you but it can help you. (and I hope save you the headache I had) Here is how as I managed it with help of <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html" rel="nofollow noreferrer">https://pandas.pydat...
python|dataframe|time-series|pandas-groupby
0
360,995
59,900,397
ModuleNotFoundError when running paga with scanpy
<p>I tried running code below using scanpy library but for some reason it reports an error</p> <pre><code>ModuleNotFoundError: No module named 'igraph' </code></pre> <pre><code>import numpy as np import scanpy as sc import anndata adata = anndata.AnnData(np.random.rand(300,300)) sc.tl.pca(adata, n_comps=30) sc.pp.n...
<p>You just need to run install igraph library using the command</p> <pre><code>pip install python-igraph </code></pre>
python|numpy|scanpy
1
360,996
59,701,937
How to create a dataframe with the column included in groupby clause?
<p>I have a data frame. It has 3 columns A, Amount. I have done a group by using 'A'. Now I want to insert these values into a new data frame how can I achieve this?</p> <pre><code>top_plt=pd.DataFrame(top_plt.groupby('A')['Amount'].sum()) </code></pre> <p>The resulting dataframe contains only the Amount column but t...
<p><code>DataFrame</code> constructor is not necessary, better is add <code>as_index=False</code> to <code>groupby</code>:</p> <pre><code>top_plt= top_plt.groupby('A', as_index=False)['Amount'].sum() </code></pre> <p>Or add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_inde...
python|python-3.x|pandas|pandas-groupby
3
360,997
59,838,327
Convert to datetime using column position/number in python pandas
<p>Very simple query but did not find the answer on google.</p> <p>df with timestamp in date column</p> <pre><code>Date 22/11/2019 22:30:10 etc. say which is of the form object on doing df.dtype() </code></pre> <p>Code:</p> <pre><code>df['Date']=pd.to_datetime(df['Date']).dt.date </code></pre> <p>Now I want the ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>DataFrame.iloc</code></a> for column (<code>Series</code>) by position:</p> <pre><code>df.iloc[:, 0] = pd.to_datetime(df.iloc[:, 0]).dt.date </code></pre> <p>Or is also possible extra...
python|pandas|datetime
1
360,998
59,633,425
count specific column values
<p>I have the following dataframe and I would like to have the column "counter_col_x" which should "count" where column x == 8. Only column x=8 is important.</p> <pre><code>counter_col_x x y 0 8 36 0 8 36 0 8 36 0 8 36 0 8 36 nan 1 0 nan 1 1 nan 1 ...
<p>Use:</p> <pre><code>df = ( df.assign(counter_col_x = df.loc[df['x'].eq(8)] .groupby(df['x'].ne(df['x'].shift()) .cumsum()) .ngroup() #.reindex(index = df.index) #o...
pandas|count
3
360,999
59,863,148
In pandas, how to create dataframe indexed by id and with columns with separate content for each appearance?
<p>In Python 3 and pandas I have the dataframe:</p> <pre><code>comps.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 62679 entries, 0 to 62678 Data columns (total 39 columns): cnpj 62679 non-null object razao_social 62679 non-null object nome_fantasia ...
<p>You can use <code>groupby</code>, <code>agg</code> and do something like:</p> <pre><code>df1 = (df .groupby(['cnpj','razao_social', 'nome_fantasia']) .agg({'nome_socio': lambda x: ';'.join(list(x)), 'cnpj_cpf_do_socio': lambda x: ';'.join(list(map(str, x)))}) .reset_index() </code></pr...
python|pandas|dataframe|separator|identity-column
1