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
356,700
71,643,005
Split string with commas while keeping numeric parts
<p>I'm using the following function to separate strings with commas right on the capitals, as long as it is not preceded by a blank space.</p> <p>def func(x):</p> <pre><code>y = re.findall('[A-Z][^A-Z\s]+(?:\s+\S[^A-Z\s]*)*', x) return ','.join(y) </code></pre> <p>However, when I try to separate the next string it rem...
<p>Here is a regex <code>re.findall</code> approach:</p> <pre class="lang-py prettyprint-override"><code>inp = &quot;49ersRiders&quot; output = ','.join(re.findall('(?:[A-Z]|[0-9])[^A-Z]+', inp)) print(output) # 49ers,Riders </code></pre> <p>The regex pattern used here says to match:</p> <pre class="lang-regex prettyp...
python-3.x|regex|pandas|function
1
356,701
71,759,905
Most efficient way to iterate rows across 2 dataframes checking for a condition
<p>So I have a dataframe (D1) that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>nID</th> <th>name</th> </tr> </thead> <tbody> <tr> <td>n1</td> <td>Sarah</td> </tr> <tr> <td>n2</td> <td>John</td> </tr> </tbody> </table> </div> <p>and I have another dataframe (D2) which lo...
<p>we can do <code>explode</code> then <code>melt</code> + <code>groupby</code> with the nId in <code>df2</code> get the tID</p> <pre><code>df2['writers'] = df2['writers'].str.split(',') df2['directors'] = df2['directors'].str.split(',') s = df2.melt('tID').explode('value').groupby('value')['tID'].agg(','.join) df1['ne...
python|pandas|dataframe|numpy
1
356,702
71,499,081
How can I assign data from a list to pandas DataFrame?
<p>I created a df with different courses, and list with prices. What I need is to assign prices to all courses in dataframe - for example, all English courses in df should have first price from price list, all finance courses should have second price from price list etc. (order doesn't matter). Any suggestions?</p> <pr...
<p>Use <a href="https://www.programiz.com/python-programming/dictionary-comprehension" rel="nofollow noreferrer"><code>dict comprehension</code></a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a>:</p> <pre><code># Create a dict wi...
python|pandas|dataframe|numpy
1
356,703
71,659,083
Fill NaN of selected columns based on a dictionary whose keys are column names and values are content of anther column in Python
<p>For the dataframe <code>df1</code> as follows:</p> <pre><code> id products black metal non-ferrous metals precious metal 0 M0066350 copper NaN NaN NaN 1 M0066352 aluminum NaN NaN NaN 2 M0066353 gold NaN ...
<p>Using a simple loop on the columns and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.update.html" rel="nofollow noreferrer"><code>update</code></a>:</p> <pre><code>customized_dict = { 'black metal': ['iron ore', 'coke'], 'non-ferrous metals': ['copper', 'aluminum'], 'precious me...
python-3.x|pandas|dataframe
2
356,704
71,546,557
Make a new dataset from from average of subsets of another data set with pandas
<p>I have a data set (CSV file) with monthly benzine prices in Norway from 1986 to 2022. I want to make a new data frame with an average benzine price per year. Furthermore, I managed to do it, but is there a more efficient way to do it? A link to the CSV file is given. Here is what I did,</p> <pre><code>import matplot...
<p>Try:</p> <pre><code>df = pd.read_excel('BensinPris.xlsx') df_avg = ( df.groupby(df['ÅrMåned'].str[:4].astype(int))['Priser (kr per liter)'].mean() .round(2).rename_axis('Year').rename('Average bensin price').reset_index() ) print(df_avg) # Output Year Average bensin price 0 1986 4....
python|pandas|dataframe
0
356,705
71,587,693
How to replace 0 in multiple columns and specific row with values from another dataframe
<pre><code>import pandas as pd data = {'Region': ['A', 'A', 'B', 'B', 'C', 'C'], 'Description': ['D1', 'D2', 'D1', 'D2', 'D1', 'D2'], 'Baseline 1':[1,2,3,4,5,6] : 'Baseline N': [some numbers] 'Regime 1': [0,0,0,0,2,3] : 'Regime N': [some numbers] } df1 ...
<p>You can try to slice the portion of the DataFrame to replace and replace it with a filled version of the DataFrame</p> <pre><code>cols = df1.filter(like='Regime').columns.to_list() d = dict(zip(replace_data['Region'], replace_data['Values'])) repl_df = df1.mask(df1.eq(0)).T.fillna(df1['Region'].map(d)).T df1.loc[d...
python|pandas|dataframe|numpy
2
356,706
71,630,049
Pandas custom second level groupby function
<p>I have this:</p> <pre><code>df = pd.DataFrame({'sku_id' : ['A','A','A','B','C','C'], 'order_counts' : [1,2,3,1,1,2], 'order_val' : [10,20,30,10,10,20]}) </code></pre> <p>which creates:</p> <p><a href="https://i.stack.imgur.com/3WjGr.png" rel="nofollow noreferrer"><img src="https:/...
<p><code>Mask</code> the <code>!= 1</code> values in the <code>order_counts</code> column with <code>R</code>, then use <code>groupby</code> + <code>sum</code></p> <pre><code>g = df['order_counts'].mask(df['order_counts'] != 1, 'R') df.groupby(['sku_id', g])['order_val'].sum() </code></pre> <p>Result</p> <pre><code>sku...
pandas|pandas-groupby
2
356,707
71,744,579
Converting Table to associative array using python pandas
<p>I have this HTML table</p> <pre><code> &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;Bore:&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;73&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;Color:&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;Machine...
<p>You can use <code>set_index</code> and <code>transpose</code> functions to achieve this. Consider the code below:</p> <pre><code>import pandas as pd url = &quot;pd.html&quot; df = pd.read_html(url) tb = df[0] tb = tb.set_index(0) tb1 = tb.transpose() print(tb1) </code></pre> <p>Results in output:</p> <pre><code>0 B...
python|pandas
0
356,708
71,447,286
Python Memory Mystery with pd.DataFrames, np.ndarrays, and multiprocessing's Queue
<h2>Introduction</h2> <p>Hello Fellow Internauts!</p> <p>I am encountering a strange error when working with three popular Python libraries: pandas, NumPy, and multiprocessing. Whenever I put a pandas DataFrame (containing NumPy arrays) into a multiprocessing queue, the memory of the data frame is altered. This is visi...
<p>Based on the discussion in this <a href="https://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python">SO forum</a>, I noticed that the issue was the pickling (which is done by the <code>multiprocessing.Queue</code> internally) of NumPy arrays and the <code>sys.getsizeof</code> funct...
python|pandas|numpy|memory|multiprocessing
0
356,709
71,517,475
Find string in one csv and replace with string in a different csv in a loop
<p>I have two csv files. <code>csv1</code> looks like this:</p> <pre><code>Title,glide gscore,IFDScore 235,-9.01,-1020.18 235,-8.759,-1020.01 235,-7.301,-1019.28 </code></pre> <p>while <code>csv2</code> looks like this:</p> <pre><code>ID,smiles,number 28604361,NC(=O)CNC(=O)CC(c(cc1)cc(c12)OCO2)c3ccccc3,102 14492699,COc...
<p>You could <code>map</code> it; then use <code>fillna</code> in case there were any &quot;Titles&quot; that did not have a matching &quot;number&quot;:</p> <pre><code>csv1 = pd.read_csv('first_csv.csv') csv2 = pd.read_csv('second_csv.csv') csv1['Title'] = csv1['Title'].map(csv2.set_index('number')['ID']).fillna(csv1[...
python|pandas|bash|dataframe|csv
1
356,710
71,443,134
Adding New Vocabulary Tokens to the Models and saving it for downstream model
<p>Is the mean initialisation of new tokens correct? Also how should I save new tokenizer( after adding new tokens to it) to use it in downstream model?</p> <p>I train a MLM model by adding new tokens and taking mean. How should I use the fine tuned MLM model for new classification task?</p> <pre><code>tokenizer_org = ...
<p>What you are going to do is a convenient method for adding new markers and information to raw text. <code>huggingface</code> provided several method to do that I used the simplest one IMO.</p> <pre><code>BASE_MODEL = &quot;distilbert-base-multilingual-cased&quot; tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)...
python|nlp|huggingface-transformers|huggingface-tokenizers
0
356,711
71,713,428
Effect of nested @tf.function calls on computation graph
<p>Consider the following code:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf @tf.function def inner(tensor): tf.print(tensor) @tf.function def outer(tensor): tf.print(tensor) inner(tensor) tensor = tf.convert_to_tensor([1, 2, 3], dtype=tf.int32) writer = tf.summary.creat...
<p>Yes. When you create a <code>tf.function</code>, you are creating a new graph for the operations within that function. All computed tensors then belong to this created graph an can only be accessed if returned from the <code>tf.function</code>, irrespective of inner/outer graph relationship (under normal use anyway ...
tensorflow|tensorflow2.0
0
356,712
71,663,054
'ValueError: cannot set a row with mismatched columns' when adding a row to pandas DataFrame
<p>While learning python, I decided to try create genetic algorithm and got stuck in the mutation step.</p> <p>I will be glad for any advice both on solving this problem and in general on the architecture and style of the code.</p> <pre><code>one_generation = genlib.create_generation() print(genlib.almost_generation(on...
<p>In your <code>almost generation</code> function, change the line within your <code>if</code> block to assign <code>values</code>:</p> <pre><code>if creature_index == sample.index: print(creature_index, ' == ', sample.index) updated_generation.loc[creature_index] = sample[updated_generation.columns].values </...
python|pandas|dataframe|genetic-algorithm
0
356,713
71,475,369
Sorting column by a number in a string
<p>I have a data frame that looks something like this:</p> <pre><code> ID Data 0 1_SS22 D1 1 7_SS22 D7 2 4_SS22 D4 3 3_SS22 D3 4 8_SS22 D8 5 6_SS22 D6 6 2_SS22 D2 7 5_SS22 D5 </code></pre> <p>I want to sort the 'ID' column by the number associated with it so that my data frame looks like t...
<p>You can use <code>.str.split</code>, <code>.str[0]</code>, and <code>.astype(int)</code> to get the numeric value from the <code>ID</code> column. Then, sort it with <code>sort_values</code>, and take the index from that and use it to index the original dataframe. Finally, use <code>reset_index()</code> to straighte...
python|pandas
1
356,714
71,509,332
How to define the input layer in (spiking) neural network with Pytorch
<p>I have recently started working with Python and more specifically with the Pitorch library in order to create a neural network. I am working with Spiking Neural Network (SNN) but I suspect that the way to define an Artificial Neural Network (ANN) and a SNN is very similar, being the only change that you have to sp...
<p>As stated in the <a href="https://pytorch.org/docs/stable/generated/torch.nn.Linear.html?highlight=linear#torch.nn.Linear" rel="nofollow noreferrer">documentation</a>, the first parameter of <code>nn.Linear</code> is the dimension of the input that will go through this layer, and the second parameter is the size of ...
python|input|neural-network|pytorch
0
356,715
71,518,800
Mistake with lambda function applied on geodataframe's row
<p>I trying to transform a 3D geodataframe of points in 2D. So I've develped the function below:</p> <pre><code>def point3D_to_2D(point3D_wkt: shapely.geometry.point.Point) -&gt; shapely.geometry.point.Point: print(point3D_wkt) point2D_wkt = transform(lambda x, y, z=None: (x, y), point3D_wkt).wkt print(poin...
<h3>convert 3D geometry to 2D</h3> <ul> <li>it's a simple case of not using last (3rd) <strong>z</strong> coordinate of point</li> <li>no need to work with <strong>WKT</strong> strings</li> <li>an issue with your code is you are using <code>apply()</code> to <strong>GeoDataFrame</strong>, plus not taking care of <code>...
python|geopandas
1
356,716
71,486,395
Pandas - Assign value to subset of dataframe, based on multiple conditions
<p>So I have one large file covering all the markets, as well as a dict of symbols with the ticker as key. I only want to update the &quot;submarket&quot; column for &quot;Mk 1&quot; rows, which I know can easily be done with</p> <pre><code>table2.loc[table2['Market'] == &quot;Mk 1&quot; , ['Sub Market']] </code></pre>...
<p>Use <code>isin</code> and <code>map</code>:</p> <pre><code>df.loc[df['Market'].isin(['Mk 1', 'Mk1']), 'Sub Market'] = df['Symbol'].isin(dct).map({True:'A', False:'B'}) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df Market Sub Market Symbol 0 Mk1 A ABC 1 Mk 1 A ABC 2 Mk 1 ...
python|pandas|dataframe
2
356,717
71,530,663
How to set max sequence length with a hugging face sagemaker estimator?
<p>I'd like to increase the max sequence length from 128 to 512 (the maximum <a href="https://huggingface.co/distilbert-base-uncased" rel="nofollow noreferrer">distilbert</a> can handle.) I believe it's only using 128 tokens right now, because the training samples it prints out have an attention_mask with 128 values. T...
<p>It turns out <code>max_seq_length : 512</code> can just be plugged into the hyperparams. I likely typo'd this before as I was getting messages that the param wasn't being used.</p>
amazon-sagemaker|huggingface-transformers
0
356,718
71,644,185
Tensorflow - ImportError: SystemError: <built-in method __contains__ of dict object at 0x00000244B47ADDB8> returned a result with an error set
<p>I am taking this error, My versions like below;</p> <p>Python Version 3.7 Tensorflow Version 2.8.0</p> <p>File &quot;C:\Users\ABC1\Anaconda3\envs\DevArea3\lib\site-packages\tensorflow\python\eager\context.py&quot;, line 35, in from tensorflow.python.client import pywrap_tf_session File &quot;C:\Users\ABC1\Anaconda3...
<p>Try going into the location where your packages are installed on your machine (given in the file path in the error) and deleting any duplicates you don't need. Turns out my requirements.txt file was installing versions of packages that didn't match some of the default versions, and when I thought I was &quot;replaci...
python|tensorflow|python-3.7
0
356,719
71,768,061
huggingface transformers classification using num_labels 1 vs 2
<p>question 1)</p> <p>The answer to <a href="https://stackoverflow.com/questions/71755535/huggingface-classification-struggling-with-prediction">this question</a> suggested that for a binary classification problem I could use <code>num_labels</code> as 1 (positive or not) or 2 (positive and negative). Is there any guid...
<p>Well, it probably is kind of late. But I want to point out one thing, according to the Hugging Face code, if you set num_labels = 1, it will actually trigger the regression modeling, and the loss function will be set to MSELoss(). You can find the code <a href="https://github.com/huggingface/transformers/blob/7ae6f0...
python|classification|huggingface-transformers
3
356,720
71,689,131
Import Excel Data with datetime format to Pandas DF and convert to seconds
<p>i'm trying to import excel data to a pandas df with datetime format. The data is an export file generated by a porgram to track worktime. My code works fine but i just realised, that i started from thinking that my import file always contains the following format:</p> <div class="s-table-container"> <table class="s-...
<p>IIUC use if input values are in format <code>HH:MM:SS</code>:</p> <pre><code>df['Seconds'] = pd.to_timedelta(df['Duration']).dt.total_seconds().astype(int) </code></pre>
python|excel|pandas|datetime|timedelta
0
356,721
71,597,655
Retrieving rows from Pandas DataFrame based on month of a date column in a range
<p>I currently have a table called <code>Sales</code>. The <code>Sales</code> table has a column called <code>sale_date</code> which is in the form <code>YYYY-MM-DD</code> and I want to extract rows where the month is within a range.</p> <pre><code>| seller_id | product_id | buyer_id | sale_date | quantity | price |...
<p>You can convert values to datetimes and then extract months:</p> <pre><code>df.loc[pd.to_datetime(df['sale_date']).dt.month.isin([1, 2, 3])] </code></pre> <p>Or modify your solution with extract second values from list by indexing <code>str[1]</code> with casting to integers:</p> <pre><code>df.loc[df['sale_date'].st...
python|pandas
1
356,722
71,696,761
GPU printing None for machine learning layers
<p>I am running the following code, Using tensorflow for GPU</p> <pre><code>import numpy as np import keras from keras.models import Model, Sequential from keras import layers from keras.layers import BatchNormalization, Dropout, Activation, Flatten, Dense, Reshape, Conv2DTranspose, Conv2D input_img = keras.Input(sh...
<p>I have resolved this. Basically, I changed the</p> <pre><code>layers.Conv2D </code></pre> <p>to</p> <pre><code>Conv2D </code></pre>
python|tensorflow|keras|gpu
0
356,723
71,733,050
Get the column numerically closest to a specific column from all columns in a pandas dataframe
<p>I wonder if it is possible to get the column whose value is closest to a specific column from all data frames without iterating over all the columns. I.e. if there is some built in functionality or an efficient way to do this? I see so many elegant solutions here, I felt like there must be for this scenario too</p> ...
<p>Subtract all columns without <code>C</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sub.html" rel="nofollow noreferrer"><code>DataFrame.sub</code></a>, get absolute values and get column by minimal values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference...
python|pandas
2
356,724
71,738,625
Create new columns based on column values
<p>so I have the following dataframe. In essence it gives me the participation of two commodities (commodity 55 and 73) relative to the world's trade value, that for every country in the world. What I need is to create two new columns that give me the participation of commodity 55 and commodity 73 for each country (giv...
<p>Your desired output is not clear entirely. However I can suggest the following based on the snippet of the table you have shared.</p> <p>With df as your dataframe, use Numpy's <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">np.where()</a> to create and update the...
python|pandas|dataframe
0
356,725
71,454,495
Strange `ErrorType` error referencing columns
<p>Given the following pandas Dataframe <code>df</code> -</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th><strong>Reporting Group</strong></th> <th><strong>Entity/Grouping</strong></th> <th><strong>Entity ID</strong></th> <th><strong>Adjusted Value (Today, No Div, USD)</strong></th> <th><st...
<ol> <li>You need one more square bracket.</li> <li>You can use <code>any</code> method to make a proper condition.</li> </ol> <h2>Code:</h2> <pre class="lang-py prettyprint-override"><code>import pandas as pd def databases_creation(): import numpy as np return pd.DataFrame({'Reporting Group': {0: 'Barrack Fam...
python|pandas|dataframe
1
356,726
71,768,207
Pandas: The most efficient way to subtract some columns from multiple other columns in a dataframe
<p>I have a data frame:</p> <pre><code>id P1T1 P1T2 P1T3 P2T1 P2T2 P2T3 1 10 20 20 16 50 10 2 20 10 25 10 52 20 3 20 5 50 2 40 20 4 23 5 6 78 5 65 5 4 8 ...
<p>Try with <code>apply</code>:</p> <pre><code>&gt;&gt;&gt; df.apply(lambda x: x.sub(df[x.name[:2]+&quot;T1&quot;])) P1T1 P1T2 P1T3 P2T1 P2T2 P2T3 0 0 10 10 0 34 -6 1 0 -10 5 0 42 10 2 0 -15 30 0 38 18 3 0 -18 -17 0 -73 -13 4 0 ...
python|pandas
0
356,727
71,562,430
let user input a letter, find the names starring with that letter in the data frame, then find the maximum column value
<pre><code>df_pm = dataset[[&quot;names&quot;,&quot;pop_mig&quot;]].copy() starring_letter = str(input(&quot;starring_letter:&quot;)) </code></pre> <p>-df_pm is the data frame. I want to list the names that starring with starring_letter, then find which one of them have the highest <code>pop_mig</code> value. <code>pop...
<p>This should work</p> <pre><code>df = df[df.names.str.startswith(input_letter.title())].nlargest(n=1,columns = ['pop_mig']) </code></pre>
python|pandas|dataframe
0
356,728
71,666,523
Find the index of the last true occurrence in a column by row
<p>I have the following table format:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">id</th> <th style="text-align: center;">bool</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">true</td> </tr> <tr> <td style="...
<p>IIUC, you can mask and <code>ffill</code>:</p> <pre><code>df['new'] = df['id'].where(df['bool']).ffill(downcast='infer') </code></pre> <p>output:</p> <pre><code> id bool new 0 1 True 1 1 2 True 2 2 3 False 2 3 4 False 2 4 5 False 2 5 6 True 6 </code></pre>
python|pandas
4
356,729
71,689,722
Dictionary to Dataframe with keys as index
<p>Having this dictionary</p> <pre><code>{'ON': time atm rr25 bf25 rr10 bf10 0 2022-03-29 23:00:00 0.0895 -0.008 0.0015 -0.014 0.004, '1W': time atm rr25 bf25 rr10 bf10 0 2022-03-29 23:00:00 0.0785 -0.01 0.002 -0.017 0.0065, '2W': ...
<p>Use <code>pd.concat</code>:</p> <pre><code>df = pd.concat(data).droplevel(1) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df time atm rr25 bf25 rr10 bf10 ON 2022-03-29 23:00:00 0.0895 -0.008 0.0015 -0.014 0.0040 1W 2022-03-29 23:00:00 0.0785 -0.010 0.0020 -0.017 0.006...
python|pandas|dataframe|dictionary
2
356,730
71,480,638
How to efficiently and correctly implement numba jit decorator or apply vectorization instead of a for loop to speed up the program execution?
<p>Atttempted to implement jit decorator to increase the speed of execution of my code. Not getting proper results. It is throughing all sorts of errors.. Key error, type errors, etc.. The actual code without numba is working without any issues.</p> <pre><code># The Code without numba is: df = pd.DataFrame() df['Serial...
<p>You can only use <code>df['A'].values[:]</code> if the column <code>A</code> exists in the dataframe. Otherwise you need to create a new one, possibly with <code>df['A'] = ...</code>.</p> <p>Moreover, the trick with <code>astype(object)</code> applies for string but not for numbers. Indeed, string-based dataframe co...
pandas|numpy|optimization|vectorization|numba
1
356,731
71,656,376
Pandas: Merging/Organizing Tables into a new table
<p>What is the best way to merge/consolidate multiple tables in pandas? For simplicity, lets say we have 3 simple tables as a dataframe like so:</p> <p>Table1</p> <pre><code>AA_max 55 AA_min 40 BB_max 23 BB_min 10 </code></pre> <p>Table2</p> <pre><code>AA_max 55 AA_min 40 </code></pre> <p>Table3</p> ...
<h2>Solution</h2> <ul> <li><code>Concat</code> the tables along column axis</li> <li><code>Split</code> the index in order to convert to multiindex</li> <li><code>Unstack</code> on level=1 to reshape</li> <li>Flatten the multilevel columns using <code>map</code> and <code>join</code></li> </ul> <pre><code>tables = [df1...
python|pandas|dictionary|merge
1
356,732
71,734,159
How to use haversine distance using haversine library on pandas dataframe
<p>Here's using how I use haversine library to calculate distance between two points</p> <pre><code>import haversine as hs hs.haversine((106.11333888888888,-1.94091666666667),(96.698661, 5.204783)) </code></pre> <p>Here's how to calculate haversine distance using sklearn</p> <pre><code>from sklearn.metrics.pairwise imp...
<p>Following the documentation and example found on: <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.haversine_distances.html" rel="nofollow noreferrer">sklearn.metrics.haversine</a></p> <pre><code>result = haversine_distances(np.radians(df_1[[&quot;lat&quot;,&quot;lon&quot;]]), np.r...
python|pandas|numpy|haversine
1
356,733
71,553,537
How to find nearest nearest place by lat long quickly
<p>Here's my script, it takes to much time to give output</p> <pre><code>from math import radians, cos, sin, asin, sqrt def dist(lat1, long1, lat2, long2): &quot;&quot;&quot; Calculate the great circle distance between two points on the earth (specified in decimal degrees) &quot;&quot;&quot; # conv...
<p>To be faster, you should use compiled code.</p> <p><a href="https://pyproj4.github.io/pyproj/stable/index.html" rel="nofollow noreferrer"><code>pyproj</code></a> allows to calculate a distance between 2 points: (<a href="https://pyproj4.github.io/pyproj/stable/api/geod.html#pyproj.Geod.line_length" rel="nofollow nor...
python|pandas
3
356,734
71,502,630
delete rows of and 2D array with a condition refering to a different array in python numpy
<p>I have two numpy arrays:</p> <pre class="lang-py prettyprint-override"><code>a = np.array([12, 13, 10]) b = np.array([[22, 123], [10, 142], [23, 232], [42, 122], [12, 239]]) </code></pre> <p>I want to delete rows in <code>b</code> if the first element is not in <code>a</code>. Something like:</p> <pre class="lang-py...
<p>Your input:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a=[12,13,10] b=[[22, 123],[10,142],[23,232],[42,122],[12,239]] a, b = np.array(a), np.array(b) c = b[np.isin(b[:, 0], a)] </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>array([[ 10, 142], [ 12, 2...
python|numpy|where-clause
1
356,735
71,712,314
spread then subtract consecutive rows in pandas data frame
<p>I have a data frame where I need to pair consecutive events within the same day and subtract the later from the former. Each has a timestamp and a date.</p> <pre><code> time date event score 0 2022-03-07 06:45:00+00:00 2022-03-07 light 80.066667 1 2022-03-07 18:12:00+00:00 2022-0...
<p>Here's one way using <code>groupby</code> + <code>cumcount</code> to create groups, then use that groups in <code>groupby</code> + <code>first</code> to get the first time each event happens each day. Then <code>pivot</code>.</p> <p>Finally, use <code>diff</code> to get the difference between &quot;light&quot; and &...
python|pandas|dataframe|pandas-groupby|pivot-table
2
356,736
71,769,930
How do I compare dates between two columns within a range of days and perform a task?
<p>Every time there is an UNKNOWN in df, I would like to use the UNKNOWN delivery date and check against the oldest delivery date (grouped by car_part) in df2 to see if it matches within +- 90 days range? If the date matches, then print the date else go to the next UNKNOWN.</p> <pre><code>data = {'car_part': ['100009',...
<p>Change your code with this. I don't really understand the final ouptut and what you are asking however your map is wrong. Since you want to use the same structure of code, the map line should be something like this</p> <pre><code>df[&quot;delivery&quot;] = pd.to_datetime(df[&quot;delivery&quot;]) df2[&quot;delivery&...
python|pandas|dataframe|datetime
1
356,737
71,767,065
How to get a set of numbers between 10^0 and 10^-3
<p>I have a list of numbers between 0 and -3 which I got using...</p> <p><code> InfectProbs=np.arange(0, (-3-(3/11)), -(3/11)).tolist()</code></p> <p>However, I need to get this list of numbers to become 10^(i) where i is a number in the InfectProbs list. I attempted to do..</p> <p><code>InfectProbs=(10^(np.arange(0, (...
<p>use <a href="https://numpy.org/doc/stable/reference/generated/numpy.power.html" rel="nofollow noreferrer">np.power</a></p> <pre class="lang-py prettyprint-override"><code>np.power(10, InfectProbs) </code></pre>
python|numpy|math
0
356,738
71,594,797
Python Array Computations: get two values per item
<p>I'm trying to get a list with all numbers that are in the form 6n+1 or 6n-1. Currently I have this:</p> <pre><code>n = 100000000 l = int(n/6) f1 = lambda x: (6*x)-1 f3 = lambda x: (6*x)+1 primeCandidate = [f(i) for i in range(1,l+1) for f in (f1,f3)] </code></pre> <p>This works nicely, and it gets me 2 values on the...
<p>Certainly.</p> <pre><code>pc1 = np.arange(0,n,6)+5 pc2 = np.arange(0,n,6)+1 pc = np.concatenate((pc1,pc2)) </code></pre>
python|python-3.x|numpy
3
356,739
71,709,939
How import a 3D numpy array?
<p>Using python 3, I am trying to process a set of data in a four-column text file: The first column is the <em>x</em> index, the second column is the <em>y</em> index and the third column is the <em>z</em> index, or depth index. The fourth column is the data value. The values in the text file look like this:</p> <pre>...
<p>With your sample file:</p> <pre><code>In [94]: txt = &quot;&quot;&quot;0 0 0 0.0 ...: 1 0 0 0.0 ...: 2 0 0 2.0 ...: 0 1 0 0.0 ...: 1 1 0 0.0 ...: 2 1 0 2.0 ...: 0 2 0 0.0 ...: 1 2 0 0.0 ...: 2 2 0 2.0 ...: 0 0 1 0.0 ...: 1 0 1 0.0 ...: 2 0 1 2.0 ...: 0 1 1 0.0 ...:...
arrays|python-3.x|numpy
1
356,740
71,517,448
Pandas create new column using dictionary
<p>I'm trying to create a new column within one of my dataframes by combining existing columns through finding the values in a dictionary.</p> <p>values[&quot;-R1-&quot;] and values[&quot;-R2-&quot;] are allocated a value through a listbox using pysimplegui which are a list of all column headings in the df.</p> <p>If I...
<p>Question is answered by Jason Yang above.</p>
python|pandas|dataframe|dictionary|pysimplegui
0
356,741
71,744,183
check if two columns containing sentences match and return only the matches for each dataframe
<p>I'm trying to match two columns in two different dataframes using this:</p> <pre><code>res = mergedStuff = pd.merge(df1, df2, on=['text']) </code></pre> <p>However for some reason, it also returns rows that are not a match.</p> <p>Ideally, I would return two new dataframes containing only the rows that match in each...
<p>You could use <code>set.intersection</code>; then filter the common texts:</p> <pre><code>common = set(df1['text']) &amp; set(df2['text']) df1 = df1[df1['text'].isin(common)] df2 = df2[df2['text'].isin(common)] </code></pre> <p>Then <code>df1</code> looks like:</p> <pre><code> text feature1 feat...
python|python-3.x|pandas|dataframe
3
356,742
71,750,744
Parallelize np.searchsorted
<p>Is there a way to parallelize the implementation of <code>np.searchsorted()</code>?</p> <p>I have a situation where the base array <code>a</code> and value array <code>v</code> are of the same order of size. From what I understand of the search sorted algorithm, it does the operation for each element in <code>v</cod...
<p>A trivially parallelized <code>np.searchsorted</code> works for me. Between 3.4x and 3.9x speed up on a 2-core x 2 threads colab instance with <em>a</em>, <em>b</em> length 10**7 (e.g. <em>9.94 s/2.62 s</em>) using <code>numba 0.55.1</code>, <code>omp</code> threading layer.</p> <pre class="lang-py prettyprint-overr...
python|numpy|numba
1
356,743
71,581,368
How do I color clusters after k-means and TSNE in either seaborn or matplotlib?
<p>I have a dataframe that look something like this:</p> <pre><code>transformed_centroids = model2.fit_transform(everything) df = pd.DataFrame() df[&quot;y&quot;] = model.labels_ df[&quot;comp-1&quot;] = transformed_centroids[-true_k:, 0] df[&quot;comp-2&quot;] = transformed_centroids[-true_k:, 1] </code></pre> <p>The ...
<p>With help from @tdy, I realized one of the solutions tried a little while ago was the solution I needed. My main problem was my edit 2, I wasn't graphing the right set of data. I changed the df to this:</p> <pre><code>df[&quot;y&quot;] = model.labels_ df[&quot;comp-1&quot;] = transformed_centroids[:-2, 0] df[&quot;c...
python|pandas|scikit-learn|seaborn|tsne
1
356,744
71,742,745
How to quickly select a sub matrix in a 2-dimensional matrix using numpy?
<p>I have a 7×7 matrix and I don't want to use the loop to quickly slice out a submatrix.</p> <pre><code>matrix= array([[ 0, 1, 2, 3, 4, 5, 6], [ 7, 8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27], [28, 29, 30, 31, 32, 33, 34], [35, 36, 37, 38, 39, 40, 41], [4...
<p>If you have the indices you could do:</p> <pre><code>x = np.array([[1,2,3], [2,3,4], [0,1,2], [4,5,6]]) y = np.array([0, 2, 4, 5]) matrix[y[:,None], x] </code></pre> <p>output:</p> <pre><code>array([[ 1, 2, 3], [16, 17, 18], [28, 29, 30], [39, 40, 41]]) </code></pre>
python|numpy|matrix|slice
3
356,745
71,650,345
How do I collapse a dataframe?
<p>I have a dataframe where some of the values are NA. I want to remove the NAs and replace them with data, where data is available.</p> <p>This is what the dataframe looks like -</p> <pre><code>&lt;dataframe: flowers&gt; type pedals depth height iris 4 NA NA iris NA 3 ...
<p>First, you would need to replace the NaN with zeros, and then you can just group by and sum.</p> <pre><code>df = df.fillna(0) final_df = df.groupby('type').sum() </code></pre> <p>Since the NaN values are zeros, the sum will simply take the only non-zero value for all rows of a given type.</p>
python|pandas
0
356,746
71,758,798
Find the index of rows which has a special condition in a numpy array
<p>I have a <code>(n,2)</code> array. I want to choose the index of array which their value is equal to the maximum of their rows. For example, in the below array, the maximum of column 0 is 7, and the maximum of column 1 is 10. So, I only want to get the rows which their values are (7,10). Here is an example:</p> <pre...
<p>In the first step we can find maximum values columnar using <code>np.amax</code> and then find rows where both columns satisfy the condition:</p> <pre><code>cols_max = np.amax(a, axis=0) result = np.argwhere((a == cols_max).all(axis=1)) # add &quot;.squeeze()&quot; to reduce dimensions </code></pre>
python|numpy
0
356,747
71,737,385
How to convert numpy.int8 to string?
<p>The below code tries to get ascii code from a 128 bit long numpy array.</p> <pre><code>st=&quot;&quot; ans_final=&quot;&quot; for i in range(len(key)): j=0 while(j&lt;8): st=st+ (key[i]) j+=1 i+=1 ans=b_to_ascii(st) ans_final=ans_final+ans </code></pre> <p>In this code I am planning to pass a st...
<p>You can use the <code>numpy.packbits</code> function (<code>arr</code> is your array of bits):</p> <pre><code>result = ''.join(map(chr, np.packbits(arr))) </code></pre>
python|numpy
0
356,748
71,566,929
Pytorch transfer learning accuracy and lossess not improving. Resnet 50 and Cifar-10
<p>I have been trying everything to fix this issue however my results are still the same, my validation accuracy, train_loss, val_loss are not improving. I have no idea what to do anymore.</p> <p>I am currently using the resnet 50 pre-trained model on the Imagenet dataset. My normalization values are [0.485, 0.456, 0.4...
<p>Surprisingly I had the same problem and was searching the Internet for an answer and found your post.</p> <p>Later I have read that the problem is with CIFAR-10</p> <p>CIFAR-10 is based on 32×32 images which isn't suitable for the ResNet50 architecture so one have to resize it to 224×224 before passing it to the net...
python|neural-network|pytorch
0
356,749
42,579,427
Use from_dict() to initialize a subclass of pandas DataFrame
<p>I know that inheritance is <a href="http://pandas.pydata.org/pandas-docs/stable/internals.html#subclassing-pandas-data-structures" rel="nofollow noreferrer">not the simplest alternative</a> when using pandas, but I'm curious as how to obtain the result I wish for.</p> <p>Say I have a function that from a string ret...
<p>The reason why what you are trying to doesn't work is elaborated here:</p> <p><a href="https://github.com/pandas-dev/pandas/issues/2859" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/2859</a></p> <blockquote> <p>And this won't work because it does not return an instance of your subclass...
python|python-3.x|pandas|inheritance
1
356,750
42,150,769
Pandas multi index dataframe to nested dictionary
<p>Let's say I have the following dataframe</p> <pre><code>df = pd.DataFrame({0: {('A', 'a'): 1, ('A', 'b'): 6, ('B', 'a'): 2, ('B', 'b'): 7}, 1: {('A', 'a'): 2, ('A', 'b'): 7, ('B', 'a'): 3, ('B', 'b'): 8}, 2: {('A', 'a'): 3, ('A', 'b'): 8, ('B', 'a'): 4, ('B', 'b'): 9}, 3: {('A', 'a'): 4, ('A', 'b'): 9, ('B', 'a'...
<p>You can use a dictionary comprehension to iterate through the outer levels (values 'A' and 'B') and use the <code>xs</code> method to slice the frame by those levels.</p> <pre><code>{level: df.xs(level).to_dict('index') for level in df.index.levels[0]} {'A': {'a': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'b': {0: 6, 1: 7...
pandas
17
356,751
42,146,361
Loop changes data of rows not even looped through?
<p>I have a <code>vocabulary</code>, which is a list of words. I have a dataframe <code>posts</code> with two columns, <code>words</code> and <code>wordsdictcoded</code>. First one contains a list of words like <code>['this', 'is']</code>. The vocabulary contains all the words that appear in the <code>words</code> colu...
<p>That's a common python gotcha. The problem is that <code>[listofzeros] * len(posts)</code> copies the same list <code>len</code> times, it does not create copies. You can test that</p> <pre><code>id(posts['wordsdictcoded'][0]) == id(posts['wordsdictcoded'][1]) </code></pre> <p>See comment below (by user <code>DYZ<...
python|loops|pandas
2
356,752
42,399,012
Tensorflow: Transforming manually build layers to tf.contrib.layers
<p>I have these four layers defined:</p> <pre><code>layer_1 = tf.add( tf.matmul(input, tf.Variable(tf.random_normal([n_input, n_hidden_1])), tf.Variable(tf.random_normal([n_hidden_1])))) layer_2 = tf.nn.sigmoid(tf.add( tf.matmul(layer_1, tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), tf.Varia...
<p>One difference between your code and the <code>tf.contrib.layers</code> version is that the default initializers are different:</p> <ul> <li>The initializer for the weights defaults to <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/layers/xavier_initializer" rel="nofollow noreferrer"><code>tf.contr...
python|tensorflow
1
356,753
42,526,344
Cumulative sum only applying on 1 column python
<p>I would like to apply cumsum on 1 specific column only since I have got other values in different columns that must stay the same.</p> <p>This is the script that I have so far</p> <pre><code>df.groupby(by=['name','day']).sum().groupby(level=[0]).cumsum() </code></pre> <p>However this script results in that all of...
<p>Consider the dataframe <code>df</code></p> <pre><code>df = pd.DataFrame(dict( name=list('aaaaaaaabbbbbbbb'), day=np.tile(np.arange(2).repeat(4), 2), data=np.arange(16) )) </code></pre> <p>First, you perform your <code>cumsum</code> over a specific column by naming the column after the <...
python|pandas|cumulative-sum
3
356,754
42,349,931
Tensorflow ValueError:Cannot feed value of shape (40, 24, 24, 4) for Tensor u'real_images:0', which has shape '(40, 24, 24, 3)'
<p>When trying to implement a DCGAN i get this error message when trying to use my training function:</p> <pre><code>ValueError: Cannot feed value of shape (40, 24, 24, 4) for Tensor u'real_images:0', which has shape '(40, 24, 24, 3)' </code></pre> <p>This error occurs when trying to use the line:</p> <pre><code>_,s...
<p>It looks like your image loading function is giving you RGBA images, while the network expects RGB images. Replacing <code>batch_images</code> with <code>batch_images[:,:,:,:3]</code> in the feed dict should be an easy hotfix, you can also look if your loading function supports giving you an RGB image directly.</p>
python|tensorflow|artificial-intelligence
1
356,755
42,463,172
how to perform max/mean pooling on a 2d array using numpy
<p>Given a 2D(M x N) matrix, and a 2D Kernel(K x L), how do i return a matrix that is the result of max or mean pooling using the given kernel over the image?</p> <p>I'd like to use numpy if possible.</p> <p>Note: M, N, K, L can be both even or odd and they need not be perfectly divisible by each other, eg: 7x5 matri...
<p>You could use scikit-image <a href="http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.block_reduce" rel="noreferrer">block_reduce</a>:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import skimage.measure a = np.array([ [ 20, 200, -5, 23], [ -13, 1...
python|arrays|numpy|matrix|max-pooling
101
356,756
42,513,805
How Can I get unique tuple in pandas Multi index from_product
<p>I have to compare employees from both data frames So I'm creating a multi index to calculate the fuzzy score between both of them</p> <pre><code> df = pd.MultiIndex.from_product([df1['employee'],df2['employee']]).to_series().reset_index() from fuzzywuzzy import fuzz from fuzzywuzzy import process df.apply(lambda...
<p>assuming that all the pairs are in a column named 'pairs', you can create a new column with these ordered and drop duplicates by it, something along the lines of:</p> <pre><code>df['ordered_pairs'] = [' '.join(sorted(x)) for x in df['pairs']] df.drop_duplicates('ordered_pairs',inplace=True) </code></pre> <p>if you...
python|pandas|multi-index
0
356,757
42,391,165
How to one hot encode variant length features?
<p>Given a list of variant length features:</p> <pre><code>features = [ ['f1', 'f2', 'f3'], ['f2', 'f4', 'f5', 'f6'], ['f1', 'f2'] ] </code></pre> <p>where each sample has variant number of features and the feature <code>dtype</code> is <code>str</code> and already one hot.</p> <p>In order to use feature...
<p>You can use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html" rel="noreferrer">MultiLabelBinarizer</a> present in scikit which is specifically used for doing this.</p> <p>Code for your example:</p> <pre><code>features = [ ['f1', 'f2', 'f3'], ...
python|pandas|numpy|scikit-learn
14
356,758
42,510,587
Count number of occurrences in Pandas with a specified list
<p>I have a list of possible integer numbers: </p> <pre><code>item_list = [0,1,2,3] </code></pre> <p>and some of the numbers do not necessarily will appear in my dataframe. For example with:</p> <pre><code>df = pd.DataFrame({'a': [0, 2, 0, 1, 0, 1, 0]}) </code></pre> <p>executing </p> <pre><code>df['a'].value_coun...
<p>You can also use reindex:</p> <pre><code> df['a'].value_counts().reindex(item_list).fillna(0) </code></pre>
python|pandas
5
356,759
42,176,153
Plot time series matplotlib with lots of data points
<p>I want to plot a time series for a dataset which has data for 12 months. However the data is recorded for every hour of every day for the 12months. The whole dataset is over 8000 datapoints. The data is in the following format</p> <pre><code> Date Time Energy 0 2014-01-01 1 1118.1 1 2014-01-01 2 ...
<p>You need <code>groupby</code> with aggregating <code>mean</code> first:</p> <pre><code>energy = energy.groupby('Date')['Energy'].mean() </code></pre> <p>and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.html" rel="nofollow noreferrer"><code>Series.plot</code></a>:</p> <pre...
python|python-3.x|pandas|matplotlib
3
356,760
42,399,118
How to set pandas tz_localize properly?
<p>Why does this "pythonic" code not work on the <code>tz_localize()</code> line?</p> <pre><code>import pandas as pd df = pd.DataFrame([{ "Localtime":"2016-01-01 12:00:00", "Timezone":"Europe/London" }, { "Localtime":"2016-01-01 12:00:00", "Timezone":"Europe/Paris" }]) df['UtcDateTime'] = pd.to_d...
<p>Your code is not working because <code>tz_localize()</code> expects to apply a single timezone to multiple values in a series. To make your loop a bit cleaner, you can use <code>apply()</code> as:</p> <p><strong>Code:</strong></p> <pre><code>def localize_ts(row): return pd.to_datetime(row['Localtime']).tz_loc...
python|pandas
4
356,761
42,260,764
Pandas timestamp difference in groupby transform
<p>I have a dataframe with an integer index, session_id, event, and time_stamp that looks like this:</p> <pre><code>In [41]: df = pd.DataFrame(data={'session_id': np.sort(np.random.choice(np.arange(3), 11)), 'event': np.random.choice(['A', 'B', 'C', 'D'], 11), 'time_stamp': pd.date_range ...: ('1/1/2017', periods=...
<p><strong>Why does <code>agg</code> work but <code>transform</code> fails?</strong></p> <p>The difference between these two behaviors is that the <code>transform()</code> operation needs to return a like-indexed. To facilitate this, <code>transform</code> starts with a copy of the original series. Then, after the co...
python|pandas|numpy|timestamp|split-apply-combine
1
356,762
42,136,280
interpolate to specific time
<p>Let's say I have this code:</p> <pre><code>import numpy as np import time from datetime import datetime class Measurements(): def __init__(self, time_var, value): self.time_var = time_var self.value = value a = np.array([ Measurements('30-01-2017 12:02:15.880922', 100), Measurem...
<p>Here is the solution of your problem :</p> <ul> <li>first, if you use cubic interpolation, you need at least 4 values for a and 4 values for b (<code>scipy.interpolate.interp1d</code> with <code>kind="cubic"</code> is not working otherwise)</li> <li>second, you can not interpolate values with <code>scipy.interpolat...
python|numpy|scipy|interpolation
2
356,763
42,401,638
Shape not the same after dumping to libsvm a numpy sparse matrix
<p>I have numpy sparse matrix that I dump in a libsvm format. VC was created using CountVectorizer where the size of the vocabulary is 85731 <code>vc &lt;1315689x85731 sparse matrix of type '&lt;type 'numpy.int64'&gt;' with 38911625 stored elements in Compressed Sparse Row format&gt;</code></p> <p>But when I load ...
<p>I suspect your last two columns consist of only 0's. When loading an libsvm file, it generally doesn't have anything indicating the number of columns. It's a sparse format of col_num:val and will learn the maximum number of columns by the highest column number observed. If you only have 0's in the last two columns, ...
python|numpy|scikit-learn|libsvm|sklearn-pandas
0
356,764
42,321,515
How to efficiency set matrix / array diagonals based on rest of column (avoiding a loop?)
<p>I'm trying to code a solution that takes a function, and sets the central diagonal values (i.e. along A[0,0], A[1,1], ...., A[N,N]) based on summing the values in the column below the diagonal cell.</p> <p>An example:</p> <pre><code>A = np.array([[0, 0, 0], [3, 0, 0], [4, 2, 0]]) B = f...
<p>You can take the lower triangular part of <code>A</code>, sum it column-wise, convert to a diagonal matrix, and add back to <code>A</code>:</p> <pre><code>A + np.eye(A.shape[0]) * np.tril(A).sum(axis=0) </code></pre>
python|numpy|matrix|indexing
2
356,765
42,296,259
How do I find weighted combinations of different lenght arrays equal to x?
<p>I have two arrays (a and b) of different length. I also have a set of weights and I need to find the weighted combinations of a + b that equals x. The sum of the weights must always equal 1. </p> <p>I have tried the following:</p> <pre><code>import numpy as np a = np.arange(1.2, 1.7, 0.1) b = np.arange(0.0, 0.9, ...
<p>IIUC here's one approach -</p> <pre><code>sums = weights[:,None, None, None] * a[:,None] + weights[:,None,None]*b idx = np.argwhere(np.isclose(sums,x)) out_idx = idx[np.isclose(weights[idx[:,0]] + weights[idx[:,1]], 1)] </code></pre> <p>Here, the first two columns are the combinations of indices of <code>weights</...
python|arrays|numpy
1
356,766
42,381,537
Using a function to generate TF Learn DNN objects
<p>I'm working in a Jupyter notebook on trying to generate a long list of TF Learn DNN objects for some brute force trial and error testing (I know this isn't the most efficient method, just trying to show an example). The data follows the Titanic quickstart tutorial.</p> <p>I have a function that, given a bunch of p...
<p>Try restarting the kernel and clear output and to run it again . I too faced this issue and this solution worked for me . It is because you have run model multiple times and it had crashed .</p>
python|tensorflow|tflearn
0
356,767
42,330,633
Logging Python/NumPy console messages
<p>I'm trying to figure out how to capture messages generated by Python/NumPy intractive shell when running my script. I would like to log all generated by console messages (errors, warnings) to same file as defined in my code log messages with time stamps:</p> <pre><code>def LogToFile(): global logger logger = logg...
<p>Afaik, you'd have to specify this in basicConfig, not in your logger:</p> <pre><code>logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG) </code></pre> <p><em>before</em> you do</p> <pre><code>logger = logging.getLogger('MyApp') logger.setLevel(logging.DEBUG) </code></pre>
python|numpy
0
356,768
42,462,196
Pandas won't skip empty line with index_col function
<p>I experience an issue when I am using pandas in python.</p> <p>I need to index my dataframe using country column. But there is an empty line after the column row which the csv file looks like this:</p> <pre><code>0 Televison, Physicians, and Life Expectancy 1 NaN, NaN, NaN, NaN, NaN, NaN 2 country, life expectancy...
<p>use <code>skiprows=[0, 1, 3]</code></p> <pre><code>pd.read_clipboard( sep=',', skipinitialspace=True, skiprows=[0, 1, 3] ) </code></pre> <p><a href="https://i.stack.imgur.com/d3YQk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d3YQk.png" alt="enter image description here"></a></p>
python|pandas|indexing|blank-line
1
356,769
42,308,405
Derivatives of a spline: `scipy splev`
<p>I'm trying to find derivatives of a spline at several points using <code>splev</code> in <code>scipy</code>. For example:</p> <pre><code>import numpy as np from scipy.interpolate import splprep, splev import matplotlib.pyplot as plt # function to normalize each row def normalized(a, axis=-1, order=2): l2 = np....
<p>Your problem (the obviously wrong derivatives) is not related to the numerical derivative since you are not using them at least in the code you posted. What is clearly wrong unless your <code>normalized</code> function does something truly magic is your dividing <code>yp_the</code> by <code>xp_the</code> since the f...
python|numpy|scipy|curve-fitting
2
356,770
69,737,668
Is there a way to add a value from a specific column to the row before?
<p>Is there a possibility to loop through a DataFrame and extract a Value from one column and add it to the row before? Afterwards deleting this row, since otherwise not containing any information.</p> <h3>Original</h3> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;"...
<p>I corrected your source DataFrame, adding one row:</p> <pre><code> A B C D Index 1 T1 T2 T3 T4 2 NaN NaN Val1 NaN 3 T5 T6 T7 T8 4 NaN NaN Val2 NaN 5 T10 T11 T12 T13 </code></pre> <p>The first step is to compute a Series, statin...
python|pandas
0
356,771
70,000,479
TypeError while trying to parse value from json
<p>I have this Json (and the ... at the middle of the code it's to reduce the amount of Json in this question, the full Json is in here <a href="https://pastebin.com/acKCSq8D" rel="nofollow noreferrer">https://pastebin.com/acKCSq8D</a>):</p> <pre><code>[ { &quot;columnHeader&quot;: { &quot;dimensions&quot;:...
<p>The rows interpreted as lists so that you need to loop through them as well to extract the dimensions. Here is a solution.</p> <pre><code>for i in raw_json: for j in i['data']['rows']: print(j['dimensions']) </code></pre>
python|json|pandas
2
356,772
69,748,678
Giving labels in pandas data frame
<p><a href="https://i.stack.imgur.com/g9V1S.png" rel="nofollow noreferrer">enter image description here</a></p> <p>Hi, in the above picture I have a column named taxable income . I want to add one more column next to it such that the income less than equal to 30000 is labelled as risky and income more than 30000 is lab...
<pre><code>df = pd.DataFrame({&quot;Taxable.Income&quot; : [15000 + random.randint(0,1)*30000 for i in range(500)]}) # creating a sample data frame </code></pre> <p>data frame looks like this</p> <p><a href="https://i.stack.imgur.com/LYW45.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LYW45.png" a...
python|pandas|data-science
0
356,773
69,858,161
Using join to append two dataframes
<p>In the following code, I am trying to create some key-value pairs in a dictionary where the first element is a name and the second element is a dataframe.</p> <pre><code># Creating a dictionary data = {'Value':[0,0,0]} kernel_df = pd.DataFrame(data, index=['M1','M2','M3']) dict = {'dummy':kernel_df} # dummy -&gt; ...
<p>Change <code>values</code> to</p> <pre><code>values = batch_df.loc[:,[&quot;Value&quot;]] </code></pre>
python|pandas
0
356,774
69,889,465
Histogram from two coupled arrays
<p>I have two arrays: one for particles locations <code>X</code> and one for the corresponding velocities <code>V</code>. I want to create a histogram for the particle locations, where each bin width is 1, and for each bin I want to calculate the variance of the associated velocities of the particles in that particular...
<p>You may want to use the function <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binned_statistic.html" rel="nofollow noreferrer">scipy.stats.binned_statistics</a>.</p> <p>Here is an example.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from scipy.stats import binn...
python|numpy|histogram
1
356,775
69,921,475
How to write vectorized functions that pull arguments from two dataframes of different size
<p>I am putting together a new formatted dataframe that aggregates data from a different dataframe. I need to create a column in this new dataframe that filters and aggregates data from a secondary dataframe. I wrote a function to do so which filters the second dataframe based on the new column title and and the values...
<p>Why don't you do something like the following (without any <code>.apply</code>s):</p> <pre><code>def get_cumsum_values(names, age, data): return ( data[data.name.isin(names) &amp; (data.age &lt; age)] .groupby(&quot;name&quot;)[&quot;values&quot;] .sum() .rename(str(age)) ...
python|pandas|dataframe|vectorization
0
356,776
69,757,162
Matching two tables using pandas
<p>I have these two tables One table is called LineMax</p> <pre><code> OrigNode DestNode DivisionNum Prefix FromMP ToMP Suffix 7764 25961 3 AB 18 20.9 7764 50213 3 AB 18 17.3 7765 35444 3 AB 0 1.5 7841...
<p>use the pandas merge to combine joins as : inner, left, or right and link by matching fields</p>
pandas
0
356,777
69,904,569
Reshaping a pandas dataframe in a specific manner
<p>Consider the code below:</p> <pre><code>import pandas as pd d = {'col1': [1, 2, 3 ,4 ,5, 5, 6, 5], 'col2': [3, 4, 3 ,4 , 5, 6 , 6, 5], 'col3': [5, 6, 3 ,4 , 5, 6 ,6, 5], 'col4': [7, 8, 3 , 4 , 5, 4 , 6, 4], } df = pd.DataFrame(data=d) df=df.T </code></pre> <p>This code gives me the following output:</p> <pre><cod...
<p>Try this:</p> <pre><code>import pandas as pd d = {'col1': [1, 2, 3 ,4 ,5, 5, 6, 5], 'col2': [3, 4, 3 ,4 , 5, 6 , 6, 5], 'col3': [5, 6, 3 ,4 , 5, 6 ,6, 5], 'col4': [7, 8, 3 , 4 , 5, 4 , 6, 4], } df = pd.DataFrame(data=d) df = df.T number = 2 #Here you can choose the number of columns df1 = df.iloc[:, :number] fo...
pandas|dataframe|reshape
3
356,778
69,826,100
Groupby, aggregate and check the condition in Pandas
<p>I am supposed to aggregate the values in number column for each country and check if it is greater than or equal to 2. If true, it should be displayed as a column in my data.</p> <p>Dataset</p> <pre><code>Country Number bool India 1 yes India 0 no India ...
<p>So in your case do <code>trasnform</code> with <code>groupby</code> then filter it</p> <pre><code>df['result'] = df.groupby('Country')['Number'].transform('sum') df = df.query('result&gt;=2') df Out[18]: Country Number bool result 0 India 1 yes 3 1 India 0 no 3 2 India 2 ...
python|pandas|pandas-groupby|aggregate
0
356,779
69,786,558
How do I plot an asymptote
<p>Hi I'm new to code and trying to plot an asymptote at <code>y=x</code> in python where my y and x are both functions</p> <pre><code>import NumPy as np #define t t=np.linspace(0.1,10,1000) #define x x=(4/3)*t+(np.cos(13*t))/t #define y y=(4/3)*t+(np.sin(13*t))/t #imprort mat plot import matplotlib.pyplot as pl...
<p>If you're wanting to plot a <code>y=x</code> line then this will do</p> <pre><code>plt.plot(x,x) </code></pre>
python|numpy
0
356,780
69,668,141
Load multiple pieces of datasets in python with pandas
<p>I would like to have a unique dataset, like a single .csv file with all my data in it.</p> <p><strong>The problem:</strong> the whole datasets is divided into 22 folders, one for each user (see images below) and then, for each user, there are 7 .csv files which correspond to statistic data for each user.</p> <p>I wo...
<p>if I understand, you are trying to read multiple dataFrames and concatenate. But you want to avoid to do write the same sentences. This is not exactly the solution but you can do something like:</p> <pre><code>#this create a list of users userList = [f&quot;user_{i}&quot; for i in range(1,22)] #read all df dfList ...
python|pandas|dataframe|csv|dataset
0
356,781
69,781,955
Python pandas, substitute all elements in a dataframe column with closest string match from known list
<p>I have a dataframe where the values in a column are strings which are often mispelled, something like:</p> <pre><code>col01 | col02 | name ----------------------- --- | --- | mrk --- | --- | anth3n7 --- | --- | j4ck </code></pre> <p>and a list of possible correct values for this column</p> <pre><co...
<p>Use:</p> <pre><code>import difflib import pandas as pd df = pd.DataFrame(data=[&quot;mrk&quot;, &quot;anth3n7&quot;, &quot;j4ck&quot;], columns=[&quot;name&quot;]) possible_names = ['mark', 'anthony', 'jack'] df[&quot;correct_name&quot;] = df[&quot;name&quot;].apply(lambda x: difflib.get_close_matches(x, possible...
python|pandas|difflib
2
356,782
69,942,232
Evaluate solve_ivp solution on 2D array
<p>I'm solving an initial value problem with <code>scipy.integrate.solve_ivp</code> with <code>dense_output=True</code>. This is supposed to yield an interpolating polynomial which can help me evaluate the solution at any arbitrary point within the domain of solution.</p> <p>I want to evaluate the solution over a 2D ar...
<p>Don't worry for efficiency when you need to reshape arrays. They are fast because array data is not copied (normally).</p> <p>Flatten:</p> <pre><code>&gt;&gt;&gt; a = np.random.random((1000, 1000)) &gt;&gt;&gt; shape = a.shape &gt;&gt;&gt; b = a.ravel() &gt;&gt;&gt; b.shape (1000000,) &gt;&gt;&gt; b.base is a True ...
python|arrays|numpy|scipy
1
356,783
69,745,554
Python Pandas calculate value_counts of two columns and use groupby
<p>I have a dataframe :</p> <pre><code>data = {'label': ['cat','dog','dog','cat','cat'], 'breeds': [ 'bengal','shar pei','pug','maine coon','maine coon'], 'nicknames':[['Loki','Loki' ],['Max'],['Toby','Zeus ','Toby'],['Marty'],['Erin ','Erin']], 'eye color':[['blue','green'],['green'],['brown','brown...
<p>First, we use a <code>groupby</code> with <code>sum</code> on the lists as <code>sum</code> concatenates the lists together :</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df_grouped = df.groupby(['label', 'breeds']).agg({'nicknames': sum, 'eye color': sum}).reset_index() &gt;&gt;&gt; df_grouped ...
python|pandas|group-by|count|apply
1
356,784
69,820,879
How to match rows in DataFrame on another DataFrame with multiply condition
<p>I have two dataframes - df1 and df2 as following:</p> <pre><code>df_1 = pd.DataFrame( {'num': [1,2,3], 'time': [100,200,300]}) df_2 = pd.DataFrame( {'num': [1,2,3], 'time': [101,104,200]}) </code></pre> <p>Match = is when 'num' in df1 not equals to 'num' in df2 and the time in df1 is in df2 with offset of 10. The re...
<p>Use <code>merge</code> with <code>how='cross'</code> before use boolean masks to select right rows:</p> <pre><code>out = pd.merge(df_1, df_2, how='cross', suffixes=('_df1', '_df2')) m1 = out['num_df1'] != out['num_df2'] m2 = abs(out['time_df2'] - out['time_df1']) &lt;= 10 out = out[m1 &amp; m2] </code></pre> <p>Outp...
python|pandas|dataframe
0
356,785
70,002,775
how to know how many images are augmented in tensorflow.keras.layers.experimental.preprocessing?
<p>I'm studying CNN to image classification and using data augmentation for prohibiting overfitting. Data augmentation works which the loss function go decrease but, I can't find out how many training images are augmented. Many research papers talk about the augmentation factor(I understood 'augmentation factor' means ...
<p>You need to mention the batch size, which is the number of images selected each epoch. You can read the link <a href="https://www.tensorflow.org/tutorials/images/data_augmentation" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/images/data_augmentation</a> . It provides some insight. They use batch s...
python|tensorflow|keras|conv-neural-network|preprocessor
2
356,786
69,886,610
matplotlib multiple Y-axis pandas plot
<p>Could someone give me a tip on how to do multiple Y axis plots?</p> <p>This is some made up data below, how could I put <code>Temperature</code> its own Y axis, <code>Pressure</code> on its own Y axis, and then have both <code>Value1</code> and <code>Value2</code> on the <em><strong>same</strong></em> Y axis. I am t...
<p>You are adding 4 different plots in one, which is not helpful. I would recommend breaking it into 2 plots w/ shared x-axis &quot;Date&quot;:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt rows,cols = 8760,4 data = np.random.rand(rows,cols) tidx = pd.date_range('2019-01-01', p...
python|pandas|matplotlib
2
356,787
69,891,807
How do I drop rows in a pandas dataframe based on the time of day
<p>I am trying to drop specific rows in a dataframe where the index is a date with 1hr intervals during specific times of the day. (It is hourly intervals of stock market data).</p> <p>For instance, 2021-10-26 09:30:00-4:00,2021-10-26 10:30:00-4:00,2021-10-26 11:30:00-4:00, 2021-10-26 12:30:00-4:00 etc.</p> <p>I want...
<p>If your columns are datetime objects and not strings, you can do something like this</p> <pre><code>df = pd.Dataframe() ...input data, etc... columns = df.columns kept = [] for col in columns if (col.dt.hour == 6 or col.dt.hour == 10) and col.dt.minute == 30 kept.append(col) else: continue d...
python|pandas|datetime|rows|drop
0
356,788
69,918,186
KNN Classifier build from scratch with numpy, what is wrong with the code?
<p>Why my KNN Classifier build from scratch with numpy gives different results than the <code>sklearn.KNeighborsClassifier</code>? What is wrong with my code?</p> <pre><code># create a function that computes euclidean distance and return the most common class label # for given k. def k_neighbors(self, x): ...
<p>Based on <code>sklearn</code> <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html" rel="nofollow noreferrer">documentation</a>, there are multiple reasons:</p> <ol> <li>Distance metric: you are using Euclidean distance metric, while <code>sklearn</code> by default u...
python|numpy|scikit-learn|knn
1
356,789
69,762,745
how to import and read multiple json files in pandas?
<p>I'm trying to read multiple json files using python. My files look something like this:</p> <ul> <li>Inbox <ul> <li>Jack <ul> <li>message1.json</li> </ul> </li> <li>Brad <ul> <li>message1.json</li> </ul> </li> <li>Charles <ul> <li>message1.json</li> </ul> </li> <li>Emerson <ul> <li>message1.json</li> </ul> </li> <li...
<p>You can use the method <code>os.listdir(&quot;relative path to where the folders are&quot;)</code> <a href="https://docs.python.org/3/library/os.html#os.listdir" rel="nofollow noreferrer">(take a look at the domumentation)</a> to get all subdirectories in the cwd. And you should not use loads for getting the content...
python|json|pandas|file
1
356,790
69,841,593
pd.Grouper() when applied on datetime, changes the original column of dates
<p>I have a sample dataframe from my huge dataframe as shown given below.</p> <pre><code>import pandas as pd import numpy as np NaN = np.nan data = { 'ID':['AAQRB','AAQRB','AAQRB', 'AHXSJ','AHXSJ','AHXSJ','GABOY','GABOY','GABOY','GHZGS','GHZGS','GHZGS'], 'Date':['10/18/2021 10:52:53 PM','10/18/2021 10:53:55...
<p>Create a virtual column to group by month:</p> <pre><code>&gt;&gt;&gt; test_df.assign(month=test_df['Date'].dt.strftime('%Y-%m')) \ .groupby(['ID', 'month']).agg('first') \ .droplevel(1).reset_index() \ .assign(Date=lambda x: x['Date'].dt.date) ID Date Race_x Vaccine S...
python|pandas|dataframe|data-science|data-analysis
2
356,791
69,744,954
Error operating data with pandas (in case of missing data)
<p>I have the DataFrame 'indata2'. The following code allows me to add an 'Indicator' column that groups my data based on Indata2['Label'].</p> <pre><code>import pandas as pd import numpy as np indata2 = [[2, 'SIS X+', 9.65, 'Q'], [2, 'SIS X-', 5.32, 'Q'], [2, 'SIS Y+', 8....
<p>Make sure the mapper always has values for Q and W even if you don't need them:</p> <pre><code>mapper = {&quot;Q&quot;: 1, &quot;W&quot;: 2} mapper.update({label: i+2 for i, label in enumerate(indata2[~indata2[&quot;Label&quot;].isin([&quot;Q&quot;,&quot;W&quot;])][&quot;Label&quot;].unique())}) indata2[&...
python|python-3.x|pandas|numpy
1
356,792
69,862,726
Numpy extracting data in one column versus another
<p>I have the following problem with extracting data in one column versus another.</p> <pre><code>import numpy as np from numpy import genfromtxt df = genfromtxt('data.csv', delimiter=&quot;,&quot;) data1 = [] data2 = [] data3 = [] for i in range(150): if df[i,4] == 0: data1 += df[i,0] elif df[i,4] =...
<pre><code>df = np.array([[4.9, 3., 1.4, 0.2, 0.], [6.2, 2.2, 4.5, 1.5, 1.], [6.3, 2.3, 4.7, 1.8, 1.], [6.5, 2.9, 1.5, 6.5, 2.]]) data1 = list(df[df[:, 4] == 0, 0]) data2 = list(df[df[:, 4] == 1, 0]) data3 = list(df[np.isin(df[:, 4], (0, 1), invert=True), 0]) print(data1, ...
python|numpy|csv|file
1
356,793
69,689,140
Using Pandas function isin()
<p>I explain my problem to you. I have a data frame and I want to add a column (true / false). This dataframe contains the following columns: Référence, msn, description... I have another dataframe containing a reference called &quot;AM&quot; and other columns. The objective of filling this one column (true / false) if...
<p>It's a warning, use</p> <pre><code>df.loc[:, &quot;Avis BE&quot;] = False df.loc[df[&quot;Référence&quot;].isin(df1[&quot;AM&quot;]), &quot;Avis BE&quot;] = True </code></pre> <p>Also refer pandas documentation for indexing and setting values. it highlights this issue and suggesets better practices. <a href="https:/...
python|pandas|dataframe
0
356,794
69,953,917
Stacking multiple 2d arrays by picking 1 column from each of the arrays
<p>I have 3 numpy arrays of dimensions 20x308 each. I want to stack them so that i have the first column from 1st array, 1st column from 2nd array, 1st from 3rd and then 2nd from each and so on so that i will end up with 20x924 array. I have tried by looking at np.column_stack but that won't work. Thank You.</p>
<p>I have found a solution now, by using dstack and reshape.</p> <pre><code> a = np.ones((2,3)) b = np.zeros_like(a) d = [[1,3,5], [2,5,9]] c = np.dstack([a, b,d]).reshape(2,9) </code></pre>
python|arrays|numpy|stack
0
356,795
69,819,992
df.to_html setting column width for each column using col_space
<p>I was going through the documentation <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html</a> It says I can pass a list. My understanding is passing a list should set width for each c...
<p>Read pandas df.to_html documentary. If your pandas version is below 0.25.0 it wont work. <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html</a></p>
python|pandas
1
356,796
69,793,013
How can I apply BeautifulSoup on a part of a HTML tag collected in a CSV?
<p>I have a CSV where one column has strings with a full HTML table on each row.</p> <p>I want to navigate those tables and extract the TDs corresponding to some definite THs. BeautifulSoup, obviously, raises an error saying it can't read strings, only HTML.</p> <p>What should I do? Is Beautiful Soup really the best wa...
<p>If you want to read a HTML string and parse the data, a better option might be the etree module from lxml,</p> <pre><code>from lxml import etree tree = etree.fromstring(your_html_string) </code></pre> <p>You can parse the <code>tree</code> object by passing in the xpath to the desired elements.</p> <pre><code>tds = ...
python|pandas|beautifulsoup
1
356,797
69,966,530
How do I delete this or that row in python?
<p><code>one.dropna(subset = ['director', 'cast'])</code></p> <p>When I use this I delete both rows, but I want to delete either director or cast rows that are NaNs, how do I do that?</p>
<p><code>one.dropna(subset = ['director', 'cast'], how = 'any')</code></p> <p>You need to add <code>how</code> parameter inside the dropna function. It can be either 'any' or 'all'.</p>
python|pandas
0
356,798
70,017,142
Best way to select column with OR condition
<p>I am comparing data where the same quantities are given by different names ('radius', 'r', 'Radius[m]', etc.) in the different DataFrames I am comparing. Now I need to loop over these DataFrame and select a quantity. What would be the most elegant/clean way to select column based on an <code>OR</code> condition? So ...
<h3><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rename.html" rel="nofollow noreferrer"><code>DataFrame.rename</code></a></h3> <p>Assuming each dataframe will only contain one of those quantities, you can <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rename.html" rel="...
python|pandas|dataframe
1
356,799
69,821,377
pandas translate from a column that is a list to create new columns with all options as a binary yes/no if the value exists in the original list
<p>given the data set</p> <pre><code>#Create Series s = pd.Series([[1,2,3,],[1,10,11],[2,11,12]],['buz','bas','bur']) k = pd.Series(['y','n','o'],['buz','bas','bur']) #Create DataFrame df from two series df = pd.DataFrame({'first':s,'second':k}) </code></pre> <p>I was able to create new columns based on all possible v...
<p>From your update it seems that what you need is simply:</p> <pre><code>for opt in unique : df[opt]=df['first'].apply(lambda x: int(opt in x)) </code></pre> <p>Output:</p> <pre><code> first second 1 2 3 10 11 12 buz [1, 2, 3] y 1 1 1 0 0 0 bas [1, 10, 11] n 1 0 0 1 1 ...
python|pandas
1