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 |
|---|---|---|---|---|---|---|
19,700 | 70,384,854 | Python Pandas iterate through list and map | <p>I'm trying to make a simple script that should get the id of an item and get some stats associated with it and add it to the dataframe.</p>
<pre><code>stats = ['info_attack', 'info_defense', 'info_magic', 'info_difficulty', 'stats_hp', 'stats_hpperlevel', 'stats_mp', 'stats_mpperlevel',
'stats_movespeed', '... | <p>Try using <code>.replace</code> instead of <code>.map</code>:</p>
<pre><code>for stat in stats:
print(stat)
ngrams[stat] = ngrams['ChampionID'].replace(champDataFrame.set_index('key')[stat])
</code></pre> | python|pandas|mapping | 0 |
19,701 | 42,996,110 | deleting a range of rows in enothught canopy | <p>Here is my Pandas DataFrame:</p>
<pre><code>import pandas as pd
dfa = df = pd.read_csv("twitDB3__org.csv")
dfa.drop([7-100], axis=0, inplace=True)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>ValueError: labels [-93] not contained in axis
</code></pre>
<p>I am new to canopy and want to delete a range... | <p>a) I think you want <code>dfa.drop(range(7,101),...</code> (What you did was just subtract 100 from 7 and pass the result (-93) as the label to drop.)</p>
<p>b) Note that this will also change <code>df</code>, because as you've written it, <code>df</code> and <code>dfa</code> are just two names for the same mutable... | python|pandas|canopy | 0 |
19,702 | 42,590,768 | Explaining Variational Autoencoder gaussian parameterization | <p>In the original Auto-Encoding Variational Bayes <a href="https://arxiv.org/abs/1312.6114" rel="nofollow noreferrer">paper</a>, the authors describes the "reparameterization trick" in section 2.4. The trick is to breakup your latent state z into learnable mean and sigma (learned by the encoder) and adding Gaussian no... | <ol>
<li><p>They are not assuming that the activations of the encoder follow a gaussian distribution, they are enforcing that of the possible solutions choose a gaussian resembling one.</p></li>
<li><p>The image is generated from decoding a activation/feature, the activations are distributed resembling a gaussian.</p><... | tensorflow|autoencoder | 2 |
19,703 | 43,001,729 | How should I interpret the output of numpy.fft.rfft2? | <p>Obviously the rfft2 function simply computes the discrete fft of the input matrix. However how do I interpret a given index of the output? Given an index of the output, which Fourier coefficient am I looking at?<br>
I am especially confused by the sizes of the output. For an n by n matrix, the output seems to be an ... | <p>The output of <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.rfft2.html#numpy.fft.rfft2" rel="noreferrer"><code>numpy.fft.rfft2</code></a> is simply the left half (plus one column) of a standard two-dimensional FFT, as computed by <a href="https://docs.scipy.org/doc/numpy/reference/generated... | python|numpy|fft | 8 |
19,704 | 42,871,043 | How to measure the accuracy of predictions using Python/Pandas? | <p>I have used the Elo and Glicko rating systems along with the results for matches to generate ratings for players. Prior to each match, I can generate an expectation (a float between 0 and 1) for each player based on their respective ratings. I would like test how accurate this expectation is, for two reasons:</p>
<... | <p>An industry standard way to judge the accuracy of prediction is Receiver Operating Characteristic (ROC). You can create it from your data using sklearn and matplotlib with this code below. </p>
<p>ROC is a 2-D plot of true positive vs false positive rates. You want the line to be above diagonal, the higher the bett... | python|python-3.x|pandas|statistics | 5 |
19,705 | 30,382,912 | Transpose Pandas Pivot Table | <p>I created a pandas pivot table using <code>pd.pivot_table</code>. My table has one dependent variable, and then three independent variables (1 for rows, 2 for columns). I want to export the table so all the values are in one row. However, when I try to <code>unstack()</code> the table, instead of moving the row vari... | <p>You are producing a Series by stacking (or unstacking), which is actually one-dimensional and displays as a column. You could force to display as a row with something like this: </p>
<pre><code>pd.DataFrame(df.stack()).T
</code></pre> | python|pandas | 3 |
19,706 | 30,500,311 | Bounded optimization using the Hessian matrix (scipy) | <p>I am trying to optimize a function of a small number of variables (somewhere from 2 to 10). What I am trying to do is calculate the minimum of the function on a bounded hypercube </p>
<p><code>[0,1] x [0,1] x ... x [0,1]</code></p>
<p>The calculation of the function, its gradient and its hessian is al relatively s... | <p>Here are a couple of alternatives:</p>
<p><a href="http://trac.mystic.cacr.caltech.edu/project/mystic/wiki" rel="nofollow">Mystic</a>, a framework which enables constraint optimization by using external constraints (I think, Lagrange multipliers). The package uses scipy.optimize, so it should be possible to use Sci... | python|numpy|optimization|scipy | 1 |
19,707 | 23,934,905 | Pandas - conditionally select source column of data for a new column based on row value | <p>Is there a pandas function that allows selection from different columns based on a condition? This is analogous to a CASE statement in a SQL Select clause. For example, say I have the following DataFrame:</p>
<pre><code>foo = DataFrame(
[['USA',1,2],
['Canada',3,4],
['Canada',5,6]],
columns = ('Cou... | <p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html?highlight=where#pandas.DataFrame.where" rel="noreferrer"><code>DataFrame.where</code></a>'s <code>other</code> argument and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferr... | python|pandas | 19 |
19,708 | 62,471,243 | How to drop pandas rows that has partial match of substring? | <p>I have a dataframe , I want to drop rows that has partial substring match as below, and save those to new csv file . The below line of code works fine , but I did not know how to drop those rows from the original dataframe (<code>df2</code>) and save the output to other csv file .</p>
<pre><code>df2_output=df2[df2[... | <p>I believe you want select non matched values by inverting mask by <code>~</code>:</p>
<pre><code>df3_output=df2[~df2['Name'].str.contains("planning|Test|tgt",case=False)]
</code></pre>
<p>Or for improve performance (test only once, not 2 times) save output of mask to variable:</p>
<pre><code>mask = df2['Name'].s... | python|pandas | 2 |
19,709 | 62,355,233 | In pandas dataframes, how would you convert all index labels as type DatetimeIndex to datetime.datetime? | <p>Just as the title says, I am trying to convert my DataFrame lables to type datetime. In the following attempted solution I pulled the labels from the DataFrame to dates_index and tried converting them to datetime by using the function DatetimeIndex.to_datetime, however, my compiler says that DatetimeIndex has no att... | <p>I found a quick solution to my problem. You can create a new pandas column based on the index and then use datetime to reformat the date.</p>
<pre><code>df['date'] = df.index # Creates new column called 'date' of type Timestamp
df['date'] = df['date'].dt.strftime('%m/%d/%Y %I:%M%p') # Date formatting
</code></pr... | python|pandas|dataframe|datetime | 0 |
19,710 | 62,314,939 | TFX - REST API Without Serializing the Data Input to Get Prediction | <p>I'm new to TFX, and I've been following through the Keras tutorial, and I have successfully created the TFX pipeline using my data. While I learn to serve my model through Docker with TF Serving, my data input has to be serialized as follows to return the prediction result. </p>
<p>How can I have data input to REST... | <p>After retest again, the test 1 has successfully executed. </p> | python|python-3.x|tensorflow2.0|tfx | 0 |
19,711 | 62,141,208 | Date Error in Pandas looking to resolve 1970 error | <p>I am using the following code in python to convert an object to date format:
df['MATURITY_DATE'] = pd.to_datetime(df['MATURITY_DATE'])</p>
<p>However, it keeps making the dates turn to 1970. The raw data looks like "20270601".</p>
<p>Any suggestions would be great, the data is coming in from a CSV and the CSV itse... | <p>Does "20270601" is a unix time format?
if yes, use:</p>
<pre><code>pd.to_datetime(df['MATURITY_DATE'],unit='s')
</code></pre>
<p>or</p>
<pre><code>pd.to_datetime(df['MATURITY_DATE'],unit='ns')
</code></pre>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel=... | python|pandas | 0 |
19,712 | 51,459,592 | Merging Batches of 200 Rows into 1 Row Pandas Dataframe | <p>Is there a way to merge 200 rows of a pandas dataframe into one row. The dataset consists of million of posts and i'm attempting to train a model on batches (profile level, instead of message level).</p>
<p>Image the next three lines are my pandas dataframe ( data['Body][:2] ):</p>
<pre><code>line1 = "I'm a beast"... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.Series.str.cat.html" rel="nofollow noreferrer"><code>str.cat</code></a></p>
<pre><code>df = pd.DataFrame({'lines':["I'm a beast",
"Ofocurse, that's great",
"Hey John, what's up?"]... | python|pandas|dataframe | 2 |
19,713 | 51,327,863 | Python Adding leading zero to Time field | <p>How to add leading zeros to a int column in a data frame. I have an int column which has the time values in the format HHMMSS. Some of the time values which are after 12am have two digits. i.e 30 is supposed to be 0030, 45 is supposed tp be 0045. How do I add leading zeros to the below column</p>
<pre><code>ColumnN... | <p>You have to take the following steps:</p>
<ol>
<li>Convert the content of the column to strings</li>
<li>Access the content with the <code>str</code> accessor.</li>
<li>Call <code>zfill</code></li>
</ol>
<p>And most importantly, </p>
<p><strong>4. Reassign back to the series:</strong></p>
<p><br></p>
<pre><code... | python|string|python-2.7|pandas | 3 |
19,714 | 51,423,911 | pandas pct_change unrealistic values | <p>i execute the following python code:</p>
<pre><code>data_extracted = data_extracted.interpolate(method='linear',
axis=0).ffill().bfill()
data_extracted = data_extracted.replace([np.inf, -np.inf], np.nan).fillna(0)
data_pct_change = data_extracted.pct_change(axis=0).replace([np.inf, -np.inf],
np.nan)
data_pct_chan... | <p>You can utilize the <code>shift</code> function in <code>pandas</code> to turn this into a vectorized operation. The first thing to do is to make sure <code>DATE</code> is your index. If you have already set <code>DATE</code> as your index you can skip this set.</p>
<pre><code>data_extracted.set_index("DATE", inp... | python|pandas | 1 |
19,715 | 48,067,360 | Error TensorFlow "Dimensions must be equal, but..." | <p>For start in Tensorflow, I am triying to reproduce the basic example of the estimator with the IRIS data set, but with my own data.</p>
<pre><code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from six.moves.urllib.request import urlopen
... | <p>Your labels and predictions have different dimensions (160 and 128).</p> | python-3.x|tensorflow | 1 |
19,716 | 48,471,926 | In Tensorflow's Dataset API how do you map one element into multiple elements? | <p>In the tensorflow <code>Dataset</code> pipeline I'd like to define a custom map function which takes a single input element (data sample) and returns multiple elements (data samples).</p>
<p>The code below is my attempt, along with the desired results. </p>
<p>I could not follow the documentation on <code>tf.data.... | <p>Two more steps were required to achieve this. First, the map function needs to return a numpy array, not a list.</p>
<p>Then you can use <code>flat_map</code> combined with <code>Dataset().from_tensor_slices()</code> to flatten them. The code below now produces the desired result:</p>
<p>Tested in Tensorflow 1.5 (... | python|tensorflow|tensorflow-datasets | 11 |
19,717 | 48,670,424 | Pandas combine 2 Dataframes and overwrite values | <p>I've looked into pandas join, merge, concat with different param values (how to join, indexing, axis=1, etc) but nothing solves it!</p>
<p>I have two dataframes:</p>
<pre><code>x = pd.DataFrame(np.random.randn(4,4))
y = pd.DataFrame(np.random.randn(4,4),columns=list(range(2,6)))
x
Out[67]:
0 1... | <p>You can try <code>combine_first</code>:</p>
<pre><code>df = y.combine_first(x)
</code></pre> | python|pandas | 1 |
19,718 | 48,739,924 | Pandas add a new column whose values depend on a specific conditions | <p>I have a dataframe that has a column called 'Date; that contains the date in the format month/day/year('01/01/2018'). I want to create a new column called 'Month' that will contain the name of the month, in this example january.
Obviously i want to do that for each month.</p>
<p>Ex:</p>
<pre><code> Date ... | <p>I am assuming 'Date' in df is <code>string</code> , hence the need to convert.
If not you will need to adjust accordingly.</p>
<p>Try following</p>
<pre><code>from datetime import date,datetime #date needed for simulation.
import pandas as pd
l = ['01/01/2018','02/03/2018','04/08/2018']
df = pd.DataFrame({'Da... | python|pandas | 1 |
19,719 | 48,697,412 | Pandas groupby unique issue | <p>I have a dataframe 'region_group'. As shown below, this dataframe does not have 'ARTHOG' value in 'Town/City' column. However when I do groupby-first, on this column, this value pops back in. I am trying to understand why this is happening.</p>
<p>Note: region_group dataframe is based on another dataframe which has... | <p>Category data will carry over the category , when there is no value , will still keeping the category but fill the value as NaN </p>
<pre><code>df=pd.DataFrame({'A':[1,1,3,4,5],'B':[1,2,2,2,2]})
df.A=df.A.astype('category',categories=[1,2,3,4,5])
df.groupby('A').B.first()
Out[905]:
A
1 1.0
2 NaN
3 2.0
4 ... | python|pandas | 1 |
19,720 | 70,815,773 | Unable to calculate the aggregated mean | <p>I have a dataset in this form:</p>
<pre><code>Customer_key purcahse_amount Date
12633 4435 08/07/2021
34243 7344 11/11/2021
54355 4642 10/11/2020
12633 6322 11/12/2021
</code></pre>
<p>Purchase_amount has few Nan values.... I want to ... | <p>You can <code>groupby</code> "Customer_key" and then compute the mean of "purchase_amount" and transform it for the DataFrame (we need to transform it to use it in <code>np.where</code> where the values to choose from must be broadcastable). Note that <code>mean</code> method skips NaN values by ... | python|pandas|dataframe | 1 |
19,721 | 51,864,701 | How can I add an X axis showing plot data seconds to a matplotlib pyplot price volume graph? | <p>The code below plots a price volume chart using data from a tab separated csv file. Each row contains values for those columns: IDX, TRD, TIMESTAMPMS, VOLUME and PRICE. As is, the X axis shows the IDX value. I would like the X axis to display the seconds computed from the timestamp in milliseconds attached to each r... | <p>I believe you need to <code>data.setindex('TIMESTAMPMS')</code> to get the axis to autoscale</p> | python-3.x|pandas|matplotlib | 0 |
19,722 | 51,594,725 | Populate column with the subfolder's name in Python? | <p>I have written this question focused on pandas since it is a more popular module, to understand a similar example.</p>
<p>I want to add a column and populate it with the part of each files unique address in the directory:</p>
<p>Example:
say I have two files from each subfolder named: <code>45554</code> and <code>... | <p>Using <code>str.split</code></p>
<p><strong>Ex:</strong></p>
<pre><code>import pandas as pd
df = pd.DataFrame({"Path": ['C:\\Users\\user\\Desktop\\SHAPE\\45554\\INS\\INS.shp', 'C:\\Users\\user\\Desktop\\SHAPE\\45554\\INB\\INB.shp', 'C:\\Users\\user\\Desktop\\SHAPE\\32456\\INS\\INS.shp', 'C:\\Users\\user\\Desktop\... | python|pandas | 1 |
19,723 | 64,608,359 | Filtering out keywords(case insensitive) from a column of a dataframe - Pandas | <p>Want to create a new column based on a word in an existing column
The new column should either Lobby,UPS,Electrical or '<em>Blank Space</em>'</p>
<pre><code>Name SubUnitName
Lobby Area Lobby
Sensor - Bank lobby Lobby
Temperature - UPS Room ... | <p>Establishes the list of words to look for in the "Name" column, then applies the function "find_match" in order to create the new "SubUnitName" column.</p>
<pre><code>search_list = ["Lobby", "UPS", "Electric"]
def find_match(name_str: str) -> str:
... | python|pandas|numpy|dataframe | 1 |
19,724 | 64,340,467 | Parsing information out of a pandas multi-index | <p>From this pandas data frame, I am trying to parse out all the values corresponding to the date of '2019-1-02' for each ticker,</p>
<pre><code> (Dividends + Share Buyback) / FCF ... Price to Book Value
Ticker Date ...
A 2007-01-03... | <p>You'll want to use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.xs.html" rel="nofollow noreferrer">DataFrame.xs(...)</a> method for this. This should work for your dataframe:</p>
<pre><code>df.xs("2019-1-02", level="Date")
</code></pre> | python|python-3.x|pandas | 3 |
19,725 | 64,198,461 | How to groupby and forward fill with 0 | <p>My dataframe looks like this:</p>
<pre><code>ID Time Quantity
1 2020-01-01 00:00:01 0
1 2020-01-01 00:00:02 500
2 2020-01-01 00:00:03 0
1 2020-01-01 00:00:04 300
1 2020-01-01 00:00:05 0
2 2020-01-01 00:00:06 200
2 2020-01-0... | <ul>
<li>Columns should be sorted by <code>'ID'</code> and <code>'Time'</code>, to ensure the filled data aligns with <code>df</code>
<ul>
<li><code>.groupby</code> will order <code>'ID'</code>, so if <code>df</code> is not sorted, the <code>groupby</code> results will not match with <code>df</code></li>
</ul>
</li>
<l... | python|pandas|pandas-groupby | 2 |
19,726 | 47,932,955 | How to check if a 3D point is inside a cylinder | <p>Given two 3d points and another list of 3d points, I want to check which one is inside the cylinder defined as the 3d line between the two points with a radius of r.
I've implemented a numeric solution for that, which isn't accurate and too slow:</p>
<pre><code>def point_in_cylinder(pt1, pt2, points, r, N=100):
... | <p>(To my understanding) You are creating a discrete (and quite large) list of uniformly spaced points inside the cylinder on its axis, then checking if the minimum distance of the test point to an axial point is within the radius of the cylinder. </p>
<hr>
<p>This is slow because each of these tests has complexity <... | python|numpy|3d | 9 |
19,727 | 49,045,283 | Python - Group Column values into Classes | <p>I've a CSV with the following data:</p>
<pre><code>Customer Age
A 10
B 53
C 20
D 2
E 55
F 12
</code></pre>
<p>For that I'm using Pandas library to read the csv. My question is how I can group the Ages values in order to get a new column with intervals... | <p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a>:</p>
<pre><code>df['Age_Interval'] = pd.cut(df['Age'], bins=np.arange(0,110,10))
print (df)
Customer Age Age_Interval
0 A 10 (0, 10]
1 B 53 ... | python|pandas|dataframe|grouping | 5 |
19,728 | 48,960,010 | ValueError: Cannot feed value of shape (128, 28, 28) for Tensor 'Placeholder:0', which has shape '(?, 784)' | <p>I am new to Tensorflow and Machine Learning and trying out CNN using Tensorflow with my custom input data. But I am getting the error attached below.</p>
<p>The Data or Image Size is 28x28 with 15 Labels.
I am not getting the numpy reshape thing in this script or the error.</p>
<p>Help is highly appreciated.</p>
... | <p>If you look closely, you'll see that you have <em>two</em> <code>x</code> placeholders:</p>
<pre><code>x = tf.placeholder('float', [None, 784]) # global
...
x = tf.reshape(x, shape=[-1,28,28,1]) # in neural_network_model
</code></pre>
<p>One of them is in the function scope, hence not visible in <code>train... | numpy|tensorflow|machine-learning|neural-network|training-data | 5 |
19,729 | 49,301,344 | Pass Different Columns in Pandas DataFrame in a Custom Function in df.apply() | <p>Say I have a dataframe <code>df</code>:</p>
<pre><code> x y z
0 1 2 3
1 4 5 6
2 7 8 9
</code></pre>
<p>I wanna have two new columns that are x * y and x * z:</p>
<pre><code> x y z xy xz
0 1 2 3 2 3
1 4 5 6 20 24
2 7 8 9 56 63
</code></pre>
<p>So I define a function <code>func</code> (just for example) that t... | <p>I think <code>eval</code> is perfect here </p>
<pre><code>df['x*y'],df['x*z']=df.eval('x*y'),df.eval('x*z')
df
Out[14]:
x y z x*y x*z
0 1 2 3 2 3
1 4 5 6 20 24
2 7 8 9 56 63
</code></pre> | python|pandas|dataframe | 4 |
19,730 | 49,185,032 | Creating a column based on multiple conditions | <p>I'm a longtime SAS user trying to get into Pandas. I'd like to set a column's value based on a variety of if conditions. I think I can do it using nested np.where commands but thought I'd check if there's a more elegant solution. For instance, if I set a left bound and right bound, and want to return a column of str... | <p><strong>Option 1</strong></p>
<p>You can use nested <code>np.where</code> statements. For example:</p>
<pre><code>df['area'] = np.where(df['x'] > df['rbound'], 'right',
np.where(df['x'] < df['lbound'],
'left', 'somewhere else'))
</code></pre>
<p><strong>... | python|pandas|dataframe|nested | 5 |
19,731 | 49,307,346 | Accessing a cell value in Pandas DataFrame - nsepy | <p>Can someone please help me to understand the structure of the data frame I am receiving from a function call and also share how can I access a particular cell value in that data frame? </p>
<p>Following is the output when I print <code>resultData.shape</code></p>
<pre><code>(0, 14)
(22, 14)
</code></pre>
<p>Foll... | <p>The dataframe indicated has index of data type datatime.date and columns as represented [Symbol, Series, Prev Close, Open, High, Low, Last, Close, VWAP, Volume, Turnover, Trades, Deliverable Volume, %Deliverble]</p>
<p>to Access the "Open" value for the date 2018-01-01,
use the below statement </p>
<p>Format:
data... | python|pandas|dataframe|quandl|nsepy | 0 |
19,732 | 58,667,304 | Apply if statement function to 3D array numpy | <p>i have a 92x92x1 array in numpy, and for every value in this array, if the value is greater than 122, than it should be converted to 255, otherwise it should be converted to 0. Previously i have tried;</p>
<pre class="lang-py prettyprint-override"><code>new_array=[]
for i in arr:
column=[]
for j in i:
... | <p>NumPy supports vectorized operations so you do not need a for-loop. You can use boolean indexing and it will apply to all dimensions. </p>
<pre><code>import numpy as np
arr = np.random.randint(0, 255, (92, 92, 1))
arr[arr >= 122] = 255
arr[arr < 122] = 0
</code></pre> | python|arrays|numpy|mapping | 3 |
19,733 | 58,912,568 | Replacing value in list gives error message: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() | <p>I would like to replace every '-1' in my list (containing 370 lines with different numbers of rows) to the value '0'.</p>
<p>My list looks like that:
<a href="https://i.stack.imgur.com/FUmNi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FUmNi.png" alt="list example"></a></p>
<p>I tried that c... | <p>The problem is that each <em>item</em> is a list on its own, and not just a value, so python is saying it can't determine that the list is or is not a value.
Anyway, it's better to use list comprehension:</p>
<pre><code>expression_list = [[x if x != -1 else 0 for x in item] for item in expression_list]
</code></pre... | python|pandas|list | 1 |
19,734 | 70,251,298 | read a specific cells from multiple excel spreadsheets into single pandas dataframe | <p>I would like to read specific cells from multiple excel spreadsheets into single pandas dataframe.</p>
<p>so far, I have tried this. (without a success)</p>
<pre><code>import pandas as pd
import glob
import xlrd
file_list = glob.glob("*.xls")
df = pd.DataFrame()
for f in file_list:
wb = xlrd.open_wo... | <p>I think you need two sets of <code>[[]]</code> around what is being appended. With one set of brackets, it tries to add name as a row and city as a row, rather than as columns in the same row.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import glob
import xlrd
file_list = glob.glob("... | python|excel|pandas|openpyxl | 0 |
19,735 | 70,184,524 | Create multiple rows from several column indexes | <p>Please can you help me? This is the structure of my origin dataset:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Country</th>
<th style="text-align: center;">2020</th>
<th style="text-align: right;">2021</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:... | <p>Your question is similar to this <a href="https://stackoverflow.com/questions/28654047/convert-columns-into-rows-with-pandas">question</a>. You can use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer">melt</a> method of pandas</p>
<pre><code>df.melt(id_vars=['Coun... | pandas|dataframe|python-2.7 | 1 |
19,736 | 56,293,405 | interpreter->typed_input_tensor issues with uchar variables | <p>I have issue with fill input of tensorflow-lite model.</p>
<p>First stage of my model takes uchar variables but:</p>
<pre class="lang-cpp prettyprint-override"><code>//seg falut
interpreter_stage1->typed_input_tensor<uchar>(0)[i] = 0;
//works good
interpreter_stage1->typed_input_tensor<floa... | <p>Here is the answer if someone will face a similiar issue. </p>
<p>When I printed interpretetState</p>
<pre class="lang-cpp prettyprint-override"><code>tflite::PrintInterpreterState(interpreter.get());
</code></pre>
<p>I saw that model which was previously moved from Keras to TFLite has different input type than e... | c++|embedded-linux|tensorflow-lite | 1 |
19,737 | 56,324,419 | Updating list inside for loop, which is using this list | <p>I am working on a dataframe with some values inside. The problem is, I might have duplicates.</p>
<p>I went on this <a href="https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop">link</a> but i couldn't find what I needed</p>
<p>What I tried is to create a list of duplicates using... | <p>If you need indexes of non-duplicated IDs:</p>
<pre><code>df = pd.DataFrame({'ID':[0,1,1,3], 'B':[0,1,2,3]})
B ID
0 0 0
1 1 1
2 2 1
3 3 3
# List of indexes
non_duplicated = df.drop_duplicates(subset='ID', keep=False).index
df.loc[df.index.isin(non_duplicated)]
B ID
0 0 0
3 3 3
</code>... | python|pandas|dataframe | 0 |
19,738 | 56,224,155 | Sorting data by day and month (ignoring year) python pandas | <p>I found many questions similar to mine, but none of them answer it exactly (<a href="https://stackoverflow.com/questions/11326305/array-sort-by-date-and-month-only-ignore-year">this one</a> comes closest, but it focusses on ruby).</p>
<p>I have a pandas DataFrame like this:</p>
<pre><code>import pandas as pd
impor... | <p>On way from <code>argsort</code></p>
<pre><code>yourdf=df.loc[df.Date.dt.strftime('%m%d').astype(int).argsort()]
</code></pre> | python|pandas|sorting|datetime | 2 |
19,739 | 56,021,164 | Two columns unique strings | <p>I want to find the unique combination of both <code>person1</code> and <code>person2</code> columns despite the reverse values in my dataframe. Below you can find the initial Dataframe example, where I want to find the unique persons: </p>
<pre><code>df = pd.DataFrame({"person1":["AL","IN","AN","DL","IN","AL","AL",... | <p>If possible sorting both columns:</p>
<pre><code>df1 = pd.DataFrame(np.sort(df[['person1','person2']].fillna('')),
index=df.index,
columns=['person1','person2'])
df['person'] = np.where(df1.person1 != df1.person2,
df1.person1.str.cat(df1.person2, sep="... | python|pandas|dataframe|pandas-groupby | 0 |
19,740 | 55,847,734 | Join tables in pandas read_sql_query() - multi index problem | <p>I would like to create a pandas DataFrame using <code>pandas.read_sql_query()</code> by joining two tables. This is my code:</p>
<pre><code>import pandas as pd
connection = ...
query = 'SELECT T0.*, T1.* FROM %s T0 LEFT JOIN %s T1 ON T0.NUMPERSO = T1.NUMPERSO' % (TABLE, TABLE_VARS)
raw_train_data = pd.read_sql_quer... | <p>I can't comment on what the sql query is doing, but you could just fix up your index in pandas. Try the following: </p>
<pre><code>idx = pd.DataFrame(raw_train_data.index.values.tolist(), columns=["rtd_idx", "nan"]).set_index(
"rtd_idx"
).index
</code></pre>
<p>I'm hoping this will give you a new index and the... | oracle|pandas|dataframe|join|indexing | 0 |
19,741 | 55,672,808 | Convert composite values into columns in pandas dataframe | <p>Suppose I have a pandas dataframe as follow:</p>
<pre><code>Category col1 col2 value
A a a 1
A a b 2
A b a 3
A b b 4
B a a 5
B a b 6
B b a ... | <p>Join columns together with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a>:</p>
<pre><code>df['new'] = df['col1'] + df['col2']
df1 = df.pivot('Category','new','value')
print (df1)
new aa ab ba bb
Category ... | python|pandas|dataframe | 1 |
19,742 | 55,874,365 | Print input while training model on every iteration | <p>I want to check what data is in input, or to check output of some layer. For this i do the following:</p>
<pre><code>import tensorflow.keras.backend as K
import tensorflow as tf
import numpy as np
x = [[i, i * 3 + 1] for i in range(100)]
y = [2 * i + 1 for i in range(100)]
x = np.array(x)
y = np.array(y)
print_we... | <p>One option is to use a [custom callback][1]</p>
<p>like so:</p>
<pre class="lang-py prettyprint-override"><code>class MyCallback(tf.keras.callbacks.Callback):
def __init__(self, patience=0):
super(MyCallback, self).__init__()
def on_epoch_begin(self, epoch, logs=None):
tf.print(self.model... | python-3.x|tensorflow|keras|placeholder | 3 |
19,743 | 64,659,729 | Iterate two data frame whitout same lenght | <p>I would like to iterate on two dataframes that do not have the same size in order to output the list of users, with their information, who are leaving the company and who are still active.</p>
<pre class="lang-py prettyprint-override"><code>df1=pd.DataFrame({'Name':['PAUL','LAURE','DAVID','MAT'],
'MATRICULE':['AP','... | <p>There is a better option than iterating over DataFrame, you can filter your first DataFrame according to the second DataFrame values and select the desired columns.</p>
<p>See the following code:</p>
<pre><code>df1[(df1.Name.isin(df2.Name)) & (df1.ACTIF=='YES')][['Name', 'MATRICULE']]
</code></pre> | python|pandas | 0 |
19,744 | 64,622,833 | Interpreting attention in Keras Transformer official example | <p>I have implemented a model as explained in (Text classification with Transformer) <a href="https://keras.io/examples/nlp/text_classification_with_transformer/" rel="nofollow noreferrer">https://keras.io/examples/nlp/text_classification_with_transformer/</a></p>
<p>I would like to access the attention values for a sp... | <p><strong>EDIT: In case you want to interpret the classification output using attention</strong></p>
<p>From what I know, it is impossible to fully interpret what Transformer does in classification. What Transformer does is just to see how each input is related to each other, not how each word contributes to the label... | tensorflow|keras|nlp|attention-model | 1 |
19,745 | 64,936,023 | Pandas forward fill entire rows according to missing integers in specific column | <p>I can't seem to figure out a clean way to forward fill entire rows based on missing integers in a specific column. For example I have the dataframe:</p>
<p><code>df = pd.DataFrame({'frame':[0,3,5], 'value': [1,2,3]})</code></p>
<pre><code> frame value
0 0 1
1 3 2
2 5 3
</code></pre>
... | <p>You can set <code>frame</code> as index and <code>reindex</code> with <code>ffill</code>:</p>
<pre><code>frame_range = np.arange(df['frame'].min(), df['frame'].max()+1)
df.set_index('frame').reindex(frame_range).ffill().reset_index()
</code></pre>
<p>Or you can also use <code>merge</code> then <code>ffill</code></p>... | python|pandas | 3 |
19,746 | 64,749,643 | Pandas how to rename existing index and merge it with another one | <p>I have a df like this</p>
<p><img src="https://i.stack.imgur.com/KiB5f.png" alt="example" /></p>
<p>and I want to have an output like this :</p>
<p><img src="https://i.stack.imgur.com/hxBEe.png" alt="output" /></p>
<p>There are 53k Rows , and there are many Rows like that , How can I filter them and re-organize them... | <p>try:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
'Parrot', 'Parrot'],
'Max Speed': [380., 370., 24., 26.]})
df.index = df.Animal #updating the index for illustration purposes
df.groupby(df.index).agg(sum)
</code></pre>
<p>t... | python|pandas | 1 |
19,747 | 39,894,312 | TensorFlow: how to implement a per-class loss function for binary classification | <p>I have two classes: positive (1) and negative (0).</p>
<p>The data set is very unbalanced, so at the moment my mini-batches contain mostly 0s. In fact, many batches will contain 0s only. I wanted to experiment with having a separate cost for the positive and negative examples; see code below. </p>
<p>The problem w... | <p>Since you have 0 and 1 labels, you can easily avoid <code>tf.where</code> with a construction like this</p>
<pre><code>labels = ...
entropies = ...
labels_complement = tf.constant(1.0, dtype=tf.float32) - labels
entropy_ones = tf.reduce_sum(tf.mul(labels, entropies))
entropy_zeros = tf.reduce_sum(tf.mul(labels_comp... | machine-learning|neural-network|tensorflow | 1 |
19,748 | 40,038,557 | I have a numpy array, and an array of indexs, how can I access to these positions at the same time | <p>for example, I have the numpy arrays like this</p>
<pre><code>a =
array([[1, 2, 3],
[4, 3, 2]])
</code></pre>
<p>and index like this to select the max values</p>
<pre><code>max_idx =
array([[0, 2],
[1, 0]])
</code></pre>
<p>how can I access there positions at the same time, to modify them.
like "a... | <p>Simply use <code>subscripted-indexing</code> -</p>
<pre><code>a[max_idx[:,0],max_idx[:,1]] = 0
</code></pre>
<p>If you are working with higher dimensional arrays and don't want to type out slices of <code>max_idx</code> for each axis, you can use <code>linear-indexing</code> to assign <code>zeros</code>, like so -... | python|arrays|numpy | 1 |
19,749 | 44,147,827 | Can I reinforce good patterns recognition in LSTM? | <p>People talking of LSTMs predicting next time step. Which means it should recognise a pattern to make a prediction. Let say it often saw 1 2 3 sequences during learning phase. So when it sees 1 2 it will predict 3. Right?</p>
<p>But what if I don't want to predict the number? What if I need an LSTM to recognise a pa... | <p>Take a look at <a href="https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py" rel="nofollow noreferrer">https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py</a> for an example of using LSTM for a classification task. The most basic architecture is just a single LSTM layer followed by a... | machine-learning|tensorflow|keras|lstm | 2 |
19,750 | 44,070,621 | Pandas pivot_table re-arrage columns in proper hierarchy | <p>After doing some logn magic with pivot tables (changing levels of columns, dropping some levels, merging several pivot_tables) I ended up with this presentation of column levels in the final df:</p>
<pre><code>P1 P2 P1 P2 - level 0
F1 F1 F2 F2 - level 1
</code></pre>
<p>I am lost as to why it is represented ... | <p>It seems you need sort it by first level with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer"><code>sort_index</code></a>:</p>
<pre><code>df = df.sort_index(axis=1, level=0)
</code></pre>
<p>Sample:</p>
<pre><code>np.random.seed(123)
cols ... | pandas | 1 |
19,751 | 43,989,310 | Can I slice tensors with logical indexing or lists of indices? | <p>I'm trying to slice a PyTorch tensor using a logical index on the columns. I want the columns that correspond to a 1 value in the index vector. Both slicing and logical indexing are possible, but are they possible together? If so, how? My attempt keeps throwing the unhelpful error</p>
<blockquote>
<p>TypeError: inde... | <p>I think this is implemented as the <a href="http://pytorch.org/docs/tensors.html#torch.Tensor.index_select" rel="noreferrer"><code>index_select</code></a> function, you can try</p>
<pre><code>import torch
A_idx = torch.LongTensor([0, 2]) # the index vector
B = torch.LongTensor([[1, 2, 3], [4, 5, 6]])
C = B.index_se... | python|matrix-indexing|pytorch | 23 |
19,752 | 69,561,643 | Turn multi-indexed series with different lengths and non-unique indexes into Dataframe | <pre><code>0 6 1689.306931
6 345.198020
6 226.217822
6 34.574257
6 14.000000
...
3 6 1.077353
6 1.116176
6 1.078431
6 1.049020
6 0.980294
</code></pre>
<p>Here's my multi-indexed series <em>my_df</em>, where I can access each s... | <p>Try enumerate the rows within one level with <code>groupby.cumcount</code>, then unstack:</p>
<pre><code># your first level seem to be identical, just drop it
(df.reset_index(level=1)
.set_index(df.groupby(level=0).cumcount(), append=True)
.unstack()
)
</code></pre> | pandas|dataframe|concatenation|series | 1 |
19,753 | 69,522,114 | Get first and Last date of each unique element in pandas dataframe | <p>I have a dataframe like this :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">A-Party</th>
<th style="text-align: center;">Date & Time</th>
<th style="text-align: right;">IMEI</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">3022275</td>
<td s... | <p>I just form each column manually and then create the DataFrame.</p>
<pre><code>A_Party = [df.iloc[0,0],'']
Total_IMEI = [df['IMEI'].nunique(),'']
IMEI = df['IMEI'].unique()
First_Date = df.groupby('IMEI')['Date & Time'].first()
Last_Date = df.groupby('IMEI')['Date & Time'].last()
col = ['A-Party','Total IMEI... | python|pandas|dataframe | 2 |
19,754 | 40,915,492 | pandas: groupby only if condition is satisfied | <p>I have the following multi-indexed DataFrame:</p>
<pre><code> m dist
a a 2 5
b 3 8
c 4 12
d 2 3
b a 2 5
b 3 8
c 4 14
d 2 27
</code></pre>
<p>I want to calculate a new column s based on an algorithm. For example, for (a,a) the a... | <p>You can sort the data frame by <code>dist</code> and then do a <code>cumsum</code> on the column <code>m</code>:</p>
<pre><code>df['s'] = df.sort_values('dist').groupby(level=0).m.cumsum()
</code></pre>
<p><a href="https://i.stack.imgur.com/Oieum.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O... | python|pandas | 3 |
19,755 | 53,936,777 | scipy.optimize.minimize cannot use 2D or scalar bounds | <p><strong>Problem</strong></p>
<p>I guess <code>scipy.optimize.minimize</code> cannot use 2D bounds.</p>
<p>I can work around the problem by:</p>
<ol>
<li>reshape input to <code>minimize</code> to 1D arrays</li>
<li>reshape the arrays back to 2D within the objective function.</li>
</ol>
<p>But that is tedious.</p>... | <p>From the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html" rel="nofollow noreferrer">docs</a></p>
<blockquote>
<p>x0 : ndarray, <strong>shape (n,)</strong></p>
<p>Initial guess. Array of real elements of size (n,), where ‘n’ is the number of independent variables.</p>
</bloc... | python|numpy|optimization|scipy | 1 |
19,756 | 53,862,023 | SVD with numpy - intepretation of results | <p>I'm trying to get into Singular Value Decomposition (SVD). I've found this <a href="https://www.youtube.com/watch?v=P5mlg91as1c" rel="nofollow noreferrer">YouTube Lecture</a> that contains an example. However, when I try this example in numpy I'm getting "kind of" different results. In this example the input matrix... | <p>As mentioned on <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.linalg.svd.html" rel="nofollow noreferrer">this</a> page, numpy internally uses LAPACK routine <code>_gesdd</code> to get the SVD decomposition. Now, if you see <code>_gesdd</code> <a href="https://software.intel.com/en-us/mk... | python|numpy|linear-algebra|svd | 3 |
19,757 | 66,045,836 | Interactive Choropleth Map Using Python | <p>I found a code for creating the worldmap that uses the shapefile from <a href="https://www.naturalearthdata.com/downloads/110m-cultural-vectors/" rel="nofollow noreferrer">https://www.naturalearthdata.com/downloads/110m-cultural-vectors/</a>
Download Countries v4.1.0</p>
<pre><code>shapefile = 'data/countries_110m/n... | <p>It seems like you renamed the columns:</p>
<p><code>gdf.columns = ['country', 'country_code', 'geometry']</code></p>
<p>where <code>admin</code> is now <code>country</code> and <code>ADM0_A3</code> is now <code>country_code</code></p> | python|shapefile|geopandas|country|world-map | 0 |
19,758 | 66,146,557 | Why do equality and inequality comparison against a completely nan categorical series always return False? | <p>I have discovered this to be the root of a confusing issue for me. Pandas 1.05</p>
<pre><code>>>> left = pd.Series(pd.Categorical([numpy.nan, numpy.nan, numpy.nan, numpy.nan], categories=["1"], ordered=False))
>>> right = pd.Series(pd.Categorical(["1", "1", "1&quo... | <p>This is one of the basic properties of <code>NaN</code>, as defined in the ISO standard.</p>
<p>A <code>NaN</code> value fails (<code>returns False</code>) <em>any</em> comparison operation.</p>
<pre><code>numpy.nan == numpy.nan
</code></pre>
<p>is <code>False</code>. Again, this is <em>required</em> by the standar... | python|pandas | 2 |
19,759 | 66,082,677 | How to modifiy a specific caracter from DataFrame date in Python | <p>here is a script :</p>
<pre><code>date = ['1871-01', '1871-02', '1871-1', '1871-11', '1871-12']
div = np.zeros(len(date))
tab = pd.DataFrame({'date':date, 'zeros':div})
tab
</code></pre>
<p>I would like to change directly in the table and not from the list date the value of '1871-1' in '1871-11'.
Maybe you can help... | <p>Use mask</p>
<pre><code>tab['date']=tab['date'].mask(tab['date'].eq('1871-1'),'1871-11')
date zeros
0 1871-01 0.0
1 1871-02 0.0
2 1871-11 0.0
3 1871-11 0.0
4 1871-12 0.0
</code></pre>
<p>alternatively, use np.where</p>
<pre><code>tab['date']=np.where(tab['date'].eq('1871-1'),'1871-11',tab[... | python-3.x|pandas|dataframe|datetime | 1 |
19,760 | 66,078,489 | Webcam Frame to model.predict_generator - Jupyter Notebook & CV2 | <p>I have created this custom CNN, trained it, and now wish to try and pass frames from my webcam in real-time for testing the predictions.</p>
<p>The webcam video playback starts to capture the frame by frame, however, I am unsure what to do to the frame in order to get it working with the CNN model</p>
<p>Any advice ... | <p>Keras model has a method called "predict". It takes a single np.array or a list of np.arrays as input (which should have the exact same shape as your neural net. input, including the batch part: (batch_count, width, height, channels) for example). You input this to model.predict, then it returns you back t... | tensorflow|keras|conv-neural-network|jupyter|cv2 | 0 |
19,761 | 66,144,359 | Pytorch model runtime error when testing U-Net | <p>I've defined a U-Net model using Pytorch but it won't accept my input. I've checked the model layers and they seem to be applying the operations as I would expect them to but I still get an error.</p>
<p>I've just switched to Pytorch after mostly using Keras so I'm not really sure how to debug this issue, the error ... | <p>Your problem is in the model layer definition.</p>
<p>You defined <code>self.upconv2 = self.expand_block(64, 32, 3, 1)</code> but what you do is concatenating 2 tensors each with <strong>64</strong> channels so in total you get <strong>128</strong>.</p>
<p>You should fix the channels of the up-sampling part of the U... | python|deep-learning|pytorch|conv-neural-network | 1 |
19,762 | 52,864,770 | Numpy add (append) value to each row of 2-d array | <p>I have numpy array of floats with shape (x,14) and I would like to add to the end of each "row" one more value (to each row different value), so that end result has shape (x,15).</p>
<p>We can suppose that I have those values in some list, so that part of the question is also defined.</p>
<p>How to do it with nump... | <p>Define a 2d array and a list:</p>
<pre><code>In [73]: arr = np.arange(12).reshape(4,3)
In [74]: arr
Out[74]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [75]: alist = [10,11,12,13]
</code></pre>
<p>Note their shapes:</p>
<pre><code>In [76]: arr.shape
Out[76]: (4, 3)
In... | python|numpy | 5 |
19,763 | 46,194,989 | [[[1., 2., 3.]], [[7., 8., 9.]]] # a rank 3 tensor with shape [2, 1, 3] | <p>Can someone explain to me why does this example have a shape of [2,1,3], i just don't see it?</p>
<p>[[[1., 2., 3.]], [[7., 8., 9.]]] # a rank 3 tensor with shape [2, 1, 3]</p> | <p>Indentation does wonders:</p>
<pre><code>[ # this one contains 2 items
[ # each of this contains 1 item
[1., 2., 3.] # each of this contains 3 items
],
[
[7., 8., 9.]
]
]
</code></pre>
<p>Thus, shape is <code>[2,1,3]</code></p> | tensorflow | 5 |
19,764 | 58,310,948 | Will TensorFlow2.0 trim unncessary computations? | <p>Will TensorFlow 2.0 be able to trim unnecessary computations?</p>
<p>For example, </p>
<pre><code>a = tf.constant(1.0)
for i in range(10):
c = a + 1
a = a + 1
print(a)
</code></pre>
<p>In TF1.x, <code>c=a+1</code> won't be computed. Will TF2.0 automatically detect <code>c=a+1</code> is not used so it doesn't ... | <p>It won't be computed. The preprocessor will detect it is never used and the program won't take into account. You can (not recommended) suppress warnings about unused stuff, instead, you should take care of the unused things.</p> | tensorflow | 0 |
19,765 | 58,451,101 | performance issues applying double lambda functions | <p>I have two dataframes: df1, df2 which contain each a column with names. I compare every name in df1 with every name in df2.
This has to be an approximate match. Iam using fuzzywuzzy token_sort_ratio to get a comparison score. </p>
<p>However this method is very slow and df2 keeps growing, it already takes more the... | <p>You can try this,</p>
<pre class="lang-py prettyprint-override"><code>from fuzzywuzzy import fuzz
def similarity(name1, name2):
return fuzz.token_sort_ratio(name1, name2)
df1['key'] = 1
df2['key'] = 1
merged = df1.merge(df2, on='key')
merged['name_score'] = merged[['name_x', 'name_y']] \
.apply(lambda ro... | python|pandas|performance|loops|lambda | 1 |
19,766 | 68,935,374 | Write string conditional assigning into new column as one linear or in a more concise manner | <p>I am wondering if there's a way to write the string conditional assigning method in a more concise way.</p>
<pre><code>import pandas as pd
import numpy as np
from sklearn import datasets
wine = pd.DataFrame(datasets.load_wine().data)
wine.columns = datasets.load_wine().feature_names
conditions = [(wine.hue > 1),... | <p>you can use list comprehension !</p>
<pre><code>win_hue = [1, 2, -5, 0, -9, 4, 10, 1, -9, 8]
wine_status = [((wh < 1)*'A' + (wh == 1)*'B' + (wh > 1)*'C') for wh in win_hue]
In [1]: wine_status
Out[1]: ['B', 'C', 'A', 'A', 'A', 'C', 'C', 'B', 'A', 'C']
</code></pre> | python|pandas | 0 |
19,767 | 69,029,115 | fill Nas with other column in pandas | <p>I have some NAs and would like to fill them with values in another column in the same row.</p>
<pre><code>df = pd.DataFrame({"column A": ["Atlanta", "Atlanta", "New York", "",""],
"column B": ["AT", "AT", &q... | <p>You can Simply Use the <code>fillna</code> with the Column Name like this:</p>
<pre><code>df['column A'].fillna(df['column B'])
</code></pre> | python|pandas|fillna | 0 |
19,768 | 68,926,007 | Make Number of Rows Based on Column Values - Pandas/Python | <p>I want to expand my data frame based on numeric values in two columns (<code>index_start</code> and <code>index_end</code>). My df looks like this:</p>
<pre><code>item index_start index_end
A 1 3
B 4 7
</code></pre>
<p>I want this to expand to create rows for A from 1 to... | <p>You could use <code>.explode()</code></p>
<pre><code>df['index'] = df.apply(lambda row: list(range(row['index_start'], row['index_end']+1)), axis=1)
df.explode('index')
item index_start index_end index
0 A 1 3 1
0 A 1 3 2
0 A 1 3 3... | python|pandas|dataframe | 5 |
19,769 | 69,102,974 | Returning plots in repeated function calls without plotting in notebook | <p>I have a function that returns plots <strong>without saving images</strong>. It uses the <code>pd.DataFrame.plot</code> method to plot the images and return them. I need to call this function repeatedly in a large number of iterations.</p>
<p>The problem is that I can't modify the function at all, therefore I need t... | <ul>
<li>In Jupyter, turn <code>inline</code> plotting off in <code>Jupyter</code> by using <code>%matplotlib qt</code> in a cell prior to plotting. This is a notebook wide setting, so only needs to happen once.
<ul>
<li>Turn <code>inline</code> plotting back on with <code>%matplotlib inline</code>, or going to <kbd>Ke... | python|pandas|matplotlib|jupyter-notebook | 1 |
19,770 | 68,887,216 | In Python, how to loop through a list, append to pandas df, do an api lookup based on the list, and more | <p>First off, thank you for taking the time to review my question. I have looked up how to do this but have not found a solution.</p>
<p>I have a list of values (here I am using string which are the names of shapes as a simple example). I would like to loop through this list and use the names of the Shapes to lookup th... | <p>You can do this,</p>
<pre><code>import pandas as pd
#create/initialize the dataframe
Shapes = pd.DataFrame({
'Shape': [],
'Length': [],
'Width': [],
'Ratio_Length2Width':[]
})
#Here is the shape list
Shape = ["Rectangle", "Square", "Circle"]
length = 10
width = 5
for ... | python|pandas|dataframe|loops | 0 |
19,771 | 69,160,267 | Cut one part of an autoencoder (pytorch) | <p>I have a simple autoencoder architecture in PyTorch, which I train to do feature compression and reconstruction. My goal is to use the latent space of the autoencoder to reduce the initial dimensionality of my data and compress it in the test phase.
To perform this, I would need to pass my test data only to my encod... | <p>Base on your model definition, you can call forward on the encoder submodule directly:</p>
<pre><code>class Autoencoder(nn.Module):
def __init__(self, n_features):
super(Autoencoder, self).__init__()
self.n_features = n_features
self.encoder = nn.Sequential(
nn.Linear(self... | python|pytorch|autoencoder | 0 |
19,772 | 44,430,985 | How to select most repeated field in a column in pandas? | <p>I am a beginner in coding and would highly appreciate your help. I have a file of 4gb and i am trying to select the the most repeated field in column B (that is not similar to column A) and the corresponding column C </p>
<p>For example,</p>
<pre><code> Column A Column B Column C id
Sam Sa... | <p>You're going to have trouble with a 4Gb dataframe using <code>pandas</code>. I recommend you have a look at <code>dask</code> instead which replicates parts of the <code>pandas</code> api but does out of core computation, i.e. does not load everything into memory at once. It should be a drop in replacement for most ... | pandas | 1 |
19,773 | 60,771,843 | How Can I create a Method in a class that I can convert a numpy matrix to a Pandas Frame? | <p>I am trying to define a method where I can convert from a numpy matrix to Pandas DataFrame. </p>
<p>I have the following:</p>
<pre><code>import pandas as pd
import numpy as np
class Analisis():
def __init__(self, matriz = np.array([])):
self.__matriz = matriz
self.__filas = matriz.shape[0]... | <p>Since you are defining a <em>method</em> you would want to call it on your object:</p>
<pre><code>data.as_data_frame()
</code></pre>
<p>But your definition uses <code>data</code>, presumably the global variable. But you should be using the <em>internal state</em>. So, presumably, you want <code>self.__matriz</code... | python|python-3.x|pandas|numpy|methods | 3 |
19,774 | 61,178,033 | how to convert (1084, 1625, 3) to (none,none,none ,3) | <p>Here I have one tensor with (1084, 1625, 3) shape.</p>
<p>And I need to reshape it to (none,none,none ,3).</p>
<p>how can i do that?</p>
<p>I used this code but it does not work.</p>
<pre><code>image = tf.cast(img, tf.float32)
image = (image / 127.5) - 1
</code></pre> | <p>I don't think you can do that. I think what you're trying to do is turn a 3D tensor into a 4D tensor. I'm guessing this is the origin of your problem. You can do this to add a 4th dimension, because Tensorflow needs it:</p>
<pre><code>import tensorflow as tf
tensor = tf.random.uniform((100, 100, 3), 0, 256, dtype=... | python|tensorflow | 1 |
19,775 | 61,082,323 | Pandas share of value with condition and adding new column | <p>I'm new to pandas and got stuck a bit. Can you help me?</p>
<p>I have a dataframe storing orders:</p>
<pre><code>| item | store_status | customer_status |
|------|--------------|-----------------|
| A | 'dispatched' | 'received' |
| A | 'dispatched' | 'pending' |
| B | 'pending' | 'pending' ... | <p>Create Boolean Series that check the conditions, then take the mean of those Series within each group. </p>
<pre><code>(df.assign(dispatched=df.store_status.eq('dispatched'),
dispatched_and_received=(df.store_status.eq('dispatched')
& df.customer_status.eq('receive... | pandas|dataframe|pandas-groupby | 2 |
19,776 | 60,795,345 | calculating a range based on the fields of a pandas dataframe | <p>I have a pandas dataframe</p>
<pre><code>import pandas as pd
import numpy as np
d = pd.DataFrame({
'col': ['A', 'B', 'C', 'D'],
'start': [1, 4, 6, 8],
'end': [4, 9, 10, 12]
})
</code></pre>
<p>I'm trying to calculate a range field based on start and end fields such that the values for i... | <p>Try this:</p>
<pre><code>d.apply(lambda x: np.arange(x['start'], x['end']+1), axis=1)
</code></pre>
<p>Output:</p>
<pre><code>0 [1, 2, 3, 4]
1 [4, 5, 6, 7, 8, 9]
2 [6, 7, 8, 9, 10]
3 [8, 9, 10, 11, 12]
dtype: object
</code></pre>
<p><strong><em>Note:</em></strong> <code>np.arange</code> and <... | python|pandas|numpy | 2 |
19,777 | 71,467,570 | Getting 'bool object not callable' error when inserting data into sql server using pandas dataframe and pyodbc's fast_executemany() | <p>I've lots of records to be inserted into sql server. I'm using pyodbc and <code>cursor.fast_executemany()</code> to achieve this. The regular <code>cursor.execute()</code> is inserting records too slowly.</p>
<p>I'm following this article as a reference: <a href="https://towardsdatascience.com/how-i-made-inserts-int... | <p>The second line in the following snippet has to be wrong. You set <code>fast_executemany</code> to <code>True</code> and then try to call it with <code>fast_executemany()</code>.</p>
<pre><code>cursor.fast_executemany = True
cursor.fast_executemany(my_insert_statement,df.values.tolist())
</code></pre>
<p>I looked at... | python-3.x|pandas|pyodbc | 0 |
19,778 | 71,516,371 | Partially freeze a layer in Tensorflow | <p>I was looking for a way to partially freeze a layer in a Keras model. If I were to freeze a layer, I would just set the <code>trainable</code> property to <code>False</code> like this:</p>
<pre><code>model.get_layer('myLayer').trainable = False
</code></pre>
<p>But, let's take for example a Dense layer with <code>n<... | <p>Use the <code>model.layers[ ]</code> to get the layers from the trained model to make them non-trainable.
For example,</p>
<pre><code>model=tf.keras.Sequential([
tf.keras.Input(shape=(28,28,1)),
tf.keras.layers.Conv2D(32,kernel_size=(3,3),activation='relu'),
t... | tensorflow|keras | 1 |
19,779 | 42,309,075 | Using broadcast in ND4J | <p>I recently switched from numpy to ND4J but had a hard time understanding how broadcasting in ND4J works. </p>
<p>Say I have two ndarray, a of shape [3,2,4,5] and b of shape [2,4,5]. I would like to element-wise add them up and broadcast b to each <code>a[i] for i = 0 to 2</code>. In numpy it can simply be done via ... | <p>The only method I have found so far is as following</p>
<pre><code>var a = Nd4j.createUninitialized(Array(3,2,4,4))
var b = Nd4j.createUninitialized(Array(2,4,4))
b = b.reshape(1,32)
b = b.broadcast(3,32)
b = b.reshape(3, 2, 4, 4)
a.add(b)
</code></pre>
<p>Please kindly let me know if there is a better way to do t... | numpy|multidimensional-array|nd4j | 1 |
19,780 | 42,468,070 | Use subfolders in training set to retrain Inception's Final Layer | <p>In the example doc to <a href="https://www.tensorflow.org/tutorials/image_retraining#training_on_your_own_categories" rel="nofollow noreferrer">retrain Inception's Final Layer</a> the training image data is stored in folders. Each folder defines the category for the containing images through its name.</p>
<p>In the... | <p>No, unfortunately you can't create sub-classes like that. Instead, you can try naming your classes like this:</p>
<pre><code>roses_alba -> rose-alba-1.jpg
roses_damascena -> rose-damascena-1.jpg
roses_damascena -> rose-damascena-2.jpg
</code></pre>
<p>I'd need to know more about what your requirements are... | tensorflow|neural-network | 2 |
19,781 | 69,811,709 | How to divide two dataframes elementwise | <p>I have two dataframes, they share the same columns and one has more indexes than the other, what I want is to divide each element of one dataframe by the corresponding element (having the same index and column) in another dataframe, an example:</p>
<p>df1</p>
<pre><code> value1 value2 ... | <p>If no missing values in original DataFrame remove only <code>NaN</code>s rows after division:</p>
<pre><code>df = df1.div(df2).dropna(how='all')
print (df)
value1 value2
0 0.5 1.5
1 1.0 2.0
</code></pre>
<p>Or first filter common indices in <a href="http://pandas.pydata.org/pandas-docs/stable/ref... | python|pandas|dataframe | 0 |
19,782 | 69,946,243 | Can keras_tuner (Keras Tuner) be used for non model hyper parameters? | <p>After looking at doc and tutorial, it seems to me it is very easy to define a hyper parameter for your model. This includes the code to construct it out of layers, as well as compile related ones such as learning rate. What I am looking for (also) is a way to run hyper-param search on non model related parameters. H... | <p>This will help. <a href="https://keras.io/guides/keras_tuner/custom_tuner/" rel="nofollow noreferrer">https://keras.io/guides/keras_tuner/custom_tuner/</a> The custom tuner can be the way to “hyperparameterized” the tf dataset pipeline. Here's the code snippet I used and it works.</p>
<pre><code>class MyTuner(kt.Bay... | python|tensorflow2.0|keras-tuner | 0 |
19,783 | 69,776,026 | Missing data range Pandas dataframe comparison Python | <p>How would I be able to write a code that outputs the differences between <code>dates</code> and <code>data</code>. There are missing data points in the <code>data</code> code where there is a skip in the <code>dates</code> data frame of the 1 minute timeframe. For example after <code>2015-10-08 13:53:00</code> th... | <p><code>dates</code> and <code>data</code> here are both datetimeindexes. You can take the difference of these using <code>pd.Index.difference</code></p>
<pre class="lang-py prettyprint-override"><code>In [55]: s = pd.Series(dates.difference(data))
...: s # sort if needed
Out[55]:
0 2015-10-08 13:40:00
1 2015-... | python|pandas|numpy|datetime|time | 1 |
19,784 | 43,305,643 | How to convert nested dictionary to dataframe? | <p>I've got a nested dictionary. It's some Nasdaq kind of data. Like this:</p>
<pre><code>{'CLSN':
Date Open High Low Close Volume Adj Close
2015-12-31 1.92 1.99 1.87 1.92 79600 1.92
2016-01-04 1.93 1.99 1.87 1.93 39700 1.93... | <p><strong>UPDATE:</strong></p>
<p>assuming that <code>Date</code> is an index (not a regular column):</p>
<p>Source dictionary:</p>
<pre><code>In [70]: d2
Out[70]:
{'CCC': Open High Low Close Volume Adj Close
Date
2015-12-31 17.270000 17.389999 17.120001 17.250000 177200 ... | python|pandas|dictionary|dataframe | 3 |
19,785 | 72,328,244 | Is there a way to remove values from a pandas data frame with less than 4 decimal places and end up with an overwrite of the originally loaded data? | <p>I have a pandas data frame with 200 entries that has some values rounded to 4 decimal places and some values rounded to 2 decimal places. How can I clean the dataset by removing all rows which have values with decimal places less than 4 and end up with an overwrite of the originally loaded data?</p>
<p>For example: ... | <p>Other solution is using some math manipulation, checking for remainder</p>
<pre><code>df['new'] = df['old'] * 10000
df['check'] = 1
df.loc[(df['new'] % 10) == 0, 'check'] = 0
df = df.loc[df['check']==1, :].copy()
</code></pre> | python|pandas | 1 |
19,786 | 45,716,517 | Speed difference in np.einsum | <p>I noticed that <code>np.einsum</code> is faster when it reduces one dimension</p>
<pre><code>import numpy as np
a = np.random.random((100,100,100))
b = np.random.random((100,100,100))
%timeit np.einsum('ijk,ijk->ijk',a,b)
# 100 loops, best of 3: 3.83 ms per loop
%timeit np.einsum('ijk,ijk->ij',a,b)
# 1000 lo... | <p><code>einsum</code> is implemented in compiled code, <code>numpy/numpy/core/src/multiarray/einsum.c.src</code>.</p>
<p>The core operation is to iterate over all dimensions (e.g. in your case <code>100*100*100</code> times) using the <code>c</code> version of <code>nditer</code>, applying the <code>sum-of-products</... | python|numpy|numpy-einsum | 1 |
19,787 | 45,716,378 | Weighted cost function in tensorflow | <p>I'm trying to introduce weighting into the following cost function:</p>
<pre><code>_cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=_logits, labels=y))
</code></pre>
<p>But without having to do the softmax cross entropy myself. So I was thinking of breaking the cost calc up into cost1 a... | <p>The weight masks can be computed using <code>tf.where</code>. Here is the weighted cost example:</p>
<pre><code>batch_size = 100
y1Weight = 0.25
y0Weight = 0.75
_logits = tf.Variable(tf.random_normal(shape=(batch_size, 2), stddev=1.))
y = tf.random_uniform(shape=(batch_size,), maxval=2, dtype=tf.int32)
_cost = t... | tensorflow | 1 |
19,788 | 45,665,130 | Create mesh from cells and points in Paraview | <p>I have a CSV file with stress data and geometry that I have exported from ANSYS Mechanical that I would like to visualize in Paraview. Each node has a bunch of stress data related to it. I managed import the points as a point cloud in Paraview but I want to recreate the ANSYS mesh as well. I thought that "programabl... | <p>The following python script creates a polydata object from your csv-file and writes it to a file, that can be read in paraview:</p>
<pre><code>import vtk
f = open('Example-2.csv')
pd = vtk.vtkPolyData()
points = vtk.vtkPoints()
cells = vtk.vtkCellArray()
connectivity = vtk.vtkIntArray()
connectivity.SetName('Conn... | python|csv|numpy|vtk|paraview | 3 |
19,789 | 62,707,594 | Dividing Two Dataframe Columns after Groupby to order time | <p>I'm working with 20 years of data. The important columns right now are YEAR, MONTH, NUM1, and NUM2. How can I get the monthly percent of NUM1/NUM2?</p>
<pre><code>YEAR | MONTH | NUM1 | NUM2 |
------------------------------
2000 | 6 | 60 | 100 |
2000 | 6 | 55 | 100 |
2000 | 2 | 80 | 160 |
to
YE... | <p>You should add <code>transform</code></p>
<pre><code>g = df.groupby(['YEAR', 'MONTH'])
df['PCT']=g.NUM1.transform('sum')/g.NUM2.transform('sum')*100
df
YEAR MONTH NUM1 NUM2 PCT
0 2000 6 60 100 57.5
1 2000 6 55 100 57.5
2 2000 2 80 160 50.0
</code></pre> | python|pandas|dataframe|pandas-groupby | 1 |
19,790 | 62,506,382 | Add file name and line number to tensorflow op name during debug mode | <p>I am interested in a feature or hacky solution that allows every tensorflow (specifically tf1.x) op name to include the file name and line number where the op is defined, in an automated fashion across the entire code base. This will greatly facilitate tracking down the place where an op raises an error, such as the... | <p>The easiest way might be to show the graph on <a href="https://www.tensorflow.org/tensorboard/graphs" rel="nofollow noreferrer">tensorboard</a> and then search for failing op by name. Among the names of parent scopes or preceding operations you would probably be able to tell which layer is failing.</p>
<p>If not tha... | tensorflow | 1 |
19,791 | 62,552,439 | Elegant way to shift multiple date columns - Pandas | <p>I have a dataframe like as shown below</p>
<pre><code>df = pd.DataFrame({'person_id': [11,11,11,21,21],
'offset' :['-131 days','29 days','142 days','20 days','-200 days'],
'date_1': ['05/29/2017', '01/21/1997', '7/27/1989','01/01/2013','12/31/2016'],
'dis_date... | <p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add.html" rel="nofollow noreferrer"><code>DataFrame.add</code></a> along with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add_prefix.html" rel="nofollow noreferrer"><code>DataFrame.add_p... | python|pandas|numpy|dataframe|python-datetime | 2 |
19,792 | 54,395,101 | The following error occurred when running the tflite model: input->params.scale != output->params.scale in MAX_POOL_2D Node | <p>I trained the face recognition model with the quantization-aware training method of tensorflow version 1.12.0. The network uses inception-resnet_v1(The source of the code is tensorflow/models/research/slim/nets/). After the training is completed, I get ckpt, then I create a new freeze.py file to generate eval.pb, an... | <p>While converting the model, the function <strong>HardcodeMinMaxForConcatenation</strong> in <strong>hardcode_min_max.cc</strong> tweaks the minmax of input arrays and output array of concatenation layer to be the same.</p>
<p>Then the function <strong>HardcodeMinMaxForAverageOrMaxPool</strong> in the same file, wou... | tensorflow|tensorflow-lite|quantization | 0 |
19,793 | 73,703,267 | comparing two dataframes on the same date range python | <p>I have two dataframes and I want to compare df2 with df1 in order to show the "id_number missing" that are not in df1 but are in df2.</p>
<p>I have a script where I end up with more missing values than expected because I am not comparing the two dataframes on the same date range.</p>
<p>I want to compare t... | <p>Convert your <code>date</code> columns to a <code>datetime</code> object and then compare the <code>.min()</code> and <code>.max()</code> values of the columns in the dataframes:</p>
<pre><code>df1.loc[:,'date'], df2.loc[:,'date'] = (pd.to_datetime(col) for col in [df1.date, df2.date])
df1_cut = df1[df1.date.ge(df2.... | python|pandas|dataframe|date|merge | 1 |
19,794 | 73,633,189 | Grouping age in Pandas (Python) | <p>I have a DataFrame with column "ages" and column "professional qualification", like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ages</th>
<th>professional qualification</th>
</tr>
</thead>
<tbody>
<tr>
<td>45</td>
<td>labourer</td>
</tr>
<tr>
<td>49</td>
<td... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a> with aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> cust... | python|pandas|dataframe|grouping|frequency | 0 |
19,795 | 73,604,983 | Not able to create data buckets in Python dataframe | <p>I am new to Python and not able to create categorical data buckets for continuous data column. I am using the following nested-if combination but its not working. Can someone tell me what am I doing wrong?</p>
<pre><code>POS_Bucket = []
for elements in range(0,len(df['CURRENT_BALANCE'])):
if elements <= 25000... | <p>Use <code>Series.apply</code> for a custom row-wise mapping function:</p>
<pre><code>import pandas as pd
def get_bucket(balance):
if balance <= 25000:
return "0-25k"
if balance <= 50000:
return "25k-50k"
if balance <= 75000:
return "50k-75k"... | python|pandas|dataframe | 1 |
19,796 | 62,021,932 | How can I drop column using combination of string and integer? | <p>I have many columns name with string with (t+1) (t+2) .... (t+54)
In pictured attached, How can I drop just only columns "lemon(t+1),....,lemon(t+30), not lemon(t-1)</p>
<p>Thanks</p>
<p><img src="https://i.stack.imgur.com/lyPlo.jpg" alt="enter image description here"></p> | <p>using a list comprehension - </p>
<pre><code>df.drop([f"lemon(t-{i})" for i in range(1,31)],axis=1)
</code></pre> | python|pandas|dataframe | 1 |
19,797 | 61,710,956 | Date Offset depending on other column in pandas df | <p>Hi I am new to python switching from R and I have a hard time with this pretty simple task of changing a date based on another column of a pandas data frame. I read several other questions on this and I was hoping that someone could just quickly solve my issue, since I have nobody else to ask but the internet. </p>
... | <p>Try this code .. it worked for me:</p>
<pre><code>import datetime
from datetime import datetime
import pandas as pd
import numpy as np
today=pd.to_datetime(datetime.today().strftime('%Y-%m-%d'))
d={"Start_Date":[today,today]}
df=pd.DataFrame(data=d)
n=len(df)
df["Distance"]=np.round_(np.random.uniform(low=1, high... | python|pandas|time | 1 |
19,798 | 61,736,020 | Generating a tuple of indexes based on a sequence of values in a pandas DataFrame | <p>It's a follow up to my previous question here: <a href="https://stackoverflow.com/questions/61735585/finding-the-index-of-rows-based-on-a-sequence-of-values-in-a-column-of-pandas-da">Finding the index of rows based on a sequence of values in a column of pandas DataFrame</a></p>
<p>I want to get a list of tuples tha... | <p>IIUC, you can try:</p>
<pre class="lang-py prettyprint-override"><code># filters only rows with bad and very bad
m = df[df['status'].isin(['bad','very bad'])]
# check id current row is very bad and next row is bad
c = m['status'].eq('very bad') & m['status'].shift(-1).eq('bad')
# if true return next row as t... | python|python-3.x|pandas|dataframe | 7 |
19,799 | 57,896,767 | fetch values using reference dataframe from another dataframe and apply calulation | <p>I have two dataframes one dataframes containes four column names as Field_name, field_Type, Unit_Measurement, and Asset Name. and another dataframe contains all the field_name in single row and their corressponding values in the another row.
An example </p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'Field... | <p>if your <code>DataFrame</code> are:</p>
<pre><code>df1 = pd.DataFrame({'Field_Name' : ['W_LD(1)', 'R_LD(3)', 'WMEAS_LD(1)', 'WMEAS_LD(2)','W_LN(1)','WMEAS_LN(1)'],
'Field_Type' : ['est', 'est', 'meas', 'meas','est','meas'],
'Unit' : ['mw', 'mv', 'mw', 'mw','mw','mw'],
... | python|pandas|dataframe | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.