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
372,500
55,109,684
How to handle large JSON file in Pytorch?
<p>I am working on a time series problem. Different training time series data is stored in a large JSON file with the size of 30GB. In tensorflow I know how to use TF records. Is there a similar way in pytorch?</p>
<p>I suppose <code>IterableDataset</code> (<a href="https://pytorch.org/docs/stable/data.html#iterable-style-datasets" rel="noreferrer">docs</a>) is what you need, because:</p> <ol> <li>you probably want to traverse files without random access;</li> <li>number of samples in jsons is not pre-computed.</li> </ol> <p>I've...
deep-learning|time-series|pytorch
8
372,501
55,051,096
How to do exact string match while filtering from pandas dataframe
<p>I have a dataframe as </p> <p>df</p> <pre><code> indx pids A 181718, B 31718, C 1718, D 1235,3456 E 890654, </code></pre> <p>I want to return a row that matches 1718 exactly.</p> <p>I tried to do this but as expected it returns rows where the 1718 is subset as well: </p...
<p>you can try with:</p> <pre><code>df[df.pids.replace('\D','',regex=True).eq('1718')] indx pids 2 C 1718, </code></pre> <blockquote> <p>'\D' : Any character that is not a numeric digit from 0 to 9.</p> </blockquote> <p><strong><em>EDIT</em></strong> Considering the below df:</p> <pre><code> indx ...
python|pandas
5
372,502
55,092,187
A Basic Python Question about Defining Function
<p>I have a basic question regarding Python code.</p> <p>For example,</p> <pre><code>import torch import torch.nn as nn loss = nn.MSELoss() input = torch.randn(3, 5, requires_grad=True) target = torch.randn(3, 5) output = loss(input, target) output.backward() </code></pre> <p>Why do I need to define the loss function ...
<p>As a few others have pointed out, <code>nn.MSELoss</code> is a class and not a function. In line 1 you are creating an object of type <code>torch.nn.modules.loss.MSELoss</code>. And because it inherits from <code>nn.Module</code>, you can call this object like you would call a function, like you do in line 4.<br> If...
python|pytorch
2
372,503
54,873,325
Finding n lowest values for each row in a dataframe
<p>I have a large datarframe with 1739 rows and 1455 columns. I want to find the 150 lowest values for each row (Not the the 150 th value but 150 values). </p> <p>I iterate over rows with a basic for loop. </p> <p>I tried <code>df.min(axis=1)</code> but it only gives out one min. And also the <code>rolling_min</code>...
<p>Use <code>.argsort</code> to get the indices of the underlying array sorted. Slice the values and the column Index to get all of the information you need. We'll create a MultiIndex so we can store both the column headers and values in the same DataFrame. The first level will be your nth lowest indicator.</p> <h3>Exa...
python|pandas|min
4
372,504
54,744,783
Pytorch: How to get all model's parameters that require grad?
<p>I have some model in pytorch, whose updatable weights I want to access and change manually.</p> <p>How would that be done correctly?</p> <p>Ideally, I would like a tensor of those weights.</p> <p>It seems to me that</p> <pre><code>for parameter in model.parameters(): do_something_to_parameter(parameter) </co...
<p>here's my method, you can generally input any model here and it will return a list of all torch.nn.* things, just add a wrap around it to return not module but it's weights</p> <pre><code>def flatten_model(modules): def flatten_list(_2d_list): flat_list = [] # Iterate through the outer list ...
python|machine-learning|pytorch|backpropagation
0
372,505
54,861,150
Change the date format for a column in Python
<p>I would like to change the date format of a entire column in data frame.</p> <p>My code looks like this:</p> <pre><code>fwds['fwdlookupterm'] = fwds['symbol'] + datetime.datetime.strptime(fwds['expiration_date'],'%y%m%d') </code></pre> <p>When i do so, i get an error:</p> <pre><code>TypeError: strptime() argumen...
<p>I believe you need convert column to strings, then to datetimes and last to custom format by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>strftime</code></a>:</p> <pre><code>s = pd.to_datetime(fwds['expiration_date'].astype(str)).dt.s...
python|pandas|date
1
372,506
49,564,064
Lag the date by considering data from another table
<p>have a question on whether the following can be done without having to do a for loop</p> <p>i have a ctry table that looks like the below</p> <pre><code> CTRY LAG AU 2 US 3 </code></pre> <p>my data table looks like this</p> <pre><code> CTRY DATE A B C AU 1960-01-31 0.3 0.4 0.5 ...
<p>You can using merge firstly , then using <code>pd.DateOffset</code>, convert your LAG column to month.</p> <pre><code>#df.DATE=pd.to_datetime(df.DATE) s=df.merge(ctry) s['DATE']=s['DATE']+s['LAG'].apply(lambda x : pd.DateOffset(months=x)) s Out[452]: CTRY DATE A B C LAG 0 AU 1960-03-31 0.30...
pandas
1
372,507
49,789,730
what is sequence_length field in tf.contrib.seq2seq.TrainingHelper?
<p>Can anyone explain the purpose of sequence length field in <code>tf.contrib.seq2seq.TrainingHelper</code></p>
<p>It represents the length of each target sequence in "inputs" parameter.</p> <p>Check : <a href="http://higepon.hatenablog.com/entry/20171212/1513076578" rel="nofollow noreferrer">http://higepon.hatenablog.com/entry/20171212/1513076578</a> for example.</p> <p>It is used for checking if the target sequence tokens ex...
tensorflow|seq2seq
2
372,508
49,498,706
Text Classification with RNN in TensorFlow - AttributeError: '_IndicatorColumn' object has no attribute 'key'
<p>I'm attempting to make a program that will classify blocks of text into classes using DynamicRnnEstimator in TensorFlow. Unfortunately I'm receiving this error when I run my code:</p> <p><strong><em>AttributeError: '_IndicatorColumn' object has no attribute 'key'</em></strong></p> <p>My <strong>data.csv</strong> f...
<p>It looks like your features are set up in a pandas df, not a dictionary. In the following code, for example, you see how the expected behaviour is with panda's DataFrames in TensorFlow:</p> <pre><code># Convert pandas data into a dict of np arrays. features = {key:np.array(value) for key,value in dict(features).ite...
python|tensorflow|machine-learning|rnn
0
372,509
49,503,173
pandas dataframe character columns to integer
<p>I have my dataframe like below:</p> <pre><code>+--------------+--------------+----+-----+-------+ | x1 | x2 | km | gmm | class | +--------------+--------------+----+-----+-------+ | 180.9863129 | -0.266379416 | 24 | 19 | T | | 52.20132828 | 28.93587875 | 16 | 14 | I | | -17.17127419...
<p><strong>Option 1</strong><br> Assuming your column <em>only</em> has single, uppercase characters, you can do a little arithmetic on the <code>view</code>:</p> <pre><code>df['class'] = df['class'].values.astype('&lt;U1').view(np.uint32) - 64 df x1 x2 km gmm class 0 180.986313 -0.266379 24 ...
python|pandas
5
372,510
49,545,758
Flip or reverse columns in numpy array
<p>I want to flip the first and second values of arrays in an array. A naive solution is to loop through the array. What is the right way of doing this?</p> <pre><code>import numpy as np contour = np.array([[1, 4], [3, 2]]) flipped_contour = np.empty((0,2)) for point in contour: x_y_fipped = n...
<p>Use the aptly named <code>np.flip</code>:</p> <pre><code>np.flip(contour, axis=1) </code></pre> <p>Or,</p> <pre><code>np.fliplr(contour) </code></pre> <p></p> <pre><code>array([[4, 1], [2, 3]]) </code></pre>
python|arrays|numpy
11
372,511
49,662,291
How can I force Pandas dataframe column query to return only str and not interpret what it is seeing?
<p>I have an excel spreadsheet that has four column names: "Column One, Column Two, Jun-17, and Column Three"</p> <p>When I display my column names after reading in the data I get something very different from the "Jun-17" text I was hoping to receive. What should I be doing differently?</p> <pre><code>import pandas...
<p>One of your column names is a <code>datetime</code> object. You can rename it to a string using <code>datetime.strftime</code>. Example below.</p> <pre><code>import datetime import pandas as pd, numpy as np df = pd.DataFrame(columns=['Column One', 'Column Two', datetime.datetime(2018, 6,...
python|python-3.x|pandas|datetime|dataframe
1
372,512
49,554,139
Boxplot of Multiple Columns of a Pandas Dataframe on the Same Figure (seaborn)
<p>I feel I am probably not thinking of something obvious. I want to put in the same figure, the box plot of every column of a dataframe, where on the x-axis I have the columns' names. In the <code>seaborn.boxplot()</code> this would be equal to <code>groupby</code> by every column. </p> <p>In pandas I would do </p> ...
<p>The seaborn equivalent of</p> <pre><code>df.boxplot() </code></pre> <p>is</p> <pre><code>sns.boxplot(x=&quot;variable&quot;, y=&quot;value&quot;, data=pd.melt(df)) </code></pre> <p>or just</p> <pre><code>sns.boxplot(data=df) </code></pre> <p>which will plot any column of numeric values, without converting the DataFr...
python|pandas|seaborn
120
372,513
49,374,192
What is the Best way to compare large datasets from two different sources in Python?
<p>I have large datasets from 2 sources, one is a huge csv file and the other coming from a database query. I am writing a validation script to compare the data from both sources and log/print the differences. One thing I think is worth mentioning is that the data from the two sources is not in the exact same format or...
<p>You were in the right path. What do you want is to quickly match the 2 tables. Pandas is probably overkill. </p> <p>You probably want to iterate through you first table and create a dictionary. What you <strong>don't</strong> want to do, is interact the two lists for each elements. Even little lists will demand a l...
python|pandas
1
372,514
49,352,331
Pandas Column and Row exists
<p>This is going to be hard for me to explain....but here I go...</p> <p>I have two CSV files that I load in via PANDAS, but they are not the same "shape" We shall call then CSV1 and CSV2</p> <p>I take two values from CSV1 and check to see if they exist in CSV2 We shall call the values VAL1 and VAL2; they are all fl...
<p>I am 10 minute into a train journey, I settle down to take another crack at my problem and I almost immediately see whats wrong...</p> <p>..I am missing ".values" in "_data.columns" The IF statements should infact read:</p> <pre><code>if str(a) in str(_data['LAT'].values) and str(b) in str(_data.columns.value): </...
python|pandas
0
372,515
49,655,656
Shape of weight variable Tensorflow
<p>I am trying to learn how to work with <code>tf.data.TFRecordDataset()</code> but I am confused about it. I have a <code>tfrecords</code> file which contains my images(24K) and labels and I have resized all my images to 100x100x3.</p> <p>First, I loaded my <code>tfrecords</code> file with <code>tf.data.TFRecordDatas...
<p>The problem arises from this line:</p> <pre><code> w = tf.get_variable(name='Weights',shape= [None, 100, 100, 3] , initializer=tf.random_normal_initializer(0, 0.01)) </code></pre> <p>You specified that your weights have shape <code>shape=[None,100,100,3]</code> which tensorflow can't handle. As the error says "...
python|python-3.x|tensorflow|deep-learning|tensorflow-datasets
0
372,516
49,558,545
Filtering option in table.query function in python Pandas
<p>I am using cx_oracle lib to fetch some data from Oracle DB and start performing some calculations. Here in my code, I created a table and I want to plot my data in Subplots for each item in a column.</p> <p>In my program, I used for loop and query from pandas lib to filter data based on a column value called "Sub",...
<p>Try this </p> <pre><code>table.query('Subrack == [{}]'.format(i)) </code></pre> <p>I am not so sure about <code>[]</code>,depending on how the content of the column it's not necessary and you can just write <code>Subrack == {}</code>.</p> <p>The error arises because you provide i to the method query, which assume...
python|pandas|cx-oracle
0
372,517
49,721,246
Pandas date calculation
<p>I'm just starting to learn python, and was trying to make it do something useful for my work.</p> <p>My objective is to read a table from an excel file with data of the following format, and do some calculations on it: This is the service record of days worked by an employee:</p> <pre><code>Day from Day to 01/0...
<p>I think need pandas functions because working with <code>NaN</code> and <code>NaT</code> values also - first convert columns <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>s and then get <a href="http://pandas.pydata.org/p...
python|pandas|datetime
2
372,518
49,469,363
Dataframe Lookup rows to return Index
<p>I have a dataframe as per</p> <pre><code>Alpha Bravo Charlie Final 10 20 30 30 15 25 35 25 </code></pre> <p>I like to create a new column with the header such that it will be:</p> <pre><code>Alpha Bravo Charlie Final NewColumn 10 20 30 30 Charlie 15 25 35 25 B...
<p>Here's a 100% numpy vectorized solution using broadcasted comparison:</p> <pre><code>i = df.values j = df.Final.values df['NewColumn'] = df.columns[(i == j[:, None]).argmax(1)] </code></pre> <p></p> <pre><code>df Alpha Bravo Charlie Final NewColumn 0 10 20 30 30 Charlie 1 15 25...
python|pandas|numpy|dataframe|lookup
4
372,519
49,638,955
Remove level and all of its rows from pandas dataframe if one row meets condition
<p>Below is a pandas dataframe that I would like to filter. I would like to remove the year and all of its rows when the temp for at least one row (i.e., <code>visit</code>) in that year is &lt; 37. I am able to remove the specific row in 2014 where the temp is 36; however, I do not know how to make the entire year go ...
<p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration" rel="nofollow noreferrer"><code>groupby/filter</code></a> to remove groups based on a condition:</p> <pre><code>import numpy as np import pandas as pd index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]], names=['yr',...
python|pandas
3
372,520
49,370,879
Python and HyperOpt: How to make multi-process grid searching?
<p>I am trying to tune some params and the search space is very large. I have 5 dimensions so far and it will probably increase to about 10. The issue is that I think I can get a significant speedup if I can figure out how to multi-process it, but I can't find any good ways to do it. I am using <code>hyperopt</code> an...
<p>If you have a Mac or Linux (or Windows Linux Subsystem), you can add about 10 lines of code to do this in parallel with <code>ray</code>. If you install ray via the <a href="http://ray.readthedocs.io/en/latest/installation.html#trying-the-latest-version-of-ray" rel="noreferrer">latest wheels here</a>, then you can r...
python|pandas|machine-learning|grid-search|hyperparameters
6
372,521
49,360,576
Interpolating missing data in Python keeping in mind x values
<p>I need a clarification on what tool to use and how to interpolate missing in Python. Refer to the code below:</p> <pre><code>import matplotlib.pyplot as plt from scipy import interpolate # Create data with missing y values x = [i for i in range(0, 10)] y = [i**2 + i**3 for i in range(0, 10)] y[4] = np.nan y[7] = n...
<p>I would drop the values associated with NaN values and develop a model for the remaining value pairs and then predict over all <code>x</code>. Like so:</p> <pre><code># Create data with missing y values x = [i for i in range(0, 10)] y = [i**2 + i**3 for i in range(0, 10)] y[4] = np.nan y[7] = np.nan # convert to n...
python|pandas|interpolation|missing-data
2
372,522
49,433,555
dataframe drop_duplicates with subset of columns
<p>For the subset argument i want to specify the first n-1 columns. How'll I do that? </p> <p>For example: in the following dataset</p> <pre><code> 0 1 2 3 4 5 6 0 0 12 1 99 23 2 75 1 0 12 1 99 23 2 66 2 5 12 1 99 23 2 66 </code></pre> <p>I want the result to be 1st and 3 rd row only...
<p>You can using <code>duplicated</code></p> <pre><code>df[~df.iloc[:,:-1].duplicated()] Out[53]: 0 1 2 3 4 5 6 0 0 12 1 99 23 2 75 2 5 12 1 99 23 2 66 </code></pre>
python|pandas|dataframe
3
372,523
49,436,774
Selecting rows in pandas for where a column is equal to certain values
<p>I have a pandas dataframe that looks like this:</p> <p><a href="https://i.stack.imgur.com/m0efr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m0efr.png" alt="Pandas dataframe"></a></p> <p>From this, I want to grab all the rows for particular Filters (1st column). So for example, I want to grab...
<p>This is a simple slicing:</p> <pre><code>df[df["# Filter"].isin(["F218W", "F336W","F373N"])] </code></pre> <p>If the rules across multiple columns, you can simply combine them using <code>&amp;</code>:</p> <pre><code>df[df["# Filter"].isin(["F218W", "F336W","F373N"]) &amp; (df["Chip"] == 1)] </code></pre>
python|pandas|selection
1
372,524
49,430,178
Is it possible to force Tensorflow to generate orthogonal matrix?
<p>I'm using Tensorflow to generate a transformation matrix for a set of input vectors (X) to target vectors (Y). To minimize the error between the transformed input and the target vector samples I'm using a gradient descent algorithm. Later on I want to use the generated matrix to transform vectors coming from the sam...
<p>It should be possible. I see two solutions.</p> <p>If you don't care that the transformation is a perfect rotation, you can take the matrix, adjust it to what you think it's a good matrix (make it a perfect rotation) then compute the difference between the one you like and the original and add it as a loss. With t...
python|tensorflow
0
372,525
49,444,445
Reassign labels of columns from 0 after drop of few columns
<p>I removed some duplicate columns by the following command. </p> <pre><code>columns = XY.columns[:-1].tolist() XY1 = XY.drop_duplicates(subset=columns,keep='first'). </code></pre> <p>The result is below:</p> <blockquote> <pre><code>Combined Series shape : (100, 4) Combined Series: ...
<p>So first create a dictionary with the mapping you want</p> <pre><code>trafo_dict = {x:y for x,y in zip( [1,222,223,0],np.linspace(0,3,4))} </code></pre> <p>Then you need to rename columns. This can be done with pd.DataFrame.rename:</p> <pre><code> XY1 = XY1.rename(columns=trafo_dict) </code></pre> <p>Edit: If y...
python|pandas|dataframe
1
372,526
49,500,259
How to find Most frequently used words used on data using Python?
<p>I am doing a sentiment analysis project in Python (using Natural Language Processing). I already collected the data from twitter and saved it as a CSV file. The file contains tweets, which are mostly about cryptocurrency. I cleaned the data and applied sentiment analysis using classification algorithms.</p> <p>Sinc...
<p>Demo:</p> <pre><code>from nltk import sent_tokenize, word_tokenize, regexp_tokenize, FreqDist from nltk.corpus import stopwords from sklearn.datasets import fetch_20newsgroups from wordcloud import WordCloud, STOPWORDS def tokenize(text, pat='(?u)\\b\\w\\w+\\b', stop_words='english', min_len=2): if stop_words...
python|pandas|twitter|nlp|sentiment-analysis
1
372,527
49,368,274
get_dummies does not have columns attribute
<p>This line of code:</p> <pre><code>for j in range(0,len(names)): #fullSet = pandas.get_dummies(fullSet,columns=[names[j]]) fullSet = pandas.get_dummies(fullSet,columns=[categoricalNames.columns[j]]) </code></pre> <p>Is generating this error:</p> <pre><code>Traceback (most recent call last): File "noPrintsMac...
<p>It looks like the <code>columns</code> argument for <code>get_dummies</code> was introduced in pandas version 0.15. Therefore, if you are using a version &lt; 0.15 (e.g. <a href="http://pandas.pydata.org/pandas-docs/version/0.14.0/generated/pandas.get_dummies.html" rel="nofollow noreferrer"> version 0.14</a>), using...
python|pandas|numpy|scipy
1
372,528
49,740,758
Using Template Matching on different sizes efficiently
<p>Is there a more efficient way to use Template Matching with images of different sizes? Here is my current Script:</p> <pre><code>import cv2 import numpy as np img_bgr = cv2.imread('./full.jpg') img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) template = cv2.imread('./template.jpg', 0) w, h = template.shape[:...
<p>The easiest way is to use feature matching instead of template matching. Feature matching is exactly meant for this kind of applications. It can also detect if the image is rotated .. etc</p> <p>Have a lock at this <a href="https://docs.opencv.org/master/dc/dc3/tutorial_py_matcher.html" rel="nofollow noreferrer">htt...
python|numpy|opencv|computer-vision|scale
1
372,529
49,690,793
scipy.linalg.block_diag vs scipy.sparse.block_diag in terms of efficiency
<p>I have a question about the way scipy builds block diagonal matrices. I was expecting that creating a sparse block diagonal matrix would be much quicker and more efficient than creating a dense one (because of sparsity compressions). But it turns out that it's not the case (or maybe am I using some inefficient metho...
<pre><code>In [625]: [np.identity(1)*i for i in range(1,5)] Out[625]: [array([[1.]]), array([[2.]]), array([[3.]]), array([[4.]])] In [626]: sparse.block_diag(_) Out[626]: &lt;4x4 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 4 stored elements in COOrdinate format&gt; In [627]: _.A Out[627]: array([[...
numpy|scipy|sparse-matrix|coding-efficiency
0
372,530
49,482,436
Tensorflow reading a tab separated file
<p>I am trying to read a tab separated file into tensorflow</p> <pre><code># Metadata describing the text columns COLUMNS = ['queue_name','block_name', 'car_name', 'position_id', 'x_ord', 'y_ord'] FIELD_DEFAULTS = [[''], [''], [''], [0], [0], [0]] def _parse_line(line): # Decode the line into...
<p>The reason for the error is because you are trying to run something that is not a Tensor or an Operation but a Dataset object. You can create a tensor from the Dataset object such that everytime you run it, you get the next sample from your dataset.</p> <p>Try the following:</p> <pre><code>value = ds.make_one_shot...
python|tensorflow
1
372,531
49,672,963
Color every point in a scatterplot differently in numpy/python
<p>I am solving an optimization problem. There are n iterations and at each one I have a point x_n=[x_n1, x_n2]. I want to plot the iterates x_n so that as n increases the color of the points gets dark or lighter or whatever. Currently I can plot the iterates but they are all the same color so i cannot tell which point...
<p>You can directly give a list of color to <code>plt.scatter()</code>. For example: you can do:</p> <pre><code>import seaborn as sns color_list = sns.color_palette("Paired", n_colors=x_test.shape[0]) plt.scatter(x_test[:,0], x_test[:,1], color=color_list) </code></pre> <p>Check <a href="https://matplotlib.org/exampl...
python|numpy|matplotlib|plot|colors
1
372,532
49,420,272
how to make pandas dataframe Fortran type ordered
<p>I knew a little that inside python pandas package, the dataframe has part that was constructed with NumPy NDArrays. And numpy has the option that you can choose your data order type, like 'C' or 'F'.</p> <p>Since I always have to implement lots of ops on columns on huge dataframe(like 100 million lines), I expected...
<p>Interestingly, Pandas uses internally C order numpy array for each column. Whenever you access multiple columns or all of dataframe, it joins those numpy arrays and returns a Fortran order numpy array. </p> <pre><code>print(df[df.columns[0]].values.flags) print(df[df.columns[0:2]].values.flags) print(df.values.flag...
python|performance|pandas|numpy
10
372,533
49,722,225
Multiple boxplots from multi-index data in Pandas
<p>I have data in a multi-index DataFrame structured as follows:</p> <pre><code> 0 1 method metric HASH L2_TCM 287 296 TOT_CYC 6211 6100 RECV L2_TCM 331 323 TOT_CYC 10881 7524 SYNTH L2_TCM 869 856 TOT_CYC 29117 29560 </code></pre> <p>The ...
<p>Is this what you're looking for?</p> <pre><code>import pandas as pd import seaborn as sns ''' method metric 0 1 HASH L2_TCM 287 296 HASH TOT_CYC 6211 6100 RECV L2_TCM 331 323 RECV TOT_CYC 10881 7524 SYNTH L2_TCM 869 856 SYNTH TOT_CYC 29117 29560 ''' df = pd.read_...
python|pandas
1
372,534
49,757,497
Conditions based in date periods and groups
<pre><code> A B C D 0 2002-01-13 Dan 2002-01-15 10 1 2002-01-13 Dan 2002-01-25 24 2 2002-01-13 Vic 2002-01-17 14 3 2002-01-13 Vic 2002-01-03 18 4 2002-01-28 Mel 2002-02-08 37 5 2002-01-28 Mel 2002-02-06 29 6 2002-01-28 Mel 2002-02-10 20 7 2002-01-28 Rob 2002-02-1...
<p>Ok , seems you need </p> <pre><code>df['E']=abs((df.C-df.A).dt.days-10)# get the days different df['E']=df.B.map(df.loc[df.E==df.groupby('B').E.transform('min')].groupby('B').D.mean())# find the min value for the different , and get the mean df Out[106]: A B C D E 0 2002-01-13 Dan 200...
python|pandas|conditional
2
372,535
49,695,382
pandas sort/average numerical/text data in single column
<p>I have data that is in 3 columns (name, question, response) that resulted from judging a student research symposium. There are 2 possible choices for level (graduate/undergraduate), and 5 for college (science, education, etc.) </p> <p>What I need to do is take the average of the numerical responses for a given nam...
<p>convert response column to numeric, the string will be na then groupby and aggregate</p> <pre><code>import pandas as pd import numpy as np import StringIO data = '''name;question;response Smith, John;Q1;10 Smith, John;Q2;7 Smith, John;Q3;10 Smith, John;Q4;8 Smith, John;Q5;10 Smith, John;Q8;8 Smith, John;level;gra...
python|pandas
1
372,536
49,436,628
Mapping multiple input samples to single output sample in Keras
<p>I'm working on a project using Keras which has a large amount of input data, and a smaller amount of output/label data (which are images). The mapping of input->output data is contiguous and consistent, i.e. the first 1000 input samples correspond to the first image, the second 1000 input samples correspond to the s...
<p>I believe this can be achieved with <code>TimeDistributed</code> and averaging the results.</p> <p>There's a lot of missing information in your question, but I will assume your input's shape is <code>(batch_size, 224, 224, 3)</code> and your output shape is <code>(batch_size, 7, 7, 512)</code> in order to illustrat...
python|numpy|tensorflow|machine-learning|keras
2
372,537
49,436,402
Python - Pandas - Search string in cell for keyword and look up value based on keyword
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;style type="text/css"&gt; table.tableizer-table { font-size: 12px; border: 1px solid #CCC; font-family: Arial, Helve...
<p>You can use a <code>split</code>, <code>map</code> and some dataframe reshaping:</p> <pre><code>df_out = df1.set_index('Name')['Description'].str.split(expand=True).stack().to_frame() df_out['cols'] = df_out[0].map(df2.set_index('Sub')['Category']) df_out = df_out.reset_index(level=1, drop=True).set_index('cols',...
python|pandas
0
372,538
49,678,807
Explaining large runtime variations
<p>I am a bit baffled by the following profiling results, and would like to hear some explanation in order to make sense of them. I thought I would take the inner-product as a simple function to compare different possible implementations:</p> <pre><code>import numpy as np def iterprod(a,b): for x,y in zip(a,b): ...
<h3>Q1</h3> <p>Python lists contain pointers to python objects, while arrays contain those numbers directly. The underlying numpy code however expects it to be a contiguous array. So when passed a list, it has to read the value out of the float into a new array for every element of the list.</p> <p>As noted in the co...
python|python-3.x|numpy
3
372,539
49,765,578
Transforming a list to a column vector in Python
<p>I was wondering if there's a function that takes a list <code>X</code> as input and outputs a column vector corresponding to <code>X</code>?</p> <p>(I looked around and I suspect it might be: <code>np.matrix(X).T</code> )</p>
<p>I don't think there is a function, but there is a dedicated object, <code>np.c_</code></p> <pre><code>&gt;&gt;&gt; X = list('hello world') &gt;&gt;&gt; X ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] np.c_[X] array([['h'], ['e'], ['l'], ['l'], ['o'], [' '], ['w'],...
python|numpy|transpose
9
372,540
28,161,356
Convert Column to Date Format (Pandas Dataframe)
<p>I have a pandas dataframe as follows:</p> <pre><code>Symbol Date A 02/20/2015 A 01/15/2016 A 08/21/2015 </code></pre> <p>I want to sort it by <code>Date</code>, but the column is just an <code>object</code>.</p> <p>I tried to make the column a date object, but I ran into an issue where that for...
<p>You can use <code>pd.to_datetime()</code> to convert to a datetime object. It takes a format parameter, but in your case I don't think you need it.</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame( {'Symbol':['A','A','A'] , 'Date':['02/20/2015','01/15/2016','08/21/2015']}) &gt;&gt;...
python|pandas
188
372,541
28,328,636
Calculating year over year growth by group in Pandas
<p>I have the following <code>dataframe</code>:</p> <pre><code>In [1]: df Out[1]: ID Month Transaction_Amount 1 2013/01 10 1 2013/02 20 1 2013/03 10 1 2013/04 20 1 2013/05 10 1 2013/0...
<p>I think there is a much more simple way to do this that doesn't require keeping track of shifting time periods, try using the <code>df.pct_change()</code> method:</p> <pre><code>import pandas as pd import numpy as np date_range = pd.period_range("2016-01", "2018-01",freq='m') df= pd.DataFrame({'A':np.random.rand(le...
python|function|indexing|pandas
12
372,542
28,355,896
Monkeypatch with instance method
<p>I'm trying to monkeypatch how <code>pandas</code> Panel's slicing (<code>__getitem__</code>). This is straightforward to do with a basic function, foo.</p> <pre><code>from pandas import Panel Panel.__getitem__ = ORIGINAL_getitem def newgetitem(panel, *args, **kwargs): """ Append a string to return of panel._...
<p>You can use <a href="https://docs.python.org/3/library/unittest.mock.html#patch" rel="nofollow"><code>patch</code> from mock framework</a> to handle your case. Even it is designed for testing, its primary work is monkey patching in defined contex.</p> <p>Your <code>set_backend()</code> method could be:</p> <pre><c...
python|pandas|partials|monkeypatching|functools
1
372,543
28,247,529
Applying Conditional Exclusions to Pandas DataFrame using Counts
<p>I have the following DataFrame in pandas:</p> <pre><code>import pandas as pd example_data = [{'ticker': 'aapl', 'loc': 'us'}, {'ticker': 'mstf', 'loc': 'us'}, {'ticker': 'baba', 'loc': 'china'}, {'ticker': 'ibm', 'loc': 'us'}, {'ticker': 'db', 'loc': 'germany'}] df = pd.DataFrame(example_data) print df loc ticker ...
<p>How about groupby and <code>.head</code>:</p> <pre><code>In [90]: df.groupby('loc').head(2) Out[90]: loc ticker 0 us aapl 1 us mstf 2 china baba 4 germany db </code></pre> <p>Also, be careful with your column names, since <code>loc</code> clashes with the <code>.loc</code> method....
python|python-2.7|pandas
1
372,544
28,372,847
Why can't I apply shift from within a pandas function?
<p>I am trying to build a function that uses .shift() but it is giving me an error. Consider this:</p> <pre><code>In [40]: data={'level1':[20,19,20,21,25,29,30,31,30,29,31], 'level2': [10,10,20,20,20,10,10,20,20,10,10]} index= pd.date_range('12/1/2014', periods=11) frame=DataFrame(data, index=index) frame Out[...
<p>Try passing the frame to the function, rather than using <code>apply</code> (I am not sure why <code>apply</code> doesn't work, even column-wise):</p> <pre><code>def f(x): x.level1 return x.level1 + x.level1.shift(1) f(frame) </code></pre> <p>returns:</p> <pre><code>2014-12-01 NaN 2014-12-02 39 201...
python|algorithm|pandas
3
372,545
28,120,122
Subtract next row use current row, python dataframe
<p>I have this Pandas Dataframe in python, I want to know the time difference between two rows, next row subtract previous row, how should I approach this?</p> <p>Reviewed[x] - Reviewed[x-1] x is the number of where that row is </p> <pre><code> ReporterID ID Type Reviewed 0 2754525...
<p>Assuming your <code>Reviewed</code> column are datetimes you can do:</p> <pre><code>df.ix[4, 'Reviewed'] - df.ix[3, 'Reviewed'] </code></pre> <p>If you want to do it for all rows at once:</p> <pre><code>df['Reviewed'] - df['Reviewed'].shift() </code></pre>
python|datetime|numpy|pandas|dataframe
12
372,546
28,377,072
Write contents of dataframe to .txt files with one file per row?
<p>I have a two column data frame with nrows.</p> <pre><code>Col1 Col2 123 abc 456 def </code></pre> <p>I would like to loop through the data frame and for each row create a text file. The first column is the text file name and the second column is the text file contents.</p> <p>Result:</p> <ul> <li>123.txt w...
<p>Here is a way to do it with <code>pandas</code>. Even if it is a bit ugly it does the job, and will get you on the way.</p> <pre><code>import pandas as pd df = pd.DataFrame({'food': ['eggs','eggs','ham','ham'],'co1':[20,19,20,21]}) for x in df.iterrows(): #iterrows returns a tuple per record whihc you can unpa...
python|python-2.7|pandas
1
372,547
28,068,156
Indexerror: list index out of range/numpy
<p>I am really new to python. I am getiing an error stating Indexerror list index out of range. Kindly help me out. Thanks in advance . Edit 1</p> <pre><code>x = np.array([10,0]) Phi = np.array([[ 1. , 0.01], [ 0. , 1. ]]) Gamma = np.array([[ 0.0001048 ], [ 0.02096094]]) Z = np.array([[...
<p>To answer your question in the comments about tracebacks (stack traces): running the following</p> <pre><code>a = [1,2,3] b = [True, False] print(a[2]) print(b[2]) </code></pre> <p>produces one answer and one traceback.</p> <pre><code>&gt;&gt;&gt; 3 Traceback (most recent call last): File "C:\Programs\python34...
python|python-3.x|numpy
0
372,548
73,499,614
column number to be automate with specified value
<p>I have a few columns</p> <pre><code>df = pd.read_csv('D:\data_ana\\10.05.43.csv') cols_in_the_slice = df.loc[:,(' Objects[0].MeasuredTimeStamp', ' Objects[0].LifeCycles', ' Objects[0].KinematicRel.f_DistX', ' Objects[0].KinematicRel.f_Dis...
<p>As you are working with strings, you can use <a href="https://docs.python.org/3/tutorial/inputoutput.html" rel="nofollow noreferrer">f-strings</a>. Below is an example. Note the <code>...</code> should be replaced with all the other columns:</p> <pre><code>index = 3 cols_in_the_slice = df.loc[:, ...
python|dataframe|numpy
0
372,549
73,312,864
how to add a day to date column?
<p>I wanna add a day to all cells of this dataframe:</p> <pre><code>value B N S date date 2020-12-31 1 11 0 2020-12-31 2021-01-01 3 80 0 2021-01-01 2021-01-02 4 99 0 2021-01-02 2021-01-03 3 78 0 2021-01-03 2021-01-04 0 50 0 2021-01-04 </code></...
<p>You can temporarily convert to datetime to add a <a href="https://pandas.pydata.org/docs/reference/api/pandas.tseries.offsets.DateOffset.html" rel="nofollow noreferrer"><code>DateOffset</code></a>:</p> <pre><code>df['date'] = (pd.to_datetime(df['date']) .add(pd.DateOffset(days=1)) .dt...
python|pandas|dataframe
1
372,550
73,405,748
Convert pandas series to boolean doesn't work
<p>I have a data frame <code>df</code> and column <code>col</code>. The value of the last entry is <code>NaN</code>, like this</p> <pre class="lang-py prettyprint-override"><code>df['col'][-1:] 48 NaN Name: col, dtype: float64 </code></pre> <p>I'm trying to apply a condition on that last value, but running this give...
<p><code>~</code> is bitwise operator, when you do <code>~True</code> you are actually doing <code>~1</code> which will invert the each bit from binary representation of <code>1</code>. <sup>[1]</sup></p> <p>What you want is logical operator <code>not</code>.</p> <p>[1] <a href="https://stackoverflow.com/questions/3137...
python|pandas|boolean
0
372,551
73,504,894
Split string in pandas dataframe into individual columns - no delimiter
<p>I have a pandas dataframe <code>df</code> and one of the columns <code>df['x']</code> contains strings of length 100, each string of the form <code>'ABBABBBABBAABAABABBAAABAAAA...'</code></p> <p>How would I go about splitting this 1 column into 100 different columns, each containing only 1 character from the origina...
<p>You can use <code>str.split</code>:</p> <pre><code>df['x'].str.split('',expand=True).iloc[:,1:-1] </code></pre> <p>or <code>str.extractall</code> with <code>unstack</code>:</p> <pre><code>df['x'].str.extractall('(.)')[0].unstack() </code></pre>
python|pandas|dataframe
1
372,552
73,357,742
Tensorboard is not creating any files
<p>I am trying to use tensorboard with pytorch lightning.</p> <p>The code runs, but nothing gets created in the tensorboard logs folder.</p> <p>Relevant (not complete) code:</p> <pre><code>class LightningClassifier(LightningModule): def __init__(self,): self._train_accuracy = torchmetrics.Accuracy() de...
<p>Your logs are expected to be found here:</p> <p><code>/my_path/to/tb_logs/my_logger/version_0</code></p> <p>Note that there is a &quot;/&quot; at the front, so this will go to the root of the filesystem. I'm not sure if this is what you did or it is because you replaced the real path with this for illustration. I'm ...
python|deep-learning|pytorch|tensorboard|pytorch-lightning
0
372,553
73,500,448
After mapping data in order to change to integer, variable only showing NaN value
<p>So I was having trouble with a NaN error where asking for df['column'] was only showing NaN and I've narrowed it down to this specific part of the code and i think it has something to do with the way I have mapped the data. Does anyone have any idea?</p> <p><strong>My code is below:</strong></p> <pre><code>df['count...
<p>I've created <code>df['country_code']</code> in the following way, you should have something similar:</p> <pre><code>import pandas as pd d = {'country_code': [&quot;?&quot;, &quot;BRZ&quot;, &quot;USA&quot;]} df = pd.DataFrame(data=d) print(df) </code></pre> <p>Output:</p> <pre><code> country_code 0 ? 1...
python|pandas|database|sqlite|jupyter-notebook
0
372,554
73,382,841
Error doing CV for training and testing datasets
<p>I am trying to do CV for my training and testing datasets. I am using LinearRegressor. However, when I run the code, I get the error below. How to fix this? Is my code for the CV section correct? Thank you for your help.......................................................</p> <p>Reference for the CV code: <a href=...
<p>Try this</p> <pre><code>from sklearn.model_selection import KFold model=LinearRegression() kfold_validation=KFold(10) import numpy as np from sklearn.model_selection import cross_val_score results=cross_val_score(model,X,y,cv=kfold_validation) print(results) print(np.mean(results)) </code></pre>
python|pandas|scikit-learn
0
372,555
73,290,546
Unpivot multiple variables in a python pandas dataframe
<p>I've got a big dataframe which shows the amount of each product and their costs for different products. However, I want to transform (unpivot) the dataframe into a long dataframe with each product name as an ID and their amounts and costs in two different columns. I've tried the ‍<code>pd.melt‍‍‍</code> and ireshape...
<p>Create MultiIndex by splitting columnsnames and setting <code>Year</code> to <code>index</code>, then replace missing values with <code>amount</code> and reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></...
pandas|dataframe|unpivot
1
372,556
73,364,566
Format date column
<p>For reference, visit <a href="https://pythonprogramming.net/machine-learning-pattern-recognition-algorithmic-forex-stock-trading/" rel="nofollow noreferrer">https://pythonprogramming.net/machine-learning-pattern-recognition-algorithmic-forex-stock-trading/</a></p> <p>I have a text file containing date, bid, ask data...
<p>I don't know the datetime format you want so,</p> <p>if the format it's already ok:</p> <pre><code>from datetime import datetime date, bid, ask = np.loadtxt( &quot;src/data.txt&quot;, unpack=True, delimiter=&quot;,&quot;, converters={ 0: lambda x: x.decode() }, ) </code></pre> <p>if you ...
python|numpy
1
372,557
73,329,700
Calculate Weekly Percent Change in Timeseries data using Pandas for Missing Data in Dataframe
<p>I am having Financial Data,trying to calculate percent change in values between two consecutive <code>thursday</code>. Sometime due to Holiday's on <code>Thursday</code> the weekly data for this week is absent, so I want to calculate that week <code>pct_change</code> from <code>Thursday</code> to <code>Wednesday</co...
<p>Onde idea is add missing datetimes by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.asfreq.html" rel="nofollow noreferrer"><code>DataFrame.asfreq</code></a> with <code>method='ffill'</code> and then reassign names of days by <a href="http://pandas.pydata.org/pandas-docs/stable/r...
python|pandas|dataframe
2
372,558
73,287,450
What did the HDF5 format do to the csv file?
<p>I had a csv file of 33GB but after converting to HDF5 format the file size drastically reduced to around 1.4GB. I used vaex library to read my dataset and then converted this vaex dataframe to pandas dataframe. This conversion of vaex dataframe to pandas dataframe did not put too much load on my RAM.</p> <p>I wanted...
<ol> <li>HDF5 <a href="https://portal.hdfgroup.org/display/HDF5/Using+Compression+in+HDF5" rel="nofollow noreferrer">compresses</a> the data, that explains lower amount of <strong>disk space</strong> used.</li> <li>In terms of <strong>RAM</strong>, I wouldn't expect any difference at all, with maybe even slightly more ...
python|pandas|csv|hdf5|vaex
0
372,559
73,340,057
How to deal with string integers in a dataframe when using the pandas query method?
<pre><code>import numpy as np import pandas as pd numbers = [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;Missing Value&quot;, &quot;7&quot;] df = pd.DataFrame(numbers, columns=[&quot;Numbers&quot;]) new_df = df.query(&quot;Numbers &gt; 4&quot;) print(new_df) </code></...
<p>We have <code>to_numeric</code></p> <pre><code>df['Numbers'] = pd.to_numeric(df['Numbers'], errors = 'coerce') new_df = df.query(&quot;Numbers &gt; 4&quot;) new_df Out[10]: Numbers 4 5.0 5 6.0 7 7.0 </code></pre>
python|pandas|dataframe
1
372,560
73,353,518
How to reload tensorflow model in Google Cloud Run server?
<p>I have a webserver hosted on cloud run that loads a tensorflow model from cloud file store on start. To know which model to load, it looks up the latest reference in a psql db.</p> <p>Occasionally a retrain script runs using google cloud functions. This stores a new model in cloud file store and a new reference in t...
<p>Your current pattern should implement cache management (because you cache a model). How can you invalidate the cache?</p> <ul> <li>Restart the instance? Cloud Run doesn't allow you to control the instances. The easiest way is to redeploy a new revision to force the current instance to stop and new ones to start.</li...
python-3.x|tensorflow|google-cloud-platform|fastapi|distributed-system
2
372,561
73,497,368
How can I check if a timestamp entry is within a time range and with a person filter in two different dataframe?
<p>I need to check if an entry is within a person's shift:</p> <p>The data looks like this:</p> <pre><code>timestamp = pd.DataFrame({ 'Timestamp': ['01/02/2022 16:08:56','01/02/2022 16:23:31','01/02/2022 16:41:35','02/02/2022 16:57:41','02/02/2022 17:38:22','02/02/2022 17:50:56'], 'Person': ['A','B','A','B','B'...
<p>For this kind of <code>merge</code>, an efficient method is to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a>:</p> <pre><code>timestamp['Timestamp'] = pd.to_datetime(timestamp['Timestamp']) (pd.merge_asof(timestamp.sort_values(...
python|pandas
1
372,562
73,498,869
Reformat weird Dataframe
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>place</th> <th>pers_data</th> </tr> </thead> <tbody> <tr> <td>NaN</td> <td>NaN</td> <td>Nan</td> </tr> <tr> <td>Smith John</td> <td>NY</td> <td>sjohn@gmail.com</td> </tr> <tr> <td>NaN</td> <td>Nan</td> <td>0987 4567</td> </tr> <tr> <...
<p>This is a variation on a <code>pivot</code>:</p> <pre><code>idx = df['Name'].notna().cumsum() out = (df .assign(col=df.groupby(idx).cumcount(), Name=df['Name'].groupby(idx).ffill(), place=df['place'].groupby(idx).ffill() ) .pivot(index=['Name', 'place'], columns='col', values='p...
python|pandas
4
372,563
73,306,938
Combining pandas dataframes and ArcGIS feature classes
<p>I have a bit of a general question about the compatibility of Pandas dataframes and Arc featureclasses.</p> <p>My current project is within ArcGIS and so I am mapping mostly with featureclasses. I am however, most familiar with using pandas to perform simple data analysis with tables. Therefore, I am attempting to w...
<p>Esri introduced something called <a href="https://developers.arcgis.com/python/guide/introduction-to-the-spatially-enabled-dataframe/" rel="nofollow noreferrer">Spatially Enabled DataFrame</a>:</p> <blockquote> <p>The Spatially Enabled DataFrame inserts a custom namespace called spatial into the popular Pandas DataF...
pandas|dataframe|arcpy
1
372,564
73,396,454
Polars - Perform matrix inner product on lazy frames to produce sparse representation of gram matrix
<p>Suppose we have a polars dataframe like:</p> <pre><code>df = pl.DataFrame({&quot;a&quot;: [1, 2, 3], &quot;b&quot;: [3, 4, 5]}).lazy() shape: (3, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 3 │ ├╌╌╌╌╌┼╌╌╌╌╌┤ │ 2 ┆ 4 │ ├╌╌╌╌╌┼╌╌╌╌╌┤ │ 3 ┆ 5 │ └─────┴─────┘ </code></pre>...
<p>Polars doesn't have matrix multiplication, but we can tweak your algorithm slightly to accomplish what we need:</p> <ul> <li>use the built-in <a href="https://pola-rs.github.io/polars/py-polars/html/reference/api/polars.Expr.dot.html" rel="nofollow noreferrer"><code>dot</code></a> expression</li> <li>calculate each ...
python|pandas|python-polars
2
372,565
73,308,909
import tensorflow_addons as tfa on conda
<p>i cannot install <code>tensorflow_addons</code> on python on VS code on my anaconda environemnt I have tried using different variations of pip install / conda install but none seem to work for me, and i am getting:</p> <pre><code>ModuleNotFoundError: No module named 'tensorflow_addons' </code></pre> <p>Any help appr...
<p>I think it is just a typo. It is not <code>tensorflow_addons</code> but <code>tensorflow-addons</code>. So:</p> <pre><code>pip install tensorflow-addons </code></pre>
python|tensorflow
0
372,566
73,251,309
How to feed big data into pipeline of huggingface for inference
<pre class="lang-py prettyprint-override"><code>MODEL = &quot;bert-base-uncased&quot; # load the model model_name = MODEL + '-text-classification' from transformers import AutoModelForSequenceClassification, AutoTokenizer load_model = AutoModelForSequenceClassification.from_pretrained(model_name) load_tokenizer = Au...
<p>The error you get (please always post the full error stacktrace in the future), is not caused by the size of a, it is caused by one of the texts exceeding the length your model can handle. Your model can handle up to 512 tokens and you need to <a href="https://huggingface.co/docs/transformers/main_classes/tokenizer#...
huggingface-transformers
2
372,567
73,297,643
How to return individual dates from a date-time series in Python?
<p>I have a datetime column in a data frame. From that column i want to return every single day. In that df, I have 14 days and each day has so many values with even miliseconds.</p> <p>So I want a output like [2022-07-18, 2022-07-19,………………]</p>
<p>You can standardize the format with <code>.dt.date</code>. If it has not yet been converted into datetime, then use:</p> <pre><code>df['Dates'] = pd.to_datetime(df['Dates'],infer_datetime_format=True).dt.date </code></pre> <p>Based on your comment, you can then filter the dates so:</p> <pre><code>filtered_dates = df...
python|pandas|datetime
2
372,568
73,502,202
How to convert a non-fixed width spaced delimited file to a pandas dataframe
<pre><code>ID 0x4607 Delivery_person_ID INDORES13DEL02 Delivery_person_Age 37.000000 Delivery_person_Ratings 4.900000 Restaurant_latitude 22.745049 Restaurant_longitude 75.892471 Delivery_location_latitude ...
<p>Each of your txt files seems to contain only 1 row (as a <code>Series</code>).</p> <p>Unfortunately, these rows are not in an easy-to-read format (for the machines) - looks like they were just printed out and saved like that.</p> <p>Because of this in my solution the indices of the dataframe (which correspond to the...
python-3.x|pandas|csv
0
372,569
73,336,800
pandas: Get the newest record from each group
<p>I have a dataframe that has the following columns:</p> <p><code>region</code> <code>target</code> <code>date</code> <code>info</code> <code>subinfo</code></p> <p>The combination of <code>'region', 'target', 'info', 'subinfo'</code> is unique in the dataframe, except when there is an older duplicate, that has the sam...
<p>If you have a data frame like this:</p> <pre><code>df = pd.DataFrame([ ['region1', 'target1', datetime.datetime(year=2022, month=5, day=1), 'info1', 'subinfo1'], ['region1', 'target1', datetime.datetime(year=2022, month=5, day=2), 'info1', 'subinfo1'], ['region1', 'target1', datetime.datetime(year=2022, ...
python|pandas|dataframe|filter|group-by
0
372,570
73,510,512
Identifying unique index numbers from a list
<p>I have a list <code>A</code> containing an array with indices. I want to print all the unique index numbers by scanning each <code>[i,j]</code>. In <code>[0,3]</code>, <code>i=0,j=3</code>. I present the expected output.</p> <pre><code>import numpy as np A=[np.array([[[0, 1], [0, 3], [1, 3], ...
<p><a href="https://numpy.org/doc/stable/reference/generated/numpy.unique.html" rel="nofollow noreferrer">numpy</a> has this very cool function <code>np.unique</code>.</p> <p>Simply to get the output <code>A=[0,1,3,4,5,6,7]</code></p> <p><code>B = np.unique(A[0])</code></p> <p>Output : <code>[0 1 3 4 5 6 7]</code></p>
python|list|numpy
0
372,571
73,447,695
Apply styler to pivot table
<p>I try to apply <strong>styler</strong> to the pivot table based on the next condition: if the percentage is in the range from 0 to 100, then color it yellow, if more than 100, then color it red, but after that I take a correction for another value <code>df['Value']</code> and if the value in the same row is less tha...
<p>Your function that is basically trying to define the map to colour the given df. Should return a map(boolean values reflecting your conditions) what you are return is something completely different.</p> <p>There are many way of doing what you want here is one, you can try formulating other types of maps, but this is...
python|pandas|pivot-table|pandas-styles
0
372,572
73,317,209
python dataframe pandas drop multiple column using column name
<p>I understand that to drop a column you use <code>df.drop('column name', axis=1, inplace =True)</code></p> <p>The file format is in <code>.csv</code> file</p> <p>I want to use above syntax for large data sets and more in robust way</p> <p>suppose I have 500 columns and I want to keep column no 100 to 140 using colum...
<pre class="lang-py prettyprint-override"><code>df = df.loc[:, 'col_100_name' : 'col_140_name'] </code></pre> <p><code>.loc</code> always selects using both ends inclusive. Here I am selecting all rows, and only the columns that you want to select (by names).</p> <p>After this (or before - it doesn't matter) you can dr...
python|pandas|dataframe
2
372,573
73,404,312
How to write multiple conditional statements for loc dataframe with operators
<p>I'm trying to create a loc dataframe with multiple conditional statements. The problem I am having is that when I use and 'and' operator for my second conditional statement, I get the error below.</p> <p>As a side problem, is there any better way to seperate the conditional statements than with |.</p> <p>My code:</p...
<p>Make sure they are correctly separated by parenthesis to group the logics and consider using bitwise operator:</p> <pre><code>df = df2.loc[(df2['Position'] == 0) | ((df2['TABNo'] == 0) &amp; (df2['IsBarrierTrial'] == 'FALSE'))] </code></pre>
python|pandas|dataframe
1
372,574
73,314,888
Key value pairs into a data frame
<p>I have pulled the key-value pairs below from a API as listed below: summary[&quot;awayBattingTotals&quot;],summary[&quot;homeBattingTotals&quot;],summary[&quot;teamInfo&quot;]</p> <pre><code>response; {'namefield': 'Totals', 'ab': '33', 'r': '2', 'h': '7', 'hr': '1', 'rbi': '2', 'bb': '0', 'k': '8', ...
<p>You are in the right path. This should work:</p> <pre><code>import pandas as pd dict = [{'namefield': 'Totals', 'ab': '33', 'r': '2', 'h': '7', 'hr': '1', 'rbi': '2', 'bb': '0', 'k': '8', 'lob': '13', 'avg': '', 'ops': '', 'obp': '', 'slg': '', 'name': 'Totals', 'position': '', 'note': ...
python|pandas|dataframe|dictionary
0
372,575
73,324,675
Creating New Column in Pandas Using Value from Previous Cell
<p>I'm attempting to build a cash flow loan model table using Pandas. I've generated several of the fields I need such as Beginning Balance, Interest, Principal, Payment, Ending Balance - as shown below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Beginning Bal...
<p>I've figured out what I was trying to accomplish in the above post. With some help from this <a href="https://stackoverflow.com/questions/34855859/is-there-a-way-in-pandas-to-use-previous-row-value-in-dataframe-apply-when-previ">post here</a> I was able to put together this code to fill out the rest of this table:</...
python|pandas
0
372,576
73,194,910
How to Save excel pages file with a loop?
<p>i would like to save a different dataframe in different excel pages withb a simpler loop. How can i construct correctly this loop?</p> <p>my Currently codes are:</p> <pre><code>for fund in list(read_ex.keys()): writer = pd.ExcelWriter(excel_file, engine='xlsxwriter') data_2 .to_excel(writer, shee...
<p>For future readers:</p> <p>I have been resolved this quastion in this way:</p> <pre><code>writer = pd.ExcelWriter(excel_file, engine='xlsxwriter') data_2 .to_excel(writer, sheet_name= 'Df_ag') for fund in list(read_ex.keys()): read_ex[fund] .to_excel(writer, sheet_name= fund[:28]) writer.sav...
python|excel|pandas|loops|writer
1
372,577
73,201,897
get text from a class of a class with beautifulsoup
<p>I am a new with beautifulsoup, I usually do web scrapping with scrapy which uses <code>response.xpath</code> to get the text.</p> <p>This time, I want to get the article news from a class called <code>article-title</code> and the pubslished date from a class called <code>meta-posted</code></p> <p>The html is look li...
<p>This should fix your problem.</p> <pre class="lang-py prettyprint-override"><code>soup = BeautifulSoup(html_doc, 'html.parser') titles= soup.findAll('h1', attrs={'class':'article-title'}) for title in titles: print(title.get_text()) dates = soup.findAll('span', attrs={'class':'meta-posted'}) for date in d...
python|html|pandas|beautifulsoup
1
372,578
73,381,998
Using a regular expression to pull data from multiple dataframes
<p>I am trying to use Regular expression to look at multiple contract specifications in a data frame to then use them in a filter. Below is a snippet of my code.</p> <pre><code>import pandas as pd import re Example_dict = {'S_1':pd.DataFrame({'Product1 Hours':'Lowest priced 5 concecutive hours in HE09 thru HE16', ...
<p>You're applying the regex against <code>str(Example_DF)</code>.</p> <p>I assume you want to apply the regex to the entire DataFrame (every row, every cell), but <code>str(Example_DF)</code> is not a good reproduction of the entire DataFrame. Just evaluate it in python to see. When I evaluate it I see something like ...
python|pandas|regex
1
372,579
73,280,535
Group dataframe by two columns and then find average count based on one of the groups
<p>Really struggling to get this solution. Suppose I have the dataframe below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SEX</th> <th>ITEM</th> <th>Some other column</th> </tr> </thead> <tbody> <tr> <td>M</td> <td>Socks</td> <td>233</td> </tr> <tr> <td>M</td> <td>Socks</td> <td>1</td>...
<p>Let us try <code>crosstab</code></p> <pre><code>out = pd.crosstab(df['SEX'], df['ITEM'],normalize='index').stack().reset_index(name='average') Out[36]: SEX ITEM average 0 F Hat 0.750000 1 F Socks 0.250000 2 M Hat 0.333333 3 M Socks 0.666667 </code></pre>
python|pandas|dataframe|group-by|data-science
4
372,580
73,444,228
Pandas Dataframe - Convert time interval to continuous time series
<p>I have an energy data with a start time and end time interval. I want to distribute the total energy to the continuous time series (dividing total energy to total hours). As I searched the results, I have found staircase and daterange functions. However, with these results I couldn't distribute energy and sum same i...
<p>I'm not 100% clear on what is needed, but if it is to essentially take the average (i.e. &quot;distribute&quot; as you say) the energy within 15 minute intervals then the below approach with <a href="https://www.staircase.dev" rel="nofollow noreferrer"><code>staircase</code></a> can be used.</p> <p><strong>setup</st...
pandas|time-series|date-range
1
372,581
73,402,405
Concat rows in dataframe
<p>I have a dataframe looking like this :</p> <pre><code>DATA | 0 | 1 | 2 | 3 XX1 | | 0A | 0B | XX2 | | 0C | | XX3 | | 1A | 0A | 1C </code></pre> <p>I would like to transform it that way :</p> <pre><code>id | DATA 0A | XX1 0A | XX3 0B | XX1 0C | XX2 1A | XX3 1C | XX3 </code></pre> <p>Every id mus...
<p>You can use <code>DataFrame.melt</code> for this:</p> <pre class="lang-py prettyprint-override"><code>( df.melt(id_vars=&quot;DATA&quot;, value_name=&quot;id&quot;) .dropna() .sort_values(&quot;id&quot;, ignore_index=True) .drop(columns=[&quot;variable&quot;]) ) </code></pre> <pre><code> DATA id 0 ...
python|pandas|iteration|concatenation
1
372,582
73,266,186
Python Machine Learning value in e form instead of integer or float
<p>When i am running this code the predicted values come out to be in the form of e(6.291149e+06,5.684170e+06)</p> <pre><code>pred_y_df=pd.DataFrame({'Actual Value':y_test,'Predicted value':y_pred,'Difference':y_test-y_pred}) pred_y_df[0:20] </code></pre> <p><a href="https://i.stack.imgur.com/einVd.png" rel="nofollow n...
<p>Try adding this line before you are displaying the results:</p> <pre><code>pd.options.display.float_format = '${:,.2f}'.format </code></pre> <p>Alternatively, you can format the actual columns, e.g.:</p> <pre><code>pred_y_df['Predicted'] = pred_y_df['Predicted'].map('${:,.2f}'.format) </code></pre>
python|pandas
0
372,583
73,373,387
Can I put a condition for y-index in numpy.where?
<p>I have a 2D numpy array taken from a segmentation. Therefore, it's an image like the one in the right:</p> <p><a href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwYeYOHk0xUJ6vBd_g8Xn1LxMON0g2qHpf_TPJx6h7IM5nG2OXeKtDuCcjgN9mqFtLB5c&amp;usqp=CAU" rel="nofollow noreferrer">https://encrypted-tbn0.gstatic.com...
<p>Your current example seems to be misaligned with what you want:</p> <pre class="lang-py prettyprint-override"><code>a = np.array([1, 1, 2, 2, 3, 3]) np.where(a==2, a, 7) </code></pre> <p>produces:</p> <pre class="lang-py prettyprint-override"><code>array([7, 7, 2, 2, 7, 7]) </code></pre> <hr /> <p>If you want to <st...
python|numpy
2
372,584
73,375,451
Class can't read its attribute
<p>I following <a href="https://github.com/python-engineer/pytorchTutorial/blob/master/09_dataloader.py" rel="nofollow noreferrer">this pytorch tutorial</a></p> <p>On the basis of this link I wrote the following code:</p> <pre><code>import torch import torchvision from torch.utils.data import Dataset,DataLoader import ...
<p>Change <code>def __int__(self)</code> to <code>def __init__(self)</code>. Right now you have no constructor.</p>
python|pytorch
3
372,585
73,267,868
How to do slice and update operation on tensors in Tensorflow 2.0
<p>I have been trying to convert the following PyTorch code into TensorFlow 2.0.</p> <pre><code>def __getitem__(self, idx): mask = torch.from_numpy(self.mask[idx]) input_seq = torch.zeros(self.dataset[idx].shape, dtype=torch.float32) input_seq[1:, :] = torch.from_numpy(self.d...
<p>You can just use the <code>assign</code> method just like this:</p> <pre class="lang-py prettyprint-override"><code>input_seq[1:, :].assign(tf.convert_to_tensor(self.dataset[idx, :-1, :])) </code></pre>
python|tensorflow|pytorch|tensorflow2.0
0
372,586
73,509,541
Detrending by date ranges
<p>Considering a df structured like this</p> <pre><code>Time X 01-01-18 1 01-02-18 20 01-03-18 34 01-04-18 67 01-01-18 89 01-02-18 45 01-03-18 22 01-04-18 1 01-01-19 11 01-02-19 6 01-03-19 78 01-04-19 5 ...
<p>When converting strings to the datetime format, you can specify the format directly. <code>infer_datetime_format</code> can mix up day and month.</p> <pre class="lang-py prettyprint-override"><code>df['date'] = pd.to_datetime(df['Time'], format='%d-%m-%y') </code></pre> <hr /> <pre class="lang-py prettyprint-overrid...
python|pandas|dataframe|date|time-series
1
372,587
73,375,020
Power of 2 requirement when using python rfft
<p>I'm using numpy.fft in python to compute Fast Fourier Transforms. In particular, I'm using rfft as I have a real signal and don't need negative frequencies. My question is this: when I go to compute the FFT, does the length of my signal have to be a power of 2? My signal has 184320 points so I'm wondering if I need ...
<p>You do not have to pad the signal. The FFT implementation in NumPy is efficient for array lengths that are products of small prime factors, as noted in <a href="https://github.com/numpy/numpy/blob/main/numpy/fft/README.md" rel="nofollow noreferrer">README.md</a>, which says</p> <blockquote> <p>Efficient codelets ar...
python|numpy|fft
1
372,588
73,211,891
Change numpy array inside recursive function
<p>Question 4.1-1 from CLRS Introduction to Algorithms</p> <p>I have code that multiply n*n matrix, where n is exact power of 2, using recursion. I need to modify this code, so that n doesn't need to be exact power of 2. Obvious way to do it is adding zeroes to matrix so it became k*k, where k is power of 2.<br /> I tr...
<p>I tested it only with your example - so I don't know if there are other problems.</p> <hr /> <p>I see two problems:</p> <ol> <li><p>You resize <code>C</code> but you have to resize also <code>A</code> and <code>B</code> to make calculations on matrixes with the same shapes. And this was generating <code>IndexError: ...
python|arrays|algorithm|numpy
0
372,589
35,029,002
Run a function on every row of a pandas dataframe with dictionary return
<p>I have a number of functions that each return dictionary, which I would like to run on each row of a Pandas <code>DataFrame</code>.</p> <p>For example</p> <pre><code>def calc_a(input): # do calculations return {"x": valuex, "y": valuey, "z": valuez} </code></pre> <p>I've obviously omitted all the calculat...
<p>If you return a <code>Series</code> it should create separate columns for each key, this should be as simple as wrapping your existing dictionary in a <code>Series</code> call like:</p> <pre><code>return pd.Series({"x": valuex, "y": valuey, "z": valuez}) </code></pre>
python|dictionary|pandas
2
372,590
35,330,117
How can I run a loop with a tensor as its range? (in tensorflow)
<p>I want to have a for loop that the number of its iterations is depend on a tensor value. For example:</p> <pre><code>for i in tf.range(input_placeholder[1,1]): # do something </code></pre> <p>However I get the following error:</p> <p><strong>"TypeError: 'Tensor' object is not iterable"</strong></p> <p>What sho...
<p>To do this you will need to use the tensorflow while loop (<a href="https://www.tensorflow.org/api_docs/python/tf/while_loop" rel="noreferrer"><code>tf.while_loop</code></a>) as follows:</p> <pre><code>i = tf.constant(0) while_condition = lambda i: tf.less(i, input_placeholder[1, 1]) def body(i): # do something...
python|tensorflow|neural-network|deep-learning
34
372,591
35,283,817
How can I get the index of next non-NaN number with series in pandas?
<p>In pandas, I am now looping with an instance of Series, is it possible for me to know the index of the next non-NaN instantly when I meet a NaN. I don't want to skip those NaNs, because I want to do the interpolation against them.</p> <p>e.g now I have a Series <code>a</code> with elements</p> <pre><code>5, 6, 5, ...
<p>You could use <a href="https://www.google.ru/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=0ahUKEwiS95y57enKAhVGCZoKHTn6BKQQFggbMAA&amp;url=http%3A%2F%2Fpandas.pydata.org%2Fpandas-docs%2Fstable%2Fgenerated%2Fpandas.isnull.html&amp;usg=AFQjCNF-zsbxBhTegthKXtMm3fDGC13IvQ&a...
python|pandas|interpolation
10
372,592
35,130,773
ThreadPoolExecutor - how to return arguments
<p>I need to parse around 1000 URLs. So far I have a function that returns a pandas dataframe after parsing the URL. How should I best structure the program so I can add all the dataframes together? I'm also unsure how to return arguments into 'futures'. In the below example, how can I eventually merge all temp datafra...
<p>You have to protect your launch code with <code>if __name__ == '__main__':</code> to prevent creating processes forever. Just before <code>concurrent.futures.wait(futures)</code></p>
python|pandas|threadpoolexecutor
0
372,593
34,951,005
Re-index data frame; fill index using elements from multiple columns
<p>I have a Pandas DataFrame as shown below:</p> <pre><code> I1 V1 I2 V2 I3 V3 ... 0 13.823560 0.000000 13.639405 0.000000 13.455246 0.000000 ... 1 13.823376 0.001274 13.639224 0.001273 13.455068 0.001272 ... 2 13.823193 0.002547 13.639043 ...
<p>Starting with:</p> <pre><code>Int64Index: 11 entries, 0 to 10 Data columns (total 6 columns): I1 11 non-null float64 V1 11 non-null float64 I2 11 non-null float64 V2 11 non-null float64 I3 11 non-null float64 V3 11 non-null float64 dtypes: float64(6) </code></pre> <p>Try:</p> <pre><code>pd.conca...
python|python-2.7|pandas
0
372,594
35,089,255
pandas - reshape dataframe to edge list according to column values
<p>Starting from this simple dataframe:</p> <pre><code> node t1 t2 0 a pos neg 1 b neg neg 2 c neg neg 3 d pos neg 4 e neg pos 5 f pos neg 6 g neg pos </code></pre> <p>I would like to build an edgelist file to read it as a undirected network. The expected output is:</p> <pre><...
<p>Have a look at this:</p> <pre><code>df = pd.DataFrame({'node': ['a', 'b','c', 'd', 'e', 'f', 'g'], 't1': ['pos', 'neg', 'neg', 'pos', 'neg', 'pos', 'neg'], 't2': ['neg', 'neg', 'neg', 'neg', 'pos', 'neg', 'pos']}) K = nx.Graph() K.add_nodes_from(df['node'].values) # Create edges for ...
python|pandas|networkx
3
372,595
35,236,880
Groupby on categorical column with date and period producing unexpected result
<p>The issue below was created in Python 2.7.11 with Pandas 0.17.1</p> <p>When grouping a categorical column with both a period and date column, unexpected rows appear in the grouping. Is this a Pandas bug, or could it be something else?</p> <pre><code>df = pd.DataFrame({'date': pd.date_range('2015-12-29', '2016-1-3...
<p>As defined in pandas, grouping with a categorical will always have the full set of categories, even if there isn't any data with that category, e.g., doc example <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html#operations" rel="nofollow">here</a></p> <p>You can either not use a categorical, or ...
python|pandas
0
372,596
35,157,742
How to convert singleton array to a scalar value in Python?
<p>Suppose I have 1x1x1x1x... array and wish to convert it to scalar?</p> <p>How do I do it?</p> <p><code>squeeze</code> does not help.</p> <pre><code>import numpy as np matrix = np.array([[1]]) s = np.squeeze(matrix) print type(s) print s matrix = [[1]] print type(s) print s s = 1 print type(s) print s </code></...
<p>You can use the <code>item()</code> function:</p> <pre><code>import numpy as np matrix = np.array([[[[7]]]]) print(matrix.item()) </code></pre> <p><strong>Output</strong></p> <pre><code>7 </code></pre>
python|numpy|multidimensional-array
59
372,597
34,903,916
How to refer to a built-in op when writing a custom user op
<p>I'm writing a custom op in tensorflow, and I would like to refer to an op that already exists, either one of my own user ops, or one of the built-in ops. Is there any way to do this without just copy pasting the code from the other op that I'm referring to?</p>
<p>The answer to this is "it depends." Only some of the built-in ops are factored in a reusable way. For example, the component-wise ops are implemented as <a href="https://github.com/tensorflow/tensorflow/blob/04de87f1204103cf9b753858ecae33099aafb4c2/tensorflow/core/kernels/cwise_ops.h#L573" rel="nofollow">reusable fu...
c++|tensorflow
1
372,598
34,931,310
How to subtract two unsigned numpy arrays to give a signed result?
<p>I would like to subtract two unsigned numpy arrays and get a signed result. I don't know the types in advance. Casting both to int64 works, but this needlessly wastes space if the inputs are uint8 (casting to int16 would suffice).</p> <p>I have thought of writing a function that returns the next larger signed type ...
<p>You could use <code>newtype = np.promote_types(x.dtype, np.byte)</code>, where <code>x</code> is your unsigned array with unknown dtype. Since <code>np.byte</code> is the smallest possible signed integer type, <code>newtype</code> will be the smallest signed integer type to which <code>x</code> can be safely cast.</...
python|arrays|numpy
2
372,599
35,293,672
Why do these dtypes compare equal but hash different?
<pre><code>In [30]: import numpy as np In [31]: d = np.dtype(np.float64) In [32]: d Out[32]: dtype('float64') In [33]: d == np.float64 Out[33]: True In [34]: hash(np.float64) Out[34]: -9223372036575774449 In [35]: hash(d) Out[35]: 880835502155208439 </code></pre> <p>Why do these dtypes compare equal but hash diff...
<p>As <code>tttthomasssss</code> notes, the <code>type</code> (class) for <code>np.float64</code> and <code>d</code> are different. They are different kinds of things:</p> <pre><code>In [435]: type(np.float64) Out[435]: type </code></pre> <p>Type <code>type</code> means (usually) that it is a function, so it can be ...
python|numpy
5