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
16,400
72,108,968
How to convert string to date in pandas df
<p>I have a datafram df_cc_su and I want to compare whether two attributes CalculationDateKey and AgreementStartDate are within the same year-month.</p> <p>CalculationDateKey samples: 20220331, 20220229, 20220132 (string) AgreementStartDate samples: 2022-03-17, 2022-02-27, 2022-01-01 (date format)</p> <p>I tried to con...
<p>Use <code>format=&quot;%Y%m%d&quot;</code>, because not <code>/</code> separator in your data, also <code>20220132</code> not exist, so for wrong values are generated <code>NaT</code> if add <code>errors='coerce'</code>:</p> <pre><code>df_cc_su['CalculationDateKey_date'] = pd.to_datetime(df_cc_su['CalculationDateKey...
python|pandas|numpy
2
16,401
72,051,409
Efficient way of generating new columns having string similarity distances between two string columns
<p>I have a pandas dataframe with shape <code>(1138812, 14)</code> and columns</p> <pre><code>['id', 'name', 'latitude', 'longitude', 'address', 'city', 'state', 'zip', 'country', 'url', 'phone', 'categories', 'point_of_interest', 'id_2', 'name_2', 'latitude_2', 'longitude_2', 'address_2', 'city_2', ...
<p>Starting with a dataframe that looks like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">first_name</th> <th style="text-align: left;">address</th> <th style="text-align: left;">city</th> <th style="text-align: left;">state</th> <th style="text-align: right;">...
python|pandas|levenshtein-distance|difflib
1
16,402
55,515,391
Combine selected column from multiple csv files from different folders to a single csv file
<p>This is for creating the final dataframe for my analysis.So I have three kinds of csv files.I want to extract specific columns from file 1 &amp; file 2 and concatenate it to file 3 to get a single csv file.</p> <p>I have one folder with the three types of files as subfolders-> that is 3 subfolders These 3 subfolder...
<p>I tried to recreate your case with one example</p> <p>I generated 3 random files each one with 3 columns and 100 lines and each one in a different folder </p> <pre><code>import numpy as np import pandas as pd a = np.random.rand(100,3) b = np.random.rand(100,3) c = np.random.rand(100,3) dataframe1 = pd.Data...
python|pandas|dataframe|glob|analysis
2
16,403
55,313,058
Can not connect to tensorboard on my google compute engine
<p>I am trying to connect to tensorboard on my google compute engine instance but it is not working.</p> <p>I have an anacondo distribution and use:</p> <p><code>tensorboard --logdir=/logs</code></p> <p>to create my tensorboard at default port 6006.</p> <p>I also allowed HTTP/HTTPS traffic at my instance and also e...
<p>Normally this type of configuration is related to port communication issues. Go ahead and get all the available ports with nmap, and you should see something as following:</p> <p>$ nmap -Pn [YOUR IP ADDRESS]<br> PORT STATE SERVICE<br> 22/tcp open ssh<br> 80/tcp closed http<br> 443/tcp closed https<br> 3...
tensorflow|google-compute-engine|tensorboard
0
16,404
55,559,356
How do I group date by month using pd.Grouper?
<p>I've searched stackoverflow to find out how to group DateTime by month and for some reason I keep receiving this error, even after I pass the dataframe through <code>pd.to.datetime</code></p> <blockquote> <p>TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64In...
<p>The reason is simple: you didn't pass a groupby key to <code>groupby</code>. </p> <p>What you want is to group the entire dataframe by the month values of the contents of <code>df['Date']</code>.</p> <p>However, what <code>df['Date'].groupby(pd.Grouper(freq='M'))</code> actually does is first extract a <code>pd.Se...
python|python-3.x|datetime|pandas-groupby
12
16,405
55,561,540
keras model.get_weight is not returning results in expected dimensions
<p>I am doing classification over mnist dataset using keras. I am interested in doing some operation on weight matrix generated after the training but some layers weight matrix looks like they are not fully connected.</p> <pre><code>model = Sequential() model.add(Dense(1000, input_shape = (train_x.shape[1],), activati...
<p>Because it is bias. Don't forget that layer is defined by <a href="https://i.stack.imgur.com/WAxAK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WAxAK.png" alt="enter image description here"></a> (sometimes also written as <a href="https://i.stack.imgur.com/oKG07.png" rel="nofollow noreferrer"><...
python|tensorflow|keras|deep-learning|keras-layer
3
16,406
56,518,466
How can I group element and list them all together in Python Pandas?
<p>I have something like this:</p> <pre><code>time 0 1 2 3 4 5 Val1 32 12 56 45 3 67 Val2 60 34 2 5 13 90 </code></pre> <p>I want a list of sub-array composed of 3 values like this:</p> <pre><code>dataset= [ [["32", "12", "56"], ["45", "3", "67"]], [["60", "34", "2"], ["5", "13", "90"]] ] <...
<p>IIUC</p> <pre><code>df=df.set_index('time') df.groupby(np.arange(df.shape[1])//3,axis=1).agg(lambda x : x.values.tolist()).values.tolist() [[[32, 12, 56], [45, 3, 67]], [[60, 34, 2], [5, 13, 90]]] </code></pre>
python|arrays|pandas|numpy
1
16,407
56,529,724
How to decode geohash using python in pandas?
<p>I need code to decode geohash in python. There's a column which contains geohashes. I need them decoded into latitude and longitude.</p>
<p>You can install <a href="https://pypi.org/project/pygeohash/" rel="nofollow noreferrer">pygeohash</a> from pypi using pip</p> <pre class="lang-sh prettyprint-override"><code>$ pip install pygeohash </code></pre> <p>Then add a new column to the dataframe with the latitude and longitude</p> <pre class="lang-py pret...
python|pandas|geolocation|data-science|geocode
3
16,408
56,656,780
Set a the same dictionary for each Pandas cell
<p>I have a simple Python dictionary. I'd like to add a new column to a Pandas Dataframe where each row in that column is equal to the dictionary.</p> <pre><code>import pandas as pd df = pd.DataFrame(data=[[1,2,3],[4,5,6]],columns=['A','B','C']) df['D'] = {'AA': 'BB', 'CC': 'DD'} </code></pre> <p>Desired output</p>...
<p>One option is to construct a list the length of the column, then assign it to the column</p> <pre><code>df['D'] = [{'AA': 'BB', 'CC': 'DD'} for _ in range(df.shape[0])] </code></pre>
python|python-3.x|pandas
4
16,409
47,183,828
pandas how to find continuous values in a series whose differences are within a certain distance
<p>I have a <code>pandas</code> <code>Series</code> that is composed of <code>int</code>s</p> <pre><code>a = np.array([1,2,3,5,7,10,13,16,20]) pd.Series(a) 0 1 1 2 2 3 3 5 4 7 5 10 6 13 7 16 8 20 </code></pre> <p>now I want to cluster the series into groups that in each group, the differences between two ne...
<p>Here's one approach -</p> <pre><code>np.split(a,np.flatnonzero(np.diff(a)&gt;d)+1) </code></pre> <p>As a function to output list of lists -</p> <pre><code>def splitme(a,d) : return list(map(list,np.split(a,np.flatnonzero(np.diff(a)&gt;d)+1))) </code></pre> <p>For performance, I would suggest using <code>zip...
python|python-3.x|pandas|numpy
10
16,410
47,341,275
Drop duplicate rows from a pandas DataFrame whose timestamps are within a specified range or duration
<p>I have a DataFrame like this:</p> <pre><code>Subject Verb Object Date --------------------------------- Bill Ate Food 7/11/2015 Steve Painted House 8/12/2011 Bill Ate Food 7/13/2015 Steve Painted House 8/25/2011 </code></pre> <p>I would like to drop all duplicates, where a duplicate...
<p>Use <code>duplicated</code> + <code>diff</code> in conjunction with <code>groupby</code> to figure out what rows you want to remove.</p> <pre><code>c = ['Subject', 'Verb', 'Object'] def f(x): return x[c].duplicated() &amp; x.Date.diff().dt.days.lt(5) df = df.sort_values(c) df[~df.groupby(c).apply(f).values] ...
python|pandas|dataframe|duplicates
9
16,411
68,243,122
RuntimeError: Given groups=1, weight of size [64, 32, 3, 3], expected input[128, 64, 32, 32] to have 32 channels, but got 64 channels instead
<p>I am trying to experiment with why we have a Vanishing &amp; exploding gradient, and why <strong>Resnet</strong> is so helpful in avoiding the two problems above. So I decided to train a plain Convolution network with many layers just to know why the model <strong>LOSS</strong> increases as I train with many layers ...
<p>I can see by the model, it looks like you made a typo on the 4th conv block in your sequential. You have</p> <pre><code>nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1), nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1), </code></pre> <p>However, you already convert the image to 64 channels and you then pa...
python|neural-network|pytorch
1
16,412
68,398,061
Top 10 per unit in python?
<p>I have delay data for 105 units. I need the data to show the Top 10 largest delays per unit.</p> <p>I need it to show 3 columns <code>Unit, DelayDesc, and Time_hrs</code> and each unit needs to show only the top 10 <code>DelayDesc</code> and the hours for those 10 largest delays</p> <p><strong>At the moment I can on...
<p>Not having your exact data to test with, I can't be positive, but it may be as simple as using the pandas function for <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.nlargest.html" rel="nofollow noreferrer"><code>df.nlargest()</code></a>.</p> <p>If your <code>Sum_Time</code> dataframe has the...
python|pandas|jupyter-notebook
0
16,413
68,290,405
Iterating file paths in python dataframe
<p>I have a data frame that has all the file paths that is called filedataframe. My code works for pulling what I want from a individual xml file. But it is currently set up for a single file. <strong>How do I make this where it will iterate through the data frame filedataframe to use the file path?</strong> I want to ...
<p>Try this.</p> <pre class="lang-py prettyprint-override"><code>import re import pathlib import os import pandas as pd import xml.etree.ElementTree as ET from typing import Dict, List def process_single_xmlfile(xmlfile: str, verbose: bool=False) -&gt; Dict: tree = ET.parse(xmlfile) root = tree.getroot() ...
python|pandas|dataframe|loops|iteration
1
16,414
68,162,699
Keras Model with 2 inputs during training, but only 1 during inferencing
<p>A similar question has been asked earlier by someone but the answer was not satisfactory.</p> <p>Given a model made using Functional API in keras.</p> <p>During training the model we have two inputs and one output. One input is image. Another input is an array of costs that is needed for custom loss function.</p> <p...
<p>Just use a &quot;dummy&quot; input if it doesn't affect the forward pass</p>
python|tensorflow|keras|deep-learning|computer-vision
1
16,415
68,143,271
Generate K random numpy arrays given N variables and ranges
<p>I have N variables (defining N-dimensional space), with their defined ranges (normally or uniformly distributed in the given range):</p> <p>each variable is defined by a list containing its possible integer values.</p> <pre><code>v1_range = [1, 2, 3, 4, 5, 6] v2_range = [10, 20, 30, 40, 50, 60] v3_range = [100, 200,...
<p>Will simple iteration work? I think for 13 lists x 20 values it will work just fine.</p> <pre><code>import random d = { &quot;v1_range&quot; : [1, 2, 3, 4, 5, 6], &quot;v2_range&quot; : [10, 20, 30, 40, 50, 60], &quot;v3_range&quot; : [100, 200, 300, 400, 500], &quot;v4_range&quot; : [15, 16, 17, 18] } def give(k)...
python|arrays|numpy|scipy|distribution
0
16,416
57,005,583
Multiplying two separate dataframes
<p>I have two dataframes and I would like to use them to create a third by applying a simple function. The datasets are quite large so instead of looping through every row and column, is there a more efficient way to do this?</p> <pre><code># dfA id | value | mars | 10 | jupt | 15 | satn | 14 | # dfB id ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> for match, multiple by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mul.html" rel="nofollow noreferrer"><code>D...
python|pandas|dataframe
3
16,417
57,212,517
Breakdown code for concatenating CSV files I found from a previous question?
<p>I had hundreds of CSV files to merge, and doing so manually would have taken weeks. As a result, I decided to learn Python. Unfortunately I didn't have time to learn enough to resolve my problem so I found a code here that would merge the CSV files and add the filename into a new column. My problem is solved, but no...
<p>You start by importing the libraries you need to use</p> <pre><code>import pandas as pd import glob import os </code></pre> <p>This line creates a list of path names to all files that meet the *.csv wildcard within the directory</p> <pre><code>globbed_files = glob.glob("*.csv") </code></pre> <p>You create an ...
python|python-3.x|pandas|csv
0
16,418
45,900,122
TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type int32 of argument 'a'
<p>I'm trying to follow word2vec example, but I'm getting this error:</p> <pre><code>TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type int32 of argument 'a'. </code></pre> <p>At this line</p> <p>similarity = tf.matmul( tf.cast(valid_embeddings,tf.int32), tf.cast(normalized_embedding...
<p>I've met the same problem using Tensorflow r1.4 with Python 3.4. </p> <p>Indeed, I think you need to change the code</p> <pre><code>tf.nn.nce_loss(nce_weights, nce_biases, embed, train_labels, num_sampled, vocabulary_size)) </code></pre> <p>into</p> <pre><code>tf.nn.nce_loss(nce_weights, nce_bia...
python|python-2.7|tensorflow
4
16,419
45,803,984
How can I ignore empty series when using value_counts on a Pandas groupby?
<p>I've got a DataFrame with the metadata for a newspaper article in each row. I'd like to group these into monthly chunks, then count the values of one column (called <code>type</code>):</p> <pre><code>monthly_articles = articles.groupby(pd.Grouper(freq="M")) monthly_articles = monthly_articles["type"].value_counts()...
<p>You'd better give us data sample. Otherwise, it is a little hard to point out the problem. From your code snippet, it seems that the <code>type</code> data for some months is null. You can use <code>apply</code> function on grouped objects and then call <code>unstack</code> function. Here is the sample code that wor...
python|python-3.x|pandas|pandas-groupby
4
16,420
66,400,333
Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() - possible issue with not()
<p>I'm trying to add a new column in to a dataframe with a nested logic but I'm getting the error &quot;Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()&quot;. The solutions I've found online don't apply to my scenario.</p> <pre><code>#original case statement in sql ,case when p...
<p>You problem is that logical operators in python will match against the whole object. What you want is to make a element-wise logical operation. You can use <code>numpy.logical_not()</code> for that or, in the special case of logical operation between array of booleans, you can use bitwise operations, which in the ca...
python|pandas
1
16,421
70,460,347
How to find repeated rows in pandas DataFrame for specific columns, and modify values by adding counter?
<p>Consider a dataframe with 2 columns for easiness. The first column is <code>label</code> which has same values for some of the observations in dataset.</p> <p>Sample dataset:</p> <pre><code>import pandas as pd data = [('A', 28), ('B', 32), ('B', 32), ('C', 25), ('D', 25), (...
<p>You can create an empty <code>dictionary</code>, which you can append with your label and it's count (<code>keys</code> and <code>values</code> respectively). Then depending on whether the label is new, or it exists, you can increment it's value or return it intact.</p> <p>The last step would be to use this new <cod...
python|pandas|dataframe|transform|repeat
1
16,422
51,535,532
Python: how to add missing values to index and columns of a dataframe?
<p>I have a dataframe like the following:</p> <pre><code>df 2 4 5 0 1 3 2 3 -1 4 5 5 3 -6 7 </code></pre> <p>I want to fill the missing values in the index and in the columns and fill the values with zeros, so that:</p> <pre><code>df 0 1 2 3 4 5 0 0 0 1 0 3 2 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> by <code>np.arange</code>:</p> <pre><code>df = (df.reindex(index = np.arange(df.index.max() + 1), columns = np.arange(df.columns.max() + 1), ...
python|pandas
4
16,423
51,251,085
How to write a Function where you can both include an argument as an input or request it
<p><a href="https://i.stack.imgur.com/kA4BK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kA4BK.png" alt="enter image description here"></a>I have a function where an argument is passed in as follows:</p> <pre><code>def Q_Avg1(Ticker): stock = web.DataReader(Ticker, 'iex', start, end) # Dail...
<p>Put Ticker with default argument as object, So if u passed object it will take as parameter and if you dont pass it will simple take default one Example:- </p> <pre><code>def Q_Avg2(Ticker=None): if Ticker is None: Ticker = str(input('Enter Ticker (without quotes)')) stock = web.DataReader(Ticker,...
python-3.x|pandas|function
1
16,424
70,764,975
Using tf.where (or np.where) to draw randomly conditional on an input
<p>I have a TensorFlow vector that only contains 1s and 0s, like <code>a = [0, 0, 0, 1, 0, 1]</code>, and conditional on the value of <code>a</code>, I want to draw new random values 0 or 1. If the value of <code>a</code> is 1, I want to draw a new value but if the value of <code>a</code> is 0 I want to leave it alone....
<p><strong>APPROACH 1:</strong></p> <p>Not tested, but I think the middle param should be a tensor that matches the original one. E.g. 6 elements:</p> <p>First, make a second random sequence, of same length:</p> <pre><code>a2 = tfd.Binomial(total_count = 1.0, probs = 0.5).sample(6) </code></pre> <p>NOTE: If you need a ...
python|numpy|tensorflow|tensorflow-probability
1
16,425
71,039,196
Why can't I vectorize Python's datetime.utcfromtimestamp()?
<p>I have an array of Unix timestamps. I can run <code>datetime.utcfromtimestamp</code> on each entry individually, but I cannot run them all from a <code>numpy</code> array. Why does that happen?</p> <p>MWE</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from datetime import datetime times = ...
<p>You can use <code>np.vectorize()</code> to create a vecorized version of the function which does what you want:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from datetime import datetime times = np.array((1524967210, 1524967211, 1524967212)) func = np.vectorize(datetime.utcfromtimestamp) ...
python|numpy|datetime
1
16,426
51,657,294
Use pretrained pytorch model in C?
<p>So I have a pretrained pytorch model, I have saved both the model and the parameters just in case, but I need to use this model in C or C++ code, anybody know how I can do that?</p> <p>Thanks a lot.</p>
<p>If you are using Ubuntu, try pytorch package in PPA of <a href="https://launchpad.net/~nnstreamer/+archive/ubuntu/ppa" rel="nofollow noreferrer">ppa:nnstreamer/ppa</a>. In this Ubuntu pytorch package, there are header files and pkgconfig (.pc) file that helps building C/C++ programs using pytorch. If you want more s...
c|pytorch|pre-trained-model
0
16,427
37,562,559
Pandas union on two columns of set
<p>I have two columns in a data frame containing sets.</p> <p>How do I get a new column where each row contains the union of the items from the respective columns?</p> <p>For example:</p> <pre><code>col1 : [{1,2} , {4,5}] col2 : [{1,6} , {7,5}] union : [{1,2,6}, {4,5,7}] </code></pre> <p>A naive try:</p> <pre><cod...
<p>I think you are very close - use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> with <code>axis=1</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame([[{1,2} , {1,6}], [{4,5} , {7,5}]], columns=['col1', 'col2']) df['union'...
python|pandas|set
4
16,428
37,253,302
How can I rearrange a DataFrame with Pandas?
<p>I have a DataFrame:</p> <pre><code> Amount dwy bmd Portfolio EUR GBP JPY USD EUR GBP JPY USD EUR GBP JPY USD date 2016-05-13 100 200 300 400 -0.5 0.5 0 0.8 ...
<p><code>pd.DataFrame(df.stack("Currency").to_records())</code> Should do the trick.</p> <p>Here's an explanation of the steps:</p> <p><strong>1. Reproducing your dataframe:</strong></p> <pre><code>arrays = [['Amount', 'Amount', 'Amount', 'Amount', 'dwy', 'dwy', 'dwy', 'dwy', 'bmd', 'bmd', 'bmd', 'bmd'], [...
python|pandas
5
16,429
41,919,229
Counting non-overlapping runs of non-zero values by row in a DataFrame
<p>Let's say I have the following Pandas <code>DataFrame</code>:</p> <pre><code>id | a1 | a2 | a3 | a4 1 | 3 | 0 | 10 | 25 2 | 0 | 0 | 31 | 15 3 | 20 | 11 | 6 | 5 4 | 0 | 3 | 1 | 7 </code></pre> <p>What I want is to calculate the number of non-overlapping runs of <code>n</code> consecutive non-z...
<p>Here's one approach with <a href="https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.signal.convolve2d.html" rel="nofollow noreferrer"><code>2D convolution</code></a> to solve for any number of elements in a row -</p> <pre><code>from scipy.signal import convolve2d as conv2 n = 6 v = np.vstack([(conv...
python|pandas|numpy|dataframe
5
16,430
37,992,326
Change initializer of Variable in Tensorflow
<p>I have a predefined code that creates a Tensorflow graph. The variables are contained in variable scopes and each has a predefined initializer. Is there any way to change the initializer of the variables?</p> <p>example: The first graph defines</p> <pre><code>with tf.variable_scope('conv1') w = tf.get_variab...
<p>The problem is that initialization can't be changed on setting up reuse (the initialization is set during the first block).</p> <p>So, just define it with xavier intialization during the first variable scope call. So the first call would be, then initialization of all variables with be correct:</p> <pre><code>with...
python|tensorflow
4
16,431
64,254,457
Selecting patterns in character sequence using regex
<p>I would need to select all the accounts were 3 (or more) consecutive characters are identical and/or include also digits in the name, for example</p> <pre><code>Account aaa12 43qas 42134dfsdd did </code></pre> <p>Output</p> <pre><code>Account aaa12 43qas 42134dfsdd </code></pre> <p>I am considering of using regex ...
<p>Can you try :</p> <pre><code>x = re.search([a-zA-Z]{3}|\d, string) </code></pre>
python|regex|pandas
0
16,432
64,350,687
How to add dictionary line to an JSON file
<p>I am trying to achieve the below JSON format and store it in a json file:</p> <pre><code>{ &quot;Name&quot;: &quot;Anurag&quot;, &quot;resetRecordedDate&quot;: false, &quot;ED&quot;: { &quot;Link&quot;: &quot;google.com&quot; } } </code></pre> <p>I know how to create a simple JSON file using ...
<p>Assuming the input json content is</p> <pre><code> { &quot;Name&quot;: &quot;Anurag&quot;, &quot;resetRecordedDate&quot;: False } </code></pre> <p>Program</p> <pre><code>import json # read file with open('example.json', 'r') as infile: data=infile.read() # parse file parsed_json = json.loa...
python|json|pandas
0
16,433
64,231,624
Where does a TensorFlow model instance get `input` property from?
<p>I am <strong>not</strong> talking about how to pass an input to a model.</p> <p>If you make a model, e.g. from the docs:</p> <pre class="lang-py prettyprint-override"><code>model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.kera...
<p>The class <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model" rel="nofollow noreferrer"><code>tf.keras.Model</code></a> inherits from <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer" rel="nofollow noreferrer"><code>tf.keras.layers.Layer</code></a>, which inherits from <a hre...
tensorflow|keras
2
16,434
47,769,111
Create pandas dataframe from list of tuple of nested lists
<p>I have this data below, which is a list with 4 elements. These elements are tuple which items are list them self...</p> <pre><code>data = [(['a', 'b', 'c'], [1, 2, 3, 4, 5], ['aa', 'bb'], ['00', '03', '0000', '0006']), (['e', 'f', 'g'], [2, 1, 4, 4, 6], ['qq', 'er'], ['10', '04', '3340', '9009']), (['...
<p>You can flatten nested <code>list</code>s:</p> <pre><code>df = pd.DataFrame([[item for sublist in l for item in sublist] for l in data]) print (df) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 0 a b c 1 2 3 4 5 aa bb 00 03 0000 0006 1 e f g 2 1 4 4 6 qq er 10 04 33...
python|list|pandas|dataframe
1
16,435
47,813,091
converting numpy array into dictionary
<p>I have an array like the following:</p> <pre><code>[( 1, b'"C"'), ( 2, b'"C#"'), ( 3, b'"D"'), ( 4, b'"D#"'), ( 5, b'"E"'), ( 6, b'"F"'), ( 7, b'"F#"'), ( 8, b'"G"'), ( 9, b'"G#"'), (10, b'"A"'), (11, b'"A#"'), (12, b'"B"'))] </code></pre> <p>I want to convert this to a dictionary "d" such that when I say <code>...
<pre><code>list1 = [( 1, b'"C"'), ( 2, b'"C#"'), ( 3, b'"D"'), ( 4, b'"D#"'), ( 5, b'"E"'), ( 6, b'"F"'), ( 7, b'"F#"'), ( 8, b'"G"'), ( 9, b'"G#"'), (10, b'"A"'), (11, b'"A#"'), (12, b'"B"')] dict1 = {a : b for a,b in list1} print(dict1) {1: '"C"', 2: '"C#"', 3: '"D"', 4: '"D#"', 5: '"E"', 6: '"F"', 7:...
python|arrays|numpy|dictionary
4
16,436
47,679,326
How to filter a dataframe by multiple columns and add a value
<pre><code>df = mdb.read_table(mdbfile, "table") invoices = pd.read_csv(file, delimiter=';') lst = df[(df['El4'] == el4)] #contains specific rows of df for i, row in lst.iterrows(): prop = row['propertyid'] mouvement = (row['Mouvements']*-1) a = invoices[(invoices['propertyReference'] == prop) &amp; (inv...
<p>Following up on my comment. It seems like you're just trying to join (or, in pandas terminology, a <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer">merge</a>). </p> <p>Let's start with your source data:</p> <pre><code>df = mdb.read_table(mdbfi...
python|pandas|dataframe|filter
0
16,437
58,674,487
how to query dataframe in for loop with changing values, ValueError: Lengths must match to compare?
<p>This works, but I had to type 4 different times for each value in charge_names list</p> <pre><code>charge_names = ['Vehicle Theft','Robbery','Burglary','Receive Stolen Property'] charges[charges['Charge Group Description']== 'Vehicle Theft'].head(2) </code></pre> <p>I tried to run for loop like this:</p> <pre><c...
<p><code>DataFrame.isin</code> Whether each element in the DataFrame is contained in values.</p> <p><code>DataFrame.groupby</code> Group DataFrame based on entries</p> <pre class="lang-py prettyprint-override"><code>charge_names = ['Vehicle Theft','Robbery','Burglary','Receive Stolen Property'] charges[charges['Charg...
pandas|select
1
16,438
58,616,958
Get the immediate values from the adjacent columns based on the value of another column with Pandas
<p>Let's say that I want to find the person that ate the most tacos from a taco eating competition.</p> <p>DataFrame</p> <pre><code>df = pd.DataFrame({'tacos':[5,10,7]},index=['John','Carlos','Peter']) </code></pre> <p>If I have identified the max tacos a person has eaten, then how I could get the name of that perso...
<p>If I understand correctly, then you should be able to use <code>df.idxmax()</code>:</p> <pre><code>df = pd.DataFrame({'tacos':[5,10,7]},index=['John','Carlos','Peter']) df.idxmax() </code></pre> <p>That will return Carlos in this example.</p> <p>Now, if you want the value of another column, you could do something...
python|pandas
1
16,439
59,019,101
Create bins of specific size between two values in numpy/pandas
<p>I have two values which define the maximum and minimum of a dataset (e.g. in the reproducible example below 2503 and 2991). </p> <p>I would like to create a list of equal bin sizes (50) between zhe range of maximum and minimum value. </p> <p>As a solution I am looking for a way to create a list <code>rangebins</co...
<p>With the help of @ayhan and <a href="https://stackoverflow.com/a/44396692/3896548">this answer</a> I managed to do what I wanted using the pretty() function.</p> <pre><code>import numpy as np minimum = 2503 maximum = 2991 def nicenumber(x, round): exp = np.floor(np.log10(x)) f = x / 10**exp if roun...
python|pandas|numpy
1
16,440
70,186,240
Function parameters iterate over a csv file values
<p>i have this function</p> <pre><code>def audience(lat,lon,ids): buff = buff_here(lat,lon)[-1] count_visitas = [] for visitas in glob.glob(path): ...... df = pd.DataFrame(count_visitas, columns =['Visitas']) df.to_csv(f'output/visitas_simi_{ids}.csv', index = False) return count_visitas </code></pre> <p>I can't post ...
<p>You would need to bring the csv in with <code>csv.DictReader</code> and then you can call the desired columns:</p> <pre><code>csv_file = csv.DictReader(open(file, 'rU')) for row in csv_file: count_visitas = audience(row['lat'],row['lon'],row['ids']) </code></pre>
python|python-3.x|pandas|function|csv
0
16,441
70,133,176
How can I construct double sorted portfolio?
<p><a href="https://i.stack.imgur.com/QB3Jo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QB3Jo.png" alt="enter image description here" /></a></p> <p>My code of decile portfolio by RETl1 and VOL</p> <pre><code>merged['decile_RETl1'] = merged.groupby(['Date'])['RET_l1'].transform(lambda x: pd.qcut(x...
<p>If you're interested in sorting a Pandas DataFrame by multiple columns, as I understand from your question, you can use <a href="https://www.kite.com/python/docs/pandas.DataFrame.sort_values" rel="nofollow noreferrer"><code>sort_values</code></a> method.</p> <p>For example:</p> <pre class="lang-py prettyprint-overri...
python|pandas|dataframe|portfolio
0
16,442
56,305,097
How to fix 'not found ' error in numpy, loadtxt?
<p>I want to load a file located in my desktop into numpy, python. However, the code causes an error.</p> <p>The file consists only of numbers and ',' characters</p> <p>Also, what is the meaning of <code>dtype=np.int64</code>? What is the difference between <code>int64</code>, <code>int32</code>, <code>float</code>.....
<p>You mentioned that your file is called <code>weather.txt</code>, but your code shows <code>.loadtxt("weather.csv",</code>.</p> <p>Have you tried changing the filename extension in your code from <code>.csv</code> to <code>.txt</code>?</p> <pre><code>x = np.loadtxt("weather.txt", delimiter=",", dtype=np.int64) </co...
python|numpy
0
16,443
55,872,127
Count duplicated values, delete duplicates and keep count and other columns
<p>I'm setting up a data-set of about 10 000 rows and 55 columns from a excel file format. I pick out the relevant column to be displayed (Number and Date).</p> <p>Now, the column "Number" has many duplicated values that i want to count and then remove the duplicates. In the same time i want to show the latest date th...
<p>Use:</p> <pre><code>df['Count']=df.groupby('Column_1').transform('count') df=df.drop_duplicates('Column_1') print(df) </code></pre> <hr> <pre><code> Column_1 Column_2 Count 0 445 2019-04-26 3 1 446 2019-03-26 1 2 447 2019-03-15 1 3 449 2019-02-26 2 5 451 2018...
python|pandas|pivot-table|large-data
3
16,444
55,800,584
Is there any quadratic programming function that can have both lower and upper bounds - Python
<p>Normally I have been using <a href="https://octave.sourceforge.io/optim/function/quadprog.html" rel="noreferrer">GNU Octave</a> to solve quadratic programming problems.</p> <p>I solve problems like</p> <pre><code>x = 1/2x'Qx + c'x </code></pre> <p>With subject to</p> <pre><code>A*x &lt;= b lb &lt;= x &lt;= ub </...
<p>You can write your own solver based <code>scipy.optimize</code>, here is a small example on how to code your custom python <code>quadprog()</code>:</p> <pre class="lang-py prettyprint-override"><code># python3 import numpy as np from scipy import optimize class quadprog(object): def __init__(self, H, f, A, b...
python|numpy|scipy|quadratic-programming|scipy-optimize
5
16,445
65,044,195
Pandas Ascending Label
<p>Sorry if this question has already been answered, I am having trouble discerning the error in the following code snippet</p> <pre class="lang-py prettyprint-override"><code>for layer in set(df['i']): print(layer, end='\r') df.loc[df['i'] == layer, ['c']] += max_ max_ = df.loc[df['i'] == layer, ['c']].max...
<p>Following on the comment of @S3DEV, you can either omit <code>set</code> entirely:</p> <pre><code>for layer in df['i']: </code></pre> <p>or, if the intention was to go through unique values in <code>df['i']</code>, you can do</p> <pre><code>for layer in df['i'].unique(): </code></pre> <p>if this does not solve you p...
python|pandas
0
16,446
39,710,894
How can I plot rows less than 0 as a different color?
<p>I have a dataframe with one column of data. I'd like to visualize the data such that all the bars above the horizontal axis are <code>blue</code>, and those below it are <code>red</code>.</p> <p>How can I accomplish this?</p>
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.where.html" rel="nofollow noreferrer"><code>where</code></a> for selecting values above and below <code>0</code> to new columns <code>b</code> and <code>c</code>:</p> <pre><code>import pandas as pd import numpy as np import mat...
pandas|matplotlib|plot|dataframe|colors
1
16,447
39,692,711
Tensorflow: Filter must not be larger than the input
<p>I want to perform convolution along the training sample that is of shape [n*1] and apply zero-padding too. So far, no results.</p> <p>I am building a character-level CNN (idea taken from <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/text_classification_character_cnn.py" r...
<blockquote> <p>Why is zero-padding not applied?</p> </blockquote> <p>Use <code>padding = 'SAME'</code> in conv2d for zero-padding.</p> <blockquote> <p>Could someone please explain what is happening?</p> </blockquote> <p>You can't use the 3x3 filter in the case of 'flat' image. To use the 3x3 filter, input shoul...
python|machine-learning|tensorflow|deep-learning|convolution
2
16,448
44,121,962
set_shape raising problems in read_and_decode with TFRecordReader in tensorflow
<p>I am trying to train an imagenet classifier with my own architecture (the pretrained weights are needed for my project). I have preprocessed the images of ILSVRC2012 and everything as explained in the <em>inception tutorial</em> in tensorflow but I can not pass this read_and_decode function. The problem lies in imag...
<p>One possible issue:</p> <p>Did you feed shape in image.set_shape() ? It should be like </p> <pre><code>image.set_shape([image_height,image_width,nchannels]) or image.set_shape([None,None,nchannels]) </code></pre> <p>Could you post the error log ?</p>
tensorflow
0
16,449
44,017,326
How could I use TensorFlow in jupyter notebook? I install TensorFlow via python 3.5 pip already
<p>I installed tensorflow via python3.5 pip, it is in the python3.5 lib folder and I can use it perfectly on shell IDLE.</p> <p>I have anaconda(jupyter notebook) on my computer at the same time, however, I couldn't import tensorflow on notebook.</p> <p>I guess notebook was using the anaconda lib folder, not python3.5...
<p>There is a package called <strong>nb_conda</strong> that helps manage your anaconda kernels. However, when you launch Jupyter make sure that you have jupyter installed inside your conda environment and that you are launching Jupyter from that activated environment.</p> <p>So:</p> <ul> <li>Activate your conda envir...
python-3.x|tensorflow|pip|installation|jupyter-notebook
0
16,450
69,423,258
Training a new dataset on bert
<p>I am new to BERT</p> <p>I have a amazon review dataset, where I want to predict the star rating based on the review</p> <p>I know I can use a pretrained bert model as shown <a href="https://github.com/nicknochnack/BERTSentiment/blob/main/Sentiment.ipynb" rel="nofollow noreferrer">here</a></p> <p>But I want to train ...
<p>First of all what is pretraining? The procedure helps the model to learn syntactic &lt;==&gt; semantic (this is a spectrum) features of the language using an enormous amount of raw text (40GB) and processing power. objective function: casual language model and mask language model</p> <p>What about fine-tuning a pre-...
python|tensorflow|nlp|tokenize|bert-language-model
0
16,451
69,319,521
Fill in dataframe values based on group criteria without for loop?
<p>I need to add some values to a dataframe based on the ID and DATE_TWO columns. In the case when DATE_TWO &gt;= DATE_ONE then fill in any subsequent DATE_TWO values for that ID with the first DATE_TWO value. Here is the original dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>...
<p>I slightly changed your data so we can see how it works.</p> <h1>Data</h1> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np data = {'ID': [1,1,1,1,2,2,3,3,3,3], 'EVENT': [12, 20, 32, 43,1,2,1,12,13,15], 'DATE_ONE': ['3/1/2021','3/5/2021','3/6/2021','3/7/2021','3/3/2021...
python|pandas
1
16,452
69,462,535
Pandas: Merge two string columns in Python, remove duplicated strings and remove unwanted string unless only unwanted string left
<p>I'm trying to merge two string columns and I wish to get rid of <code>'others'</code> if the counter value is a 'non-others' value - like <code>'apple' + 'others' = 'apple'</code> but <code>'others' + 'others' = 'others'</code>. I managed the 2nd condition but how can I accommodate the two conditions on the merge?</...
<p>You want to replace only one <code>&quot;others&quot;</code>, so simple join and then use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>str.replace</code></a> once:</p> <pre><code>df[&quot;together&quot;] = (df[&quot;fruit1&quot;] + &quot; &quot...
python|pandas
5
16,453
66,096,726
In Keras, what is the best between using validation_split (in "fit" method) and model.evaluate function?
<p>In Keras there are two ways (at least) to split the data and display loss/accuracy:</p> <ol> <li><p>In Keras <em>fit</em> function there is the <strong>validation_split</strong> option that allows to split the dataset into training and testing sets AND to display loss/accuracy values during the training.</p> </li> <...
<p>The best way to see your validation results would be to split your training and validation data into equal amounts of each class. This can be done using <code>StratifiedKFold</code> from <code>sklearn.model_selection</code>.</p> <p>When I looked through the <a href="https://www.tensorflow.org/api_docs/python/tf/kera...
python|tensorflow|keras
0
16,454
65,929,274
How do I add a " unit symbol after each number in a column in a pandas data frame?
<p>I am taking over a project that is built in a pandas data frame where there is a large amount of measurements in this format: 6x6 , 52x14</p> <p>I need to go in and add a quote (&quot;) inches unit symbol after each number in two specific columns that have this type of measurement data, the desired outcomes in the a...
<p>Here's <strong>how to do the string replacement for units with a regex</strong> (but depending on your use-case, it might make more sense to split them into separate (numeric) columns width, length; see below):</p> <pre><code>import pandas as pd df = pd.DataFrame({'measurements': ['6x6', '52x14']}) df['measurement...
python|pandas|string-formatting|number-formatting|units-of-measurement
1
16,455
65,981,630
Iterate Through Nested Dictionary to Create Dataframe and Add New Column Value
<p>Python noob so bear with me.</p> <p>I have a list of a dictionary of stock info. Variable name &quot;json&quot;, I want to convert it to a dataframe then append a column with the ticker symbol in a new column next to the data. See below.</p> <pre><code> json = [{'Meta Data': {'1. Information': 'Monthly Prices...
<blockquote> <p>Update:</p> </blockquote> <p>Single loop one line execution</p> <pre><code>df = [ (pd.DataFrame.from_dict(i['Monthly Time Series'] , orient= 'index').sort_index(axis=1).assign(ticker=i['Meta Data']['2.Symbol'])) for i in json] </code></pre> <p>json data:</p> <pre><code>json =[{ 'Meta Data': { ...
python|pandas|list|loops|dictionary
1
16,456
66,141,049
How to update pandas DataFrame based on the previous row information
<p>I have the following DataFrame in Pandas and I want to check if HH value is greater than the previous row's High value and if it is greater, then update previous rows HH value and replace the current HH with Nonvalue.</p> <p><a href="https://i.stack.imgur.com/s94Ms.jpg" rel="nofollow noreferrer">How to check if the ...
<p>To help you understand how the shift(-1) works, please review the below solution. I looked at the image and created the raw DataFrame.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Dates':['2021-02-04 19:00:00','2021-02-04 20:00:00', '2021-02-04 21:00:00','2021...
python|pandas|dataframe
3
16,457
52,531,196
I am trying to create a new dataframe using another dataframe consisting of values
<pre><code>temp['DateTime']= Total_12hravg_all[index_end, 'DateTime'] </code></pre> <p><code>temp</code> is a new dataframe </p> <p><code>Total_12hravg_all</code> is dataframe from which i want a particluar value of the row of column using index_end as a variable. <code>Datetime</code> is a column in <code>Total_12hr...
<p>Example : The columns of interest are company_id (string) and company_score (float). </p> <p>So, You can use <code>groupby</code> <strong>company_id</strong> column and convert its result into a dictionary of DataFrames:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({ ... "comp...
python|pandas
1
16,458
46,400,926
Create single row for each entry in df rows
<p>Hello I read in an excel file as a DataFrame whose rows contains multiple values. The shape of the df is like:</p> <pre><code> Welding 0 65051020 ... 1 66053510 66053550 ... 2 66553540 6655...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> and last <a href="http://...
python|pandas|dataframe
1
16,459
46,325,761
Creating new pandas dataframe in each loop iteration
<p>I have several pandas dataframes (A,B,C,D) and I want to merge each one of them individually with another dataframe (E).</p> <p>I wanted to write a for loop that allows me to run the merge code for all of them and save each resulting dataframe with a different name, so for example something like:</p> <pre><code>ta...
<p>you want to clutter the namespace with automatically generated variable names? if so, don't do that. just use a dictionary.</p> <p>if you really don't want to use a dictionary (really think about <em>why</em> you don't want to do this), you can just do it the slow-to-write, obvious way:</p> <pre><code>ea = E.merge...
python|pandas
1
16,460
58,349,407
How can I pivot and restructure my convoluted dataframe such that all key-value pairs in all the rows are ready to be put into a db?
<p>Currently I have a csv file that looks like this:</p> <pre><code>id key1 value1 key2 value2 key3 value3 key4 value4 0 Colour Blue Shape Square Price 3 1 Age 4 Colour Red Price 5 Condition New </code></pre> <p>I'm attempting to read this in as a DataFrame in pandas...
<p>You can use this</p> <pre><code>df1 = df.filter(like='key').stack().reset_index().rename(columns={'level_0':'id','level_1':'keys',0:'key_val'}) df2 = df.filter(like='value').stack().reset_index().rename(columns={'level_0':'id','level_1':'valnum',0:'val'}) (df1.merge(df2,on ='id',how='outer', left_index=True, righ...
python|pandas|csv|dataframe|pivot-table
1
16,461
44,747,092
syntax error running Tensorflow on Ubuntu
<p>I have installed Tensorflow on Ubuntu. Wen want to test Tensorflow I get this syntax error:</p> <pre><code>VirtualBox:~$ # Python VirtualBox:~$ import tensorflow as tf VirtualBox:~$ hello = tf.constant('Hello, TensorFlow!') bash: syntax error near unexpected token `(' </code></pre> <p>I use ubuntu on virtual mach...
<p>You didn't start python and bash doesn't understand your import statement. Type python hit enter (not Python). Then there should be a prompt like >>> . Now run the statements import and so on.</p>
linux|ubuntu|machine-learning|tensorflow|deep-learning
0
16,462
71,689,204
How can I vectorize this PyTorch snippet?
<p>My pytorch code is running too slow due to it not being vectorized and I am unsure how to go about vectorizing it as I am relatively new to PyTorch. Can someone help me do this or point me in the right direction?</p> <pre><code>level_stride = 8 loc = torch.zeros(H * W, 2) for i in range(H): for j in range(W): ...
<p>First of all, you defined the tensor to be of size <code>(H*W, 2)</code>. This is of course entirely optional, but it might be more expressive to preserve the dimensionality explicitly, by having <code>H</code> and <code>W</code> be separate dimension in the tensor. That makes some operations later on easier as wel...
python|pytorch|vectorization
0
16,463
71,469,546
panda-melt is not transposing columns into a sequance
<p>I read a csv it has multiples columns. I want to transpose</p> <pre><code>Date A B C 25/5/2019 25 765.3 896 26/5/2019 98 769 27/5/2019 27.6 453.2 98.6 </code></pre> <p>I have tried</p> <pre><code>df2 = pd.melt(df, id_va...
<p>Alternative solution with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> and removeinf second level from columns names by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dro...
python|pandas|pandas-melt
5
16,464
71,685,851
Pandas: Conditionally dropping columns based on same values throughout the column in MultiIndex dataframe
<p>I have a dataframe as below:</p> <pre><code>data = {('5105', 'Open'): [1.99,1.98,1.99,2.05,2.15], ('5105', 'Adj Close'): [1.92,1.92,1.96,2.07,2.08], ('5229', 'Open'): [0.01]*5, ('5229', 'Adj Close'): [0.02]*5, ('7076', 'Open'): [1.02,1.01,1.01,1.06,1.06], ('7076', 'Adj Close')...
<p>Try with <code>nunique</code></p> <pre><code>df = df.loc[:,~(df.nunique()==1).values] Out[125]: 5105 7076 Open Adj Close Open Adj Close 0 1.99 1.92 1.02 0.90 1 1.98 1.92 1.01 0.92 2 1.99 1.96 1.01 0.94 3 2.05 2.07 1.06 0.94 4 2.15 2.0...
python|python-3.x|pandas|dataframe|multi-index
2
16,465
42,225,711
Create new pandas column based on start of text string from other column
<p>I have a pandas dataframe with a text column. </p> <p>I'd like to create a new column in which values are conditional on the start of the text string from the text column.</p> <p>So if the 30 first characters of the text column: </p> <p><code>== 'xxx...xxx'</code> then return value <code>1</code> </p> <p><code>=...
<p>There is possible use multiple <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> but if more conditions use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer">...
python|string|pandas|conditional-statements|startswith
7
16,466
42,546,173
Finding max date of the month in a list of pandas timeseries dates
<p>I have a timeseries without every date (ie. trading dates). Series can be reproduced here.</p> <pre><code> dates=pd.Series(np.random.randint(100,size=30),index=pd.to_datetime(['2010-01-04', '2010-01-05', '2010-01-06', '2010-01-07', '2010-01-08', '2010-01-11', '2010-01-12', '2010-01-13', '2010-...
<p>You can try the following to get your desired output:</p> <pre><code>import numpy as np import pandas as pd dates=pd.Series(np.random.randint(100,size=30),index=pd.to_datetime(['2010-01-04', '2010-01-05', '2010-01-06', '2010-01-07', '2010-01-08', '2010-01-11', '2010-01-12', '2010-01-13', '20...
pandas|python-datetime
2
16,467
42,498,850
TypeError: unsupported operand type(s) for /: 'list' and 'int' after 28 iterations
<p>My code runs on a random image for 28 iterations and THEN gets the <strong>error:</strong></p> <p><code>TypeError: unsupported operand type(s) for /: 'list' and 'int'</code> </p> <p>I'm not really sure why it is getting that error after 28 iterations when it should have broken after 1 iteration only.</p> <p><stro...
<p>Initialize <code>s1</code> and <code>m</code> as arrays, not lists.</p> <pre><code>s1 = np.array([0.0, 0.0, 0.0]) m = np.array([0.0, 0.0, 0.0]) </code></pre>
python|opencv|numpy
0
16,468
69,982,275
Plot bar chart in multiple subplot rows with Pandas
<p>I have a simple long-form dataset I would like to generate bar charts from. The dataframe looks like this:</p> <pre><code>data = {'Year':[2019,2019,2019,2020,2020,2020,2021,2021,2021], 'Month_diff':[0,1,2,0,1,2,0,1,2], 'data': [12,10,13,16,12,18,19,45,34]} df = pd.DataFrame(data) </code></pre> <p>I w...
<h3>1. <a href="https://seaborn.pydata.org/generated/seaborn.catplot.html" rel="nofollow noreferrer"><code>seaborn.catplot</code></a></h3> <p>The simplest option for a long-form dataframe is the <a href="https://seaborn.pydata.org/generated/seaborn.catplot.html" rel="nofollow noreferrer"><code>seaborn.catplot</code></a...
python|pandas|matplotlib|data-visualization
3
16,469
69,744,351
Creating a multiindexed dataframe from other dataframe values with different indicies
<p>I have a dataframe (dfA) composed from several files. dfA has three things, a date value which matches other date values in dfA, a name from a list of an unknown number of names that will be the same as other names in the dfA, and a concentration value which is unique. I want to create a new dataframe (dfB), where ...
<p>You may find it easier down the line to reformat your dates to be datetime variables, rather than strings. With that said, set up test:</p> <pre><code>dfA = pd.DataFrame({ &quot;date&quot;:[&quot;090721&quot;,&quot;083021&quot;,&quot;090721&quot;,&quot;083021&quot;,&quot;083121&quot;,&quot;083021&quot;,&quot;083...
python|pandas|dataframe|multi-index
1
16,470
69,846,772
Reading in Date / Time Values Correctly
<p>Any ideas on how I can manipulate my current date-time data to make it suitable for use when converting the datatype to time? For example:</p> <pre><code>df1['Date/Time'] = pd.to_datetime(df1['Date/Time']) </code></pre> <p>The current format for the data is mm/dd 00:00:00</p> <p>an example of the column in the dataf...
<p>For the condition where the hour is denoted as 24, you have two choices. First you can simply reset the hour to 00 and second you can reset the hour to 00 and also add 1 to the date.<br /> In either case the first step is detecting the condition which can be done with a simple find statement <code>t.find(' 24:')</...
python|pandas|date|datetime
1
16,471
69,838,518
loop over rows in pandas
<p>Im using python, and i have some difficulties to loop over rows in python. my dataframe contains 3 columns : id, val1, size. i want to create column col1 based on size. Il trying this code and my code is never inside the first condition . How should i correct it please. Let's say that i don't won't something working...
<p>Do you want <code>print</code>? You can do that without loop like below:</p> <pre><code>df['col1'] = np.where(df['size'] == 2, df['val1'], np.nan) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df id val1 size col1 0 x1 100 1 NaN 1 x2 200 2 200.0 2 x3 300 1 NaN </code></pr...
python|pandas
4
16,472
43,161,964
Concat & Indexing Several Different Time Series In Pandas
<p>I've got several different futures price time series combined into one data frame using concat. For example, soybeans and corn futures contracts for a number of different years.</p> <p>I would like to compare the prices of the varying contracts graphically on the same time basis, in this case Nov 1 through July 1, ...
<p>The way I did this was to get a <code>mmdd</code> column and use that as the index -- for the x-axis and x-axis labels.</p> <p>I did it for two of the three <code>DataFrames</code>.</p> <pre><code>dfr14['mmdd'] = (dfr14['Date'].dt.month.astype(str).str.zfill(2) + dfr14['Date'].dt.day.astype(str)....
python|pandas|matplotlib
0
16,473
43,133,056
saving numpy array to a file without brackets and white spaces
<p>I have been trying to save numpy array to a file without brackets and white spaces at the beginning of each line. Unfortunately the last one does not work. Array:</p> <pre><code>[[ 6. -2.86751284 -0.35808319 1.79360812] [ 6. -1.59351284 -0.02808319 -0.47039188] [ 6. 0.51848716 0.217916...
<p>For more controls about how your text should be use <code>np.savetxt</code> with additional parameters as required:</p> <pre><code>arr = np.ones((3, 3)) with open("test.txt" , 'wb') as f: np.savetxt(f, arr, delimiter=' ', newline='\n', header='', footer='', comments='# ') </code></pre>
python|arrays|numpy|serialization|numpy-ndarray
1
16,474
72,384,596
NetworkXError: Adjacency matrix not square: nx,ny=(737, 39)
<p>How can I solve this error?</p> <pre><code>import networkx as nx df=pd.read_excel('peso-ao-nascer.xlsx') </code></pre> <p><code>G=nx.from_numpy_matrix(array)</code></p> <p>So I have this: NetworkXError: Adjacency matrix not square: nx,ny=(737, 39)</p>
<p>Adjacency matrices must be square because the &quot;index&quot; of the rows and columns are from the same set, the set of the nodes in the graph.</p> <p><a href="https://en.wikipedia.org/wiki/Adjacency_matrix#:%7E:text=Adjacency%20matrix,-From%20Wikipedia%2C%20the" rel="nofollow noreferrer">From Wikipedia:</a></p> <...
python|numpy|networkx
0
16,475
72,396,854
How do I add a header into a DataFrame without removing the first row?
<p>So, iam trying to add headers to a dataframe without removing the first row.</p> <p>This is the dataframe</p> <pre><code>01/02/2022 Lorem 369,02 0 01/02/2022 Lorem 374,12 1 01/02/2022 Lorem 1149,49 </code></pre> <p>When i try to use df.columns, it removes the first row and return this</p> <pre><code> ...
<p>As @Ynjxsjmh commented best would be to set <code>header=None</code> when you read in the table with <code>pd.read_csv</code>.</p> <p>If you have already read in the table here is a hacky way to do what you need which transposes the table twice to make use of <code>reset_index</code>.</p> <pre><code>import pandas as...
python|pandas|dataframe
0
16,476
72,427,123
How to use pandas' df.get function for a dataframe column so that each row in the column maintains its own value?
<p>To summarize as concisely as I can, I have data file containing a list of chemical compounds along with their ID numbers (&quot;CID&quot; numbers). My goal is to use pubchempy's pubchempy.get_properties function along with pandas' df.map function to essentially obtain the properties of each compound (there is one co...
<p>If you cast the column to float, that should help you: <code>df['MolecularWeight'] = df['MolecularWeight'].astype(float)</code>.</p>
python|pandas|dataframe|pubchem
0
16,477
72,214,808
LSTM model Evaluation
<p>I have the following LSTM model, its input is embedded by the word2vec model:</p> <p><a href="https://i.stack.imgur.com/P8y4M.jpg" rel="nofollow noreferrer">LSTM Model</a></p> <p>I need your opinion about the model evaluation as shown in the below pictures <a href="https://i.stack.imgur.com/P7Wlv.jpg" rel="nofollow ...
<p>Training your LSTM model. Training is a processing of update your model's parameter by epoch, the accuracy will promote and loss will decline by epoch.</p>
python|tensorflow|keras|lstm
0
16,478
50,395,752
Tensorflow shuffle iterator
<p>I would like to retrieve 2 items that belongs to different classes with a Tensorflow iterator (to do BC learning)...</p> <p>The solution I've been digging into is with tf.while_loop, yet I don't find it proper. Does anyone find any other way than my proposed solution ?</p> <p>Here is an example on a naive dataset ...
<p>I'm not quite clear on what you're trying to do, but if you have two <code>tf.data.Dataset</code> objects and you want to sample from them randomly, you could do something like the following (note that this will require upgrading to the <code>tf-nightly</code> package or waiting for TensorFlow 1.9 to be released):</...
tensorflow|tensorflow-datasets
0
16,479
50,542,815
How to create multiple column list of booleans from given list of integers in phython?
<p>I am new to Python. I want to do following.</p> <p>Input: A list of integers of size <em>n</em>. Each integer is in a range of 0 to 3.</p> <p>Output: A multi-column (4 column in this case as integer range in 0-3 = 4) numpy list of size <em>n</em>. Each row of the new list will have the column corresponding to the ...
<blockquote> <p>Is this the best way to do this in Python? </p> </blockquote> <p>No, a more Pythonic and probably the best way is to use a simple broadcasting comparison as following:</p> <pre><code>In [196]: a = np.array([0, 3, 2, 1, 1, 2]) In [197]: r = list(range(0, 4)) In [198]: a[:,None] == r Out[198]: arra...
python|numpy
3
16,480
50,575,596
pandas .loc returns empty dataframe
<p>I have pandas dataframe, which looks like below. </p> <pre><code>chainage(km) 0 0.001 0.002 0.003 0.004 </code></pre> <p>while I use <code>.loc</code> to search for the <code>chainage(km)</code> it returns the empty dataframe for some chainages.</p> <pre><code>print data.loc[data['chainage(km)'] == flo...
<p>The problem arises due to floating point inaccuracies. This is explained in <a href="https://stackoverflow.com/questions/588004/is-floating-point-math-broken">Is floating point math broken?</a>.</p> <p>In situations like this, please use <code>np.isclose</code> instead.</p> <pre><code>df[np.isclose(data['chainage(...
python|pandas
3
16,481
50,621,786
LBFGS never converges in large dimensions in pytorch
<p>I am playing with Rule 110 of Wolfram cellular automata. Given line of zeroes and ones, you can calculate next line with these rules:</p> <p><a href="https://i.stack.imgur.com/TOjI7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TOjI7.png" alt="enter image description here"></a></p> <p>Starting...
<p>What's you're trying to do here is non convex optimisation and this is a notoriously difficult problem. Once you think about it, it make sense because just about any practical mathematical problem can be formulated as an optimisation problem.</p> <p><strong>1. Prelude</strong><br> So, before giving you hints as to ...
python|tensorflow|pytorch|nonlinear-optimization
1
16,482
45,454,307
Why am I losing data after I perform a GroupBy?
<p>So this dataset has 2 million records of patients. I've been asked to make every variable dichotomic, and that part is done, but any patient can have multiple records so I have to group them by the patient. When I perform this I lose data; any idea why? This doesn't happen in every field:</p> <p><a href="https://i....
<p>I think there is problem after aggregate <code>max</code> you get all <code>NaN</code>s, so <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts</code></a> return empty <code>Series</code>:</p> <pre><code>df = pd.DataFrame({'A':...
python|python-3.x|pandas|data-analysis
4
16,483
45,698,621
TensorFlow embedding_rnn_decoder 'Tensor' object is not iterable
<p>I am trying to construct a custom estimator for my ML Engine package and I seem to be having trouble properly constructing my decoder input sequence in the correct format. Consider the following where label1, label2 is supposed to be a sequence of labels.</p> <pre><code>label1, label2 = tf.decode_csv(rows, record_...
<p>The <code>label_idx</code> values is not a list hence you are facing this problem:</p> <p>Below example should clarify better:</p> <pre><code>label_idx = 1 features = dict(zip(['decoder_input'], [label_idx])) features['decoder_input'] # 1 output </code></pre> <p>where as if I change label_idx to a list:</p> <...
python|tensorflow|google-cloud-ml-engine
1
16,484
62,654,922
How can I merge time series data from 2 different csv
<p>I have 2 csv files, the first one contains timestamp of event. I want to add weather details from the 2nd csv file.</p> <p>File 1 (irregular time stamps)</p> <pre><code>Time UserID_Detected 2019-01-01 01:00:32 3 2019-01-02 06:02:12 2 ...
<p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>pd.merge_asof</code></a> with <code>direction=nearest</code> to merge the two dataframes on the column <code>Time</code>:</p> <pre><code>df_event['Time'] = pd.to_datetime(df_event['Time'])...
python|pandas|dataframe|time-series|data-processing
1
16,485
62,823,454
How to convert Index column with name 'Date' to weekday name in dataframe. The index format is dtype: int64
<p>How to convert Index column with name Data to weekday name in dataframe</p> <p><a href="https://i.stack.imgur.com/ChChc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ChChc.png" alt="" /></a></p>
<p>try:</p> <pre><code>daynumber = [0,1,2,3,4,5,6] weekday = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] df = df.rename(index=dict(zip(daynumber,weekday))) df </code></pre> <p>output:</p> <pre><code>Date ... Monday ... Tuesday ... Wednesday ... Thursday ... Friday ... </...
python|pandas|google-colaboratory
0
16,486
62,822,426
Pandas GroupBy without filling in missing data
<p>I have a file of half-hourly data which I wish to group together by hour. This works:</p> <pre><code>data.groupby(pd.Grouper(freq='1h')).agg('sum') </code></pre> <p>However, it fills in hours where there is no half-hourly data.</p> <p>How can I perform a grouping like this but not create records where there was no d...
<p>If you just want to filter out the added times, you can do what cs95 said in the comments or:</p> <pre><code>out = data.groupby(pd.Grouper(freq='1h')).sum(min_count=1).dropna() </code></pre> <p>The <code>min_count</code> makes NaN be the output if there is no data for the bin, which can then be removed with <code>dr...
pandas|pandas-groupby
1
16,487
54,519,111
K Nearest Neighbors First App. Error on drop function from pandas
<p>I was trying to make my first KNN App using sklearn, numpy and pandas. This is my code </p> <p>I looked on pandas website but the documentation isn't fantastic.</p> <pre><code>import numpy as np from sklearn import preprocessing, model_selection, neighbors import pandas as pd df = pd.read_csv('D:\\Projects\\m...
<p>I fixed the error by removing all the spaces in txt file. try id,clump_thick,unif_cell_size,unif_cell_shape,marg_adhesion,sing_epith_cell_size,bare_nuclei,bland_chromatin,normal_nucl,mitoses,class(without spaces)</p> <p>hope it helps!</p>
python|pandas|machine-learning|knn
1
16,488
73,626,495
pandas str.contains is not showing any functions
<p>Gents/Ladies,</p> <p>When trying the following example from google:</p> <pre><code>import pandas import numpy as np import re s1 = pandas.Series(['Mouse', 'dog', 'house and parrot', '23', np.NaN]) s1.str.&lt;No functions available&gt; </code></pre> <p>The 2nd line has only those function options:</p> <pre><code>pri...
<p>The functions are there. It is probably issue with the IDE that you are working. You can try this and see if it runs.</p> <pre><code>&gt;&gt;&gt; s1.str.count(&quot;o&quot;) 0 1.0 1 1.0 2 2.0 3 0.0 4 NaN dtype: float64 </code></pre>
pandas|string|pycharm
0
16,489
73,577,067
NameError: name 'timeseries' is not defined
<p>I'm developing telegram alarm bot and having a problem to print dataframe. So I converted it into json but the error occurred.</p> <p>My code:</p> <pre><code>!pip install -U finance-datareader import FinanceDataReader as fdr import matplotlib.pyplot as plt %matplotlib inline import numpy as np import pandas as pd im...
<p>I didn't get what exactly you want to print from that dataframe or why you want to json-serialize the values before printing.</p> <p>Please note the variable <code>row</code> in the <code>iterrows</code> is the panda's <code>Series</code> type which is not json-serializable. A json string can be obtained using the <...
python|json|pandas|dataframe
0
16,490
73,544,982
How to change Json data output in table format
<pre><code>import requests from pprint import pprint import pandas as pd baseurl = &quot;https://www.nseindia.com/&quot; url = f'https://www.nseindia.com/api/live-analysis-oi-spurts-underlyings' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, ' '...
<p>Try this :</p> <pre><code>import json import codecs df = pd.DataFrame(json.loads(codecs.decode(bytes(res.text, 'utf-8'), 'utf-8-sig'))['data']) </code></pre> <p>And to select a specific columns, you can use :</p> <pre><code>mini_df = df[['symbol', 'latestOI', 'prevOI', 'changeInOI', 'avgInOI']] </code></pre> <h4><c...
python|pandas
0
16,491
71,212,128
Bokeh models to plot interactive addition of columns using CustomJS and CheckboxGroup
<p>I want a CheckboxGroup to represent different columns of a dataframe. The idea is for the user to be able to add multiple column values if they select multiple columns and interactively display the sum as a plot.</p> <p>I have the following plot from a previous help I got:</p> <pre><code>from bokeh.io import output_...
<p>Here is a solution for your problem using lines to plot the data.</p> <p>The idea in the JS part is, to initialize for every click your values for <code>combined</code> with 0 and then loop over all selected <code>labels</code> given through the values in <code>active</code> and add them to <code>combined</code>.</p...
javascript|python|callback|bokehjs|pandas-bokeh
0
16,492
71,340,785
how to make Tensorflow 2.8.0 Logging work?
<p>I want to print debugging or logging messages in the Python (high level operations) and C++ (inner operations and kernel implementation) of tensorflow 2.8.0, however neither seems to work.</p> <p>I tried two builds of tensorflow: the latest version (2.8.0) and the master branch version (2.9)</p> <p>For Python API lo...
<p>After some digging, I worked it out:</p> <p><code>TF_CPP_MIN_VLOG_LEVEL</code> has been renamed to <code>TF_CPP_MAX_VLOG_LEVEL</code>. It works only when setting the variable before importing tensorflow.</p> <p><code>TF_CPP_MAX_VLOG_LEVEL</code> produces a lot of output regarding the internal C++ operations.</p> <p>...
python|c++|tensorflow|logging
1
16,493
71,224,389
Detecting rows from 2 columns of dates and return as dictionary
<p>I have an event calendar dataframe as follows.</p> <pre><code>calendar = pd.DataFrame({&quot;name&quot;: [&quot;event1&quot;, &quot;event2&quot;, &quot;event3&quot;], &quot;loc&quot;: [&quot;USA&quot;, &quot;JPN&quot;, &quot;USA&quot;], &quot;start_date&quot;: [&quo...
<p>IIUC, your output is incorrect.</p> <p>Here is an approach by computing all date of an event and using <code>explode</code> to enable the match:</p> <pre><code>(daily .merge(calendar .assign(date=calendar.apply(lambda r: pd.date_range(r['start_date'], r['end_date']), axis=1)) .explode('date').drop(columns=['start...
python|pandas
1
16,494
71,182,186
pandas.to_datetime: TypeError: invalid type promotion
<p>I get</p> <p><strong>TypeError: invalid type promotion</strong></p> <p>at</p> <pre><code>df.iloc[1:,0] = pd.to_datetime(np.where(m, df.iloc[1:,0], np.NaN), errors='ignore') </code></pre> <p>in the below code.</p> <p>It is because at df.iloc[1, 0], the empty value has m = True. How do I solve this issue?</p> <pre><co...
<p>The column was read in as datetime. Hence <code>np.NaN</code> led to the error in</p> <pre><code>np.where(m, df.iloc[1:,0], np.NaN) </code></pre> <p>Changing to <code>np.datetime64('NaT')</code>, solved the issue</p>
python|pandas|datetime
1
16,495
60,704,813
Interpolate/Resize ascii art in python?
<p>I want to resize some ascii art. Say it looks like this:</p> <pre><code>..K .T. .A. </code></pre> <p>I want to upscale it, by some number n, so it will look like this (n=2)</p> <pre><code>....KK ....KK ..TT.. ..TT.. ..AA.. ..AA.. </code></pre> <p>One way I thought about doing this was to convert the text into a ...
<p>Assuming you have a file <code>test.txt</code> with following content:</p> <pre><code>..K .T. .A. </code></pre> <p>The following code will read the file and prodcue an output file <code>test_out.txt</code> which contains horizontally and vertically multiplied characters, depending what you specify for <code>N</cod...
python|numpy|matrix|text|scipy
2
16,496
60,370,821
Find latitude and longitude using City and State columns
<p>I have a column with 'CITY' and 'STATE' strings. I tried using geocoder from geopy library to calculate Latitude and Longitude but it timeouts as it exceeds the number of requests also there are about 85895 rows in the data set. So I did value count for the 'CITY_STATE' column and there are 1340 values. Is there a w...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>GroupBy.apply</code></a> with custom function and joined both columns to Series <code>s</code>:</p> <pre><code>s = train['CITY'].astype(str) + ', ' + train['...
python|pandas|numpy|machine-learning|data-processing
1
16,497
60,411,404
Executing Python module without installing it
<p>How can we run python scripts implementing pandas module in the environment where pandas is not installed?</p> <p>For example, on a server we don't have permission to install python modules. We have a script which is using the pandas module, so how can we run those scripts?</p>
<p>In short: no, you can't. You have to install the package.</p> <p>There are at least two options. First, you can <a href="https://stackoverflow.com/questions/7143077/installing-pip-packages-to-home-folder">install the packages that are not in the system to your home dir</a> (but this is messy and dependent on the ch...
python|pandas|installation
0
16,498
59,894,984
Torch installation results in not supported wheel on this platform
<p>Tried running <code>pip3 install torch===1.4.0 torchvision===0.5.0 -f https://download.pytorch.org/whl/torch_stable.html</code> first, taken from <a href="https://pytorch.org/get-started/locally/" rel="nofollow noreferrer">PyTorch website</a><br> which resulted in <code>No matching distribution found for torch===1.4...
<blockquote> <p>using 64 Python 3.8</p> </blockquote> <p>but you downloaded the <code>cp37</code> whl which is for python <strong>3.7</strong>. There is currently no whl file available for python 3.8. So either install from source (probably not recommended), install a different python version or create a virtual env...
python|pip|pytorch
5
16,499
59,759,107
How to avoid poor performance of pandas mean() with datetime columns
<p>I have a pandas (version <code>0.25.3</code>) <code>DataFrame</code> containing a <code>datetime64</code> column. I'd like to calculate the mean of each column.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd n = 1000000 df = pd.DataFrame({ "x": np.random.normal(0.0, ...
<p>You could restrict it to the numeric values: <code>df.mean(numeric_only=True)</code></p> <p>Then it runs very fast as well.</p> <p>Here is the text from the documentation:</p> <blockquote> <p>numeric_only : bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, t...
python|pandas|performance
3