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 |
|---|---|---|---|---|---|---|
17,300 | 38,816,277 | Stock Price Date adjusting in Python | <p>I would like to ask about how to adjust (delete non-duplicated ones) dates in stock prices of two different companies using pandas.</p>
<p>I have downloaded stock prices via [from yahoo_finance import Share] and let it be saved as pickle. And each "len" of dataset says different length just as I expected.</p>
<p>T... | <p>Make sure the <code>date</code>s have been parsed as Timestamps:</p>
<pre><code>df1['date'] = pd.to_datetime(df1['date'])
df2['date'] = pd.to_datetime(df2['date'])
</code></pre>
<p>Set the <code>date</code> column as the index:</p>
<pre><code>df1 = df1.set_index('date')
df2 = df2.set_index('date')
</code></pre>
... | python|pandas | 1 |
17,301 | 38,792,122 | How to group and count rows by month and year using Pandas? | <p>I have a dataset with personal data such as name, height, weight and date of birth. I would build a graph with the number of people born in a particular month and year. I'm using python pandas to accomplish this and my strategy was to try to group by year and month and add using count. But the closest I got is to ge... | <p>To group on multiple criteria, pass a list of the columns or criteria:</p>
<pre><code>df['birthdate'].groupby([df.birthdate.dt.year, df.birthdate.dt.month]).agg('count')
</code></pre>
<p>Example:</p>
<pre><code>In [165]:
df = pd.DataFrame({'birthdate':pd.date_range(start=dt.datetime(2015,12,20),end=dt.datetime(20... | python|pandas | 67 |
17,302 | 63,002,302 | why does keras give me so many weights in the array, and what are they for? | <pre><code>import tensorflow as tf
from tensorflow import keras
import numpy as np
import random
model = keras.Sequential([
keras.layers.Flatten(input_shape=(2,)),
keras.layers.Dense(20, activation=tf.nn.relu),
keras.layers.Dense(20, activation=tf.nn.relu),
keras.layers.Dense(1)
])
print(model.summa... | <p><code>model.weights</code> return all the weights. Your understanding is correct. <code>weights[0]</code> is a 2x20 set of connections & <code>weights[1]</code> is the weights for the corresponding bias. Since, you are using <code>tf.keras.layers.Dense</code> which has <code>use_bias=True</code> by default. So, ... | tensorflow|machine-learning|keras | 1 |
17,303 | 62,948,077 | How to further pretrain a bert model using our custom data and increase the vocab size? | <p>I am trying to further pretrain the bert-base model using the custom data. The steps I'm following are as follows:</p>
<ol>
<li><p>Generate list of words from the custom data and add these words to the existing bert-base vocab file. The vocab size has been increased from <code>35022</code> to <code>35880</code>.</p>... | <p>You can further pretrain a BERT model with your own data with run_mlm.py at: <a href="https://github.com/huggingface/transformers/tree/master/examples/pytorch/language-modeling" rel="nofollow noreferrer">https://github.com/huggingface/transformers/tree/master/examples/pytorch/language-modeling</a>.</p>
<p>Also look ... | python|tensorflow|nlp|pre-trained-model|bert-language-model | 1 |
17,304 | 63,202,338 | How to get top n values from data frame columns? | <p>I have a data frame as below</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
{
'rating': [5.0,4.5,3.0,2.5,4.0,4.5,5.0,3.0],
'productname': ['s','v','r','n','k','a','q','w'],
'category': [
'mobile',
'mobile',
'mobile',
'mobile',
'laptop',
'laptop',
'lapt... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nlargest.html" rel="nofollow noreferrer"><code>df.nlargest</code></a>:</p>
<pre><code>>>> df
rating productname category
0 5.0 s mobile
1 4.5 v mobile
2 3.0 r mobile
3 ... | python|dataframe|pandas-groupby | 0 |
17,305 | 62,897,550 | How to convert an object into DateTime in pandas | <p>I have a really messy file where there are datetime that I need to read and use it as an index. (I am adding this to clarify how it looks my data). My messy file were the datetime are located look like:</p>
<pre><code>31.01.2016 13:59:13 31.01.2016 13:59:13 31.01.2016 14:39:20 31.01.2016 14:39:20 31.01.2016 15:19:2... | <p>Finally I got it. I did not apply the format to the date. I used this :</p>
<pre><code>df["Date"] = pd.to_datetime(df["Date"], errors="coerce", dayfirst=True )
</code></pre>
<p>I got what I wanted, even with repeated values inside the data frame. I have to drop them.</p>
<pre><code>df =... | python|pandas|datetime|python-datetime|pandas-datareader | 1 |
17,306 | 67,749,910 | How do I get multiple outputs for 2 simultaneous equations in python? | <p>I'm trying to plot a graph with 2 simultaneous equations, but I don't need to solve them, I'm just trying to get multiple results from substitution, like when x is 1, or when y is 0.</p>
<p>My equations are <code>5x + 2y = 20</code>, <code>y = 2x + 1</code></p>
<p>All the solutions that I found are only to solve the... | <p>You are asking two different questions: how to plot and how to get values. If you are plotting, the plotting engine will supply the values, you just have to put the equations in a form that it can work with. In this case, as univariate equations.</p>
<pre><code>>>> from sympy import var, solve, Eq, plot
>... | python|numpy|matplotlib|sympy|equation | 1 |
17,307 | 67,949,482 | About tensorflow 2.3.0-rc1 | <p>I recently updated my tensorflow version to 2.3.0. When I output the version, I found it was 2.3.0-rcl. I want to know what the latter ‘rcl’ means. Thank you.</p> | <p>From comments</p>
<blockquote>
<p>It means release candidate 1, you installed a beta version of
tensorflow, not the final version (paraphrased from Dr. Snoopy)</p>
</blockquote>
<p>To install latest version, you can try as shown below</p>
<pre><code>pip install tensorflow #install TF 2.5.0
</code></pre>
<p>For speci... | tensorflow|version | 0 |
17,308 | 67,763,741 | How to pass separated tfrecord datasets: trainX (images) and trainY (labels) to model.fit()? | <h1>Problem</h1>
<p>Due to one custom layer in my model, I need to pass the labels together with images to the model during training. So this is how I called the fit method:</p>
<pre><code>history = model.fit((trainX,trainY),
trainY,
epochs=epochs,
... | <p>For the benefit of Community, I am providing the @Niel_Eenterm solution here</p>
<blockquote>
<p>I've found a solution which now solves my problem and that is to
implement a fully custom training loop using tf.GradientTape():</p>
<pre><code>@tf.function
def train_step(x, y):
with tf.GradientTape() as tape:
... | python|tensorflow|tensorflow-datasets|tfrecord | 0 |
17,309 | 67,977,760 | Is there a way to reference a previous value in Pandas column without a loop? | <p>For example if I wanted</p>
<pre><code>df = pd.DataFrame(index=range(5000)
df[‘A’]= 0
df[‘A’][0]= 1
for i in range(len(df):
if i != 0: df['A'][i] = df['A'][i-1] * 3
</code></pre>
<p>Is there a way to do this without a loop?</p> | <ul>
<li>your code sample has missing close brackets and quotes are not valid. Fixed these</li>
<li>if I understand what you are trying to achieve, multiply previous value by 3 where zeroth number is 1
<ul>
<li>initialize the series to 3, then set zeroth item to 1</li>
<li>then simple use of <a href="https://pandas.py... | python|pandas|dataframe | 0 |
17,310 | 31,843,831 | Using If/Truth Statements with pandas | <p>I tried referencing the pandas documentation but still can't figure out how to proceed.</p>
<p>I have this data</p>
<pre><code>In [6]:
df
Out[6]:
strike putCall
0 50 C
1 55 P
2 60 C
3 65 C
4 70 C
5 75 P
6 80 P
7 85 C... | <p>Typically, when you want to set values using such a if-else logic, <strong>boolean indexing</strong> is the solution (see <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">docs</a>):</p>
<p>The logic in:</p>
<pre><code>if df['strike']<100:
df['optVol'] = 1
</... | if-statement|pandas | 2 |
17,311 | 31,681,943 | (Python) ValueError: could not convert string to float: | <p>I'm having an issue with python not liking values with decimals. I believe that it wants the numbers in whole number format, not decimal...</p>
<p><strong>Error:</strong></p>
<pre><code>Traceback (most recent call last):
File "plotpoints.py", line 29, in <module>
data = np.loadtxt('/home/weather/data/m... | <p>Turn out that there were some fields that had missing data, so just used</p>
<pre><code>sed -i '/,0/d' /home/weather/data/mos/full_highs_00z
</code></pre>
<p>to delete the lines that had zeros in them!</p> | python|unix|numpy|matplotlib-basemap | 0 |
17,312 | 41,352,991 | Tensorflow AttributeError: 'DataSet' object has no attribute 'image' | <p>I am trying to use Tensorflow for the first time</p>
<p>Here is my code that I got from a tutorial:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
learn = tf.contrib.learn
tf.logging.set_verbosity(tf.logging.ERROR)
mnist = learn.datasets.load_dataset('mnist')
data = mnis... | <p>The MNIST <code>DataSet</code> object (implemented <a href="https://github.com/tensorflow/tensorflow/blob/13f9309ccb063a58b0ce34aafc23f93a49e33733/tensorflow/contrib/learn/python/learn/datasets/mnist.py" rel="noreferrer">here</a>) does not have an <code>image</code> property, but it does have <a href="https://github... | python|tensorflow | 6 |
17,313 | 41,620,975 | Predict product returns in e-commerce | <p>I was trying to build a NN model using TF by following this article on the internet <a href="http://aisel.aisnet.org/cgi/viewcontent.cgi?article=1369&context=icis2015" rel="nofollow noreferrer">link</a></p>
<p>As of now, I have been able to use some code online <a href="https://github.com/JRMeyer/tensorflow-tut... | <p>Have you tried other learning models such as a Decision Tree (and by extension Random Forest), or perhaps XGBoost? In small experiments, I found those to be better at classifying over a neural network.</p>
<p>You could also spend a few minutes reading up on feature engineering to some other ideas for getting bette... | python|tensorflow|prediction | 0 |
17,314 | 41,330,030 | Construct sequences from a dataframe using dictionaries in Python | <p>I would like to construct sequences of user's purchasing history using dictionaries in Python. I would like these sequences to be ordred by date.</p>
<p>I have 3 columns in my dataframe:</p>
<pre><code>users items date
1 1 date_1
1 2 date_2
2 ... | <p>Firstly, set <em>users</em> as the index and perform <code>groupby</code> w.r.t that. Then, you could pass a function to sort each group by it's <em>date</em> column and extract it's underlying array part using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow n... | python|pandas|dictionary|dataframe|sequences | 1 |
17,315 | 61,585,473 | ValueError: An operation has `None` for gradient - Not using Custom | <p>As per the title, I get this common error when trying to use Keras to do some Image Classification training. Unlike nearly all of the other examples, I am <em>not</em> trying to customise anything and simply using bog-standard keras functionality!
Like <a href="https://stackoverflow.com/questions/59122371/valueerror... | <p>I think the problem is that you are clearing the session before training the model, doing this would make no sense, because clearing the session cleans the model structures in memory, so there would be no model representation in the TensorFlow side, making training fail.</p>
<p>So do not juse <code>K.clear_session(... | python|tensorflow|keras | 1 |
17,316 | 68,758,927 | calculate how much percentage of the data is between two given points? | <p>I like to calculate how much percent of the data is between two given points?</p>
<p>let's say I have an array of floats:</p>
<pre><code>a = np.arange(1, 2, 0.1)
a
>>> array([1.0 , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9])
</code></pre>
<p>I would like to know how much percent of the data is between 1.2... | <p>Pretty easy:</p>
<pre><code># percentage between 1.2 and 1.7:
np.mean((a>1.2) & (a<1.7)) * 100
# percentile of 1.2:
np.mean(a<1.2) * 100
</code></pre> | python|pandas|numpy|quantile|percentile | 1 |
17,317 | 53,159,251 | Matmul Eror shape | <h2>Defining weights as variables in a linear model</h2>
<p>I'm new in tensorflow , and i ran this code using <code>tf.matmul</code>,
At first- I didn't understand why the shape in <code>matmul</code> is not good.- i fixed it with another [] int the definition of the variable.</p>
<p>now- i don't understand why it's... | <p>The issue is you're using <code>matmul</code> to multiply one-dimensional vectors. If you check the shape of <code>W</code> by <code>W.get_shape()</code>, it will return (1,) while it should be a 2D matrix of shape (1,1). You can do this by simply adding brackets: <code>W = tf.Variable([[.3]], tf.float32)</code>.<... | python|tensorflow | 0 |
17,318 | 53,284,814 | How to randomly throw numbers in a 2D dimensional board | <p>I have a 50x50 2D dimensional board with empty cells now. I want to fill 20% cells with 0, 30% cells with 1, 30% cells with 2 and 20% cells with 3. How to randomly throw these 4 numbers onto the board with the percentages?</p>
<pre><code> import numpy as np
from numpy import random
dim = 50
map = [[" "for i... | <p>One way to get this kind of randomness would be to start with a random permutation of the numbers from 0 to the total number of cells you have minus one.</p>
<pre><code>perm = np.random.permutation(2500)
</code></pre>
<p>now you split the permutation according the proportions you want to get and treat the entries ... | python|numpy | 2 |
17,319 | 53,082,643 | A tedious loop looking for improvements | <p>in my code I need to calculate the values of a vector many times which are the mean values from different patches of another array.
Here is an example of my code showing how I do it but I found that it is too less-efficient in running...</p>
<pre><code>import numpy as np
vector_a = np.zeros(10)
array_a = np.random... | <p>EDIT:</p>
<p>Actually you can do this much faster. The previous function can be improved by operating on summed columns like this:</p>
<pre><code>def rolling_means_faster1(array_a, n, first, size):
# Sum each relevant columns
sum_a = np.sum(array_a[:, first:(first + size + n - 1)], axis=0)
# Reshape as... | python|loops|numpy|coding-efficiency | 3 |
17,320 | 65,497,726 | Replace and remove text in a column | <p>I would like to:</p>
<ol>
<li>delete the words "ANOS" and "ANO";</li>
<li>replace "A" to "TO"; and</li>
<li>replace "<1ano" to "0 to 1".</li>
</ol>
<p>Example: "10 A 19 ANOS" to "10 to 19"</p>
<pre><code>data = pd.DataFrame({'FAIXA_E... | <p>here's one possible way:</p>
<pre><code>data["FAIXA_ETARIA"] \
.str.replace(r"ANO\w?", "") \ # Regex for ANO plus an optional single character
.str.replace(r"A", "TO") \ # Replace a single character
.str.replace(r"<\w?", "0 to 1") #... | python|pandas | 1 |
17,321 | 65,675,732 | Torch, how to use Multiple GPU for different dataset | <p>Assume that I have 4 different datasets and 4 GPU like below</p>
<p>4 dataset</p>
<pre><code>dat0 = [np.array(...)], dat1 = [np.array(...)] , dat2 = [np.array(...)] , dat3 = [np.array(...)]
</code></pre>
<p>4 GPU</p>
<pre><code>device = [torch.device(f'cuda:{i}') for i in range(torch.cuda.device_count())]
</code></... | <p><em><strong>Assuming</strong></em> you only need <code>ans</code> for inference. You can easily perform those operations but you will certainly need function <code>f</code> to be on all four GPUs at the same time.</p>
<p>Here is what I would try: duplicate <code>f</code> four times and send to each GPU. Then compute... | pytorch|torch|torchvision | 1 |
17,322 | 21,382,521 | Good way to implement a normalize filter in numpy | <p>I'm not so familiar with the memory model of Numpy arrays. Is there a more efficient way (or a 'better practice' way) of computing a normalized version of an image? That is, the image such that for each pixel <code>r+g+b == 1</code>.</p>
<p>Using a more matrix oriented approach perhaps? Does such a filter have a na... | <p>This would be done much more efficiently taking advantage of numpy's <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcasting rules</a> </p>
<pre><code>>>> import numpy as np
>>> image = np.random.random(size=(3,4,5))
>>> sums = image.sum(axis=2... | python|image-processing|numpy|scipy | 4 |
17,323 | 20,973,527 | Compute daily climatology using pandas python | <p>I am trying to use pandas to compute daily climatology. My code is:</p>
<pre><code>import pandas as pd
dates = pd.date_range('1950-01-01', '1953-12-31', freq='D')
rand_data = [int(1000*random.random()) for i in xrange(len(dates))]
cum_data = pd.Series(rand_data, index=dates)
cum_data.to_csv('test.csv', sep... | <p>You can groupby the day of the year, and the calculate the mean for these groups:</p>
<pre><code>cum_data.groupby(cum_data.index.dayofyear).mean()
</code></pre>
<p>However, you have the be aware of leap years. This will cause problems with this approach. As alternative, you can also group by the month and the day:... | python|pandas|time-series | 8 |
17,324 | 63,689,052 | Convert timedelta to decimal [Pandas] | <p>I would like to convert <code>time_delta</code> to <code>float</code> in Pandas:</p>
<p>Main_df</p>
<pre><code>date time_delta
2019-01-01 01:30:07.502101
2019-01-01 02:00:00.134445
2019-01-01 01:45:02.949292
2019-01-01 00:30:06.393828
</code></pre>
<p>Ouput_df</p>
<pre><code>date time_... | <p>This should do it:</p>
<pre><code>df['time_delta'] = (df['time_delta'].dt.total_seconds()/3600).round(2)
</code></pre> | python|pandas | 1 |
17,325 | 63,487,367 | Python - Convert JSON into table structure | <p>I wrote a python script to download synonyms from an API and put it into a df.</p>
<pre><code>import requests
import pandas as pd
import json
Result = []
Begriffe = ['See','Meer','Katze']
for Begriff in Begriffe:
# Make a get request to get the latest position of the international space station from the op... | <pre><code>df[["term", "terms"]].to_csv('file_name', sep='\t')
</code></pre> | python|json|pandas | 0 |
17,326 | 63,435,169 | Validation accuracy zero and Loss is higher. Intent classification Using LSTM | <p>I'm trying to Build and LSTM model for intent classification using Tensorflow, Keras. But whenever I'm training the model with 30 or 40 epochs, my 1st 20 validation accuracy is zero and loss is more than accuracy. and if I try to change the code a little bit, validation accuracy is getting lower than Loss.</p>
<pre>... | <p>There can be multiple reasons for the validation accuracy to be zero, you can check on these below things to make changes accordingly.</p>
<ol>
<li>The samples you had taken are very less, train on 200 samples and validate on 79 samples, you can try increasing samples through some upsampling methods.</li>
<li>There ... | tensorflow|lstm|text-classification|tf.keras | 1 |
17,327 | 63,648,469 | inplace replacement works for object but not string dtype | <p>Replace method on object dtype yields different result than on string dtype. I was expecting same result. I'm running Pandas 1.1.0 on Python 3.8.5.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
a = pd.DataFrame({'a':['a','b','c'],'b':['d','','']},dtype='object')
b = pd... | <p>This is a confirmed bug. See <a href="https://github.com/pandas-dev/pandas/issues/35977" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/35977</a></p> | python|pandas|dataframe|replace | 0 |
17,328 | 21,885,135 | Choosing random one from each row of a binary numpy matrix? | <p>Suppose I have a binary matrix. I would like to cast that matrix into another matrix where each row has single one and the index of that one would be random for each row.</p>
<p>For instance if one of the row is <code>[0,1,0,1,0,0,1]</code> and I cast it to <code>[0,0,0,1,0,0,0]</code> where we select the 1's inde... | <p>Extending @zhangxaochen's answer, given a random binary array</p>
<pre><code>x = np.random.random_integers(0, 1, (8, 8))
</code></pre>
<p>you can populate another array with a randomly drawn 1 from <code>x</code>:</p>
<pre><code>y = np.zeros_like(x)
ind = [np.random.choice(np.where(row)[0]) for row in x]
y[range(... | python|numpy|matrix | 3 |
17,329 | 24,543,187 | Count nan in data string with python | <p>I am trying to count 'nan' in my data file.</p>
<p>For this purpose, I have used two codes
one is:</p>
<pre><code>with open(filin,'r') as f:
arrays = [map(float, line.split(',')) for line in f]
newa = [x[6] for x in arrays]
</code></pre>
<p>The other is:</p>
<pre><code>for columns in ( raw.strip().split(','... | <p>Maybe change this</p>
<pre><code>newa = np.array(a)
</code></pre>
<p>to this:</p>
<pre><code>newa = np.array(a).astype(float)
</code></pre>
<p>or just:</p>
<pre><code>newa = newa.astype(float)
</code></pre> | python|string|numpy|count|nan | 3 |
17,330 | 24,460,725 | Python Pandas Reading CSV file with Specific Line Terminators | <p>I am trying to create a dataframe from the below sample csv I've been given but I am getting Error tokenizing data. C error: EOF inside string starting at line 0. I haven't had very much practise with treating bad lines but would really like to learn the best way to handle something like this. I have attempted many ... | <p>I had a similar error. Fixed it by using the option quoting=csv.QUOTE_NONE in read_csv.</p>
<p>For example:</p>
<pre><code>df = pd.read_csv(csvfile, header = None, delimiter="\t", quoting=csv.QUOTE_NONE, encoding='utf-8')
</code></pre>
<p>Some info about why in the second comment here: <a href="https://github.co... | python|pandas | 4 |
17,331 | 30,028,103 | Cython Class, create NumPy with Zeros | <p>i am trying to create a cython class which creates a NumPy with zeros. Later i want to write float values in that Numpy...
My python class looks like this:</p>
<pre><code>class test:
def __init__(self, b):
self.b = b
self.eTest = np.zeros((100, 100))
</code></pre>
<p>My cython class looks like th... | <p>Redefine your class::</p>
<pre><code> cdef class test:
cdef double[:,:] eTest
def __init__(self, b):
cdef np.ndarray[FTYPE_t, ndim=2, mode='c'] tmp
tmp = np.zeros((100,100), dtype=FTYPE)
self.eTest = tmp
</code></pre>
<p>Your ndarray (<code>tmp</code> in this case) can only be local to a fun... | python|performance|numpy|optimization|cython | 2 |
17,332 | 53,460,174 | Converting time stamp to to_date in pandas | <p><a href="https://i.stack.imgur.com/B4i8l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B4i8l.png" alt="Input"></a>I am building and app for sql query genreation , i am able to generate it but receiving output in timestamp format , please help in converting it to to_date format.
Here is my code:-... | <p>If you must manually stitch together SQL query strings, try this (untested since I don't have your data):</p>
<pre><code>import pandas as pd
table_name = 'ADI'
df = pandas.read_excel('supermarke.xlsx')
def SQL_Insert(SOURCE, TARGET):
sql_texts = []
for index, row in SOURCE.iterrows():
formatted_dat... | pandas | 0 |
17,333 | 15,936,732 | Converting empty strings to 0 using Numpy | <p>I have a numpy array where each element looks something like this:</p>
<pre><code>['3' '1' '35' '0' '0' '8.05' '2']
['3' '1' '' '0' '0' '8.4583' '0']
['1' '1' '54' '0' '0' '51.8625' '2']
</code></pre>
<p>I would like to replace all empty strings like the ones in the second row above, with some default value like 0... | <p>If your array is t:</p>
<pre><code>t[t=='']='0'
</code></pre>
<p>and then convert it.</p>
<p><strong>Explanation:</strong></p>
<p><code>t==''</code> creates a boolean array with the same shape as <code>t</code> that has a True value where the corresponding <code>t</code> value is an empty space. This boolean arr... | python|numpy | 18 |
17,334 | 72,071,405 | 'module' object is not callable sgd | <p>Here is my code.</p>
<pre><code>from keras.optimizers import gradient_descent_v2 as SGD
sgd=SGD(lr=0.01,momentum=0.9,decay=(0.01/25),nesterov=False)
</code></pre>
<p>I get the following error when I try to run it.</p>
<pre><code>----> 1 sgd=SGD(lr=0.01,momentum=0.9,decay=(0.01/25),nesterov=False)
Type... | <p>You do not need to use the <code>gradient_descent_v2</code> to import SGD optimizer.</p>
<p>Now, <a href="https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/SGD" rel="nofollow noreferrer">SGD</a>(Stochastic Gradient Descent) optimizer inherits from <strong>tf.keras.optimzers</strong>, which you can impor... | python|tensorflow|keras | 0 |
17,335 | 72,113,727 | Find index of row from df for which |df$col1-df2$col1| = min|dist|. Then find max value of col2 from df in the range [idx-5;idx+5] | <p>I have two data frames <code>df1</code> and <code>df2</code>.</p>
<p><code>df1</code> has two columns. I'd like to find the index <code>idx</code> of <code>row</code> from <code>df1</code>, that contains in <code>col1</code> the minimum distance from the value of <code>df2 col1</code>.</p>
<p>Next, I want to find th... | <p>Assuming <code>df1</code> is already sorted on column <code>A</code>, Lets use <code>searchsorted</code> to get the indices of closest values in <code>A</code> corresponding to the values from <code>A1</code> , then make sure to clip the indices where the index value equal to length of <code>df1</code>. Now, do a ce... | python|pandas|dataframe | 1 |
17,336 | 71,895,854 | Is it possible in Python to load a large object into memory with one process, and access it in separate independent processes? | <p>I'm writing a program that requires running algorithms on a very large (~6GB) csv file, which is loaded with pandas using read_csv().
The issue I have now, is that anytime I tweak my algorithms and need to re-simulate (which is very often), I need to wait ~30s for the dataset to load into memory, and then another 30... | <p>Found a solution that worked, although it was not directly related to my original ask.</p>
<p>Instead of loading a large file into memory and sharing between independent processes, I found that the bottleneck was really the parsing function in pandas library.
Particularly, CSV parsing, as CSVs are notoriously ineffi... | python|pandas|memory|process | 1 |
17,337 | 16,716,302 | How do I fit a sine curve to my data with pylab and numpy? | <p>I am trying to show that economies follow a relatively sinusoidal growth pattern. I am building a python simulation to show that even when we let some degree of randomness take hold, we can still produce something relatively sinusoidal.</p>
<p>I am happy with the data I'm producing, but now I'd like to find some way... | <p>Here is a parameter-free fitting function <code>fit_sin()</code> that does not require manual guess of frequency:</p>
<pre><code>import numpy, scipy.optimize
def fit_sin(tt, yy):
'''Fit sin to the input time sequence, and return fitting parameters "amp", "omega", "phase", "offset", "freq", "period" and "fitfun... | python|numpy|matplotlib|curve-fitting | 91 |
17,338 | 19,222,711 | Python histogram with points and error bars | <p>I want to plot a histogram with points and error bars. I do not want bar or step histograms. Is this possible? Google has not helped me, I hope you can. Also it should not be normalized. Thanks!</p> | <p>Assuming you're using numpy and matplotlib, you can get the bin edges and counts using <code>np.histogram()</code>, then use <code>pp.errorbar()</code> to plot them:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as pp
x = np.random.randn(10000)
counts,bin_edges = np.histogram(x,20)
bin_centres = ... | python|numpy|matplotlib|histogram|point | 2 |
17,339 | 22,173,448 | numpy savetxt: save a matrix as row | <p>I'm using numpy <code>savetxt()</code> to save the elements of a matrix to file as a single row (I need to print lots of them in order). This is the method I've found:</p>
<pre><code>import numpy as np
mat = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
with open('myfile.dat','a') as hand... | <p>OK. My original code for printing as an array only works if you want to print once. The <code>mat.reshape()</code> method doesn't just return the reshaped matrix it alters m<code>mat</code> itself. This means the next time through the loop any <code>linalg</code> routines will fail.</p>
<p>To avoid this we need ... | python|python-3.x|numpy|matrix | 0 |
17,340 | 22,054,978 | compare all x with in a group in dfA to all possible y's in the same group in dfB using pandas python | <p>How do i compare all x values for a case in a dataset to every possible y value for a case in another dataset? that is, compare all x's to y's in these dataframes (df.A and df.B) which are duplicated by case.
dfA</p>
<pre><code> case x
0 A 1
1 B 2
2 B 3
3 B 4
4 C 5
[5 rows x 2 columns]
</cod... | <p>I think -- if I understand the problem correctly -- all you need is <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging" rel="nofollow">pd.merge</a> (and maybe a call to <code>sort</code>):</p>
<pre><code>import pandas as pd
import datetime as DT
dfA = pd.Data... | python|pandas | 1 |
17,341 | 22,276,503 | How do I change data-type of pandas data frame to string with a defined format? | <p>I'm starting to tear my hair out with this - so I hope someone can help. I have a pandas DataFrame that was created from an Excel spreadsheet using openpyxl. The resulting DataFrame looks like:</p>
<pre><code>print image_name_data
id image_name
0 1001 1001_mar2014_report
1 1002 1002_mar2014_repor... | <p>I'm unable to reproduce your problem but have you tried converting it to an integer first?</p>
<pre><code>image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
</code></pre>
<p>Then, regarding your more general question you could use <code>map</code> (<a href="https://stackoverflow.com/questions/... | python|string|floating-point|pandas|format | 62 |
17,342 | 55,468,850 | Unable to read excel files from set of folder using pandas | <p>I am trying to read excel files from a folder using xlrd but an extra file is being created with extension <code>".~.Lock.example1.xlsm"</code> which is eventually giving <code>xlrderror :unsupported file format</code>.When i try to read individual files everythig is fine.
my folder files are: <code>example1.xlsm, ... | <p>One way to work this out is to add these into your code so it only read excel files, instead of every files in the folder.</p>
<pre><code>for f1 in files:
if f1.endswith(".xlsx"):
#Do something with f1
</code></pre>
<p>Also, I find <code>os.walk(path)</code> very useful if you want to find all the file... | python|pandas | 0 |
17,343 | 55,191,280 | How can I split my normalization in two according to column values? | <p>HI I have a column data in pandas with a hugely skewed distribution:
<a href="https://i.stack.imgur.com/yyw1x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yyw1x.png" alt="data distribution"></a></p>
<p>I split the data in two according to a cutoff value of 1000 and this is the distribution of ... | <p>It's not pretty, but works.</p>
<pre><code>df = pd.DataFrame({'dataExample': [0,1,2,1001,1002,1003]})
less1000 = df.loc[df['dataExample'] <= 1000]
df.loc[df['dataExample'] <= 1000, 'datanorm'] = less1000['dataExample'] / (less1000['dataExample'].max() * 2)
high1000 = df.loc[df['dataExample'] > 1000]
df.... | python-3.x|pandas|normalization|distribution | 0 |
17,344 | 56,694,039 | How can I use lambdify to evaluate my function? | <p>I have an expression with several variables, let's say something like below:</p>
<pre><code>import numpy as np
import sympy as sym
from sympy import Symbol, Add, re, lambdify
x = sym.Symbol('x')
y = sym.Symbol('y')
z = sym.Symbol('z')
F = x+ y +z
</code></pre>
<p>I have three lists for the variables like below:</... | <pre><code>import sympy as sp
x = sp.Symbol('x')
y = sp.Symbol('y')
z = sp.Symbol('z')
X = [3, 2 ,3]
Y = [4, 5 , 6]
Z = [7, 10 ,3]
values = list(zip(X, Y, Z))
f_dis = sp.lambdify([x, y, z], x + y + z, 'numpy')
ans = [f_dis(*value) for value in values]
for d in ans:
print ( "f_dis =", d)
</code></pre>
<p>t... | python|numpy|symbols|sympy|lambdify | 5 |
17,345 | 56,601,506 | How to vectorize in Pandas when values depend on prior values | <p>I'd like to use Pandas to implement a function that keeps a running balance, but I'm not sure it can be vectorized for speed.</p>
<p>In short, the problem I'm trying to solve is to keep track consumption, generation, and the "bank" of over-generation. </p>
<p>"consumption" means how much is used in a given time p... | <p>Here is a numpy-ish approach, mostly because I'm not that familiar with pandas:</p>
<p>The idea is to first compute the free <code>cumsum</code> and then to subtract the cumulative minimum if it is negative.</p>
<pre><code>import numpy as np
import pandas as pd
id = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,... | pandas|numpy|signal-processing | 3 |
17,346 | 66,784,496 | Program calculating tax rate per line item equaling into VAT | <p>I have the following df:</p>
<pre><code> quantity#1 unit price#1 line amount#1 line amount#2 line amount#3 line amount#4 VAT
-- ------------ -------------- --------------- --------------- --------------- --------------- -----
0 nan nan 5 ... | <p>You have 3 different tax rates and 4 line amounts per row, so it can be one of 3**4 = 81 combinations. We can calculate total VAT for each combination, and then find the combination that matches the VAT from the dataframe:</p>
<pre><code>from itertools import product
# get all possible tax rate combinations
x = [0.... | python|pandas|dataframe | 2 |
17,347 | 67,118,615 | How to calculate the weighted average from three stocks | <p>I am trying to 'calculate the weighted return for my portfolio assuming assuming an equal number of shares for each stock'. I am looking at three stocks.</p>
<p>I combined all three stocks as so:</p>
<pre><code>my_portfolio = pd.concat([appl_df, cost_df, goog_df], axis='columns', join='inner')
my_portfolio.columns =... | <p>Try normalizing each of the three stocks to a maximum ceiling value like a percentage or something.</p> | python|pandas|numpy | 0 |
17,348 | 66,893,150 | Append dataframe to CSV file automatically | <p>I have a script which gets a range of tweets and converts these to a dataframe. I would like to run this every 2 hours using cron, and append the results to one CSV. However, I am having trouble with the appending part. This is the code I used to try it:</p>
<pre><code>import csv
df
with open(r'name of csv', 'a')... | <p>I think you need to use <code>writer.writerows(df)</code> rather than <code>writer.writerow(df)</code> if your <code>df</code> object stores more than one dataframes. Please refer to this <a href="https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows" rel="nofollow noreferrer">link</a>. Therefore, chang... | python|pandas|csv|twitter | 0 |
17,349 | 67,141,395 | Assigning labels each cycle of a for loop | <p>Similarly to these questions, <a href="https://stackoverflow.com/questions/16327055/how-to-add-an-empty-column-to-a-dataframe">How to add an empty column to a dataframe?</a> and <a href="https://stackoverflow.com/questions/55303976/adding-a-new-column-to-a-df-each-cycle-of-a-for-loop">Adding a new column to a df eac... | <p>Keep a copy of original index. After adding new rows to dataframe, use boolean indexing to assign new rows <code>Label</code> column to <code>0</code>.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [5,6,7]}) # Sample DataFrame
df['Label'] = 1
origin_... | python|pandas|for-loop|indexing | 1 |
17,350 | 47,255,640 | Pandas read multiple CSV files, compute percent change for a column in each file | <p>I have a series of CSV files in multiple locations, but all folders have the same format below where the only difference in folder name is the asset/symbol being used. So I'm trying to use a wildcard (% assets) to search for each folder, <strong>as well as the most recent file in that folder</strong>. I then want to... | <p>The main problem here is how you're reading your files. If you want to load every single file, you probably don't want to use things like <code>max</code> there. Furthermore, <code>string % Assets</code> is going to insert a stringified version of the list as-is, without any intricate substitution as you'd expect.</... | python|pandas|dataframe | 1 |
17,351 | 47,106,678 | Multiplication and Division of elements in a numpy array gives integer results | <pre><code>import numpy as np
A = np.array([[2,1,-1,8],
[-3,-1,2,-11],
[-2,1,2,-3]])
B = A[1]+A[0]* (-A[1][0]/A[0][0])
print(B) #B =[ 0. 0.5 0.5 1. ]
A[1] = A[1]+A[0]* (-A[1][0]/A[0][0])
print(A[1]) #A[1] = [0 0 0 1]
</code></pre>
<p>How does the above situation happen, and what can I do about ... | <p>Use <code>dtype=float</code> in main array. Your array is integer by default.</p>
<pre><code>import numpy as np
A = np.array([[2,1,-1,8],
[-3,-1,2,-11],
[-2,1,2,-3]], dtype=float)
B = A[1] + (A[0]*(-A[1,0]/A[0,0]))
print(B)
A[1] = A[1] + (A[0]*(-A[1,0]/A[0,0]))
print(A[1])
#Output:
#[ 0. 0.5 0... | python|numpy | 3 |
17,352 | 68,353,385 | Need help on creating a conditional statement in pandas | <p>Can anyone tell me what's wrong about this pandas conditional statement?
</p>
<pre><code>dfm_Final['Pass'] = np.where(
dfm_Final['Percent_change'] >= 0.8 * dfm_Final['Agg_Percent_change'] &
dfm_Final['Percent_change'] <= 1.25 * dfm_Final['Agg_Percent_change'], True, False)
</code></pre>
<p>I'm try... | <p>like mentioned in comment, you don't need np.where, also use <code>()</code></p>
<pre><code>dfm_Final['Pass'] =
(dfm_Final['Percent_change'] >= 0.8 * dfm_Final['Agg_Percent_change']) &
(dfm_Final['Percent_change'] <= 1.25 * dfm_Final['Agg_Percent_change'])
</code></pre> | pandas|dataframe|conditional-statements | 0 |
17,353 | 68,328,344 | separate a column by groups | <p>This is how my data looks:</p>
<p><a href="https://i.stack.imgur.com/tqKF1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tqKF1.png" alt="enter image description here" /></a></p>
<p>This is the code I have come up with:</p>
<pre><code>surgery_types = ["Ascendensvervanging", "AVR&qu... | <p>Try:</p>
<p>boolean masking,<code>loc</code> accessor and <code>str.contains()</code>:</p>
<pre><code>m=df['Surgery Type'].str.contains('|'.join(surgery_types),case=False)
#created a boolean mask
df.loc[~m,'Surgery Type']='other_types'
#pass that boolean mask(opposite) and changed value
</code></pre>
<p>OR</p>
<p>bo... | python|pandas|dataframe | 1 |
17,354 | 59,454,733 | Generating Dataframe from JSON URL in a column in another DataFrame | <p>I am trying to generate one dataframe based on Json Url in another Dataframe called Data</p>
<pre><code>import requests
import pandas as pd
import numpy as np
resp = requests.get('https://financialmodelingprep.com/api/v3/company/stock/list')
txt = resp.json()
Data = pd.DataFrame(txt['symbolsList'])
Data = Data.ass... | <p>This code can work.</p>
<pre><code>import pandas as pd
import requests
resp = requests.get('https://financialmodelingprep.com/api/v3/company/stock/list')
txt = resp.json()
Data = pd.DataFrame(txt['symbolsList'])
def get_value(symbol):
resp_keymetric = requests.get(f'https://financialmodelingprep.com/api/v3/co... | python|json|pandas|dataframe|for-loop | 1 |
17,355 | 59,470,762 | I am trying to find all rows that have values between 0-500, 500-5000, 5000-35000, 35000-65000, >60000 | <pre><code>import pandas as pd
df = pd.read_csv('/Users/gfidarov/Desktop/daylite/export_daylite_v0.2.csv')
#print(df)
df1 = df[df['Итог'] >'60000']
a = len(df1)
df5 = df[df['Итог'].isin(['40565', '60000'])]
f = len(df5)
df2 = df[df['Итог'].isin(['5000', '35000'])]
b = len(df2)
df3 = df[df['Итог'].isin(['500', '5000... | <p>You could consider using <code>pd.cut</code> as following</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
lst = [44300, 23400, 4050, 31230, 12, 45333,
12341, 64500, 3430, 13, 95844, 330, 2,
32, 78, 0]
df = pd.DataFrame({"a":lst})
bins = [0, 500, 5000, 35000... | python|pandas|csv|dataframe | 0 |
17,356 | 45,261,479 | How do I calculate the number of consecutive columns with zero values from the right until the first non zero element occurs | <p>Suppose I have the following dataframe: </p>
<pre><code> C1 C2 C3 C4
0 1 2 3 0
1 4 0 0 0
2 0 0 0 3
3 0 3 0 0
</code></pre>
<p>Then I want to add another column such that it will display the number of zero valued column that occur contiguously from the right.
The new column would be: </... | <p>You can use:</p>
<ul>
<li>reverse order by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> and <code>[::-1]</code></li>
<li>get <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.cumsum.html" rel=... | python|pandas|sum|reverse|cumsum | 5 |
17,357 | 56,899,158 | Pandas implode Dataframe with values separated by char | <p>I was just wondering how is the best approach to implode a DataFrame with values separated by a given char.</p>
<p>For example, imagine this dataframe:</p>
<pre><code>A B C D E
1 z a q p
2 x s w l
3 c d e k
4 v f r m
5 b g t n
</code></pre>
<p>And we want to i... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferrer"><code>DataFrame.agg</code></a> with <code>join</code>, then convert <code>Series</code> to one row <code>DataFrame</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api... | python|python-3.x|pandas|dataframe | 2 |
17,358 | 56,914,862 | Deleting rows in pandas unitil the specific value first occurred | <p>I would like to delete the rows that users equal to 1 first occurred and its previous rows for each unique user in the DataFrame.</p>
<p>For instance, I have the following Dataframe, and I would like to get another dataframe which deletes the row in the "val" column 1 first occured and its previous rows for each us... | <p><code>groupby</code> checking <code>cummax</code> and <code>shift</code> to remove all rows before, and including, the first <code>1</code> in the <code>'val'</code> column per user.</p>
<p>Assuming your values are either 1 or 0, also possible to create the mask with a double cumsum.</p>
<pre><code>m = df.groupby(... | python|pandas | 2 |
17,359 | 56,931,803 | In 1D array 'a' find indexes of 'a' at which 'a'='b', where 'b' are random values of 'a' | <p>This is my first attempt to use Python. I would appreciate any advice on how to post process data using Python.</p>
<p>I have a 2D array with two columns that consists of numbers: <code>a</code> and <code>c</code>. In addition, I have 1D array <code>b</code> that consists of some specific (and exact) values of <cod... | <p>I think that you want to do something like </p>
<pre><code>import numpy as np
arr = np.array([[1, 20], [40, 70], [83, 67], [1054,90]])
b = np.array([40, 1054])
output = []
for value in b:
a_indexes = np.where(arr == value)
for a_index in a_indexes[0]: # we look where the value was found along first dimen... | python|arrays|numpy | 0 |
17,360 | 46,016,091 | Sum all integers in a PANDAS DataFrame "cell" | <p>I have a PANDAS DF object where each "cell" is a list of tuples: </p>
<pre><code>d = {"seen":[[('A', 4)], [], [('B', 4), ('C',3)], [('A', 1), ('C',4)]],\
'unseen':[[('B', 2), ('C',2)], [('A', 4), ('B', 2), ('C',2)], [('A', 4)],
[('C',1)]]}
df = pd.DataFrame(d)
df
</code></pre>
<p>this is the result: </p>
<pr... | <p>Let's use <code>df.agg</code>, lambda functions with a custom name, and <code>map</code> <code>join</code> to flatten multiindex column.</p>
<pre><code>count_f = lambda x: x.str.len()
count_f.__name__ = '_count'
sum_f = lambda x: sum(i[1] for i in x)
sum_f.__name__ = '_sum'
df2 = df.agg([count_f, sum_f])
df2.colum... | python|python-3.x|pandas | 5 |
17,361 | 35,609,812 | Syntax for Passing Args to a Pandas Dataframe apply function | <p>My problem is here:
<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html#pandas.Series.apply" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html#pandas.Series.apply</a>. </p>
<p>If you have</p>
<pre><code>def subtract_custom_value(x, cu... | <p>They didn't choose anything like that. As stated in the docs you linked, <code>args</code> is expected to be a tuple. Use a tuple (or another kind of iterable) and it might work, provided the number and type of its elements are suitable. Use something that is not a iterable and it won't work. Use invalid python synt... | python|pandas|syntax|apply | 3 |
17,362 | 35,623,776 | Import NumPy on PyCharm | <p>I'm trying to import NumPy on PyCharm.</p>
<p>Using the PyCharm terminal and Miniconda I've launched the command:</p>
<pre class="lang-none prettyprint-override"><code>conda install numpy
</code></pre>
<p>And this was the output:</p>
<pre><code>Fetching package metadata: ....
Solving package specifications: ........... | <p>Go to</p>
<ol>
<li>ctrl-alt-s</li>
<li>click "project:projet name"</li>
<li>click project interperter</li>
<li>double click pip</li>
<li>search numpy from the top bar</li>
<li>click on numpy</li>
<li>click install package button</li>
</ol>
<p>if it doesnt work this can help you:</p>
<p><a href="https://www... | python|python-3.x|numpy|pycharm | 64 |
17,363 | 50,951,644 | pass a list as argument of the func1d in numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs) | <p>I don't manage to pass a list as arguments to func1d in numply.apply_along_axis(...).</p>
<pre><code>def test(a, value):
print(value)
return a
a = np.zeros((49), dtype=list)
kwargs = {"value":[1,1,1]}
zep = np.vectorize(test)
np.apply_along_axis(zep, 0, a, **kwargs)
</code></pre>
<p>Out: </p>
<pre><code... | <p>As I commented, neither <code>vectorize</code> or <code>apply...</code> is a speed tool. <code>vectorize</code> can be useful for broadcasting several arrays against each other. <code>apply ...</code> can be useful for iterating over more than 2 dimensions. With only one or two it is overkill. Both are tools tha... | python-3.x|numpy | 0 |
17,364 | 20,406,399 | Exporting a 2D array with 0-values into a txt/csv file | <p>I have a 100x100 array which I would like to export as either a txt or csv file. The elements of the array are all 0 and a few other integer numbers. When using the following code, the integer numbers are exported properly, but the zeros are replaced by random numbers with giganormous exponents (1.98E-258). Does any... | <p>That's actually a really small number ... But what you need to do is tell numpy that the array will be filled with integers, not floats:</p>
<pre><code>#or np.int32, np.int64, np.uint8 ... depending on desired range.
my_array=np.zeros((100,100), dtype=int)
</code></pre>
<p>While we're at it, I used <code>np.zeros<... | python|arrays|numpy | 4 |
17,365 | 33,383,182 | Importing TIFF images into NumPy array using base modules | <p>I need to read tiff images into a NumPy array. However, as much as I would like to use PIL/Pillow, or MatPlotLib, to do this, I cannot. I am limited to the base python modules in python 2.6, since that is what is installed on the system that will execute on and I do not have sufficient privileges to install new mo... | <p>First, <strong>don't mess with the system Python</strong> or complain that you cannot. That is just an imaginary problem. Whether you are using Linux or Mac, the system Python encironment is needed by the operating system. Even if you did have sudo rights you shouldn't touch it because the integrity of the operating... | python|numpy|tiff | 1 |
17,366 | 66,607,008 | Multi-year time series charge with shaded range in python | <p>I have these charts that I've created in Excel from dataframes of a structure like such:</p>
<p><a href="https://i.stack.imgur.com/IC57L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IC57L.png" alt="enter image description here" /></a></p>
<p>so that the chart can be created like this, stacking ... | <p>Two step process</p>
<ol>
<li>restructure DF so that years are columns, rows indexed by uniform date time</li>
<li>plot using <strong>matplotlib</strong></li>
</ol>
<pre><code>import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# straight date as index, quantity as column
d = pd.... | python|pandas|matplotlib | 2 |
17,367 | 66,414,160 | How can I get the difference of the values of the rows in a dataframe? (for customer code) | <p>My dataset has Customer_Code, As_Of_Date and 24 products. The products have a value of 0 -1. I ordered the data set by customer code and as_of_date. I want to subtract from the next row in the products to the previous row. The important thing here is to get each customer out according to their as_of_date.</p>
<p>I t... | <p>You didn't share any data so I made up something that you may use. Your expected outcome also lacks. For further reference, please do not share images. Let's say you have this data:</p>
<pre><code> id date product
0 12 2008-01-01 1
1 12 2008-01-01 2
2 12 2008-01-01 1
3 ... | python|pandas|dataframe | 0 |
17,368 | 66,610,487 | Dice outcome evaluation based on bias | <p>I am trying to determine throw of dices on a bias condition, during implementing its code, i am facing this error (code and error):</p>
<pre><code>from numpy import random
def roll(N,bias):
'''will return the dice outcome'''
return random.choice(np.range(N),p=bias)
>>N= 50
>>bias= (0.25, 0.2, 0.15, ... | <p>Really?</p>
<pre><code> return random.choice(np.arange(N),p=bias)
</code></pre>
<p><strong>Edit</strong><br />
I misunderstood the requirement. You want this to return the results of N rolls.</p>
<pre><code>def roll(N,bias):
return (random.choice(range(len(bias)),p=bias)+1 for _ in range(N))
</code></pre> | python|function|numpy|random|return | 1 |
17,369 | 66,688,013 | Python - Differential equation solver for time-dependent coefficients gives different dynamics for different time offsets | <p>I am solving the dynamics of a system when it interacts with a pulse, which basically is solving a time-dependent differential equation. In general it works fine, but whenever I take the bandwidth of the pulse small, i.e. around unity, the solver depends on where the pulse starts t0.
Let me give you the code and som... | <p>This is a well-known behavior, there have been several questions on this topic.</p>
<p>In short, it is the step size controller. The assumption behind it is that the ODE function is smooth to a high order, and that local behavior informs the global behavior in a medium range. Thus if you start flat, with vanishing h... | python|numpy|scipy|solver|differential-equations | 2 |
17,370 | 66,544,994 | How to include a OneHot in an ONNX coming from PyTorch | <p>I'm using PyTorch to train neural-net and output them into ONNX. I use these models in a <a href="https://vespa.ai" rel="nofollow noreferrer">Vespa</a> index, which loads ONNXs through TensorRT. I need one-hot-encoding for some features but this is really hard to achieve within the Vespa framework.</p>
<p>Is it poss... | <p>So, according to my testing, PyTorch does support one-hot encoding export to ONNX. With the following model:</p>
<pre><code>#! /usr/bin/env python3
import torch
import torch.onnx
import torch.nn.functional as F
class MyModel(torch.nn.Module):
def __init__(self, classes=5):
super(MyModel, self).__init_... | pytorch|one-hot-encoding|onnx|vespa | 2 |
17,371 | 16,081,797 | Diagonal Matrix Exponential in Python | <p>I'm writing a numerical algorithm with speed in mind. I've come across the two matrix exponential functions in scipy/numpy (scipy.linalg.expm2, scipy.linalg.expm). However I have a matrix that I know to be diagonal beforehand. Do these scipy functions check if the matrix is diagonal before they run? Obviously the e... | <p>If a matrix is diagonal, then its exponential can be obtained by just exponentiating every entry on the main diagonal, so you can calculate it by:</p>
<pre><code>np.diag(np.exp(np.diag(a)))
</code></pre> | python|matrix|numpy|scipy|exponential | 4 |
17,372 | 57,512,596 | How to generate sequence data with keras with multiple input? | <p>I'm writing a VAE for sequence to sequence problem in keras. The decoder is an auto-regressive model so I have two different inputs, one for the encoder and the same (shifted by 1, but this is not the problem) for the decoder.
I want also to do data augmentation so I decide to use the fit_generator() method but I ha... | <p>You should return a <strong>tuple</strong> from generator/Sequence instance. The first element of the tuple is a list of input arrays (or just one array if your model has one input layer), and the second element is a list of output arrays (or just one array if your model has one output layer).</p>
<p>Therefore, <co... | python|tensorflow|keras|generator|autoregressive-models | 5 |
17,373 | 57,540,261 | Drop all rows in Pandas DataFrame where value is NOT NaN | <p>I can remove all rows with nan in a column with this line:</p>
<pre><code>df2 = df.dropna(subset=['columnA'])
</code></pre>
<p>How do I remove all rows that have values <strong>other than</strong> NaN?</p> | <p>You can do <code>drop</code></p>
<pre><code>df2 = df.dropna(subset=['columnA'])
df1 = df.drop(df2.index)
</code></pre> | python|pandas | 8 |
17,374 | 57,315,069 | Outlier detection approach with smaller datasets | <p>I have a python function that takes a list of smaller images <code>boxes</code> (represented as arrays) and the whole image <code>img</code> in as a parameter and finds outliers. The outliers will either be significantly brighter or darker than the other images in the list, but darker is the more common case.</p>
<... | <p>Rather than finding outliers in the list of boxes, we calculate the lower and upper boundaries <em>with respect to the whole image</em> and any boxes with average gray values outside these boundaries are considered as outliers:</p>
<pre><code>def find_outliers(boxes, img):
q1, q3 = np.percentile(img, [25,75])
... | python|numpy|opencv|comparison|outliers | 1 |
17,375 | 73,079,270 | how do i get rid of a key error in jupyter notebook? | <p>otherwise when i remove the inplace=true, it works just fine
here is the code:
in: x=df1.drop('Outcome', axis=1, inplace=True)
y=df1['Outcome']</p>
<p>out: KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, metho... | <p>Have you understood what <code>inplace=True</code> does ?</p>
<pre><code>x=df1.drop('Outcome', axis=1, inplace=True)
</code></pre>
<p>creates an empty object x (because <code>df1.drop('Outcome', axis=1, inplace=True)</code> works by side effect so returns nothing) AND will drop the <code>Outcome</code> column of the... | python-3.x|pandas|data-science | 0 |
17,376 | 73,110,831 | Group bar chart after using .loc and .groupby in pandas | <p>Need to draw a grouped bar chart of the following data set.The volume of name product in each location on daily data set.For the group bar chart, x-axis needs to be week and y-axis needs to volume and used group by to name and hue needs the location.</p>
<pre><code>new.loc[(new['Volume'] !=0)].groupby('name')['Volum... | <p>If using pandas's plotting doesn't work, are you opposed to using Seaborn and Matplotlib.pyplot? If not, you can try something like this:</p>
<pre class="lang-py prettyprint-override"><code>########### Create mock dataframe ##############
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
Volu... | python|pandas|data-visualization|data-analysis | 1 |
17,377 | 73,021,649 | I want to change a number with 5 decimal places in the form "yyyy-mm-dd hh:mm:ss." | <p>I want to change the data 20220718.20154 to 2022-07-18 20:15:40 in dataframe.
So I wrote the code below.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
pd.options.display.float_format = '{:.6f}'.format
df = pd.read_excel(filepath)
df["date"] = pd.to_datetime(df["date"].a... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.ljust.html" rel="nofollow noreferrer"><code>Series.str.ljust</code></a> for add <code>0</code> if less like 15 characters from left side:</p>
<pre><code>df["date"] = pd.to_datetime(df["date"].astype(str).str.... | python-3.x|pandas|datetime | 0 |
17,378 | 73,129,665 | How to merge rows with same id in python? | <p>I have a pandas DataFrame with the following property, How Can I merge rows with same id in python?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">id</th>
<th style="text-align: center;">test1</th>
<th style="text-align: right;">test2</th>
</tr>
</thead>
<tbody... | <p>Here is one way:</p>
<pre class="lang-py prettyprint-override"><code>df = df.groupby('id', sort=False).max().reset_index()
</code></pre>
<p>Input:</p>
<pre><code> id test1 test2
0 one 10.0 NaN
1 one NaN 30.0
2 two NaN 3.0
3 three 10.0 5.0
</code></pre>
<p>Output:</p>
<pre><code>... | python|pandas|dataframe | 0 |
17,379 | 73,159,541 | plotting graph of day from a years data | <p>So I have a dataset that has electricity load over 24 hours:</p>
<pre><code>Time_of_Day = loadData.groupby(loadData.index.hour).mean()
Time_of_Day
Time Load
2019-01-01 01:00:00 38.045
2019-01-01 02:00:00 30.675
2019-01-01 03:00:00 22.570
2019-01-01 04:00:00 22.153
2019-01-01 05:00:00 21.085
... .... | <p>With the following toy dataframe:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import random
df = pd.DataFrame({"Time": pd.date_range(start="1/1/2019", end="12/31/2019", freq="H")})
df["Load"] = [round(random.random() * 100, 2) for _ in ra... | python|pandas|numpy | 1 |
17,380 | 73,140,107 | Saving numpy array to GIF using PIL | <p>I'm trying to save a series of numpy arrays to a gif using PIL.</p>
<p>When I initialise each frame as a white background (before adding to the frame) for some reason it only saves the first image.</p>
<p>However, when the frame is initialised randomly the whole gif is saved.</p>
<p>Can anyone explain what the probl... | <p>There was a bug in my code where I was adding to the frame. As a result each of the frames was identical. If PIL detects that the next image is identical then it clearly doesn't append it. Hence why I ended up with just one frame, and why the example above with the same blank image each time also just returns one im... | python|numpy|python-imaging-library | 1 |
17,381 | 72,869,255 | Scraping Issue while extracting data from the source | <p>I am trying to scrape :- <a href="https://www.adsbhub.org/station.php?id=2018" rel="nofollow noreferrer">https://www.adsbhub.org/station.php?id=2018</a> using selenium and I am able to do so.</p>
<p>Is there any alternative for selenium in this case as we are not allowed to use selenium where I am working?</p>
<p>I ... | <p>you could try changing the <code>df</code> line to this:</p>
<pre class="lang-py prettyprint-override"><code>df= pd.read_csv('link', on_bad_lines='skip')
</code></pre>
<p>But this means that the lines that cause errors will be skipped, so if you need those lines this probably wont work for you.</p> | javascript|python|pandas|selenium|beautifulsoup | 0 |
17,382 | 70,543,793 | how to use if something in dataframe after groupby? | <p>This is my code, that works until <code>df=pd.df</code>, and if I try to <code>print((df.loc[("invoice type")])</code> before the if, the code works, but when i use the if gives me the error <code>"Key Error: ´type´"</code>
when I <code>groupby</code> the column name type appears below the other ... | <p>First of all, you don't want to use <code>df[type]</code> - you want to use either <code>df['type']</code> (note the quotes) or <code>df.type</code>.</p>
<p>Secondly, you can check <code>if "your string" in df.your_column</code>. You need to use <code>df.your_column.str.contains("your string")</c... | python|pandas|string|dataframe|if-statement | 1 |
17,383 | 70,447,794 | Pandas merge with "left" option is losing rows in left data frame | <p>I have 2 dataframes.
The first (left) dataframe has 5,000,000 rows, second has only 47,000 rows.
When I try to merge these dataframes with "left" option I get only 47.000 rows.</p>
<pre><code>first = pd.read_csv('first.csv')
second = pd.DataFrame(first['id'])
second.drop_duplicates(inplace=True)
second['ma... | <p>I don't see any issue with code, so you need to look into the data:</p>
<pre><code>import pandas as pd
import numpy as np
import sys
print('python version ', sys.version)
def get_mark(x):
# just random data
return np.random.normal(x, 2)
# Simulate data
first_series = np.random.randint(0, 47000, 5000000)
... | python|pandas|dataframe|merge | 0 |
17,384 | 43,013,446 | How to prepare data for training and data for predict? | <p>I'm new in TensorFlow and Machine Learning (python also).
In first step to create an image recognition program, i was hit the wall of confusion in feeding data preparation. Can someone please help me on this?
I was look into this tutorial, but the data preparation is obfuscated.
<a href="https://github.com/tensorfl... | <p>It's important to understand the error, you say</p>
<blockquote>
<p>But the problem is the predict line always raise an error of "Can not
feed value of shape...." no matter what shape my testing data is
(2352,), (1, 2352) (it's ask for (3670, 2352) shape, but no way)</p>
</blockquote>
<p>Oh yes way my friend... | python|tensorflow | 0 |
17,385 | 42,619,947 | How to apply lambda function to timestamp column in pandas dataframe | <p>I have dataframe with a timestamp column and iam using lambda function to that column. When i am doing that i am getting the following error:</p>
<pre><code>row['date'] = pd.Timestamp(row['date']).apply(lambda t: t.replace(minute=15*(t.minute//15)).strftime('%H:%M'))
AttributeError: 'Timestamp' object has no attri... | <p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> for convert column to <code>datetimes</code> instead <code>Timestamp</code> - it convert only <a href="http://pandas.pydata.org/pandas-docs/stable/timeserie... | python|pandas | 1 |
17,386 | 42,617,620 | Plot all the values in a row against the index in pandas | <p>I have a daframe <code>df</code>:</p>
<pre><code> beat1 beat2 beat3 beat4 beat5 beat6 beat7 beat8 beat9
0 0.6839 0.8879 0.7543 0.4805 0.8528 0.6982 0.5520 0.6154 0.6579
1 1.0380 0.4868 0.3099 0.4994 0.7509 0.4649 0.5080 0.4040 0.7537
2 0.7116 0.8063 0.6754 0.7365 0.... | <p>You can apply the scatter plot to each row:</p>
<pre><code>df.apply(lambda x: plt.scatter(x.index, x, c='g'))
plt.show()
</code></pre> | python|pandas|dataframe | 2 |
17,387 | 42,812,682 | How can I sort values within a Dask dataframe group? | <p>I have this code which generates autoregressive terms within each unique combination of variables 'grouping A' and 'grouping B'.</p>
<pre><code>for i in range(1, 5):
df.loc[:,'var_' + str(i)] = df.sort_values(by='date']) \
.groupby(['grouping A', 'grouping B']) \
... | <h3>Dask.delayed</h3>
<p>So if you want to just parallelize the for loop you might do the following with dask.delayed</p>
<pre><code>ddf = dask.delayed(df)
results = []
for i in range(1, 5):
result = ddf.sort_values(by='date']) \
.groupby(['grouping A', 'grouping B']) \
['target']... | python|pandas|dataframe|sorting|dask | 4 |
17,388 | 42,760,926 | Replace value in column dataframe python | <p>Let's assume the dataframe below : df</p>
<pre><code>Code Type
14 . House
15 . Flat
15 Flat
15. House
16 . Elevator
17 . Flat
</code></pre>
<p>I would like to do do something like that:</p>
<pre><code>if df.code = 15, df.type.replace = flat
if df.code = 1... | <p>df.Type.replace({'flat': 'house' }, inplace=True) works! – </p> | python|loops|pandas|replace | 0 |
17,389 | 14,631,139 | Pandas Rolling Computations on Sliding Windows (Unevenly spaced) | <p>Consider you've got some unevenly time series data:</p>
<pre><code>import pandas as pd
import random as randy
ts = pd.Series(range(1000),index=randy.sample(pd.date_range('2013-02-01 09:00:00.000000',periods=1e6,freq='U'),1000)).sort_index()
print ts.head()
2013-02-01 09:00:00.002895 995
2013-02-01 09:00:00.003... | <p>You can solve most problems of this sort with cumsum and binary search.</p>
<pre><code>from datetime import timedelta
def msum(s, lag_in_ms):
lag = s.index - timedelta(milliseconds=lag_in_ms)
inds = np.searchsorted(s.index.astype(np.int64), lag.astype(np.int64))
cs = s.cumsum()
return pd.Series(cs.... | python|pandas | 11 |
17,390 | 25,170,864 | Precision error in numpy.var | <p>I am trying the following code for estimating the variance in a sample, and compare it to the numpy.var implementation.</p>
<pre><code>import numpy as np
def rcov(xj, (i, Mi, Si)):
j = i + 1
Mj = Mi + (xj - Mi) / j
Sj = Si + (i/j) * (xj - Mi) ** 2
return (j, Mj, Sj)
def mycov(X):
... | <p>For the sake of speed, NumPy does not check for arithmetic overflow or underflow. It's the user's responsibility to choose dtypes which are large enough to maintain the desired level of precision throughout all computations. </p>
<p>Using NumPy 1.8, and selecting <code>X</code> to be of dtype <code>longdouble</code... | numpy|numerical-methods|floating-point-precision|variance | 3 |
17,391 | 30,366,142 | Finding very large jumps in data | <p>I need to find very large jumps only so that I can find clusters and later the noise as well. The sample data is as under:</p>
<pre><code>0.000000
0.000500
0.001500
0.003000
0.005500
0.008700
0.012400
0.000000
0.000500
0.001500
0.003000
0.005500
0.008700
0.012400
0.000000
0.000500
0.001500
0.003000
0.005500
0.00870... | <p>First, you should visualise your problem to get a better understanding what's going on:</p>
<pre><code>import matplotlib.pyplot as plt
data = (0.000000, 0.000500, 0.001500, 0.003000, 0.005500, 0.008700,
0.012400, 0.000000, 0.000500, 0.001500, 0.003000, 0.005500,
0.008700, 0.012400, 0.000000, 0.00050... | python|numpy|outliers | 6 |
17,392 | 30,332,683 | Changing pandas group column throws warning | <p>In the following piece of code, I group the points of a DataFrame by their X value into <em>bins</em>. Now I want to assign a group ID to the Y column, but pandas keep throwing me a warning of type <code>SettingWithCopyWarning</code>. What am I doing wrong?</p>
<pre class="lang-py prettyprint-override"><code>import... | <p>There are two issues here. First, you are getting a <code>SettingWithCopyWarning</code> because </p>
<pre><code>group["gid"][:] = gid
</code></pre>
<p>uses "chained-indexing". The problem is that sometimes <code>group[...]</code> may return a <em>copy</em> instead of a <em>view</em> of <code>group</code>, and so f... | python|pandas | 1 |
17,393 | 26,475,863 | len() compared with __len__ on numpy array | <p>What is going on here? How can I check that <code>a</code> has length? </p>
<pre><code>>>> import numpy as np
>>> a = np.array(3)
>>> hasattr(a , '__len__')
True
>>> len(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: len() of un... | <p>Hm, maybe I am missing something here, but why don't you check for types?</p>
<pre><code>import numpy as np
def make_ary(item):
if not isinstance(item, list):
ary = np.array([item])
else:
ary = np.array(item)
ary = ary.ravel()
return ary
</code></pre>
<p>And then:</p>
<pre><co... | python|python-2.7|numpy | 1 |
17,394 | 39,202,580 | Obtaining a pandas dataframe from a dict with tuples as keys | <p>I am new to python and have been struggling with this problem for quite a while. I have a dict like this:</p>
<p><code>dict1 = {(a,a) : 5, (a,b) :10, (a,c) : 11, (b,a): 4, (b,b) : 8, (b,c) : 3....}</code></p>
<p>What I would like to do is convert this into a pandas dataframe that looks like this:</p>
<pre><code> ... | <p>You're almost there, just need to <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-stacking-and-unstacking" rel="nofollow noreferrer">unstack</a>:</p>
<pre><code>dataset.unstack()
</code></pre>
<p>I prefer to use this <a href="https://web.archive.org/web/20161029015223/http://nikgro... | python-2.7|pandas|dictionary | 4 |
17,395 | 39,401,709 | Python list or pandas dataframe arbitrary indexing and slicing | <p>I have used both R and Python extensively in my work, and at times I get the syntax between them confused.</p>
<p>In R, if I wanted to create a model from only <strong><em>some</em></strong> features of my data set, I can do something like this:</p>
<pre><code>subset = df[1:1000, c(1,5,14:18,24)]
</code></pre>
<p... | <p>In a file of <code>index_tricks</code>, <code>numpy</code> defines a class instance that converts a scalars and slices into an enumerated list, using the <code>r_</code> method:</p>
<pre><code>In [560]: np.r_[1,5,14:18,24]
Out[560]: array([ 1, 5, 14, 15, 16, 17, 24])
</code></pre>
<p>It's an instance with a <code... | python|r|pandas|numpy|slice | 3 |
17,396 | 13,079,852 | How do I stack two DataFrames next to each other in Pandas? | <p>I have two sets of stock data in DataFrames:</p>
<pre><code>> GOOG.head()
Open High Low
Date
2011-01-03 21.01 21.05 20.78
2011-01-04 21.12 21.20 21.05
2011-01-05 21.19 21.21 20.90
2011-01-06 20.67 20.82 20... | <p>pd.concat is also an option</p>
<pre><code>In [17]: pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)
Out[17]:
GOOG AAPL
Open High Low Open High Low
Date
2011-01-03 21.01 21.05 20.78 596.48 605.59 596.48
2011-01-04 21.12 21.20 21.05 605.62 60... | python|pandas | 9 |
17,397 | 29,329,725 | Pandas and Matplotlib - fill_between() vs datetime64 | <p>There is a Pandas DataFrame:</p>
<pre><code><class 'pandas.core.frame.DataFrame'>
Int64Index: 300 entries, 5220 to 5519
Data columns (total 3 columns):
Date 300 non-null datetime64[ns]
A 300 non-null float64
B 300 non-null float64
dtypes: datetime64[ns](1), float64(2)... | <p><a href="https://github.com/pydata/pandas/blob/master/pandas/tseries/converter.py#L27" rel="noreferrer">Pandas registers a converter</a> in <code>matplotlib.units.registry</code> which converts a number of datetime types (such as pandas DatetimeIndex, and numpy arrays of dtype <code>datetime64</code>) to matplotlib ... | python|pandas|matplotlib | 36 |
17,398 | 33,569,590 | Numba'fied function evaluates differently in for loop then pure Python one | <p>I'm using numba to speed up functions including many for loops. Than they are called in outside for loop.</p>
<p>One of the functions evaluates differently to not jited one when called in loop.</p>
<p>The function:</p>
<pre><code>def collison(u, v, f, feq, omega, w, cx, cy, n, m):
for i in range(0, n):
... | <p>In the jitted function <code>rho</code> is taken as constant at the moment Numba compiles the function. This is different from the non-jitted function that always considers the updated <code>rho</code>.</p>
<p>See <a href="http://numba.pydata.org/numba-doc/dev/user/faq.html#numba-doesn-t-seem-to-care-when-i-modify-... | python|numpy|numba | 3 |
17,399 | 23,663,626 | Element in array is masked or no | <p>I need to check a single element in a numpy array, I need to know if it is masked the element.</p>
<pre><code>y,x=np.mgrid[slice(0,25, 1),slice(0,43, 1)]
z=pp[y,x,_mapa_]
z = np.ma.masked_where(_mascara<0.5,z)
for _x in range(24,0,-1):
for _y in range(0,43,1):
print z[-_x,_y] NEED TO NO... | <p>I resolve</p>
<p>to check one element in array is:</p>
<pre><code>z[-_x,_y].mask give me true
</code></pre>
<p>Sorry this not resolve the question. Give me elements that have mask, but elements that not have mask not give me False.</p>
<p>Ok I find a solution</p>
<pre><code>z[-_x,_y] is np.ma.masked with thi... | python|arrays|numpy | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.