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
363,600
64,838,556
Time-series data in PyTorch Geometric
<p>I have time-series graph data. I try to predict graph representation for the next time period. Is there any Graph Convolution to handle time-series data or should I use PyTorch Geometric Temporal instead?</p>
<p>There is a very flexible class called &quot;MessagePassing&quot; provided in torch_geometric, where you can build custom GNNs. Have a look at this: <a href="https://pytorch-geometric.readthedocs.io/en/latest/notes/create_gnn.html" rel="nofollow noreferrer">https://pytorch-geometric.readthedocs.io/en/latest/notes/cre...
pytorch|pytorch-geometric
0
363,601
64,922,128
is there any function to filter dataset based on rows?
<p>i'm trying to get list of some platform from dozen of platform in dataset <a href="https://i.stack.imgur.com/20LgV.png" rel="nofollow noreferrer">video-games-sales</a></p> <pre><code> Rank Name Platform Year Genre Publisher NA_Sales 1 Wii Sports Wii 2006 Sports Nintendo 41.25 2 ...
<p>This will return you a dataframe just containing the rows that has the platform &quot;Wii&quot; on it.</p> <pre class="lang-py prettyprint-override"><code>df = df[df.Platform.eq(&quot;Wii&quot;)] </code></pre> <p>You can find more stuff on pandas documentation. <a href="https://pandas.pydata.org/docs/index.html" rel...
python|pandas|dataframe
0
363,602
64,978,653
How do you use pandas and python to assess within how many geographic boxes the user is located?
<p>I am trying to figure out how apps such as Uber and UbersEats operate and manage the logistics. And I am wondering how can we build a function to calculate within how many boxes the user is located. This is the data for users:</p> <pre><code>user_id,loc_lat,loc_lon 1,55.737564,37.345186 2,56.234564,37.234590 3,55.23...
<p>From the test cases of users: none of them are within the bounds of the boxes. Following the logic from <a href="https://stackoverflow.com/questions/217578/how-can-i-determine-whether-a-2d-point-is-within-a-polygon">How can I determine whether a 2D Point is within a Polygon?</a></p> <pre><code>// p is your point, p....
python|python-3.x|pandas|geolocation|geo
1
363,603
64,623,007
Converting from Hex to color name Python
<p>I am working on a project and I am trying to find the different colours used in an image, I have a list of Hex colours and trying to convert them to colour names. I know that not all the hexdecimals have color names related to them but I have found a huge dictionary with the names and I am trying to link them togeth...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html?highlight=apply#pandas.Series.apply" rel="nofollow noreferrer">.apply()</a> method for Series and <a href="https://www.w3schools.com/python/ref_dictionary_get.asp" rel="nofollow noreferrer">.get()</a> method for ...
python|pandas
1
363,604
64,631,086
How can I add new layers on pre-trained model with PyTorch? (Keras example given.)
<p>I am working with <code>Keras</code> and trying to analyze the effects on accuracy that models which are built with some layers with meaningful weights, and some layers with random initializations.</p> <h2>Keras:</h2> <p>I load <code>VGG19</code> pre-trained model with <code>include_top = False</code> parameter on l...
<p>If all you want to do is to replace the classifier section, you can simply do so. That is :</p> <pre class="lang-py prettyprint-override"><code>model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg19', pretrained=True) model.classifier = nn.Linear(model.classifier[0].in_features, 4096) print(model) </code></pre> <p>w...
python|keras|pytorch|vgg-net|pre-trained-model
4
363,605
64,959,332
How to write a proper dataset_fn in tff.simulation.FilePerUserClientData?
<p>I'm currently implementing federated learning using <code>tff</code>.</p> <p>Because the dataset is very large, we split it into many npy files, and I'm currently putting the dataset together using <a href="https://www.tensorflow.org/federated/api_docs/python/tff/simulation/FilePerUserClientData" rel="nofollow noref...
<p>The problem is the <code>dataset_fn</code> must be serializable as a <a href="https://www.tensorflow.org/api_docs/python/tf/Graph" rel="nofollow noreferrer"><code>tf.Graph</code></a>. This is required because TFF uses TensorFlow graphs to execute logic on remote machines.</p> <p>In this case, <code>np.load</code> is...
python|tensorflow|tensorflow-federated
1
363,606
64,720,032
How to filter one row, calculate range and find similar rows from it falling within that range in a dictionary?
<p>How to filter one row, calculate range and find similar rows from it falling within that range in a dictionary with id as key and id's falling in that range as values using multiprocessing?</p> <p>Suppose I have a data frame:</p> <pre><code>id val1 val2 1 10 20 2 9.5 19 3 100 200 4 9.3 19...
<p>To accomplish this, we'll apply a function over the dataframe that computes the IDs where values lie in a range of the dataframe's rows.</p> <pre><code>df = pd.DataFrame.from_records([ {'id': 1, 'val1': 10.0, 'val2': 20.0}, {'id': 2, 'val1': 9.5, 'val2': 19.0}, {'id': 3, 'val1': 100.0, 'va...
python|python-3.x|pandas|dataframe|parallel-processing
0
363,607
64,866,227
python plot multiple bar ranges with dates
<p>I have this two dataframe:</p> <pre><code>x1=[{&quot;dates&quot;:'2018-01-31',&quot;rev&quot;:-2}, {&quot;dates&quot;:'2018-02-28',&quot;rev&quot;:-5}, {&quot;dates&quot;:'2018-03-31',&quot;rev&quot;:-7}, {&quot;dates&quot;:'2018-04-30',&quot;rev&quot;:-8}, {&quot;dates&quot;:'2018-05-31',&quot;rev&quot;:-9}, {&quot...
<p>Let's try <code>merge</code> and plot:</p> <pre><code>ax = df1.merge(df2, on='dates', how='outer').plot.bar(x='dates') # other format with `ax` ax.xaxis_date() </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/768JU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/768JU.png" alt="e...
pandas|datetime|matplotlib|bar-chart
1
363,608
64,903,655
Pandas Python remove elements from list with condition
<p>Suppose I have a the following list</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>List = ['0000', '0010', '0020', '0030', '0040', '0050', '0060', '0070']</code></pre> </di...
<p>You are removing items from list while iterating, maybe that's the root of the problem, Try out a list comprehension</p> <pre><code>List = ['0000', '0010', '0020', '0030', '0040', '0050', '0060', '0070'] List = [x for x in List if not x[-2] in [str(z) for z in range(1,10,2)]] print(List) </code></pre>
python|pandas|list
3
363,609
64,814,576
merging table in Pandas
<p>I am trying to merge two different tables.</p> <p><a href="https://i.stack.imgur.com/qNTcB.png" rel="nofollow noreferrer"> Table 1 containing NGS FILE chromosome starting &amp; END position and Sequence</a></p> <p><a href="https://i.stack.imgur.com/pP2SV.png" rel="nofollow noreferrer">Table 2 Containing another tabl...
<p>What you are trying to do is merging two dataframes based on a condition (merge rows of <code>df2</code> if the position in that dataframe is within the range <code>Pos</code> - <code>Pos_End</code> in <code>df1</code>.).</p> <p>We can use numpy broadcasting to make this work.</p> <pre><code># import numpy if you ha...
python|pandas
0
363,610
64,779,137
How do I get all the data in a row of a CSV from defining the text in the first cell of the row?
<p>I tried to do this by using 'Apple' in the iloc but it gave me a traceback. I know that when using iloc, anything in [] has to be an integer so how would I find a cell-like 'Apple'</p> <pre><code>file1 = pd.read_csv('SHARADAR_SF1_aafe962511a67db10c0a72fe536305b0.csv', usecols=['ticker','datekey','assets','eps','pe',...
<p><code>pandas.read_csv</code> documentation is confusing and behavior in unexpected, IMHO. By default, pandas will infer a header, index and data types from the first few lines of the CSV file. If the header has one fewer cells than the first data line, it will assume that the first column is an index (also referred ...
python|pandas
1
363,611
64,884,613
How do I verify an SSL certificate file (.crt) with Python?
<p>Basically I used to have a process that would load .csv files from a network shared drive in Windows to a cloud location (Google Cloud Storage). There were some changes in the network that I.T. implemented which disrupted this job, throwing an error that looks like this:</p> <p><code>HTTPSConnectionPool(host='storag...
<p>You can take a look at it Sir. <a href="https://rambling-ideas.salessandri.name/validating-a-ssl-certificate-in-python/" rel="nofollow noreferrer">https://rambling-ideas.salessandri.name/validating-a-ssl-certificate-in-python/</a></p>
python|pandas|ssl|google-cloud-platform
0
363,612
64,685,914
get rows based on a condition and separate them into subsets
<p>am trying to subset a dataset based on a condition and pick the rows until it sees the value based on a condition</p> <p>Condition, if Column A == 0, column B should start with 'a'.</p> <p>Dataset:</p> <pre><code>A B 0 aa 1 ss 2 dd 3 ff 0 ee 1 ff 2 bb 3 gg 0 ar 1 hh 2 ww 0 jj 1 ll </code>...
<p>May be try with <code>cumsum</code> as well ~</p> <pre><code>{x : y.to_dict('list')for x , y in df.groupby(df['A'].eq(0).cumsum())} Out[87]: {1: {'A': [0, 1, 2, 3], 'B': ['aa', 'ss', 'dd', 'ff']}, 2: {'A': [0, 1, 2, 3], 'B': ['ee', 'ff', 'bb', 'gg']}, 3: {'A': [0, 1, 2], 'B': ['rr', 'hh', 'ww']}, 4: {'A': [0, 1]...
python|python-3.x|pandas|dataframe|pandas-groupby
2
363,613
64,850,356
Error with strided slice in tensorflow lite
<p>I'm facing a problem with tensorflow-lite. I get this error:</p> <blockquote> <p>Type INT32 (2) not supported. Node STRIDED_SLICE (number 2) failed to invoke with status 1</p> </blockquote> <p>What I did was:</p> <p>I trained a model with MNIST data.</p> <pre><code> model = tf.keras.Sequential([ tf.keras.layers.I...
<p>I worked around this issue simply adding INT32 support to striced_slice.cc.</p> <pre><code>case kTfLiteFloat32: reference_ops::StridedSlice(op_params, tflite::micro::GetTensorShape(input), tflite::micro::GetTensorData&lt;float&gt;(input), ...
c++|tensorflow-lite|quantization
0
363,614
40,184,419
Compiling tensorflow pip package for GPU in Windows
<p>I am brand new to tensorflow and was really excited to see the GPU support for windows. I've set up all dependencies and gotten to where I can kick off a build, but now after compiling for 2 hours it fails with:</p> <pre><code>"C:\Users\Cameron\Desktop\tensorflow\tensorflow\tensorflow\contrib\cmake\build\tf_python_...
<p>This ended up being an issue with using the 3.7 version of CMake, the package only supported 3.6 for this build. Still can't build the whole thing but it's different problems now. Can see the whole discussion on the github pull request here: <a href="https://github.com/tensorflow/tensorflow/pull/5071" rel="nofollow"...
python|msbuild|cmake|tensorflow
2
363,615
39,984,509
TypeError: 'PathCollection' object is not iterable when adding second legend to plot
<p>I am making a scatter plot from three separate dataframes and plotting the points as well as the best fit lines. I can accomplish this using this code:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt fig=plt.figure() ax1=fig.add_subplot(111) ax2=fig.add_subplot(111) ax3=fig.a...
<p>I had the same error. I found out that you shouldn't include the comma after your variable names. So try</p> <pre><code>scat1 =ax1.scatter(ex_x, ex_y, s=10, c='r', label='Fire Exclusion') scat2 =ax2.scatter(one_x,one_y, c='b', marker='s',label='One Fire') scat3 =ax3.scatter(two_x, two_y, s=10, c='g', marker='^', la...
python-2.7|pandas|matplotlib
18
363,616
40,278,845
suppress Name dtype from python pandas describe
<p>Lets say I have </p> <pre><code>r = pd.DataFrame({'A':1 , 'B':pd.Series(1,index=list(range(4)),dtype='float32')}) </code></pre> <p>And <code>r['B'].describe()[['mean','std','min','max']]</code> gives an output : </p> <pre><code>mean 1.0 std 0.0 min 1.0 max 1.0 Name: B, dtype: float64 ...
<p>If need output as <code>DataFrame</code> add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>reset_index</code></a>:</p> <pre><code>x=r['B'].describe()[['mean','std','min','max']].reset_index() print (x) index B 0 mean 1.0 1 std 0.0 ...
python|pandas|dataframe|format|series
9
363,617
40,267,131
how to multiply 2 numpy array with different dimensions
<p>I try to multiply 2 matrix x,y with shape (41) and (41,6) as it is supposed to broadcast the single matrix to every arrow in the multi-dimensions </p> <p>I want to do it as :</p> <pre><code>x*y </code></pre> <p>but i get this error</p> <pre><code>ValueError: operands could not be broadcast together with shapes (...
<p>Broadcasting involves 2 steps </p> <ul> <li><p>give all arrays the same number of dimensions</p></li> <li><p>expand the <code>1</code> dimensions to match the other arrays</p></li> </ul> <p>With your inputs</p> <pre><code>(41,6) (41,) </code></pre> <p>one is 2d, the other 1d; broadcasting can change the 1d to ...
python|arrays|numpy|matrix
4
363,618
40,310,602
How to run TensorFlow in Google App Engine Flexible Enviroment?
<p>Before I asked why GAE can't find TensorFlow lib here <a href="https://stackoverflow.com/questions/40241846/why-googleappengine-gives-me-importerror-no-module-named-tensorflow">https://stackoverflow.com/questions/40241846/why-googleappengine-gives-me-importerror-no-module-named-tensorflow</a></p> <p>And <code>Dmytr...
<p>To help anyone else, I am posting my hello world tensor flow code for google app engine flexible environment using <strong>Python 3</strong> (I know that original question was asked for python 2.7). Also note that webapp2 is not yet compatible with python 3, so I am using Flask.</p> <p>Complete code is</p> <p><str...
python|google-app-engine|tensorflow
4
363,619
40,257,980
How to add all variables under a scope into a certain collection
<p>In tensorflow python APIs, <strong>tf.get_variable</strong> has a parameter <strong>collections</strong> to add the created var to the specified collections. But <strong>tf.variable_scope</strong> does not. What's the suggested way to add all variables under a variable scope into a certain collection?</p>
<p>I don't believe there is a way to do this directly. You could file a feature request on Tensorflow's github issues tracker.</p> <p>I can suggest two workarounds you might try though:</p> <ul> <li><p>iterate over the result of <code>tf.all_variables()</code>, and extract variables whose names look like <code>".../s...
tensorflow
1
363,620
40,326,098
count common entries between two string variables via Python
<p>I would greatly appreciate someones help with counting the number of matching state names from two columns in my csv file. For instance consider the first 7 observations from columns <code>State_born_in</code> and <code>state_lives_in</code>:</p> <pre><code>State_born_in State_lives_in New York Florida Massach...
<p>You can use first <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> and then simple divide <code>length</code> of filtered <code>DataFrame</code> with <code>length</code> of original (it is same as length of <code>index</code>, what ...
python|pandas|bigdata
1
363,621
40,297,693
How to get the same initial results if seed is provided , without restarting the Ipython kernel in Tensorflow
<p>I am not sure , whether this question follow any logic as per the design of Tensorflow . Here is the Code</p> <pre><code>import numpy as np import tensorflow as tf np.random.seed(0) tf.set_random_seed(0) class Sample(): def __init__(self, hidden_dim = 50 , input_dim = 784): self.hidden_dim = hidden_dim ...
<p>Don't use an <code>InterativeSession</code> but use a normal <code>Session</code>. </p> <p>Create a new Session each time with the same seed and you will get the same results.</p> <pre><code>graph = tf.Graph() with graph.as_default(): model = Sample() with Session(graph=graph) as sess: np.random.seed(0) ...
ipython|tensorflow|deep-learning
1
363,622
39,980,868
Tensorflow running two RNNs: Variable hidden/RNN/LSTMCell/W_0 already exists
<p>I am trying to run two RNNs at the same time and concatenate their outputs together, by defining two variable scopes for each <code>rnn_cell.LSTMCell</code>. Why am I receiving this Variable Already Exists error??</p> <blockquote> <p>ValueError: Variable hidden/RNN/LSTMCell/W_0 already exists, disallowed. Did y...
<p>Just use <code>tf.variable_scope</code> instead of <code>tf.name_scope</code>. <code>tf.name_scope</code> doesn't add prefixes to the variables created <code>with tf.get_variable()</code>.</p>
neural-network|tensorflow|recurrent-neural-network
4
363,623
40,224,267
"No suitable image found" using Python/TensorFlow
<p>I'm trying to run a program from GitHub (<a href="https://github.com/sherjilozair/char-rnn-tensorflow" rel="nofollow">https://github.com/sherjilozair/char-rnn-tensorflow</a>) that requires TensorFlow to run, but every time I use TensorFlow (not just this program), I get the following error:</p> <pre><code>Traceback...
<p>Try re-installing Tensorflow from the <a href="https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation" rel="nofollow noreferrer">instructions</a> as suggested <a href="https://stackoverflow.com/questions/40034570/requiring-tensorflow-with-python-2-7-11-occurs-importerror">here</a>.</p>
python|tensorflow
1
363,624
39,928,035
What is the loss function that use the DNNRegressor?
<p>I am using <strong>DNNRegressor</strong> to train my model. I search in the documentation what is the loss function used by this wrapper but i don't find it. On the other hand, it is possible to change that loss function?.</p> <p>Thank you for your suggestions.</p>
<p>It uses L2 loss (mean squared error) as defined in <a href="https://github.com/tensorflow/tensorflow/blob/754048a0453a04a761e112ae5d99c149eb9910dd/tensorflow/contrib/layers/python/layers/target_column.py" rel="nofollow">target_column.py</a>: </p> <pre><code>def regression_target(label_name=None, ...
python|machine-learning|neural-network|tensorflow|deep-learning
5
363,625
40,214,415
Pandas: replace some values in column if that contain a substring
<p>I have dataframe</p> <pre><code>member_id,device_type,device_id,event_type,event_path,event_duration 603609,url,mail.ru/,0,pc,7d4a095373874b4fb26a2e6d070b6ad3 603609,url,mail.ru/,0,pc,7d4a095373874b4fb26a2e6d070b6ad3 603609,url,mail.ru/,0,pc,7d4a095373874b4fb26a2e6d070b6ad3 603609,url,mail.ru/,3,pc,7d4a095373874b4f...
<p>After long time testing with real data there is problem <code>Series</code> from list comprehension return 2 category, not one in row <code>13</code>.</p> <p>One posible solution is use <code>iloc[0]</code> for return only first item from <code>Series</code>:</p> <pre><code>df['category'] = df.device_id ...
python|pandas
1
363,626
40,223,470
how do I get at the pandas.offsets object given an offset string
<p>Suppose I have an offset string <code>'BM'</code> or <code>'7W'</code><br> I know the answer for <code>'BM'</code> is <code>pd.offsets.BMonthEnd()</code><br> for <code>'7W'</code> is <code>pd.offsets.Week(7)</code></p> <p>Is there a generic solution in which I can pass a string and get the offset object?</p>
<p>It looks like <a href="https://github.com/pandas-dev/pandas/blob/master/pandas/tseries/frequencies.py#L390" rel="noreferrer"><code>pandas.tseries.frequencies.to_offset</code></a> is what's used internally to convert from offset strings to a <code>DateOffset</code> object:</p> <pre><code>from pandas.tseries.frequenc...
python|pandas
11
363,627
40,082,844
slicing series of panels
<p>I have a simple dataframe:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame(np.random.randint(0,5,(20, 2)), columns=['col1','col2']) &gt;&gt;&gt; df['ind1'] = list('AAAAAABBBBCCCCCCCCCC') &gt;&gt;&gt; df.set_index(['ind1'], inplace=True) &gt;&gt;&gt; df col1 col2 ind1 A 0 4 A 1 ...
<p>Your problem is that <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.window.Rolling.corr.html" rel="nofollow"><code>.corr()</code></a> is being called without specifying the <code>other</code> argument. Even though your dataframe only has two columns, Pandas doesn't know which correlation...
python|pandas|slice
2
363,628
40,095,632
Replacing values in a column for a subset of rows
<p>I have a <code>dataframe</code> having multiple columns. I would like to replace the value in a column called <code>Discriminant</code>. Now this value needs to only be replaced for a few rows, whenever a condition is met in another column called <code>ids</code>. I tried various methods; The most common method seem...
<p>you are slicing too much. try something like this:</p> <pre><code>indexer = df[df.ids == encodedid].index df.loc[indexer, 'Discriminant'] = 'Y' </code></pre> <p><code>.loc[]</code> needs an index list and a column list. you can set the value of that slice easily using <code>=</code> 'what you need'</p> <p>looking...
python|pandas|dataframe
3
363,629
40,023,661
How to make Pandas aware of holiday dates?
<p>I've been looking at the documentation <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html" rel="nofollow">here</a></p> <p>I have a dataframe which contains a daily time series (Note that 2013-03-29 is a holiday and <code>mydf</code> contains 2013-03-28).</p> <pre><code>import pandas as pd busine...
<p>Try something like this:</p> <pre><code>import numpy as np import pandas as pd from pandas.tseries.offsets import CustomBusinessMonthEnd index = pd.date_range('2010-01-31', '2014-04-30', freq='BM') df = pd.DataFrame(data=np.random.rand(len(index), 2), columns=['a', 'b'], index=index) holidays = ['2013-03-29'] df...
python|pandas
0
363,630
40,311,987
Pandas: Mean of columns with the same names
<p>I have a dataframe with columns like:</p> <pre><code>['id','name','foo1', 'foo1', 'foo1', 'foo2','foo2', 'foo3'] </code></pre> <p>I would like to get a new dataframe where columns sharing the same name are averaged:</p> <pre><code>['id','name','foo1', 'foo2','foo3'] </code></pre> <p>Here column foo1 would be the...
<p>The basic idea is that you can group by your columns names and do mean operations for each group.</p> <p>I saw some comments for your question and tried to give you different ways to achieve the goal. (<strong>Solution (3) is the best I found!</strong>)</p> <p>(1) Quick solution. If you have very limited columns t...
python|pandas
14
363,631
40,055,835
Removing elements from an array that are in another array
<p>Say I have these 2D arrays <code>A</code> and <code>B</code>.</p> <p>How can I remove elements from <code>A</code> that are in <code>B</code>. (Complement in set theory: A-B)</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]...
<p>there is an easy solution with a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehension</a>,</p> <pre><code>A = [i for i in A if i not in B] </code></pre> <p>Result</p> <pre><code>[[1, 1, 2], [1, 1, 3]] </code></pre> <p>List comprehension is not remov...
python|arrays|numpy
30
363,632
40,005,264
Optimization of for loop in python
<p>I am executing the following code for different time stamps and each will have close to one million records. It took more than one hour for one date and I have the data for a total of 35 dates.</p> <p>Is there a way to optimize this code?</p> <pre><code>def median(a, b, c,d,e): I=[a,b,c,d,e] I.sort() r...
<p>I'm guessing that your <code>df</code> is a Pandas <code>DataFrame</code> object. Pandas has built-in functionality to compute rolling statistics, including a rolling median. This functionality is available via the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rolling.html" rel="nofoll...
python|loops|pandas|for-loop|optimization
4
363,633
40,081,109
Pandas: convert unicode elem in column to list
<p>I have dataframe</p> <pre><code>category dictionary Classified [u'\u043e', u'\u0441', u'\u043a', u'\u043f\u043e', u'\u0443', u'avito', u'\u043e\u0431', u'\u043d\u0438', u'\u043e\u0431\u044a\u044f\u0432\u043b\u0435\u043d\u0438\u044f', u'%8f-', u'\u0434\u043e', u'\u0435\u0449\u0435', u'\u043f\u0440\u0438', u'000'...
<p>Try this:</p> <pre><code>rlst = [] for lst in lsts: ls0 = lst.strip('[] ').split(',') rlst.append([unicode(l.lstrip(' u\'').rstrip('\'')) for l in ls0]) </code></pre> <p><code>rlst</code> is your result as a list of lists of unicode strings.</p>
python|pandas|unicode
0
363,634
40,306,865
Converting a WinAPI screenshot to a OpenCV compatible form
<p>So I originally asked a question <a href="https://stackoverflow.com/questions/40098142/taking-fast-screenshot-winapi-and-opencv">here</a> about taking faster screen captures using win api as compared to PIL. I was able to succesfully capture the screen via BitBlt.</p> <p>Now I am unsure how to convert the bitmap in...
<p><a href="http://docs.activestate.com/activepython/3.3/pywin32/PyCBitmap__GetBitmapBits_meth.html" rel="nofollow"><code>GetBitmapBits()</code></a> in its Python incarnation returns an array of signed ints instead of unsigned bytes. You should first convert it to unsigned bytes and then do as @DanMašek said.</p>
python|opencv|numpy|winapi
2
363,635
40,215,699
Python pandas column asignment between dataframe and series does not work
<p>I have a <code>df</code> dataframe:</p> <pre><code>df = pd.DataFrame({'b':[100,100,100], 'a':[1,2,3]}) df['c'] = pd.np.nan df['d'] = pd.np.nan df['c'] = df['c'].astype(object) df['d'] = df['d'].astype(object) </code></pre> <p><code>df</code> is:</p> <pre><code> a b c d 0 1 100 NaN NaN 1 2 100 Na...
<p>For me works creating new <code>DataFrame</code> <code>df1</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> to original <code>df</code>:</p> <pre><code>def func(x): return pd.Series({'d':{'foo':5, 'bar':10}, 'c':300}) df1 ...
python|pandas|dataframe|variable-assignment|series
2
363,636
39,978,893
optimal data structure to store million of pixels in python?
<p>I have several images and after some basic processing and contour detection I want to store the detected pixels locations and their adjacent neighbours values into a Python Data Structure. I settled for <strong>numpy.array</strong></p> <p>The pixel locations from each Image are retrieved using:</p> <pre><code>loca...
<p>Numpy arrays are great for computation. They are not great for storing data if the size of the data keeps changing. As ali_m pointed out, all forms of array concatenation in numpy are inherently slow. Better to store the arrays in a plain-old python list:</p> <pre><code>coordlist = [] coordlist.append(locationsPx[0...
python|arrays|numpy
1
363,637
39,586,398
How to compare decimal numbers available in columns of pandas dataframe?
<p>I want to compare decimal values which are available in two columns of pandas dataframe.</p> <p>I have a dataframe:</p> <pre><code>data = {'AA' :{0:'-14.35',1:'632.0',2:'619.5',3:'352.35',4:'347.7',5:'100'}, 'BB' :{0:'-14.3500',1:'632.0000',2:'619.5000',3:'352.3500',4:'347.7000',5:'200'} } df1 = pd....
<p>You need cast column to <code>float</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a> and then compare columns, because <code>type</code> of values in columns is <code>string</code>. Then use <a href="http://pandas.pydata.org/pa...
python|pandas|indexing|dataframe|conditional-statements
2
363,638
39,609,426
Pandas: remove encoding from the string
<p>I have the following data frame:</p> <pre><code> str_value 0 Mock%20the%20Week 1 law 2 euro%202016 </code></pre> <p>There are many such special characters such as <code>%20%</code>, <code>%2520</code>, etc..How do I remove them all. I have tried the following but the dataframe is large and I am not sure how many ...
<p>You can use the <code>urllib</code> library and apply it using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html"><code>map</code></a> method of a series. Example - </p> <pre><code>In [23]: import urllib In [24]: dfSearch["str_value"].map(lambda x:urllib.unquote(x).decode('utf8'...
python|python-2.7|pandas
8
363,639
39,848,610
How can I test own image to Cifar-10 tutorial on Tensorflow?
<p>I trained Tensorflow Cifar10 model and I would like to feed it with own single image (32*32, jpg/png).</p> <p>I want to see label and probability of each label as an output, but I having some trouble about this..</p> <p>After searching stack overflow, I found some post which is <a href="https://stackoverflow.com/q...
<p>The video <a href="https://youtu.be/d9mSWqfo0Xw" rel="nofollow noreferrer">https://youtu.be/d9mSWqfo0Xw</a> shows an example for classifying a single image.</p> <p>After the network has already trained by python cifar10_train.py we evaluate the individual image deer6.png of CIFAR-10 database and an own photo of a m...
python|tensorflow
2
363,640
39,579,875
Combine multiple time-series rows into one row with Pandas
<p>I am using a recurrent neural network to consume time-series events (click stream). My data needs to be formatted such that a each row contains all the events for an id. My data is one-hot encoded, and I have already grouped it by the id. Also I limit the total number of events per id (ex. 2), so final width will al...
<p>The idea here is to <code>reset_index</code> within each group of <code>'id'</code> to get a count which row of that particular <code>'id'</code> we are at. Then follow that up with <code>unstack</code> and <code>sort_index</code> to get columns where they are supposed to be.</p> <p>Finally, flatten the multiindex...
python|pandas|numpy
5
363,641
39,676,328
Indexing dataframe by datetime python ignoring hour, minutes, seconds
<p>I have a pandas dataframe <code>df1</code> like the following, where the left hand column is in datetime index:</p> <pre><code>2016-08-25 19:00:00 144.784598 171.696834 187.392857 2016-08-25 20:30:00 144.837891 171.800840 187.531250 2016-08-25 22:00:00 144.930882 171.982199 187.806134 2016-08-25 23:30:00 ...
<p>You can use strings to slice a datetime index:</p> <pre><code>df.loc['2016-08-30':'2016-08-31'] Out: 1 2 3 2016-08-30 01:00:00 144.613005 171.620593 188.083008 2016-08-30 02:30:00 144.532600 171.503879 187.901940 2016-08-30 04:00:00 144.600160 171.569375 1...
python|datetime|pandas|dataframe
1
363,642
39,864,211
How to show truncated X-axis in matplotlib (seaboard) heatmap
<p>I have the following image:</p> <p><a href="https://i.stack.imgur.com/sUDks.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sUDks.jpg" alt="enter image description here"></a></p> <p>Created with this code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import seaborn as sns i...
<p>There's a convenient way to do this through a <code>subplots_adjust</code> method: </p> <pre><code>import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd # create some random data data = pd.DataFrame(np.random.rand(11, 5), columns=['A', 'B', 'C', 'D', 'E'], index = ['yyyyyyyy ...
python|pandas|matplotlib|seaborn
2
363,643
39,428,505
How to "flatten" a Panda Panel by summing up specific columns
<p>I am still familairizing myself with Pandas, and Python in general, so please excuse if this is a simple question. I'd also like to avoid one liners so I can understand the underlying actions if possible! :)</p> <p>I've managed to pull data data which results in a Panel, with four items. The key of each item is a...
<pre><code>agg_dict = {'Quarterly Sales': 'sum', 'Ending Inventory': 'last'} pnl.to_frame().T.stack(0).groupby(level='Type').agg(agg_dict) </code></pre> <p><a href="https://i.stack.imgur.com/ztaiy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ztaiy.png" alt="enter image description here"></a></p>
python|pandas
0
363,644
39,708,455
Compare between 2 Excel files and give difference based on key column
<p>I have 2 excel files (which can be coverted to CSV).</p> <pre><code>File 1: Last Name First Name id(10 digit) email age course abc def 1234567890 axd 00 y2k bcd efg 9012345875 bxe 11 k2z cnn nbc 5678912345 cxn 00 z2k File 2: Group_ID ...
<p>Assuming that you read file 1 and file 2 into pandas data frames df1 and df2,</p> <p>df1.loc[df1['id'] != df2['Person_ID']]</p>
python|csv|pandas
0
363,645
39,740,989
Reformat table in Python
<p>I have a table in a Python script with numpy in the following shape:</p> <pre><code>[array([[a1, b1, c1], ..., [x1, y1, z1]]), array([a2, b2, c2, ..., x2, y2, z2]) ] </code></pre> <p>I would like to reshape it to a format like this:</p> <pre><code>(array([[a2], [b2], . . . ...
<p>Round brackets <code>(1, 2)</code> are <a href="https://docs.python.org/3/library/stdtypes.html#tuple" rel="nofollow">tuples</a>, square brackets <code>[1, 2]</code> are <a href="https://docs.python.org/3/library/stdtypes.html#list" rel="nofollow">lists</a>. To convert your data structure, use <a href="http://docs.s...
python|numpy
1
363,646
39,732,460
How to use evaluation_loop with train_loop in tf-slim
<p>I'm trying to implement a few different models and train them on CIFAR-10, and I want to use TF-slim to do this. It looks like TF-slim has two main loops that are useful during training: train_loop and evaluation_loop. </p> <p>My question is: what is the canonical way to use these loops? As a followup: is it possi...
<p>Thanks to @kmalakoff, <a href="https://github.com/tensorflow/tensorflow/issues/5987" rel="noreferrer">the TensorFlow issue</a> gave a brilliant way to the problem that how to validate or test model in <code>tf.slim</code> training. The main idea is overriding <code>train_step_fn</code> function:</p> <pre><code>impo...
tensorflow|tf-slim
6
363,647
39,502,783
Pandas read_sql_query converting integer column to float
<p>I have the following line</p> <pre><code>df = pandas.read_sql_query(sql = sql_script, con=conn, coerce_float = False) </code></pre> <p>that pulls data from Postgres using a sql script. Pandas keeps setting some of the columns to type float64. They should be just int. These columns contain some null values. Is the...
<p>As per the <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#support-for-integer-na" rel="nofollow">documentation</a>, the lack of NA representation in Numpy implies integer NA values can't be managed, so pandas promotes int columns into float.</p>
python|pandas
4
363,648
39,811,464
How to solve loss = Nan issue in Keras LSTM network?
<p>I am training a LSTM network using Keras with tensorflow as backend. The network is used for energy load forecasting with the size of the dataset being (32292,24). But as the program runs, I am getting Nan values for the loss right from the first epoch. How can I solve this problem ?</p> <p>PS: as far as data prepr...
<p>I changed the activation function of dense layer to 'softmax' (in my case it's about a multi-class classification), and it works.</p>
machine-learning|tensorflow|deep-learning|keras|lstm
2
363,649
39,603,567
How to Combine CSV Files with Pandas (And Add Identifying Column)
<p>How do I add multiple CSV files together and an extra column to indicate where each file came from?</p> <p>So far I have:</p> <pre><code>import os import pandas as pd import glob os.chdir('C:\...') # path to folder where all CSVs are stored for f, i in zip(glob.glob('*.csv'), short_list): df = pd.read_csv(f, ...
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow">.assign(id=i)</a> method, which will add <code>id</code> column to each parsed CSV and will populate it with the <code>i</code> value:</p> <pre><code>df = pd.concat([pd.read_csv(f, header = None)....
python|csv|pandas
3
363,650
39,520,532
How to measure the memory footprint of importing pandas?
<p>I am running Python on a low memory system.</p> <p>I want to know whether or not importing pandas will increase memory usage significantly.</p> <p>At present I just want to import pandas so that I can use the date_range function.</p>
<p>You may also want to use a Memory Profiler to get an idea of how much memory is allocated to your Pandas objects. There are several Python Memory Profilers you can use (a simple Google search can give you an idea). PySizer is one that I used a while ago.</p>
python|pandas
3
363,651
39,538,938
Weird artefacts in a matplotlib bar plot
<p>I am using the pandas plot facilities, to plot a bar plot:</p> <pre><code>spy_price_data.iloc[40:,1].plot(kind='bar') </code></pre> <p>The bar data is plotted correctly, but the figure contains weird artefacts in the form of additional horizontal bars below the actual figure:</p> <p><a href="https://i.stack.imgur...
<p>The 'weird artefacts' are your ticklabels. You can even (almost) read them at the end:</p> <p><a href="https://i.stack.imgur.com/Vx4mZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vx4mZ.png" alt="enter image description here"></a></p> <p>The last value seems to say something like <code>2018-0...
python|pandas|matplotlib|bar-chart
0
363,652
39,480,038
Pandas python: Create function to merge two dataframes based on defined list of columns
<p>In the script that I am writing, I want to frequently repeat the same piece of code, where I create a "numerator" dataframe with one group by, and then a "denominator" dataframe with a different group by. I then merge the two together so that I have the numerator and denominator in one place. I am trying to create a...
<p>So, after concocting my own dataframe with bogus values and trying to work through this, I have found that I run into a <code>ValueError: setting an array element with a sequence</code>. This is due to the fact that you are appending a list to a list and trying to use that as a column index in your df:</p> <pre><co...
python|pandas
1
363,653
39,839,310
TypeError: unsupported operand type(s) for *: 'PCA' and 'float'
<p>EDIT:</p> <p>Here is the head of the data csv:</p> <pre><code> Fresh Milk Grocery Frozen Detergents_Paper Delicatessen 0 12669 9656 7561 214 2674 1338 1 7057 9810 9568 1762 3293 1776 2 6353 8808 7684 2405 3516 7844 3 13265 1196 4221 6404 507 1...
<p><code>pca.fit(X[, y])</code> just fit the model with X, and return the <code>self</code>, that is pca itself.</p> <p>Since that you want to get the transformed data with </p> <pre><code>pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values)) </code></pre> <p>So, you should call <code>pca.fit_t...
python|scikit-learn|sklearn-pandas
2
363,654
39,566,474
Fastest way to insert a 2D array into a (larger) 2D array
<p>Say there's two 2D arrays, <code>a</code> and <code>b</code></p> <pre><code>import numpy as np a = np.random.rand(3, 4) b = np.random.zeros(8, 8) </code></pre> <p>and <code>b</code> is always larger than <code>a</code> over both axes.</p> <p><em>(Edit: <code>b</code> is initialized as an array of zeros, to reflec...
<p>What about :</p> <pre><code>b[:a.shape[0],:a.shape[1]] = a </code></pre> <p>Note I assumed <code>a</code> is to be placed at the begining of <code>b</code> but you could refine it a bit to put <code>a</code> anywhere:</p> <pre><code>a0,a1=1,1 b[a0:a0+a.shape[0],a1:a1+a.shape[1]] = a </code></pre>
python|numpy
9
363,655
39,601,251
Python error when calling column data from Pandas DataFrame
<p>I was practicing to import stock market data from Google Finance into a Pandas DataFrame:</p> <pre><code>import pandas as pd from pandas import Series path = 'http://www.google.com/finance/historical?cid=542029859096076&amp;startdate=Sep+22%2C+2001&amp;enddate=Sep+20%2C+2016&amp;num=30&amp;ei=3HvhV4n3D8XGmAGp4q74A...
<p>this CSV file contains <a href="https://stackoverflow.com/questions/17912307/u-ufeff-in-python-string">BOM (Byte Order Mark) signature</a>, so try it this way:</p> <pre><code>df = pd.read_csv(path, encoding='utf-8-sig') </code></pre> <p>How one can easily identify this problem (thanks to <a href="https://stackover...
python|pandas|dataframe
5
363,656
44,046,171
Python Text similarity and matching - increase weighting when terms are together
<p>I have two columns in pandas which contain a sequence of terms, and my objective is to find the entry from column B which is the closest match to for the entries in column A. I have used the TF-IDF to find the similarity between the two columns, but the problem with this is that it looks for the occurrence of indiv...
<p>What you want is document similarity. I've done a lot of research into this and from my experience Word Mover's Distance is currently the best performing algorithm.</p> <p>The easiest way to do it:</p> <ol> <li>Download the official <a href="https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?usp=sha...
python|pandas|text|similarity|textmatching
0
363,657
43,986,558
Replace integers with labels across different columns - pandas
<p>I have a panda data frame with several column of integers, as well as a corresponding dictionary of {column : {integer:string_label}}.</p> <p>I am trying to create a dataframe in which the integers have been replaced by their labels. The closest I got is below, but the output is somewhat unexpected.</p> <p><strong...
<p>The problem is that you're using the variable <code>column</code> inside the lambda function, the lambda declaration won't store the value, it will use what the variable holds at the time it is being called ( in <code>series.apply(converters[col])</code>), and it can be anything. In fact, if you run your code some t...
python|pandas
0
363,658
44,041,439
How to group similar groups by colum in pandas
<p>folks! </p> <p>I have dataframe like this:<br></p> <pre><code>ID | Name | Thing | belongs ---+------+---------+-------- 1 John 10 1 2 Tom 10 2 3 Tom 10 1 4 John 10 2 5 Bob 10 3 </code></pre> <p>I can't figure out how to group it like:<br></p> <p...
<p><strong>Setup</strong></p> <pre><code>df = pd.DataFrame({'ID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'Name': {0: 'John', 1: 'Tom', 2: 'Tom', 3: 'John', 4: 'Bob'}, 'Thing': {0: 10, 1: 10, 2: 10, 3: 10, 4: 10}, 'belongs': {0: 1, 1: 2, 2: 1, 3: 2, 4: 3}}) </code></pre> <p><strong>Solution</strong></p> <pre><code>#group...
pandas
0
363,659
44,357,084
Pandas: Generate a timeseries filled with the last day of the year
<p>Say I have a Pandas timeseries with irregular intervals.</p> <pre><code>2010-01-04 88.82 2010-11-29 90.70 2010-12-01 90.09 2011-02-26 90.10 2011-08-01 90.55 2011-09-21 89.50 2012-04-01 89.06 2012-04-30 90.22 2012-05-03 90.21 </code></pre> <p>I would like to create from the index anoth...
<p>Make sure your index is a datetimeindex object.</p> <p>If you have pandas series you can use this:</p> <pre><code>s.to_frame().assign(end_dates=s.groupby(s.index.year).transform(lambda x: x.index.max())) </code></pre> <p>or if you already have a dataframe:</p> <pre><code>df.assign(end_dates=df.groupby(df.index.y...
python|pandas|time-series|pandas-groupby
1
363,660
44,363,750
(tensorflow) uavbilgi@uavbilgi-Lenovo-G500:~$ pip install --ignore-installed --upgrade TF_PYTHON_URL
<p>When I write this code on terminal "(tensorflow) uavbilgi@uavbilgi-Lenovo-G500:~$ pip install --ignore-installed --upgrade TF_PYTHON_URL" I am faced with errors: Could not find a version that satisfies the requirement TF_PYTHON_URL (from versions: ) No matching distribution found for TF_PYTHON_URL</p> <p>what shoul...
<p>The <a href="https://www.tensorflow.org/install/install_linux" rel="nofollow noreferrer">Linux installation instructions for TensorFlow</a> use <code>TF_PYTHON_URL</code> as a placeholder for a URL:</p> <blockquote> <ol start="5"> <li><p>(Optional) If Step 4 failed (typically because you invoked a pip version l...
python-3.x|ubuntu|tensorflow
0
363,661
44,320,255
Summing over specific time windows in python pandas
<p>I have medical transaction data that looks like this: </p> <pre><code>id date amt code 124 1/14/12 135 P 124 1/15/12 135 P 124 1/16/12 135 P 124 1/17/12 135 R 124 2/12/12 135 P 124 2/14/12 135 R 124 2/29/12 142 P 124 2/30/12 159 P 192 2/12/12 922 P 192 2/13/12 922 R 192 2/25/12 124 P 192 2/26/12 40 P 135 2/17/...
<p>I had to make sure we had a datetime column</p> <pre><code>df.date = pd.to_datetime(df.date) </code></pre> <hr> <pre><code>df.sort_values('date') \ .assign(code=df.code.eq('P')) \ .groupby('id').rolling('10d', on='date')[['amt', 'code']].sum() \ .query('code &gt;= 2 and amt &gt; 100').reset_index() ...
python|pandas|sum
2
363,662
44,336,269
TensorFlow error "unable to get element from the feed as bytes" when using ActionVLAD
<p>I installed TensorFlow r0.12 using Anaconda and execute the <code>run.sh</code> file from the action detection algorithm <a href="https://github.com/rohitgirdhar/ActionVLAD/" rel="nofollow noreferrer">ActionVLAD</a>: </p> <p>Then I got this error traceback:</p> <pre><code>tensorflow.python.framework.errors_impl.In...
<p>Please refer to the closed issue <a href="https://github.com/rohitgirdhar/ActionVLAD/issues/3" rel="nofollow noreferrer">#3</a> on Github.</p> <p>The issue was that the input path for the pre-trained model was set incorrectly, and so TensorFlow could not load the pre-trained model. The solution is to change the <co...
tensorflow|vlad-vector
0
363,663
44,090,278
Keras LSTM for time-series bad prediction and convergance to unchangable range of values
<p>the model: </p> <pre><code>def buildModel(neurons= 5, batch_size= 1, timestep=1, features=1): model = Sequential() model.add(LSTM(neurons, batch_input_shape=(batch_size, timestep, features), #return_sequences= True, stateful=True)) model.add(De...
<p><code>neurons = 5</code>, this is a very low capacity model. Might not be enough to model the targeted time series function.</p> <p><code>timesteps = 1</code>, this is time series so the output must be dependent on a certain number of <code>timesteps</code> before a correct prediction should be made. <code>timestep...
tensorflow|time-series|keras|forecasting|lstm
1
363,664
44,031,697
How do I split a dataframe into multiple dataframes where each dataframe contains equal but random data
<p>How do I split a dataframe into multiple dataframes where each dataframe contains equal but random data? It is not based on a specific column. </p> <p>For instance, I have one 100 rows and 30 columns in a dataframe. I want to divide this data into 5 lots. I should have 20 records in each of the dataframe with same ...
<p>If you do not care about the new dataframes potentially containing some of the same information, you could use <code>sample</code> where <code>frac</code> specifies the fraction of the dataframe that you desire</p> <pre><code>df1 = df.sample(frac=0.5) # df1 is now a random sample of half the dataframe </code></pre>...
pandas
8
363,665
43,979,996
extracting the top 25 percentile of a sub list in a large data file
<p>I have a large csv file with three columns: <code>AID, VID, Rel</code>. </p> <p>The file is 21 GB. </p> <ol> <li><p>I would like to sort it such that AID is sorted followed by Rel. Result should look like this:</p> <pre><code>AID VID Rel A 3 0.9 A 4 0.88 A 5 0.87 A 1 0.7 A...
<p>Standard pandas syntax does appear to solve this for you:</p> <p><code> import dask.dataframe as dd df = dd.read_csv(...) out = df.groupby('AID').apply( lambda f: f[f.Rel &gt; f.Rel.quantile(0.75)].sort_values( 'Rel', ascending=False), meta=df) </code></p> <p><code>out</code> is now a dask dataframe, w...
python|pandas|sorting|dask|bigdata
0
363,666
44,132,579
feed data into a tf.contrib.data.Dataset like a queue
<p>About the <code>tf.contrib.data.Dataset</code> (from TensorFlow 1.2, see <a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/contrib/data" rel="noreferrer">here</a> and <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/data/README.md" rel="noreferrer">here</a>) usage: ...
<p>The new <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator" rel="nofollow noreferrer"><code>Dataset.from_generator()</code></a> method allows you to define a <code>Dataset</code> that is fed by a Python generator. (To use this feature at present, you must download a nightly build of T...
tensorflow
8
363,667
44,118,416
Pandas: Using variables to create dataframe with one row and column names from variable names
<p>Suppose I have some variables in Python. I am trying to create a 1-row Pandas dataframe, where the column names are the variables' names and the values in the row are from the variables.</p> <p>For example, if I have this code:</p> <pre><code>pi = 3.142 e = 2.718 phi = 1.618 </code></pre> <p>I would like a dat...
<p>I think you were looking for this format:</p> <pre><code>pd.DataFrame([[pi,e,phi]],columns=['pi','e','phi']) </code></pre> <p>Output:</p> <pre><code> pi e phi 0 3.142 2.718 1.618 </code></pre>
python|r|pandas|dataframe
11
363,668
44,357,591
Assigning values to a block in a numpy array
<p>I am trying to change a block within a two-dimensional numpy array by inserting pasting another 2-dim array. The sample below gives me unexpected behavior:</p> <pre><code>import numpy as np M=np.ones((4,4)) print(M) S=[0,1] print('to be set to zero: ',M[S,:][:,S]) M[S,:][:,S]=np.zeros((2,2)) print('after setting to...
<p>You can use numpy advanced indexing <a href="https://docs.scipy.org/doc/numpy-1.12.0/reference/arrays.indexing.html" rel="nofollow noreferrer">ix_</a></p> <pre><code>M[np.ix_(S,S)]=0 M Out[622]: array([[ 0., 0., 1., 1.], [ 0., 0., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.]]) </...
arrays|numpy
2
363,669
43,978,022
Parsing date/time strings in Pandas DataFrame
<p>I have the following Pandas series of dates/times:</p> <pre><code>pd.DataFrame({"GMT":["13 Feb 20089:30 AM", "22 Apr 20098:30 AM", "14 Jul 20108:30 AM", "01 Jan 20118:30 AM"]}) GMT 13 Feb 20089:30 AM 22 Apr 20098:30 AM 14 Jul 20108:30 AM 01 Jan 20118:30 AM </code></pre> <p>What I wo...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="noreferrer"><code>dt.strftime</code></a>:</p> <pre><code>df['GMT'] = pd.to_d...
python|pandas
7
363,670
44,061,823
Removing Data Below A Line In A Scatterplot (Python)
<p>So I had code that graphed a 2dhistogram of my dataset. I plotted it like so:</p> <pre><code>histogram = plt.hist2d(fehsc, ofesc, bins=nbins, range=[[-1,.5],[0.225,0.4]]) </code></pre> <p>I wanted to only look at data above a certain line though, so I added the following and it worked just fine: </p> <pre><code>c...
<p>You could define a <code>mask</code> for your data before you plot and then just plot the data points that actually meet your criteria. Below an example, where all data points above a certain line are plotted in green and all data points below the line are plotted in black. </p> <pre><code>from matplotlib import py...
python|python-3.x|numpy|matplotlib
4
363,671
44,031,016
ValueError: Shape of passed values is (1, 31), indices imply (1, 32)
<p>I'm getting this error:</p> <pre><code> ValueError: Shape of passed values is (1, 31), indices imply (1, 32) </code></pre> <p>In this function:</p> <pre><code>def compute_r_statistic(x): R_stat = np.zeros(shape=(0,0)) x = x[np.logical_not(np.isnan(x))] sample = x for i in range(0,len(x)): ...
<p>Try chaning:</p> <pre><code>print sample[0].argmax() </code></pre> <p>To</p> <pre><code>print(sample.iloc[:,0].argmax()) </code></pre> <p>To see if it helps?</p>
python|pandas
1
363,672
44,059,388
TensorFlow: use tensor as list argument in graph
<p>I would like to use a tf.Tensor as an argument of type (python) list for another operation in a TensorFlow graph. In other words, I would like to use a Tensor as dynamic list argument for another operation. Is this possible?</p> <p>Executable example:</p> <pre><code>import tensorflow as tf import numpy as np grap...
<p>I found a solution using get_shape():</p> <pre><code>def getMoments(myTensor): myRank = len(myTensor.get_shape().as_list()) print('rank via shape:', myRank) myMoments = tf.nn.moments(myTensor, axes=list(range(1, myRank))) return myMoments </code></pre>
python|tensorflow
0
363,673
44,242,795
Numpy/Scipy with masks and RGB images
<p>I'm trying to create a mask for an RGB image using skikit learn. I want to create a mask selecting only pixels which are equal to [0,10,0], ie 10 on green channel. And then show only those pixels. This should be straight-forward, akin to <a href="http://scikit-image.org/docs/dev/user_guide/numpy_images.html" rel="no...
<p>You could get that <code>2D</code> mask with ALL reduction along the last axis -</p> <pre><code>mask = (image == [0,10,0]).all(-1) </code></pre> <p>Then, <code>image[mask]</code> would be <code>(N,3)</code> shaped array of only <code>[0,10,0]</code> values, where <code>N</code> is number of pixels which were of th...
python|numpy|scipy|python-imaging-library
16
363,674
44,204,770
Reading csv like file to pandas
<p>I am trying to read an Excel file into <code>pandas</code>, but I get the message <code>format and extension of the file don't match</code>. </p> <p>When I try to use <code>read_excel</code>, I get an error message, I am therefore using <code>read_csv</code>.</p> <p>This is where the issue is; my 'Excel like' fil...
<p>Your separator is a regex. <code>sep=r'\t*'</code> matches any number of consecutive tabs, and so what should be blank cells get treated as a single delimiter. Try <code>sep='\t'</code> instead.</p>
excel|pandas|export-to-csv
0
363,675
44,230,272
How to use str methods inside pandas query()
<p>There appears to be a right and a wrong way to use str methods inside of pandas query. Why is the first query working as expected but the second one fails: </p> <pre><code>&gt;&gt;&gt; import pandas &gt;&gt;&gt; data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], ... 'year': [2012, 2012, 2013, 20...
<p>Try this trick:</p> <pre><code>In [62]: df.query("name.str.startswith('J').values") Out[62]: coverage name year Cochice 25 Jason 2012 Maricopa 62 Jake 2014 </code></pre> <p>alternatively you can specify <code>engine='python'</code>:</p> <pre><code>In [63]: df.query("name.str.start...
python|string|pandas
3
363,676
44,192,954
How to write csv to another disk in ubuntu by pandas?
<p>I'm new to ubuntu. In my directory <code>/home/admin/mxc/newdata</code>, there is a python file <code>test.py</code> to write csv. But I don't have space to write on this directory. I need to write it to /dev/sda6/export. How to do it?</p> <p><code>test.py</code> contents:</p> <pre><code>import pandas as pd sales...
<p>If all you need is to go a few directories back, then forward, do "../../../path" however many directories back you need to go</p>
python|python-2.7|pandas|ubuntu
0
363,677
69,523,187
For each unique value in pandas dataframe column, make a go.Figure and scatter t
<p>I have a dataframe somewhat like so:</p> <p>Date | Category | Number | Number2 | Etc. |</p> <p>I want to take every unique value in Category, and plot a line graph with the first Number column, with Date as the X axis. For now I was thinking of doing indiviudal go.Figures, but I may condense it into one graph if it ...
<p>I don't think your first approach is too bad---probably not the most efficient method, but can definitely get the job done.</p> <pre><code> listOfUniques = df['Category'].unique() for unique in listOfUniques.values(): tempdf = df[ df['Category'] == unique] plt.plot(tempdf['Date'], tempdf['Numb...
python|pandas|plotly
2
363,678
69,330,911
Pandas/Python: How to create new column based on values from other columns and apply extra condition to this new column
<p>I have a pandas dataframe and I want to create a new column <strong>BB</strong> based on the below condition.</p> <ol> <li>Create a new column <strong>BB</strong>, if the values in column <strong>TGR1</strong> is 0, assign 0 to <strong>BB</strong> else,</li> <li>The value in <strong>TGR1</strong> is not 0, look up ...
<p>One way is to use <a href="https://numpy.org/doc/stable/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer">numpy advanced indexing</a>:</p> <pre><code>import numpy as np # extract columns 1,2,3 into a numpy array with a zeros column stacked on the left vals = np.column_stack((np.zeros(len(df...
python|pandas|dataframe
4
363,679
69,309,398
Python (CSV/XLSX Editing) - If Column 'A' includes "string", then write "string_2" in Column B
<p>Current outcome:</p> <pre><code> *Email* *Organization* m.ali@firstdomain.com /Org: First m.tyson@seconddomain.com /Org: First e.holyfield@firstdomain.com /Org: First </code></pre> <p>Desired outcome:</p> <pre><code> *Email* *Organization* m.ali@f...
<p>Try using <code>loc</code> assignment:</p> <pre><code>df.loc[df['Email'].str.contains('second'), 'Organization'] = '/Org: Second' </code></pre>
python|pandas|string|openpyxl
2
363,680
69,388,239
Python Panda dataframe, giving the amount where 2 columns return true
<p>So I have a really big dataframe with the following information: <a href="https://i.stack.imgur.com/vicdg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vicdg.png" alt="enter image description here" /></a></p> <p>There are 2 columns &quot;eethuis&quot; and &quot;caternaar&quot; which return True ...
<p>If I understand your question correctly, you can use '&amp;', here is an example on random data:</p> <pre><code>import pandas as pd import random # create random data df = pd.DataFrame() df['col1'] = [random.randint(0,1) for x in range(10000)] df['col2'] = [random.randint(0,1) for x in range(10000)] df = df.astype(...
python|pandas|dataframe
1
363,681
69,547,753
multiplying "across" in two numpy arrays
<p>Given two numpy arrays of shape <code>(25, 2)</code>, and <code>(2,)</code>, one can easily multiply them across:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.random.rand(2, 25) b = np.random.rand(2) (a.T * b).T # ok, shape (2, 25) </code></pre> <p>I have a similar situation where...
<pre><code>In [185]: a = np.random.rand(2, 25) ...: b = np.random.rand(2) </code></pre> <p>The multiplication is possible with <code>broadcasting</code>:</p> <pre><code>In [186]: a.shape Out[186]: (2, 25) In [187]: a.T.shape Out[187]: (25, 2) In [189]: (a.T*b).shape Out[189]: (25, 2) </code></pre> <p>(25,2) * (2,)...
python|arrays|numpy
1
363,682
69,610,920
Add two torch tensor list
<p>I want to add two PyTorch tensors together, for example, let</p> <pre><code>a = tensor([[1., 1., 2.], [1., 1., 2.], [1., 1., 2.], [1., 1., 2.], [1., 1., 2.], [1., 1., 2.]]) b = tensor([[4., 5., 6., 7., 8., 9.], [4., 5., 6., 7., 8., 9.], ...
<p>You can repeat the columns of <code>a</code> to match the shape of <code>b</code> with <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.repeat.html" rel="nofollow noreferrer"><code>torch.Tensor.repeat</code></a>, then add the resulting tensor to <code>b</code>:</p> <pre><code>&gt;&gt;&gt; b + a.repeat...
python|pytorch
1
363,683
69,618,062
How to join point with polygon in geopandas
<p>I have the polygon combination of lat-long1,lat2-long2 ..... and point like Lat - Long .</p> <p>I have used GeoPandas library to get the result if there is any point is exist within polygon.</p> <p>Sample Data of Polygon saved in csv file:</p> <ol> <li> <blockquote> <p>POLYGON((28.56056 77.36535,28.564635293716776 7...
<p>I would check the axis order - WKT usually interpreted as longitude first, latitude second order, while the point you construct uses latitude:longitude order.</p> <p>You can try removing the CRS identifier to see if it changes the result.</p> <p>Also see <a href="https://gis.stackexchange.com/questions/376751/shapel...
python|scala|apache-spark|geospatial|geopandas
1
363,684
69,634,325
How do I create a dataframe from a geojason file without using geopandas?
<p>I'm looking to turn a geojason into a pandas dataframe that I can work with using python. However, for some reason, the geojason package will not install on my computer.</p> <p>So wanted to know how I could turn a geojason file into a dataframe witout using the geojason package.</p> <p>This is what I have so far</p>...
<p>You could use <a href="https://github.com/geopandas/geopandas" rel="nofollow noreferrer">geopandas</a>. It's as easy as this:</p> <pre><code>import geopandas as gpd gdf = gpd.read_file('Local_Authority_Districts_(December_2020)_UK_BGC.geojson') </code></pre> <p>You can turn the resulting <code>geodataframe</code> i...
python|json|python-3.x|pandas|geojson
0
363,685
69,613,548
Masking on the entire df
<p>I have two dataframes</p> <p>df1</p> <pre><code>timestamp ABC_d XYZ_d PQR_d ... 2018-01-01 16 nan nan 2018-01-02 15 nan nan 2018-01-03 14 nan nan 2018-01-04 nan 15 nan 2018-01-05 nan 13 nan 2018-01-06 nan nan 17 2018-01-07 nan nan 16 2018-01-08 nan nan 15...
<p>You can compare values in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>DataFrame.where</code></a> with test not missing values, last reshape values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame...
python-3.x|pandas
2
363,686
69,613,848
Choosing values from pandas column with the lowest value
<p>I'm reading a df from csv that has 2 columns showing the prices of various items. In some cases the price is a single int/float, but other cases it could be a range of spaces seperated int/floats or mixture of int/floats with strings.</p> <p>example df:</p> <pre><code> item prices ------ ---...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extractall.html" rel="nofollow noreferrer"><code>Series.str.extractall</code></a> for get <code>integer</code>s or <code>float</code>s, convert to floats and get minimal values:</p> <pre><code>df['prices'] = (df['prices'].str.ex...
python|pandas
2
363,687
69,515,209
error: nothing to repeat at position 0 pd.read_csv()
<p>I'm trying to open a txt file with <code>sep='+++$+++</code> but I get that error. This is the code:</p> <pre><code>pd.read_csv(&quot;dataset.txt&quot;, sep='+++$+++', engine='python') # Error: error: nothing to repeat at position 0 </code></pre> <p>Sample of the txt file:</p> <pre><code>u0 +++$+++ u2 +++$+++ m0 ++...
<p>Change the code to:</p> <pre><code>pd.read_csv('dataset.txt', sep='\+\+\+\$\+\+\+' , engine='python') </code></pre> <p>This is because both + and $ are considered special characters</p>
python|pandas|dataframe
1
363,688
69,608,573
How to filter specific columns of DataFrame for a condition in a different column
<p>My DataFrame has several columns representing specific measurements for the different specimens, and the numbers of rows (measurement points) for each sample are not the same. e.g.</p> <pre><code>df= p1 v1 dv1 p9 v9 dv9 p21 v21 dv21 p26 ...
<p>There's an option with <code>wide_to_long</code>, if you know all of the prefixes:</p> <pre><code>out = (pd.wide_to_long(df.reset_index(), # temporary make index stubnames=['p','v','dv','r'], # the prefixes i='index', j='enum') .query('dv&gt;0'...
python|pandas|dataframe
2
363,689
69,626,729
PyTorch Training exitting after Caching Images
<p>I have a dataset of around 12k Training Images and 500 Validation Images. I am using YOLOv5-PyTorch to train my model. When i start the training, and when it comes down to the <strong>Caching Images</strong> stage, it suddenly quits.</p> <p>The code I'm using to run this is as follows:</p> <pre><code>!python train.p...
<p>Maybe you should add &quot;VRAM consumption&quot; to your title, because this was the main reason your training was crashing. <br><br> Your awnser is still right though, but I would like to get into more detail, to why such crashes can happen for people with this kind of problems.<br><br> Yolov5 works with Imagesize...
pytorch|google-colaboratory|training-data|yolov5
0
363,690
69,541,564
How to concatenate along a dimension of a single pytorch tensor?
<p>I wrote a custom pytorch <code>Dataset</code> and the <code>__getitem__()</code> function return a tensor with shape <code>(250, 150)</code>, then I used <code>DataLoader</code> to generate a batch of data with batch size 10. My intension was to have a batch with shape <code>(2500, 150)</code> as concatenation of th...
<p>PyTorch DataLoader will always add an extra batch dimension at 0th index. So, if you get a tensor of shape <code>(10, 250, 150)</code>, you can simple reshape it with</p> <pre><code># x is of shape (10, 250, 150) x_ = x.view(-1, 150) # x_ is of shape (2500, 150) </code></pre> <p>Or, to be more correct, you can suppl...
numpy|pytorch|tensor
4
363,691
69,584,357
reindex multi level index with missing categories
<p>I have a dataframe with two indexes, <em>group</em> and <em>class</em>. I have a dictionary containing additional levels that need to be added in to both those indexes. Specifically I want to add E to the <em>group</em> index. And i want to ensure all g1, g2, and g3 are present in the <em>class</em> index, per <em>g...
<p>Solution with <code>MultiIndex</code> - created from <code>dict</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.from_product.html" rel="nofollow noreferrer"><code>MultiIndex.from_product</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/...
python|pandas|dataframe|multi-index|reindex
4
363,692
69,664,125
How to download a HuggingFace model 'transformers.trainer.Trainer'?
<p>In 1 code., I have uploaded hugging face 'transformers.trainer.Trainer' based model using save_pretrained() function In 2nd code, I want to download this uploaded model and use it to make predictions. I need help in this step - How to download the uploaded model &amp; then make a prediction?</p> <p>Steps to create m...
<p>What you have saved is the model which the trainer was going to tune and you should be aware that predicting, training, evaluation and etc, are the utilities of <code>transformers.trainer.Trainer</code> object, not <code>transformers.models.xlm_roberta.modeling_xlm_roberta.XLMRobertaForQuestionAnswering</code>. Base...
python|nlp|huggingface-transformers|pre-trained-model
1
363,693
69,383,056
Is there any way to get global ranks from Pytorch distributed (nccl) group?
<p>Suppose we have a Pytorch distributed group object that initialized by <code>torch.distributed.new_group([a,b,c,d])</code>, is there any way to get the global ranks <code>a,b,c,d</code> from this group?</p>
<p>Pytorch offers an <code>torch.distributed.distributed_c10d._get_global_rank</code> function can be used in this case:</p> <pre><code>import torch.distributed as dist def get_all_ranks_from_parallel_group(group): rank=0 results=[] try: while True: results.append(dist.distributed_c10d._...
deep-learning|pytorch|distributed-training
0
363,694
69,652,691
python Incorrect date when converting unix time to utc time
<p>i would like to convert unix timestamp to utc time. i have to convert it using the code below, but each time i get an incorrect result. online date converter returns correct result. how to convert a date to count the number of hours between two periods?</p> <pre><code>import datetime print(datetime.datetime.fromtim...
<p>The timestamp you've provided (<code>1633438809404</code>) is a timestamp <em>in milliseconds</em>, yes? If so, then divide it by 1000 before providing it to <code>datetime.datetime.fromtimestamp</code> (which expects a timestamp in seconds):</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; datetime...
python|pandas|date|datetime|unix
1
363,695
69,606,128
How to split a column from a DataFrame?
<p>I am trying to split a column from a Data frame. I know this can be easily achieved using str.split(), but when I split it should return 7 columns, but it only return the first column.</p> <p>This is the column I am trying to split:</p> <pre><code>print(df1['Genres']) 0 ['D...
<p>Try with <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>ast.literal_eval</code></a> then <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><code>explode</code></a></p> <pre><code>import ast df1['Genres']...
python|pandas
2
363,696
69,538,534
Python - standard deviation of chosen rows in each column
<p>I would like to calculate the standard deviation for each column in the data frame, but only for the selected rows. I would like to reflect this formula from Excel (calculates standard deviation only for highlighted cells and moves one index down each column)</p> <p><img src="https://i.stack.imgur.com/v9nnE.png" alt...
<p>I would use numpy for that:</p> <p>example input:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame(np.arange(50).reshape(10,5,order='F')).add_prefix('m') &gt;&gt;&gt; df m0 m1 m2 m3 m4 0 0 10 20 30 40 1 1 11 21 31 41 2 2 12 22 32 42 3 3 13 23 33 43 4 4 14 24 34 44 5 5 15 25 35 ...
python|pandas|dataframe|loops
-1
363,697
69,386,974
adding column total and mean to DataFrame
<p>I have a data frame like below, I want the sum of col1 and the average of col2 and col3 in the last row.</p> <pre><code>col1 col2 col3 1 3 1 3 4 1 3 5 2 1 1 3 2 2 4 3 1 9 2 3 5 2 5 6 total 17.0 3.0 3.8 </code></pre> <p>Please help.</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.aggregate.html" rel="nofollow noreferrer"><code>DataFrame.agg</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:...
python|pandas|dataframe
4
363,698
69,420,912
Pandas count by time slots
<p>I'm new to pandas and it's still hard to understand how to do that. In pure python, it becomes so hard and unreadable. I need to count rows day-by-day with 1-hour time slots (is the begin-end range in this slot).</p> <p>For ex., for data:</p> <pre><code> begin_time end_time 2020-01-01 11:02:10 20...
<p>This question needs a bit more context but I think you're looking for</p> <pre><code>df.groupby([pd.Grouper(key='begin_time', freq='H')])['column_to_count'].count() </code></pre>
python|pandas|dataframe
1
363,699
69,403,949
Python: Apply .apply() with a self-defined function to a Data Frame- why doesn't it work?
<p>I am trying to apply a self-defined function by using apply() to a data frame. Goal is to calculate the mean of each row / column with a self-defined function. But it doesn't work, probably I still don't understand the logic of .apply() fully. Can someone help me? Thanks in advance:</p> <pre><code>d = pd.DataFrame(...
<p>If possible the best way is a vectorized solution:</p> <pre><code>df = d.sum() / len(d) </code></pre> <p>Your solution is possible too, but you need to change to return the values, and also in <code>apply</code> remove <code>()</code>, finally <code>axis=0</code> is the default value for that parameter, so it can al...
python|pandas|apply
1