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 |
|---|---|---|---|---|---|---|
370,000 | 57,139,632 | Image: Numpy random poisson function lam < 0 Value error | <p>I start with an image and do some processing on it. One of its stages involves adding Poisson distribution to the image. I have a function taking an array and which returns a poisson distribution image. In reality when I run the numpy image array through the numpy Poisson function ,I get the following error </p>
<... | <p>Your error comes from the fact that you defined a Poisson distribution with negative lambda parameter (negative mean) somewhere which makes no sense.</p> | python|image|numpy|image-processing|poisson | 0 |
370,001 | 57,230,109 | how to get multiple column indexes that satisfy a condition | <p>I have data like below:</p>
<pre><code> id attribute1 attribute2 attribute3 attribute4 attribute5 new otherattri
0 1 1 0 0 0 0 1 2
1 2 1 1 1 1 0 1234 12
2 3 0 ... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dot.html" rel="nofollow noreferrer"><code>.dot()</code></a>:</p>
<pre><code>df1=df.loc[:,df.columns[:-2]] #omitting the last 2 columns for reproducibility
df1['new']=df1.dot(df1.columns.str.replace('attribute',''))
print(df1)
</cod... | python|python-3.x|pandas|numpy | 4 |
370,002 | 56,877,033 | Reduce and append in Numpy | <p>Is there a way to use reduce with numpy's append? I want to append 3 arrays together like this:</p>
<pre><code>a = np.array([1,2,3])
b = np.array([11,12,13])
c = np.array([21,22,23])
#below is my real code - the above is just for this example)
np.append.reduce((a,b,c))
</code></pre>
<p>but it looks like reduc... | <p>np.r_[] will do this cleanly...</p>
<pre><code>a = np.array([1,2,3])
b = np.array([11,12,13])
c = np.array([21,22,23])
#below is my real code - the above is just for this example)
np.r_[a,b,c]
</code></pre> | python|numpy|append|reduce | 0 |
370,003 | 57,191,517 | About Output of the Keras LSTM | <p>I have a built a LSTM architecture using Keras. My goal is to map length 29 time series input sequences of floats to length 29 output sequences of floats. I am trying to implement a "many-to-many" approach. I followed <a href="https://stackoverflow.com/questions/43034960/many-to-one-and-many-to-many-lstm-examples-in... | <p>Your model has few flaws. </p>
<ol>
<li><p>The last layer of your model is an LSTM. Assuming you're doing either classification / regression. This should be followed by a Dense layer (SoftMax/sigmoid - classification, linear - regression). But since this is a time-series problem, dense layer should be wrapped in a ... | python|tensorflow|keras|neural-network|lstm | 2 |
370,004 | 57,019,479 | Group pandas DataFrame by given row indices | <p>Let's assume we have a pandas DataFrame <code>df</code> and somehow computed a subsample of the indices of this DataFrame and we name this subsample <code>idx</code>. Now I want to group <code>df</code> by using <code>idx</code> in the sense that the first group contains every row from <code>0</code> to <code>idx[0]... | <p>I do not think there is a native way to do it, but I think you can get what you want like that: </p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=["data"])
idx = np.sort(df.sample(n=10).index)
ind = np.digitize(df.index, idx, right=False)
print... | python|pandas | 1 |
370,005 | 57,031,520 | Modify data in a csv using pandas dataframe | <p>I have a structure like this; used to create a pandas dataframe:</p>
<pre><code>my_dict = { 'name' : ["joe", "jack", "jill", "joan", "jesse","jacob", "jonas"],
'age' : [20,27, 35, 55, 18, 21, 35],
'designation': ["VP", "CEO", "CFO", "VP", "VP", "CEO", "MD"]}
</code></pre>
<p>I... | <p>If you just want to make some modifications/variants to/off the initial data set you can make it with pandas as save it as a different csv file (or append to the original one). But as others have mentioned we might need to know in more detail what you want to accomplish.</p>
<p>1 turn your dictionary into a datafra... | python|pandas|csv | 2 |
370,006 | 57,222,221 | How to write different array together to a file | <p>I want to write some information from a certain hdf5 file to a new txt file.
The information include time,lat,lon,obs,covariance matrix, where each variable is array.</p>
<p>The <code>time</code>is 1D array with a shape <code>(t,)</code>, <code>lat</code> and <code>lon</code> are also 1D array with a shape <code>(t... | <p>This code seems to work. I avoided a few loops by using the <code>print(*anarray)</code> trick to easily print the contents of a one-dimensional array in one line separated by spaces. I used <code>print</code> rather than <code>write</code> to easily get the end-of-line markers in the right places. I could have left... | python|file|numpy | 1 |
370,007 | 57,189,280 | Parsing All Pages of HTML using BeautifulSoup | <p>I'm having problems within my code which works perfectly with one page, but when I try to parse all the 28 pages it doesn't parse 27 pages, but parse only the first one. </p>
<p>The main idea is parse the data from the mentioned url which has 28 pages in overall and I made for loop for it in order to make BS parse ... | <p>You are overwriting <code>titles</code>, <code>companies</code> and <code>summaries</code> with every iteration of the loop. Simply change <code>titles = ...</code> to <code>titles += ...</code>:</p>
<pre><code>from bs4 import BeautifulSoup as bs
import requests
import pandas as pd
titles = []
companies = []
summa... | python|pandas|parsing|beautifulsoup | 2 |
370,008 | 57,012,213 | slow Inference time for Neural Net | <p>I have written a simple Fully connected Neural Network in Pytorch. I saved the model and loaded it in C++ using LibTorch but my inference time is pretty slow for my application field. Inference time right now is about 10 ms. Is it normal or am I doing something wrong?</p>
<p>I measured the inference time on python ... | <p>How much data did you use for the inference? If it is only a few data points, I think there will be no much difference in execution time between python and C++. Maybe try with much more data? </p>
<p>Also, the architecture you are using is straightforward; it can probably run in CPU very well for inference. Don't f... | python|machine-learning|pytorch|libtorch | 1 |
370,009 | 57,034,785 | Removing backslash escape character when saving DataFrame to CSV | <p>I currently have a Pandas DataFrame that contains many backslashes used in escape characters. For example, there are strings that are of the form <code>'Michael\'s dog'</code>.</p>
<p>When I save this DataFrame to a CSV file using <code>pandas.DataFrame.to_csv</code>, I would like to get rid of these backslashes so... | <p>Don't use str.replace, it will simply replace every '\' character.</p>
<p><strong>Use this instead:</strong></p>
<pre><code>df.ColumnName.str.decode('unicode_escape')
</code></pre>
<p><strong>Tests:</strong></p>
<pre><code>>>> data = {'Name':['Tom\\\\\'', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]... | python|pandas|csv|dataframe | 2 |
370,010 | 57,108,112 | Double for loop in 1 line to create a new tuple list | <p>I have two sets of coordinates as numpy array. I would to create a new coordinate based on the first element of each set. </p>
<pre><code>a = np.array([[1,2],[3,4],[5,6]])
b = np.array([[10,20],[30,40],[50,60]])
</code></pre>
<p>so I would like to get </p>
<blockquote>
<p>[(1,10), (3,30), (5, 50)]</p>
</blockqu... | <p>If you want result as tuples, first concatenate them along the second axis with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.c_.html" rel="nofollow noreferrer"><code>np.c_</code></a>, view the result as an array of tuples and flatten the result with <a href="https://docs.scipy.org/doc/numpy/re... | python|numpy | 5 |
370,011 | 46,098,602 | python pandas: lookup value in one column conditioned on other column | <p>I have the following df:</p>
<pre><code>Customer | transaction_id | medium | first_transaction_flag
ABC 12345 organic Y
ABC 23456 email 0
ABC 34567 organic 0
BCD ... | <p>First get the first medium in a series indexed by customer:</p>
<pre><code>first_medium = df.loc[
df['first_transaction_flag'] == 'Y',
['Customer', 'medium']
].set_index('Customer')['medium'] # makes it a series
</code></pre>
<p>Then do the lookup:</p>
<pre><code>df['first_medium'] = first_medium.loc[df[... | python|pandas|if-statement|match|vlookup | 1 |
370,012 | 45,826,688 | Transposing and Aggregating DataFrame | <p>I have a dataframe like this </p>
<pre><code> name tag time val
0 ABC A 1 10
0 ABC A 1 12
1 ABC B 1 12
1 ABC B 1 14
2 ABC A 2 11
3 ABC C 2 12
4 DEF B 3 10
5 DEF C 3 9
6 GHI A 4 14
7 GHI B 4 12
8 GHI C 5 10
</code>... | <pre><code>In [175]: df.pivot_table(index=['name','time'], columns='tag', values='val').reset_index()
Out[175]:
tag name time A B C
0 ABC 1 11.0 13.0 NaN
1 ABC 2 11.0 NaN 12.0
2 DEF 3 NaN 10.0 9.0
3 GHI 4 14.0 12.0 NaN
4 GHI 5 NaN NaN 10.0
</code></p... | python|pandas | 6 |
370,013 | 46,091,635 | How to load a model of Tensorflow over 2GiB, with C++ interface? | <p>When applying TF model with its C++ interface, <code>freeze_graph</code> operations, for the graph file and the cpk file, are required. This operation will then generate a dumped binary protobuffer file.</p>
<p>However, protobuffer does not support to dump a file that is larger than 2GiB.</p>
<p>In this case, what... | <p>You can still load a model if you don't freeze the graph and use savedmodel.</p> | c++|tensorflow|protocol-buffers | 0 |
370,014 | 45,878,054 | Why aren't shapes aligned? | <p>I have been experimenting with basic neural networks, and I found some python code online. However, when I try to add 2 more hidden layers to the network, I receive an error:</p>
<p>File "python", line 30, in
ValueError: shapes (6,4) and (1,4) not aligned: 4 (dim 1) != 1</p>
<p>Can someone please explain what the... | <p>Shape of X is (3,6) so shape of l0 is the same and shape of syn0 is (3,4).</p>
<p>So in line 22 <code>np.(dot0,syn0)</code> they already fail to be dot and raise a <code>ValueError</code> which says shape not align.</p>
<p>You should transpose l0 so its shape become (6,3) then they can be not.</p>
<p>Read <a href... | python|numpy|neural-network|matrix-synapse | 0 |
370,015 | 46,166,275 | Resampling a frequency column in Pandas | <p>I've been looking at the panda resample function, and it seems to only work for daily and above range. But, I want to resample a 64 Hz data into 8 Hz. The file is 170 MB, so I can't attach it here, but the data has 2 arrays, one for time, and the other for the corresponding value. Is it possible to resample it using... | <p><a href="https://en.wikipedia.org/wiki/Frequency" rel="nofollow noreferrer">Frequency is the inverse of time period</a>. Essentially, you want to </p>
<ol>
<li><p>convert frequency to time period</p>
<pre><code>df['T'] = 1 / df['f']
</code></pre></li>
<li><p><code>resample</code> every <code>0.125s</code> (or <cod... | python|pandas | 0 |
370,016 | 46,161,976 | Write Pandas data frame to a file with a leading space | <p>I have a Pandas dataframe of the form</p>
<pre><code>YYYYMMDD HHMMSS JJJJJ.JJJJ
20050414 120000 53474.5
20050415 120000 53475.5
</code></pre>
<p>I would like to concatenate these lines to an existing file, with the output looking like</p>
<pre><code>PREVIOUS DATA HERE
YYYYMMDD HHMMSS JJJJJ.JJJJ
20050... | <p>You can use the <code>line_terminator</code> parameter by adding a space after the newline : <code>line_terminator='\n '</code>.</p>
<pre><code>with open('myfile', 'a') as f:
df.to_csv(f, line_terminator='\n ', sep=' ', index=False)
</code></pre>
<p>It doesn't move the header, and all other lines get the wante... | python|pandas | 1 |
370,017 | 45,748,384 | using groupby/aggregate to return multiple columns | <p>I have an example dataset that I want to groupby one column and then produce 4 new columns based on all of the values of existing columns.</p>
<p>Here is some sample data:</p>
<pre><code>data = {'AlignmentId': {0: u'ENSMUST00000000001.4-1',
1: u'ENSMUST00000000001.4-1',
2: u'ENSMUST00000000003.13-0',
3: u'EN... | <p>You need change <code>name</code> to <code>['name']</code>, because <code>.name</code> return name of group (value of column grouping by):</p>
<pre><code>def aggfunc(s):
if s.value_CDS.any():
c = set(s['name'])
else:
c = set(s['name'])
return ('CodingDeletion' in c or 'CodingInsertion' ... | python|pandas | 8 |
370,018 | 46,011,319 | How to use feed_dict in slim.learning.train of tensorflow | <p>I read an example in tf-slim-mnist, and read one or two answers in Google, but all of them feed data to an 'images' tensor and a 'labels' tensor from an already filled-up tenser of data. For example, in tf-slim-mnist,</p>
<pre><code># load batch of dataset
images, labels = load_batch(
dataset,
FLAGS.batch_... | <p>I think feed_dict is not a good way when input data size varies and hard to fill in memory. </p>
<p>Convert your data into tfrecords is a more proper way. <a href="https://github.com/tensorflow/models/blob/master/slim/datasets/download_and_convert_mnist.py" rel="nofollow noreferrer">Here</a> is the example of conve... | tensorflow | 0 |
370,019 | 45,765,604 | ValueError when doing df.groupby('col1').col2.rank() with Pandas in Python 2 | <p>I received a ValueError when doing a groupby rank.</p>
<p>How do I properly calculate the grouped ranking?</p>
<pre><code>df = pd.concat([pd.DataFrame(dict(col1=[1,2,3], col2=[4,5,6])),
pd.DataFrame(dict(col1=[1,2,3], col2=[7,8,9]))])
df.groupby('col1').col2.rank()
</code></pre>
<p>With ValueErro... | <p>The issue here is one of the same index value for different rows of the input dataframe.</p>
<pre><code>df.index
Int64Index([0, 1, 2, 0, 1, 2], dtype='int64')
</code></pre>
<p>Resetting the index will work to alleviate this error.</p>
<pre><code>df = pd.concat([pd.DataFrame(dict(col1=[1, 2, 3], col2=[4, 5, 6])),
... | python|python-2.7|pandas | 1 |
370,020 | 45,872,498 | Can I add a column header row to a list of lists within a function after the function has compiled the list of lists? | <p>I have a function that (1) scrapes data from a list of URLs that each contain table data. It scrapes html text with BeautifulSoup to collect separate lists containing column headers and table rows. Then it (2) iterates through table row list to create a list of lists. Finally, (3) I have my call function in a for lo... | <p>It seems it will be easiest if you change the return statement in your "scrape_sports_stats" function to this:</p>
<pre><code>return pd.DataFrame(output_list, columns=column_headers)
</code></pre>
<p>You can then use a list comprehension inside <code>pd.concat</code> to build your concatenated DataFrame:</p>
<pre... | python|pandas|loops|beautifulsoup | 0 |
370,021 | 45,790,889 | Replace non-zero values in a pandas dataframe with 1 | <p>I have a pandas dataframe 'result'. One of the attribute in this data frame is 'transaction' which contain value like 0 if it's a non cash transaction and some real number if transaction is cash transaction.This attribute look like:</p>
<pre><code>result['transaction'] = [0,0,0,23.2,432,12,0,0,56.4]
</code></pre>
... | <p>Another option could be to use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html" rel="noreferrer"><code>astype</code></a> to convert to <code>bool</code> and then <code>int</code>. </p>
<pre><code>df.astype(bool).astype(int)
</code></pre>
<p>Which outputs</p>
<pre><code... | python|pandas|dataframe | 9 |
370,022 | 45,888,928 | Passing in array of different sized array tf.placeholder | <p>I want to pass in an array filled with multidimensional arrays of different shapes. What is the best way of passing this into a placeholder to be used in sess.run?</p>
<p>I currently have the following code which is not surprising producing an error.</p>
<pre><code>arr = tf.placeholder(tf.float32, shape=None, name... | <p>The issue is related with the feed_dict input, input should be numpy array not list/placeholder.</p>
<pre><code>a1, a2, a3, ts = sess.run([model.a1, model.a2, model.a3, train_step], feed_dict={
x_input: np.asarray(sub_batch[0]),
y_input: np.asarray(sub_batch[1]),
arr_input: <this should be numpy array, not... | python|tensorflow | 1 |
370,023 | 45,790,873 | How to use np.random.seed() to create new matrix with fixed random value | <p>I want to create new matrix (V) with fixed random value in each position (every time I run algorithm, I want to have this same matrix showing up). Is it possible to use np.random.seed() for matrix? Something like</p>
<pre><code>V = np.zeros([20,50])
V = np.random.seed(V)
</code></pre> | <p>use this to set the seed:</p>
<pre><code>np.random.seed(0) # or whatever value you fancy
</code></pre>
<p>and then generate your random data:</p>
<pre><code>V = np.random.rand(your_shape) # or whatever randomness you fancy like randint, randn ...
</code></pre> | python|numpy|matrix | 4 |
370,024 | 45,777,666 | How to add columns to a tkinter.Listbox? | <p>I am trying to add these panda columns to a <code>Listbox</code>, so they read like this:</p>
<pre><code>New Zealand NZD
United States USD
</code></pre>
<p>ETC.</p>
<p>I am using pandas to get the data from a .csv, but when I try and use a for loop to add the items to the list box using insert I get the error</p>... | <p>You could turn the csv file into a dictionary, use the combined country and currency codes as the keys and just the codes as the values, and finally insert the keys into the <code>Listbox</code>. To get the code of the current selection, you can do this: <code>currencies[listbox.selection_get()]</code>.</p>
<p><cod... | python-3.x|pandas|csv|tkinter|listbox | 2 |
370,025 | 46,056,563 | Appending function created column to an existing data frame | <p>I currently have a dataframe as below:</p>
<p><a href="https://i.stack.imgur.com/8aYgC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8aYgC.png" alt="enter image description here"></a></p>
<p>and wish to add a column, E, that is calculated based on the following function. </p>
<pre><code>def g... | <p>As i understand the essense of question is how to apply some method to every column, taking into account, the fact that to calculate a new value you need an index from dataframe:</p>
<p>I suggest you to extract index as separate column and use apply as usually.</p>
<pre><code>from functools import partial
df['ind... | python|numpy | 2 |
370,026 | 45,846,252 | Save model for Tensorflow Serving | <p>I am new to tensorflow. I have followed tensorflow serving instructions to serve models in docker container. I am able to serve the mnist and inception model by following the instructions from <a href="https://www.tensorflow.org/serving/" rel="nofollow noreferrer">https://www.tensorflow.org/serving/</a>.</p>
<p>... | <p>Tensorflow Serving now support SavedModel format. If you have a retrained model, actually you don't need to use object detection. What you can do is to use the <strong>saver</strong> to <strong>restore session</strong> from a previous format retrained model and then export it again with <strong>SavedModelBuilder</st... | tensorflow|tensorflow-serving | 2 |
370,027 | 45,944,102 | Extracting rows from a pandas DataFrame based on records | <p>Suppose I have a dataframe as follows:</p>
<pre><code>In [42]: df
Out[42]:
regiment company name preTestScore postTestScore
0 Nighthawks 1st Miller 4 25
1 Nighthawks 1st Jacobson 24 94
2 Nighthawks 2nd Ali 31 ... | <p>The key error is because <code>loc</code> expects the index as the first argument. You're passing the entire record...? This isn't going to work. </p>
<p>This works:</p>
<pre><code>print(df.loc[:4])
regiment company name preTestScore postTestScore
0 Nighthawks 1st Miller 4 ... | python|pandas|dataframe|indexing | 1 |
370,028 | 45,889,229 | groupby timeseries fill missing data with 0 | <p>Given a panda timeseries dataframe grouped by 'UUT'</p>
<pre><code>df
Out[64]:
UUT Sum
Date_Time
2017-04-28 18:48:16 uut-01 2
2017-04-28 18:48:18 uut-02 2
2017-04-28 18:48:19 uut-03 2
</code></pre>
<p>I want to use reindex to create a time series in 1 se... | <pre><code>df = df.set_index(['time', 'uut'])
idx = pd.MultiIndex.from_product([df.index, df.uut])
df.reindex(index=idx, fill_value=0)
sum
18:48:16 uut-01 2
uut-02 0
uut-03 0
18:48:18 uut-01 0
uut-02 2
uut-03 0
18:48:19 uut-01 0
uut-0... | python|pandas|dataframe|time-series|pandas-groupby | 1 |
370,029 | 45,939,468 | TF 1.3 build hangs with CUDA-9 on ppc64le | <p>I'm trying to build TF 1.3 with CUDA-9 on Ubuntu ppc64le. With all the required patches for CUDA-9 support (eigen, nccl, and even [TF's PR] (<a href="https://github.com/tensorflow/tensorflow/pull/12502" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/pull/12502</a>), I'm able to build most of TF c... | <p>I found the cause for this hang. This was due to a local change in Eigen that has been working for us for older TF (< 1.3) + CUDA-8 but not with new TF (>1.3) and CUDA-9 with their respective Eigens. On Ubuntu, the problem was raised in the form of hang with no clue whereas RHEL was kind enough to throw the exact... | tensorflow | 0 |
370,030 | 46,170,009 | Return values from a list where difference != 2 | <p>I have a list e.g. <code>my_list = [1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43]</code></p>
<p>I want a function that will return all values from the list where the difference between that value and previous value is not equal to <strong>2</strong>, e.g. the function will return <code>[1, 14, 22, 28, 41]</code> ... | <p>To avoid using the inefficient <code>np.concat</code>, use <code>np.ediff1</code> instead of <code>np.diff</code>, which takes a <code>to_begin</code> argument to pre-pend to the result:</p>
<pre><code>>>> my_list = [1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43]
>>> arr = np.array(my_list)
>&... | python|arrays|numpy | 5 |
370,031 | 45,842,618 | Distance calculation in pandas dataframe with two lat columns and two long columns | <p>I have a pandas Dataframe df with these 4 colums :</p>
<ul>
<li>pickup_latitude</li>
<li>pickup_longitude</li>
<li>dropoff_latitude</li>
<li>dropoff_longitude</li>
</ul>
<p>And I want to create a new column with the distance between the pickup and the dropoff point. </p>
<p>I created this function : </p>
<pre><c... | <p>I think you need only:</p>
<pre><code>data['pickup_longitude'] = data['pickup_longitude'].apply(radians)
</code></pre>
<p>and similar code for the other columns (using lambda or defining a function).</p> | python|pandas|distance|latitude-longitude | 3 |
370,032 | 23,191,550 | Filling dataframe where minimum interval is not satisfied | <p>I have a series of data at approximately 2 to 3 minutes interval. Sometimes the there are huge gaps in the data due to someone closing the monitoring software, say for few hours, and I would like to fill these gaps with an invalid marker if there's a >5 minute interval of missing data, so that I can present the data... | <p>I'm assuming you want <code>NaN</code>'s every few minutes, not just one <code>NaN</code> in the gap, and that you don't mind adding <code>NaN</code>'s where there is no gap, as long as they're also added in the gap. Let me know if this solution does what you want:</p>
<pre><code># Imports
from datetime import dat... | python|pandas | 0 |
370,033 | 23,267,805 | Calculate Euclidean Distance within points in numpy array | <p>I have 3D array as</p>
<pre><code> A = [[x1 y1 z1]
[x2 y2 z2]
[x3 y3 z3]]
</code></pre>
<p>I have to find euclidean distance between each points so that I'll get output with only 3 distance between <code>(row0,row1)</code>,<code>(row1,row2)</code> and <code>(row0,row2)</code>.</p>
<p>I have some code ... | <p>Consider using <a href="http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.spatial.distance.pdist.html#scipy.spatial.distance.pdist" rel="noreferrer">scipy.spatial.distance.pdist</a>.</p>
<p>You can do like this.</p>
<pre><code>>>> A = np.array([[1, 2, 3], [4, 5, 6], [10, 20, 30]])
>>&... | python|arrays|numpy|euclidean-distance | 6 |
370,034 | 23,197,124 | Display non ascii (Japanese) characters in pandas plot legend | <p>If I do this:</p>
<pre><code>import pandas as pd
pd.DataFrame( data=nr.random( (2,2) ), columns=[u'é',u'日本'] ).plot()
</code></pre>
<p>Result:</p>
<p><img src="https://i.stack.imgur.com/cDbH2.png" alt="enter image description here"></p>
<p>So <code>é</code> shows up, but not <code>日本</code>. After googling a bit... | <pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
df = pd.DataFrame( data=np.random.random( (2,2) ), columns=[u'é',u'日本'] )
ax = df.plot()
legend = ax.legend()
font = font_manager.FontProperties(fname='/Users/user/Downloads/IPAfont00303/ipa... | python|unicode|matplotlib|pandas | 7 |
370,035 | 23,377,694 | sum array inside for loop and call it outside of function | <p>Im trying to sum an array that has been populated by a loop, but i can only call the last value in the array. </p>
<p>def nots():</p>
<pre><code>global smhx
tilt, lfo = genfromtxt('reso.csv',
unpack=True,
delimiter=',')
for t in xrange(2,5200):
mrt=max(tilt[0:t])
x= 1-((lfo[t-... | <p>Your question isn't very clear, but I am answering what was asked in the title:</p>
<p>To call a value outside of a function, use <code>global</code>, or pass it in as a parameter:</p>
<p>Using <code>global</code>:</p>
<pre><code>>>> global var
>>> var = 8
>>> def foo():
... global ... | python-2.7|numpy | 0 |
370,036 | 23,353,732 | Python Pandas write to sql with NaN values | <p>I'm trying to read a few hundred tables from ascii and then write them to mySQL. It seems easy to do with Pandas but I hit an error that doesn't make sense to me:</p>
<p>I have a data frame of 8 columns. Here is the column list/index:</p>
<pre><code>metricDF.columns
Index([u'FID', u'TYPE', u'CO', u'CITY', u'LIN... | <p><strong>Update</strong>: starting with pandas 0.15, <code>to_sql</code> supports writing <code>NaN</code> values (they will be written as <code>NULL</code> in the database), so the workaround described below should not be needed anymore (see <a href="https://github.com/pydata/pandas/pull/8208" rel="noreferrer">https... | python|mysql|sql|pandas | 32 |
370,037 | 23,082,342 | Assigning comma separated strings to an array of tuples - python, numpy | <p>Some shell escape command gives me:</p>
<pre><code>a=!ls /cygdrive/s | grep "^Something6" | tr -d [A-Za-z] | sed "s/_.*$//" | sed "s/-/ /" | sed "s/ /,/"
</code></pre>
<blockquote>
<p>['64,2014-04-01',
'64,2014-04-02',
'64,2014-04-03',
'64,2014-04-04',
'64,2014-04-07',
'64,2014-04-07',
'64,2014... | <pre><code>[tuple(x.split(',')) for x in a]
</code></pre> | python|arrays|numpy|tuples|ipython | 6 |
370,038 | 23,015,148 | reading only unique data pandas | <p>I have a huge csv dataset with few columns. One of the column is 'Id'. I want to read only the unique values of the id from the CSV. Is it possible to do so in pandas?</p>
<p>I only want the unique ids but i don't want to load the whole dataset in memory</p> | <p>You will need to put all the content of your file in your memory at one point in time, there is no way around that. (how does your computer know where your IDs are on the disk, without loading them first?)</p>
<p>You can do this sequentially though, so it won't kill your RAM:</p>
<pre><code>unique_ids = set()
csv_... | python|pandas | 1 |
370,039 | 23,022,988 | How to resample large dataframe with different functions, using a key? | <p>I have a large time-series set of data with over 200 recorded values (columns). Some values need to be averaged and some need to be summed, and I have a list that determines which is which. I need help figuring out how to feed that list into the how= function of resample.</p>
<p>Example data: </p>
<pre><code>"Time... | <p>I would pass <code>how</code> a dictionary:</p>
<pre><code>>>> df
WD (deg) RAIN (mm)
Timestamp
2014-04-01 01:01:01.005000 40.916620 68.158840
2014-04-01 01:02:01.027000 40.929836 68.158840
2014-04-01 01:03:01.050000 40.890184 68.103... | python|numpy|pandas|time-series | 2 |
370,040 | 23,272,529 | Merge columns together if the other values are blank | <p>I tend to routinely get data files which have a lot of similar columns, but for each row only one of those columns actually has any data. Though sometimes it only looks that way. Ideally what I want to do is have a function that I can input a list of columns to check, and for any rows that contain just 1 value have ... | <p>My method seems marginally quicker:</p>
<pre><code>In [415]:
df = pd.DataFrame({
"id": pd.Series([1,2,3,4,5,6,7]),
"a1": pd.Series(['a',np.NaN,np.NaN,'c','d',np.NaN, np.NaN]),
"a2": ([np.NaN,'b','c',np.NaN,'d','e', np.NaN]),
"a3": ([np.NaN,np.NaN,np.NaN... | python|pandas | 0 |
370,041 | 23,333,786 | Reference values in the previous row with map or apply | <p>Given a dataframe <code>df</code>, I would like to generate a new variable/column for each row based on the values in the previous row. <code>df</code> is sorted so that the order of the rows is meaningful.</p>
<p>Normally, we can use either <code>map</code> or <code>apply</code>, but it seems that neither of them ... | <p>If you just want to do a calculation based on the previous row, you can calculate and then shift:</p>
<pre><code>In [2]: df = pd.DataFrame({'a':[0,1,2], 'b':[0,10,20]})
In [3]: df
Out[3]:
a b
0 0 0
1 1 10
2 2 20
# a calculation based on other column
In [4]: df['c'] = df['b'] + 1
# shift the column
In... | python|pandas | 4 |
370,042 | 22,983,070 | Multiplying array in python | <p>From <a href="https://stackoverflow.com/questions/8194959/in-python-how-will-you-multiply-individual-elements-of-an-array-with-a-floating">this</a> question I see how to multiply a whole numpy array with the same number (second answer, by JoshAdel). But when I change P into the maximum of a (long) array, is it bette... | <p>There is little difference between the 2 methods:</p>
<pre><code>In [74]:
import numpy as np
H = np.random.random(100000)
%timeit P=H.max()
S=np.random.random(100000)
%timeit SP = P*np.array(S)
%timeit SP = H.max()*np.array(S)
10000 loops, best of 3: 51.2 µs per loop
10000 loops, best of 3: 165 µs per loop
1000 lo... | python|arrays|numpy | 3 |
370,043 | 23,068,488 | Need to write multiple csv files to new folder | <p>I haven't been able to find any information on this topic here, and would really appreciate your help! I'm pretty new to python, but here's what I have.</p>
<p>I have multiple file in a folder, and want to read them, transpose them, and then rewrite them into a new folder. I think I have everything going, but can't... | <p>A few things:</p>
<ol>
<li><p><code>filenames = glob.glob(path + "/*.csv")</code> -- unless I'm wrong, that should be a backslash, not a forward-slash. Forward slashes are primarily used in Unix systems, etc. but definitely not in Windows where path names are concerned.</p></li>
<li><p>Try printing out <code>filena... | python|csv|pandas|transpose | 1 |
370,044 | 35,495,045 | Exponential fit of the data (python) | <p>Hi I'm trying to fit my data with an either polynomial or exponential function which I failed in both. The code I'm using is as follows:</p>
<pre><code>with open('argon.dat','r') as f:
argon=f.readlines()
eng1 = np.array([float(argon[argon.index(i)].split('\n')[0].split(' ')[0])*1000 for i in argon])
II01 = n... | <p>The reason <code>curvefit</code> is giving you a constant (a flat line), is because you're passing it a dataset that is uncorrelated using the model you have defined!</p>
<p>Let me recreate your setup first:</p>
<pre><code>argon = np.genfromtxt('argon.dat')
copper = np.genfromtxt('copper.dat')
f1 = 1 - np.exp(-ar... | python|numpy|matplotlib|scipy|curve-fitting | 6 |
370,045 | 35,604,173 | Split numpy array into similar array based on its content | <p>I have a 2D numpy array that represents the coordinates (x, y) of a curve, and I want to split that curve into parts of the same length, obtaining the coordinates of the division points.</p>
<p>The most easy example is a line defined for two points, for example <strong>[[0,0],[1,1]]</strong>, and if I want to split... | <p>If I understand well, what you want is a simple interpolation. For that, you can use <code>scipy.interpolate</code> (<a href="http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html</a>):</p>
<pre><code>from scipy.interp... | python|arrays|numpy|curves|curvesmoothing | 2 |
370,046 | 35,493,676 | Pandas - Apply function and generate more than one row with lambda function | <p>This apply function works but I don't think its efficient;</p>
<pre><code>xyz = data.apply(lambda row: pd.Series({"z":getNVC(row)[0],"y":getNVC(row)[1],"x":getNVC(row)[2]}),axis=1)
</code></pre>
<p>So I basically want to apply the NVC function once per row and return an <code>np.array</code> which has 3 elements. ... | <p>Going purely by creating the <code>dict</code> (that is input to <code>Series</code>), while calling <code>getNVC</code> only once, the following may work:</p>
<pre><code>pd.Series( dict(zip("zyx", getNVC(row))) )
</code></pre> | pandas | 0 |
370,047 | 35,465,534 | How do I save the entire workspace in pandas (like RData) | <p>starting in pandas here from R. our production use for R is to save a huge amount of data as .RData (through save_image) to disk and use it the next time we load the workspace. it seems that there is no real solution to save the entire pandas workspace to disk . </p>
<p>there is Dill, but doesnt look like to be pro... | <p>You can put your whole script in a class and then use <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow">pickle</a> to serialize and deserialize that object. It might not work out exactly like the work-space instance in R but it's the nearest thing I can think of right now.</p> | python|r|numpy|pandas|hdf | 0 |
370,048 | 35,341,297 | How to create a numpy _object_ array of other numpy arrays of same and different length? | <p>This is my very first question. So let's see if I can explain exactly what I need.</p>
<p>I am given a python <code>list</code> of numpy arrays which can or cannot have different lengths (in one dimension only but this is not important here), e.g.</p>
<pre><code>my_list = [
np.ones((20, 3, 3)),
np.ones(( 1... | <p>Create an empty object arrary first and fill it with my_list, e.g.:</p>
<pre><code>wrapped_list = np.empty((3,),dtype=object)
wrapped_list[:] = my_list2
</code></pre> | python|arrays|numpy | 2 |
370,049 | 35,448,793 | IPython Notebook & Pandas: How does pandas produce html table? | <p>The output of <code>pandas</code> <code>dataframe</code> is an <code>HTML table</code>, I want to know how it produce the html into <code>Ipython Notebook</code>?</p>
<p><a href="https://i.stack.imgur.com/vzBrT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vzBrT.png" alt="enter image descriptio... | <p>In IPython you can display arbitrary HTML by importing ipython's display module. Pandas can convert a <code>DataFrame</code> to html which you can then apply your updates to, e.g.:</p>
<pre><code>import pandas as pd
from IPython import display
df = pd.DataFrame(...)
display.HTML(df.to_html())
</code></pre>
<p>Shou... | python|pandas|ipython|jupyter | 3 |
370,050 | 35,542,749 | Which elements of list go into which histogram bins? | <p>I'm trying to make a scaled scatter plot from a histogram. The scatter plot is fairly straight-forward, make the histogram, find bin centers, scatter plot.</p>
<pre><code>nbins=7
# Some example data
A = np.random.randint(0, 10, 100)
B = np.random.rand(100)
counts, binEdges=np.histogram(A,bins=nbins)
bincenters = ... | <p>You write</p>
<blockquote>
<p>but I want each element of A to only contribute a scaled value to it's bin, that scaled value is stored in B. (i.e. instead of each bin being the count of elements from A for that bin, I want each bin to be the sum of corresponding values from B)</p>
</blockquote>
<p>IIUC, this func... | python|numpy|histogram | 3 |
370,051 | 35,564,253 | tensorflow element-wise matrix multiplication | <p>Say I have two tensors in tensorflow, with the first dimension representing the index of a training example in a batch, and the others representing some vectors of matrices of data. Eg</p>
<pre><code>vector_batch = tf.ones([64, 50])
matrix_batch = tf.ones([64, 50, 50])
</code></pre>
<p>I'm curious what the most i... | <p>Probably the most idiomatic way to do this is using <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/math_ops.html#batch_matmul" rel="noreferrer"><code>tf.batch_matmul()</code></a> operator (in conjunction with <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/array_ops.html#expand_d... | matrix|matrix-multiplication|tensorflow | 6 |
370,052 | 35,659,927 | How can I get the timezone adjusted hour for each row in a pandas DataFrame when working with multiple timezones? | <p>I have a Pandas DataFrame where the index is a <code>uuid</code> and it has two columns: <code>publication_datetime</code> and <code>timezone</code>. I would like to get the timezone adjusted hour for this column to determine if it was published in the morning, afternoon, or evening.</p>
<p>I have come up with a so... | <p>I suspect there is some bad data in the timezone column that is producing your error; I can reproduce the error with a very small dataframe if I have a numeric value for a time zone:</p>
<pre><code>df = pd.DataFrame({
"uuid": [0,1,2,3,4,5],
"publication_timestamp": [
"2015-07-28 00:10:05.852",
"2015-10-03 0... | python|datetime|pandas | 0 |
370,053 | 35,412,492 | Get nearest time value and convert format | <p>I am building a telegram bot which given a geographical position will return the time the next buses will leave from the nearest stop. Now, I am having a problem with the time format and I don't know how to efficiently find the nearest time value.</p>
<p>In pandas I loaded the following file (I deleted some irrelev... | <p><strong>Slicing</strong>: In order to select a slice in the way you asked, you could use a mask:</p>
<pre><code>mask = df['arrival_time'] > '07:35:00'
# then work on df[mask]
</code></pre>
<p>Or if you set the time as index, you can use regular Python-type slicing:</p>
<pre><code>df.set_index('arrival_time', i... | python|pandas | 1 |
370,054 | 35,351,629 | How do I subset a pandas data frame based on a list of string values? | <p>I've got a dF that's over 100k rows long, and a few columns wide — nothing crazy. I'm trying to subset the rows based on a list of some 4000 strings, but am struggling to figure out how to do so. Is there a way to subset using something like. </p>
<p>The dF looks something like this</p>
<pre><code>dog_name coun... | <p>I believe you have a list in your dog name column.</p>
<p>This works fine:</p>
<pre><code>>>> df[df['dog_name'].isin(['Fido', 'Yeller'])]
dog_name count
1 Fido 4
3 Yeller 2
</code></pre>
<p>But if you add a list:</p>
<pre><code>df.ix[4] = (['a'], 2)
>>> df
dog_name count
0... | python|pandas | 12 |
370,055 | 35,609,318 | Fill pandas dataframe with specific values from json | <p>I have a very large, deeply nested json, from which I need only some key-values pairs, not all of them. Because it's very deeply nested, it's not comfortable to create a pandas dataframe directly from the json, because all the values I need will not be in columns.</p>
<p>I need to create pandas dataframe that shoul... | <p>If you're just trying to add a single row to your dataframe, you can use</p>
<pre><code>df = df.append({"groupe":group,"id":id,"MotherName":MotherName,"FatherName":FatherName},
ignore_index=True)
</code></pre> | python|json|pandas|iteration|dataframe | 0 |
370,056 | 35,676,512 | Accessing variables from one class to another in Python | <p>I've got couple of huge tables with data called <strong>bnds.data</strong> and <strong>densities.data</strong>. I've also got a class processing those data tables.
That class is called in a loop and in order to avoid repetitive and time demanding loading those data tables into memory, I want to creat another class a... | <p>In general - yes, with current code, Pixel's __init__ is only executed once. However, there is no need for Density to be a subclass of Pixel, it shares no resemblance or functionality.</p>
<p>A more sensible solution would be to have a method on Pixel, which returns a Density, which is required for initialization o... | python|numpy | 1 |
370,057 | 35,464,652 | How to create ensemble in tensorflow? | <p>I am trying to create an ensemble of many trained models. All models have the same graph and just differ by its weights. I am creating the model graph using <code>tf.get_variable</code>. I have several different checkpoints (with different weights) for the same graph architecture and I want to make one instance mode... | <p>This requires a few hacks. Let us save a few simple models</p>
<pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import tensorflow as tf
def build_graph(init_val=0.0):
x = tf.placeholder(tf.float32)
w = tf.get_variable('w', initializer=init_val... | tensorflow | 3 |
370,058 | 35,344,844 | When to use numpy, csv and pandas, reading a file (2D array) in Python? | <p>There are several ways to read a file whose data is a 2D array. </p>
<ul>
<li>read as a list of lists/tuples</li>
<li>use the module <strong>csv</strong></li>
<li>use the module <strong>numpy</strong></li>
<li>use the module <strong>pandas</strong></li>
</ul>
<p>What are their application scenarios?</p>
<hr>
<pr... | <p>If you want to do matrix multiplication or other operations with matrices based on the data in your file, definitely use <code>numpy</code>, since it's <em>much faster</em> than pure Python code doing the same. </p>
<p>If you want to <em>just store</em> the data and then output it somehow, use either plain text eit... | python|csv|numpy|pandas|read-write | 2 |
370,059 | 11,970,820 | Pool workers do not complete all tasks | <p>I have a relatively simple python multiprocessing script that sets up a pool of workers that append output to a pandas <code>dataframe</code> by way of a custom manager. What I am finding is when I call close()/join() on the pool, not all the tasks submitted by apply_async are being completed.</p>
<p>Here's a simpl... | <p><strong>[EDIT]</strong> The issue which you're seeing is because of this code:</p>
<pre><code>self.results = self.results.append(...)
</code></pre>
<p>this isn't atomic. So in some cases, the thread will be interrupted after reading <code>self.results</code> (or while appending) but before it can assign the new fr... | python|pandas|dataframe|multiprocessing|python-multiprocessing | 3 |
370,060 | 11,953,867 | How do I find out eigenvectors corresponding to a particular eigenvalue of a matrix? | <p>How do I find out eigenvectors corresponding to a particular eigenvalue? </p>
<p>I have a stochastic matrix(P), one of the eigenvalues of which is 1. I need to find the eigenvector corresponding to the eigenvalue 1.</p>
<p>The scipy function <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.linal... | <pre><code>import numpy as np
import numpy.linalg as linalg
P = np.array([[2, 0, 0], [0, 1, 0], [0, 0, 3]])
D, V = linalg.eig(P)
print(D)
# [ 2. 1. 3.]
</code></pre>
<p>The eigenvectors are columns of V:</p>
<pre><code>V = V.T
for val, vec in zip(D, V):
assert np.allclose(np.dot(P, vec), val*vec)
</code></p... | python|numpy|scipy|eigenvector|eigenvalue | 8 |
370,061 | 28,425,484 | SWIG return PyObject as python object? | <p>Suppose I have a SWIG-wrapped class taking care of a pointer to some data, as shown in the following code. I would like to construct a numpy <code>ndarray</code> object from the data and return it to the user. I want it to use the data as it's buffer but not take the ownership. If I'm right, I shall use the numpy C+... | <p>I figured out the solution using typemap in swig:</p>
<pre><code>%typemap(out) double* {
npy_intp dims[1] = {25};
$result = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, $1);
}
class Test {
public:
Test () { ptr_ = new uint8_t[200]; }
~Test() { delete [] ptr_; }
double* get() {
return (double*... | python|numpy|swig | 0 |
370,062 | 28,468,307 | scipy.ndimage.filters.convolve and multiplying Fourier Transforms give different results | <p>Here's my code:</p>
<pre><code>from scipy.ndimage import filters
import numpy
a = numpy.array([[2,43,42,123,461],[453,12,111,123,55] ,[123,112,233,12,255]])
b = numpy.array([[0,2,2,3,0],[0,15,12,100,0],[0,45,32,22,0]])
ab = filters.convolve(a,b, mode='constant', cval=0)
af = numpy.fft.fftn(a)
bf = numpy.fft.fftn... | <p>This turned out to be a fascinating question. It seems that convolution using the Discrete Fourier Transform (as implemented by <code>numpy.fft.fftn</code>) is equivalent to a <a href="http://en.wikipedia.org/wiki/Convolution_theorem#Functions_of_discrete_variable_sequences" rel="nofollow noreferrer">circular convol... | python|numpy|scipy|convolution | 5 |
370,063 | 28,786,954 | Python Pandas: Using 'apply' to apply 1 function to multiple columns | <p>Quick Pandas DataFrame question... Just a conceptual question</p>
<p>Let's say I have a 3 column DataFrame. Call it <code>df</code>:</p>
<pre><code> A B C
0 1 2 3
1 1 2 3
2 1 2 3
3 1 2 3
4 1 2 3
</code></pre>
<p>Now let's say I have a function <code>f(A,B,C)<... | <p>You could do this:</p>
<pre><code>>>> pandas.concat(function(*[col for colname, col in df.iteritems()]), axis=1)
A B C
0 2 1 9
1 2 1 9
2 2 1 9
3 2 1 9
4 2 1 9
</code></pre>
<p>If your function operates row-wise (i.e., it accepts three individual values A, B, and C and returns a tuple ... | python|pandas | 1 |
370,064 | 28,460,830 | using masked array to create pandas DataFrame | <p>Thinking I'm getting the following behaviour b/c my input array is masked, which I'm having a hard time understanding. I've been looking at <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#nan-integer-na-values-and-na-type-promotions" rel="nofollow">this pandas doc on gotchas</a>, but not really sur... | <p>I'm not sure this is the "best-est" way to do this, but I converted the masked array to a regular <code>numpy.ndarray</code> using the <code>numpy.ma.filled()</code> function (<a href="http://docs.scipy.org/doc/numpy/reference/routines.ma.html#to-a-ndarray" rel="nofollow">options listed in this doc</a>). </p>
<pre... | arrays|numpy|pandas | 2 |
370,065 | 28,683,060 | Counting entries by sub-categories and date in pandas | <p>I have a dataframe and I'm trying to count the number of people who've joined a group by date. So this:</p>
<pre><code>individual_id group_id date
a 1 2000-01-01
a 1 2000-01-02
a 1 2000-01-03
b 1 2000-01-02
b ... | <p>First, you can use GroupBy to find out how many joined <strong><em>on</em></strong> each date - i.e.</p>
<pre><code>import pandas as pd
from datetime import datetime
import numpy as np
df = pd.DataFrame({'individual_id':['a','a','a','b','b','c','c','d'],
'group_id':[1,1,1,1,1,1,1,2],
... | python|pandas | 1 |
370,066 | 28,821,150 | Plot points with different colors in a matplotlib animation | <p>I have this piece of code:</p>
<pre><code>fig,ax=subplots(figsize=(20,10))
#ax=plot(matriz[0],matriz[1],color='black',lw=0,marker='+',markersize=10)
#ax=plot(matriz[2],matriz[3],color='blue',lw=0,marker='o',markersize=10)
#show ()
def animate(i):
ax=plot((matt[i][0],matt[i][2]),(matt[i][1],matt[i][3]),lw=0,col... | <p>I think I see what you want to do and, yes, I think it is possible. First, I have set up some random data to simulate what I think you have in <code>matt</code></p>
<pre><code>from random import random as r
numlin=50
matt = []
for j in xrange(numlin):
matt.append([r()*20, r()*10,r()*20,r()*10])
</code></pre>... | python|numpy|matplotlib | 3 |
370,067 | 50,760,792 | Plotting a plane and its normal | <p>I have the normal of a plane and a point lying on it. I am trying to plot both of these out but I don't think this is coming out correctly and I cannot figure out why. Here is my code. </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
point = np.array([1309... | <p>It looks weird because of the aspect ratio of the axis. </p>
<p>If you set the range limit for each axis to be 1:1:1 it will look perpendicular.</p>
<p>Here is an example of 1:1 and not 1:1 range limit of the same "angle":</p>
<p><a href="https://i.stack.imgur.com/lmhHS.png" rel="nofollow noreferrer"><img src="ht... | python|numpy|matplotlib|plot|linear-algebra | 1 |
370,068 | 51,012,995 | Pandas DataFrame - filter, aggregate, and then assign back to original pre-filtered dataset? | <p>I am trying to find a way how to take a ecommerce DataFrame, filter out some values, calculate aggregated metrics per each <code>CustomerID</code>, and then assign them back to each <code>CustomerID</code> to the pre-filtered dataset.</p>
<p>For example - the dummy dataset looks like this:</p>
<pre><code>CustomerI... | <p>Is this what you need ?</p>
<pre><code>df['quantile.25']=df.loc[df.Month==1,'Value'].quantile(0.25)
df
Out[230]:
CustomerID Month Value quantile.25
0 a 1 10 20.0
1 a 2 20 20.0
2 a 3 20 20.0
3 b 1 30 20.0
4 ... | pandas|dataframe | 2 |
370,069 | 51,070,303 | Pandas: create rows for each unique value of a column, even with missing data | <p><em>Note</em>: I had difficulty wording the title of my question, so if you can think of something better to help other people with a similar question, please let me know and I will change it.</p>
<h1>Current Data</h1>
<p>Stored as a Pandas DataFrame </p>
<pre><code>print(df)
week | site | vol
1 | a | 10
2... | <p>Using <code>stack</code> with <code>unstack</code></p>
<pre><code>df.set_index(['week','site']).unstack('week',fill_value=0).stack().reset_index()
Out[424]:
site week vol
0 a 1 10
1 a 2 11
2 a 3 2
3 b 1 55
4 b 2 1
5 b 3 0
6 c 1 69
7 c 2 ... | python|pandas | 5 |
370,070 | 50,979,496 | Python Pandas ordering strings | <p>I am trying to take a final/summary dataframe and create a written summary by concatenating text with numbers/data from various series from the dataframe. The below written script is what I would like to see</p>
<pre><code>Team Stat1 Stat2 Stat3 total increase/decrease written script
red 8 -6... | <p>Lambda function will help to meet this requirement.</p>
<pre><code>def summaryText(x):
text = 'the {} is driven by {},{} and {}'.format(x['total'],\
'Stat1'+ " "+str(x['Stat1']),\
" "+'Stat2'+ " "+str(x['Stat2']),\... | python|string|pandas | 0 |
370,071 | 50,827,164 | Round time in a dataframe | <p>I want to round time in milliseconds in a dataframe
My dataframe is : </p>
<pre><code> id Time
0 12 12:21:13.985
1 21 12:21:15.236
2 88 12:22:52.523
3 32 12:25:26.023
4 64 12:26:33.632
</code></pre>
<p>My desired dataframe:</p>
<pre><code> id ... | <p>Use <strong><code>to_datetime</code></strong> with <strong><code>round</code></strong> and <strong><code>strftime</code></strong></p>
<pre><code>df['Time'] = pd.to_datetime(df['Time']).dt.round('1s').dt.time
id Time
0 12 12:21:14
1 21 12:21:15
2 88 12:22:53
3 32 12:25:26
4 64 12:26:34
</code></pr... | python|pandas|dataframe|time | 2 |
370,072 | 51,034,574 | Total Time difference(in millisecond) between rows with respect to column field | <p>I would like to do up a calculation of time differences/timedelta between rows of my vehicle monitoring system. I have a total of 700 thousand rows of data which includes field such as:</p>
<p>Index, Timestamp, Lat, Long, Vehicle Model</p>
<p>There are 7 different models in my data</p>
<p>As of now, I'm able to d... | <p>Just <code>groupby</code> model and take the <code>diff()</code></p>
<pre><code>>>> df.groupby('model').timestamp.diff()
</code></pre> | python|pandas|spyder|duration|calculation | 1 |
370,073 | 51,101,998 | Python - Filter DataFrame via column-comparison with another df/list | <p>So I have a dictionary of DataFrames which I've split up at the moment into single DataFrames because I don't know how to work on it directly in the dictionary. They are results of test specimen which look like this for example</p>
<pre><code>T01
mm N Cycle
a 1 1
b 2 1
c 3 2
d 4... | <p>Let's assume you have a list of cycles you want to filter for:</p>
<pre><code>cycle_list = [1, 2, 3]
</code></pre>
<p>Now given a dictionary of dataframes <code>data_dict</code>, you can use a dictionary comprehension with Boolean masks to filter for rows satisfying your condition:</p>
<pre><code>res = {k: v[v['C... | python|python-3.x|pandas|dataframe | 0 |
370,074 | 50,693,322 | Exception training Resnet50: "The shape of the input to "Flatten" is not fully defined" | <p>I want to use <code>keras.applications.resnet50</code> to train a Resnet for a two class problem using the following setup:</p>
<pre class="lang-python prettyprint-override"><code>from keras.layers import Dropout, Flatten, Dense
from keras.applications.resnet50 import ResNet50
from keras.models import Model
resN... | <p>Since you are applying no <strong>pooling(avg or max)</strong> to the output of your Resnet model, the output that it is providing is a 4-D tensor, being passed to your Dense layer. Its a good idea to apply pooling before the dense layer, which will extract either the <strong>avg</strong> or <strong>max</strong> of ... | python|tensorflow|keras|deep-learning|resnet | 1 |
370,075 | 50,800,884 | Create dataframe from other dataframe with intermediate calculations | <p>Say I have some data in a pandas dataframe that I want to work with.</p>
<pre><code>>>> df = pd.DataFrame([['a',10,5],['a',12,6],['b',4,2],['b',5,10]],
... columns=['id','val','val2']))
</code></pre>
<p>So the dataframe looks something like this:</p>
<pre><code>>>> df
id ... | <p>Yes, there is.</p>
<ol>
<li>If you're taking the mean over every column, you don't have to specify the column names</li>
<li>You can vectorize your division using <code>DataFrame.div</code> (or the division operator <code>__div__</code>)</li>
</ol>
<p></p>
<pre><code>v = df.groupby('id').mean()
v.T / v.sum(1) * 1... | python|pandas|dataframe | 2 |
370,076 | 50,977,910 | Is there a way to save a frozen tensorflow graph in C++? | <p>I know that you can save a model into a checkpoint or SavedModel with Python. I want to know if there is a way to save the GraphDef returned from FreezeSavedModel C++ function using C++. Thanks!</p> | <p>The function FreezeSavedModel returns a <em>GraphDef</em>-Object. You can save this object with <em>WriteBinaryProto</em> or <em>WriteTextProto</em></p>
<pre><code>//BinaryProto
const string binary_file = io::JoinPath(testing::TmpDir(), "binary_graph.pb");
TF_ASSERT_OK(WriteBinaryProto(Env::Default(), binary_file, ... | c++|tensorflow | 1 |
370,077 | 50,915,875 | Creating a string from pandas column and row data | <p>I am interested in generating a string that is composed of pandas row and column data. Given the following pandas data frame I am interested only in generating a string from columns with positive values</p>
<pre><code>index A B C
1 0 1 2
2 0 0 3
3 0 0 0
4 1 ... | <p>Here is one way using <code>pd.DataFrame.apply</code> + <code>pd.Series.apply</code>:</p>
<pre><code>df = pd.DataFrame([[1, 0, 1, 2], [2, 0, 0, 3], [3, 0, 0, 0], [4, 1, 0, 0]],
columns=['index', 'A', 'B', 'C'])
def formatter(x):
x = x[x > 0]
return (x.index[1:].astype(str) + '-' + x[1:... | python|pandas | 1 |
370,078 | 50,746,653 | Merge Dataframe alonside and rename column | <p>c:/somepath contains below files</p>
<blockquote>
<p>file1 file2 file3</p>
</blockquote>
<p>from "c:/somepath/", I am capturing all the file names in a list called users </p>
<pre><code>users=[d for d in os.listdir("c:/somepath/") if os.path.isdir(os.path.join("c:/somepath/", d))]
</code></pre>
<p><em>Note: t... | <p>IIUC:</p>
<pre><code>pd.concat(pd.read_fwf(f, index_col=[0, 1]).squeeze() for f in users).unstack()
</code></pre>
<h2>MCVE</h2>
<p>I dropped those files into my directory</p>
<pre><code>print(*(p.read_text() for p in Path('.').glob('file*')), sep='\n\n')
index user name %used
1 a 25
2 ... | python|pandas | 1 |
370,079 | 50,680,293 | Python line detection | <p>I am trying to detect lines using this python script:</p>
<pre><code>import cv2
import numpy as np
img = cv2.imread('10crop.tiff')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
minLineLength = 1
maxLineGap = 10
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLengt... | <p>You are almost there, you only need to print all lines. The code you provided only draws 1 line. So add this to your for loop: </p>
<pre><code>for x in range(0, len(lines)):
for x1,y1,x2,y2 in lines[x]:
</code></pre> | python|image|numpy|opencv | 1 |
370,080 | 50,951,412 | Pandas pivot one column while using same column value as column headers | <p>I want to pivot a column in a data frame where column values become the column header and actual value for those columns become <code>1</code> or <code>0</code>.</p>
<p>Example: </p>
<pre><code> movie_id cluster_id answer_id
0 73 1 4
1 80 1 5
4... | <p>Incase you want to rely only on <code>pivot_table</code>. You can do this way :</p>
<pre><code># Use a temporary column with values one, pivot and fill nan with 0
new = df.assign(val=1).pivot_table(columns='answer_id',index=['cluster_id','movie_id'],values='val',fill_value=0).reset_index()
</code></pre>
<p>Or, you... | python|pandas | 1 |
370,081 | 50,929,469 | ImportError: /home/kei/darkflow/darkflow/cython_utils/cy_yolo_findboxes.so: undefined symbol: _Py_ZeroStruct | <p>I have an ImportError:</p>
<pre><code>(tensorflow) kei@giga:~/darkflow$ ./flow --model cfg/yolo.cfg --load yolo.weights --savepb
Traceback (most recent call last):
File "./flow", line 4, in
from darkflow.cli import cliHandler
File "/home/kei/darkflow/darkflow/cli.py", line 3, in
from .net.build import TFNet
File ... | <p>I had a similar issue and I fixed it by cleaning and rebuilding the application in Cython</p>
<pre><code>setup.py clean --all
</code></pre> | python-3.x|tensorflow|cython|yolo|darkflow | 1 |
370,082 | 50,700,325 | How to specify colorbar range and keep it regardless of plotting values | <p>I typed this up last night then as I was about to submit it I figured it out. Submitting in case anyone else needs it.</p>
<p>I am plotting meteorological values for every hour for multiple days on basemap. </p>
<p>I want to keep the same values of the colorbar at all times for each map. Lets say from 0-10 for eac... | <p>The issue was in my contour() and contourf(). Prior I was passing a 10 within the function. </p>
<pre><code>bm.contour(x, y, to_np(energyproduction), 10, colors="black",vmin=0,vmax=10.0)
bm.contourf(x, y, to_np(energyproduction), 10,cmap = get_cmap('jet'),vmin=0,vmax=10.0)
</code></pre>
<p>The 10 designation means... | python|numpy|matplotlib|matplotlib-basemap | 2 |
370,083 | 50,706,598 | How to create a summary DF using data from a primary DF? | <p>This is a small extract of some mock data I am using - it's form what I am calling the "primary" DF. It has multiple customer keys, who each can have multiple devices which could access wifi on a number of days.</p>
<pre><code>Customer Account Key Device Ref Date Data Used (mb)
ABC123 Dev1 ... | <p>You can use <code>groupby</code> + <code>agg</code> function:</p>
<pre><code># aggregate data
df = df.groupby('Customer').agg({'Account_Key': {'Total_Devices':'nunique'},
'Device_Ref_Date':{'Total_Days':'nunique'},
'Data_Used':{'Total_Data_Used':'sum... | python|pandas|dataframe | 1 |
370,084 | 50,996,642 | Create a column based on if a string is a substring in pandas Dataframe | <p>One of the columns in my data frames are identifier names with a specific naming convention. When it was entered, it wasn't entered correctly. I wanted to ask how I can find specific keywords to input in its own column in python. Maybe some sort of loop?</p>
<p>Example:</p>
<pre><code>types = ['XYZ', 'OPQ', 'MNO',... | <p>Using <strong><code>str.extract</code></strong></p>
<pre><code>df['types'] = df.Name.str.extract('({})'.format('|'.join(types)))
ID Name types
0 45 I_name_ls_XYZ_random XYZ
1 46 I_22_name_ABC_random ABC
2 47 I_name_ls_XYZ_random_45 XYZ
3 48 I_name_ls_MNO_random MNO
4... | python|string|pandas|dataframe|series | 1 |
370,085 | 50,778,190 | Pandas dataframe creation returning none | <p>I want to add a column of 1s in the beginning of a pandas dataframe which is created from an external data file 'ex1data1.txt'. I wrote the following code. The problem is the <code>print(data)</code> command, in the end, is returning None. What is wrong with this code? I want <code>data</code> to be a pandas datafra... | <p>Another solution might look like this:</p>
<pre><code>import numpy as np
import pandas as pd
raw_data = pd.read_csv('ex1data1.txt', header= None, names= ['x1','y'])
raw_data.insert(loc=0, column='x0', value=1.0)
print(raw_data)
</code></pre> | python|python-3.x|pandas|dataframe | 2 |
370,086 | 51,053,565 | Weights saved in (Python) tensorflow not loaded in C++ tf | <p>I've followed along with the linked posts and finally managed to load my trained tensorflow model's graph+weights into C++ without it throwing errors at me, but it seems to not properly load the weights. It's possible I'm missing a step, most likely in the inference section. </p>
<p>I've included a fully functional... | <p>You can modify main.cc from tf_label_image_example project.</p>
<p>However, I set the tensorflow_BUILD_CC_EXAMPLE=ON when I built the tensorflow using CMake. </p>
<p>You can reference this <a href="http://www.stefanseibert.com/2017/10/tensorflow-as-dll-into-your-windows-c-project-with-gpu-support-and-cmake-v1-3/" ... | python|c++|tensorflow|keras | 0 |
370,087 | 50,917,211 | Pandas Merge and Sum Data Frames | <p>I have the following data frames:</p>
<p>Data Frame 1:</p>
<pre><code>ID1,ID2,VAL1,VAL2
CAR,RED,5,5
TRUCK,RED,6,6
CAR,BLUE,1,1
</code></pre>
<p>Data Frame 2:</p>
<pre><code>ID1,ID2,VAL1,VAL2
BIKE,RED,5,5
TRUCK,BLACK,6,6
CAR,RED,1,1
</code></pre>
<p>I want to left join these two data frames on the key = {ID1, ID... | <p>To join dataframes in <code>pandas</code> use <a href="http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>pd.merge</code></a>. In the given case join is applied on columns with similar names, thus it's enough to pass the list of those column names... | python|pandas|join|merge | 2 |
370,088 | 51,087,158 | Installing numpy with pip on windows 10 for python 3.7 | <p>I installed python 3.7 on my Windows 10 laptop since it has been officially released as of today (06/28/2018). Then i tried to install numpy package using pip </p>
<pre><code>pip install numpy
</code></pre>
<p>The install proceeds but finally fails with the below error :</p>
<pre><code> source = func(exten... | <p>Installing NumPy on Windows is a common problem if you don't have the right build setup. Instead, I always go to <a href="https://www.lfd.uci.edu/%7Egohlke/pythonlibs" rel="noreferrer">Christoph Gohlke's website</a> to download the wheels you can install for your computer. Christoph generously builds the librarie... | python|numpy|python-3.7 | 28 |
370,089 | 50,839,375 | Applying re to Pandas Dataframe | <p>!! The aim is to apply the working method to text in a Pandas Dataframe !!</p>
<p>Given that I have sentences like the following ones:</p>
<p>"He invited 2 people and pet 3 dogs."</p>
<p>"She invited 3 friends and pet 1 cat."</p>
<p>For each sentence I want to count in a variable how many humans are invited and ... | <p>With pandas, you can use <code>str.extract</code> such as:</p>
<pre><code>df['humans'] = df['sentence'].str.extract('(\d+) (?:people|friend)', re.IGNORECASE, expand=False)
</code></pre>
<p>and same for pets</p> | python|regex|pandas | 2 |
370,090 | 50,746,530 | Tensorflow : Value Error , cannot feed value of (64,) to (?, 27) | <p>I am new python and right now i have this problem.
I am trying to make a CNN model for 27 classifications . But i am getting this error
ValueError: Cannot feed value of shape (64,) for Tensor 'targets/Y:0', which has shape '(?, 27)'[here is the picture of my error<a href="https://i.stack.imgur.com/4Q739.png" rel="n... | <p>It means that your tensor's shapes don't fit the shapes you desired. In your case, you were trying to feed shape of 64 to 27. I think this line of code <code>convnet = fully_connected(convnet,27, activation='softmax')</code> that made this error happened, you have to change the shape of the previous layer first.</p> | python|tensorflow|deep-learning|conv-neural-network|tflearn | 0 |
370,091 | 51,107,460 | setting a value for a column based on groupby of other columns | <p>trying to use pandas <code>loc</code> to subset a dataframe by critera and give a value to another column.</p>
<h3>initialize dataframe</h3>
<pre><code>import random
random.seed(100)
nums = 100
df = pd.DataFrame({'value':[random.randint(-7, 10) for x in range(nums)],
'id': [random.randint(50... | <p>If you instead of <code>.sum()</code> use <code>.transform('sum')</code> you get the grouped result returned per row instead. And by comparing that value with <code>< 0</code> you get a boolean mask.</p>
<p>We can then create your different masks on separate rows and join them with <code>&</code>.</p>
<pre>... | python|pandas|dataframe | 2 |
370,092 | 50,838,170 | Date difference coming out to be wrong - Python | <p>I had date values in two formats (6/13/2018 and 6-13-2018). I had to calculate date difference. Below is my working. </p>
<p>Question: Number of days are coming out to be incorrect for few items.</p>
<pre><code>X['Date of Closing'] = X['Date of Closing'].str.replace('/','-')
X['Date of First Contact'] = X['Date of... | <p>I believe need parameter <code>dayfirst=True</code> or <code>format</code>:</p>
<pre><code>X['Date Difference'] = (pd.to_datetime(X['Date of Closing'], dayfirst=True)-
pd.to_datetime(X['Date of First Contact'], dayfirst=True)).dt.days
</code></pre>
<hr>
<pre><code>X['Date Difference'] = (... | python|pandas|date|date-difference | 1 |
370,093 | 50,877,618 | How to correct this custom loss function for keras with tensorflow? | <p>I want to write a custom loss function that would penalize underestimation of positive target values with weights. It would work like mean square error, with the only difference that square errors in said case would get multiplied with a weight greater than 1.</p>
<p>I wrote it like this:</p>
<pre class="lang-pyth... | <p>As @nuric mentioned, you have to implement your loss using only Keras / Tensorflow operations with derivatives, as these frameworks won't be able to back-propagate through other operations (like numpy ones).</p>
<p>A Keras only implementation could look like this:</p>
<pre class="lang-python prettyprint-override">... | tensorflow|machine-learning|keras|loss-function | 8 |
370,094 | 50,841,462 | ResourceExhaustedError when trying to train with MNIST | <p>I am getting ResourceExhaustedError when trying to train MNIST
I found out that I can change the batch size in order to avoid the problem, but unfortunately I dont know where to do that in my code</p>
<p>Traceback:</p>
<blockquote>
<p>ResourceExhaustedError (see above for traceback): OOM when allocating tensor w... | <p>You have to change the 100 in the following line:</p>
<pre><code>for i in range(10001):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob:0.5})
</code></pre>
<p>So the right code would be :</p>
<pre><code>size_batch=50
for i in range(100... | python|tensorflow|machine-learning|deep-learning|mnist | 0 |
370,095 | 51,038,096 | How can I merge two data sets of different lengths in Python? | <p>I have tried merging with Pandas merge, however, as the length of data is different, merge function is broadcasting the data even when using a key.
The following line of code has been used. </p>
<pre><code>dt = pd.merge(df,data[['Post ID','Sentiment']], on = 'Post ID')
</code></pre>
<p>Using <code>join</code> pro... | <p>This error means that in one of your database, <code>Post ID</code> is an <code>object</code>and in the other one it is defined as <code>int</code>.
You need to convert them so they have the same type, for instance by doing :</p>
<pre><code>df['Post ID'] = df['Post ID'].astype(int)
</code></pre> | pandas|dataframe | 0 |
370,096 | 50,821,934 | combine row from csv with python | <p>For example the below dataframe I have this</p>
<pre><code>jan,feb,mar
AAA,BBB,CCC
Dog,Cat,Ant
111,222,333
Mon,Tue,Wed
1990,1991,1991
XXX,YYY,ZZZ
</code></pre>
<p>I would like to append row 1 and row 2 to first row and so on</p>
<pre><code>jan,feb,mar,AAA,BBB,CCC,Dog,Cat,Ant
AAA,BBB,CCC,Dog,Cat,Ant,111,222,333
D... | <p>Use <code>pd.concat</code> with <code>axis=1</code> and <code>DataFrame.shift()</code>.</p>
<pre><code>n = 3
df = pd.concat((df.shift(-i) for i in range(n)), 1)
</code></pre>
<p>Full example:</p>
<pre><code>import pandas as pd
data = '''\
jan,feb,mar
AAA,BBB,CCC
Dog,Cat,Ant
111,222,333
Mon,Tue,Wed
1990,1991,199... | python|excel|pandas|csv|for-loop | 1 |
370,097 | 50,939,162 | Python Multiindexing and custom sorting | <p>I have a pandas series (edit: whoops meant dataframe) as shown here: <a href="https://i.stack.imgur.com/j9vnh.png" rel="nofollow noreferrer">image</a></p>
<p>I have two questions. First, what is the syntax to display/return all winning hands where Players at Table = 4, and Players to Showdown = 2?</p>
<p>Secondly,... | <p>That is a DataFrame, not a Series. Try</p>
<pre><code>df.loc[4, 2]
</code></pre>
<p>Your second question is more complicated, and might warrant its own SO question. Please post code instead of images!</p> | python|pandas|poker | 1 |
370,098 | 51,096,308 | Searching for multiple values in multiple lines for every unique value in python | <p>I have 3 fields 1:) Invoice number 2:) invoice sub number and 3:) invoice amount. Every unique invoice number might have multiple Invoice sub numbers. The requirement is that for every unique invoice number in the multiple lines if the invoice sub number begins with 1200 and 2100 then a dummy column should be introd... | <p>I suggest use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.any.html" rel="nofollow noreferrer"><code>GroupBy.any</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>tra... | python|pandas|numpy | 0 |
370,099 | 50,919,666 | Match implementation specific C++ char to uint32_t cast in Python | <p>Consider the following C++ program:</p>
<pre><code>#include <cstdint>
#include <iostream>
int main() {
std::string s = "αa";
std::cout << std::hex << uint32_t(s[0]) << std::endl;
std::cout << std::hex << uint32_t(s[1]) << std::endl;
std::cout << std::he... | <p>According to <a href="https://docs.python.org/3.1/library/functions.html#bytearray" rel="nofollow noreferrer">Python doc.</a>:</p>
<blockquote>
<p>The bytearray type is a mutable sequence of integers in the range 0 <= x < 256.</p>
</blockquote>
<p>IMHO, the conversion in C++ should hence handle the charact... | python|c++|numpy|casting|ctypes | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.