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 |
|---|---|---|---|---|---|---|
361,400 | 59,925,585 | How to strip a comma in the middle of a large number? | <p>I want to convert a str number into a float or int numerical type. However, it is throwing an error that it can't, so I am removing the comma. The comma will not be removed, so I need to find a way of finding a way of designating the location in the number space like say fourth.</p>
<pre><code>power4 = power[power.... | <blockquote>
<p>Use replace()</p>
</blockquote>
<pre><code>float('127,000'.replace(',',''))
</code></pre> | python|pandas | 2 |
361,401 | 60,218,052 | Mapping data between arrays of different shape | <p>I have an array of data with shape <code>(256,256,3)</code> where each value on axis <code>(0,1)</code> has the value <code>[1,0,0], [0,1,0],[0,0,1]</code> or <code>[1,1,0]</code>.</p>
<p>I want to convert this to an array of shape <code>(256,256,4)</code> where the values are mapped as follows:</p>
<pre class="la... | <p>Let's reproduce the problem:</p>
<pre><code>a = numpy.array([[1,0,0], [0,1,0], [0,0,1], [1,1,0]])
b = a[numpy.random.randint(0,4,256*256)].reshape(256,256,3)
</code></pre>
<p>We can insert your original array in an array of zeros with size 4 on the last axis:</p>
<pre><code>c = numpy.zeros((b.shape[0], b.shape[1]... | python|arrays|numpy|mapping | 0 |
361,402 | 60,098,383 | Why can't I find the index of the maximum value in my spectrogram array? | <p>I'm working with a spectrogram, and I want to find the index of the maximum value in that array at a certain frequency in a certain time range in order to tell when the maximum happens. I found the maximum and it was the value I expected from a plot of the data, however when I attempt to index the value I get an emp... | <p>The function <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="nofollow noreferrer"><code>np.argmax</code></a> returns the index of the maximum value in an array:</p>
<pre class="lang-py prettyprint-override"><code>peakindex = np.argmax(Xsum)
</code></pre> | python|numpy|indexing|spectrogram | 0 |
361,403 | 60,190,294 | How to save only the rows with a specific numpy array / matrix shape in Pandas dataframe? | <p>Say I have a dataframe <code>df</code>, and a column <code>'Array'</code> that contains bunch of numpy arrays. Now I want to save only the rows with the array shape that most commonly existed in this column, and drop the other rows. I want to input these arrays as features to do some machine learning stuff, so I nee... | <p>My suggestion would be to create a filter in this way for your dataframe</p>
<pre><code>filter = [i.shape == most_common for i in df['c_matrix']]
df = df[filter]
</code></pre>
<p>Or simply</p>
<pre><code>df = df[[i.shape == most_common for i in df['c_matrix']]]
</code></pre> | python|pandas|numpy|dataframe|machine-learning | 0 |
361,404 | 60,020,156 | TensorFlow label number is a mismatch with the shape on the axis | <p>trying to run the codelab:
<a href="https://codelabs.developers.google.com/codelabs/recognize-flowers-with-tensorflow-on-android/#6" rel="noreferrer">https://codelabs.developers.google.com/codelabs/recognize-flowers-with-tensorflow-on-android/#6</a></p>
<p>I have developed my own files and list files although I see... | <p>Sorry for being late.
There may be some empty line in your labels.txt file or there may be some extra label in your labels.txt file. Do check that.</p> | java|android|tensorflow|classification|tensorflow-lite | 0 |
361,405 | 60,225,151 | Pandas Check Multiple Conditions | <p>I have a small excel file that contains prices for our online store & I am trying to automate this process, however, I don't fully trust the stuff to properly qualify the data, so I wanted to use Pandas to quickly check over certain fields, I have managed to achieve everything I need so far, however, I am only a... | <p>Example:</p>
<pre><code>df = pd.DataFrame([
['a',1,2],
['b',3,4],
['a',5,6]],
columns=['f1','f2','f3'])
# | represents or
print(df[(df['f1'] == 'a') & (df['f2'] > 1)])
</code></pre>
<p>Output:</p>
<pre><code> f1 f2 f3
2 a 5 6
</code></pre> | python|pandas|dataframe | 1 |
361,406 | 59,935,155 | How to calculate Mean Bias Error(MBE) in Python? | <p>I am trying to calculate <strong>Mean Bias Error</strong>(<strong>MBE</strong>) for a set of actual and test prediction in Python. I looked in sklearn.metrics library or NumPy, but there is no method listed to calculate it.</p>
<p>Can anyone suggest any library or a way for how to calculate it?</p>
<p>Thanks,
Deba... | <p>MBE is defined as a mean value of differences between predicted and true values so you can calculate it using simple mean difference between two data sources:</p>
<pre><code>import numpy as np
data_true = np.random.randint(0,100,size=100)
data_predicted = np.random.randint(0,100,size=100) - 50
MBE = np.mean(data_pre... | python|numpy|scikit-learn|statistics | 2 |
361,407 | 60,119,060 | How to offset Date to the beginning of the month? | <p>I have the data frame that goes more or less like this: </p>
<pre><code>Date x y z
1998-01-30 000445 Abbey National Plc 2.24455118179321
1998-01-30 001097 Mytravel Group 1.55792689323425
</code></pre>
<p>The 'Date' column is datetime64[ns] type and I would like to offset the 'Date' column so that my d... | <p>You could try</p>
<pre><code>df['New_date'] = df.set_index('Date').index.to_period('M').to_timestamp('D')
</code></pre>
<p>This assumes that <code>Date</code> is already a datetime object. If it isn't, then first convert using.</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'])
</code></pre>
<p>It's not esse... | python|pandas | 2 |
361,408 | 60,254,233 | Plot sample images over network graph | <p>I am using Plotly to display a network graph and I'm trying to display sample images belonging to specific data points (each data point is a 64x64 luminosity map of a sculpture). I have two problems:</p>
<ol>
<li>I'm using the datapoint coordinates to position the image, but they are not aligned. I tried to use <co... | <p><em>First pitch</em></p>
<p>Since you haven't provided a fully reproducible example, it's difficult to solve your problem directly. But I do have a suggestion building on the top example from <a href="https://plot.ly/python/network-graphs/" rel="nofollow noreferrer">plot.ly/python/network-graphs/</a> and using the ... | python|numpy|plotly|networkx | 1 |
361,409 | 60,069,564 | Plotly: Why will px.line not show this figure in google colab? | <p>I want to plot an interactive plot for dataset <code>df</code>:</p>
<pre><code>Time Temperature
8:23:04 18.5
8:23:04 19
9:12:57 19
9:12:57 20
9:12:58 20
9:12:58 21
9:12:59 21
9:12:59 23
9:13:00 23
9:13:00 25
9:13:01 25
9:13:01 27
9:13:02 27
9:13:02 28
9:13:... | <p>The problem has to be related to your data import <strong><em>or</em></strong> plotly itself. I'm getting this plot using two different approaches:</p>
<p><a href="https://i.stack.imgur.com/maARS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/maARS.png" alt="enter image description here"></a></p... | python|pandas|matplotlib|plotly|google-colaboratory | 2 |
361,410 | 60,297,576 | Mutilple delimiter pandas txt | <p>I am trying to turn a long string in a .txt file into a 2D pandas table</p>
<pre><code>[{"CAN":"5420060701","VAL":"0"},{"CAN":"1920010101","VAL":"1"},{"CAN":"1920020101","VAL":"1"},...]
</code></pre>
<p>Into </p>
<pre><code>+----CAN-----+----VAL--+
+-5420060701-+----0----+
+-1920010101-+----1----+
+-19200... | <p>Just use pandas read_json method:</p>
<pre><code>df = pd.read_json('jsn.txt')
print(df.head())
</code></pre> | python|pandas|csv | 2 |
361,411 | 59,983,144 | Pandas join two dataframes with condition | <p>I want to join two dataframes together, both dataframes have date columns (<code>df1[date1]</code>, <code>df2[date2]</code>). I want the joined dataframe to satisfy this condition <code>df2[date2] > df1[date1]</code>. Second dataframe does not have any duplicates but first one does, so this does not work as expec... | <p>based on your clairification I sugegst the following solution:</p>
<p>1) <code>concatenate</code> (not <code>join</code>) the 2 dataframes. </p>
<pre><code>df12 = pd.concat([df1, df2], axis=1)
</code></pre>
<p>I assume that the indices match. If not - reindex on id or <code>join</code> on id. </p>
<p>2) filter ... | python|pandas|dataframe|join | 1 |
361,412 | 60,185,297 | How to search word in column A and count it based on column B in Pandas? | <p>I have dataframe based on Text, Date and Author like this: </p>
<pre><code>TEXT Author Date
This is a Cat Jane 1.01.1997
This is a Dog Sara 1.02.2009
I have a cat Lesner 5.07.2001
</code></pre>
<p>So, I want to write a scr... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html" rel="nofollow noreferrer"><code>Series.str.count</code></a> with ignore lower and upper cases, but also are counts words like <code>cation</code>, <code>locate</code> because contains subtring <code>cat</code>:</p>
... | python|pandas | 1 |
361,413 | 60,076,741 | Resume training with Adam optimizer in Keras | <p>My question is quite straightforward but I can't find a definite answer online (so far).</p>
<p>I have saved the weights of a keras model trained with an adam optimizer after a defined number of epochs of training using:</p>
<pre><code>callback = tf.keras.callbacks.ModelCheckpoint(filepath=path, save_weights_only=... | <p>In order to perfectly capture the status of your optimizer, you should store its configuration using the function <a href="https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam#get_config" rel="nofollow noreferrer"><code>get_config()</code></a>. This function returns a <strong>dictionary (containing th... | python|tensorflow|keras|adam | 5 |
361,414 | 59,921,220 | How to insert value in df based on function output from another column value | <p>I have 2 columns in my dataframe:
ip,geoIP</p>
<p>I want to loop through my df and perform a user defined function to geolocate an IP and fill the geoIP column with the return value from the function. </p>
<p>How can i populate the column geoIP with the output from my user defined function which takes the input of... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">apply</a>.</p>
<pre><code>def user_defined_function(x):
#add your code here
df['geoIP'] = df['ip'].apply(user_defined_function)
</code></pre> | pandas | 0 |
361,415 | 60,036,874 | How to plot every single row in a Dataframe? | <p>I would like to have a 3 x n matrix with plots for a Dataframe</p>
<p>The DataFrame looks like the following:</p>
<pre><code> file_sizes
A [36556.0, 204052.0, 18029.0, 36866.0, 10310.0]
B [36516.0, 221952.0, 78029.0, 36166.0, 20310.0]
C [26456.0, 284152.0, 38029.0, 36766.0, 50310.0]
D [16356.0... | <pre><code>for i in range(0,df_final.shape[0]):
print(df_final.loc[[i]])
</code></pre>
<p>or u might prefer </p>
<pre><code>print(df.loc[:,:])
</code></pre>
<p>If it doesn't work, please answer me back!</p> | python|pandas|seaborn | 0 |
361,416 | 60,040,576 | Taking the mean value of N last days | <p>I have this data frame:</p>
<pre><code>ID Date X 123_Var 456_Var 789_Var
A 16-07-19 3 777 250 810
A 17-07-19 9 637 121 529
A 20-07-19 2 295 272 490
A 21-07-19 3 778 600 544
A 22-07-19 6 741 792 907
A 25-07-19 6 ... | <p>I change <a href="https://stackoverflow.com/a/30274639"><code>unutbu solution</code></a> for working in <code>rolling</code>:</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
n = 5
cols = df.filter(regex='Var').columns
df = df.set_index('Date')
df_ = df.set_index('ID', append=True).swaplevel(1... | python|pandas|numpy | 2 |
361,417 | 60,270,444 | How to write a vector function to apply operation f(x,y)? | <blockquote>
<p>scalar_function can only handle scalar input, we could use the function np.vectorize() turn it into a vectorized function. Note that the input argument of np.vectorize() should be a scalar function, and the output of np.vectorize() is a new function that can handle vector input.</p>
<p>Please write a ve... | <p>Try this</p>
<pre class="lang-py prettyprint-override"><code>vector_function = np.vectorize(scalar_function)
</code></pre> | python|numpy|vector|vectorization|scalar | 0 |
361,418 | 60,232,908 | Iteratively INSERTing from a Dataframe | <p>My question may be out of pure ignorance. Given an arbitrary dataframe of say 5 rows. I want to insert that dataframe into a DB (in my case it's postgresSQL). General code to do that is along the lines of:</p>
<pre><code> postgres_insert_query = """ INSERT INTO table (ID, MODEL, PRICE) VALUES (%s,%s,%s)""" rec... | <p>In python you could simply loop over your data frame and then do your inserts.</p>
<pre><code>for record in dataframe:
sql = '''INSERT INTO table (col1, col2, col3)
VALUES ('{}', '{}', '{}')
'''.format(record[1], record[0], record[2])
dbo.execute(sql)
</code></pre>
<p>This is highly... | python|sql|pandas|postgresql | 0 |
361,419 | 60,047,816 | Sum list of NumPy arrays without summing coordinates if the list is size 1 | <p>If I have a list of numpy arrays and want to add them coordinate-wise: <code>np.sum()</code> does the job.</p>
<pre><code>sum([np.array([1, 2, 3]), np.array([6, 5, 4])])
>>> array([7, 7, 7])
</code></pre>
<p>But if my list happens to contain only one array, a new (and unwanted) thing happens:</p>
<pre><c... | <p>Numpy arrays can be sumed over arbitrary dimension. You'll need to transform this into a single array first:</p>
<p><code>np.array([...]).sum(axis=0)</code></p>
<p>As it was hinted in the comment, handling it as a numpy array from the start makes more sense.</p> | python|numpy|sum | 2 |
361,420 | 60,247,228 | Get average data based on date, week, month | <p>I have a dataset that includes three years data of a factory workers' output. Now I would like to get average output based on date, week, month for example. The problem is the date format is like %d.%m.%Y (day-month-year). My question is how could I keep the date format unchanged while get the expected output. </p>
... | <p>Your code seems fine and in fact works well at least for the first four data records. The problem here is that the date format is not consistent from the error you reported. Like others pointed out, letting the pandas find out format for you would solve the problem, i.e. <code>df["date"]=pd.to_datetime(df["date"])</... | python|pandas|numpy | 0 |
361,421 | 60,102,370 | Troubleshooting format of JSON get request | <p>I'm running into an issue with trying to convert a get request response into my desired format. The structure of the JSON response is a little more complicated and I'm having trouble with getting it into the right format. </p>
<p>Here's my code for converting the json script into a pandas dataframe:</p>
<pre><code... | <p>A bit of preprocessing may be needed to achieve what you want. This is fairly typical for json results from requests. In some cases a more general approach may be used. But here, since the structure is fairly simple, metrics can be flattened fairly easily.</p>
<pre><code>def flatten2df(resp_isrc, df=None):
metr... | python|json|pandas|get|request | 1 |
361,422 | 60,171,225 | How to transpose CSV data from a wide format to long dataset using Python | <p>I need to perform the below data transformation for an arbitrary number of "items" using Python. The first two columns are always the same, then there could be thousands of "itemN" columns, and I would want all the real-values in a new single column.</p>
<p>I have attempted to use pandas.wide_to_long but to my know... | <p>This looks like a job for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a> (pandas 0.25+).</p>
<pre><code># Build a DataFrame identical to the first example data you provided
d = {'type': {0: 'apple', 1: '... | python|pandas|numpy|transpose | 0 |
361,423 | 59,960,410 | How to run a function to each row of Dataframe in Python | <p>I would like to loop through a function on each row of my dataset df. df is <code>920 x 10080</code>. The function extracts the first 5 frequency components from a wave(which is formed from each row of data) using concept of Fast Fourier Transformation. The code for function:</p>
<pre><code>def get_fft_values(y_val... | <p>For the question how to apply a function on each row in a dataframe, i would like to give a simple example so that you can change your code accordingly.</p>
<pre><code>df = pd.DataFrame(data) ## creating a dataframe
def select_age(row): ## a function which selects and returns only the names which have age greater ... | python|pandas|for-loop|fft | 3 |
361,424 | 60,159,338 | shift particular rows of a particular column of pandas dataframe | <p>I have this dataframe<a href="https://i.stack.imgur.com/Zfknt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zfknt.png" alt="df"></a></p>
<p>And am trying to shift rows which have <code>NaNs</code> in the first two columns to the left, so the values to the right now fill this column. Here is wha... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html" rel="nofollow noreferrer"><code>DataFrame.rename</code></a>, then you only need <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFr... | python|pandas|dataframe | 2 |
361,425 | 60,276,364 | Pandas remove the row index from the pandas dataframe | <p>i have a dataframe with the data as follows</p>
<pre><code> id Name Age
0 1 XXX 30
</code></pre>
<p>and i have to remove the 0(the row index value) from the dataframe.</p>
<p>I have tried the folowing</p>
<pre><code>df.reset_index(inplace=True) # Resets the index, makes factor a column
df.drop("Fa... | <p>Try this one:</p>
<pre><code>df.set_index('id', inplace=True)
</code></pre> | python-3.x|pandas | 1 |
361,426 | 60,047,559 | How can I speed up my code here? Trying to iterate and replace certain values in every row. Details in body | <p>I'm trying to modify a pandas dataframe such that in every row, columns <code>SdLog</code> and <code>Meanlog</code> get updated until a third column, <code>std</code>, is less than half of <code>std_o</code>. I'm calculating the values within the loop and reducing <code>sdLog</code> every time until the calculation ... | <p>As far as I can see your code is not just slow but gets permanently stuck in the <code>while</code> loop because the relevant variables are not actually altered on each iteration. (The values within <code>sf</code> are altered but not within the current <code>row</code>.) You can make it work by moving the logic to ... | python|pandas|loops|dataframe | 1 |
361,427 | 60,267,911 | Keras inconsistent prediction time | <p>I tried to get an estimate of the prediction time of my keras model and realised something strange. Apart from being fairly fast normally, every once in a while the model needs quite long to come up with a prediction. And not only that, those times also increase the longer the model runs. I added a minimal working e... | <p>TF2 generally exhibits poor and bug-like memory management in several instances I've encountered - brief description <a href="https://stackoverflow.com/questions/58441514/why-is-tensorflow-2-much-slower-than-tensorflow-1#answer-58653632">here</a> and <a href="https://github.com/tensorflow/tensorflow/issues/33487#iss... | python|performance|tensorflow|keras|tensorflow2.0 | 10 |
361,428 | 60,053,881 | mandelbrot set gets blurry at around 2^47 zoom | <p>So i created a simple mandelbrot zoom code that zooms in(lmb) or out(rmb) where you click. The portion that is render is halved every click as it zooms in the curve.</p>
<p>The problem is no matter how large the maxiter and additer count is, the fractal always seems to get blurry at around 2^47 zoom value.
<a href=... | <p>Below a 2^-47 image width and for most of the areas where you would like to zoom, the difference between 2 adjacent pixels - considering 1000 pixels width - will yield 0 at the standard double precision.</p>
<p>To go deeper you will need to compute at least one point (reference orbit) with a multi-precision arithmet... | python|numpy|matplotlib|mandelbrot | 0 |
361,429 | 59,998,241 | How to conditionally drop rows in pandas | <p>I have the following dataframe:</p>
<pre><code> True_False cum_val
Date
2018-01-02 False NaN
2018-01-03 False 0.006399
2018-01-04 False 0.010427
2018-01-05 False 0.017461
2018-01-08 False 0.019124
2018-01-09 False 0.020426
2018-01-10 False 0.019314
2018-01-11 False 0.026348
2... | <p>Let's try using <code>where</code> with <code>ffill</code> and parameter <code>limit=2</code> then boolean filtering:</p>
<pre><code>df[~(df['True_False'].where(df['True_False']).ffill(limit=2).cumsum() > 1)]
</code></pre>
<p>Output:</p>
<pre><code>| | Date | True_False | cum_val |
|----|---------... | python|pandas | 6 |
361,430 | 60,310,948 | How to replace NaNs in a 1D array with the mean of nearest neighbors? | <p>I have a large 1D-array with some 'NaN' values dispersed in it. I would like to replace the 'NaN' values with the mean of the values on each side of the 'NaN'.</p>
<p>There is a lot of documentation on this site about replacing 'NaN' with the mean of a column or row, but I want to replace it with just the average of... | <pre><code># to convert, you can use
lfc=['nan', 4, 'nan', 6, 3, 'nan', 1]
lfc= [np.nan if x == 'nan' else x for x in lfc ]
for i in range(0,len(lfc)):
if lfc[0] is np.nan:
lfc[0]=lfc[1]
elif lfc[i] is np.nan:
lfc[i]=(lfc[i-1]+lfc[i+1])/2
elif lfc[len(lfc)-1] is np.nan:
lfc[len(lfc... | python|arrays|numpy|nan|mean | 0 |
361,431 | 65,223,420 | Cumsum on Pandas DF with reset to zero for negative cumulative values | <p>I have a time sequential grouped table in Pandas DF. I am trying to create a running sum within groups, conditional upon running sum can not be negative, i.e. column cell value resets to zero when running sum turns negative, and continue running sum calculation to preserve integrity and data quality.</p>
<p>I've use... | <p>Let's try:</p>
<pre><code>neg = df['val'] < 0
df['output'] = df['val'].groupby([neg[::-1].cumsum(),df['group']]).cumsum().clip(0)
</code></pre>
<p>Output:</p>
<pre><code> group val cumsum_output expected_out output
0 A -5 -5 0 0
1 A 4 -1 4... | python|pandas|pandas-groupby|cumsum | 1 |
361,432 | 65,393,527 | Count rows with 2 different Date-time columns in python | <p>I have a Dataframe with 2 date columns as:</p>
<pre><code> ----------------------------
| date_created | date_ended |
|--------------| ----------- |
|20/12/01 | 20/11/01 |
|20/12/01 | 20/12/02 |
|20/12/02 | 20/12/02 |
|20/12/02 | 20/12/03 |
|20/12/02 | 20/12/03 |
|20/12/03 ... | <p>You could do:</p>
<pre><code>res = pd.concat((df['date_created'].value_counts(),
df['date_ended'].value_counts()),
axis=1, sort=True).fillna(0).astype(int)
print(res)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> date_created date_ended
20/11/01 0 ... | python|pandas|dataframe|datetime|python-datetime | 1 |
361,433 | 65,307,405 | Counting the emails in an excel file(python) | <p>I have a excel file that includes many emails and some of them are written more than once. I need to count have many times those emails were repeated. how do I do that by using python?</p> | <p>Assuming that all emails are in a "clean" format (not a free text field with misspellings, extra spaces, etc.).</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame([
['add1','val1'],
['add2','val2'],
['add3','val3'],
['add1','val4']
],columns=['Add... | python|excel|pandas | 0 |
361,434 | 65,296,138 | Identify duplicate records in python dataframe based on groupby concept, skipping first 2 occurences | <p>My requirement is to identify duplicate elements/occurrences for the same store,</p>
<ul>
<li>if only 1 incident is present for a particular store and category -> mark 1st as 'False' (skip it)</li>
<li>if 2 incidents are present for the same element -> mark 1st and 2nd as 'False' & copy 1st incident number... | <p>Let's try:</p>
<pre><code>groups = sample.groupby(['store','part1'])
sizes = groups['store'].transform('size')
orders = groups.cumcount()
first_rows = groups['inc_num'].transform('first')
sample['Duplicate'] = orders > 1
sample['Source_Inc_Num'] = np.where(sizes==1, np.nan, first_rows)
</code></pre>
<p>Output:</... | python|pandas|dataframe|pandas-groupby | 2 |
361,435 | 65,325,039 | How to delete lines in an Excel file using the pandas library | <p>Here is my code</p>
<pre><code>def delete_teach():
df = pd.read_excel('bd1.xlsx', sheet_name='teachers')
print("Enter the name of the teacher you want to remove:")
print(df['Teachers'])
delete_teach_vyb=input("Enter: ")
print("You are about to delete ", delete_teach_... | <p>You need to write the <code>df</code> back to <code>excel</code> file. Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html" rel="nofollow noreferrer"><code>df.to_excel</code></a>:</p>
<pre><code>def delete_teach():
df = pd.read_excel('bd1.xlsx', sheet_name='teac... | python|excel|pandas|function|openpyxl | 0 |
361,436 | 65,315,585 | Pytorch modifying intermediate values during forward | <p>If I have a model with several different layers, is there a way for me to modify the values in between those layers and see what the result would be if that modified value was passed through the rest of the network? I know you can use hooks to obtain the intermediate values during a forward pass but I would also lik... | <p>In the <code>forward</code> function you can do what you want, for example:</p>
<pre class="lang-py prettyprint-override"><code>class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
# example layers
self.dense1 = nn.Linear(1024, 512)
self.dense2 = nn.Linea... | neural-network|pytorch | 0 |
361,437 | 65,213,532 | Pandas replacing negative values with opposite sign for a column | <p>I am trying to visualize buy and sell transactions with matplotlib.</p>
<p>BEFORE that, I need to work on some columns.</p>
<p>In my dataset containing the sell and buy of a date, I've managed to isolate the buy and sell transactions with</p>
<pre><code>sell = df[df.side == 1]
buy = df[df.side == 0]
</code></pre>
<p... | <p>You're looking to change <code>amount</code> to its absolute value:</p>
<pre><code>df['amount'] = np.abs(df['amount'])
</code></pre> | python|pandas | 1 |
361,438 | 65,209,961 | Confusion about inability to assign numpy array element using multiple array indexing | <p>I ran into a bug caused by using multiple sets of brackets to index an array, i.e. using a[i][j] (for various reasons, mostly laziness, which I've now fixed properly). While attempting to assign an element of the array, I found that I was unable to, but I didn't receive any kind of error to tell me why. I am confuse... | <p>Because:</p>
<pre><code>x[idx]
</code></pre>
<p>Creates a <em>new array object with an independent, underlying buffer</em>.</p>
<p>So then you <em>index into that</em>:</p>
<pre><code>[1] = 10
</code></pre>
<p>Which <em>does work</em>, but then you don't keep that new array around, and it is discarded immediately.</... | python|numpy|indexing | 2 |
361,439 | 65,068,657 | Identify column wise difference in pandas dataframe | <p>I have two sets of pandas dataframes:</p>
<p>df_old:</p>
<pre><code> Drug_Name Special_Code Tier bold italic
0 abc None T9 FALSE TRUE
1 por None T9 TRUE FALSE
2 ASD None T9 FALSE TRUE
3 bhj None T9 TRUE FALSE
4 JLL None T9 FALSE TRUE
5 hhj None T2 TRUE ... | <p>There may be a better solution, but here's what comes to my mind. First, calculate the inequality between the dataframes:</p>
<pre><code>diff = (df_new != df_old)
</code></pre>
<p>Prepare a function that will process each row of the new dataframe. It selects the names of the columns that <strong>differ</strong> and ... | python-3.x|pandas|dataframe | 0 |
361,440 | 65,472,453 | Mask and reshape a matrix using Tensorflow | <p>I would like to use a <code>mask</code> to select vectors in <code>mat</code> variable. Below is the resultant matrix that I expcxt to get:</p>
<pre><code>[[0, 0, 2, 2],
[4, 4, 5, 5],
[8, 8, 9, 9]]
</code></pre>
<p>Below is the code that I use:</p>
<pre><code>mat = tf.constant([[[0, 0], [1, 1], [2, 2]],
... | <p>If you just want reshape it then using <code>tf.reshape</code> instead, because <code>tf.keras.layers.Reshape</code> will take first dimension as batch size:</p>
<pre><code>#TF2
import tensorflow as tf
mat = tf.constant([[[0, 0], [1, 1], [2, 2]],
[[4, 4], [5, 5], [6, 6]],
[[7... | tensorflow | 0 |
361,441 | 65,300,689 | Import Excel file to pandas from Github repository | <p>In my effort to export Excel file in my private Github repository to Pandas data frame using the source code below:</p>
<pre><code>username= 'xxx'
token = 'yyyy'
github_session = requests.Session()
github_session.auth = (username, token)
url = 'correct path to raw file'
export = requests.get(url).content
df = pd.r... | <p>Excel is a binary file format. Use <code>io.BytesIO(export)</code> instead</p> | python|pandas|github|import | 1 |
361,442 | 65,133,618 | astropy CartesianRepresentation to NumPy array | <p>I have an Astropy CartesianRepresentation object that looks like this:</p>
<pre><code><CartesianRepresentation (x, y, z) in km
[( 4082.71516205, 248.89483863, -5882.92418597),
( 5501.55728501, 2581.64039883, -5017.87534951), ...
</code></pre>
<p>I'd like to convert this to a NumPy ndarray so that in... | <p>considering your object name is "r" you could achieve that accessing r.x for the x component and r.y and r.z for the other components. You could also retrieve r.xyz.</p> | python|numpy-ndarray|astropy | 2 |
361,443 | 65,131,377 | Method without arguments or parenthesis for Scipy odeint | <p>help, please - I can't understand my own code! lol
I'm fairly new at python and after many trials and errors, I got my code to work, but there is one particular part of it I don't understand.</p>
<p>In the code below, I'm solving a fairly basic ODE through scipy's odeint-function. My goal is then to build on this bl... | <p>I assume you are referring to the line</p>
<pre><code>kinetics = Batch_basic.reaction_rate_simple
</code></pre>
<p>You are not calling it, you are saving the method as a variable and then passing that method to <code>equations_system(...)</code>, which simply returns it. I am not familiar with odeint, but according... | python|numpy|math|scipy|chemistry | 0 |
361,444 | 65,149,747 | How to change numbers in jsonl file and save it | <p>I have a jsonl file with content</p>
<p>How to read a file and change the number after the label sign to a random number 0 or 1 and save the converted file back in python</p>
<pre><code>{"idx": 0, "passage": {"questions": [{"idx": 0, "answers": [{"idx": 0, ... | <pre><code>import json
import random
# read each decoded JSON line into a list
with open('test.jsonl',encoding='utf8') as f:
data = [json.loads(line) for line in f]
# walk the structure and change the labels
for item in data:
for q in item['passage']['questions']:
for a in q['answers']:
a[... | python|json|pandas|json-ld | 2 |
361,445 | 65,326,577 | Simple case with regression not working (PyTorch) | <p>This simple PyTorch code from <a href="https://medium.com/@benjamin.phillips22/simple-regression-with-neural-networks-in-pytorch-313f06910379" rel="nofollow noreferrer">https://medium.com/@benjamin.phillips22/simple-regression-with-neural-networks-in-pytorch-313f06910379</a> doesn't find the regression expected on f... | <p>Well, the solution is easy: increase the number of layers, of nodes of the layers, and of epochs.
Example: layer1=400 nodes, layer2=200 nodes, layer3=100 nodes, layer4=50 nodes, epochs=1500</p> | machine-learning|pytorch|regression | 0 |
361,446 | 65,134,136 | Empty cells when using an apply function | <p>So I am trying to calculate a value from one column or another based based on which one has data available into a new column. This is the code I have right now. It doesn't seem to notice when there is no data present and always goes to the "else" statement. My dataframe is an imported excel file. Thanks fo... | <p>This is can be done by using numpy.where</p>
<p>Import numpy as np</p>
<pre><code>df['newcol'] = np.where(df["Sulphate-S(HCL Leachable)_%S"].isna(),df["Total-S_%S"]- df["Sulphate-S(HCL Leachable)_%S"],df["Total-S_%S"]- df["Sulphate-S_%S"])
</code></pre> | pandas|apply | 0 |
361,447 | 65,404,049 | PackagesNotFoundError: The following packages are not available from current channels: pytorch | <p>I am trying to install <code>Pytorch Library</code> on My <code>Windows 10</code>, having <code>Python Version 3.6.9</code> and using the following command taken from this website :<a href="https://pytorch.org/get-started/locally/#windows-package-manager" rel="noreferrer">https://pytorch.org/get-started/locally/#win... | <p>I had the same issue trying to install pytorch using miniconda 32-bit. I uninstalled it and installed the 64-bit version of miniconda. I was able to install pytorch after that.</p> | python|anaconda|pytorch | 0 |
361,448 | 65,312,926 | Create a dictionary from two pandas series split by a delimiter | <p>I have two columns A and B with corresponding keys and values if split by ':'. I am trying to create a dictionary in ColumnC to be able to later add more columns based on keys in ColumnC.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ColumnA</th>
<th>ColumnB</th>
<th>ColumnC</th>
<th>a... | <p>Simplified a bit in the process as below:</p>
<p>Code:</p>
<pre><code>import pandas as pd
import numpy as np
ColumnA = 'abc:def:ghi'
ColumnB = '111:222:333'
ColumnC = dict(zip(ColumnA.split(':'), ColumnB.split(':')))
print(ColumnA, ColumnB, ColumnC)
df = pd.DataFrame()
df['ColumnA'] = ColumnA.split(':')
df['Column... | python|pandas|dictionary|typeerror | 0 |
361,449 | 65,235,226 | Excel SUMIF equivalent in Pandas | <pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame([['A', 201901, 10, 201801, 201801],
['B', 201902, 11, 201801, 201802],
['B', 201903, 13, 201801, 201803],
['B', 201905, 18, 201801, 201805],
['A', 201906, 80, 201801, 20180... | <h2>Completely replaced the answer following clarifications from OP</h2>
<p>Note that the df you coded up is inconsistent with the df you printed in the table. I went with the one in the table</p>
<p>The below is not the most elegant but I cannot think of a more vectorized operation given missing weeks etc</p>
<p>We ba... | python|pandas|sumifs | 3 |
361,450 | 65,152,682 | Using function on tuples on list works in Google Colab, but not on local machine | <p>I can't figure out what's going on. In my google colab environment, I have a dataframe that looks like the below using spaCy's named entity extraction on snippets from NYT:</p>
<pre><code>raw_data = {'id': [1,2,3],
'ents': [[(('PARIS', 'GPE'), 6), (('French', 'NORP'), 3), (('France',
'GPE'), 1)],
... | <p>Doh! After much banging my head against the wall, turns out that all I needed to do was to check if the object has type list. I was reading in a *.csv extracted ents and the values for that column were not longer type list - evaluated to False when I did an isinstance. Should've saved my original output as a pickle ... | python|pandas|list | 0 |
361,451 | 65,472,336 | Pandas: convert for loop with if/else conditions into apply method (lambda function) | <p>I have the following function with for loop:</p>
<pre><code>def add_CQI_iterrows(df):
previous_row = df['Date'].astype(str)[0]
CQI_index = 0
series = []
for index, row in df.iterrows():
if row['Date'] == previous_row:
previous_row = row['Date']
print(CQI_index)... | <p><code>df['CQI'] = (df['Date'] != df['Date'].shift()).cumsum()</code></p>
<pre class="lang-py prettyprint-override"><code>In [120]: (df['Date'] != df['Date'].shift()).cumsum()
Out[120]:
0 1
1 1
2 1
3 2
4 2
5 2
6 3
7 3
8 3
9 4
10 4
11 4
Name: Date, dtype: int64
</code></pr... | python|pandas|for-loop|vectorization|apply | 2 |
361,452 | 65,379,408 | Pandas groupby and find difference between max and min | <p>I have a dataframe. I have aggregated as below. But, I want to difference them as max value - min values</p>
<p><img src="https://i.stack.imgur.com/cO1hy.png" alt="enter image description here" /></p>
<pre><code>dnm=df.groupby('Type').agg({'Vehicle_Age': ['max','min']})
</code></pre>
<p>Expect:</p>
<p><img src="http... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.ptp.html" rel="noreferrer"><code>np.ptp</code></a>, this does the <code>max - min</code> calculation for you:</p>
<pre><code>df.groupby('Type').agg({'Vehicle_Age': np.ptp})
</code></pre>
<p>Or,</p>
<pre><code>df.groupby('Type')['Vehicle_Age'... | python|pandas|numpy | 9 |
361,453 | 65,366,602 | Fast way to create incidence matrix from list of label python? | <p>I have an array <code>y, len(y) = M</code> that contains values from <code>0 -> N</code>. For example, with <code>N = 3</code>:</p>
<pre><code>y = [0, 2, 0, 1, 2, 1, 0, 2]
</code></pre>
<p>Incidence matrix <code>A</code> is defined as followed:</p>
<ul>
<li>Size <code>MxM</code></li>
<li><code>A(i,j) = 1 if y(i) ... | <p>You can take advantage of numpy broadcasting to gain some efficiency here over our python by simply asking if <code>y</code> equals its transpose:</p>
<pre><code>import numpy as np
y = np.array([1, 2, 1, 0, 0, 1, 2])
def mat_me(y):
return (y == y.reshape(-1, 1)).astype(int)
mat_me(y)
</code></pre>
<p>which pr... | python|algorithm|numpy|cluster-analysis|vectorization | 1 |
361,454 | 65,102,525 | convert dataframe to fasttext data format | <p>I want to convert a dataframe to fasttext format</p>
<p>my dataframe</p>
<pre><code>text label
Fan bake vs bake baking
What's the purpose of a bread box? storage-method
Michelin ... | <p>Try:</p>
<pre><code>'__label__'+df['label']+' '+df['text']
</code></pre> | python|pandas|fasttext | 6 |
361,455 | 65,169,539 | Replace rows in a dataframe with rows in another dataframe given multiple columns as keys | <p>There are questions similar to this on SO but I am yet to see one exactly like this - replacing with multiple columns as keys.
I have two dataframes. Example below:</p>
<pre><code>df1 = pd.DataFrame([["X",Monday,1,0],
["Y",Tuesday,1,0],
["Z",Wednesday,0,0],
... | <p>You can still use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html" rel="nofollow noreferrer"><code>DataFrame.update</code></a> to update the values in place using non-nan values from another DataFrame but before using it you have to <code>align</code> the indices in b... | python|pandas|dataframe | 2 |
361,456 | 65,392,539 | pandas sqlite read_sql dynamic in clause | <p>I am trying to use pandas read_sql function to query some data from sqlite DB. I need to use parameterized SQL which contains in clause (List) and some static parameters.</p>
<p>Below is my query</p>
<pre><code>battingDataQuery = ('SELECT ID, MATCH_DATE, ROLE, DOWN_NUM, NAME, RUNS,'
'MATCH_ID, T... | <p>You should supply a list of 7 parameters for your 7 question marks:</p>
<pre><code>battingDataDF = pd.read_sql_query(battingDataQuery , conn, params=playerIdList + [battingDownNum, "'T20'"])
</code></pre>
<p>(you supplied 3 parameters: a list of 5 numbers, a number and a string, hence the error)</p> | pandas|sqlite|dataframe|parameters|read-sql | 1 |
361,457 | 65,435,712 | numpy broadcasting - explanation of trailing axes | <h1>Question</h1>
<p>Please elaborate the answer in <a href="https://stackoverflow.com/a/11178246/4281353">Numpy array broadcasting rules</a> in 2012, and clarify what <em><strong>trailing axes</strong></em> are, as I am not sure which "linked documentation page" the answer refers to. Perhaps it has changed i... | <p>Trailing axes are <code>axis=-1, axis=-2, axis=-3 ...</code> . Broadcasting rules compare trailing axes as opposed to <code>leading</code> axes (<code>axis=0</code> onwards).</p>
<p>This is specifically for applying broadcasting to different dimensional tensors (say 2D and 3D tensors). <code>Trailing axes</code> bas... | python|numpy|array-broadcasting | 1 |
361,458 | 65,297,828 | problem to importing values after filling time gaps | <p>I have a text file that includes time series data, but there are some gaps in the time series and values. ( i only insert the first 5 rows of data as example the time series is from 1996 to 2010)</p>
<p>o_data is a (dataframe):</p>
<pre><code> Time Value
01.01.1996 00:00 nan
01.01.1996 00:10 ... | <p>Not exactly sure how your data is setup but I had to change data types and use reindex to get your result</p>
<pre><code>d = """Time,Value
01.01.1996 00:00,nan
01.01.1996 00:10,10.4
01.01.1996 00:20,10.4
01.01.1996 00:50,10.4"""
o_data = pd.read_csv(io.StringIO(d), sep=',')
o_data['Tim... | python|pandas|dataframe|datetime | 0 |
361,459 | 65,107,411 | Trying to replace part of array to another array, get error ValueError: assignment destination is read-only | <p>I have two arrays with pixels, I need to replace the first part of array 'pixels_new', to array 'pixels_old'</p>
<pre><code>pixels_old = numpy.asarray(im) #picture 100X100
pixels_new = numpy.asarray(img) #picture 100X200
for k in range(0,101):
for i in range(len(pixels_old[k])):
print(pixels_new[i])
... | <p>I did a simple test as below.</p>
<pre><code>import numpy as np
data = np.asarray([1, 2, 3])
data[0] = 2
data
>>> array([2, 2, 3])
</code></pre>
<p>This shows <code>np.asarray</code> does not return the immutable variable, which is read-only. The error is <code>ValueError: assignment destination is read-onl... | python|numpy | 0 |
361,460 | 65,455,478 | Selecting rows where column value is 1 in the current row, but 0 in the previous row | <p>I am working with a DataFrame on Python 3.8 where I try to replicate Excel calculations - a basic <code>if</code> with two criteria, one of which is referencing itself a row before.</p>
<pre><code>Backtest['trade_price']=0
Backtest.loc[(Backtest['z_en_crit']==1) &
(Backtest['trade_price'].shift(-1)... | <p>Are you looking to shift on "z_en_crit" instead? Also, you should reverse the direction of the shift if you want to match on the first of the group, not the last.</p>
<pre><code>df['trade_price'] = np.where(
df['z_en_crit'].eq(1) & df['z_en_crit'].shift(1).eq(0), 1, 0)
df
... | python|pandas|shift|rolling-computation | 3 |
361,461 | 65,428,804 | How to write into Excel using Pandas? | <p>The first code below works and allows me to read my excel file, as a test, I added a new column.</p>
<pre><code>import numpy as np
import pandas as pd
excl = pd.read_excel (r'C:\Users\Family\Desktop\Anaconda\Book1.xlsx')
excl['new_pop'] = (excl.Pop2010 + excl.Pop2020)
print (excl)
</code></pre>
<p>Now, I would like... | <pre class="lang-py prettyprint-override"><code>excl.to_excel("new-file.xlsx")
</code></pre>
<p>Scroll down until you see examples:
<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/referen... | python-3.x|pandas|dataframe | 1 |
361,462 | 65,477,586 | Methods of improving the efficiency of a a python-loop computation | <p>I would like to speed up the following code related to spherical modes. It is a simplification of my actual code (I didn't want to oversimplify it because it can lead to solutions that are not valid for my actual problem):</p>
<pre><code>import numpy as np
import time
import math
def function_call(npp,nmax):
ma... | <p>I've worked a little bit on your code, here the benchmark.
the bottleneck is in the factorial computation.</p>
<pre><code> ================== PerfTool ==================
task |aver(s) |sum(s) |count |std
main loop | 0.134| 10.712| 80| 0.101
+-second loop ... | python|performance|numpy|numba|computation | 1 |
361,463 | 65,250,490 | Pandas: get column name of (row-wise) n-smallest value of selected columns | <p>Consider the following sample data:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(123)
n = 200
df = pd.DataFrame({'v1': np.random.randint(0, 100, n),
'v2': np.random.randint(10, 90, n),
'v3': np.random.randint(10, 90, n),
'another_v': ... | <p>You can use for improve performance not loop apply solution in <code>numpy</code>:</p>
<pre><code>np.random.seed(200)
n = 200
df = pd.DataFrame({'v1': np.random.randint(0, 100, n),
'v2': np.random.randint(10, 90, n),
'v3': np.random.randint(10, 90, n),
'anoth... | pandas | 1 |
361,464 | 65,470,105 | Iterate through multiple Pandas list-type series and find matches | <p>I have a Pandas DF containing three list-like series that I need to iterate through and compare against external lists to then create a True/NaN series for rows where exact matches of these external lists are found</p>
<p>Recreation code:</p>
<pre><code>data = {
"num_elements": [1,3,3,4],
"el... | <p><a href="https://stackoverflow.com/a/53102773/3965888">Use tuples instead of lists :</a></p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
data = {
"num_elements": [1,3,3,4],
"elements_bool_identifiers": [["Y"],["N", "Y"],["N"... | python|pandas | 0 |
361,465 | 65,218,994 | How to create new column in DataFrame based on other columns in Python Pandas? | <p>I have DataFrame like below:</p>
<pre><code>data = pd.DataFrame({"col1" : ["a", "b", "c"],
"binary" : [0, 1, 0]})
</code></pre>
<p>I would like to create and add new column in this <code>DataFrame</code> called <code>"new"</code> where... | <p>you can use <code>where</code> from the <code>numpy</code> package and , and do:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({"col1" : ["a", "b", "c"], "binary" : [0, 1, 0]})
df['new'] = np.where(df['binary']==1,df['col1'],np.nan)
</code><... | python|pandas | 0 |
361,466 | 65,321,409 | Pandas DataFrame: Find unique words in string column, count their occurrence and sum values in another column on condition | <p>I have the following dataframe:</p>
<pre><code>import pandas as pd
data = {'String': ['foo bar hello world this day', 'foo bar', 'hello bar world'],
'Value' : [ 10, 2, 5]}
df = pd.DataFrame(data, columns = ['String', 'Value'])
</code></pre>
<p>What I want t... | <p>You could do:</p>
<pre><code>df['Unique Word'] = df['String'].str.split()
res = df.drop('String', 1).explode('Unique Word').groupby(['Unique Word'])['Value'].agg(['count', 'sum']).reset_index()
print(res)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> Unique Word count sum
0 bar 3 17
1 ... | python|pandas|dataframe|series | 2 |
361,467 | 65,381,136 | filter pandas dataframe on column and add string to the filtered data | <p>I am having a dataframe column that contains either 4 or 6 char strings in length, I would like to add "00" string to the end of the strings having length of 4.</p>
<p>I am using this code but its giving me a syntax error.</p>
<pre><code>df['col'] = np.where((df['col'].str.len() = 4, df['col'].astype(str) ... | <p>The clean <em>pandas</em> way to do this is to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.ljust.html" rel="nofollow noreferrer">ljust</a> instead:</p>
<pre><code>import pandas as pd
df = pd.DataFrame()
df['col'] = pd.Series(['aaaa', 'bbbbbb'], dtype='string')
df['col'... | python|pandas|dataframe | 3 |
361,468 | 65,459,887 | importing Cross tab data from excel to Pandas Data frame | <p>I have data in excel extracted from IBM Cube in the form of Cross tab.</p>
<pre><code>Crosstab example:
|Account| Entity| Functions| JAN | FEB | MAR | JAN | Feb | Mar |
Actuals Actuals Actuals Forecast Forecast Forecast
A2100 10021 ABS $200 $300 ... | <p>Assuming that you already read your data from Excel into a dataframe <code>df</code> you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>melt</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow... | python|python-3.x|excel|pandas|dataframe | 0 |
361,469 | 65,337,392 | Using apply function to convert values in columns | <p>I am trying to convert a value of a column in the dataframe. column name is size. it has data as 11.1 K or 51.6M, i.e ending in K or M and has object data type. i want to write an apply function which converts this value to 11.1 if it is ending in K and 516000 if it is ending in M . Any help?</p>
<p>I am trying to c... | <p>Lots of way to do this, a simple way would be to use <code>pd.eval</code> with <code>replace</code></p>
<pre><code>df = pd.DataFrame({'A' : ['56.1M', '11.1K']})
print(df)
A
0 56.1M
1 11.1K
df['B'] = df['A'].replace({'M' : '*10000', 'K' : '*1'},regex=True).map(pd.eval)
print(df)
A B
0 56.1M ... | python-3.x|pandas|apply | 0 |
361,470 | 65,122,296 | Bin time column and group multiple columns within each bin | <p>I have a pandas dataframe that looks like this, with one Date column and two categorical columns:</p>
<pre><code>Date Feature1 Feature2
2019-01-06 19:15:52+00:00 A K
2019-01-27 23:44:11+00:00 B H
2019-01-29 16:50:31+00:00 A K
2019-01-29 19:49:15+00:00 C ... | <p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow norefer... | python|pandas | 0 |
361,471 | 65,099,251 | How to extract slices and specific columns of a numpy array with one command? | <p>I would like to extract both column slices and specific columns of a <code>numpy</code> array in one command.</p>
<p>For instance, for an array A:</p>
<pre><code>import numpy as np
A = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])
</code></pre>
<p>I would like to select the columns from 0 to 2 together with ... | <p>As <em>ombk</em> suggested, you can use <em>r_</em>.
It is a perfect tool to concatenate slice expressions.</p>
<p>In your case:</p>
<pre><code>A[:, np.r_[0:3, 4]]
</code></pre>
<p>retrieves the intended part of your array.</p>
<p>Just the same way you can concatenate more slice expressions.</p> | python|arrays|numpy | 1 |
361,472 | 65,072,843 | ERROR: No matching distribution found for torch===1.7.0+cu110 | <p>Hi I got an error while trying to install pytorch:</p>
<pre><code>PS C:\windows\system32> pip install torch===1.7.0+cu110 torchvision===0.8.1+cu110 torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
Looking in links: https://download.pytorch.org/whl/torch_stable.html
ERROR: Could not find a ... | <p>The newest version of torch is 1.7.0, so</p>
<pre class="lang-sh prettyprint-override"><code>pip install torch
</code></pre>
<p>should be enough.</p> | python|pip|pytorch | -1 |
361,473 | 65,079,789 | Loop through schools append to dataframe pandas | <p>I am working on scraping some data from schools and each school has three credentials (user1 - user2 - password)
I could create a function that enables me to scrape the name of each school
Here's the function</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'http://student.emis... | <p>If you are looking to merge DataFrames together in pandas you first make a list out of the Dataframes and then use the built-in concat function:</p>
<pre class="lang-py prettyprint-override"><code>list_of_dfs = [df1, df2, df3]
new_df = pd.concat(list_of_dfs)
</code></pre> | python|pandas|python-requests | 1 |
361,474 | 65,412,694 | Unique values from dataframe columns via loop | <p>Is it possible to get unique values from multiple columns? I would like each column to have it's own unique values output via a loop.</p>
<pre><code>df["col A"].unique()
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Col A</th>
<th>Col B</th>
</tr>
</thead>
<tbody>
<... | <p>It kinda depends on what you want as output. You can do it like this to get a dict with each column:</p>
<pre class="lang-py prettyprint-override"><code>unique_vals = {col:df[col].unique() for col in df}
</code></pre>
<p>But you probably don't want it as a dataframe like this, because there is no guarantee the amoun... | python|pandas|numpy | 2 |
361,475 | 65,062,580 | How to vectorize a function within loop with break in Python 3 | <p>I am trying to run the following program with numpy vector code within <strong>loop</strong> with <strong>break</strong> in Python 3 but get <code>ValueError: The truth value of an array with more than one element is ambiguous</code> because of the "if" (it's ok to compare a numpy array to a scalar as each... | <p>You question was unclear.</p>
<p>The symptom you experience is clear and easy to avoid.
It sounds like you may want to compute an aggregate over the booleans.
An <code>if</code> could then make a decision based on the aggregate.</p>
<pre><code>>>> ARRAY_LEN = 8
>>> calculation = np.zeros(ARRAY_LEN)... | python-3.x|numpy | 1 |
361,476 | 65,410,051 | Split Column with Differing Lengths | <p>I am looking to split out a cell into multiple columns with differing lengths (some have one additional field while others will not). I also have additional data in other columns so I'd like to maintain my dataframe structure while doing this. Any ideas?</p>
<p>Code:</p>
<pre><code>d = {'Product':product, 'Descripti... | <p>The <code>pandas.DataFrame.str.split</code> method splits string on whitespaces by default (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer">see the docs here</a>). So if you want a different delimiter you need to specify it, such as</p>
<pre... | python|pandas | 0 |
361,477 | 65,111,126 | How to use the argsort output to order multidimensional arrays | <p>I have a 'list of arrays' and I order each of these arrays with argsort:</p>
<pre><code>import numpy as np
arr = np.array([[4, 2, 5], [4, 3, 1], [1, 5, 7], [1, 5, 4]])
idxs = arr.argsort(axis=1)
idxs
>>> array([[1, 0, 2],
[2, 1, 0],
[0, 1, 2],
[0, 2, 1]])
</code></pre>
<... | <p>You can use pair indexing:</p>
<pre><code>arr2 = np.arange(3*4*3).reshape(4,3,-1)
arr2[np.arange(arr2.shape[0])[:,None],:, idxs]
</code></pre>
<p>Output:</p>
<pre><code>array([[[ 1, 4, 7],
[ 0, 3, 6],
[ 2, 5, 8]],
[[11, 14, 17],
[10, 13, 16],
[ 9, 12, 15]],
[[18... | python-3.x|numpy|sorting|indexing|numpy-ndarray | 1 |
361,478 | 65,314,654 | Pandas reads almost every column in .txt as index - SOLVED | <p>I have a file named "sample name_TIC.txt". The first three columns in this file are useful - Scan, Time, and TIC. It also has 456 not useful columns after the first 3. To do other data processing, I need these not-useful columns to go away. So I wrote a bit of code to start:</p>
<pre><code>os.chdir(main_fo... | <p>Answering here to make sure the problem gets flagged as answered, in case someone else searches for it.</p>
<p>I made an error when calling the result from the code which included the <code>usecols=[0,1,2]</code> argument, and I was calling an older dataframe. The following line of code successfully generated the de... | python|pandas|txt | 0 |
361,479 | 65,136,338 | How to print a tensor every epoch | <p>I am trying to train a keras model. I have a random integer in the model, and I would like to print it every epoch to make sure it is in fact changing.</p>
<pre><code>rand_int = tf.random.uniform((), 0, 2, dtype=tf.int32)
...
model.fit(X, y epochs = 10, batch_size = 20, validation_split=0.1)
</code></pre>
<p>How wou... | <p>You can write a custom <code>Callback</code> and use it each time an epoch ends.</p>
<pre><code>class CustomCallback(keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
rand_int = tf.random.uniform((), 0, 2, dtype=tf.int32)
print(rand_int)
model.fit(X, y epochs = 10, bat... | tensorflow|keras|tensorflow2.0 | 3 |
361,480 | 65,118,281 | Adding 2D array to DataFrame | <p>I am trying to create a DataFrame from these two lists</p>
<pre><code>a = ['a', 'b', 'c']
b = [[1,2,3], [4,5], [7,8,9]]
df = pd.DataFrame(a, columns=['First'])
df['Second'] = b
df
</code></pre>
<p>This is the output I got-</p>
<pre><code> First Second
0 a [1, 2, 3]
1 b [4, 5]
2 c [7, 8, ... | <p>What are you trying to achieve here? A column with list of numeric values that is not a list? It seems bit counter-intuitive. You can maybe convert the values to string to get rid of the so called square brackets of list representation.</p>
<pre><code>c = [", ".join(str(x) for x in y) for y in b]
df['Secon... | python|pandas | 0 |
361,481 | 65,162,138 | Time Conversions in pandas | <p><em><strong>tldr; How do I convert DateTimeIndex back to a column in a dataframe?</strong></em></p>
<p>The long explanation:</p>
<p>I have accelerometer and loadcell data for the same time period, but the timestamps for each device are in different formats and timezones. My current theory is that I need them to be i... | <p>After a great deal of fussing around the Internet, I solved my problem!</p>
<pre><code># CREATE a DateTimeIndex
pull_index = df_pull.set_index('Time').index.astype('datetime64[ns]')
# Localize time with tz
pull_index = pull_index.tz_localize('UTC').tz_convert('US/Eastern')
# Back to an naive datetimeindex! https:/... | python|pandas|datetime | 1 |
361,482 | 65,414,308 | How to turn nested dictionary into pandas dataframe? | <p>I have this nested dictionary:</p>
<pre><code>{'attrs': ('LA', 'E', 'Can', 'AP', 'ME', 'A', 'M', 'Car', 'US'),
'self': {'ac': {'AP', 'Can', 'Car', 'E', 'LA', 'M', 'ME', 'US'},
'anz': {'AP', 'E', 'US'},
'ana': {'AP', 'E', 'US'},
'aa': {'AP'},
'taag': {'A', 'AP', 'Can', 'E', 'ME', 'US'},
'bm': {'E'},
'l':... | <p>Let us try <code>explode</code> then <code>crosstab</code></p>
<pre><code>s = pd.Series(d['self']).apply(list).explode()
out = pd.crosstab(s.index,s).reindex(columns=d['attrs'],fill_value=0)
out =out.rename_axis(None).rename_axis(None,axis=1).reset_index().rename(columns={'index':'company'})
Out[193]:
company L... | python|python-3.x|pandas|dictionary | 3 |
361,483 | 65,198,908 | DateTimeIndex should be sorted, but isn't | <p>I am trying to resample a DateTime Series in pandas as follows:</p>
<pre><code>df = pd.read_csv(pathToParam + "/" + file)
df.drop(["LAT", "LON", "STATION_HEIGHT"], axis = 1, inplace=True)
df.set_index(df.DATE, inplace=True, drop=True)
if granularity == "daily":
... | <p>Most likely one of the rows in your csv has an empty value where the date should be.</p>
<p>I can recreate your problem only if I intentionally put a blank date in:</p>
<pre><code>dateSeries = ["2016-01-01", "", "2016-01-02", "2016-01-04"]
data = [[1048, 6.7], [1048, 7.8], [10... | python|pandas|dataframe | 0 |
361,484 | 65,138,642 | Cartopy:'numpy.ndarray' and 'numpy.ndarray'-Geograph plotting of population literacy | <p>Here is the data set I have and after cleaning and excluding others I make a set as such-
<a href="https://i.stack.imgur.com/yJxG8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yJxG8.png" alt="enter image description here" /></a></p>
<p>I intend to make geographical plot using <code>cartopy</cod... | <p>The issue is the data structure <code>literacy</code>. You need to pass a list or array to matplotlib.colors.Normalize. You can solve this by extracting the numerical literacy values like so:</p>
<pre><code> norm = Normalize(
vmin=min(literacy['literacy_rate']), vmax=max(literacy['literacy_rate']))
</code></p... | python|pandas|numpy|data-visualization|cartopy | 0 |
361,485 | 49,931,055 | TensorFlow model gets zero loss | <pre><code>import tensorflow as tf
import numpy as np
import os
import re
import PIL
def read_image_label_list(img_directory, folder_name):
# Input:
# -Name of folder (test\\\\train)
# Output:
# -List of names of files in folder
# -Label associated with each file
cat_label = 1
dog_l... | <p>As <a href="https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits" rel="nofollow noreferrer">documented</a>:</p>
<blockquote>
<p><code>logits</code> and <code>labels</code> must have the same shape, e.g. <code>[batch_size, num_classes]</code> and the same dtype (either <code>float16</... | python|tensorflow|cross-entropy|convolutional-neural-network | 1 |
361,486 | 50,147,967 | Dictionary data is not properly appended to another dictionay | <p>Dictionary data is not properly appended to another dictionay. Here<code>acc_grp</code> is a grouped pandas data.</p>
<p><strong>acc_grp</strong></p>
<pre><code> amount_currency balance credit debit lid
ldate
2018-04-01 ... | <p>You need to create a new dictionary for each line. Otherwise, you're always changing the very same dictionary:</p>
<pre><code> ...
for index,row in acc_grp.iterrows():
result = {} # Create a brand new dictionary
balance=0
row.balance=row.debit.... | python|python-2.7|pandas|odoo-10|pandas-groupby | 2 |
361,487 | 49,998,091 | Find if a string is in a Pandas range | <p>I am trying to figure out a way to separate values stored in a dataframe column depending on if values fall within a pre-defined range. The column is of <code>object</code> datatype and contains characters and integers. Here is an example of the data:</p>
<pre class="lang-none prettyprint-override"><code> code... | <p>You could use a regex to separate your letters and numbers, which would then allow you to apply your numeric calculations as usual:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'code': ['C92.20','C80','C12.30','C18.5','C40.5','E66.01','C78.5','L73.2','D46.22','N18.3','N18.5','M34','M37','N18.8']})
df[['L... | python|pandas|comparison | 2 |
361,488 | 50,149,391 | Copying multiple python dataframes into excel using StyleFrame's to_excel method | <p>I have multiple dataframes, df1, df2 etc. Each dataframe contains different number of columns and rows. Using the StyleFrame library, is it possible to copy all the dataframes one by one into a single sheet in an excel file using the to_excel method by specifying cell locations? Currently, here's what I am doing: </... | <p>Yes. Just like <code>pandas.to_excel</code> supports <code>startrow</code> and <code>startcol</code> arguments, so does <code>StyleFrame.to_excel</code>. </p>
<p>The API is pretty much the same as <code>pandas</code>'s:
You need to create an <code>excel_writer</code> object, call <code>to_excel</code> on both style... | excel|python-3.x|pandas|styleframe | 2 |
361,489 | 49,869,622 | Training changing input size RNN on Tensorflow | <p>I want to train an RNN with different input size of sentence X, without padding. The logic used for this is that I am using Global Variables and for every step, I take an example, write the forward propagation i.e. build the graph, run the optimizer and then repeat the step again with another example. The program is... | <p>As a general guideline, GPU boosts performance only if you have calculation intensive code and little data transfer. In other words, if you train your model one instance at a time (or on small batch sizes) the overhead for data transfer to/from GPU can even make your code run slower! But if you feed in a good chunk ... | python|numpy|tensorflow|machine-learning|rnn | 0 |
361,490 | 50,134,090 | Keras Sequential - ValueError: Error when checking target: expected dense_3 to have shape (None, 45) but got array with shape (2868700, 1) | <p>I am trying to create a simple deep neural network using the keras API but i am getting the following error:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Ali J/PycharmProjects/SPECOM/1dcnn_experiment.py", line 86, in <module>
model.fit(trainX, trainY)
File "C:\ProgramData\Anaconda3... | <p>You need to convert your targets (<code>trainY</code>) into categorical shape, meaning one-hot shape.</p>
<p>You can use this keras function:</p>
<pre><code>keras.utils.to_categorical(y, num_classes=None)
</code></pre>
<blockquote>
<p>Converts a class vector (integers) to binary class matrix.</p>
<p>E.g. f... | python|tensorflow|keras | 0 |
361,491 | 50,230,233 | How to reduce part of a dataframe colunm value based on another column | <p>I have a dataframe like this.</p>
<p>I am trying to remove the string which presents in substring column.</p>
<pre><code>Main substring
Sri playnig well cricket cricket
sri went out NaN
Ram is in NaN
Ram went to UK,US UK,US
</code></pre>
<p>My expected outupt ... | <p>This one-liner should do it:</p>
<pre><code>df.loc[df['substring'].notnull(), 'Main'] = df.loc[df['substring'].notnull()].apply(lambda x: x['Main'].replace(x['substring'], ''), axis=1)
</code></pre> | python|string|pandas|dataframe|data-analysis | 2 |
361,492 | 50,170,659 | Return cell difference in pandas dataframe | <p>Here is the code that works as expected. </p>
<p>From:
<a href="https://stackoverflow.com/questions/17095101/outputting-difference-in-two-pandas-dataframes-side-by-side-highlighting-the-d">Outputting difference in two Pandas dataframes side by side - highlighting the difference</a></p>
<pre><code>import sys
if sys... | <pre><code>df_select = df_final.copy()
df_select.columns = df_final.columns.swaplevel()
duplicate = (df_select['First'] == df_select['Second']).all(axis=1)
df_final = df_final[~duplicate]
</code></pre>
<p>Explanation:
We create a second dataframe <code>df_select</code> to select the relevant rows (and copy <code>df_fi... | python|pandas | 1 |
361,493 | 50,012,584 | pca with number of 2 componenets outputs 1 feature | <p>I have a list of 10 elements and I chose 5 features to create my input and converted the input list to an array; then I applied pca with the number of components=2:</p>
<pre><code>idx = {0, 2, 3, 7, 8}
Input = array([Input[x] for x in idx]).reshape((1, -1))
print (Input.shape) # prints (1, 5)
pca = PCA(n_component... | <p>Yes, its the expected behaviour. </p>
<p>As per the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA" rel="nofollow noreferrer">documentation for PCA</a>:</p>
<pre><code>actual n_components = min(n_samples, specified n_components)
</code></pre>
<p>... | python|numpy|scikit-learn | 1 |
361,494 | 50,212,158 | Turn a column into two columns using the values of another column (pandas) | <p>I have a dataframe that looks something like this:</p>
<pre><code>measure | location | cause | val
Deaths | Alabama |sickness1 | 0.045
Deaths | Alabama |sickness2 | 0.001
...
Prevalence| Alabama |sickness1 | 0.05
Prevalence| Alabama |sickness2 | 0.003
...
</code></pre>
<p>So, there are basical... | <p>What you are looking for is <code>pivoting</code>, but regular <code>DataFrame.pivot</code> won't do it, because you need to use multiple columns as unique indexes: <code>location</code> and <code>cause</code>.</p>
<pre><code>pd.pivot_table(df, columns=['measure'], values='val', index=['cause', 'location'],
... | python-3.x|pandas | 1 |
361,495 | 49,942,361 | Need help turning pandas dataframe into multiindex by grouping just one column. | <p>I have a pandas dataframe <code>df</code> that looks like this:</p>
<pre><code>>>>df
group A B C
1 1 2 3
1 2 3 6
1 4 9 9
2 8 1 2
2 5 6 4
3 6 5 7
</code></pre>
<p>I would like it multi-indexed so it looks like</p>
<pre><code>group
A B C
1 1 2 3
2 3 6
4 9 9
2 ... | <p><code>set_index</code> will do this for you.</p>
<pre><code>df = df.set_index('group').set_index(
df.groupby('group').cumcount(), append=True
)
df
A B C
group
1 0 1 2 3
1 2 3 6
2 4 9 9
2 0 8 1 2
1 5 6 4
3 0 6 5 7
</code></pre>
<p>Alternativ... | python|pandas|dataframe | 2 |
361,496 | 50,115,896 | Python | Combine multiple csv (100+) files from one folder taking csv header into consideration | <p>Requirement: I have a folder with multiple csv files. I need to perform following:</p>
<ol>
<li>Scan the input folder for all csv files (file1.csv, file2.csv ..... filen.csv etc) & perform below steps </li>
<li>Open the first csv file (file1.csv) & store the file header in a list & then copy the entire ... | <p>Consider using <code>pandas</code> methods to iteratively check columns and run import instead of scanning first lines with <code>csv</code>. Also, use <code>os</code> to manage the file names extract and locations with <code>shutil</code> for moving <em>done</em> files. Below builds a list of dataframes for final c... | python|pandas|csv | 0 |
361,497 | 49,808,038 | Create pandas MultiIndex from Cartesian Product but "Unfold" Several Levels in the Same way | <p>I am looking to create a MultiIndex in pandas from a Cartesian product, with the catch that one of the levels is "special" and will be associated with an arbitrary number of additional levels that I would like to "unfold" in the same way as the special level. The end result is much easier to demonstrate than describ... | <h2><code>pd.MultiIndex.from_tuples</code> v1</h2>
<pre><code>midx = pd.MultiIndex.from_tuples(
[(id[i], l, color[i], shape[i])
for i in range(len(id)) for l in loc],
names=['ID', 'LOC', 'color', 'shape']
)
df3 = pd.DataFrame(data, midx)
df3
0
ID LOC color shape ... | python|pandas | 1 |
361,498 | 50,109,015 | Filtering DataFrame based on its groups properties | <p>Let's say we have issue tracker logs and we want to find out issues owners (guys who logged the most time to the issue)</p>
<ol>
<li>User can log time multiple times to the same issue</li>
<li>If 2 users log the same time, the are both owners</li>
</ol>
<p>So we have some sample data:</p>
<pre><code>df = pd.DataF... | <p>Something along the lines of a <code>groupby</code> will work for your data:</p>
<pre><code>i = df.groupby(['IssueKey', 'User']).TimeSpent.sum()
j = i.groupby(level=0).transform('max')
i[i == j].reset_index()
IssueKey User TimeSpent
0 1 John 30
1 1 Tom 30
2 2 John ... | python|pandas|grouping | 1 |
361,499 | 49,933,425 | replace all strings to a default number in DataFrame | <p>I have a pandas DataFrame of numbers (int and floats) which results in a datatype of float for all columns. or so I thought.</p>
<p>These tables are the result of OCR scanning to EXCEL. in some case there's ascii or word values because of a bad scan.</p>
<p>How do I perform a blanket str value to default -999999... | <p>Please try</p>
<pre><code> df = df.apply(lambda x: pd.to_numeric(x, errors='coerce')).fillna(-999999)
</code></pre>
<p>The pd.to_numberic function will convert all non-parsable strings to 'NaN' and the fillna replaces those values with the given value '-999999'</p> | python|pandas | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.