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
9,700
40,707,158
type conversion in python from float to int
<p>I am trying to change <code>data_df</code> which is type <code>float64</code> to <code>int</code>.</p> <pre><code>data_df['grade'] = data_df['grade'].astype(int) </code></pre> <p>I get the following error.</p> <blockquote> <p>invalid literal for int() with base 10: '17.44'</p> </blockquote>
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="noreferrer"><code>to_numeric</code></a> first because <code>float</code> cannot be cast to <code>int</code>:</p> <pre><code>data_df['grade'] = pd.to_numeric(data_df['grade']).astype(int) </code></pre> <p>An...
python|pandas
11
9,701
61,881,449
Unable to import TensorFlow_hub, getting "AttributeError: module 'tensorflow' has no attribute 'flags'" message
<p>I am trying to import TensorFlow hub in my local jupyter notebook but unable to do so. I have created a local conda environment installed all packages. Current tf version: Tensorflow 2.0 and local tf hub version : tensorflow-hub 0.1.1. when I run the "import tensorflow_hub as hub" code i get the below error.</p> <p...
<p>Since <code>TensorFlow Hub's</code> initial support for <code>Tensorflow 2.0</code> started from <code>TensorFlow Hub 0.3.0 version</code>, the issue is in the version of <code>TensorFlow Hub</code>(0.1.1) you are using which only supports Tensorflow 1.x versions. </p> <p>Upgrade your TensorFlow Hub to latest( 0.8...
python|tensorflow|bert-language-model
1
9,702
61,948,625
Python DataFrames has a concat or append problem
<p>My major is not programming or coding. But there's something to do with Python at work, and I have to do it. I studied alone for a month and made this code, but I'd like to change it to the right loop structure. How can I do it?</p> <ul> <li>Condition 1. df and mark changes 0 ~ 900.(not 0 ~ 10) </li> <li>Condition...
<p>You can try the following code:-</p> <pre><code>import urllib.request import json import pandas as pd import datetime Host = "https://oapi.saramin.co.kr/job-search?access-key=L8ILhlpIElsdz7BvhWQxcON3g8WBCSRyPTBEY7qlitt5ksdVBV6" headers = { Host: "oapi.saramin.co.kr", "Accept": "application/json"} df_list = list()...
python|pandas|dataframe|concat
0
9,703
61,810,759
Replace values of a column from another column with the same month and year
<p>I have a large data frame that looks like this</p> <pre><code>df: date close open 01/01/2012 5 5 01/02/2012 5 5 01/31/2012 5 5 02/29/2012 5 5 03/02/2012 5 5 10/15/2012 5 5 10/21/2012 5 5 11/21/2012 5 5 ........... . . </code></pre> <p>and have a ...
<p>Please Try</p> <p>In lieu of your comment. Can add</p> <p><strong>Dataframes used</strong></p> <p><a href="https://i.stack.imgur.com/mPjZm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mPjZm.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/7il97.png" rel...
python|pandas
0
9,704
57,795,697
tf.keras h5 to Tensorflow pb - resulting pb lacks output node even though input clearly has it?
<p>I am using Google Collab, training a sequence model (NASNet) with a custom output. I export my model to an h5 using the <code>model.save()</code> method. I use a separate ipynb to load my h5 and convert it to a pb, however, my resulting pb lacks a named output node, and I cannot get predictions from my resulting mod...
<p>So, it appears that tf 2.0 resolve this bug (see <a href="https://github.com/tensorflow/tensorflow/issues/26809" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/26809</a>) , which is unhelpful because 1.14 can export to a valid protobuf (which I need, I can't use the SaveModel new format in...
python|tensorflow|machine-learning|keras|deep-learning
0
9,705
57,876,790
Splitting dataframe based on multiple column values
<p>I have a dataframe with 1M+ rows. A sample of the dataframe is shown below:</p> <p><strong>df</strong></p> <pre><code> ID Type File 0 123 Phone 1 1 122 Computer 2 2 126 Computer 1 </code></pre> <p>I want to split this dataframe based on Type an...
<p>You can make do with <code>groupby</code>:</p> <pre><code>dfs = {} for k, d in df.groupby(['Type','File']): type, file = k # do want ever you want here # d is the dataframe corresponding with type, file dfs[k] = d </code></pre> <p>You can also create a mask:</p> <pre><code>df['mask'] = df['File']...
python-3.x|pandas
1
9,706
57,766,675
How to delete same data on the date in Python
<p>I have a csv file like below.<br></p> <pre><code>In 'order.csv' date orderName orderNumber state 1/7 Tom 1 1/7 Jeny 4 1/7 Brown 2 1/7 Tom 3 1/8 Sky 5 1/8 Blue 7 1/8 Red 6 1/8 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>DataFrame.duplicated</code></a> with <code>keep=False</code> for get all duplicates per columns specified in list and for set new column <a href="https://docs.scipy.org/doc/numpy/r...
python|pandas
4
9,707
58,153,888
How to set the input of a keras subclass model in tensorflow?
<p>I've created a keras subclass model using tensorflow. Snippets are shown below. </p> <pre class="lang-py prettyprint-override"><code>class SubModel(Model): def call(self, inputs): print(inputs) model = SubModel() model.fit(data, labels, ...) </code></pre> <p>When <code>fit</code> the model, it will ge...
<p>Something like that?</p> <pre><code>model_ = SubModel() inputs = tf.keras.input(shape=(100,)) outputs = model_(inputs) model = tf.keras.Model(inputs=inputs, outputs=outputs) </code></pre>
tensorflow|keras|subclass
3
9,708
34,239,537
How to Update Tensorflow from source
<p>I installed the latest <code>Tensorflow 0.5.0</code> from source via git clone. and want to update to <code>Tensorflow 0.6.0</code></p> <pre><code>git pull ./configure bazel build -c opt --config=cuda //tensorflow/cc:tutorials_example_trainer </code></pre> <p>but the Tensorflow library in the directory <code>/usr/...
<p>To install the TensorFlow library from source, you need to <a href="https://www.tensorflow.org/versions/master/get_started/os_setup.html#create-pip" rel="noreferrer">build a PIP package and install it</a>. The steps are as follows:</p> <pre><code>$ git pull $ ./configure $ bazel build -c opt //tensorflow/tools/pip...
tensorflow
10
9,709
36,856,076
Expand dataframe with dictionaries
<p>I've got a dataframe that contains a mostly NaN's, but also dictionaries in certain entries. My goal is expanding those dictionaries to columns of the dataframe and keeping their entries on their respective indices. This is what a small part of the dataframe looks like. </p> <pre><code> ...
<p>In order to expand the dictionary into a dataframe with multiple columns, you should <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">apply</a> a function that returns the dictionary as a pandas series. In order to do that, you have to remove <code>NaN</code>...
python|dictionary|pandas
4
9,710
55,133,051
Keras Output tensors to a Model must be the output of a Keras `Layer` (thus holding past layer metadata)
<p>I am trying to implement <strong>unpooling masks in Keras</strong>. I have a VGG encoder that outputs a specific feature map like relu5_1 and a list of unpooling masks.</p> <pre><code>def VGG19(input_tensor=None, input_shape=None, target_layer=1): """ VGG19, up to the target layer (1 for relu1_1, 2 for rel...
<p>When invoking the Model API, the value for outputs argument should be tensor(or list of tensors), in this case it is a list of list of tensors, hence there is a problem. Just unpack the unpooling_masks list(*unpooling_masks) when calling Model.</p> <pre><code>model = Model(inputs, [layer, *unpooling_masks], name='v...
python|tensorflow|keras|deep-learning
2
9,711
55,140,675
labelling variables pd dataframe
<p>In df, there are a lot of variables , included of <code>vaccine_preg</code>, <code>only_breastf</code> and so on .</p> <p>As data dictionary , </p> <pre><code>vaccine={'1':'Anti Tetanus Toxoid Injection', '2':'Polio Vaccine', '3':'BCG vaccine'} yndk={'1':'yes','0':'no','-88':'Prefer not to answer', '-99':"Don't kn...
<p>It sounds like you want to do:</p> <pre><code>df.vaccine_preg=df.vaccine_preg.map(vaccine) df.only_breastf=df.only_breastf.map(yndk) </code></pre> <p>If not your first line is overwriting your dataframe with the series returned from </p> <pre><code>df.vaccine_preg.map(vaccine) </code></pre>
python|pandas
0
9,712
49,633,725
Using Pandas with Idle
<p>I wrote code in spyder which does not work in python (3.6) IDLE.</p> <pre><code>import pandas as pd df = pd.read_excel('file.xlsx', usecols = ['A','B']) print(df) </code></pre> <p>This should print the DF but it just prints an empty frame. I have installed Pandas and xlrd. How do I make this work in IDLE?</p> <p...
<p>I think <code>usecols</code> need to be String if using column names:</p> <pre><code>df = pd.read_excel('file.xlsx', usecols = 'A,B') </code></pre> <p>I have tested this and as mentioned above is the case.</p> <p>From Documentation : </p> <blockquote> <p>usecols : int or list, default None</p> <p>If None ...
python|pandas|spyder|python-idle
2
9,713
73,361,613
Tensorflow define lossfunction
<p>The following code works, converges and the neural net approximates the exponential on the interval from 0 to 1:</p> <pre><code># code works import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # fit an exponential n = 101 x = np.linspace(start=0, stop=1, num=n) y_e = np.exp(x) # any odd ...
<p>I think your problem may be that you are using a global variable (y_e) in the second version of your loss function. There's no guarantee, or even reasonable expectation, that the value of this will be updated in the right way, batch by batch, when the loss function is called.</p> <p>Loss has to be calculated from y_...
python|tensorflow|loss-function
2
9,714
35,234,196
Optimizing a DBSCAN to run computationally
<p>I am running DBSCAN algorithm in Python on a dataset (modelled very similar to <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html" rel="nofollow noreferrer">http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html</a> and loaded as a pandas dataframe) that has a total of ~ 3 ...
<p>Have you considered to do: </p> <ul> <li>partitioning, cluster one day (or less) at a time</li> <li>sampling, break your data set randomly into 10 parts. process them individually</li> </ul>
python-2.7|scipy|scikit-learn|dbscan|sklearn-pandas
1
9,715
35,262,294
Scipy ndimage median_filter origin
<p>I have a binary array, say, <code>a = np.random.binomial(n=1, p=1/2, size=(9, 9))</code>. I perform median filtering on it using a <code>3 x 3</code> kernel on it, like say, <code>b = nd.median_filter(a, 3)</code>. I would expect that this should perform median filter based on the pixel and its eight neighbours. How...
<p>origin says it accepts only a scalar, but for me it also accepts array-like input as also the case for the <a href="http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.ndimage.filters.convolve.html" rel="nofollow">scipy.ndimage.filters.convolve</a> function. Passing 0 is indeed the center of the footpri...
python|numpy|scipy|median|ndimage
3
9,716
35,189,778
conditional filtering in a numpy matrix
<p>I have such a matrix:</p> <pre><code>[[1,2,3,4,5,6] ['a','b','c','d','e'] [1,2,3,4,5,6] [1,2,3,4,5,6] [1,2,3,4,5,6] [1,1,1,0,0,0] [1,2,3,4,5,6]] </code></pre> <p>And I want to make this query: <code>pos_data = data[data[:, 5] == 1]</code></p> <p>But I get this error: </p> <blockquote> <p>IndexError: too ...
<p>Don't you have an other error in your workflow ? It seems to work in my test :</p> <pre><code>data = np.random.randint(1, 23, (22136, 27)) data.shape # (22136,27) res = data[data[..., 5] == 1] res.shape # (1001, 27) res #array([[21, 10, 18, ..., 10, 12, 20], # [ 7, 20, 12, ..., 10, 13, 7], # [ 1, 12, ...
python|numpy
1
9,717
67,340,423
Send Outlook Emails with attachments in Python (pywin32)
<p>I am trying to use the library pywin32 to write Outlook e-mails in Python. I have a dataframe that has some recipients' emails and attachment paths. I'd like to know how to add all attachments under each unique recipient?</p> <pre><code>print(my_df) Receiver_Email Attachment_Path ...
<p>Do a <code>groupby</code> on the email addresses, which creates unique dataframes, then iterate on the mail attachments. Something like this should work:</p> <pre><code>GB = my_df.groupby(&quot;Receiver_Email&quot;) for ID , DF in GB: outlook = client.Dispatch('Outlook.Application') mail = outlook.CreateItem...
python|pandas|email|pywin32
1
9,718
67,222,055
Splitting data into batches
<p>I currently have the following data:</p> <pre><code>f_map, inputs, s_bias = ml_dataset.dataset_for_s_bias() </code></pre> <p>where f_map is a tensor of matrices, inputs is a tensor of floats, and s_bias is a tensor of floats. The first two, f_map and inputs, are the inputs to my ML regression algorithm, and s_bias i...
<p>I figured it out. When I was using the dataloader originally, I assumed that the dataloader itself was one batch. However, I needed to iterate over the dataloader to access the batches within. Those batches have the correct type (tensor).</p>
split|pytorch|dataset|batch-processing|dataloader
0
9,719
67,268,658
Checking if some particular string exists in a column of a dataframe or not ; if exists then add a prefix to it
<p>i want a solution where i have to check if values of a dataframe column has specific code and if it is so i will add a predefined prefix to it. to make it easier please look into the folowing example. For say i have a Dataframe like below.</p> <pre><code>PRODUCT_KEY EXI-CD_5S-WW5678 EX-PWN-PRO-193 EX-NIS-NS-HZ049 EX...
<p>Using <code>np.where</code> with <code>.str.startswith</code></p> <p><strong>Ex:</strong></p> <pre><code>import numpy as np df[&quot;New&quot;] = np.where(df[&quot;PRODUCT_KEY&quot;].str.startswith(('AU', 'NL','HK','WW')), &quot;GST-YIP-&quot;+df[&quot;PRODUCT_KEY&quot;], df[&quot;PRODUCT_KEY&quot;]) print(df) </co...
python|pandas
1
9,720
67,211,250
Numpy Integer Array to Hex String Array without "0x"
<pre><code>array([(1, 1, 0, 2, 240), (1, 1, 0, 255, 255), (1, 1, 0, 255, 255), ..., (1, 1, 0, 255, 255), (1, 1, 0, 255, 255), (1, 1, 0, 255, 60)], dtype=[('A','u1'), ('B','u1'), ('C','u1'), ('D','u1'), ('E','u1')]) </code></pre> <p>I have a numpy array as shown above and I want to print them to a file in H...
<p>Ok I did some more work on this and I found this solution that worked for me:</p> <pre><code>numpy.savetxt(&quot;my_file.txt&quot;, my_numpy_structured_array, delimiter=&quot; &quot;, fmt=&quot;%x %x %x %02x %02x&quot;) </code></pre>
string|numpy
1
9,721
67,437,452
Iterate over rows and select all between max and min
<p>Suppose I have a Pandas DataFrame like the following:</p> <pre><code>ID update_time cap date diff A 05/05/21 1:45 136 05/05/21 136 A 05/05/21 1:50 0 05/05/21 -136 A 05/05/21 2:10 1 05/05/21 1 A 05/05/21 2:15 0 05/05/21 -1 A 05/05/21 3:35 1 05/05/21 1 A 05/05/21 ...
<p>You need to first perform a <code>groupby</code> on the <code>ID</code> and <code>date</code> since you want <code>&quot;all rows before a drop to 0 occurs in caps&quot;</code> for each unique ID-date combination. Then we will apply a custom function that selects all rows before the occurrence of the first zero. The...
python|pandas|dataframe|data-science
2
9,722
67,285,481
Read multiple excels according to the date and year you have
<p>How can I read multiple xlsx files in order and place them in the same dataframe?</p> <p>Right now I have the following code which is giving me <code>Error: No such file or directory: 'C:\\Users\\HN_1701.xlsx'</code></p> <pre><code>months=['01','02','03','04','05','06','07','08','09','10','11','12'] years=['21','20...
<p>You could try something like this. Here, I do this for csv-files but it works the same with xlxs files. I look at a private folder but you can translate this to your own. First, define all the years, months and days you need. Create an empty df.</p> <pre><code>import pandas as pd months=['04'] day = ['13','14','21']...
python|excel|pandas
0
9,723
34,823,593
how to add new item in pandas series without erasing other items
<p>I have a following pandas series. </p> <pre><code>new_orders_list Out[853]: Cluster 1 [525, 526, 533] Cluster 2 [527, 528, 532] Cluster 3 [519, 534, 535] Cluster 4 [530] Cluster 5 [529, 531] Cluster 6 [520, 521, 524] </code></pre> <p>And,I have two more series which I get after so...
<p>You can try this solution. </p> <p>New Series of remove data was created and was called <code>remseries</code>. </p> <p>Types of values in <code>lists</code> in <code>Series</code> <code>new_orders_list</code> are integers and types of other <code>Series</code> are <code>strings</code>, so all values are converted...
python|pandas
1
9,724
60,328,184
Is there a way to insert into numpy array in a loop?
<p>I have a 2D numpy array of :</p> <pre><code>[[9.29526424407959, -3.68755626678467], [9.7620153427124, -2.16865086555481], [9.9980001449585, 0.199986666440964], [9.95050621032715, 0.993697226047516], [9.84010124206543, 1.78112530708313], [9.43374633789063, 3.31729197502136], [8.7891960144043, 4.7696990966...
<pre><code>your_array = [[9.29526424407959, -3.68755626678467], [9.7620153427124, -2.16865086555481], [9.9980001449585, 0.199986666440964], [9.95050621032715, 0.993697226047516], [9.84010124206543, 1.78112530708313], [9.43374633789063, 3.31729197502136], [8.7891960144043, 4.76969909667969], [8.382458686828...
python|python-2.7|numpy
1
9,725
59,908,131
Thonny : installing tensorflow and importing it
<p>I am having trouble importing and installing tensorflow. I can't install it via that Thonny manage package option nor via the command window for windows operators. I get the same error for both ways:</p> <p><strong>ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none) Error...
<p>There are two important rules to install Tensorflow:</p> <ul> <li><p>You have to install Python <strong>x64</strong>. It doesn't work on 32b and it gives the same error as yours.</p></li> <li><p>It <strong>doesn't</strong> support the latest version of Python3 = 3.8.</p></li> </ul> <p>For example, you can install ...
python|tensorflow|machine-learning|data-science|thonny
0
9,726
59,948,610
numpy import error ModuleNotFoundError: No module named 'numpy.core._multiarray_umath'
<p>I got the following numpy error. I have tried 1. But it did solve the problem. Would you please let me know how to fix the problem? Thanks.</p> <pre><code>$ python3 Python 3.8.0a3 (v3.8.0a3:9a448855b5, Mar 25 2019, 17:05:20) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" fo...
<p>The problem is that I had Python 3.8.0a3 installed. I updated it to 3.8.1. Now the problem is solved.</p>
python-3.x|numpy
0
9,727
65,272,827
How to get index.cuda?
<p>I am reading a code about CMC downloaded from github, and it can't work on vscode.</p> <p>Code:</p> <pre><code>if torch.cuda.is_available(): index = index.cuda(async=True) inputs = inputs.cuda() </code></pre> <p>Error message is as follows:</p> <pre><code> File &quot;e:\CMC-master\train_CMC.py&quot;...
<p>Try using <code>non_blocking=True</code> instead:</p> <pre class="lang-py prettyprint-override"><code>index = index.cuda(non_blocking=True) </code></pre> <p>See <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor.cuda" rel="nofollow noreferrer"><code>Tensor.cuda</code></a> for more information, and <a...
python|pytorch
1
9,728
50,148,708
how do I best validate email in pandas data frame
<p>I have a data frame (df) with emails and numbers like</p> <pre><code> email euro 0 firstname@firstdomain.com 150 1 secondname@seconddomain.com 50 2 thirdname@thirddomain.com 300 3 kjfslkfj 0 4 fourthname@fourthdomain.com 200 </code></pre...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="noreferrer"><code>apply</code></a>, chain mask by <code>&amp;</code> for <code>AND</code> and filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer"><code>boolean...
python|pandas|validation|email|dataframe
8
9,729
50,136,563
Pandas Relative Time Pivot
<p>I have the last eight months of my customers' data, however these months are not the same months, just the last months they happened to be with us. Monthly fees and penalties are stored in rows, but I want each of the last eight months to be a column. </p> <p>What I have:</p> <pre><code>Customer Amount Penalties M...
<p>You can do it with <code>unstack</code> and <code>set_index</code> </p> <pre><code># assuming all date is sort properly , then we do cumcount df['Month']=df.groupby('Customer').cumcount()+1 # slice the most recent 8 one df=df.loc[df.Month&lt;=8,:]# slice the most recent 8 one # doing unstack to reshape your df...
python|pandas|csv|dataframe|pivot
4
9,730
50,009,542
CNN Training in Keras freezes
<p>I am training a CNN model in Keras (Tensorflow backend). I have used on the fly augmentation with <code>fit_generator()</code>. The model takes images aa input and is supposed to predict the steering angle for a self driving car. The training just freezes after this point. I have tried changing the batch size, learn...
<p>You have a weird structure for the data generator and that is most likely causing this issue, though I cannot be completely sure.</p> <p>You structure is as follows:</p> <pre><code>while 1: .... for _ in range(batch_size): randomly select an image # this is inefficient, see below for comments ...
tensorflow|keras|convolutional-neural-network
0
9,731
50,106,163
Having an N element output from rejection sampling for N elements
<p>I am applying a rejection sampling for N elements given probability density function <code>pdf</code>. When applying this method for N elements, it is likely that you will return an array of values that has less number of elements compared to the N number you are evaluating, which is from applying the rejection meth...
<p>Here is one way using boolean and advanced indexing. It keeps a list of indices at which values were rejected and redraws these values until the list is empty.</p> <p>Example sampling and accept/reject functions:</p> <pre><code>def sample(N): return np.random.uniform(-3, 3, (N,)) def accept(v): return np....
python|numpy
1
9,732
47,058,879
How to work with numpy.where?
<p>I want to find indexes of array like <code>x = np.array([[1, 1, 1], [2, 2, 2]])</code> where elements equals to <code>y = np.array([1, 1, 1])</code>. So I did this:</p> <pre><code>In: np.where(x == y) Out: (array([0, 0, 0]), array([0, 1, 2])) </code></pre> <p>It is the correct answer. But I expect to get only inde...
<p>You need to use <code>(x == y).all(axis=1)</code> to reduce the comparison result over <code>axis=1</code> first, i.e <em>all elements are equal</em>:</p> <pre><code>np.where((x == y).all(axis=1))[0] # array([0]) </code></pre>
python|numpy|array-broadcasting
3
9,733
47,032,167
Pandas get date value by index
<p>df_transactions is a dataframe that looks like this:</p> <pre><code> id date is_cancel 0 A 2017-10-30 0 1 A 2017-10-31 1 2 B 2017-09-14 0 3 B 2017-09-15 0 </code></pre> <p>I did</p> <pre><code>mask = df_transactions.groupby('id',as_index=False)['is_cancel'].nth(-1)==1 </c...
<p>There is possible <code>mask</code> return more <code>True</code>s, so need select value by position - e.g. first value by <code>[0]</code>:</p> <pre><code>print (df_transactions) id date is_cancel 0 A 2017-10-30 0 1 A 2017-10-31 1 2 B 2017-09-14 0 3 B 2017-09-15 ...
python|pandas
0
9,734
47,052,433
Multiple instructions for np.where python pandas
<p>I would like to do something like :</p> <pre><code>if condition: instruction 1 instruction 2 ... instruction N </code></pre> <p>Do I have to repeat the np.where statement multiple times ?</p> <pre><code>my_df["1"] = np.where(condition, instruction1, other) my_df["2"] = np.where(condition, instru...
<p>Without knowing more details, maybe something like that:</p> <pre><code>instructions = [instruction1, instruction2, ..., instructionN] for i in range(len(instructions)): my_df[str(i+1)] = np.where(condition, instructions[i], other) </code></pre>
python|pandas|numpy
0
9,735
32,959,721
Is there a function that sums dependent data types?
<p>I have a dataframe in pandas with the columns <code>Year</code> (int), <code>Loc</code> (ordered pair of ints), and <code>Rain</code> (boolean). There are many data points of <code>Rain</code> for each <code>Year</code>. For example, in the graph, you might see:</p> <pre><code>Year | Loc | Rain 1700 ...
<p>Do you mean to group by "Year" and "Loc" and show SUM of Rain? something like the following?</p> <pre><code>df.groupby(['Year', 'Loc']).sum().reset_index() </code></pre>
python|pandas
1
9,736
32,799,076
Filter our elements of matrices where both/neither/either are nonzero?
<p>I have two <code>numpy</code> arrays <code>A</code>, and <code>B</code>. I want to create arrays <code>Ap</code> and <code>Bp</code> such that <code>Ap</code> and <code>Bp</code> are all elements of <code>A</code> and <code>B</code> where at least one of <code>A</code> or <code>B</code> is nonzero and, alternatively...
<p>You use masked indices to achieve that.</p> <pre><code>A = np.asarray(A) B = np.asarray(B) ind1 = A!=0 ind2 = B!=0 </code></pre> <p>then, to achieve the first case (<code>|</code> is an "or" operator):</p> <pre><code>case1 = ind1 | ind2 Ap = A[case1] Bp = A[case1] </code></pre> <p>whereas for the second case (...
python|arrays|numpy
1
9,737
32,850,491
Applying np.dot to each row of two DataFrames
<p>Let's say that I have two Pandas DataFrames of equal shape and I'd like to produce a Series which is the row-wise (thinking of using pandas.DataFrame.apply) dot product of the two DataFrames.</p> <p>So, for example:</p> <pre><code>df1 = pd.DataFrame(np.random.rand(1000,10)) df2 = pd.DataFrame(np.random.rand(1000,1...
<p>You could multiply the two DataFrames together, and then sum along <code>axis=1</code>:</p> <pre><code>df1 = pd.DataFrame(np.random.rand(1000,10)) df2 = pd.DataFrame(np.random.rand(1000,10)) result = (df1*df2).sum(axis=1) </code></pre> <p>Note that when you multiply two DataFrames together, Pandas aligns the rows ...
python|pandas
8
9,738
32,775,415
How can i get statistics on the empty fields in DataFrame
<p>I have a dataframe:</p> <pre><code>| city | field2 | field3 | field4 | field5 | | 1 | a | | b | b | | 2 | | | c | | | 3 | | a | | | | 4 | a | | | | | 1 | | a | | b | | 2 | ...
<pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ "city": [1,2,1,2,1,2], "field2": [np.nan, "a", np.nan, np.nan, "b", np.nan], "field3": [np.nan, np.nan, np.nan, "b", "a", "b"], }) df </code></pre> <p>This is my example data:</p> <pre><code> city field2 field3 0 1 NaN N...
python|pandas
3
9,739
33,022,290
Writing datetime.datetime() column using pandas.to_sql()
<p>I have a single column dataframe <code>df</code> which has column <code>TS</code> where</p> <pre class="lang-python prettyprint-override"><code>In [1]: type(df.TS.values[0]) Out[1]: pandas.tslib.Timestamp </code></pre> <p>I convert the column to type <code>datetime.datetime()</code> </p> <pre class="lang-python p...
<p>In my case (working with a <code>PostgreSQL</code> database) the data type for the timestamp column is <code>sqlalchemy.DateTime</code></p> <pre><code>import sqlalchemy dtype = { &quot;TS&quot;: sqlalchemy.DateTime } df.to_sql(name=&quot;Table&quot;, con=engine, if_exists=&quot;append&quot;, index=False, dt...
python|datetime|pandas|sqlalchemy|sqldatatypes
1
9,740
38,606,393
Pandas pivot table arrangement no aggregation
<p>I want to pivot a pandas dataframe without aggregation, and instead of presenting the pivot index column vertically I want to present it horizontally. I tried with <code>pd.pivot_table</code> but I'm not getting exactly what I wanted.</p> <pre><code>data = {'year': [2011, 2011, 2012, 2013, 2013], 'A': [10, ...
<p>You can first create column for new index by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="noreferrer"><code>cumcount</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="noreferrer"><code>st...
python|pandas|dataframe|pivot
8
9,741
38,919,546
Correlation: make a graph
<p>I have dataframe and I try to print graph. I use</p> <pre><code>df = pd.read_excel('resp1.xlsx') corr = df.corr() sns.set(context="paper", font="monospace") df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) f, ax = plt.subplots(figsize=(12, 9)) sns.heatmap(corr, vmax=.8, square=True) networ...
<p>I'm not sure, but I think those %1 errors are related to mixing 64 bit and 32 bit of app/dll. You also have the <code>win32</code> hint. Perhaps you use a 64 bit python with 32 bit package (pandas or other) or the opposite.</p>
python|pandas|matplotlib|seaborn
0
9,742
67,671,251
pandas get a sum column for next 7 days
<p>I want to get the sum of values for next 7 days of a column</p> <p>my dataframe :</p> <pre><code> date value 0 2021-04-29 1 1 2021-05-03 2 2 2021-05-06 1 3 2021-05-15 1 4 2021-05-17 2 5 2021-05-18 1 6 2021-05-21 2 7 2021-05-22 5 8 2021-05-24 4 </code></p...
<p>With a list comprehension:</p> <pre><code>tomorrow_dates = df.date + pd.Timedelta(&quot;1 day&quot;) next_week_dates = df.date + pd.Timedelta(&quot;7 days&quot;) df[&quot;next_7days&quot;] = [df.value[df.date.between(tomorrow, next_week)].sum() for tomorrow, next_week in zip(tomorrow_dates, next...
python|pandas|dataframe
1
9,743
67,916,090
UnimplementedError: "Cast string to float is not supported" | Function call stack: predict_function
<p>I'm trying to do multivariate time series forecasting, but when I call <code>model.predict(input_x, verbose=1)</code> it returns</p> <pre><code>UnimplementedError: Cast string to float is not supported [[node sequential_5/Cast (defined at &lt;ipython-input-6-ebf024c56d89&gt;:111) ]] [Op:__inference_predict_fun...
<p>Input has to be integer array, you need encode string input to integer</p>
python|numpy|tensorflow|machine-learning|numpy-ndarray
1
9,744
68,013,917
Pandas concatenate columns values as list across columns and then dump the whole dataframe into numpy array
<p>I have a dataframe with 10 columns with each elements as list of length 40.How can i convert them into numpy array of shape (-1,400) . <a href="https://i.stack.imgur.com/s5xFO.jpg" rel="nofollow noreferrer">column (click this link to see the column) </a></p>
<p>Try: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply()</code></a> + <a href="https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer"><code>numpy.concatenate()</code></a> + <a href="htt...
python|pandas|dataframe|numpy
1
9,745
67,862,848
Pandas pivot_table: filter on aggregate function
<p>I am trying to pass a criteria to the aggregate function to pandas pivot_table and I am not able to figure out how to pass the criteria to the aggfunc. I have a data table which is converted to pandas df.</p> <p>The input table data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style=...
<p>You can't compare the word 'max' to 100 via <code>&gt;=</code> (<code>aggfunc = 'max' &gt;= 100</code>):</p> <p>I recommend not setting the fill value to a string, masking the DataFrame, to get rid of undesired rows, <em>then</em> replace with empty string via <a href="https://pandas.pydata.org/pandas-docs/stable/re...
python|pandas|dataframe|pandas-groupby|pivot-table
1
9,746
32,119,073
Replacing space with a character
<p>I need to replace all the spaces in a dataframe column with a period. ie:</p> <p>Original df:</p> <pre><code> symbol 0 AEC 1 BRK A 2 BRK B 3 CTRX 4 FCE A </code></pre> <p>Desired result df:</p> <pre><code> symbol 0 AEC 1 BRK.A 2 BRK.B 3 CTRX 4 FCE.A </code></pre> <p>Is there a way to d...
<p>Use vectorised <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html#pandas.Series.str.replace"><code>str.replace</code></a>:</p> <pre><code>In [95]: df['symbol'] = df['symbol'].str.replace(' ','.') df Out[95]: symbol 0 AEC 1 BRK.A 2 BRK.B 3 CTRX 4 FCE.A </code></p...
python|pandas
5
9,747
31,837,202
Initializing numpy string array using for loop failing for some elements
<p>I am trying to create an array of binary strings each exactly 16 bits long.</p> <p>I have declared an empty string array which holds up to 20 characters for each element:</p> <pre><code>bin_array = np.empty(len(dat_array), dtype="S20") </code></pre> <p>Then I assign each element using this loop:</p> <pre><code>f...
<p>The problem is that you've used <code>i</code> as the index in both the inner and outer for loops. You can change the inner index to <code>k</code>, say or simply eliminate the inner loop and use <code>zeros = number_of_zeros * "0"</code></p>
python|arrays|numpy
1
9,748
61,200,342
in a dataframe, after you pivot a table but you want to stack values one below another?
<p>This is the output, but i want the values of zoo to come below baz and have another column showing baz/zoo.</p> <pre><code>df.pivot(index='foo', columns='bar', values=['baz', 'zoo']) baz zoo bar A B C A B C foo one 1 2 3 x y z two 4 5 6 q w t </code></pre>
<p>You can use <code>stack</code> and indicate the level you wish to stack in long format:</p> <pre><code>import pandas as pd import numpy as np idx = pd.MultiIndex.from_product([['bar', 'zoo'], ['A', 'B', 'C']]) df = pd.DataFrame(np.random.randn(6, 6), columns=idx) </code></pre> <p>This is my dataframe (looks simila...
pandas|dataframe|pivot
1
9,749
61,190,271
Pandas fixing Date Index from 2061 to 1961
<p>Data set: </p> <pre><code> RPT VAL Date 2061-01-01 15.04 14.96 2061-01-02 14.71 NaN 2061-01-03 18.50 16.88 2061-01-04 10.58 6.63 2061-01-05 13.33 13.25 </code></pre> <p>For above data set i am trying to fix the Date Index, such as 2061 ...
<p>You can make the Date index a Date column and generate a fake index (could be a simple counter for instance), then apply this filter to the column Date. Finally, you can use the modified Date column as index again.</p>
python-3.x|pandas
1
9,750
68,722,928
Grouping rows from Pandas Dataframe with column value within 20% of first value in group
<p>Say I have a Pandas Dataframe below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>value</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>1</td> </tr> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>2</td> <td>1.2</td> </tr> <tr> <td>3</td> <td>1.6</td> </tr> <tr> <td>4</td> <td>1...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;group&quot;] = np.nan group = 0 while (m := df[&quot;group&quot;].isna()).any(): val = df.loc[m.idxmax(), &quot;value&quot;] df.loc[m &amp; (np.abs(df[&quot;value&quot;] - val) &lt;= val * 0.2), &quot;group&quot;] = group group += 1 print...
python|pandas|dataframe|pandas-groupby|rows
0
9,751
68,817,621
How to build a comparison and update function of tables in pandas?
<p>I try to build a comparison function between an old and an new version of a table. The single constant is the amound and name of columns. The amount of rows may change when new entries appear in the new version of the table. The output should be a updated table, where new entries are taken as additinonal rows and de...
<ol> <li>Use <code>pandas.merge</code> to merge the old and new tables.</li> <li><code>groupby</code> on the &quot;ID&quot; column and use custom <code>agg</code> functions.</li> <li>Assign the required &quot;Status&quot; using <code>map</code>.</li> </ol> <pre><code>frame_old = pd.DataFrame({'ID' : [&quot;IQL_000&quot...
python|pandas|dataframe
1
9,752
68,558,731
Specific complicated filtering of Pandas dataframe rows
<p>The data has many columns but the ones in question are as follows:</p> <pre><code> MR Version GB1 Package GB5 Package GB9 3.5 GB5 3.3 GB1 Package GB9 1.5 GB359 9.1 GB1 Package GB99 5.5 ... </code></pre> <p>MR (model) names are repeating and the <code>Package</co...
<p>It is not clear. Do you expect <code>Package</code> to be present in addition to other values?</p> <h3 id="if-yes-oodo">if yes</h3> <p>You can groupby <code>MR</code> and check if <code>Package</code> is present together with other values:</p> <pre><code>def good_or_bad(s): s=set(s) if 'Package' in s and len...
python|pandas|dataframe|for-loop|jupyter-notebook
1
9,753
68,816,875
How to add percent symbol to each value in a row where index finished on defined string in Python Pandas?
<p>I have Data Frame in Python Pandas like the below:</p> <pre><code>IDX | col1 | col2 ----------------- X_sum | 548 | 1200 X_perc | 3.82 | 57.45 Y_sum | 123 | 435 Y_perc | 11.98 | 22.87 </code></pre> <p>And column &quot;IDX&quot; is here as index column. And I need to add symbol &quot;%&quot; next to each v...
<p>You can use <code>str.endswith</code> for <code>index</code> of the dataframe to check if a value ends with <code>_perc</code>, then assign the value converted to string plus percentage sign to such row values, otherwise just the default value. You can use <code>np.where</code> for this:</p> <pre class="lang-py pret...
python|pandas|dataframe
1
9,754
36,607,862
error in using DataFrame.mul, related to ndarray
<p>I reference from this article,<a href="https://stackoverflow.com/questions/15753916/dot-products-in-pandas">Get dot-product of dataframe with vector, and return dataframe, in Pandas</a>, to use DataFrame.mul.<br/><br/> my problem code is this<br/></p> <pre><code>df.mul(weight) </code></pre> <p>where weight is data...
<p>From <code>help(pd.DataFrame.mul)</code>:</p> <blockquote> <p><code>mul(self, other, axis='columns', level=None, fill_value=None)</code> unbound <code>pandas.core.frame.DataFrame</code> method</p> <p>Multiplication of <code>dataframe</code> and <code>other</code>, element-wise (binary operator <code>mul</cod...
numpy|pandas|error-handling|dataframe
0
9,755
53,144,480
An unexpected increase of the number of rows after using dataframe.merge
<p>I have some dataframes in a dictionary, and I want to merge all these dataframes using a common column "date". To do so, I used the following code :</p> <pre><code>n = len(dictionary) something = dictionary[dictionnary_keys[0]] for i in range(1,n): something = something.merge(dictionary[dictionnary_keys[i], on...
<p>You most likely have duplicated <code>date</code> values.</p> <p>Here is a quick example:</p> <pre><code># Generate dict of DatFrame with duplicated 'a' d = dict() for i in range(4): d[i] = pd.DataFrame({'a': list('ABBCD'), 'b':np.random.randint(0, 10, 5), 'c': i}) n = len(d) s = d[0] for i in range(1,n): ...
python|pandas
2
9,756
52,993,773
A Difficult Deduplication
<p>I have a large dataframe, and I want to basically create a "unique identifier" for every separate person. The relevant column is the "e-mail" column, but it's made difficult by the formatting: each person can have multiple e-mails. Example frame below:</p> <pre><code>Name of person ||| E-mail Address 'John Doe' ...
<p>Assuming there is a typo on the shared email, this is a multiple steps problem that involves pandas and networkx libraries, this is a network problem, and I took inspiration from these 2 questions <a href="https://stackoverflow.com/questions/52993119/groupby-two-column-values-and-create-a-unique-id">network problem<...
python|python-3.x|pandas|dataframe
4
9,757
65,664,596
pandas.series.drop_duplicates() cannot delete all duplicates
<pre><code>&gt;&gt;&gt; info 0 (dataset, license, sources, weight) 1 (dataset, license, sources, weight) 2 (dataset, license, sources, weight) 3 (dataset, license, sources, weight) 4 (dataset, license, sources,...
<p>The reason the first and second row is equal that you are still checking the original dataframe, not the output you removed duplicates from. Most functions (but not all, always check the documentation) in pandas that modify DataFrame/Series, they don't change the original data by default instead they just return the...
python|pandas|dataframe
1
9,758
65,735,629
List of matrices: plot each element of matrix as a function of an index
<p>I have a list of matrices. I would like to plot each element of those matrices in function of another list.</p> <p>However I am struggling to do it without using a loop.</p> <p>How can I do it in the simplest way ?</p> <p>Below a code explaining a little bit more what I want to do.</p> <pre><code>import numpy as np ...
<p>I don't think there is any way to do this completely without loops, but this way is somewhat compact. There is further cleverness to be done if you want, but the code below is a trade off in terms of explicitness and ease to understand.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import ma...
python|list|numpy|matplotlib
0
9,759
3,136,432
Find root of implicit function in Python
<p>I have an implicit function, for example:</p> <pre><code>f(x,y) = x**y + y**y - 3*x </code></pre> <p>I want to solve the root on a meshgrid. So f(x,y) = 0</p> <p>Drawing the solution is easy:</p> <pre><code>x = linspace(-2,2,11) y = linspace(-2,2,11) (X,Y) = meshgrid(x,y) A = X**Y + Y**Y - 3*X contour(X,Y,A,0) ...
<p>You can get "the data that is in the [matplotlib] plot" using:</p> <pre><code>cs = contour(X,Y,A,0) data = cs.collections[0].get_paths()[1] </code></pre> <p>There are a variety of algorithms for calculating the contours directly, though I don't know of any numpy/scipy versions. <a href="http://en.wikipedia.org/wi...
python|numpy|root|implicit
3
9,760
63,680,197
Python - initialising and storing data of varying size and dimension
<p>I have multiple files of 3D data that I am trying to read in to my Python script in a more efficient manner. Currently I am changing everything manually rather than by loops, so I would like to automate this a bit.</p> <p>The data breaks down like this: each file represents data at a different location. Each locatio...
<p>Since the temp variable of varying size, I would recommend appending to a list and then reshape it using numpy.</p> <pre class="lang-py prettyprint-override"><code># Initialize a grid array grid_count_arr = np.full((max(path), max(filter), -1) # Inside the loop grid_list.append(temp) grid_count_arr[i,j] = curr_list...
python|arrays|numpy
1
9,761
21,583,073
pandas compare and select the smallest number from another dataframe
<p>I have two dataframes.</p> <pre><code>df1 Out[162]: a b c 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 10 10 10 10 11 11 11 11 df2 Out[194]: A B 0 a 3 1 b 4 2 c 5 </code></pre> <p>I ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> for row-wise methods:</p> <pre><code>In [54]: # create our data import pandas as pd df1 = pd.DataFrame({'a':list(range(12)), 'b':list(range(12)), 'c':list(range(12))}) df1 Out[54]: ...
python|pandas
2
9,762
21,453,843
How can I apply a function to pairs of elements in a list with Python?
<p>I have a list of numbers and I want to find the difference of the elements in it as a percentage. Currently I am using a for loop. Is there another way, maybe using numpy ?</p> <pre><code>example_list = [1., 5., 4., 2., 10., 8., 3., 1.] percentage_difference = [] for index, i in enumerate(example_list): if inde...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html" rel="nofollow"><code>numpy.diff</code></a> for this:</p> <pre><code>In [13]: import numpy as np In [14]: a = np.array([1., 5., 4., 2., 10., 8., 3., 1.]) In [15]: np.diff(a)/a[1:] ...
python|list|numpy
2
9,763
24,699,053
Stepinfo in Python
<p>I am trying to determine the following step characteristics for a step response in Python: </p> <ul> <li>RiseTime</li> <li>SettlingTime</li> <li>SettlingMin</li> <li>SettlingMax</li> <li>Overshoot</li> <li>Undershoot</li> <li>Peak</li> <li>PeakTime</li> </ul> <p>Matlab offers me the function <a href="http://www.ma...
<p>This <a href="http://sourceforge.net/p/python-control/discussion/1022992/thread/3d038097/" rel="nofollow">discussion</a> suggests a sort of implementation:</p> <pre><code>def step_info(t,yout): print "OS: %f%s"%((yout.max()/yout[-1]-1)*100,'%') print "Tr: %fs"%(t[next(i for i in range(0,len(yout)-1) if yout...
python|matlab|numpy|scipy|control-theory
3
9,764
29,872,699
Python Pandas velocity
<p>I have a DataFrame, where the first column is when the customer entered the theater and second column is the name. </p> <pre><code>time name 1 A 2 A 3 A 4 B 5 B 6 C 7 B 8 C </code></pre> <p>I want to get average time for a customer entry (ignore the fact that customer has to leave i...
<p>I think you are trying to take the average difference in times:</p> <pre><code>In [11]: g = df.groupby('name') In [12]: g['time'].apply(lambda x: x.diff().mean()) Out[12]: name A 1.0 B 1.5 C 2.0 Name: time, dtype: float64 </code></pre> <p>Edit: I'm not sure whether you want this or simply the mean:</p> ...
python|pandas
2
9,765
53,769,333
Adding an extra in column into 2D numpy array python
<p>I have a 2D numpy array that has a shape of <code>(867, 43)</code>. My aim is to add an extra column (np.nan value) as the leading column to this array so that the shape becomes <code>(867, 44)</code>.</p> <p>An example would be:</p> <pre><code># sub-section of array &gt;&gt;&gt; arr[:2, :5] array([[-0.30368954, ...
<p>Have a look at <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.stack.html" rel="nofollow noreferrer">stack</a>. Edit: clarification; I am making use of the <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer">broadcasting</a> feature to ...
python|arrays|python-2.7|numpy|numpy-ndarray
1
9,766
53,392,511
How can I find specified string matching filter patterns with Pandas
<p>I hava a pandas dataset called <code>tf</code> which has a column containing blank space seperated keywords titled "Keywords":</p> <pre><code>Name ... Keywords 0 Jonas 0 ... Archie Betty 1 Jonas 1 ... Archie 2 Jonas 2 ... ...
<p>I think this is more what you're looking for, pandas dataframe cells can actually contain lists:</p> <pre><code>import pandas # Create a test dataframe df = pandas.DataFrame( [ {"name": "A", "keywords": "Something SomethingElse"}, {"name": "B", "keywords": "SomethingElse Tada"}, {"name"...
python|pandas
0
9,767
17,533,813
pandas timeseries with relative time
<p>I am new to pandas and I am struggling to figure out how to convert my data to a timeseries object. I have sensor data, in which there is a relative time index with reference to the beginning of the experiment. This is not in date/time format. All documentation that I have found online deals/starts with some sort of...
<p>You should construct pandas TimeSeries objects by parsing the timestamps to dateTime objects. This requires you to pick some arbitrary starting point</p> <pre><code>start = dt.datetime(year=2000,month=1,day=1) time = datalvm['time'][1:] floatseconds = map(float,time) #str-&gt;float #floats to datetime objects -&g...
python|pandas|time-series
4
9,768
17,285,691
Creating image from point list with Numpy, how to speed up?
<p>I've following code which seems to be performance bottleneck:</p> <pre><code>for x, y, intensity in myarr: target_map[x, y] = target_map[x,y] + intensity </code></pre> <p>There are multiple coordinates for same coordinate with variable intensity.</p> <p>Datatypes:</p> <pre><code>&gt; print myarr.shape, myarr.d...
<p>If you convert your 2D coordinates into <code>target_map</code> into flat indices into it using <code>np.ravel_multi_index</code>, you can use <code>np.unique</code> and <code>np.bincount</code> to speed things up quite a bit:</p> <pre><code>def vec_intensity(my_arr, target_map) : flat_coords = np.ravel_multi_i...
optimization|numpy|enumeration
1
9,769
19,849,635
Access Columns of Numpy Array? Errors Trying to Do by Transpose or by Column Access
<p>I've a numpy.ndarray the columns of which I'd like to access. I will be taking all columns after 8 and testing them for variance, removing the column if the variance/average is low. In order to do this, I need access to the columns, preferably with Numpy. By my current methods, I encounter errors or failure to tr...
<p>Notice that the output of <code>print z_matrix</code> has the form</p> <pre><code>[ (18.712, 64.903, ..., -138.173) (17.679, 48.015, ..., -66.5854)] </code></pre> <p>That is, it is printed as a list of tuples. That is the output you get when the array is a "structured array". It is a one-dimensional array of s...
python|arrays|numpy
5
9,770
6,654,329
Speeding up iterating over Numpy Arrays
<p>I am working on performing image processing using Numpy, specifically a running standard deviation stretch. This reads in X number of columns, finds the Std. and performs a percentage linear stretch. It then iterates to the next "group" of columns and performs the same operations. The input image is a 1GB, 32-bit...
<p>One way to speed up operations over <code>numpy</code> data is to use <code>vectorize</code>. Essentially, vectorize takes a function <code>f</code> and creates a new function <code>g</code> that maps <code>f</code> over an array <code>a</code>. <code>g</code> is then called like so: <code>g(a)</code>. </p> <pre><c...
python|for-loop|numpy|gdal
7
9,771
12,436,895
How to create a multiIndex object from series?
<p>I have a data series 'rpt_date' :</p> <pre><code>&gt;&gt;&gt; rpt_date STK_ID 000002 [u'20060331', u'20060630'] 000005 [u'20061231', u'20070331', u'20070630'] &gt;&gt;&gt; type(rpt_date) &lt;class 'pandas.core.series.Series'&gt; &gt;&gt;&gt; </code></pre> <p>And how to create a multiIndex object (pandas.cor...
<p>To associate the first element to the other you can use <code>itertools.repeat</code> and <code>zip</code>, in this way:</p> <pre><code>&gt;&gt;&gt; import itertools as it &gt;&gt;&gt; L = [['000002', [u'20060331', u'20060630']], ... ['000005', [u'20061231', u'20070331', u'20070630']]] &gt;&gt;&gt; couples = [...
python|pandas
1
9,772
12,052,067
If I use python pandas, is there any need for structured arrays?
<p>Now that pandas provides a data frame structure, is there any need for structured/record arrays in numpy? There are some modifications I need to make to an existing code which requires this structured array type framework, but I am considering using pandas in its place from this point forward. Will I at any point fi...
<p>pandas's DataFrame is a high level tool while structured arrays are a very low-level tool, enabling you to interpret a binary blob of data as a table-like structure. One thing that is hard to do in pandas is nested data types with the same semantics as structured arrays, though this can be imitated with hierarchical...
numpy|scipy|pandas
16
9,773
72,011,953
how to make new data to be default type or default value (instead of nan) in pandas.dataframe
<p>i'm dynamicly constructing a df with pandas. where i wish the new data(element) when is added default to be a specific type or value, instead of nan. could this be possible? like:</p> <pre><code>import pandas as pd df = pd.DataFrame() df.at[1,[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]] = &quot;a&quot; df.at[2,[&quo...
<p>How about using <code>df.fillna(&quot;&quot;)</code> after the dataframe creation. In this way you fill the nan value with a specified value.</p> <pre><code>import pandas as pd df = pd.DataFrame() df['a'] = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] df['b'] = [&quot;a&quot;,&quot;c&quot;, np.nan] df = df.fillna(&qu...
python|pandas|dataframe
1
9,774
71,956,313
Checking Previous elements in a list with Python and based on the previous element store a value in a new column with Pandas
<pre><code>list_Crashes = ['Startup', 'Crash in A', 'Shutdown', 'Crash in B', 'Crash in C', 'Startup', 'Crash in D', 'Startup', 'Crash in E', 'Crash in F', 'Crash in G', 'Shutdown', 'Crash in X', 'Crash in Y', 'Crash in Z'] </code></pre> <p>I have a table which contains 2 columns. the code will check th...
<p>IIUC, you can use a generator:</p> <pre><code>def gen(lst): last_non_crash = '' for x in lst: if not x.startswith('Crash in'): last_non_crash = x else: yield [x, last_non_crash] pd.DataFrame(gen(list_Crashes), columns=['Crashes', 'State']) </code></pre> <p>ou...
python|pandas
2
9,775
55,315,706
2019-03 latest install of cudnn following tensorflow apt-get Ubuntu 18.04 instructions no longer working. What to try next?
<p>Getting the followig error with Conv1D in keras:</p> <p>tensorflow.python.framework.errors_impl.UnknownError: Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.</p> <p>Used to work but I purged and updated to l...
<p>I encountered the same problem sometime back. On Jupyter notebook console, I saw the error you mention. In the terminal from where I launched Jupyter, I could see the following message:</p> <p><em>2019-03-24 13:27:14.571966: E tensorflow/stream_executor/cuda/cuda_dnn.cc:328] Loaded runtime CuDNN library: 7.0.5 but ...
tensorflow|ubuntu|nvidia
2
9,776
55,554,228
Making a string out of pandas DataFrame
<p>I have pandas DataFrame which looks like this:</p> <pre><code> Name Number Description car 5 red </code></pre> <p>And I need to make a string out of it which looks like this:</p> <pre><code>"""Name: car Number: 5 Description: red""" </code></pre> <p>I'm a beginner and I really don't get how do ...
<p>You can use <code>iterrows</code> to iterate over you dataframe rows, on each row you can then get the columns and print the result the way you want. For example: </p> <pre class="lang-py prettyprint-override"><code>import pandas as pd dtf = pd.DataFrame({ "Name": ["car", "other"], "Number": [5, 6], "D...
python|python-3.x|pandas|dataframe|sklearn-pandas
2
9,777
55,462,635
Pandas Dataframe group by, column with a list
<p>Im using jupyter notebooks, my current dataframe looks like the following:</p> <pre><code>players_mentioned | tweet_text | polarity ______________________________________________ [Mane, Salah] | xyz | 0.12 [Salah] | asd | 0.06 </code></pre> <p>How can I group all p...
<p>If you are just looking to group by players_mentioned and get the averatge for that players popularity score this should do it.</p> <pre><code>df.groupby('players_mentioned').polarity.agg('mean') </code></pre>
python|pandas|dataframe
0
9,778
56,491,270
finding similar sequences (row-wise) in pandas and NDFrame
<p>I am still learning python but I am becoming more and more fluent with dataframes. I am trying to measure inside a pandas data frame which are the most frequent rows for different lengths. For example for a table of 5 columns: -Find the most appearing 3 elements out of the 5 columns that are the most frequent ones...
<p>Try using this:</p> <blockquote> <p>DataFrame.<strong>mode</strong>(axis=0, numeric_only=False, dropna=True)[source]</p> <p>Get the mode(s) of each element along the selected axis.</p> <p>The mode of a set of values is the value that appears most often. It can be multiple values.</p> <p><strong>a...
python|pandas|row
0
9,779
56,823,355
Append based on another reference
<p>Im allowed to use Numpy for the task.</p> <p>I need to show the total sales in a month with two lists: dates and sales.</p> <p>My approach is to make a list of all sales during a month by stripping the month off the date, creating a 2D matrix and adding the values that check for each month.</p> <pre><code>import ...
<p>A solution <em>keeping your logic</em>:</p> <p>Here I loop over the months (as you did, but here using <code>enumerate</code>), and look for when the month is equal to 1. Using <code>enumerate</code> allows us to know the column number of when the month equals 1 (<code>id</code>). Then it's just a matter of appendi...
python|numpy
0
9,780
56,746,784
Pandas: Interpolating time series on a pivoted dataframe
<p>I have a <code>pandas</code> dataframe with 9 time series variables: <code>AS</code>, <code>CR6</code>,<code>TCPR</code>, .... I need to interpolate values in the dataframe, though the final form of the dataframe needs to stay in the pivoted form for subsequent analysis. The tricky thing is that the dataframe is piv...
<p>First use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>str.split</code></a> by columns for <code>MultiIndex</code>, so possible reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html...
python|pandas
2
9,781
56,557,587
Why my one-filter convolutional neural network is unable to learn a simple gaussian kernel?
<p>I was surprised that the deep learning algorithms I had implemented did not work, and I decided to create a very simple example, to understand the functioning of CNN better. Here is my attempt of constructing a small CNN for a very simple task, which provides unexpected results.</p> <p>I have implemented a simple C...
<p>By examining the photos it seems like the network is learning OK, as the predicted image is not so far off the true label - for better results you can tweak some hyperparams but that is not the case.</p> <p>I think what you are missing is the fact that different kernels can get quite similar results since it is a c...
python|tensorflow
2
9,782
25,788,313
error using boolean indexing with pandas
<p>I have a column <code>"APNT_NA_ACTN"</code> that provides the type of coding used to hire employees: </p> <pre><code>115, 515, 100, 786, 101, etc... </code></pre> <p>I have aliased my set of data as names, therefore <code>names[:3]</code> provides three rows of the entire set. </p> <p>I have the ability to filte...
<p>An alternative is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html#pandas.Series.isin" rel="nofollow"><code>isin</code></a>:</p> <pre><code>names['APNT_NA_ACTN'].isin([115,515])] </code></pre> <p>You can pass a list or a Series to the method</p>
python|pandas|indexing|boolean
2
9,783
66,801,623
How to return multiple values including a list in pandas apply function?
<p>I want to apply a function that returns multiple values to my data frame such that these values are collected in different columns. How do we achieve this?</p> <p>Minimum Reproducible code:</p> <pre><code>import pandas as pd df=pd.DataFrame({'col1':[1,2,3,4,5], 'col2':['a','b','c','d','e']}) </code></pre> <p>Which r...
<p>You can do <code>result_type='expand'</code> in apply with your existing function:</p> <pre><code>df[['c','d','e']]=(df.apply(lambda x: funct(x['col1'],x['col2']), axis=1,result_type='expand') </code></pre> <hr /> <pre><code>print(df) col1 col2 c d e 0 1 a 1a a1 [1a, a1] 1...
python|pandas|list|dataframe|apply
2
9,784
47,525,650
how to stop the while true loop?
<p>I meet a question about the while true loop in python. The code is below</p> <pre><code>def batched(iterator, batch_size): while True: data = np.zeros(batch_size) target = np.zeros(batch_size) for index in range(batch_size): data[index], target[index] = next(iterator) ...
<p>I'm writing this answer because the comments section seemed a little too constricting.</p> <p>First of all, reading up about <code>Iterators</code> in python will clear up your confusion.</p> <p>I'll try to explain anyways! :D</p> <hr> <pre><code>def batched(iterator, batch_size): while True: data =...
python|tensorflow
2
9,785
68,197,664
How to take just the score from HuggingFace Pipeline Sentiment Analysis
<p>I'm quite new to the whole HuggingFace pipeline world, and I have stumbled upon something which I can't figure out. I have googled quite a bit for an answer, but haven't found anything yet, so any help would be great. I am trying to get just the score from the HF pipeline sentiment classifier, not the label, as I wa...
<p>If your classifier output looks like this:</p> <pre><code>[{'label': '1', 'score': 0.9999555349349976}] </code></pre> <p>then you could extract the score with the following:</p> <pre><code>result['sentiment'] = df['text'].apply(lambda x: classifier(x[:512]).apply( lambda x: classifier(x)).str[0].str['score'] </cod...
python|pandas|sentiment-analysis|huggingface-transformers
1
9,786
68,304,818
Compute the unit vector for each row of an array
<p>I have a large (n x dim) array, each row is a vector in a space (whatever the dimension but let's do it in 2D):</p> <pre class="lang-python prettyprint-override"><code>import numpy as np A = np.array([[50,14],[26,11],[81,9],[-11,-19]]) A.shape (4,2) </code></pre> <p>I want to quickly compute the unit vector for e...
<p>You can use a <a href="https://numpy.org/doc/stable/user/basics.broadcasting.html" rel="nofollow noreferrer">broadcasting</a> operation such as:</p> <pre class="lang-python prettyprint-override"><code>A /= np.linalg.norm(A, axis=1)[:,None] # or A /= np.linalg.norm(A, axis=1).reshape(4,1) </code></pre> <p>which both ...
python|arrays|numpy|linear-algebra
1
9,787
68,377,814
Logistic Regression not working because of "unknown label type 'continuous'"?
<p>I'm trying to implement a logistic regression with Sklearn. Currentely I have a Dataframe which consists of 12 input variables and 1 output variable.</p> <p>The output dataframe is binary valued whereas the remaining 12 variables are not necessarily so.</p> <p>Example how the input data is structured.</p> <pre><code...
<p>The problem here is that you are scaling your labels <code>y</code> using a <code>StandardScaler()</code>.</p> <p><code>y</code> is a categorical variable that is used to say that a sample belong to the class <code>1</code> or <code>0</code> and therefore it must not be scaled.</p>
python|pandas|scikit-learn|logistic-regression
1
9,788
68,356,936
Using the google.cloud.sql.connector Python library in Python
<p>I'm trying to upload a CSV file to a database in my SQL instance on Google Cloud SQL, and I'm confused as to how exactly am I supposed to go about this project.</p> <p>my code so far:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from google.cloud.sql.connector import connector read_file =...
<p>Thanks for the question! Currently, most of our documentation is in the <a href="https://github.com/GoogleCloudPlatform/cloud-sql-python-connector#how-to-use-this-connector" rel="nofollow noreferrer">project README</a> and on this <a href="https://cloud.google.com/sql/docs/mysql/connect-connectors#python" rel="nofol...
python|sql|pandas|data-science|google-cloud-sql
1
9,789
68,038,895
Python: Counting values for columns with multiple values per entry in dataframe
<p>I have a dataframe of restaurants and one column has corresponding cuisines.<br /> The problem is that there are restaurants with multiple cuisines in the same column [up to 8].</p> <p>Let's say it's something like this:</p> <pre><code>RestaurantName City Restaurant ID Cuisines Restaurant A Milan 31333 ...
<p>It sounds like you're looking for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html#pandas-series-str-split" rel="nofollow noreferrer"><code>str.split</code></a> without expanding, then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame...
python|pandas
2
9,790
68,239,361
Cant install tensorflow for huggingface transformers library
<p>Im trying to use huggingface transformers library in my python project. I am a first time python programmer, and I am stuck on this error message, even though tensorflow has been installed on my machine:</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; from transformers import pipeline None of P...
<p>From comments</p> <blockquote> <p>You have multiple python interpreters installed, that is why installing stuff does not show in your python interpreter, use <code>pip -V</code> and compare it to the python version that appears in the interpreter. Remove one and use only one then your issue will be resolved (paraphr...
python|tensorflow|pytorch|package|huggingface-transformers
1
9,791
59,142,040
Tensorflow 2.0: How to change the output signature while using tf.saved_model
<p>I would like to change the input and output signatures of the model saved, I used tf.Module objects to build the operations of the main model.</p> <pre><code>class Generator(tf.Module): def __init__(....): super(Generator, self).__init__(name=name) ... with self.name_scope: ...
<p>I figured out a way to define the output signature without using tf.Module by defining a <code>tf.function</code> that returns a dictionary of outputs where the keys used in the dictionary will be the output names.</p> <pre class="lang-py prettyprint-override"><code># Create the model model = ... # Train the model ...
python|tensorflow|tensorflow2.0|generative-adversarial-network
10
9,792
59,181,270
How to skip / ignore the empty fields of rows while appending to the python dataframe line by line?
<p>Here am reading the input file</p> <pre><code>import time import os import pandas as pd from datetime import datetime, timedelta from pandas import ExcelWriter ipfilepath = r"C:\Users\nmanthree\Desktop\m16\m16 nov\Satellite C2 PROD UK.txt" data = pd.DataFrame( columns=['ID', 'Date/Time (UTC)', 'User', 'Descri...
<p>You should read the file using pandas <code>read_csv</code>. This will read all rows, and will insert an <code>np.nan</code> where there are empty fields. No need to loop through the data yourself. </p> <pre><code>ipfilepath = r"C:\Users\nmanthree\Desktop\m16\m16 nov\Satellite C2 PROD UK.txt" ip_df = pd.read_csv(ip...
python|pandas
0
9,793
59,169,367
Filtering excel data to another excel with pandas
<p>I am training a CNN, an excel has many classes to train and I just want to work with only 3.</p> <p>What happens is that when I'm filtering it, in the header it comes out "<strong>,</strong> img_name, name" that comma at the beginning I don't know where it comes from, nor how it was done.</p> <p>Attached code</p> ...
<p>If you save the file using <code>.to_csv</code> the default behavior is to save the index as well, but you have not defined the index name, therefore you have the empty string and a comma.</p> <p>To solve this you can either omit the index:</p> <pre><code>subcar_pd.to_csv(filename, index=False) </code></pre> <p>...
python|python-3.x|pandas
1
9,794
59,276,792
Why to_sql is not working with pyodbc in pandas?
<p>I have an excel file. Im importing that to dataframe and trying to update a database table using the data.</p> <pre><code>import pyodbc def get_sale_file(): try: cnxn = pyodbc.connect('DRIVER=ODBC Driver 17 for SQL Server;' 'SERVER=' + server + ';DATABASE=' + database + ';UI...
<p>You can try another package, too, instead of pyodbc, e.g. pytds or adodbapi. The first one is very simple, with adodbapi the connection config looks like</p> <pre><code>from adodbapi import adodbapi as adba raw_config_adodbapi = f"PROVIDER=SQLOLEDB.1;Data Source={server};Initial Catalog={database};trusted_connecti...
python|python-3.x|pandas|pyodbc
0
9,795
45,221,609
ModuleNotFoundError: No module named 'pandas.rpy'
<p>I'm trying to <code>import pandas as pd</code>. I get <code>ModuleNotFoundError: No module named 'pandas.rpy'</code>. Why? I use pandas 0.20.1 + python 3.6 x64 + Windows 7 .</p> <p>Example:</p> <pre><code>import os os.environ['R_HOME'] = 'C:\Program Files\R\R-3.4.0' os.environ['R_USER'] = 'bob' import rpy2.robjec...
<p><code>pandas.rpy</code> module was deprecated and later removed. It does not exist in the version you are currently using.</p> <p>You can either downgrade your pandas version, or better yet, have a look at the new <code>rpy2</code> project.</p> <p>From pandas documentation:</p> <blockquote> <p>Up to pandas 0.19...
python|pandas|rpy2
8
9,796
45,249,937
Rotating parallel coordinate axis-names in Pandas
<p>When using some of the built in visualization tools in Pandas, one that is very helpful for me is the parallel_coordinates visualization. However, since I have around 18 features in the dataframe, the bottom of the parallel_coords plot gets really messy. </p> <p><strong>Therefore, I was wondering if anyone knew how...
<p>Use <code>plt.xticks(rotation=90)</code> should be enough. Here is an example with <a href="https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/iris.csv" rel="nofollow noreferrer">the “Iris” dataset</a>:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import par...
python|pandas|matplotlib|parallel-coordinates
3
9,797
45,251,721
Python Pandas copy columns from one sheet to another sheet without changing any data?
<p>I have an excel file with two sheets. I would like to copy 3 columns from the first sheet to the second sheet.</p> <p>Note: </p> <ul> <li>the copied 3 column’s label names have some duplicates with the second sheet. But I should <strong>keep the original data of the second sheet without changing them</strong>....
<p>This method uses pandas and <a href="https://xlsxwriter.readthedocs.io/" rel="nofollow noreferrer">xlsxwriter</a>.</p> <p>Setup (create demo excel file):</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'1_A': [1,2,3,4], '1_B': [5,4,6,5], '1_C': [8,7,9,0], '1_D': [9,7,8,5], '1_E': [2,4,9...
python|excel|pandas
2
9,798
56,869,559
Get class wise probability scores for each Semantic class in Image Segmentation using Google's DEEPLAB V3+
<p>I am trying to extract the pixel wise probabilities for each semantic class present in an Image when performing semantic segmentation using Google's DeepLab V3+. I am following the demo given here - <a href="https://github.com/tensorflow/models/tree/master/research/deeplab" rel="nofollow noreferrer">https://github.c...
<p>You can get the probability by using the following: <a href="https://github.com/tensorflow/models/blob/master/research/deeplab/model.py#L203" rel="nofollow noreferrer">Deeplab code</a></p> <pre><code>predictions[output + PROB_SUFFIX] = tf.nn.softmax(logits) </code></pre> <p><strong>EDIT</strong>: The latest deepla...
tensorflow|image-segmentation|deeplab
3
9,799
56,976,142
Error when trying to .insert() into dataframe
<p>I have some code that takes a csv file, that finds the min/max each day, then tells me what time that happens. I also have 2 variables to find the percentage for both max/min.</p> <p>This is currently the output for the dataframe</p> <pre><code>&gt;Out High Low 10:00 6.0 10.0 10:05 10.0 3.0 10:10 ...
<p>You can only add one column at a time with insert. And as you intend to add the new columns at the end of the dataframe you do not even need insert:</p> <pre><code>#adding % to end of dataframe result["High %"] = ph result["Low %"] = pl </code></pre> <hr> <p>If you insist on using insert the correct syntax would ...
python|pandas|dataframe
1