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
373,100
27,614,282
How to use user-defined input for column name in pandas series
<p>I am looking to understand how to use a user-defined variable within a column name. I am using pandas. I have a dataframe with several columns that are in the same format, but the code will be run against the different column names. I don't want to have to put in the different column names each time when only the fi...
<p>If I understand right, you could do <code>df[vari+'_count_litter']</code>. However, you may be better off using a MultiIndex that would let you do <code>df[vari, 'count_litter']</code>. It's difficult to say how to set it up without know what your data structure is and how you want to access it.</p>
python|pandas|series
0
373,101
27,717,776
Lazy loading csv with pandas
<p>I have a huge 22 GB csv file that contains a matrix 10000 x 10000 entries. But actually I only need a small portion of file for my purpose that can fit well within my 4 GB ram. Is there anyway to lazy load the CSV to my system so that I need to pick only some non contagious portion of the file say 25 different spec...
<p>For a small number of lines try using <a href="http://pymotw.com/2/linecache/" rel="noreferrer">linecache</a> and manually creating a pandas DataFrame.</p> <p>For example, the following code puts lines 12, 24, and 36 (1-indexed) into a DataFrame.</p> <pre><code>import linecache from pandas import DataFrame filena...
python|csv|pandas
6
373,102
27,555,359
How to select specific column indices from a matrix?
<p>I have a matrix and a list of column indices that I want to select from the matrix for each row. How can I do that in numpy?</p> <pre><code>my_matrix = np.array([[1, 2], [4, 5]]) col_idx = np.array([1, 0]) selected = .... # selects 1st element of row 0 and 0th element of row 1. print selected # np.array([2, 4]) </c...
<p>You can slice using range:</p> <pre><code>In [11]: my_matrix[np.arange(my_matrix.shape[0]), col_idx] Out[11]: array([2, 4]) </code></pre>
python|arrays|numpy
2
373,103
27,447,322
Insert field into structured array at a specific column index
<p>I'm currently using <code>np.loadtxt</code> to load some mixed data into a structured numpy array. I do some calculations on a few of the columns to output later. For compatibility reasons I need to maintain a specific output format so I'd like to insert those columns at specific points and use <code>np.savetxt</cod...
<p>This is a way to add a field to the array, at the position you require:</p> <pre><code>from numpy import zeros, empty def insert_dtype(x, position, new_dtype, new_column): if x.dtype.fields is None: raise ValueError, "`x' must be a structured numpy array" new_desc = x.dtype.descr new_desc.inse...
python-3.x|numpy
2
373,104
27,862,710
Python Pandas Dataframe to Nested Tuples
<p>I have a simple Pandas data frame (df), structured like this:</p> <pre><code> a b c d 0 WW XX YY ZZ 1 AA BB CC DD 2 EE FF GG HH 3 ... </code></pre> <p>I'd like to get this into a nested tuple structure inside of a list that looks like this:</p> <pre><code>[ ((WW, XX), YY, ZZ), ((AA, BB),...
<p>If you have a dataframe like this:</p> <pre><code>&gt;&gt;&gt; df a b c 0 1 2 3 1 4 5 6 2 6 7 8 </code></pre> <p>You can get the raw values into a list form like this:</p> <pre><code>&gt;&gt;&gt; t = df.values.tolist() &gt;&gt;&gt; t [[1, 2, 3], [4, 5, 6], [6, 7, 8]] </code></pre> <p>from there you...
python|python-2.7|pandas
3
373,105
27,481,211
Error: Index out of bounds - Python
<p>I am still fairly new to Python and I am attempting to run a for loop. However, I receive an error indicating that my index is out of bounds. I'm not sure what exactly the problem is, any help is appreciated!</p> <p>My code and error are both below: </p> <pre><code>croot = 1 ctip = 1 span = 1 thetaroot = 0 theta...
<p>As you have mentioned in the comments that you are using numpy.zeros here, the value of theta in your code will be</p> <pre><code>theta = array([0,0,0]) # If size of n is 3 </code></pre> <p>If you wish to add elements to theta like theta = array([0, 1, 2]), you have to do it like this:</p> <p>theta[0][i] = i * pi...
python|for-loop|numpy|indexing
0
373,106
27,545,780
Combining numpy arrays to create a value field
<p>i have coded so far:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from scipy.special import * import matplotlib.pyplot as plt import numpy as np from math import * import csv ## Globale Variablen ## # kommen später ins main file, MÜSSEN vor dem import von diesem Modul definier...
<p>According to your explanation, the problem is in your definition of 'self.r' You want a list of the distances r between (x,y) and (xlage,ylage) for all combinations of x and y, i.e. a matrix. However, you have a vector which contains r belonging to (x1,y1), (x2,y2),(x3,y3) ... , i.e. you are missing the combinations...
python|arrays|numpy|dimensions
1
373,107
27,568,886
Install Python 2.7.9 over 2.7.6
<p>I'm using Python for my research. I have both version of Python on my system: 3.3.2 and 2.7.6. However due to the compatibility with the required packages (openCV, Numpy, Scipy, etc.) and the legacy code, I work most of the time with Python 2.7.6.</p> <p>It took me quite a lot of effort at the beginning to set up t...
<p>You can install the package that already exists in Debian jessie. I recommend doing an <code>apt-get update</code> and <code>apt-get upgrade</code> before starting.</p> <p>Create <code>/etc/apt/sources.list.d/python-jessie.list</code> and add</p> <pre><code>deb http://httpredir.debian.org/debian jessie main deb-sr...
python|python-2.7|opencv|numpy|upgrade
9
373,108
61,314,839
libtorch (PyTorch C++) weird class syntax
<p>In the official PyTorch C++ examples on GitHub <a href="https://github.com/pytorch/examples/blob/master/cpp/custom-dataset/custom-dataset.cpp" rel="noreferrer">Here</a> you can witness a strange definition of a class:</p> <pre><code>class CustomDataset : public torch::data::datasets::Dataset&lt;CustomDataset&gt; {....
<p>This is the <a href="https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow noreferrer">curiously-recurring template pattern</a>, or CRTP for short. A major advantage of this technique is that it enabled so-called <em>static polymorphism</em>, meaning that functions in <code>torch::data::d...
c++|pytorch|libtorch
9
373,109
61,208,308
How to handle exceptions for Numpy modules in python?
<p>I am new to Python development. I want to know how to handle the exception for Numpy module.</p>
<p>Use <code>try</code> and <code>except</code>:</p> <pre><code>try: (your statements...) except Exception as e: print(e) </code></pre>
python-3.x|numpy
0
373,110
61,314,299
How do I update row values before taking the mean of the columns?
<p>I have a dataframe that is formed from these lines of code</p> <pre><code>projections = pd.DataFrame({"stock":["A","B","C"], "strong":[.39,.30,.06], "moderate":[.17,.15,.14], "weak":[-.05,0,.22]}) projections = projections.set_index("stock") </code></pre> <p>Which looks like this.</p> <pre><code> strong...
<p>Can you try the following to see if it works?</p> <pre><code>( projections.T .assign(B=lambda x: x.B.mul(-1)) .mean(1) ) </code></pre> <p>If you have multiple rows to multiply by -1, you can put all those rows to mylist and try the following code.</p> <pre><code>mylist = ["A", "B"] ( projections ...
python|pandas
1
373,111
61,438,269
how to decrease the decimal places in the mantissa part of an exponential number in an output in python
<p>THE CODE</p> <pre><code>avogadro = 6.0225e23 # define Avogadro number at_wt = 63.55 print ("atomic weight of copper = 63.55") print("weight of an atom = atomic weight/Avogadro's number") x = at_wt/ avogadro print ("Weight of one atom of copper = {}".format(x) ) THE OUTPUT atomic weight of copper = 63.55 weight of ...
<p>Use a better <a href="https://docs.python.org/3.8/library/string.html#formatspec" rel="nofollow noreferrer">format</a> string:</p> <pre><code>print ("Weight of one atom of copper = {:0.3e}".format(x) ) </code></pre>
python|numpy
0
373,112
61,298,127
pandas number of items in one column per value in another column
<p>I have two dataframes. say for example, frame 1 is the student info:</p> <pre><code>student_id course 1 a 2 b 3 c 4 a 5 f 6 f </code></pre> <p>frame 2 is each interaction the student has with a program</p> <pre><code>student_id day number_of_clicks 1 ...
<p>First we aggregate your <code>df2</code> to the desired information using <code>GroupBy.agg</code>. Then we <code>merge</code> that information into <code>df1</code>:</p> <pre><code>agg = df2.groupby('student_id').agg( no_days=('day', 'size'), total_clicks=('number_of_clicks', 'sum') ) df1 = df1.merge(agg,...
python|pandas
1
373,113
61,398,095
Standardize axis as multiple graphs generated from dataframe
<p>I have a seemingly simple problem of standardizing and labeling my axis on a series of graphs I am creating from a DataFrame. This dataframe contains a column with a sort of ID and each row contains a value for x and a value for y. I am generating a separate graph for each ID; however, I would like a standard axis a...
<p>If you mean by <code>standard</code> having the same ticks, there are different ways of doing this, one is, if you don't have a lot of plots, create a subplot that shares the same x-axis, </p> <pre><code>no_rows = len(data.groupby('Pedigree')) no_columns = 1 fig, ax = plt.subplots(no_rows, no_columns, sharex = True...
python|pandas|matplotlib
1
373,114
61,515,211
How can I improve the runtime of reading multiple excel files using python?
<p>I created function that iterates over a folder containing excel files and creates a list of all the headers across all sheets. I<strong>t works fine but is VERY slow</strong>. Do you have any ideas on how to improve it? THANKS!</p> <pre><code>import glob # file directory path = r'C:\Users\John\Excel_folder' all_f...
<p>you can pass <code>None</code> to <code>sheet_name</code> in <code>read_excel</code> to read all sheets at once. It creates a dictionary of dataframe, so at the end you can do with list comprehension.</p> <pre><code>def get_columns(file): return [c for df in pd.read_excel(file, ...
python|excel|pandas|runtime
1
373,115
61,545,110
Converting a dictionary including lists with different lengths to a 2-column dataframe
<p>I have a dictionary like this one</p> <pre><code>my_dict = {0:[1,2], 1:[1, 5, 100,120], 2:[1, 89, 90, 1625, 98, 0, 10]} </code></pre> <p>I want to convert it to a data frame with just two columns like this one.</p> <pre><code>col1 col2 0 [1, 2] 1 [1, 5, 100,120] 2 [1, 89, 90, 1625, 98...
<pre><code>#Input dictionary my_dict = {0:[1,2], 1:[1, 5, 100,120], 2:[1, 89, 90, 1625, 98, 0, 10]} #Convert dictionary to dataframe df = pd.DataFrame(my_dict.items(),columns=["col1","col2"]) print(df) </code></pre> <p><strong>Output:</strong></p> <pre><code> col1 co...
python|pandas|list|dataframe|dictionary
4
373,116
61,317,660
Iterating over dataframe column and creating new column in python pandas
<p>I have a dataframe like this <code>DataFrame</code></p> <p><a href="https://i.stack.imgur.com/bY2cM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bY2cM.png" alt="enter image description here"></a></p> <p>I want to create a new column(seq) and do the following things</p> <ul> <li><code>df['seq...
<p>The easiest solution it comes to me is to create an array and fill it with the value of a <code>counter</code> when you loop over your dataframe. You will add the new column after.</p> <p>For example:</p> <pre><code>seq = np.zeros(len(df)) date = '' id = 0 counter = 0 for i in range(len(df)): test_date = df['D...
python|pandas
0
373,117
61,318,304
Replace method not removing string from pandas dataframe column
<p>Hi I have a pandas dataframe column which I need to set as numeric. </p> <p>First I need to remove the 'M' (for millions) from the data. Then I can use to_numeric function. But the end result seems to just be a series of NaN's. Looking further into it, the numeric method isn't working because the column still conta...
<p>Maybe you can try another way by using this <code>df.Value=df.Value.str[:-1]</code> to remove the M. </p>
python|pandas
1
373,118
61,360,530
Creating data frames from a groupby data frame
<p>I have this <a href="https://i.stack.imgur.com/ea1w8.png" rel="nofollow noreferrer">DataFrame</a> containing stock data and I want to iterate over it to create one df for each ticker (ex. PETR4.SA). I've done it manually with <code>groupby</code> and <code>.get_group</code>, but I don't know how to do it with <code>...
<p>you can do this with the help of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.groups.html" rel="nofollow noreferrer"><strong>groups</strong></a> property of groupby. groups return a <strong>Dict {group name -> group labels}</strong>.</p> <pre><code>import pandas as...
python|pandas|loops|dataframe|data-science
0
373,119
61,300,553
How to concatenate word2vec generated features with VGGNet generated features
<p>I am working on movie dataset <strong>scraped</strong> from IMDB site. More importantly, i am working on two info i.e.movie overviews and movie poster data.</p> <p>In the first part i process the overview data and vectorize using word2vec. I get the following features:</p> <pre><code>print(X.shape);print(Y.shape) (...
<p>Word2vec, alone, just creates vectors for words. Are you doing another step, like averaging all the words of a description together, to get a 300-dimensional vector for a multi-word text? </p> <p>That can work as a simple baseline, but can lose subtleties compared to other methods of vectorizing a multi-word text. ...
python|numpy|word2vec|vgg-net
0
373,120
61,414,450
How to use a single filter over multiple dataframes in python
<p>In Python I want to use the same filter condition on multiple dataframes.</p> <p>What I currently have is:</p> <pre><code>filtered_df1=df1[(df1['Timestamp'] &gt; Lower_limit) &amp; (df1['Timestamp'] &lt; Upper_limit)] filtered_df2=df2[(df2['Timestamp'] &gt; Lower_limit) &amp; (df2['Timestamp'] &lt; Upper_limit)] f...
<p>maybe this will help</p> <pre><code> #convert to datetime Lower_limit, Upper_limit= '2019-12-4 06:00:00', '2019-12-6' Upper_limit = pd.to_datetime(Upper_limit) Lower_limit = pd.to_datetime(Lower_limit) #read in columns and change Timestamp to another name #Timestamp is a type ... cant compare time with type df1...
python|pandas|timestamp
2
373,121
61,304,599
Random orthogonal, 90 degrees rotation with ImageDataGenerator
<p>I use following code to train my CNN model with invoice images.</p> <pre><code>train_datagen = ImageDataGenerator( rescale = 1. / 255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True ) test_datagen = ImageDataGenerator(resc...
<p>I would rotate the images randomly with <code>ImageDataGenerator</code>. Just specify the following argument:</p> <blockquote> <p>rotation_range: Int. Degree range for random rotations.</p> </blockquote> <p>Or, you can pass a preprocessing function to <code>ImageDataGenerator</code> which gives you more flexibil...
python|tensorflow|image-processing|keras|conv-neural-network
4
373,122
61,575,985
Pandas datetime64 problem (datetime introduces spikes in data)
<p>This is my first question on stackoverflow, so be kind :) I work with imported csv files and pandas and really liked the pandas datetime possibilities to work and filter dataframes. But i have serious problems with plotting the data in a neat way when using dates as datetime64. Either when using pandas plots or seab...
<p>Your problem is no miracle, it's simply not reproduciable.</p> <ol> <li>Are you sure your csv doesn't have a header for the first index column 0..4?</li> <li>Are you sure in the csv column 8 is a duplicate of column 7?</li> <li>How did you actually import this csv and construct your dataframe?</li> <li>The first pl...
python|pandas|datetime|matplotlib|plot
0
373,123
61,517,044
How to find the top column values of each row in a pandas dataframe
<p>For a given dataframe with <code>m</code> columns (lets assume <code>m</code>=10), with in each row, I am trying to find top <code>n</code> column values (lets assume <code>n</code>=2). After finding these top <code>n</code> values for each row, I would like to assign the remaining column values, <code>m</code> - <c...
<p>First idea is compare top N values per rows by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.nlargest.html" rel="nofollow noreferrer"><code>Series.nlargest</code></a> and the nset values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.ht...
python|pandas
4
373,124
61,601,465
It seems tensorflow is not recognizing my GPU, how to fix it?
<p>I installed <code>tensorflow-gpu</code>into my new computer, and the system, and everything is recognizing perfectly my GPU, for that I tried on my terminal:</p> <h1>Nvidia test:</h1> <pre><code>nvcc --version nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2019 NVIDIA Corporation Built on Sun_Jul_28_19:...
<p>Your GPU is being detected, you just didn't install everything correctly. You need this post: <a href="https://stackoverflow.com/questions/50622525/which-tensorflow-and-cuda-version-combinations-are-compatible">Which TensorFlow and CUDA version combinations are compatible?</a>. I think your <code>cuda</code> is OK, ...
python|tensorflow|tensorflow2.0
1
373,125
61,223,280
Load image dataset from directory in place of MNIST dataset from tf.load
<p>I want to implement stacked capsule autoencoders (see <a href="https://github.com/google-research/google-research/tree/master/stacked_capsule_autoencoders" rel="nofollow noreferrer">here</a>) on my dataset. While implementing, I am facing the following issues :</p> <p>The MNIST dataset is loaded as follows:</p> <p...
<p>try this one:</p> <pre><code>img_list = [] for img in glob.glob(&quot;photos/*.jpg&quot;): n= cv2.imread(img) img_1 = tf.convert_to_tensor(np.array(cv2.resize(n, (256, 256)))) img_list.append(img_1) train_photos = tf.data.Dataset.from_tensor_slices(img_list).repeat().batch(64) </code></pre>
python|tensorflow|tensorflow-datasets
0
373,126
61,427,087
How to perform breadth first search using python3 pandas dataframes
<p>A single row in the dataframe looks like the following:</p> <pre><code>source Bubble Sort target Sorting Algorithms Visualization : Bubble Sort edge https://www.geeksforgeeks.org/sorting-algorithms-...
<p>I think you're looking for this, if I understood the question correctly:</p> <pre><code>print(df[(df['source'] == 'Bubble Sort') &amp; (df['target'] == 'Sorting Algorithms Visualization : Bubble Sort')]['edge']) 0 https://www.geeksforgeeks.org/sorting-algorith... </code></pre>
python-3.x|pandas|dataframe|breadth-first-search
0
373,127
61,381,508
Add hover text in plotly.express
<p>The dataframe <code>df</code>:</p> <pre><code> Id timestamp C Date sig events1 Start Peak Timediff2 datadiff2 B 51253 51494 2020-01-27 06:22:08.330 19.5 2020-01-27 -1.0 0.0 NaN 1.0 NaN NaN NaN 51254 51495 2020-01-27 06:22...
<p>You tried:</p> <pre><code>fig = px.line(x=df['Timestamp'], y=df['C'], hover_data=["B"]) </code></pre> <p>If you read the error message, you'll see that <code>["B"]</code> should be <code>df['B']</code></p> <p>So try:</p> <pre><code>fig = px.line(x=df['Timestamp'], y=df['C'], hover_data=df["B"]) </code></pre> <p...
python|pandas|matplotlib|plotly
3
373,128
61,520,151
Normalise all vectors on the z axis
<p>I have written code that calculates the angle between two vectors. However the way in which is does this is to start with two vectors, rotate each according to some euler angles calculated in a separate program, then calculate the angle between the vectors.</p> <p>Up until now I have been working with a use case th...
<p>I'm not sure to fully understand what you need but if it is to compute the angle between two vectors in space you can use the formula:</p> <p><a href="https://i.stack.imgur.com/ySZyb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ySZyb.png" alt="enter image description here"></a></p> <p>where a...
python|numpy|math|vector
1
373,129
61,209,623
How to concatenate new data from a separate file as a new column of a numpy array?
<p>I have 2 text files as follows: animals = ['tiger'; 'lion'] and birds = ['parrot'; 'eagle']</p> <p>Now I have to fetch these values into a numpy array and the array must look as follows: <a href="https://i.stack.imgur.com/lWj0S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lWj0S.png" alt="ente...
<p>You can use the logic below. I assume you have two lists animals, birds and your required array is list_req</p> <pre><code>animals = ['tiger', 'lion'] birds = ['parrot', 'eagle'] list_req = [] list_req.append(animals) list_req.append(birds) list_req = np.transpose(list_req) </code></pre>
python-3.x|numpy|numpy-ndarray
1
373,130
61,399,240
Pandas merge two time series dataframes based on time window (cut/bin/merge)
<p>Having a 750k rows <code>df</code> with 15 columns and a <code>pd.Timestamp</code> as <code>index</code> called <code>ts</code>. I process realtime data down to milliseconds in near-realtime.</p> <p>Now I would like to apply some statistical data derived from a higher time resolution in <code>df_stats</code> as ne...
<p>Let us try something new <code>reindex</code></p> <pre><code>df_stats=df_stats.set_index('ts').reindex(df['ts'], method='nearest') df_stats.index=df.index df=pd.concat([df,df_stats],axis=1) </code></pre> <p>Or </p> <pre><code>df=pd.merge_asof(df, df_stats, on='ts',direction='nearest') </code></pre>
pandas|dataframe|merge|pandas-groupby|pandas-apply
2
373,131
61,296,676
Scale between -1 and 1
<p>I have a data frame with positive,negative and neutral sentiment analysis percentages of a text and I am trying to scale this data into a number that is between -1(most negative) and 1(most positive). What would be the best formula to determine this score?<br> Dataframe example: <br> Data columns (total 11 columns):...
<p>This can be seen as min-max scaling. To get a value in [-1,1] one would do:</p> <pre><code>val = (2 *(val - min)/(max-min)) - 1 </code></pre> <p>Nedless to say that val is the current value being normalized, min is the smallest of all values and max the biggest of all values.</p>
python|pandas|dataframe|sentiment-analysis
1
373,132
61,214,119
How to retrieve the column name and row name with a condition satisfied in a dataframe?
<p>I need to check a condition if the sum of columns is 1 and if satisfies i want to retrieve the column names and row number in a dictionary. <a href="https://i.stack.imgur.com/9x9Dp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9x9Dp.png" alt="enter image description here"></a></p> <p>The output...
<p>With Pandas you can do it</p> <pre><code>import pandas as pd # Import data df = pd.read_excel("location_file") # Create a dictionary dict = dict() # Iterate in columns for i in df.columns: if df[i].sum() == 1: dict[i] = df.Employee_No[df[i] == 1] # Add filter data to dict </code></pr...
python|pandas
0
373,133
61,470,803
ValueError: No gradients provided for any variable....in tensorflow V.2.1.0
<p>I'm trying to write this tensorflow tutorial and I got the below error:</p> <blockquote> <p>ValueError: No gradients provided for any variable: ['Variable:0', 'Variable_1:0', 'Variable:0', 'Variable_1:0', 'Variable:0', 'Variable_1:0', 'Variable_6:0', 'Variable_7:0'].</p> </blockquote> <pre><code>import tenso...
<p>Oh my... If your new to tensorflow, you should really become familiar with layers, training, testing, making models, and such. From what I can tell, what you have above is a detailed expansion of what goes on under the hood of the following code: </p> <pre><code>import tensorflow as tf mnist = tf.keras.datasets.mn...
python|deep-learning|neural-network|tensorflow2.0
0
373,134
61,278,836
Replace string in one part pandas dataframe
<pre><code>print(df["date"].str.replace("2016","16")) </code></pre> <p>The code above works fine. What I really want to do is to make this replacement in just a small part of the data-frame. Something like:</p> <pre><code>df.loc[2:4,["date"]].str.replace("2016","16") </code></pre> <p>However here I get an error:</p>...
<p>What about <code>df['date'].loc[2:4].str.replace('2016', 16')</code>?</p> <p>By selecting <code>['date']</code> first you know you are dealing with a series which does have a string attribute.</p>
python|pandas|dataframe
2
373,135
61,483,532
Can I delimit one column to many in pandas at a specific column index location, or move the location of the resulting columns in bulk?
<p>I have a datafram with 60+ columns. One column (at index 10) needs to be delimited to 6 new columns on the '_' character. I am assigning the new columns like this:</p> <pre><code>df[['col1','col2','col2','col3','col4','col5','col6']] = df['original_col'].str.split('_',expand=True) </code></pre> <p>This works, but ...
<p>While I could not get this done in one line I solved the problem by adding:</p> <pre><code>new_cols = ['c1', 'c3', 'c2','c6'...] df_new_order = df.reindex(columns = new_cols) </code></pre> <p>Its a little tedious with 60+ columns, but you can just copy/paste them into order and it works. It seems logical now that ...
python|pandas|dataframe
1
373,136
61,471,416
Get tensorflow and keras to run on GPU
<p>I'm trying to get my model to train on GPU, but seem to have problem in doing so.</p> <p>My os is Windows 10</p> <p>I'm running Python 3.8</p> <p>I installed tensorflow-gpu==2.2.0rc3 using pip3.8</p> <p>I followed the instructions at <a href="https://www.tensorflow.org/install/gpu" rel="nofollow noreferrer">http...
<p>Tensorflow is often picky about the python version. Try downgrading to python 3.7 (or any other version listed as <a href="https://www.tensorflow.org/install/pip" rel="nofollow noreferrer">supported</a>).</p> <p>Also, you can try using <a href="https://docs.conda.io/en/latest/miniconda.html" rel="nofollow noreferre...
python|tensorflow|keras
1
373,137
61,333,673
Grouping consecutive values
<p>Below, I have sample input and output data. Input data is the dataframe <code>g_input</code> like</p> <pre><code> 0 1 2 3 4 5 0 1 0 1 1 1 1 1 0 1 1 1 0 0 2 0 1 1 1 1 1 3 1 1 0 1 1 1 4 1 1 1 1 0 0 5 0 0 1 0 1 0 6 1 1 1 0 1 0 </code></pre> <p>The Intermediate output called <code>g_intermediate</code> would look lik...
<p>We need <code>stack</code> then multiple <code>groupby</code> with <code>cumsum</code> and <code>transform</code> <code>count</code></p> <pre><code>s=df.stack().diff().ne(0).groupby(level=0).cumsum() s=s.groupby([s.index.get_level_values(0),s]).transform('count').unstack() thresh=2 s.gt(thresh).astype(int) 0 1 ...
python|pandas
2
373,138
61,548,650
How to do vlookup on excels(different column names) using python
<p>experts, i want to perform vlookup between two excels with two different column names and output column name also to be differnt. </p> <p>Lets take below example to understand scenario In source excel file1 I am having column name as "Computer name" at position A, In source excel file2 I am also having column name ...
<p>so guys finally i have done it with following code. Though i have added column list manually and still finding a way by which i can give this column list dynamically.</p> <pre><code>import pandas as pd import numpy as np import warnings warnings.filterwarnings('ignore') avclient_workbook ="File1.xlsx" cmdb_workboo...
python|excel|pandas
0
373,139
61,469,802
UNET training: accuracy starts over 0.99
<p>I am trying to do some image segmentation using UNET (similar to <a href="https://stackoverflow.com/questions/56715122/training-a-unet-model-but-model-is-not-learning">this</a> but 2D ). However, the accuracy starts really high even at the beginning of epoch 1.</p> <pre><code>32/3616 [.................................
<p>You are probably dealing with imbalanced dataset. Your network can have the accuracy of 99% when structures you are trying to segment are small (and take, for example, 1% of the image). Then, if your network predicts only 0s, you will get 99% accuracy (because it will be correct to predict 99% of "empty" pixels).</p...
python-3.x|tensorflow|keras|deep-learning|image-segmentation
2
373,140
61,386,299
Pandas: Convert Column to timedelta64
<p>I try to read a CSV file as pandas data frame. Beside column names, I get the expected dtype. My approach is:</p> <ol> <li>reading the CSV with inferring column types (as I want to be able to catch issues)</li> <li>reading the expected column types</li> <li>iterating over the columns and try to convert them with <c...
<p>Thanks to <a href="https://stackoverflow.com/questions/61386299/pandas-convert-column-to-timedelta64?noredirect=1#comment108713254_61386299">MrFuppes</a>.</p> <p>It's not possible to use <code>astype()</code> but <code>to_timedelta</code> works. Thank you!</p> <pre><code>df['timedelta'] = pd.to_timedelta(df['timed...
python|pandas|timedelta
0
373,141
61,204,353
How to style stackplot color in pandas
<p>I'm trying to work out how to style a stacked bar chart in Pandas.</p> <p>I've written a line of code in a Jupyter notebook which produces a plot like below. So far so simple:</p> <pre><code>df.plot(kind = 'bar', stacked=True, color=['green', 'blue'], legend=None) </code></pre> <p>However, I want to change the co...
<p>Thank you to @PaulBrodersen. Turns out I needed to use full six-digit hex code such as #ccccccc rather than shorthand although latest version of Matplotlib 3.2 does support short codes. Thank you.</p>
pandas|matplotlib|visualization
0
373,142
61,456,345
sklearn matching results become misaligned when the data sets increase
<p>I've been using sklearn NearestNeighbors to do name matching and at a certain point the results become misaligned. My standardized list of names is 100s of millions. My list of names coming in to be matched is considerably smaller but still could be in the 250k to 500k range. After a certain point it appears the i...
<p>Sets don't guarantee preservation of order in general. So the order in which <code>getNearestN</code> iterated through <code>unique_org</code> may not be the same order that the <code>list</code> constructor did:</p> <pre class="lang-py prettyprint-override"><code>distances, indices = getNearestN(unique_org) # com...
python|pandas|machine-learning|scikit-learn|unsupervised-learning
1
373,143
61,608,010
Pytorch C++ (libtorch) outputs different results if I change shape
<p>So I'm learning Neural networks right now and I noticed something really really strange in my network. I have an input layer created like this</p> <pre><code>convN1 = register_module("convN1", torch::nn::Conv2d(torch::nn::Conv2dOptions(4, 256, 3).padding(1))); </code></pre> <p>and an output layer that is a tanh fu...
<p>THANK YOU @MichaelJungo turns out you were right in that one of my BatchNorm2d wasn't being set to eval mode. I was unclear how registering modules worked in the beginning (still am to an extent) so I overloaded the ::train() function to manually set all my modules to the necessary mode.</p> <p>In it I forgot to se...
c++|neural-network|pytorch|reshape|libtorch
0
373,144
61,496,193
I dont understand the bulit-in function (shape)
<p>I am wondering x.shape[0] is whether row or column of the array.</p> <p>I coded...</p> <pre><code>x=np.array([1,2,3,4]) y=np.array([[1,2,3],[4,5,6]]) print(x.shape) print(y.shape) </code></pre> <blockquote> <blockquote> <blockquote> <p>(4,) (2,3)</p> </blockquote> </blockquote> </blockquot...
<p>Thinking about the shape of NumPy arrays in the form of rows and columns will quickly let you down if you start working with more complicated data.</p> <p>NumPy arrays are in fact multi-dimensional <a href="https://en.wikipedia.org/wiki/Tensor" rel="nofollow noreferrer">tensors</a>. A tensor can have any number of ...
python|arrays|numpy
0
373,145
61,271,216
Does TensorFlow Autograph recognising the "is" operator?
<p>Consider the following Python code</p> <pre><code>@tf.function(autograph=True) def foo(x, flag): if flag is True: x = tf.add(x, 1) return x </code></pre> <p>Now consider, this code where the only difference is the "is" is changed to a "=="</p> <pre><code>@tf.function(autograph=True) def foo(x, flag):...
<p>Libraries like Tensorflow, sympy, SQLAlchemy and others take advatage of Python's "operator overloading" feature - that is, for the specialized objects defined in those libraries, the comparison operators like "==, >, &lt;, !=" - actually, all other mathematical operators as well - "+, -, *, /", and others that are ...
python|tensorflow
1
373,146
61,304,720
workaround for numpy np.all axis argument; compatibility with numba
<p>I have a function that, given a numpy array of xy coordinates, it filters those which lies within a box of side L</p> <pre><code>import numpy as np from numba import njit np.random.seed(65238758) L = 10 N = 1000 xy = np.random.uniform(0, 50, (N, 2)) box = np.array([ [0,0], # lower-left [L,L] # upper-rig...
<p>I really, really, really wish numba supported optional keyword arguments. Until it does, I'm pretty much ignoring it. However, some hacks are possible here.</p> <p>You'll need to take extra care for anything that has other than 2 dimensions or has lengths that might be zero.</p> <pre><code>import numpy as np from ...
python|numpy|numba
7
373,147
61,419,742
TypeError: fun() missing 1 required positional argument: 'a'
<p>I know there are plenty of subject on this error and I've been on many of them trying to understand what is going on with sush a simple system. Here is my code, solving a very simple equation to test the efficiency of solve_ivp vs odeint. </p> <pre><code>import numpy as np import numpy as np import matplotlib.pyp...
<p><code>args</code> is supposed to be a tuple</p> <pre><code>In [281]: sol = solve_ivp(fun, tspan, x0, t_eval = t, args = (1,)) In [282]: sol Out[282]: message: 'The solver successfully re...
python|numpy|scipy|solver
0
373,148
61,503,256
How to get read_html to loop? Python
<p>I currently have the following code, the df2 = df[0] restricts the code to only gather data for 1 game on that corresponding date. I am trying to figure out how to gather multiple games data that took place on the same day.</p> <p>Idea is to extract match data for all games taken place on one day and continue runni...
<p>ok. So you just need to loop through the sub tables it pull form the tables. Also, I made one other change. Instead of setting <code>index = 0</code> then increment after each loop, you can use <code>enumerate()</code> which will do that sort of for you. See if this works:</p> <pre><code>import requests import pand...
python|pandas|beautifulsoup|jupyter-notebook
0
373,149
68,820,452
How to read_csv with incorrectly formatted file
<p>I have a text file as sample below:</p> <pre><code>col A,col B,col C,col D,col E val A1,val B1,val C1,val D1,val E1, val E2, val E3 val A2,val B2, val C2,val D2, val E4 </code></pre> <p>Please note that some values in col E has multiple values which contains &quot;,&quot; e.g <strong>val E1, val E2, val E3</strong><...
<ul> <li>This solution is <strong>80x faster</strong> than this <a href="https://stackoverflow.com/a/68820680/7758804">solution</a>, on a file with 31201 rows.</li> <li>The file is not a correctly formatted csv file. Multiple comma separated values that belong in 1 column should be in double quotes like <code>&quot;val...
python|pandas|dataframe|csv
1
373,150
68,578,980
How can I set up the y value of a matplotlib grid of 2x2 to a shared constant?
<p>I am currently working on a project that will plot the data collected from a accelerometer. In order to get a good insight of what we will do I need to plot the data as a grid which I have done with matplotlib:</p> <pre><code>fig, axs = plt.subplots(2, 2) axs[0, 0].plot(x, y) axs[0, 0].set_title(&quot;Non Faulty Acc...
<p>Matplotlib's <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html" rel="nofollow noreferrer">subplots()</a> has the <code>sharex</code> and <code>sharey</code> parameters that align the axes to the same range automatically.</p> <p>So in your case, you should simply use <code>subplots(2,...
python|numpy|matplotlib|graph
0
373,151
68,670,705
Can't get the shape I want when creating an array from a Python list & TypeError with sort
<p>When i specify the 'dtype' when creating an array i get a different shape than when i don't specify 'dtype'.</p> <p>I have this code below where i only want the function np.sort() to sort taking 'factor' and 'var' as parameters, not 'data'. Because inside 'data' i have 'None' values. When i run this code i get this:...
<p>The 2nd case makes <code>structured array</code>, with 3 fields, not 3 columns. If is 1d, not 2d. You may need to read the <code>structured array</code> docs a bit more carefully.</p> <p>As for the sort problem, re(read) <code>np.sort</code>:</p> <pre><code>order : str or list of str, optional When `a` is an a...
python|numpy
1
373,152
68,672,406
How to get a set of values from a Pandas dataframe?
<p>I have this Pandas dataframe with rows and columns having the same titles which are names of people: Alex, Bob, Cynthia and cells being the number of times they have met, where <code>-1</code> means that the cell is diagonal.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th styl...
<p>You can try:</p> <pre><code>set(df.values.flatten()) </code></pre> <p>And to exclude -1:</p> <pre><code>set(df.values.flatten()).difference([-1]) </code></pre>
pandas|dataframe|set
1
373,153
68,776,561
How to add a top n column based on another column in pandas
<p>Example dataframe:</p> <p>I have a dataframe that looks like this:</p> <pre><code>Item_Name Order ID Basket a Carpet b Basket c Carpet d Rug e </code></pre> <p>I want to have a new column called &quot;Top 2 Items&quot; which indicates whether or not the item name is top 2 based on f...
<p>Using <code>value_counts</code> you can return a sorted list of the frequency, so take the first 2 elements and use those with <code>np.where</code> to label your new column.</p> <pre><code>import numpy as np top2 = df['Item_Name'].value_counts().index[0:2] df['Top 2 Items'] = np.where(df['Item_Name'].isin(top2), '...
python|pandas
-1
373,154
68,782,365
How to display date in new table
<p>I apologize for the weird title, I'm new and I don't quite know the term for my question. I made a stock prediction program following a tutorial and this is what it displays right now. How do I get the dates to display alongside their respective prices? In the .csv file, the column showing dates is labeled 'Date'.</...
<p>If I don't misunderstand your question you just want to add a new column to your data frame. Just add a new column to your <code>dframe</code> from your <code>csv</code> <code>data</code>.</p> <pre><code>dframe[&quot;newcolumnfordate&quot;]=data[&quot;Date&quot;] </code></pre>
python|sklearn-pandas
2
373,155
68,689,149
What is the earliest version of Tensorflow that contains Tensorflow Lite?
<p>I'm wondering when exactly Tensorflow Lite was first introduced into the Tensorflow source code? What was the first Tensorflow release date / version that contained TFLite?</p>
<p>Edit: Looking at the past releases, I see that tensorflow lite was made an official module in 1.13.1 2019 version. Here is what is stated: TensorFlow Lite Move from tensorflow/contrib/lite to tensorflow/lite</p> <p>Old Answer: The details of when it was released are in this article: <a href="https://venturebeat.com/...
tensorflow|tensorflow-lite
1
373,156
68,639,249
How to save dict of DataFrames by copy?
<p>I have DataFrame with positionsSnapshots. One row is some position at some timestamp. I want to collect info about all positions at each timestamp and create dict with keys - timestamp of latest change in position and value - DataFrame with unique positions ID.</p> <p>My version return all DataFrames equals.</p> <pr...
<p>Is there a specific reason you need the DataFrame to be saved as a dictionary? Would another method of serializing work (i.e CSV, Pickle, etc.)?</p> <p>There is the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer">pandas method</a> <code>pd....
python|pandas|copy|deep-copy
0
373,157
68,686,662
Pandas: How to get the size of each chunk from big csv file?
<p>I have a big csv file having million rows. I would like to read that csv in chunks and save the count of rows of each chunks in dataframe for reference.</p> <pre><code>chunk_size=50000 for chunk in pd.read_csv('file.csv',chunksize=chunk_size): print(chunk.shape) </code></pre> <p>I want to save each chunk shape i...
<p>IIUC, you want something like this:</p> <pre><code>sizes = pd.DataFrame(columns=[&quot;Chunk&quot;, &quot;Size&quot;]) for i, chunk in enumerate(pd.read_csv(&quot;file.csv&quot;, chunksize=50000)): sizes.loc[i] = [f&quot;chunk{i+1}&quot;, chunk.shape[0]] </code></pre>
python|pandas
1
373,158
68,707,437
Pandas/Python - Create new column based on cross reference from other column
<p>I have a dataset with employee information. In this dataset the relevant fields are the EmployeeName column, ID column, and SupervisorName column. I want to create a new column called SupervisorID that gives us the ID of each employee's supervisor.</p> <p>Input dataframe:</p> <pre><code>EmployeeName ID SupervisorN...
<p>you can use merge, and merge the <code>DataFrame</code> with itself</p> <pre><code>import pandas as pd data =[{'EmployeeName': 'Jim', 'ID': 123,'SupervisorName': 'Brittany'}, {'EmployeeName': 'Brittany', 'ID': 345,'SupervisorName': 'Todd'}, {'EmployeeName': 'Todd', 'ID': 456,'SupervisorName': 'Grace'}] df = pd.Dat...
python|pandas|numpy|jupyter-notebook
0
373,159
68,865,097
change path name from each rows of the csv file
<p>I have a CSV file with 6 columns and the first column is the file name with the directory(<code>/imgs/train/uav0000072_05448_v/0000001.jpg</code>). now I want to add the full directory path with every row of this column(i.e <code>/home/Documnet/project/images/imgs/train/uav0000072_05448_v/0000001.jpg</code>). I am n...
<p>You can use pandas <code>apply</code> function. Let's say column name with paths is <code>col</code> then</p> <pre><code>df[col] = df[col].apply(lambda s: '/home/Document/project/images'+s) </code></pre>
python|pandas|list|csv
0
373,160
68,828,152
Is there a way to display regression coefficients in a pandas data frame for categorical independent variables?
<p>I have built a multiple linear regression model and I found the coefficients using <code>model.coef_</code>. I want to make a pandas data frame which displays each of the factors and its coefficient.</p> <p><code>pd.DataFrame(model.coef_, x.columns, columns = ['coef']).sort_values(by = 'coef', ascending = False)</co...
<p>You can set_index after</p> <pre><code>(pd.DataFrame({'coef':model.coef_, 'category':x.columns}) .sort_values(by = 'coef', ascending = False) .set_index('category')) </code></pre>
python|pandas|regression|coefficients
1
373,161
68,533,687
code to create all possible pairs of colums in pandas
<p>For the following df:</p> <pre class="lang-py prettyprint-override"><code>data=[['TAMU', 54, 0, 0, 6, 5, 0,],['UIUC', 33, 43, 5, 0, 76, 81], ['USC',4, 1, 0, 7, 21, 4], ['Austin',22,31, 0, 0,55, 0], ['UCLA', 55, 6, 7, 9, 11,12]] pd.DataFrame(data,columns = ['Name', 'Research', 'Thesis', 'Proposal', 'AI', 'Analytics'...
<p>Is this what you want?</p> <pre><code>[x for x in combinations(['Name', 'Research', 'Thesis', 'Proposal', 'AI', 'Analytics', 'Data'], 2)] </code></pre> <p>out:</p> <pre><code>[('Name', 'Research'), ('Name', 'Thesis'), ('Name', 'Proposal'), ('Name', 'AI'), ('Name', 'Analytics'), ('Name', 'Data'), ('Research', ...
python|python-3.x|pandas|dataframe|combinatorics
0
373,162
68,539,417
How to use rolling function to predict a trend based on either Simple Moving Average or some other strategy
<p>I have a code where I get the 44 days Simple Moving Average of a single stock given it's open, close, high, low, date as follows:</p> <pre class="lang-py prettyprint-override"><code>stocks.sort_index(ascending=False, inplace = True) # Without reverse, recent rolling mean will be either NaN or equal to the exact val...
<p>You can do it in the following way:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(dict(a=np.arange(10), b=np.random.randint(1, 10, 10), c=np.random.randn(10))) df.loc[:, 'Rolling Mean'] = df.apply(lambda row: df.loc[-5:row.name, 'b'].mean(), axis=1) df.loc[:, 'Valid'] = df.apply(lambda row...
python|pandas|numpy|time-series|data-science
0
373,163
68,623,720
Create custom gradient descent in pytorch
<p>I am trying to use PyTorch autograd to implement my own batch gradient descent algorithm. I want to create a simple one-layer neural net with a linear activation function and the mean squared error as the loss function. I can't seem to get my head around what exactly is happening in the backward pass and how PyTorch...
<p>Let's take a look at the implementation of <code>MSE</code>, the forward pass will be <code>MSE(y, y_hat) = (y_hat-y)²</code> which is straightforward. For the backward pass, we are looking to compute the derivative of the output with regards to the input, as well as the derivative with regards to each of the parame...
neural-network|pytorch|gradient-descent|backpropagation|autograd
1
373,164
68,804,524
Check if an array is an element of another array python
<p>I have a python array of 3d points such as [p1,p2,...,pn] where p1 = [x1,y1,zi] I want to check weather a particular point p_i is a member of this, what is the right method for this?</p> <p>Here is the code which I tried</p> <pre><code>import numpy my_list = [] for x in range(0,10): for y in range(0,10): ...
<p>Give the below a try</p> <pre><code>from dataclasses import dataclass from typing import List @dataclass class Point: x: int y: int z: int points: List[Point] = [] for x in range(0, 10): for y in range(0, 10): for z in range(0, 5): points.append(Point(x, y, z)) print(Point(1, ...
python|arrays|list|numpy
1
373,165
68,680,680
Python: fuzzywuzzy, the output of the first value is correct, the others are NaN
<p>I'm stuck in a very strange problem: I have two dfs and I have to match strings of one df with the strings of the other df, by similarity. The target column is the name of the television program (program_name_1 &amp; program_name_2). In order to let him choose from a limited set of data, I also used the column 'chan...
<p>This was for Index mismatch, resetting indices after adding first dataseries can do the work!</p> <pre><code>def scorer_tester_function(x): matching_list = [] similarity = [] # iterate on the rows for i in scorer_test_1: if pd.isnull(i): matching_list.append(np.null) s...
python|pandas|dataframe|nan|fuzzywuzzy
1
373,166
68,765,403
Group by list of different time ranges in Pandas
<p><strong>Edit:</strong> Changing example to use Timedelta indices.</p> <p>I have a DataFrame of different time ranges that represent indices in my main DataFrame. eg:</p> <pre><code>ranges = pd.DataFrame(data=np.array([[1,10,20],[3,15,30]]).T, columns=[&quot;Start&quot;,&quot;Stop&quot;]) ranges = ranges.apply(pd.to_...
<p>Here is one way to approach it:</p> <p>Generate the timedeltas and concatenate into a single block:</p> <pre><code># note the use of closed='left' (`Stop` is not included in the build) timedelta = [pd.timedelta_range(a,b, closed='left', freq='1s') for a, b in zip(ranges.Start, ranges.Stop)] timedelta =...
python|pandas
2
373,167
68,520,581
How to drop null/empty columns in a Pivot df while writing to excel
<p>I am trying to write into excel a pivot view of the following table. I am reading from index sheet of existing workbook(input.xlsx) and filtering for ID in excel DB(db1.xlsx) and trying to print pivot view of those dynamically in the input.xlsx.</p> <p>Index sheet of the input workbook:-<a href="https://i.stack.img...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df = df.replace(&quot;NOT APPLICABLE&quot;, &quot;&quot;) x = df[df.REMARKS.eq(&quot;GREEN&quot;)].pivot(&quot;SEGMENT&quot;, [&quot;PARAMETER&quot;, &quot;LEVEL&quot;], &quot;VALUE&quot;) x = x.reindex( pd.MultiIndex.from_tuples( sorted(x.columns...
python-3.x|pandas|dataframe|pivot-table|openpyxl
2
373,168
68,510,279
Python: Round decimal places after seconds in timestamp
<p>I have this series:</p> <pre><code>30478 2021-06-15 16:23:04.388 30479 2021-06-15 16:23:19.734 30480 2021-06-15 16:23:35.239 30481 2021-06-15 16:23:50.721 30482 2021-06-15 16:24:06.056 </code></pre> <p>Initially, I wanted to round to seconds by doing:</p> <pre><code>df[&quot;timestamp&quot;].dt.round('1s')...
<p>If <code>.388</code> should become <code>.380</code> we can <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>dt.floor</code></a> to the nearest 10 ms with:</p> <pre><code>df['timestamp'].dt.floor('10ms') </code></pre> <p>or</p> <pre><code>df['timestam...
python|pandas|timestamp|rounding|series
2
373,169
68,636,131
Tensorflow - Preprocessing image in model prediction
<p>I have trained a model using the Functional API and two different kind of pre-trained model: EfficientNet B5 and MobileNet V2. After tranining with the saved model, I'm running an application which uses that model to make some predictions.</p> <p>I'm fronting a doubt relatated to what is the correct way to pass the ...
<p>I copied your code and then printed out the model summary as shown below</p> <pre><code>Model: &quot;functional_5&quot; __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ...
python|tensorflow|computer-vision|conv-neural-network|image-preprocessing
0
373,170
68,624,015
Matching a value from a csv file to a particular variable depending on the filename
<p>I have a column in a csv file that contains values I wish to match to a file in a python directory I have (I want to match by date). To do this I am attempting to match the date in the filename to the date in the csv.</p> <p>The csv looks like this</p> <pre><code>Date Count 17/08/2020 5 24/04/2020 1 18/...
<p>Let's say you have the following Pandas DataFrame.</p> <pre><code>import pandas as pd df = pd.DataFrame([['17/08/2020', 5], ['24/04/2020', 1], ['18/02/2021', 3]], columns=['Date', 'Count']) df.Date = pd.to_datetime(df.Date) </code></pre> <p>That looks like this.</p> <pre><code> Date Count 0 2020-08-17 ...
python|pandas|csv|networkx
0
373,171
68,604,289
AttributeError: module transformers has no attribute TFGPTNeoForCausalLM
<p>I cloned this repository/documentation <a href="https://huggingface.co/EleutherAI/gpt-neo-125M" rel="nofollow noreferrer">https://huggingface.co/EleutherAI/gpt-neo-125M</a></p> <p>I get the below error whether I run it on google collab or locally. I also installed transformers using this</p> <pre><code>pip install g...
<p>Try without using <code>from_tf=True</code> flag like below:</p> <pre><code>from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained(&quot;EleutherAI/gpt-neo-125M&quot;) model = AutoModelForCausalLM.from_pretrained(&quot;EleutherAI/gpt-neo-125M&quot;) </code></pre> <p...
python|pytorch|huggingface-transformers|gpt|gpt-3
1
373,172
68,760,774
how to merge multiple row of text into one ID using pandas
<p>I have a dataframe similar to this</p> <pre><code>ID text A name;job A like;interest A speak;too B talk;info B study;rule C study study C learn learn </code></pre> <p>I want to mix all text together under one unique ID</p> <pre><code>ID text A name;job,like;interest, speak;too B talk...
<p>Try using <code>groupby</code> with <code>agg</code> and a aggregating function:</p> <pre><code>df.groupby('ID', as_index=False).agg(','.join) </code></pre> <p>Output:</p> <pre><code> ID text 0 A name;job,like;interest,speak;too 1 B talk;info,study;rule 2 C st...
python|pandas|aggregate
0
373,173
68,521,883
What could be causing incorrect 2-D interpolation in SciPy?
<p>I have a rectilinear (not regular) grid of data (x,y,V) where V is the value at the position (x,y). I would like to use this data source to interpolate my results so that I can fill in the gaps and plot the interpolated values (inside the range) in the future. (Also I need functionality of griddata to check arbitrar...
<p>You used a larger <code>epsilon</code> in RBF. Best bet is to set it as default and let scipy calculate an appropriate value. See the implementation <a href="https://github.com/scipy/scipy/blob/88d4d946a22b3bd933884ec236bfba9526809ec9/scipy/interpolate/rbf.py#L241" rel="nofollow noreferrer">here</a>.</p> <p>So setti...
python|numpy|matplotlib|scipy|interpolation
1
373,174
68,497,283
how to get max count of consecutive 1 in column pandas
<p>I Have one dataframe with column Flag1 in this, I want to check if in column flag value 1 occurs continuously for maximum times</p> <p>Here is the dataframe and output format</p> <pre><code>df = pd.DataFrame({'flag':[1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1]}) df_out = pd.DataFrame({'max_count':[3]}) </code></pre>
<h3 id="solution-with-pandas-uw6a">Solution with <code>pandas</code></h3> <pre><code>m = df['flag'].eq(1) max(m[m].groupby((~m).cumsum()).sum()) </code></pre> <h3 id="solution-with-itertools.groupby-a943">Solution with <code>itertools.groupby</code></h3> <pre><code>from itertools import groupby max(sum(g) for k, g in ...
python|pandas|numpy|pandas-groupby
5
373,175
68,600,561
Pandas.astype() ValueError
<p>I am trying to clean data from a csv file and have got rid of the NaN values. I am sure the data types I am tring to convert (from object to float, and from object to int) do not have any NaN values, but it throws</p> <p><code>ValueError: invalid literal for int() with base 10: 'YEAR'</code></p> <pre><code>df.dropn...
<p>The error tells you that you try to convert a string of letters to a number e.g <code>int(&quot;YEAR&quot;)</code>. To overcome this you of course have to make sure that your data, which you try to convert, only consists of numbers.</p> <p>Try the following:</p> <ol> <li>loop over all columns</li> <li>try cast it to...
python|pandas|dataframe
0
373,176
68,615,246
How can I speed up my conversion of pandas dataframe column types?
<p>I am developing a python module that allows users to read a little over 1M rows x 372 columns into memory from parquet files for folks to perform analysis on like this:</p> <pre><code>data = pandas.read_parquet(url1 + str(year) + url2, columns=columns, engine='fastparquet') </code></pre> <p>I'm trying to proactively...
<p>Instead of converting using pandas methods try with numpy arrays which is much faster. For example:</p> <pre><code>test[column] = np.array(test[column], dtype=np.float32) </code></pre> <p>Check for different data types from numpy documentations: <a href="https://numpy.org/doc/stable/reference/arrays.dtypes.html" rel...
python|pandas|dataframe|type-conversion
0
373,177
68,707,849
Pytorch Lightning Tensorboard Logger Across Multiple Models
<p>I'm relatively new to Lightning and Loggers vs manually tracking metrics. I am trying to train two distinct models and have their accuracy and loss plotted on the same charts in tensorboard (or any other logger) within Colab.</p> <p>What I have right now is basically:</p> <pre><code>trainer1 = pl.Trainer(gpus=n_gpu...
<p>The exact chart used for logging a specific metric depends on the key name you provide in the <code>.log()</code> call (its a feature that Lightning inherits from TensorBoard itself)</p> <pre><code>def validation_step(self, batch, _): # This string decides which chart to use in the TB web interface # vv...
tensorboard|pytorch-lightning
1
373,178
68,612,779
Efficient way to iterate over tf.data.Dataset
<p>I want to know which is the most efficient way to iterate through a tf.data.Dataset in TensorFlow 2.4.</p> <p>I am using the typical:</p> <pre><code>for example in dataset: code </code></pre> <p>However, I have measured the wall time and, since my dataset is huge, it takes too much time for computing the loop. I...
<p>You can use <code>.map(map_func)</code> function which is an efficient way to apply some preprocessing on each sample in your dataset. It runs the <code>map_func</code> on each sample of your dataset in parallel. You can even set number of parallel calls by <code>num_parallel_calls</code> argument. <a href="https://...
python|tensorflow|tensorflow2.0|tensorflow-datasets
5
373,179
68,612,050
Tensorflow 2 Object Detection API Function call stack error
<p>I am trying to train a model from Tensorflow 2 Object Detection API but when I start the training process, I am getting the following error message</p> <pre><code>2021-08-01 08:38:32.187042: W tensorflow/core/common_runtime/bfc_allocator.cc:467] _______________________________________________________________________...
<p>So here's the most important part of that error message:</p> <pre><code>tensorflow.python.framework.errors_impl.ResourceExhaustedError: OOM when allocating tensor with shape[3763200,1024] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc </code></pre> <p>You're running out of mem...
python|tensorflow|google-colaboratory|object-detection-api
1
373,180
68,746,224
How do you use Tensorflow Keras Custom Objects with tf.saved_model.Asset?
<p>I have a custom Keras Layer that reads from a pickle file to initialize some weights, and I'd like to be able to use <code>tf.keras.utils.register_keras_serializable()</code> on it. The issue is that my <code>__init__</code> function takes the path to the pickle file, which might not be available when the layer is d...
<p><strong>Edited code:</strong> Previous to this part , code is fine .Issue is replicating because of</p> <pre><code>!rm file.txt </code></pre> <p>(so I put it at the end)</p> <pre><code>!echo abcd &gt; file.txt model = tf.keras.Sequential([AssetLayer(&quot;file.txt&quot;)]) model(tf.ones(3)) model.save(&quot;./conten...
python|tensorflow|keras|deep-learning
0
373,181
68,562,650
Dynamically set folium zoom and postion to geopandas dataframe extent
<p>I have a geopandas dataframe containing many polygons.</p> <p>I wish to plot these in a folium map and have that map set the zoom and extent dynamically to fit all polygons onto the map.</p> <p>I've tried the following</p> <pre class="lang-py prettyprint-override"><code>bounds = df.total_bounds m.fit_bounds(bounds) ...
<p>Try this syntax:-</p> <pre><code>m.fit_bounds([[bounds[0],bounds[1]], [bounds[2],bounds[3]]]) </code></pre>
geopandas|folium
0
373,182
68,566,620
Calculating Difference Once Column turns from False to True
<p>I have a Pandas dataframe that is organized like:</p> <pre><code>+-------+-------------------+---------+ | Name | Ready | Apples | +-------+-------------------+---------+ | Alice | false | 1 | | Bob | false | 3 | | Chris | true | 10 | | Alice | tr...
<p>Assuming each name has at most one <code>True</code> row and one <code>False</code> row. We can <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> then subtract <code>True</code> from <code>False</code>:</p> <pre><code># Pivot to Wide F...
pandas|dataframe|group-by|difference
1
373,183
68,584,894
How to use pandas to agg data with different condition for different columns?
<p><a href="https://i.stack.imgur.com/A7XNB.png" rel="nofollow noreferrer">Agg by sales</a></p> <p>Original Data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Sales</th> <th style="text-align: center;">Product</th> <th style="text-align: right;">Qty</th> </tr> <...
<p>With df as your dataframe name Try:</p> <pre><code>temp_df = df.pivot_table(index='Sales', columns='Product', aggfunc=sum) cols = [ind[1] for ind in np.array(temp_df.columns)] data = np.array(temp_df) final_df = pd.DataFrame({'Sales':temp_df.index}) for i, col in enumerate(cols): final_df = pd.concat((final_df, ...
python|pandas
1
373,184
68,693,624
How to iterate over a series with identical indices
<p>I am looking to iterate over a series that contains groups of identical indices. The data looks like:</p> <pre><code>0 -0.969886 0 -0.941016 0 -0.913815 0 -0.888142 0 -0.863872 ... 3423 -0.841284 3423 -0.840156 3423 -0.839032 3423 -0.837911 3423 -0.836792 Length: 13828, dt...
<p>You can use zip to create a tupple of the two iterators ans loop trough both:</p> <pre><code>a=[1,2,3] b=[9,8,7] c=zip(a,b) for i,n in c: print(str(i) +&quot; &quot; + str(n)) ... 1 9 2 8 3 7 </code></pre> <p><a href="https://docs.python.org/3.8/library/functions.html#zip" rel="nofollow noreferrer">https://doc...
python|pandas|dataframe|for-loop
0
373,185
68,617,239
Parallel processing a dataframe after grouping and splitting
<p>I have a data frame that has about 5000000 rows. I am doing an operation using a custom function and calling it using apply. Since, the no of rows are huge apply function is extremely slow. I would like to parallelize this, but the issue is the operation I perform takes each users complete data at a time (i.e groupe...
<p>I used to write my custom function, but I found a very good package <a href="https://github.com/nalepae/pandarallel" rel="nofollow noreferrer">pandarallel</a>, which does the exact thing with a simple API.</p> <p>After installing, you need to import it</p> <pre><code>from pandarallel import pandarallel pandarallel.i...
python|pandas
0
373,186
68,649,004
Grouping of output plots from function
<p>Here is something I have been struggling with today. It's a question of how to present data in such a way as to avoid having to scroll downa notebook for ages and loosing the ability to compare graphs.</p> <p>Suppose I have this dataframe:</p> <pre><code>id type zone d 0 1 a a1 23 1 1 a b1 45 ...
<p>You have created a grid that you want, but you have not used it anywhere.</p> <p><code>pandas.DataFrame.hist()</code> has an argument <code>ax</code> as:</p> <blockquote> <p><strong>ax : Matplotlib axes object, default None</strong></p> <p>The axes to plot the histogram on.</p> </blockquote> <p>This code:</p> <pre><...
python|pandas|matplotlib|plot|seaborn
3
373,187
68,703,986
How to insert Pandas dataframe that's 1 row but multiple columns into a single SQL cell?
<p>I originally had a JSON object which I have looped through and filtered and then converted to a Python [ ] list and have now put it into a Panda's dataframe.</p> <p>The PD dataframe stands at 1 row x 79 columns, as I wanted, each column has the single word in it I was looking to get.</p> <p>I want each of these sing...
<p>Not a complete answer. As per the comment, breaking down the problem to the first part and to get the cells joined...</p> <p><strong>Given:</strong></p> <pre><code> column_1 column_2 column_3 column_4 column_5 0 This And That And Another </code></pre> <p><strong>Try:</...
python|pandas|dataframe
0
373,188
68,836,405
Calculate the difference between column and the previous column in pandas DataFrame
<p>I am pulling live data for BTCUSDT from binance every 1 minute using binance-api, and I want to calculate the percentage change between the current candle close price and the previous candle I have tried the following:</p> <pre><code>def get_live_data(symbol): candles = pd.DataFrame(Client.get_klines(symbol=symb...
<p>It looks like you're pulling one row at a time since you have <code>limit=1</code>. So when you diff, there's nothing to diff against. And with <code>fillna(0)</code>, you'll end up with diffs of 0.</p>
python|pandas|binance|binance-api-client
1
373,189
68,586,774
loss nan when trying to work with tensorflow feature columns
<p>I have <a href="https://easyupload.io/cei6af" rel="nofollow noreferrer">this dataframe</a>.</p> <p>I am trying to follow <a href="https://apimirror.com/tensorflow%7Eguide/structured_data/feature_columns" rel="nofollow noreferrer">this example</a>.</p> <p>The target value I want to predict on is the <code>zg500</cod...
<p>The reason for getting <code>nan</code> in the loss is that your target values are in the extremes. They are anywhere from e^-32 to e^31. This you can see easily.</p> <pre><code>df['zg500'] ''' 0 -3.996248e-29 1 2.476790e+11 2 -1.010202e+08 3 -1.407987e-02 4 2.240596e-32 ... ...
tensorflow|machine-learning|keras|deep-learning
1
373,190
68,507,187
How to Perform operation in each columns in Pandas
<p><a href="https://i.stack.imgur.com/OKQkB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OKQkB.png" alt="enter image description here" /></a></p> <p>I have this dataset and I want to check the percentage of each cell per year. Such as dividing each value by the sum of values of that year ( value/s...
<p>To convert column values into percentages, this is the simplest way:</p> <pre><code>df['1960_percentages'] = 100*df.1960/df.1960.sum() </code></pre> <p>Repeat similarly for other columns.</p> <p>Note: This creates a new column in your dataframe keeping the original data intact. If you would just like to replace, do ...
python-3.x|pandas|dataframe
0
373,191
68,789,313
No module named 'tensorflow.keras.model'
<p>Whenever I try to train my module it shows the following error</p> <blockquote> <p>ModuleNotFoundError: No module named 'tensorflow.keras.model'</p> </blockquote> <pre><code>import numpy as numpy import cv2 import tensorflow from tensorflow.keras.model import Sequential from keras.layers import Dense, Dropout, Flatt...
<p>According to <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Sequential" rel="nofollow noreferrer">documentation</a>, your imports are incorrect. <code>Sequential</code> is stored in <code>tensorflow.keras</code>. I also ran into a problem importing <code>Maxpooling2D</code> which is actually called <co...
tensorflow|keras
2
373,192
68,725,060
ImportError: cannot import name 'trace' from 'tensorflow.python.profiler'
<p>I'm trying to run an object detection training on Tensorflow</p> <p>Everything is working fine until I start training the network, here.</p> <pre><code>python C:\RealTimeObjectDetection-main\Tensorflow/models/research/object_detection/model_main_tf2.py --model_dir=C:\RealTimeObjectDetection-main\Tensorflow\workspace...
<p>You can import this using latest Tensorflow version 2.6.</p> <pre><code>from tensorflow.python.profiler import trace </code></pre>
python|python-3.x|tensorflow|neural-network|tensorflow2.0
1
373,193
68,732,530
Calculate Events Duration in a day using pandas
<p>I have the following pandas dataframe, the duration is espressed in Minutes:</p> <pre><code>Start Date Event Duration 2021.01.01 00:00 AM 2 540 2021.01.01 9:00 AM 1 180 2021.01.01 12:00 PM 2 20 2021.01.01 12:20 PM 1 1440 2021.01.02 12:20 PM 2 60...
<p>For some weird reasons I could not convert your dates right away but needed to replace whitespaces. Nonetheless, let’s start by converting your <code>Date</code> column to pandas dates and set it as an index:</p> <pre><code>&gt;&gt;&gt; df['Start Date'] = pd.to_datetime(df['Start Date'].str.replace(r'\s+', ' ', rege...
python|pandas|datetime|group-by
1
373,194
68,536,546
using pipelines with a local model
<p>I am trying to use a simple <code>pipeline</code> offline. I am only allowed to download files directly from the web.</p> <p>I went to <a href="https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/tree/main" rel="nofollow noreferrer">https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-en...
<p>Must be either of the two cases:</p> <ul> <li>You didn't download all the required files properly</li> <li>Folder path is wrong</li> </ul> <p>FYI, I am listing out the required contents in the directory:</p> <ul> <li>config.json</li> <li>pytorch_model.bin/ tf_model.h5</li> <li>special_tokens_map.json</li> <li>tokeni...
python|tensorflow2.0|huggingface-transformers
1
373,195
68,545,848
After doing a count with groupby, I want to plot by the groupby variable
<p>I did a value count with a groupby, here is the code. All_data4 is a dataframe.</p> <pre><code>typecount = all_data4.groupby(&quot;Index_Date&quot;)['UPLOAD_TYPE'].value_counts() </code></pre> <p>Typecount looks like the following. How can I plot with X axis being the date, and plot two bar charts grouped by the UPL...
<p>Starting from you point... First, you could reset your index:</p> <pre><code>typecount.reset_index(inplace=True) </code></pre> <p>Then, split new index column into 2 columns:</p> <pre><code>new_df =pd.DataFrame(typecount[&quot;index&quot;].to_list(), columns=['Index_Date', 'UPLOAD_TYPE']) </code></pre> <p>Then you c...
python|pandas|plot
0
373,196
68,662,510
Numpy array into if statement modifies its values
<p>I have identified an issue in my program and I do not know how to fix it :</p> <p>First, I create with the <code>arange</code> function an array of values <code>x_lin</code> from 0.014 to 0.5 with an incrementation of 0.001</p> <p>After that, I compute a ratio named <code>r1</code>, and then thanks to an if statemen...
<p>The problem here is that Python can't add exactly 0.001, so it uses an approximate value. But over the whole arange, the floating point errors accumulate and end up giving you an imprecise result.</p> <p>You can get around it by using integers instead of floats in your operations:</p> <p><code>xlin = np.arange(14, 5...
python|arrays|numpy|if-statement|rounding
0
373,197
68,518,728
How to append a set of numpy arrays while inside a for loop?
<p>The thing I want to do is, I want append a set of numpy arrays one after the other while in a for loop. So whenever a new array comes, the new array will be appended to the older one. The code I have written is as follows:</p> <pre><code>def joinArray(highest_score, seq): seq1 = np.array([]) seq2 = np.a...
<p>First of all, you are redefining your arrays each run. I used a little trick with global keyword here, but you can easily convert the code into OOP, if you are familiar with it. Secondly, in order for python to append array to array (and not number after number), you have to define your array as 1- dimension array. ...
python|numpy
1
373,198
68,503,185
how to pass multiple arguments/parameters while executing pandas
<p>I have to pass multiple arguments while executing the python script as a condition. Below is my code but i have to perform same steps with multiple condition. there are 4 different files for client 1 and 2 with data and metadata errors. so, If I pass <code>python.py client1,data,date</code> then my function should p...
<p><code>argparse</code> is your friend for creating hand command-line tools with simple syntax. Here is a snippet to help you:</p> <pre><code>import argparse parser = argparse.ArgumentParser(description='client file parser') parser.add_argument( '-c', '--client', help='client name', type=str ) parser.add_...
python|pandas
0
373,199
68,786,734
Tensorflow loss converging but model fails to predict even on train data
<p>Using ANN with Tensorflow to train a simple known equation Y=Sin(X) or Y=Cos(X). My loss function is converging properly. <a href="https://i.stack.imgur.com/WjkjD.png" rel="nofollow noreferrer">Loss function convergence graph</a>. If loss function converges it means model has fitted well to my training dataset.</p> ...
<p>It is the nature of your data.</p> <blockquote> <p>It made me remember the old paper which showed that the ANN can't compute even the XOR</p> </blockquote> <p>Anyway the reason here is that your model is shallow and shallow networks are much less efficient than deep networks. To put in perspective a model like below...
tensorflow|machine-learning|neural-network
4