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
2,900
25,190,349
Non-reducing variant of the ANY() function that respects NaN
<p>Hard to explain in words but the expample should be clear:</p> <pre><code>df = DataFrame( { 'x':[0,1], 'y':[np.NaN,0], 'z':[0,np.NaN] }, index=['a','b'] ) x y z a 0 NaN 0 b 1 0 NaN </code></pre> <p>I want to replace all non-NaN values with a '1', if there is a '1' anywhere in that row. Just like thi...
<p>You could combine a multiplication by zero (to give an empty frame but which remembers nan locations) with an <code>add</code> on <code>axis=0</code>:</p> <pre><code>&gt;&gt;&gt; df x y z a 0 NaN 0 b 1 0 NaN &gt;&gt;&gt; (df * 0).add(df.any(1), axis=0) x y z a 0 NaN 0 b 1 1 NaN </code></pr...
python|pandas
1
2,901
39,022,027
Address of last value in 1d NumPy array
<p>I have a 1d array with zeros scattered throughout. Would like to create a second array which contains the position of the last zero, like so:</p> <pre><code>&gt;&gt;&gt; a = np.array([1, 0, 3, 2, 0, 3, 5, 8, 0, 7, 12]) &gt;&gt;&gt; foo(a) [0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3] </code></pre> <p>Is there a built-in NumPy...
<pre><code>&gt;&gt;&gt; (a == 0).cumsum() array([0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]) </code></pre>
python|arrays|numpy
8
2,902
39,110,507
Call a C++ function from Python and convert a OpenCV Mat to a Numpy array
<p><strong>Background situation</strong></p> <p>I'm trying to use the OpenCV Stitching module via the Python bindings, but I'm getting an error:</p> <pre><code>import cv2 stitcher = cv2.createStitcher(False) imageL = cv2.imread("imageL.jpg") imageC = cv2.imread("imageC.jpg") imageR = cv2.imread("imageR.jpg") stitch...
<p>You need to convert the Python NDArray &lt;=> C++ cv::Mat. I can recommend this <a href="https://github.com/Algomorph/pyboostcvconverter" rel="noreferrer">GitHub Repo</a>. It contains an example that should fit to your needs. I am using the converter on Ubuntu 15.10 with Python 2.7/3.4 and OpenCV 3.1.</p>
python|c++|opencv|numpy|boost
7
2,903
29,298,757
Find Two Sets of Python Numpy Arrays on Common Column
<p>I'm trying to merge some data and I have the following two 2d numpy arrays (<strong>a</strong> and <strong>b</strong>)</p> <pre><code>a = [[ 10 9.689474368e-04][ 20 6.88780375e-04] [ 30 4.296339997e-04][ 40 -1.06232578e-03] [ 50 -1.219884414e-03][ 60 -1.27936723e-03]] b = [[ 30 6.687897...
<p>Here is a solution I would expect to be quite fast, especially on presorted data.</p> <pre><code>import numpy as np a = np.array([[ 20 ,6.88780375e-04], [ 30 , 4.296339997e-04],[ 40 , -1.06232578e-03], [ 50 ,-1.219884414e-03],[ 60 , -1.27936723e-03],[ 10 ,9.689474368e-04],]) b = np.array([[ ...
python|arrays|numpy|merge
1
2,904
22,554,116
How to use a list of values to select rows from a pandas Dataframe in specific order
<p>If I have a pandas Dataframe like this:</p> <pre><code>&gt;&gt;&gt; df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]}) &gt;&gt;&gt; df A B 0 5 1 1 6 2 2 3 3 3 4 5 </code></pre> <p>And I want to select some values in a list of values with specific order. It may look like this:</p> <pre>...
<pre><code>In [134]: df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]}, index=list('abcd')) In [135]: df Out[135]: A B a 5 1 b 6 2 c 3 3 d 4 5 [4 rows x 2 columns] In [138]: idx = pd.Index(df['A']).get_indexer([3,4,5]); idx Out[138]: array([2, 3, 0]) In [136]: df.iloc[idx] Out[136]: A B c 3 3 d...
python|pandas
6
2,905
13,478,597
Arithmetic on date series (not an index) in Pandas
<p>(Python 2.7, Pandas 0.9)</p> <p>This seems like a simple thing to do, but I can't figure out how to calculate the difference between two date columns in a dataframe using Pandas. This dataframe already has an index, so making either column into a DateTimeIndex is not desirable. </p> <p>To convert each date column ...
<p>Update: A useful workaround is to just smash this with the DatetimeIndex constructor (which is usually much faster than an apply), for example:</p> <pre><code>DatetimeIndex(df['Created_Date']).day </code></pre> <p>In 0.15 this will be vailable in the dt attribute (along with other datetime methods):</p> <pre><cod...
python|pandas
6
2,906
29,620,694
Matlab freqz function in Python
<p>I am trying to implement a Python equivalent for the Matlab frequency response function</p> <pre><code>[h,f] = freqz(b, 1, 512, 12.5) </code></pre> <p>described in <a href="http://se.mathworks.com/help/signal/ug/frequency-response.html" rel="nofollow">here</a>. My current attempt</p> <pre><code>f, h = scipy.signa...
<p>In both languages <code>freqz</code> expects numerator coefficients <code>b</code> for the first argument, not <code>a</code> like you wrote. Should be</p> <p><code>freqz(b, a, ...)</code></p> <p>Looks like you are trying to find the response of an FIR filter, for which there are only numerator coefficients and <c...
python|matlab|numpy|scipy|signal-processing
1
2,907
29,352,705
python pandas TimeStamps to local time string with daylight saving
<p>I have a dataframe with a TimeStamps column. I want to convert it to strings of local time, ie with daylight saving. </p> <p>So I want to convert ts[0] below to "2015-03-30 <strong>03</strong>:55:05". Pandas seems to be aware of DST, but only when you call .values on the series.</p> <p>Thanks</p> <pre><code>(Pdb)...
<p>DST is relative to your location (e.g. London DST began a few weeks after NY). You first need to make the timestamp timezone aware: </p> <pre><code>from pytz import UTC from pytz import timezone import datetime as dt ts = pd.Timestamp(datetime.datetime(2015, 3, 31, 15, 47, 25, 901597)) # or... ts = pd.Timestamp('...
python|pandas|timestamp|dst
13
2,908
62,387,610
Common values between multiple dataframes with different length
<p>I have 3 huge dataframes that have different length of values</p> <p>Ex, </p> <pre><code>A B C 2981 2952 1287 2759 2295 2952 1284 2235 1284 1295 1928 0887 2295 1284 1966 1567 1928 1287 2374 2846 ...
<p>Idea is create <code>Series</code> with index filtered by indexing with length of array:</p> <pre><code>a = np.intersect1d(df1.A, np.intersect1d(df2.B, df3.C)) df1['Common'] = pd.Series(a, index=df1.index[:len(a)]) </code></pre> <p>If same DataFrame:</p> <pre><code>a = np.intersect1d(df1.A, np.intersect1d(df1.B, ...
python|python-3.x|pandas
2
2,909
62,411,460
Python Conditional Statement
<p>Let's say I have 3 columns. They are 'Word', 'Word Count', and 'Positive'. The column 'Positive' is categorical by year. I need to find the most frequent words that are categorized by 'Positive'. When I use this code:</p> <pre class="lang-py prettyprint-override"><code>df.sort_values(by=['Positive', 'Word Count', '...
<p>I can't easily provide an example without an example of your data structure, but I think what you're looking for is a combination of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pd.groupby()</code></a> to group everything by year, ...
python|pandas|dataframe|subset
0
2,910
62,156,152
Why do i get different accuracies on sparse_categorical_accuracy and val_sparse_categorical_accuracy when i pass in the same data
<p>I used the same dataset for training and validating my model and yet i get different training and validation accuracy/loss. shouldn't the accuracy/loss be the same since i'm using the same data?</p> <p>Here is the code:</p> <pre><code>def create_model(dataset): model = tf.keras.models.Sequential([tf.keras.laye...
<p>This is because <code>Dropout</code> layers doesn't work while validation. Also <em>train accuracy</em> is a mean average of all batch accuracies, while <em>validation one</em> is an accuracy of whole dataset.</p>
python|tensorflow|machine-learning|keras
1
2,911
62,393,656
One Hot Encoding with Sparse categorical entropy throwing error
<p>So I am doing the MNIST Fashion example for Keras. And in the program I wrote for it, I didn't need to use "to_categorical" to one hot encode my data, and it still worked. When i tried to one hot encode it, it did not work. I am confused why this happened, because usually one should one hot encode their outputs righ...
<p>You were using sparse-categorical-crossentropy instead of categorical-crossentropy. Sparse uses integer encoding whereas the other one uses one hot encoding. You should either use sparse and not one hot your labels, or use the other and one hot encode the labels</p>
tensorflow|keras|conv-neural-network|mnist|one-hot-encoding
0
2,912
51,252,460
Pivot dataframe with columns constant withing the index column
<p>Suppose I have the following dataframe, where both <code>Y</code> and <code>Z</code> are constant within <code>ID</code>:</p> <pre><code> ID TYPE X Y Z 0 1 A 1 foo 10 1 1 B 2 foo 10 2 2 A 3 bar 20 3 2 B 4 bar 20 4 3 A 5 baz 30 5 3 B 6 baz 30 </code></pre> <p>...
<p>I just had a better look at this and the function <code>pandas.DataFrame.pivot()</code> is actually performing as expected. Unlike Stata's <code>reshape</code>, which is a <em>command</em> and does quite a few things under the hood, <code>pivot()</code> simply re-arranges the data. </p> <p>@Heleemur's solution is c...
python|pandas|dataframe|stata
3
2,913
51,119,246
create structured numpy array in python with strings and int
<p>i have this: </p> <pre><code>&gt;&gt;&gt; matriz [['b8:27:eb:d6:e3:10', '0.428s', '198'], ['b8:27:eb:d6:e3:10', '0.428s', '232'], ['b8:27:eb:07:65:ad', '0.796s', '180'], ['b8:27:eb:07:65:ad', '0.796s', '255'], dtype='&lt;U17']` </code></pre> <p>but i need the column </p> <pre><code...
<pre><code>In [484]: x = np.array([['b8:27:eb:d6:e3:10', '0.428s', '198'], ...: ['b8:27:eb:d6:e3:10', '0.428s', '232'], ...: ['b8:27:eb:07:65:ad', '0.796s', '180'], ...: ['b8:27:eb:07:65:ad', '0.796s', '255']], ...: dtype='&lt;U17') ...: ...
python|arrays|python-3.x|numpy
1
2,914
48,425,964
How to convert a list of lists into a unique Pandas DataFrame column?
<p>For a list as:</p> <pre><code>L = [[0,1,1,0], [0,1,1,1], [1,0,0,1], [1,1,0,0], ] </code></pre> <p>And I want to make a <code>DataFrame</code> as:</p> <pre><code> Column Name 0 [0,1,1,0] 1 [0,1,1,1] 2 [1,0,0,1] 3 [1,1,0,0] </code></pre> <p>The reason is that each in...
<p>You have to read the list as a indexed <code>dictionary</code> formed by the list of values:</p> <pre><code>import pandas as pd L = [[0,1,1,0], [0,1,1,1], [1,0,0,1], [1,1,0,0], ] Df = pd.DataFrame({i:[vals] for i,vals in enumerate(L)},index=['Column Name']).T </code></pre> <p>It will returns:<...
python|pandas|dataframe|merge
0
2,915
48,138,218
tensorflow value error with sess.run()
<p>I tried to play with tensorflow a bit but it seems like I am doing something wrong, the little program I made:</p> <pre><code>import tensorflow as tf x = tf.placeholder(tf.float64) y = tf.placeholder(tf.float64) test = {"A":tf.Variable(tf.random_normal([20, 20])), "B":tf.Variable(tf.random_normal([20, 20]...
<p>The <code>feed_dict</code> should contain numerical values, <strong>not</strong> <code>tf.Variable</code>. Replace your definition of <code>test</code> with:</p> <pre><code>test = {"A":np.random.randn(20,20), "B":np.random.randn(20,20)} </code></pre> <p>Also you should <code>import numpy as np</code> at t...
python|numpy|tensorflow
3
2,916
48,388,616
Create a new data frame based on conditions from columns of a given dataframe
<p>I have following data frame,</p> <p>df.head()</p> <pre><code>UID Timestamp Weekday Business_hour AAD 2017-07-11 09:31:44 TRUE TRUE AAD 2017-07-11 23:24:43 TRUE FALSE AAD 2017-07-12 13:24:43 TRUE TRUE SAP 2017-07-23 14:24:34 FALSE FALSE SAP 2017-07-24 16:58:49 TRUE TRUE YAS 2017-07-31 21:10...
<p>You could calculate them one by one like this:</p> <pre><code>data.Timestamp = pd.to_datetime(data.Timestamp) data['date' ] = [x.date() for x in data.Timestamp] target_df = pd.DataFrame() target_df['UID'] = data.UID.unique() a = data.groupby(['UID', 'date']).size() a = a[a&gt;1] target_df['Active'] = [True if x ...
python|pandas|numpy|group-by
1
2,917
48,354,243
tensorflow estimator from_generator, how to set TensorShape?
<p>I am trying use a generator to feed data into estimator. The following is the code. However, when try to run, I got the following error:</p> <p>Update2: I finally made it work. So the correct tensorshape is ([], [], [])</p> <p>Update: I added tensorshape ([None], [None], [None]), then I changed ds.batch(10), to...
<p>As mentioned by @FengTian in an update, the correct answer was to use shape <code>([], [], [])</code> as the output shape of the generator:</p> <pre class="lang-py prettyprint-override"><code>tf.data.Dataset.from_generator(lambda: gen(n), (tf.int64, tf.string, tf.float32), ([], [], [])) </code></pre>
tensorflow|generator|tensorflow-estimator
1
2,918
48,069,000
Writing value to given filed in csv file using pandas or csv module
<p>Is there any way you can write value to specific place in given .csv file using pandas or csv module?</p> <p>I have tried using csv_reader to read the file and find a line which fits my requirements though I couldn't figure out a way to switch value which is in the file to mine.</p> <p>What I am trying to achieve ...
<p>You can try this way to operate the specified csv file</p> <pre><code>import pandas as pd a = ['one','two','three'] b = [1,2,3] english_column = pd.Series(a, name='english') number_column = pd.Series(b, name='number') predictions = pd.concat([english_column, number_column], axis=1) save = pd.DataFrame(...
python|excel|pandas|csv
0
2,919
48,503,051
New docs representation in doc2vec Tensorflow
<p>I trained doc2vec model in TensorFlow. So now I have embeded vectors for words in dictionary and vectors for the documents. </p> <p>In the paper </p> <pre><code>"Distributed Representations of Sentences and Documents" Quoc Le, Tomas Mikolov </code></pre> <p>authors write </p> <blockquote> <p>“the inference s...
<p>For most neural networks, the output of the network (class for classification problems, number for regression,...) if the value you are interested in. In those cases, inference means running the frozen network on some new data (forward propagation) to compute the desired output.</p> <p>For those cases, several stra...
tensorflow|nlp|doc2vec
0
2,920
48,607,132
Timestamp fetched from websockets formatting
<p>I'm new here and need help in understanding how i can work with timestamps to datetime objects that are used in pandas. I saved some data using websockets in a csv file and loaded that csv file into a pandas dataframe. In my timestamp column i'm getting contents like <code>[2018-02-04T07:49:36.867Z, 2018-02-04T07:49...
<p>This is one way, using <code>pandas</code>:</p> <pre><code>import pandas as pd d = '2018-02-04T07:49:36.867Z' d_pd = pd.to_datetime(d) # Timestamp('2018-02-04 07:49:36.867000') d_str = d_pd.strftime('%Y%m%d %T.%f')[:-3] # '20180204 07:49:36.867' </code></pre>
python|string|python-3.x|pandas|datetime
0
2,921
70,742,561
Pivoting data and keeping only specific rows as per a condition
<p>I have a pandas dataframe with multiple columns, which looks like the following:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Index</th> <th style="text-align: center;">ID</th> <th style="text-align: center;">Year</th> <th style="text-align: center;">Code</th...
<p>Use:</p> <pre><code>#filter if difference is 1 per groups m1 = df.groupby('ID')['Mode'].transform(lambda x: x.diff().iloc[1:].eq(1).all()) #filter if first value per group is 1 m2 = df.groupby('ID')['Mode'].transform('first').eq(1) #pivoting all columns by ID per groups g created by copy Mode column df = df[m1 &a...
python|pandas
0
2,922
70,974,406
Remove all previous rows from primary dataframe based on condition from another dataframe
<p>I have two dataframe say df1 (primary dataframe) and df2. I want to drop all previous rows from df1 based on a condition from df2. My dataframe are like below:</p> <p><strong>df2</strong></p> <pre><code> tradingsymbol Time 0 BANKNIFTY2220339500CE 12:54:40 1 BANKNIFTY2220340000CE 12:53:33 2 BANKNI...
<p>In case the column elements are not yet in datetime format, you can transform:</p> <pre><code>df[&quot;Time&quot;] = pd.to_datetime(df[&quot;Time&quot;]).dt.time </code></pre> <p>Or, you can set this option directly while reading:</p> <pre><code>df = pd.read_csv( filename, parse_dates=[&quot;Time&quot;], ...
python|python-3.x|pandas|dataframe|group-by
1
2,923
70,992,167
Python Numpy CAR implementation - ValueError: shapes not aligned
<p>I am trying to implement a Common Average Reference function in python. The idea is to compute the average of the signal at all EEG channels and subtract it from the EEG signal at every channels for every time point. The input of this function is a NumPy array called trials. Trials is a 3D array that contains EEG da...
<p>WHOOPS - I didn't understand the definition of Common Average Reference. As pointed out in <a href="https://stackoverflow.com/users/1217358/warren-weckesser">Warren Weckesser's</a> <a href="https://stackoverflow.com/questions/70992167/python-numpy-car-implementation-valueerror-shapes-not-aligned/70993000#comment1255...
python|numpy|signal-processing
1
2,924
70,834,135
invalid value encountered in log in Python
<p>I am trying to impement the random walk metropolis hastings algorithm which my code is :</p> <pre><code>import numpy as np def rwmetrop(data,mu0=0,kappa0=1,alpha0=1,lambda0=1,nburn=1000,ndraw=10000,vmu=1,vomega=1): n = len(data) alpha1 = (n/2) + alpha0 - 1 stdvmu = np.sqrt(vmu) stdvomega ...
<p>When you call the function with this variables. The result of <code>1+omega*(data-mucan)**2</code> has a lot of negative number and when calculate <code>np.log(1+omega*(data-mucan)**2)</code> code calculate np.log(negative number) and this is <code>invalid value encountered in log</code>. negative number for log is ...
python|function|numpy
1
2,925
70,759,325
Is there a way to (conditionally) forward fill values in a Pandas DF in a vectorized way based on multiple criteria?
<p>In the below dataframe, I'm trying to forward fill the <code>Pos</code> and <code>Stop</code> columns based on the following criteria:</p> <ol> <li>If (Prior <code>Pos</code> == -1) &amp; (Current <code>High</code> &lt; Prior <code>Stop</code>)</li> <li>If (Prior <code>Pos</code> == 1 ) &amp; (Current <code>Low</co...
<p>I would suggest iterating over all rows and checking for both of the conditions. Unfortunately, I cannot reproduce your result as your code generates a different dataframe. Nonetheless, I think the following code does what you need:</p> <pre><code>import numpy as np import pandas as pd Open = {'Open':np.array([126....
python-3.x|pandas|numpy
1
2,926
51,644,257
Tensorflow Estimators : proper way to train image grids separately
<p>I am trying to train an object detection model as described in this <a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8281079" rel="nofollow noreferrer">paper</a> </p> <p>There are 3 fully connected layers with 512, 512, 25 neurons. The 16x55x55 feature map from the last convolutional layer is fed into ...
<p>Adding to the total_loss should be ok. </p> <p>tf.losses.sparse_softmax_cross_entropy is also adding losses together. </p> <p>It calculates a sparse_softmax with logits and then reduces the resulting array though a sum using math_ops.reduce_sum. So you are adding them together, one way or another. </p> <p><a hre...
tensorflow|deep-learning|object-detection|tensorflow-estimator
0
2,927
51,643,452
How to examine the results of a tensorflow.data.Dataset based model.train input_fn
<p>I am learning how to use the tf.data.Dataset api. I am using the sample code provided by google for their coursera tensorflow class. Specifically I am working with the c_dataset.ipynb notebook <a href="https://github.com/GoogleCloudPlatform/training-data-analyst/tree/master/courses/machine_learning/deepdive/03_ten...
<p>I do not know exactly what kind of information you want to extract. If you are interested in step N, as a general answer:</p> <ol> <li>If you want exactly the results, just run with <code>model.train(input_fn = get_train(), steps = N)</code>.</li> <li>Check train module functions <a href="https://www.tensorflow.org...
tensorflow|google-cloud-datalab
0
2,928
51,638,613
How do I multiply a pandas column with a part of a multi index dataframe
<p>I have a data frame with a multi index and one column.</p> <p>Index fields are <code>type</code> and <code>amount</code>, the column is called <code>count</code></p> <p>I would like to add a column that multiplies <code>amount</code> and <code>count</code></p> <pre><code>df2 = df.groupby(['type','amount']).count(...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for <code>Series</code> with same size as original <code>df</code> with aggregated values, so possible <code>multiple</code>:</p> <pre><code>cou...
python|python-3.x|pandas|multiplication
1
2,929
64,463,810
Convert from Keras to Pytorch - conv2d
<p>I am trying to convert the following Keras code into PyTorch.</p> <pre><code> tf.keras.Sequential([ Conv2D(128, 1, activation=tf.nn.relu), Conv2D(self.channel_n, 1, activation=None), ]) </code></pre> <p>When creating the model summary with self.channels=16 i get the following summary.</p> ...
<p>The attempt above is correct if you configure the initial channels in correcty (48 in this case).</p>
keras|pytorch
0
2,930
64,393,002
Find rows which have one column's value as substring in another column along with other OR conditions in pandas
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'A':[1,2,3,4], 'B':['abc', 'def', 'pqr', 'xyz'], 'C':['a', 'h', 'm', 'z'], 'D':['g', 'h', 'i', 'j']}) </code></pre> <p>I want to print rows that have C as a substring in B OR C equal to D Something like:</p> <pre><code>result_df = mydf[(mydf['C']==mydf[...
<p>You can only do this by going through column B and C:</p> <pre><code>print (df.loc[[y in x for x, y in zip(df[&quot;B&quot;], df[&quot;C&quot;])]|df[&quot;C&quot;].eq(df[&quot;D&quot;])]) A B C D 0 1 abc a g 1 2 def h h 3 4 xyz z j </code></pre>
python|pandas
1
2,931
64,565,717
Appending pandas series to the left of index zero
<p>I'm trying to select portions of a pandas data series <code>yf </code> according to left limit <code>a0 </code> and right limit <code>b0 </code>.<br/></p> <p>If the left limit is negative, I want to pad the difference with zeros so the resulting series would have the desired length, like this:</p> <pre><code>if a...
<p>I created the source <em>Series</em> as:</p> <pre><code>lst = np.arange(10,20) yf = pd.Series(lst + 5, index = lst) </code></pre> <p>so that it contains:</p> <pre><code>10 15 11 16 12 17 13 18 14 19 15 20 16 21 17 22 18 23 19 24 dtype: int32 </code></pre> <p>(the left column is the inde...
python|pandas|append|series|pad
1
2,932
64,264,707
character vectorization
<p>I am trying to follow the Tensorflow Beginner Example to load text data by using &quot;text_dataset_from_directory&quot; and tokenize those data with &quot;TextVectorization&quot;. (<a href="https://www.tensorflow.org/tutorials/keras/text_classification" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials...
<p>The easiest way is to create a copy of char file and word file.</p> <pre><code>Example: Char Version: I g o t o s c h o o l b y b u s Word Version: I go to school by bus </code></pre>
python|tensorflow|keras|tokenize
0
2,933
64,381,552
Python - Calling a Function Inside a For Loop - Changing Input Argument Without Overwriting It
<p>Novice Python user here, really stumped on this one. I have a 3x3 array that stores coordinates in xyz format, where the rows are the number of atoms and columns correspond to x,y and z. For every element that is not in the z direction I wish to add some scalar dr to it. Ultimately I would like to generate a diction...
<pre><code>def displace(coords, row, col): if principle_axes == 'Z': if col != 2: new_coords = coords new_coords[row, col] = new_coords[row, col] + dr return new_coords </code></pre> <p><code>new_coords = coords</code> assigns a pointer, not a copy.</p> <p>You can instead...
python|python-3.x|function|numpy|for-loop
0
2,934
47,745,373
Counting uneven bins in Panda
<pre><code>pd.DataFrame({'email':["a@gmail.com", "b@gmail.com", "c@gmail.com", "d@gmail.com", "e@gmail.com",], 'one':[88, 99, 11, 44, 33], 'two': [80, 80, 85, 80, 70], 'three': [50, 60, 70, 80, 20]}) </code></pre> <p>Given this DataFrame, I would like to compute, ...
<p>This would do it:</p> <pre><code>out = pd.DataFrame() for name in ['one','two','three']: out[name] = pd.cut(df[name], bins=[0,70,80,90,100]).value_counts() out.sort_index(inplace=True) </code></pre> <p>Returns:</p> <pre><code> one two three (0, 70] 3 1 4 (70, 80] 0 3 1 (80...
python|pandas
7
2,935
47,692,054
Tensorflow - Linear Regression
<p>I code tensorflow program for linear regression. I am using Gradient Descent algorithm for optimizing(Minimising) loss function. But value of loss function is increasing while executing the program. My program and output is in follow.</p> <pre><code> import tensorflow as tf W = tf.Variable([.3],dtype=tf.floa...
<p>Did you try changing the learning rate? Using a lower running rate (~1e-4) and more iterations should work. </p> <p>More justification as to why a lower learning rate might be required. Note that your loss function is </p> <p>L = \sum (Wx+b-Y)^2</p> <p>and dL/dW = \sum 2(Wx+b-Y)*x</p> <p>and hessian d^2L/d^2W = ...
python|machine-learning|tensorflow|deep-learning|linear-regression
1
2,936
47,598,233
How to add/delete an index in a multi index dataframe Python
<p>I have a multi-index dataframe where I'd like to add a "three" index with 6 values, 2 for a, b and c in columns X and Y.</p> <pre><code> import pandas as pd, numpy as np np.arrays = [["one", "one", "one", "two", "two", "two"], ["a", "b", "c", "a", "b", "c"]] df = pd.DataFrame(np.random.randn(6,2), ...
<p>One approach using pd.concat i.e </p> <pre><code>idx = pd.MultiIndex.from_tuples(list(zip(['three']*3,list('abc')))) new = pd.DataFrame(np.random.randn(3,2), index=idx, columns= df.columns) new_df = pd.concat([df,new]) X Y one a 0.270000 0.299000 b 0.644000 0.073000 c 1.2...
python|pandas|dataframe|multi-index
1
2,937
48,952,733
What is the purpose of numpy masked array in this function?
<p>My code</p> <pre><code>def to_norm(self, x): if isinstance(x, np.ma.MaskedArray): data = x.filled() mask = x.mask else: data = x mask = None </code></pre> <p>As I understand <code>isinstance</code> is checking type.The appropriate array elements are going to be filled. But w...
<p><code>np.ma.MaskedArray</code> is a subclass of the regular numpy <code>ndarray</code>. You can read all about in the docs.</p> <p>This method apparently tries to handle argument <code>x</code> is consistent manner, regardless of whether it is <code>ndarray</code> or <code>MaskedArray</code>.</p> <p>A masked arra...
python|numpy
3
2,938
48,994,761
How to append from multiple dictionaries in a List to another list with specific parts of the "inner" dictionary?
<p>I've got dictionaries in a list:</p> <pre><code>fit_statstest = [{'activities-heart': [{'dateTime': '2018-02-01', 'value': {'customHeartRateZones': [], 'heartRateZones': [{'caloriesOut': 2119.9464, 'max': 96, 'min': 30, 'minutes': 1232, 'name': 'Out of Range'}, {'caloriesOut': 770.2719, 'max': 134...
<p>Here is one solution via a single list comprehension:</p> <pre><code>import pandas as pd time_values = [(d['time'], d['value']) for day in fit_statstest \ for d in day['activities-heart-intraday']['dataset']] df = pd.DataFrame(time_values, columns=['time', 'value']) </code></pre> <p><strong>Result...
python|list|pandas|dictionary|append
1
2,939
49,051,805
pandas fillna: How to fill only leading NaN from beginning of series until first value appears?
<p>I have several <code>pd.Series</code> that usually start with some NaN values until the first real value appears. I want to pad these leading NaNs with 0, but not any NaNs that appear later in the series.</p> <pre><code>pd.Series([nan, nan, 4, 5, nan, 7]) </code></pre> <p>should become</p> <pre><code>ps.Series([0...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.first_valid_index.html" rel="nofollow noreferrer"><code>first_valid_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.loc.html" rel="nofollow noreferrer"><code>loc</code></a>:</p> <pre><c...
python|pandas
5
2,940
49,140,425
How to insert values from numpy into sql database with given columns?
<p>I need to insert some columns into a table in my Mariadb. The table name is Customer and has 6 columns, A,B,C,D,E,F. The primary keys are in the first column, column B has an address, C,D, and E contain None values and F the zip code. </p> <p>I have an pandas dataframe that follows similar format. I converted i...
<p>I solved it. Although very slow...</p> <pre><code>query = """ Alter Customer SET C = %s D = %s E = %s where A = %s """ for row in data: cur.execute(query,args=(row[1],row[2],row[3],row[0]) con.commit() </code></pre>
python-3.x|pandas|numpy|mysql-python
0
2,941
58,924,899
how to remove duplicated elements from a list without using set()?
<p>Let </p> <pre><code>a = np.array([1, 1, 1,1,1,1]) b = np.array([2,2,2]) </code></pre> <p>be two numpy arrays. Then let</p> <pre><code>c = [a]+[b]+[b] </code></pre> <p>clearly, <code>c</code> has duplicated elements <code>b</code>. Now I wish to remove one array <code>b</code> from <code>c</code> so that <code>c<...
<p>You can use this</p> <pre><code>c = a.tolist() + b.tolist() + b.tolist() </code></pre> <p>And then</p> <pre><code>c = set(c) </code></pre>
python|list|numpy
1
2,942
58,819,435
How to split text of a dataframe column into multiple columns?
<p>I'm trying to retrieve a string from an excel sheet and split it into words then print it or write it back into a new string but when retrieving the data using pandas and trying to split it an error occurs saying dataframe doesn't support split function </p> <p><strong>the excel sheet has this line in it:</strong> ...
<p>That's because you are applying <code>split()</code> function on a DataFrame and that's not possible.</p> <pre><code>import pandas as pd import numpy as np def append_nan(x, max_len): """ Function to append NaN value into a list based on a max length """ if len(x) &lt; max_len: x += [np.nan...
python|excel|pandas|dataframe
3
2,943
58,962,701
What Network should beused for Gesture Detection
<p>I am trying to create a gesture detection application with Keras and python.</p> <p>I have training and testing images like this one:</p> <p><a href="https://imgur.com/1uUujOi" rel="nofollow noreferrer"><img src="https://i.imgur.com/1uUujOi.jpg" title="source: imgur.com" /></a> <a href="https://imgur.com/jajU59t" ...
<p>Deep learning always require a lot of data. 60 images for each class is a very very vague figure. I would suggest you to first increase data set. The most simplest way to increase data set is by up sampling the images. You can invert the images and can easily up sample the data. Best of luck and cheers. Do followin...
python|tensorflow|keras
0
2,944
58,901,422
Heat map from pandas DataFrame - 2D array
<p>I have a data visualisation-based question. I basically want to create a heatmap from a pandas DataFrame, where I have the x,y coordinates and the corresponding z value. The data can be created with the following code -</p> <pre><code>data = ([[0.2,0.2,24],[0.2,0.6,8],[0.2,2.4,26],[0.28,0.2,28],[0.28,0.6,48],[0.28,...
<p>Found one way of doing this - </p> <p>Using Seaborn.</p> <pre><code>import seaborn as sns data = ([[0.2,0.2,24],[0.2,0.6,8],[0.2,2.4,26],[0.28,0.2,28],[0.28,0.6,48],[0.28,2.4,55],[0.36,0.2,34],[0.36,0.6,46],[0.36,2.4,55]]) data=np.array(data) df=pd.DataFrame(data,columns=['X','Y','Z']) df=df.pivot('X','Y','Z') dip...
python|pandas|dataframe|heatmap
2
2,945
58,916,413
Return rows for customers only where values in a certain column are either x or y
<p>I have a list of customer emails, and the status of their account at different dates. </p> <pre><code>df = pd.DataFrame({'email': pd.Series(['john@email.com', 'john@email.com', 'mary@email.com', 'mary@email.com', 'patrick@email.com', 'patrick@email.com', 'foo@email.com', 'foo@email.com'],dtype='object',index=pd.Ran...
<p>Idea is compare first duplicate value by <code>Lead</code> and second duplicate value by <code>Account Open</code>, chain conditions by <code>&amp;</code> for AND and <code>|</code> for <code>OR</code> and filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="...
python|pandas
1
2,946
70,319,654
pandas Dataframe create new column
<p>I have this snippet of the code working with pandas dataframe, i am trying to use the apply function to create a new column called STDEV_TV but i keep running into this error all the columns i am working with are type float</p> <pre><code>TypeError: (&quot;'float' object is not iterable&quot;, 'occurred at index 0')...
<p>Try:</p> <pre><code>import pandas as pd import numpy as np import math df = pd.DataFrame(np.random.randint(1, 10, (5, 3)), columns=['volume2Sum', 'volumeSum', 'vwap']) def sigma(df): val = df.volume2Sum / df.volumeSum - df.vwap * df.vwap return math.sqrt(val) if val &gt;= 0 else val df['...
python|pandas|dataframe
2
2,947
70,222,250
Pandas group by rolling window function on a timestamp field
<p>I want to add dates and days that are contained in a column after grouping by an ID column.</p> <p>The following generates an example df:</p> <pre><code>df = pd.DataFrame( { &quot;ID&quot;:[1,1,1,1,2,2,2,3,3,3,3,3,3], &quot;Date&quot;:list(pd.date_range(&quot;2018-1-1&quot;, &quot;2018-4-10&quot;...
<p>You can just do <code>cumsum</code></p> <pre><code>df['new_date_intermediate'] = df.groupby('ID')['new_date_intermediate'].apply(lambda x :x.cumsum()) df ID Date date_intervals new_date_intermediate 0 1 2018-01-01 NaT 2018-01-01 00:00:00 1 1 2018-02-03 33 days 2018-02-03 00:00:0...
python|pandas
1
2,948
70,344,616
KeyError: 337 when training a hugging face model using pytorch
<p>I am training a simple binary classification model using <code>Hugging face models</code> using <code>pytorch.</code></p> <p>Bert PyTorch HuggingFace.</p> <p>Here is the code:</p> <pre><code>import transformers from transformers import TFAutoModel, AutoTokenizer from tokenizers import Tokenizer, models, pre_tokenize...
<p>For me this error was happening when passing a Pandas DataFrame with values missing in the index i.e 0, 1, 2, 4. Changing the index to 0, 1, 2, 3 fixed the problem.</p>
python-3.x|nlp|text-classification|huggingface-transformers
1
2,949
56,307,591
Why is the result a recurring number when it should be an integer?
<p>Hi so i'm writing some code for class and this for Linear Regression.<br> The values calculated by hand is a=1.7 and b=1.6 for the data you can see in the code.</p> <p>I've tried separating different parts of the formula into different variables but the answer remains the same (1.6999999999999993).</p> <pre><code>...
<p>It's because you are using <code>float</code> number, binary floating point math is like this. In most programming languages, it is based on the <a href="https://en.wikipedia.org/wiki/IEEE_754#Basic_formats" rel="nofollow noreferrer">IEEE 754 standard</a>.</p> <p>see <a href="https://stackoverflow.com/questions/588...
python|numpy
0
2,950
55,753,303
Safely downcast a float to the smallest possible integer type
<p>Pandas and numpy have a variety of ways to change numerical types but I couldn't find an automated way to safely convert a float to the smallest possible integer, given that no numerical info can be lost.</p> <p>For example:</p> <pre><code>1.0 (float32) -&gt; 1 (int32) # OK, 1 == 1.0 1.0 (float32) -&gt; 1 (i...
<p>Here's a simple function:</p> <pre><code>def float_to_int( s ): if ( s.astype(np.int64) == s ).all(): return pd.to_numeric( s, downcast='integer' ) else: return s df.apply( float_to_int ) </code></pre> <p>Output:</p> <pre><code> i j x 0 1 1 -2....
python|pandas|numpy
0
2,951
55,672,605
Reading the json file correctly
<p>This statement reads the json file. But it does not split the columns correctly.</p> <p>df = pd.read_json('<a href="https://s3.amazonaws.com/todel162/config1.json" rel="nofollow noreferrer">https://s3.amazonaws.com/todel162/config1.json</a>', orient='index')</p> <p>Is there any way to read the json using pandas da...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.json.json_normalize.html" rel="nofollow noreferrer"><code>json.json_normalize</code></a>:</p> <pre><code>import json from pandas.io.json import json_normalize with open('config1.json') as f: data = json.load(f) df =...
pandas
1
2,952
55,657,732
How to see tensorflow build configuration?
<p>I am trying to build tensorflow from source on a remote server (with no superuser privileges) because I got this error when I simply installed with pip:</p> <pre><code>Loaded runtime CuDNN library: 7.1.2 but source was compiled with: 7.4.2. CuDNN library major and minor version needs to match or have higher minor ...
<p>A file is generated after running <code>./configure</code> with the name <code>.tf_configure.bazelrc</code> you can inspect that file.</p>
tensorflow
0
2,953
55,798,536
predicting using pre-trained model becomes slower and slower
<p>I'm using a very naive way to make predictions based on pre-trained model in keras. But it becomes much slower later. Anyone knows why? I'm very very very new to tensorflow.</p> <pre class="lang-py prettyprint-override"><code>count = 0 first = True for nm in image_names: img = image.load_img(TEST_PATH + nm, tar...
<p>I doubt the TF is slowing down. However there is another stack overflow question showing that to_csv slows down on append.</p> <p><a href="https://stackoverflow.com/questions/29271257/performance-python-pandas-dataframe-to-csv-append-becomes-gradually-slower">Performance: Python pandas DataFrame.to_csv append becom...
tensorflow
0
2,954
55,689,915
Python: how to groupby a given percentile?
<p>I have a dataframe <code>df</code></p> <pre><code>df User City Job Age 0 A x Unemployed 33 1 B x Student 18 2 C x Unemployed 27 3 D y Data Scientist 28 4 E y Unemployed 45 5 F y Student ...
<pre><code>def q1(x): return x.quantile(0.25) def q2(x): return x.quantile(0.75) fc = {'Age': [q1,q2]} temp = df.groupby('City').agg(fc) temp Age q1 q2 City x 22.5 30.0 y 23.0 36.5 </code></pre>
python|pandas|group-by
4
2,955
64,690,224
how can I add different size of the values into a pandas data frame at a time
<p>I need to fill a data frame gradually. in each step, I have a data like this:</p> <pre><code>pubid = 1 keywords = [2, 2,3] </code></pre> <p>knowing that the length of values for the column are not equal how can I form a data frame like this:</p> <pre><code>pubid keyword 1 2 1 2 1 3 </code><...
<pre><code>pubid = 1 keywords = [2, 2,3] df = pd.DataFrame({'pubid': pubid, 'keywords': keywords}) print(df) </code></pre> <p>Prints:</p> <pre><code> pubid keywords 0 1 2 1 1 2 2 1 3 </code></pre> <p>Then you can use <code>pd.concat</code> to add data to existing DataFrame:</p...
python|pandas|dataframe
1
2,956
64,744,358
Grouping by classes
<p>I would like to see how many times a url is labelled with 1 and how many times it is labelled with 0. My dataset is</p> <pre><code> Label URL 0 0.0 www.nytimes.com 1 0.0 newatlas.com 2 1.0 www.facebook.com 3 1.0 www.facebook.com 4 0.0 issuu.com ... ... ... 3572 0.0 www.businessinsider.com 3573 0...
<p>Now you can do <code>value_counts</code></p> <pre><code>df.value_counts([&quot;URL&quot;,&quot;Label&quot;]) </code></pre>
python|pandas
1
2,957
39,967,460
Using Pandas to Create DateOffset of Paydays
<p>I'm trying to use Pandas to create a time index in Python with entries corresponding to a recurring payday. Specifically, I'd like to have the index correspond to the first and third Friday of the month. Can somebody please give a code snippet demonstrating this?</p> <p>Something like:</p> <pre><code>import pandas...
<p>try this:</p> <pre><code>In [6]: pd.date_range("2016-10-10", periods=26, freq='WOM-1FRI').union(pd.date_range("2016-10-10", periods=26, freq='WOM-3FRI')) Out[6]: DatetimeIndex(['2016-10-21', '2016-11-04', '2016-11-18', '2016-12-02', '2016-12-16', '2017-01-06', '2017-01-20', '2017-02-03', '2017-02-17', '2017-03-03'...
python|pandas
2
2,958
40,878,053
what is the quickest way to drop zeros from a series
<p>I'm encountered this problem several times and always doing something different each time. What do others do?</p> <p>Consider the series <code>s</code></p> <pre><code>s = pd.Series([1, 0, 2], list('abc'), name='s') </code></pre> <p>What is the quickest way to to produce</p> <pre><code>a 1 c 2 Name: s, dty...
<p>Boolean slicing is probably the easiest way:</p> <pre><code>In [1]: s = pd.Series([1, 0, 2], list('abc'), name='s') In [2]: s[s != 0] Out[2]: a 1 c 2 Name: s, dtype: int64 </code></pre>
python|pandas|numpy
3
2,959
41,101,348
Share variables - two queues
<p>Thanks to <a href="https://stackoverflow.com/questions/40803697/tensorflow-multithreading-image-loading">Tensorflow multithreading image loading</a>, I have this load data function which, given a csv file e.g. a training csv file it creates some data nodes; </p> <pre><code> 34 def loadData(csvPath,shape, batchSize=...
<p>Alas, currently there is no good answer to this question. The typical evaluation workflow involves running a <strong>separate process</strong> that periodically does the following (e.g. <a href="https://github.com/tensorflow/models/blob/12f279d6f4cb33574bc20109b41eb8a59f40cfd1/tutorials/image/cifar10/cifar10_eval.py...
tensorflow
3
2,960
41,035,942
Create numPy array using list comprehension
<p>Let say I have two numPy arrays <code>arr1</code>and <code>arr2</code>:</p> <pre><code>arr1 = np.random.randint(3, size = 100) arr2 = np.random.randint(3, size = 100) </code></pre> <p>I would like to build a matrix that contains the number of joint occurrences. In other words, for all the values of <code>arr1</c...
<p>Your first list comprehension works. You won't get a <code>NameError</code> if <code>arr1</code> is defined:</p> <pre><code>import numpy as np np.random.seed(2016) arr1 = np.random.randint(3, size = 100) arr2 = np.random.randint(3, size = 100) result = [[sum(arr1[arr2 == y] == x) for x in np.arange(0,3)] ...
python|arrays|numpy|list-comprehension
3
2,961
41,155,504
H5PY/Numpy - Setting the inner shape of a numpy arrays (for h5py)
<p>I am trying to use h5py to store data as a list of tuples of (images, angles). Images are numpy arrays of size (240,320,3) of type uint8 from OpenCV while angles are just a number of type float16.</p> <p>When using h5py, you need to have a predetermine shape in order to maintain a usable speed of read/write. H5py p...
<p>In numpy, you can store that data with structured arrays:</p> <pre><code>dtype = np.dtype([('angle', np.float16), ('image', np.uint8, (240,320,3))]) data = np empty(10, dtype=dtype) data[0]['angle'] = ... # etc </code></pre>
python|numpy|h5py
2
2,962
53,889,936
Error when trying to trim a string in pandas
<p>I have the following code to trim off dangling line separators in pandas:</p> <pre><code>for idx, value in enumerate(df.loc[0]): if str(value).strip() != str(value): print ('AAAAAAAAAA', repr(value)) df[idx] = df[idx].str.strip() print ('BBBBBBBBBB') </code></pre> <p>Here is what happen...
<p>It looks like you're calling the index number where you need to be calling the index name. Here is how you would adjust it:</p> <pre><code>for idx_name, value in df.loc[0].items(): if str(value).strip() != str(value): df[idx_name] = df[idx_name].str.strip() </code></pre>
python|pandas
0
2,963
54,160,084
DataFrame repeated dictionaries in a list
<p>I have a JSON file that contains a list of nested dictionaries- <strong>(Json Sample)</strong>:</p> <pre><code>{"posts": [{"url": "http://twitter.com/AkEl_Saruman/status/1084067040481169408", "title": "", "type": "Twitter", "language": "tr", "assignedCategoryId": 19058723389, "assignedEmotionId": 0, "categoryScores...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html" rel="nofollow noreferrer"><code>json_normalize</code></a>:</p> <pre><code>import json from pandas.io.json import json_normalize with open('test.json') as file: j = json.load(file) df...
python|json|python-3.x|pandas|dataframe
3
2,964
54,212,645
How to configure tensorflow legacy/train.py model.cpk output interval
<p>I am trying to address an issue caused by overfitting of a model. Unfortunately I don't know how to increase the interval of <code>model.cpk</code> that <code>legacy/train.py</code> outputs during training. Is there a way to reduce the time between each saving of <code>model.cpk</code> and to disable its deletion. I...
<p>For save intervals and number of checkpoints to keep, have a look here: <a href="https://www.tensorflow.org/api_docs/python/tf/train/Saver" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/train/Saver</a></p> <p>From the link above <br> -> max_to_keep <br> -> keep_checkpoint_every_n_hours</p>...
python|tensorflow
1
2,965
54,124,278
Change the sign of the number in the pandas series
<p>How to change the sign in the series, if I have:</p> <blockquote> <p>1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13</p> </blockquote> <p>and need to get:</p> <blockquote> <p>1, 2, 3, -4, -5, -6, 8, 9, 10, -11, -12, -13</p> </blockquote> <p>I need to be able to set the period (now it is equal to 3) and the index f...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with integer division by (<code>//</code>) and modulo (<code>%</code>) for boolean mask:</p> <pre><code>s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) N = 3 #if def...
python|pandas|time-series|series
3
2,966
66,294,709
Creating new dataframe by selecting specific columns from other dataframe
<p>This seems to be a simple question, and it could still be, on how to create new dataframe by selecting specific columns from other dataframes. Lets illustrate it by having a three dummy dataframes df1, df2, df3, where &quot;position&quot; is common column in all dataframes</p> <pre><code>df1 = pd.DataFrame({&quot;Po...
<p>You could just concat horizontaly the relevant columns:</p> <pre><code>new_dfs = [pd.concat((df.set_index('Position').iloc[:,i] for df in ( df1, df2, df3)), axis=1).reset_index() for i in range(3)] </code></pre> <p>It gives:</p> <pre><code>for i in new_dfs: print(i) Position Team1 T1 T_1 0 A ...
python|pandas|dataframe
2
2,967
65,955,235
Elegant way to add one row DataFrame to another DataFrame
<p>I have two <code>DataFrames</code> and one of them is a single row <code>DataFrame</code>. I want to add the one row <code>dataframe</code> across all the rows of the bigger one. I can solve it, but I am looking for a simpler solution:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'C':['car'],'D':['bus']}) ...
<p>I think the most elegant is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>DataFrame.assign</code></a>, but is necessary strings columns names:</p> <pre><code>df2 = df2.assign(**df1.iloc[0]) print (df2) A B C D 0 1 8 c...
python|pandas|dataframe
5
2,968
66,144,350
How to assign a value to a new column with a string condition in pandas dataframe
<p>I try to assign values to a new column in the data-frame based on condition, if the first column contains a certain letter or not. f the first column only contains one letter, I use the dummy variable function. But how about, if the first column contains numbers, strings, and Nan?</p> <p>Here is a example:</p> <pre ...
<p>You <em>could</em> do something like this:</p> <pre><code>df['a'] = df['c1'].str.contains('a').astype(int) </code></pre> <p>... but this raises a <code>ValueError</code> if you have any <code>NaN</code> values in <code>df['c1']</code> (as you do in your example).</p> <p>Here's an alternative using <code>df.apply</co...
python|pandas|dataframe
2
2,969
66,049,765
filter a dataframe based on a specific value for each category in pandas
<p>I have a dataframe</p> <pre><code>df = url browser loadtime A safari 1500 A safari 1650 A Chrome 2800 B IE 3150 B safari 3300 C Chrome 2650 . . . . . . </code></...
<p>You can try to merge your calculation with the original dataframe</p> <pre><code>df_grouped = df.groupby(&quot;app&quot;)['loadtime'].agg([('upper_outlier', lambda x : upper_outlier(x))]).reset_index() dfmerged = df.merge(df_grouped, on = 'app', how = 'left') </code></pre> <p>and then filter</p> <pre><code>dfmerge...
python|pandas|dataframe|filter|outliers
2
2,970
52,518,283
In Python Pandas, how to search if column elements contains the first 2 digits
<p>I am fairly new to Python and currently I am trying to build a function that searches for the first 2 digits of the elements in a column and if true, return the result with a new header such as region</p> <p>For example, </p> <pre><code> Adres AreaCode Region 0 SArea 123191 A 1 BArea 122929 A ...
<blockquote> <p>I tried this df.loc[df.AreaCode.str.contains == 12, 'Region' ] = 'A' but it gives me the error: AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas</p> </blockquote> <p>You could simply convert it to a string, then use the same code:</p> <pre><code>d...
python|pandas
2
2,971
52,737,636
BeautifulSoup Python to Dataframe
<p>I'm trying to convert scraped data to a pd dataframe(table). The info is retrieved via beautifulsoup from different tags (a, span, div). for ul in soup_level1.find('ul', {'class':"fix3"}):</p> <pre><code>divjt=ul.find('div',{'class':"topb"}) a=divjt.find('a') trajectory=a.text.strip() divloc=ul.find('div',{'class':...
<p>If you want the data in an a Excel use csv Format instead , A csv file can be opened in excel/Libre office to get the required result</p> <pre><code>var row = value1 + ":" + value2 + ":" + value3 ; await fs.appendFile('file_name.csv', row + os.EOL, function (err) { if (err) throw err; }); </code></pre> ...
python|pandas|beautifulsoup
0
2,972
46,568,021
Install Tensorflow with SYCL support
<p>I am tring to use gdb to trace Tensorflow operation kernel implementation with Eigen SYCL support. However, when I try to install the <code>.whl</code> package, some error messages about <code>fglrx</code> pop up. </p> <h3>Error message</h3> <pre><code>Compiling /tmp/pip-1vfYDJ-build/tensorflow-1.0.1.data/purelib...
<p>You can't (currently) use SYCL with TensorFlow on Intel GPUs. However, it is coming soon. There are a few fixes you will need and then it will work correctly. You will need to wait for a new Intel OpenCL GPU driver and then for a few compatibility commits to TensorFlow before it will work on Intel GPU. You may also ...
python|ubuntu|tensorflow|opencl|nvidia
1
2,973
58,175,041
Append data to DF with column names stored in list
<p>Long time listener, first time caller...</p> <p>I'm new to python struggling to understand how to process lists for different purposes. In this case, I have what will ultimately be a long list of float objects that I'd like to arrange into a dataframe, appending new rows with each loop.</p> <pre><code>cols = ['c...
<p>You can try using <code>loc</code></p> <pre><code>symbolList = [*'ABCDEFG'] for symbol in symbolList: col1 = np.random.randn() col2 = np.random.randn() df.loc[symbol] = [col1, col2] </code></pre> <p>However. If you define your dataframe as <code>float</code> you can use <code>at</code></p> <pre><cod...
python-3.x|pandas
0
2,974
58,185,660
tensorflow select list of indices along dimension
<p>In order to select a list of columns in a matrix I am doing the following:</p> <pre><code>sel = tf.concat([tf.slice(mat, [0, i], [-1, 1]) for i in list_columns], axis=1) </code></pre> <p>I wonder if there is a more efficient manner</p>
<p><code>tf.gather</code> will be more efficient and concise. Let <code>axis=1</code>, then you can select columns in specified indices. </p> <pre class="lang-py prettyprint-override"><code>mat = tf.constant(np.arange(12).reshape(2,6)) #[[ 0, 1, 2, 3, 4, 5], # [ 6, 7, 8, 9, 10, 11]] list_columns = [0,2,4] res...
tensorflow
1
2,975
58,309,532
How to get distinct value, count of a column in dataframe and store in another dataframe as (k,v) pair using Spark2 and Scala
<p>I want to get the distinct values and their respective counts of every column of a dataframe and store them as (k,v) in another dataframe. Note: My Columns are not static, they keep changing. So, I cannot hardcore the column names instead I should loop through them.</p> <p>For Example, below is my dataframe </p> <...
<p>I don't have exact solution to your query but I can surely provide you with some help that can get you started working on your issue.</p> <p>Create dataframe</p> <pre><code>scala&gt; val df = Seq(("Blaze ","IND","19950312"), | ("Scarlet","USA","19950313"), | ("Jonas ","CAD","19950312"), | ("Blaze ...
pandas|scala|apache-spark|machine-learning|apache-spark-sql
1
2,976
69,129,338
Grouping a DataFrame, counting occurrences in one column, putting other column values in sets
<p>I have a dataframe, let's call it 'data', as follows:</p> <pre><code>index ID name 0 23 aaa 1 42 bbb 2 23 aab 3 42 bbb 4 42 bbb ... </code></pre> <p>I want to count the occurences of ID and create an extra column for that by which I can sort. Additionally I want to add the names...
<p>You can use <code>.agg</code> with multiple parameters:</p> <pre class="lang-py prettyprint-override"><code>x = df.groupby(&quot;ID&quot;, as_index=False).agg( count=(&quot;ID&quot;, &quot;size&quot;), name=(&quot;name&quot;, set) ) print(x) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override...
python|pandas|dataframe|pandas-groupby
1
2,977
69,027,228
All possible concatenations of two tensors in PyTorch
<p>Suppose I have two tensors <code>S</code> and <code>T</code> defined as:</p> <pre><code>S = torch.rand((3,2,1)) T = torch.ones((3,2,1)) </code></pre> <p>We can think of these as containing batches of tensors with shapes <code>(2, 1)</code>. In this case, the batch size is <code>3</code>.</p> <p>I want to concatenate...
<p>In numpy something called np.meshgrid is used.</p> <p><a href="https://stackoverflow.com/a/35608701/3259896">https://stackoverflow.com/a/35608701/3259896</a></p> <p>So in pytorch, it would be</p> <pre><code>torch.stack( torch.meshgrid(x, y) ).T.reshape(-1,2) </code></pre> <p>Where x and y are your two lists. You can...
pytorch
0
2,978
68,951,354
interval in dataframe to start from the first row [python 3.6.0]
<p>Below data is in the interval of 5 mins, trying to group it in 10 mins</p> <p>Dataframe names as <code>df</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>script_id</th> <th>date_time</th> <th>open</th> <th>high</th> <th>low</th> <th>close</th> <th>volume</th> </tr> </thead> <tbod...
<p>Seems like you just need to supply the offset argument when you call <code>pd.Grouper(... offset=&quot;5T&quot;)</code></p> <pre><code>df_f = df.groupby(['script_id', pd.Grouper(key='date_time', freq='10T', offset=&quot;5T&quot;)])\ .agg(open=pd.NamedAgg(column='open', aggfunc='first'), ...
python|pandas|dataframe|pandas-groupby
2
2,979
68,990,413
colors are not consistently applied to categories in subplots
<p>Having the following code i can't understand why is not showing correctly the information (check the column C and F) bot are show as the same value but are different</p> <p>What i need is plot some of the columns in the df and share the legend between all subplots (all columns have the same values [&quot;SI&quot;,&q...
<p>So the commenter was correct, when you have only one value with <code>value_counts()</code> you run into issues.</p> <p>So I transformed the DF with:</p> <pre class="lang-py prettyprint-override"><code>df = df.T.apply(pd.Series.value_counts, axis=1).fillna(0).reset_index() df.columns = ('question', 'no', 'si') </cod...
python|pandas|matplotlib
1
2,980
69,204,712
Delete rows above certain value once number is reached
<p>I have a large dataset where I am interested in the part where it shuts down and when it is shut down. However, the data also includes data of the startup which I want to filter out.</p> <p>The data goes down to &lt;0.2, stays there for a while and then goes up again &gt;0.2. I want to delete the part where it has b...
<p>You can identify the switching points (above 0.2 to under and vice versa) using <code>(df['Value'] &lt; 0.2).diff()</code> and then use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a>. To remove any parts of the dataframe after the...
python|pandas
3
2,981
44,524,901
How do I multiply matrices in PyTorch?
<p>With numpy, I can do a simple matrix multiplication like this:</p> <pre><code>a = numpy.ones((3, 2)) b = numpy.ones((2, 1)) result = a.dot(b) </code></pre> <p>However, this does not work with PyTorch:</p> <pre><code>a = torch.ones((3, 2)) b = torch.ones((2, 1)) result = torch.dot(a, b) </code></pre> <p>This code thr...
<p>Use <a href="https://pytorch.org/docs/stable/generated/torch.mm.html" rel="nofollow noreferrer"><code>torch.mm</code></a>:</p> <pre><code>torch.mm(a, b) </code></pre> <p><code>torch.dot()</code> behaves differently to <code>np.dot()</code>. There's been some discussion about what would be desirable <a href="https://...
python|matrix|pytorch|matrix-multiplication
117
2,982
44,458,434
Python: break up dataframe (one row per entry in column, instead of multiple entries in column)
<p>I have a solution to a problem, that to my despair is somewhat slow, and I am seeking advice on how to speed up my solution (by adding vectorization or other clever methods). I have a dataframe that looks like this:</p> <pre><code>toy = pd.DataFrame([[1,'cv','c,d,e'],[2,'search','a,b,c,d,e'],[3,'cv','d']], ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>str.split</code></a> for <code>list</code>s, then get <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>len...
performance|pandas|python-3.4
2
2,983
60,949,936
Why bilinear scaling of images with PIL and pytorch produces different results?
<p>In order to feed an image to the pytorch network I first need to downscale it to some fixed size. At first I've done it using PIL.Image.resize() method, with interpolation mode set to BILINEAR. Then I though it would be more convenient to first convert a batch of images to pytorch tensor and then use torch.nn.functi...
<p>&quot;Bilinear interpolation&quot; is an interpolation method.</p> <p>But downscaling an image is not necessarily only accomplished using interpolation.</p> <p>It is possible to simply resample the image as a lower sampling rate, using an interpolation method to compute new samples that don't coincide with old sampl...
python|image-processing|pytorch|python-imaging-library
8
2,984
60,791,997
How to check URL status for multiple URLs stored in a CSV file and save results to a new CSV file
<p>I'm new to python and currently trying to achieve the following:</p> <p>I want to check HTTP response status codes for multiple URLs in my input.csv file:</p> <pre><code>id url 1 https://www.google.com 2 https://www.example.com 3 https://www.testtesttest.com ... </code></pre> <p>and save results as an...
<pre><code>id url 1 https://www.google.com 2 https://www.example.com 3 https://www.testtesttest.com </code></pre> <p>Copy the above to clipboard. Then, run the below code. You need to loop through the urls and append the status to a list. Then, set the list as a new column.</p> <pre><code>import requests impor...
pandas|web-scraping|python-requests
2
2,985
71,580,700
Creating list from imported CSV file with pandas
<p>I am trying to create a list from a CSV. This CSV contains a 2 dimensional table [540 rows and 8 columns] and I would like to create a list that contains the values of an specific column, column 4 to be specific.</p> <p>I tried: list(df.columns.values)[4], it does mention the name of the column but i'm trying to get...
<pre><code>companies_column = list(df.iloc[:,4].values) </code></pre>
python|pandas|csv
1
2,986
71,773,219
How to segment and get the time between two dates in pandas?
<p>I want to know how long it has been driven during certain time segments, in this case we want to look at one hour segments. To get the segments I make the following code:</p> <pre><code>init = '2022-03-10 01:00:00' end = '2022-03-10 06:00:00' freq = '1h' bucket = pd.DataFrame( {'start_date': pd.date_range(s...
<p>This is what I came up with.</p> <p>First off the time on your method was:</p> <pre><code>%%timeit bucket_count(3600, df, inicio, fin) &gt;&gt;&gt; 44 ms ± 507 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) </code></pre> <p>Versus the method I came up with:</p> <pre><code>%%timeit bucket_count_new(3600, df,...
python|pandas|dataframe|numpy
1
2,987
42,148,670
Python convert large numpy array to pandas dataframe
<p>I have a chunk of code that I received that only works with pandas dataframes as input. I currently have a pretty large numpy array. I need to convert this into a pandas dataframe. </p> <p>The Dataframe will be 288 rows (289 counting the columns names) and 1801 columns. I have an array of size 1801 that will be al...
<p>You can pass a numpy array directly to the DataFrame constructor:</p> <pre><code>In [11]: a = np.random.rand(3, 5) In [12]: a Out[12]: array([[ 0.46154984, 0.08813473, 0.57746049, 0.42924157, 0.34689139], [ 0.29731858, 0.83300176, 0.15884604, 0.44753895, 0.56840054], [ 0.02479636, 0.76544594...
python|arrays|pandas|numpy|dataframe
5
2,988
43,212,725
Tensorflow multi-GPU training and variable scope
<p><strong>Context</strong></p> <p>I'm working on a detector model on multiple GPUs using Tensorflow 1.0. As suggested <a href="https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_multi_gpu_train.py" rel="nofollow noreferrer">here</a>, Gradients are computed on multiple GPUs individually a...
<p>In the cifar10 code, moving <code>grads = opt.compute_gradients(loss)</code> in front of the <code>tf.get_variable_scope().reuse_variables()</code> line should solve the problem.</p>
tensorflow|computer-vision
0
2,989
72,202,826
python equivalent of group_by, mutate using cur_group() (i.e. value of grouping variable)
<p>If I have a frame <code>d</code> and a function <code>f()</code> in R that looks like these:</p> <pre><code>df = data.frame( group=c(&quot;cat&quot;,&quot;fish&quot;,&quot;horse&quot;,&quot;cat&quot;,&quot;fish&quot;,&quot;horse&quot;,&quot;cat&quot;,&quot;horse&quot;), x = c(1,4,7,2,5,8,3,9) ) f &lt;- function(...
<p>We have <code>transform</code></p> <pre><code>d['out'] = d.groupby('group')['x'].transform('mean').mul(d['x'].add(1)) + d['group'].str.len() Out[540]: 0 7.0 1 26.5 2 69.0 3 9.0 4 31.0 5 77.0 6 11.0 7 85.0 dtype: float64 </code></pre>
python|r|pandas|dataframe
1
2,990
50,601,134
How do I calculate the confusion matrix in PyTorch efficiently?
<p>I have a tensor that contains my predictions and a tensor that contains the actual labels for my binary classification problem. How can I calculate the confusion matrix efficiently?</p>
<p>After my first version using a for-loop has proven inefficient, this is the fastest solution I came up with so far, for two equal-dimensional tensors <code>prediction</code> and <code>truth</code>:</p> <pre class="lang-python prettyprint-override"><code>def confusion(prediction, truth): confusion_vector = pre...
pytorch
1
2,991
45,539,117
How feed iterator of numpy array to tensorflow Estimator/Evaluable
<p>I have an iterator function that yields one batch of features and label as a tuple of numpy arrays.</p> <p>def batch_iter(): for ...: yield (np_features, np_labels)</p> <p>and then I try to feed the tensor Estimator like</p> <pre><code># the cnn_model_fn will print out shapes of various tensor ...
<p>in your input_fn you can use <code>tf.contrib.training.python_input</code></p>
python|numpy|tensorflow
1
2,992
62,812,706
Calculate pandas dataframe column not using for loops
<p>I have a data frame like this,</p> <pre><code>Date Open High to Low X 27-Feb-15 A P x1 26-Feb-15 B Q x2 25-Feb-15 C R x3 24-Feb-15 D S x4 </code></pre> <p>i need to calculate X column values like follows,</p> <pre><code>x1 = ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.window.Rolling.sum.html" rel="nofollow noreferrer"><code>Rolling.sum</code></a> with division by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.div.html" rel="nofollow noreferrer"><code>Series.div</co...
python|pandas
2
2,993
62,751,639
Put dict/json to dataframe
<p>I have the following input:</p> <pre><code>{'1LsquDfKDtz1uFz7txAVixkgFc82PHwqqp': {&quot;balance&quot;: 0}, '1FBGyQnLZrfwVZRdYNxbrqnKukm9trH5Ka': {&quot;balance&quot;: 0}, '1DSBqLVtDFgMypdo2yC77C5LZuTCHZS7St': {&quot;balance&quot;: 34}, ... </code></pre> <p>That I would like to put in a a dataframe. But I run the co...
<p>Add parameter <code>orient='index'</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.from_dict.html" rel="nofollow noreferrer"><code>DataFrame.from_dict</code></a>, then create index name by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFra...
python|pandas
1
2,994
62,777,242
What is the best way to install tensorflow and mongodb in docker?
<p>I want to create a docker container or image and have tensorflow and mongodb installed, I have seen that there are docker images for each application, but I need them to be working together, from a mongodb database I must extract the data to feed a model created in tensorflow.</p> <p>Then I want to know if it is pos...
<p>Interesting that I find this post, and just found one solution for myself. Maybe not the one for you, BTW.</p> <p>What I did is: docker pull mongo and run as daemon:</p> <pre><code>#!/bin/bash export VOLUME='/home/user/code' docker run -itd \ --name mongodb \ --publish 27017:27017 \ --volume ${VOLUME}:/c...
mongodb|docker|tensorflow
0
2,995
54,555,880
Pandas pivot_table using columns names
<p>I have a pandas dataframe that look like this : </p> <pre><code>ID, tag, score1 A1, T1, 10 A1, T1, 0 A1, T2, 20 A1, T2, 0 A2, T1, 10 A2, T1, 10 A2, T2, 20 A2, T2, 20 </code></pre> <p>Using pandas pivot_table function, I am able to pivot the table in order to obtain the f...
<p>Aggregate <code>mean</code> and then transpose by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html" rel="nofollow noreferrer"><code>T</code></a>:</p> <pre><code>df = df.groupby('tag').mean().T print (df) tag T1 T2 score1 7.5 15.0 score2 75.0 150.0 score3 ...
python|pandas|dataframe|pivot-table
1
2,996
54,261,202
Find those entries in numpy array bigger than input datetime
<p>I would like to get that entries of an datetime numpy array back that are bigger then my input datetime variable. </p> <p>Unfortunately, I get this error when executing the code below:</p> <pre><code>TypeError: '&gt;' not supported between instances of 'int' and 'datetime.datetime' </code></pre> <p>This is my cod...
<p>The problem is around comparing: <BR> myArray (of type np.datetime64) with <BR> myDateTime (of type pd.datetime) </p> <p>Changing myDateTime to a numpy datetime64 gives a result. </p> <pre><code>import numpy as np import pandas as pd myRange = pd.date_range('2018-04-09', periods=5, freq='1D20min') myArray = np.ar...
python|numpy
1
2,997
73,812,311
grouping the Datetime column on timestamp
<p>Existing Dataframe :</p> <pre><code>Unique_Id Date A 11-01-2022 10:20:30.500 A 11-01-2022 13:10:10:258 A 11-01-2022 17:30:22.223 A 11-01-2022 23:20:38.222 B 02-02-2022 08:25:30.000 B 04-02-2022 11:35:40.928 ...
<p>Here is one approach:</p> <pre><code>bins = [0,9,12,15,18,24] # function to convert hour as int to xAM/xPM h_to_str = lambda x: pd.to_datetime(str(x), format='%H').strftime('%-I%p') h_as_str = [h_to_str(x%24) for x in bins] labels = [f'{a} - {b}' for a,b in zip(h_as_str, h_as_str[1:])] df['Time_Group'] = pd.cut(pd....
pandas
1
2,998
73,809,000
In dataframe, if column is not available in sheet1 then ask to and ignore case and space sensitive
<p>Match all column's names from sheet2 to sheet1 if anything new, ask to add in sheet3, and ignore case sensitive</p> <p>In Sheet1 &quot;fName&quot; and in Sheet2 &quot;fname&quot; that should consider same (here, case sensitive) and replace name fName from <strong>sheet2</strong></p> <p>Same &quot;Full Name&quot; an...
<p>Try this below code after loading sheet1 &amp; sheet2 as df1 &amp; df2 respectively...</p> <pre><code>df3 = df1.copy() lst_col1 = df1.columns.to_list() lst_col2 = df2.columns.to_list() lst_col1_temp = [str(col).lower().replace(&quot; &quot;,&quot;&quot;) for col in lst_col1] lst_col2_temp = [str(col).lower().repla...
python|pandas|dataframe
1
2,999
52,434,353
fillcolor property colorstring hsl string not working
<p>I have a colorscale</p> <pre><code>colorscale2 = ['hsl(-2221.0, 60.0%, 98.0%)', 'hsl(-2192.0460921843687, 59.791583166332664%, 97.88777555110221%)', 'hsl(-2163.0921843687374, 59.58316633266533%, 97.7755511022044%)', 'hsl(-2134.138276553106, 59.37474949899799%, 97.6633...
<p>From <a href="https://www.w3schools.com/colors/colors_hsl.asp" rel="nofollow noreferrer">https://www.w3schools.com/colors/colors_hsl.asp</a>, the first value from hsl is hue which has a range from 0 to 360.0.</p> <p>The data that you have is not expected by relevant functions. Perhaps you may want to look into that...
python|colors|plotly|geopandas|choropleth
1