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 |
|---|---|---|---|---|---|---|
8,900 | 62,011,091 | Index 38 is out of bounds for axis 1 with size 38 - Sklearn | <p>I am facing this error with the <code>Naive Bayes's</code> <code>CategoricalNB</code> algorithm</p>
<p>It gives the above error after the <strong>2nd attempt</strong> I run the cells. That means it works without any errors during the 1st time and when I try to change something (as small as a comment) and run the no... | <p>I believe your issue is related to having a different set of values for a feature in the train, and feature set.</p>
<p>I went through your database, and found that you have only one record, where the total working years is 38. If that record is only accessible in the test set, then your fit from the training set wi... | python|pandas|scikit-learn | 3 |
8,901 | 57,849,831 | How to predict in multiple and simultanous Keras classifier sessions in Django? | <p>I know similar questions have been asked before and I have read all of them but none solved my problem.</p>
<p>I have a Django project in which I am using <code>CNNSequenceClassifier</code> from <code>sequence_classifiers</code> which is a <code>Keras</code> model. The model files have been fit before and saved to ... | <p>My understanding of <code>tensorflow</code> graphs and sessions is:</p>
<p>A <code>tensorflow</code> graph hosts operations, <code>placeholder</code>s and <code>Variable</code>s. A <code>tensorflow</code> graph lives inside a <code>tensorflow</code> session (that's why to save a trained model using <code>tensorflow... | python|django|tensorflow|keras|tf.keras | 2 |
8,902 | 57,949,871 | How to set/get Pandas dataframes into Redis using pyarrow | <p>Using </p>
<pre><code>dd = {'ID': ['H576','H577','H578','H600', 'H700'],
'CD': ['AAAAAAA', 'BBBBB', 'CCCCCC','DDDDDD', 'EEEEEEE']}
df = pd.DataFrame(dd)
</code></pre>
<p>Pre Pandas 0.25, this below worked. </p>
<pre><code>set: redisConn.set("key", df.to_msgpack(compress='zlib'))
get: pd.read_msgpack(redi... | <p>Here's a full example to use pyarrow for serialization of a pandas dataframe to store in redis</p>
<pre><code>apt-get install python3 python3-pip redis-server
pip3 install pandas pyarrow redis
</code></pre>
<p>and then in python</p>
<pre><code>import pandas as pd
import pyarrow as pa
import redis
df=pd.DataFrame... | python|pandas|redis|pyarrow|py-redis | 42 |
8,903 | 58,115,477 | Pretrained CNN(tensorflow/darknet/caffe) weights for human/vehicle detection only | <p>I am making use of tensorflow's pretrained weights from <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md#coco-trained-models-coco-models" rel="nofollow noreferrer">Tensorflow detection model zoo</a> , which is primarily trained on <a href="http://cocoda... | <p>Have you tried the model <a href="https://github.com/opencv/open_model_zoo/blob/develop/models/intel/person-vehicle-bike-detection-crossroad-1016/description/person-vehicle-bike-detection-crossroad-1016.md" rel="nofollow noreferrer">person-vehicle-bike-detection-crossroad-1016</a> ?</p> | python|tensorflow|caffe|yolo | 1 |
8,904 | 58,101,279 | Avoid using multiple if statements | <p>I am trying to create an if statement to check a condition for each iteration</p>
<pre><code> for in range(100):
B10 = np.random.randint(0, precip.shape[0])
T10 = np.random.randint(0, precip.shape[0] )
if np.abs(B10-T10) <=30:
T10 = np.random.randint(... | <p>Use a <code>while</code> loop instead of a for loop:</p>
<pre class="lang-py prettyprint-override"><code>B10 = np.random.randint(0, precip.shape[0])
T10 = np.random.randint(0, precip.shape[0])
while np.abs(B10-T10) <= 30:
B10 = np.random.randint(0, precip.shape[0])
T10 = np.random.randint(0, precip.shape... | python|pandas|numpy | 3 |
8,905 | 58,108,913 | Dataframe column won't convert from integer string to an actual integer | <p>I have a date string in microsecond resolution. I need it as an integer.</p>
<pre><code>import pandas as pd
data = ["20181231235959383171", "20181231235959383172"]
df = pd.DataFrame(data=data, columns=["A"])
df["A"].astype(np.int)
</code></pre>
<p>Error:</p>
<pre><code>File "pandas\_libs\lib.pyx", line 545, in pa... | <p>Per <a href="https://stackoverflow.com/a/58108900/240443">my answer</a> in your previous question:</p>
<pre><code>import pandas as pd
data = ["20181231235959383171", "20181231235959383172"]
df = pd.DataFrame(data=data, columns=["A"])
# slow but big enough
df["A_as_python_int"] = df["A"].apply(int)
# fast but has ... | pandas|numpy | 1 |
8,906 | 34,168,764 | How can I read a datetime from pandas | <p>I convert a string to date and save the CSV:</p>
<pre><code>df['date'] = pd.to_datetime(df['date'])
df.to_csv('dates.csv')
</code></pre>
<p>But when I try to read the CSV, it get the column as str:</p>
<pre><code>df = pd.read_csv('dates.csv')
type(df['date'].iloc[0])
<type 'str'>
</code></pre>
<p>How can I... | <p>There is the <code>parse_dates</code> parameter in <code>read_csv</code>.</p>
<blockquote>
<p>parse_dates : boolean, list of ints or names, list of lists, or dict
If True -> try parsing the index.
If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
If [[1, 3]] -> combine ... | python|pandas | 1 |
8,907 | 34,357,215 | Add ticks for days on Pandas plot | <p>When plotting a DataFrame with pandas:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
from StringIO import StringIO
mycsv = StringIO("""
time;openBid;highBid;lowBid;closeBid;openAsk;highAsk;lowAsk;closeAsk;volume
2015-12-06T22:00:00.000000Z;1.08703;1.08713;1.08703;1.08713;1.08793... | <p>You can do this with <code>DayLocator</code> and <code>DatesFormatter</code> from <code>matplotlib.dates</code>.</p>
<p>From the docs:</p>
<blockquote>
<p><a href="http://matplotlib.org/api/dates_api.html#matplotlib.dates.DayLocator" rel="nofollow noreferrer"><code>DayLocator</code></a></p>
<p>Make ticks on occuranc... | python|pandas|matplotlib|plot | 1 |
8,908 | 37,041,696 | HTML not rendering properly with Canopy 1.7.1.3323 / IPython 4.1.2 | <p>I've just upgraded to Canopy 1.7.1; I think this problem stems from the change in IPython version from 2.4.1 to 4.1.2.</p>
<p>The issue I have is that calling a DataFrame object in Python seems to use the <code>__print__</code> method, i.e. there's no difference between typing <code>print df</code> and <code>df</c... | <p>This has purposely been disabled. I have requested a way to have it re-enabled but but unsupported.</p>
<p>Please see the request. <a href="https://github.com/jupyter/qtconsole/issues/165" rel="nofollow noreferrer">https://github.com/jupyter/qtconsole/issues/165</a></p> | python|pandas|ipython|canopy | 1 |
8,909 | 54,822,806 | How to sort unique table in dataframe based on a single column? | <p>have df with values </p>
<pre><code> 0 | 1 | 2
0 sun | east | pass
1 moon | west | pass
2 mars | north | pass
3 saturn | east | pass
4 neptune| west | pass
</code></pre>
<p>Need to get the distinct df by looking the values of 1 column. Here in column 1 there ar... | <p>I believe you need <code>groupby</code> with <code>join</code> - only necessary same values of <code>2</code> column per groups:</p>
<pre><code>df = df.groupby([1,2], sort=False)[0].apply(' (or) '.join).reset_index().sort_index(axis=1)
print (df)
0 1 2
0 sun (or) saturn east pass
1... | python|python-3.x|pandas|dataframe|pandas-groupby | 3 |
8,910 | 54,882,230 | Update pandas dataframe values with if else condition? | <p>I want update a pandas dataframe column where it's boolean value is True / False. JSON format is</p>
<pre><code>[
{
"A":"value",
"TIME":1551052800000,
"C":35,
"D":36,
"E":34,
"F":35,
"G":33
},
...
...
]
</code></pre>
<p>Converted it into dataframe</p>
<p><code>df = pd.DataFrame.from_dict... | <p>If I understand correctly, you are better setting relevant slices of the dataframe (<a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="nofollow noreferrer">indexing</a>), as opposed to setting the values with if/else statements.</p>
<p>For example, </p>
<pre><code># df = a pandas.D... | python|pandas | 1 |
8,911 | 55,055,176 | Adding values in a row to next row and deleting first row in pandas dataframe | <p>I have a DataFrame that looks something like:</p>
<pre><code> Geo Age 2010 2011 2012
0 toronto -1 ~ 7 2 1 5
1 toronto 0 ~ 4 5 3 4
2 toronto 5 ~ 9 4 5 5
3 bc -1 ~ 7 1 3 2
4 bc 0 ~ ... | <p>Assuming your df is ordered you can just use a combination of np.where and shift, then filter</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame()
df['Geo'] = ['toronto','toronto','toronto']
df['Age'] = ['-1 ~ 7','0 ~ 4','5 ~ 9']
df['2010'] = [2,5,4]
df['2010'] = np.where(df['Age']=='0 ~ 4',... | python|pandas|indexing | 1 |
8,912 | 54,818,488 | What happens to the Pandas Dataframe after groupby command in python? | <p>I am trying to figure some things out in Pandas. I have a dataFrame(df) with 109 rows and 2 distinct "owner_name" values.</p>
<p>Before the groupby command I am able to view the entire contents with:</p>
<pre><code>with pd.option_context('display.max_rows', None, 'display.max_columns', None):
print(df)
</code><... | <p><code>pandas</code> <code>groupby</code> will return the <a href="https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby object</a>, if you want to see the detail of each <code>groupby</code> subset do with <code>list</code> </p>
<pre><code>list... | python|pandas|dataframe|group-by | 3 |
8,913 | 49,371,343 | Identify cells with only whitespace | <p>I want to apply this function</p>
<pre><code>df.column.str.split(expand = True)
</code></pre>
<p>but the problem is there are some "empty cells", and when I mean "empty" it means that it has, for example, 6 white-spaces. Moreover, this is an iteration, so sometimes I have cells with 2 white-spaces. </p>
<p>How ca... | <pre><code>df['Col1'] = df['Col1'].map(lambda x: x.strip())
</code></pre>
<p>This will remove all leading and trailing spaces in df['Col1']</p> | python|string|pandas | 0 |
8,914 | 49,674,215 | Fill missing values (na) with an list/series after modelling missing values | <p>I am trying to plug the predicted missing values into original df (of course to the column with missing value). How could I do so?</p>
<p>The predicted missing values are basically stored in a list/series whose length is the number of missing values in the original df. The order in the list matches with the order t... | <p>You can use numpy <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html" rel="nofollow noreferrer">where</a> and pandas <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.isnull.html" rel="nofollow noreferrer">isnull</a> function to do that.</p>
<pre><code>df['rel... | python|list|pandas|missing-data|fillna | 0 |
8,915 | 49,601,263 | Loss doesn't decrease in training the pytorch RNN | <p>Here is the RNN network I designed for a sentiment.</p>
<pre><code>class rnn(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super().__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size, hidden_size)
self.h2o = nn.Linear(hidden_size, out... | <p>You just need to call <code>optimizer.step()</code> after you do <code>loss.backward()</code>.</p>
<p>Which, by the way, illustrates a common misconception: <strong>Backpropagation is not a learning algorithm</strong>, it's just a cool way of computing the gradient of the loss w.r.t. your parameters. You then use s... | python|machine-learning|pytorch|rnn | 1 |
8,916 | 27,940,492 | Backward compatibility of ewmvar in pandas | <p>It seems that the <code>ewmvar</code> is not always backward compatible. When using the settings <code>bias=True</code> in both pandas 0.14.1 and 0.15.2, we obtain the same result. However, when <code>bias=False</code>, as is the default, the results are no longer the same.</p>
<p>Is there a way to stay compatible ... | <p>see the section on ewma changes here (a little ways down): <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#new-features" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#new-features</a></p>
<p>These were mostly bug fixes and inconsistencies. Any actual changes are explain... | python|pandas | 1 |
8,917 | 28,101,317 | How to self-reference column in pandas Data Frame? | <p>In Python's Pandas, I am using the Data Frame as such:</p>
<pre><code>drinks = pandas.read_csv(data_url)
</code></pre>
<p>Where data_url is a string URL to a CSV file</p>
<p>When indexing the frame for all "light drinkers" where light drinkers is constituted by 1 drink, the following is written:</p>
<pre><code>d... | <p>You can now use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.query.html#pandas-dataframe-query" rel="noreferrer">query</a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="noreferrer">assign</a> depending on what you need:... | python|pandas|scipy | 8 |
8,918 | 73,355,840 | Where does pandas_datareader get its data from? | <p>I was working on a python program that calculates stock indicators. I used the get_data_yahoo function to get most of the info. But after some research, I found out that the yahoo finance API had been discontinued for quite some time now. So now I'm just curious on how pdr gets this info since it seems that most of ... | <p>What does 'calculates stock indicators' mean? Maybe this will help.</p>
<pre><code>import pandas_datareader as web
import pandas as pd
df = web.DataReader('AAPL', data_source='yahoo', start='2011-01-01', end='2021-01-12')
df.head()
import yfinance as yf
aapl = yf.Ticker("AAPL")
aapl
# get stock info... | python-3.x|pandas | 0 |
8,919 | 73,458,161 | Sum of the values in specific rows in dataframe | <p>I have a dataframe called 'test' like this:</p>
<pre><code>import pandas as pd
from collections import Counter
from nltk import ngrams
data = [['john tom hello text shine bright', 10], ['random text hello text shine bright', 15], ['random text hello text shine bright juli', 14],
['random text hello great sh... | <p>You can achieve everything with pandas from the original dataframe:</p>
<pre><code>out = (df
.assign(words=[[' '.join(x) for x in ngrams(s.split(), 4)]
for s in df['Text']])
.explode('ngrams')
.groupby('ngrams')['Value']
.agg(['count', 'sum'])
.sort_values('count', ascending=False)
.head(5)
)
<... | python|pandas|dataframe | 0 |
8,920 | 34,997,018 | How to get time/freq from FFT in Python | <p>I've got a little problem managing FFT data. I was looking for many examples of how to do FFT, but I couldn't get what I want from any of them. I have a random wave file with 44kHz sample rate and I want to get magnitude of N harmonics each X ms, let's say 100ms should be enough. I tried this code:</p>
<pre><code>i... | <p>Further to @Paul R's answer, <code>scipy.signal.spectrogram</code> is a <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html" rel="noreferrer">spectrogram function</a> in <a href="http://docs.scipy.org/doc/scipy/reference/signal.html" rel="noreferrer">scipy's signal processing m... | python|numpy|matplotlib|scipy|fft | 6 |
8,921 | 35,240,328 | Pythonic way of calculating A x A' (without numpy) | <p>So A is a list of list only containing 0's and 1's . What is the most pythonic (and also fairly fast) way of calculating A * A' without using nympy or scipy.</p>
<p>The numpy equivalent of above would be:</p>
<pre><code>def foo(a):
return a * a.T
</code></pre> | <p>Being that your data is zeroes and ones, probably the best non-numpy solution is to use bitarrays:</p>
<pre><code>def dot_self(matrix):
""" Multiply a 0-1 matrix by its transpose.
Use bitarrays to possibly speed up calculations.
"""
from bitarray import bitarray
rows = tuple(bitarray(row) for ro... | python|numpy|matrix|multidimensional-array|matrix-multiplication | 2 |
8,922 | 67,557,724 | Coalescing rows from boolean mask | <p>I have a 2D array and a boolean mask of the same size. I want to use the mask to coalesce consecutive rows in the 2D array: By coalesce I mean to reduce the rows by taking the first occurrence. An example:</p>
<pre><code>rows = np.r_['1,2,0', :6, :6]
mask = np.tile([1, 1, 0, 0, 1, 1], (2,1)).T.astype(bool)
</code></... | <h1>Upgraded answer</h1>
<p>I realized that my initial submission did a lot of unnecessary operations, I realized that given mask</p>
<pre><code>mask = [1,1,0,0,1,1,0,0,1,1,1,0]
</code></pre>
<p>You simply want to negate the leading ones:</p>
<pre><code>#negate:v v v
mask = [0,1,0,0,0,1,0,0,0,1,1,0]
</code... | numpy | 1 |
8,923 | 60,271,606 | In pandas, how to convert a numeric type to category type to use with seaborn hue | <p>I am stuck on what seems like an easy problem trying to color the different groups on a scatterplot I am creating. I have the following example dataframe and graph:</p>
<pre><code>test_df = pd.DataFrame({ 'A' : 1.,
'B' : np.array([1, 5, 9, 7, 3], dtype='int32'),
'C' : np.arra... | <p>I copy/pasted your code, added libraries for import and removed the comment as I thought it looked good. I get a plot with 'categorical' colouring for value [2,3,4] without changing any of your code. </p>
<p>Try updating your seaborn module using: <code>pip install --upgrade seaborn</code></p>
<p>Here is a list of... | python|pandas|seaborn | 2 |
8,924 | 60,082,869 | Is there a Python alternative for len that returns 1 for simple float | <p>Is there a way in Python to let the <code>len(x)</code> function (or any similar function) return 1 if <code>x</code> is a simple float?</p>
<p>In my case, I have <code>x</code> as a input parameter to a function, and I want to make it robust to (NumPy) array type inputs of <code>x</code> as well as simple scalar f... | <p>No, there is no built-in function like this.</p>
<p>One of the core aspects of how Python is designed is that it is <a href="https://stackoverflow.com/questions/11328920/is-python-strongly-typed">strongly typed</a>, meaning that values are not implicitly coerced from one type to another. For example, you cannot do ... | python|numpy | 0 |
8,925 | 65,414,216 | How to append multiple matrices in python | <p>I have read the following related discussions
<a href="https://stackoverflow.com/questions/877479/whats-the-simplest-way-to-extend-a-numpy-array-in-2-dimensions">What's the simplest way to extend a numpy array in 2 dimensions?</a></p>
<p>However, if I want to expend multiple matrices, for example</p>
<pre><code>... | <p>Try using numpy.concatenate (<a href="https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html</a>):</p>
<pre><code>A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
... | python|numpy|matrix|append | 2 |
8,926 | 50,111,111 | Python Pandas finding column value based on multiple column values in same data frame | <p>df:</p>
<pre><code>no fruit price city
1 apple 10 Pune
2 apple 20 Mumbai
3 orange 5 Nagpur
4 orange 7 Delhi
5 Mango 20 Bangalore
6 Mango 15 Chennai
</code></pre>
<p>Now I want to get city name where "fruit= orange and price =5"</p>
<pre><code>df.loc[(df['... | <p>You could create masks step-wise and see how they look like:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([{'city': 'Pune', 'fruit': 'apple', 'no': 1L, 'price': 10L},
{'city': 'Mumbai', 'fruit': 'apple', 'no': 2L, 'price': 20L},
{'city': 'Nagpur', 'fruit': 'orange', 'no': 3L, 'price': 5L},
{'city': 'Del... | python|pandas | 2 |
8,927 | 63,924,563 | Intercepting CUDA calls | <p>I am trying to intercept cudaMemcpy calls from the pytorch library for analysis. I noticed NVIDIA has a cuHook example in the CUDA toolkit samples. However that example requires one to modify the source code of the application itself which I cannot do in this case. So is there a way to write a hook to intercept CUDA... | <p>A CUDA runtime API call can be hooked (on linux) using the <a href="https://osterlund.xyz/posts/2018-03-12-interceptiong-functions-c.html" rel="nofollow noreferrer">"LD_PRELOAD trick"</a> if the application that is being run is dynamically linked to the CUDA runtime library (<code>libcudart.so</code>).</p>... | c++|cuda|pytorch|interceptor | 4 |
8,928 | 47,029,099 | pandas argsort how to leave nan as nan? | <p>Suppose <code>sr</code> is a <code>pandas.Series</code>, then unlike <code>sr.mean()</code> or <code>sr.std()</code> which skips <code>nan</code> <em>and</em> leaves them intact in the output, <code>sr.argsort()</code> will use <code>-1</code> to indicate where <code>nan</code> are present. But I don't want this con... | <p>Your current approach isn't bad...</p>
<p>Here are some alternatives</p>
<p><strong>Alt 1</strong> </p>
<pre><code>sr.argsort().mask(sr.isnull())
0 1.0
1 0.0
2 2.0
3 NaN
dtype: float64
</code></pre>
<hr>
<p><strong>Alt 2</strong> </p>
<pre><code>sr.dropna().argsort().reindex_like(sr)
0 1.0
1... | python|pandas|dataframe|nan | 3 |
8,929 | 46,671,438 | tensorflow.string_input_producer 'hello world' | <p>I can't get the following string_input_producer-<code>hello world</code> program to run:</p>
<pre><code>import tensorflow as tf
filename = tf.placeholder(dtype=tf.string, name='filename')
f_q = tf.train.string_input_producer(filename, num_epochs=1, shuffle=False)
filename_tf = f_q.dequeue()
with tf.Session() as S... | <p>This can work.</p>
<pre><code>import tensorflow as tf
filename = ['hello world']
f_q = tf.train.string_input_producer(filename, num_epochs=1, shuffle=False)
filename_tf = f_q.dequeue()
with tf.Session() as S:
S.run(tf.local_variables_initializer())
coord = tf.train.Coordinator()
threads = tf.train.sta... | python|tensorflow | 0 |
8,930 | 46,760,812 | Use loss in the keras model function | <p>I am trying to build the a very simple model using keras using the Model function, like below, where the input and output of the Model function are [img,labels] and the loss.
I am confused why this code is not working, if the output cannot be the loss. How should the Model function work and when should we use the Mo... | <p>As @yu-yang pointed out, the loss is specified with <code>compile()</code>.
If you think about it, it makes sense because the real output of your model is your prediction, not the loss, the loss is only used to train the model.</p>
<p>A working example of your network:</p>
<pre><code>import keras
from keras.optimi... | tensorflow|keras | 3 |
8,931 | 46,731,506 | Remove exact rows and frequency of rows of a data.frame that are in another data.frame in python 3 | <p>Consider the following two data.frames created using pandas in python 3:</p>
<pre><code>a1 = pd.DataFrame(({'A': [1, 2, 3, 4, 5, 2, 4, 2], 'B': ['a', 'b', 'c', 'd', 'e', 'b', 'd', 'b']}))
a2 = pd.DataFrame(({'A': [1, 2, 3, 2], 'B': ['a', 'b', 'c', 'b']}))
</code></pre>
<p>I would like to remove the exact rows of a... | <p>Lets use groupby cumcount:</p>
<pre><code>a1['count'] = a1.groupby(['A','B']).cumcount()
a2['count'] = a2.groupby(['A','B']).cumcount()
</code></pre>
<p><strong>Option 1</strong> - merge and query </p>
<pre><code>df = (pd.merge(a1,a2, indicator=True, how='left')
.query("_merge != 'both'")
.drop(['... | python|python-3.x|pandas|dataframe | 1 |
8,932 | 46,721,982 | How can I increase the maximum query time? | <p>I ran a query which will eventually return roughly 17M rows in chunks of 500,000. Everything seemed to be going just fine, but I ran into the following error:</p>
<pre><code>Traceback (most recent call last):
File "sql_csv.py", line 22, in <module>
for chunk in pd.read_sql_query(hours_query, db.conn, chu... | <p>When executing queries, Presto restricts each query by CPU, memory, execution time and other constraints. You hit execution time limit. Please ensure that your query is sound, otherwise, you can crash the cluster.</p>
<p>To increase query execution time, define a new value in <a href="https://prestodb.io/docs/curre... | python|python-2.7|pandas|presto|jaydebeapi | 2 |
8,933 | 32,855,650 | generic scoring module using python pandas | <p>Hi I'm trying to develop a generic scoring module for grading students based on variety of attributes. I'm trying to develop a generic method using python pandas
Input:
An input data frame with student ID and UG Major and attributes for scoring (I called df_input)
An input ref. data frame that contains scoring para... | <p>If I understand the question correctly, you are trying to store a collection of rules in <code>df_ref</code> that are to be applied to <code>df_input</code> to generate scores. While this certainly can be done, you should make sure that your rules are well defined. This would also guide you in writing the correspond... | python|pandas|scoring | 2 |
8,934 | 63,189,074 | Doubts about the functioning of a tf/keras net | <p>I'm studying quantile regression and I have some problem to understand how works the net below:</p>
<pre><code> z = tf.keras.layers.Input((len(features),), name="Patient")
x = tf.keras.layers.Dense(100, activation="relu", name="d1")(z)
x = tf.keras.layers.Dense(100, activatio... | <blockquote>
<p>In the line:</p>
<pre><code>preds = tf.keras.layers.Lambda(lambda x: x[0] + tf.cumsum(x[1], axis=1),
name="preds")([p1, p2])
</code></pre>
<p>The input to Lambda layer is <code>[p1, p2]</code>. So <code>x = [p1, p2]</code>. Thus,
<code>x[0] = p1</code>, <code>x[1... | python|tensorflow|keras|regression|data-science | 1 |
8,935 | 63,195,178 | In pandas dataframe, Need to split columns and add them back to other rows | <p>I have a <code>STATUS</code> column in data frame which I am getting the counts using <code>value_count</code> function</p>
<pre><code>df.STATUS.value_counts(sort=True)
</code></pre>
<p>Output:</p>
<pre><code>Verified 171
ErrTab; 9
WarKeyWord; 4
ErrTab; and WarKeyWord; 10
... | <p>In order to get not too long source DataFrame, I defined it
as:</p>
<pre><code> STATUS Amount
0 Verified 1
1 Verified 2
2 Verified 3
3 ErrTab; 1
4 ErrTab; 2
5 Er... | python|pandas|numpy | 0 |
8,936 | 67,704,903 | Calculating average dataframe filtered by two columns | <p>I have this Dataframe</p>
<pre><code> Unnamed: 0 Datetime HomeTeam AwayTeam Ball PossessionMatch_H Ball PossessionMatch_A
0 0 2021-05-24 02:30:00 U. De Chile Everton 68 32
1 1 2021-05-23 21:00:00 Huachipato Colo Colo 48 52
2 2 2021-05... | <p>How about the following?</p>
<pre><code>hometeam_count = df.groupby("HomeTeam")["Ball PossessionMatch_H"].count()
hometeam_sum = df.groupby("HomeTeam")["Ball PossessionMatch_H"].sum()
awayteam_count = df.groupby("AwayTeam")["Ball PossessionMatch_A"].count()... | python|pandas|dataframe | 1 |
8,937 | 67,807,675 | Split a list from Dataframe column into specific column name | <p>I have a question regarding splitting a list in a dataframe column into multiple columns. But every value that is splitted needs to be placed in a specific column.</p>
<p>Let's say I have this Dataframe:</p>
<pre><code>date data
2020-01-01 00:00:00 [G07, G08, G10, G16]
2020-01-01 00:00:01 [G0... | <p>Check with <code>MultiLabelBinarizer</code> from <code>sklearn</code></p>
<pre><code>from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
s = pd.DataFrame(mlb.fit_transform(df['data']),columns=mlb.classes_, index=df.index)
df = df.join(s)
</code></pre> | python|pandas|dataframe | 4 |
8,938 | 31,690,870 | Pandas Groupby: Summarizing Activity Log | <p>I'm trying to parse an activity log that I have simplified below.</p>
<pre><code>df = pd.DataFrame({'Job_Id':[1,1,1,2,2,2],
'Activity': ['issued', 'assigned', 'complete', 'issued', 'assigned', 'complete'],
'Timestamp': ['2015-07-23 19:02:36', '2015-07-23 19:57:47', '2015-07-... | <p>It is a perfect usecase for <code>pivot_table</code>:</p>
<pre><code>df.pivot_table(columns=['Activity'],values=['Timestamp'],index=['Job_Id'], aggfunc=lambda x : x)
</code></pre> | python-2.7|pandas | 1 |
8,939 | 31,888,871 | Pandas - replacing column values | <p>I know there are a number of topics on this question, but none of the methods worked for me so I'm posting about my specific situation</p>
<p>I have a dataframe that looks like this:</p>
<pre><code>data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
data['sex'].replace(0, 'Female')
data['sex']... | <p>Yes, you are using it incorrectly, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html"><code>Series.replace()</code></a> is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. O... | python|pandas | 66 |
8,940 | 31,819,737 | Numpy put array in Nth dimension | <p>I often end up trying to take a bunch of arrays and putting them in different dimensions as below,</p>
<pre><code>x = x.reshape((x.size, 1, 1))
y = y.reshape((1, y.size, 1))
z = z.reshape((1, 1, z.size))
return x + y + z
</code></pre>
<p>I have two problems, I would like to do something like,</p>
<pre><code>x = ... | <p>first, you are doing something similar to <code>np.ix_</code>.</p>
<pre><code>In [899]: x,y,z=np.ix_(np.arange(3),np.arange(4),np.arange(5))
In [900]: x.shape,y.shape,z.shape
Out[900]: ((3, 1, 1), (1, 4, 1), (1, 1, 5))
</code></pre>
<p><code>numpy.lib.index_tricks.py</code> has this and other indexing functions an... | python|numpy|multidimensional-array | 1 |
8,941 | 41,664,280 | Understanding Numpy Multi-dimensional Array Indexing | <p>Please, can anyone explain the difference between these three indexing operations: </p>
<pre><code>y = np.arange(35).reshape(5,7)
# Operation 1
y[np.array([0,2,4]),1:3]
# Operation 2
y[np.array([0,2,4]), np.array([[1,2]])]
# Operation 3
y[np.array([0,2,4]), np.array([[1],[2]])]
</code></pre>
<p>What I don't get i... | <pre><code>In [1]: import numpy as np; y = np.arange(35).reshape(5,7)
</code></pre>
<h2>Operation 1</h2>
<pre><code>In [2]: y[np.array([0,2,4]), 1:3]
Out[2]:
array([[ 1, 2],
[15, 16],
[29, 30]])
</code></pre>
<p>Here we have a mix of advanced indexing (with the array) and basic indexing (with the sli... | python|numpy|indexing|array-broadcasting | 3 |
8,942 | 41,476,436 | Pandas transform() vs apply() | <p>I don't understand why <code>apply</code> and <code>transform</code> return different dtypes when called on the same data frame. The way I explained the two functions to myself before went something along the lines of "<code>apply</code> collapses the data, and <code>transform</code> does exactly the same thing as <... | <p>It looks like <code>SeriesGroupBy.transform()</code> tries to cast the result dtype to the same one as the original column has, but <code>DataFrameGroupBy.transform()</code> doesn't seem to do that:</p>
<pre><code>In [139]: df.groupby('id')['cat'].transform(lambda x: (x == 1).any())
Out[139]:
0 1
1 1
2 1
3... | python|pandas|transform|apply | 11 |
8,943 | 27,630,715 | Doing a scipy.optimize.root runs out of memory, what are good alternatives? | <p>So I'm trying to use <code>scipy.optimize.root</code> but I'm running out of memory, the reason being there isn't enough memory to calculate the jacobian.</p>
<p>I was wondering what alternative I might be able to use given my memory constraint?, or is there a way to circumvent it somehow?</p>
<p>My input size is ... | <p>Try using <code>method='krylov'</code>.</p>
<p>See also <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#root-finding-for-large-problems" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#root-finding-for-large-problems</a></p>
<p>If you know the jacobian, you... | python|numpy|scipy | 1 |
8,944 | 68,865,728 | Difference between a = Loss and a = Loss() | <p>I'm curious what the difference between the following lines of code are:</p>
<pre><code>a = torch.nn.BCELoss
</code></pre>
<p>and</p>
<pre><code>b = torch.nn.BCELoss()
</code></pre>
<p>I find it very interesting, that both ways work for PyTorch's BCE Loss. However, if I try to do this with a custom function, I can ... | <p>Classes are first-class objects (no pun intended) in Python; you can treat them as values like any other value. <code>torch.nn.BCELoss</code> is just an expression that evaluates to a class reference. Classes are callable, so <code>torch.nn.BCELoss()</code> is a <em>call</em> to that class.</p>
<p>You could also hav... | python|function|pytorch | 0 |
8,945 | 68,517,398 | Excessive CPU RAM being used by Pytorch even inside .cuda() mode | <p>I am having issue with excessive CPU RAM usage with <a href="https://github.com/promach/gdas" rel="nofollow noreferrer">this coding</a> even inside <em>.cuda()</em> mode</p>
<p>Could anyone advise ?</p> | <p>Problem is now <a href="https://github.com/promach/gdas/commit/9f1e0d24e077d094ebe21f71b6a1d3b5227b8e8b" rel="nofollow noreferrer">solved using this github commit</a></p> | python|pytorch | -1 |
8,946 | 65,854,475 | Perceptron on multi-dimensional tensor | <p>I'm trying to use Perceptron to reduce a tensor of size: <code>[1, 24, 768]</code> to another tensor with size of <code>[1, 1, 768]</code>. The only way I could use was to first reshape the input tensor to <code>[1, 1, 24*768]</code> and then pass it through linear layers. I'm wondering if there's a more elegant way... | <p>If the broadcasting is what's bothering you, you could use a <a href="https://pytorch.org/docs/stable/generated/torch.nn.Flatten.html" rel="nofollow noreferrer"><code>nn.Flatten</code></a> to do it:</p>
<pre><code>>>> m = nn.Sequential(
... nn.Flatten(),
... nn.Linear(24*768, 768))
>>> x = t... | python|pytorch|perceptron | 0 |
8,947 | 65,653,192 | IndexError: index 2047 is out of bounds for axis 0 with size 1638 | <p>I want to train my dataset with training data and validation data.
Total data is <em>2048</em>, train data is <em>1638</em>, and validation data is <em>410</em> (20% of total).</p>
<p>Here are my codes</p>
<ol>
<li><p>loading data (org: total training data)</p>
<pre><code> org_x = train_csv.drop(['id', 'digit', 'let... | <p>At first glance, you are using incorrect shapes: <code>org_x = org_x.reshape(-1, 28, 28, 1)</code>. The channel axis you be the second one (unlike in <em>TensorFlow</em>), as <code>(batch_size, channels, height, width)</code>:</p>
<pre><code>org_x = org_x.reshape(-1, 1, 28, 28)
</code></pre>
<p>Same with <code>x_tes... | deep-learning|pytorch|conv-neural-network | 1 |
8,948 | 63,532,429 | Missing data after scraping | <p>I am trying to scrape Google data on the top 250 IMDB movie ratings.</p>
<pre><code>movie_list = top_250_imdb["Title"]
base_url = 'https://www.google.com/search?q='
streaming = []
title = []
price = []
for movie in movie_list:
query_url = (f'{base_url}{movie}')
browser.visit(query_url)
tim... | <p>I think the one of the values in price is NaN... Idk how to solve but you might get help with that...</p>
<p>Try to create a dataframe with price only... Then fill the NaN value using fillna function and then join that price dataframe with your main dataframe....</p>
<p>A bit long but might work</p> | python|pandas|web-scraping|beautifulsoup|splinter | 0 |
8,949 | 63,499,158 | How to remove marker from plot and make it smooth | <p>I have been trying to plot a smooth graph, and here is my code</p>
<pre><code>
import matplotlib.pyplot as plt
#fig,axes= plt.subplots(nrows=6, ncols=1, squeeze=False)
x = df["DOY"]
y = df["By"]
z = df["Bz"]
a = df["Vsw"]
b = df["Nsw"]
c = df["magnetopause_dis... | <p>Use:</p>
<pre><code>from scipy.interpolate import UnivariateSpline
import numpy as np
list_x_new = np.linspace(min(x), max(x), 1000)
list_y_smooth = UnivariateSpline(x, y, list_x_new)
plt.plot(list_x_new, list_y_smooth)
plt.show()
</code></pre>
<p>This is for one of the graphs, you can substitute the values in <c... | python|pandas|matplotlib|plot|linspace | 0 |
8,950 | 63,549,478 | Error loading tensorflow_datasets: error with Google cloud | <p>When loading tensorflow_dataset, I got following error:</p>
<pre><code>ds = tfds.load('mnist', split='train', shuffle_files=True)
---------------------------------------------------------------------------
FailedPreconditionError Traceback (most recent call last)
~/anaconda3/lib/python3.7/site-pack... | <p>'ln -s /etc/ssl/certs/ca-bundle.crt /etc/ssl/certs/ca-certificates.crt' resolved the issue.</p> | python|tensorflow | 1 |
8,951 | 63,680,146 | Pandas Dataframe from a nested dictionary with list as values | <p>I'm newer to python and pandas and I can't figure out a way to push this dict into a dataframe</p>
<pre><code>a_dict = {'position': [{'points': '57.95', 'name': 'Def'}, {'points': '121', 'name': 'PK'}, {'points': '383.1', 'name': 'RB'}, {'points': '299.96', 'name': 'QB'}, {'points': '177.8', 'name': 'TE'}, {'points'... | <p>I'm guessing you want the points and names as columns</p>
<pre><code>points = []
name = []
for dct in a_dict['position']:
points.append(dct['points'])
name.append(dct['name'])
pd.DataFrame({'points':points,'name':name})
</code></pre>
<p>With the output</p>
<pre><code> points name
0 57.95 Def
1 121 ... | pandas|dictionary | 0 |
8,952 | 63,548,669 | Can I combine values of two rows if labels are not identical in pandas | <p>Here's the 2 dataframes I want to combine. But the labels are different from each other</p>
<pre><code>df1
Date Campaign Sales
11/07/2020 AMZ CT BR Leather Shoes ABCDEFG1234 $10
11/07/2020 AMZ CT NB Leather Shoes ABCDEFG1234 $20
11/07/2020 AMZ OG BR Bag HGIJK567 ... | <p>I would create an extra column to perform the <code>merge</code> on. For what I can see, merging is done based on the product name without the first acronyms.</p>
<pre><code>df1['Campaign_j'] = df1['Campaign'].map(lambda x: ' '.join(x.split()[3:]))
df2['Campaign_j'] = df2['Campaign'].map(lambda x: ' '.join(x.split()... | python|pandas|dataframe | 1 |
8,953 | 63,392,997 | Split and replace special characters from column names in Pandas | <p>I have a dataframe which has column names like this:</p>
<pre><code>id, xxx>xxx>x, yy>y, zzzz>zzz>zz>z, ...
</code></pre>
<p>I need to split by the second <code>></code> from the right side, replace <code>></code> with <code>-</code>, and then take the last element as new column names, <code>... | <p>Using Regex.</p>
<p><strong>Ex:</strong></p>
<pre><code>import re
c = ['id', 'xxx>xxx>x', 'yy>y', 'zzzz>zzz>zz>z']
print([re.sub(r"(.*?)([A-Za-z]+)>([A-Za-z]+)$", r"\2-\3", i) for i in c])
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>['id', 'xxx-x', 'yy-y', 'zz-z... | python-3.x|pandas|dataframe|split | 1 |
8,954 | 63,452,674 | Binning Data in Python versus R? | <p>I'm trying to rewrite some R code into Python but I'm not getting the same output. I would be grateful if somebody could please point me in the right direction:</p>
<p>R Code:</p>
<pre><code>Data_2017_18$ageband3 <- cut(Data_2017_18$age,
breaks = c(0, 30, 50, Inf),
... | <p>If you don't how the maximum possible value of your data you can use <code>numpy.inf</code> or more commonly <code>np.inf</code> (if you <code>import numpy as np</code>)</p>
<p>Take the following data</p>
<pre><code>np.random.seed(123)
df = pd.DataFrame(np.random.randint(1, 110, 35000), columns=['age'])
>>>... | python|r|pandas | 1 |
8,955 | 63,548,409 | Run same script in different threads python | <p>i have a script that recognize plates from camera, and now i need the same script to recognize from other camera so in short it needs to recognize from two cameras at once ,i am using Tensoflow/keras and YOLO object detection , can someone suggest sollution to this , i tried with different threads but i could not s... | <p><code>target=</code> in <code>Thread</code> needs function's name without <code>()</code> and arguments - and it will later use <code>()</code> to start it.</p>
<p>Your current code doesn't run functions in threads but it works like</p>
<pre><code>result = start_vlez(cam_izlez)
result1 = start_izlez(cam_vlez)
t = t... | python|tensorflow|keras|yolo | 1 |
8,956 | 29,846,658 | Computing MAD(mean absolute deviation) GroupBy Pandas | <p>I have a dataframe:</p>
<pre><code>Type Name Cost
A X 545
B Y 789
C Z 477
D X 640
C X 435
B Z 335
A X 850
B Y 152
</code></pre>
<p>I have all such combinations in my dataframe with Type ['A','B','C','D'] and Names ['X','Y','Z'] . I used the groupby method to ... | <p>You can use <code>groupby</code> and <code>transform</code> to create new data series that can be used to filter out your data.</p>
<pre><code>groups = df.groupby(['Name','Type'])
mad = groups['Cost'].transform(lambda x: x.mad())
dif = groups['Cost'].transform(lambda x: np.abs(x - x.mean()))
df2 = df[dif <= 3*ma... | python|pandas|group-by|dataframe|aggregate | 4 |
8,957 | 29,877,226 | How to define colors for histogram in "groupby"? | <p>I need to define clients colors (2 colors for 'F' and 'M') for next sample:</p>
<pre><code>d = {'gender' : Series(['M', 'F', 'F', 'F', 'M']),'year' : Series([1900, 1910, 1920, 1920, 1920])}
df = DataFrame(d)
grouped = df.groupby('gender').year
grouped.plot(kind='hist',legend=True)
</code></pre> | <p>If you don't need groupby (I don't see that it gains you anything in this case), then you can easily set colors:</p>
<pre><code>ax1 = plt.subplot(111)
df[df['gender']=='M'].hist(ax=ax1, color='red', label='M')
df[df['gender']=='F'].hist(ax=ax1, color='blue', label='F')
ax1.legend(loc='best')
</code></pre> | python|pandas|colors|histogram | 1 |
8,958 | 53,742,201 | TensorFlow Hub caching model - permission denied when loading | <p>I am trying to save a TensorFlow Module to disk to avoid downloading it for every use.</p>
<p>I read about caching modules here: <a href="https://www.tensorflow.org/hub/basics" rel="nofollow noreferrer">https://www.tensorflow.org/hub/basics</a></p>
<pre><code>$ export TFHUB_CACHE_DIR=/tf_models
$ echo $TFHUB_CACHE... | <p>Solved by removing the <code>/</code> sign such as:</p>
<pre><code>export TFHUB_CACHE_DIR=tf_models
</code></pre> | tensorflow|anaconda | 0 |
8,959 | 53,718,842 | can't pickle _thread.RLock objects when running tune of ray packge for python (hyper parameter tuning) | <p>I am trying to do a hyper parameter tuning with the <a href="https://ray.readthedocs.io/en/latest/tune.html" rel="nofollow noreferrer">tune</a> package of Ray.</p>
<p>Shown below is my code:</p>
<pre><code># Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: dis... | <p>You will have to call <code>rnn_config = RNNconfig()</code> in <code>def train(config, reporter=None)</code> function. Most importantly, the <code>tf.Graph()</code> needs to be initialized within <code>train</code> because it is not easily pickleable. </p>
<p>Note that the rest of your code may also need to be adju... | python-3.x|tensorflow|deep-learning|hyperparameters|ray | 1 |
8,960 | 53,366,735 | Combine two numpy arrays into matrix with a two-argument function | <p>Roughly I want to convert this (non-numpy) for-loop:</p>
<pre><code>N = len(left)
M = len(right)
matrix = np.zeros(N, M)
for i in range(N):
for j in range(M):
matrix[i][j] = scipy.stats.binom.pmf(left[i], C, right[j])
</code></pre>
<p>It's sort of like a dot product but of course mathematically not a dot pro... | <p><strong><code>scipy.stats.binom.pmf</code></strong> already is vectorized. However, you have to <strong><code>broadcast</code></strong> your inputs in order to get your desired result.</p>
<pre><code>broadcast_out = scipy.stats.binom.pmf(left[:, None], C, right)
</code></pre>
<hr>
<p><strong><em>Validation</em><... | python|numpy|matrix|scipy | 3 |
8,961 | 53,680,932 | Pandas: Find the max value in one column containing lists | <p>I have a dataframe like this:</p>
<pre><code>fly_frame:
day plcae
0 [1,2,3,4,5] A
1 [1,2,3,4] B
2 [1,2] C
3 [1,2,3,4] D
</code></pre>
<p>If I want to find the max value in each entry in the day column.</p>
<p>For example:</p>
<pre><code>fly_frame:
day ... | <pre><code>df.day.apply(max)
#0 5
#1 4
#2 2
#3 4
</code></pre> | python|pandas|dataframe | 10 |
8,962 | 53,594,769 | Applying a function to an array using Numpy when the function contains a condition | <p>I am having a difficulty with applying a function to an array when the function contains a condition. I have an inefficient workaround and am looking for an efficient (fast) approach. In a simple example:</p>
<pre><code>pts = np.linspace(0,1,11)
def fun(x, y):
if x > y:
return 0
else:
ret... | <p>The error is quite explicit - suppose you have</p>
<pre><code>x = np.array([1,2])
y = np.array([2,1])
</code></pre>
<p>such that </p>
<pre><code>(x>y) == np.array([0,1])
</code></pre>
<p>what should be the result of your <code>if np.array([0,1])</code> statement? is it true or false? <code>numpy</code> is tel... | python|numpy|lambda|conditional|vectorization | 1 |
8,963 | 53,527,688 | Tabular formatting for JSON file | <p>I have a JSON which is making requests from <a href="http://api.worldweatheronline.com/" rel="nofollow noreferrer">http://api.worldweatheronline.com/</a> via their useful API.</p>
<p>I am struggling to convert the JSON into a tabular format such as a pandas data frame. I think the issue is due to the nested structu... | <p>I saved your JSON to a file ('test.json', in wich, by the way, the apostrophes need to be swapped with inverted commas, so that the <code>json</code> module can parse it) and read it with the <code>json</code> module. You want to end up with a pandas DataFrame and we will need defaultdicts for making the flattening ... | python|json|pandas | 1 |
8,964 | 17,556,913 | Python buggy histogram? | <p>I have a strange behavior with this very simple code</p>
<pre><code>import numpy as np
[y, binEdges] = np.histogram(x, xout)
</code></pre>
<p>where x and xout are numpy arrays (xout describes the edges of the bins that are equally spaced).</p>
<p>If I do</p>
<pre><code>np.sum(y)
</code></pre>
<p>the value is no... | <p>Try this:</p>
<pre><code>y.sum() + (x < xout[0]).sum() + (x > xout[-1]).sum()
</code></pre> | python|numpy|histogram | 1 |
8,965 | 17,315,881 | How can I check if a Pandas dataframe's index is sorted | <p>I have a vanilla pandas dataframe with an index. I need to check if the index is sorted. Preferably without sorting it again.</p>
<p>e.g. I can test an index to see if it is unique by index.is_unique() is there a similar way for testing sorted?</p> | <p>How about:</p>
<p><code>df.index.is_monotonic</code></p> | python|pandas | 86 |
8,966 | 20,115,680 | Dict not hashable python | <p>I looked online and cant seem to understand much of it. im new to python and was wondering how i can fix this. </p>
<p>when running:</p>
<pre><code>results = getRecommendations(userCompare[0], userCompare[0]['1'], sim_distance)
</code></pre>
<p>i get error:</p>
<pre><code> TypeError ... | <p>You can't use a <code>dict</code> as a dictionary key. What would happen if I did:</p>
<pre><code>d = {}
k1 = {1: 2}
k2 = {2: 1}
d[k1] = "a"
d[k2] = "b"
k1[2] = 1
k2[1] = 2
</code></pre>
<p>I now have <code>k2 == k1</code>, so what does <code>d[{1:2, 2:1}]</code> do? Well, that's why you can't use a <code>dict</... | python|dictionary|hash|numpy | 1 |
8,967 | 12,374,781 | How to find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay? | <p>I have been searching for an answer to this question but cannot find anything useful.</p>
<p>I am working with the python scientific computing stack (scipy,numpy,matplotlib) and I have a set of 2 dimensional points, for which I compute the Delaunay traingulation (<a href="https://en.wikipedia.org/wiki/Delaunay_tria... | <p>I figured it out on my own, so here's an explanation for anyone future person who is confused by this.</p>
<p>As an example, let's use the simple lattice of points that I was working with in my code, which I generate as follows</p>
<pre><code>import numpy as np
import itertools as it
from matplotlib import pyplot ... | python|numpy|scipy|triangulation|delaunay | 18 |
8,968 | 12,418,234 | logarithmically spaced integers | <p>Say I have a 10,000 pt vector that I want to take a slice of only 100 logarithmically spaced points. I want a function to give me integer values for the indices. Here's a simple solution that is simply using around + logspace, then getting rid of duplicates. </p>
<pre><code>def genLogSpace( array_size, num ):
l... | <p>This is a bit tricky. You can't always get logarithmically spaced numbers. As in your example, first part is rather linear. If you are OK with that, I have a solution. But for the solution, you should understand why you have duplicates.</p>
<p>Logarithmic scale satisfies the condition:</p>
<pre><code>s[n+1]/s[n] =... | python|numpy|resampling | 19 |
8,969 | 72,058,273 | How to install mediapipe with miniforge3? | <p>I am on a new Mac M1 trying to install mediapipe and TensorFlow on the same Conda env. Installing both libraries on M1 appear to have a lot of issues. I was finally able to get TensorFlow to install using this tutorial:</p>
<p><a href="https://betterprogramming.pub/installing-tensorflow-on-apple-m1-with-new-metal-pl... | <p>My solution was also to create a conda environment with Python 3.7 and x86_64 architecture. Python 3.7 is required for Mediapipe to work with TensorFlow (<a href="https://google.github.io/mediapipe/getting_started/install.html" rel="nofollow noreferrer">https://google.github.io/mediapipe/getting_started/install.html... | python|tensorflow|opencv|conda|mediapipe | 0 |
8,970 | 72,123,992 | panda df not showing all rows after loading from MS SQL | <p>I'm using <em>Pandas</em> with latest <em>sqlalchemy</em> (<code>1.4.36</code>) to query a MS SQL DB, using the following Python <code>3.10.3</code> [Win] snippet:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd #
from sqlalchemy import create_engi... | <p>To display all the rows in pandas, you should set the display option to None or 1 extra from the dataframe size as you have done in your code:</p>
<pre><code>pd.set_option('display.max_rows', None)
pandas.set_option('display.max_rows', z.shape[0]+1)
</code></pre>
<p>Given that this is not the problem, it may be that... | python|sql-server|pandas|dataframe|sqlalchemy | 1 |
8,971 | 16,960,068 | Populate predefined numpy array with arrays as columns | <p>Something I can't figure out by reading the Python documentation and stackoverflow. Probably I'm thinking in the wrong direction..</p>
<p>Let's say I've a predefined 2D Numpy array as follow:</p>
<pre><code>a = np.zeros(shape=(3,2))
print a
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
</code></pre>
... | <p>You can assign to columns with slicing:</p>
<pre><code>>>> a[:,0] = b
>>> a
array([[ 1., 0.],
[ 2., 0.],
[ 3., 0.]])
</code></pre>
<p>To assign them all at once instead of one at a time, use <code>np.column_stack</code>:</p>
<pre><code>>>> np.column_stack((b, c))
array(... | python|arrays|numpy|populate | 1 |
8,972 | 17,871,031 | Modifying 3D array in Python | <p>I am trying to perform operations on specific elements within a 3d array in python. Here is an example of the array:</p>
<pre><code>[[[ 0.5 0.5 50. ]
[ 50.5 50.5 100. ]
[ 0.5 100.5 50. ]
[ 135. 90. 45. ]]
[[ 50.5 50.5 ... | <p>You can make your <code>VectMath.rotate_x</code> function to rotate an array of vector, then by using slice to get & put data in <code>a</code>:</p>
<pre><code>a = np.array(
[[[ 0.5, 0.5, 50., ],
[ 50.5, 50.5, 100., ],
[ 0.5, 100.5, 50., ],
[ 135. ... | python|arrays|list|numpy | 1 |
8,973 | 17,777,482 | How to remove every other element of an array in python? (The inverse of np.repeat()?) | <p>If I have an array x, and do an <code>np.repeat(x,2)</code>, I'm practically duplicating the array.</p>
<pre><code>>>> x = np.array([1,2,3,4])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
</code></pre>
<p>How can I do the opposite so that I end up with the original array?</p>
<p>It sh... | <p><code>y[1::2]</code> should do the job. Here the second element is chosen by indexing with 1, and then taken at an interval of 2. </p> | python|arrays|numpy | 55 |
8,974 | 8,407,749 | removing baseline signal using fourier transforms | <p>I have timeseries data for many terms an example of which is below:</p>
<pre><code>term1 = [0.0, 0.0, 0.0, 0.0, 2.2384935833581433e-06, 3.938767914008819e-06, 0.0, 0.0, 1.1961851263949013e-06, 0.0, 2.278384397623645e-06, 1.100158422812885e-06, 0.0, 1.095521835393462e-06, 0.0, 0.0, 1.6933152148605343e-06, 0.0, 8.460... | <p>Multiplying (or dividing) in the frequency domain is equivalent to convolving in the time domain. In other words a high-pass FIR filter would remove your low-frequency components directly without going into the frequency domain. If you <em>do</em> go to the frequency domain first be aware that simply removing some... | numpy|signal-processing|fft | 2 |
8,975 | 55,550,421 | Saving each dataframe from a list to separate csv files | <p>Im trying to save each element from a list to each separate csv files. each element is a dataframe.</p>
<p>I used the following codes, however, the problem is that the files that it saves are only from the first or last element of the list from the two following codes respectively. e.g. the output files are all ide... | <p>IIUC, i think you need:</p>
<pre><code>for a, x in enumerate(allcity):
x.to_csv('msd{}.csv'.format(a))
</code></pre> | python|pandas|export-to-csv | 2 |
8,976 | 55,522,976 | how can select data of coefficient of 3 columns from csv file | <p>I would like to plot amount of columns for 2 different scenario based on <strong>index of rows</strong> in my dataset preferably via <code>Pandas.DataFrame</code> : </p>
<p><strong>1st scenario:</strong> columns index[2,5,8,..., n+2]</p>
<p><strong>2nd scenario:</strong> the last 480 columns or column index [961-1... | <p>1st scenario:</p>
<pre><code>df.iloc[:, 2::3]
</code></pre>
<p>The slicing here means all rows, columns starting from the 2nd, and every 3 after that.</p>
<p>2nd scenario:</p>
<pre><code>df.iloc[:, :961:-1]
</code></pre>
<p>The slicing here means all rows, columns to 961 from the end of the list.</p>
<p>EDIT:<... | python|pandas|csv|dataframe|indexing | 2 |
8,977 | 55,229,848 | Apache BEAM pipeline fails when writing TF Records - AttributeError: 'str' object has no attribute 'iteritems' | <p>The issue started appearing over the weekend. For some reason, it feels to be a DataFlow issue. </p>
<p>Previously, I was able to execute the script and write TF records just fine. However, now, I am unable to initialize the computation graph to process the data.</p>
<p>The traceback is:</p>
<pre><code>Traceback ... | <p>I was experiencing the same error. </p>
<p>It seems to be triggered by a mismatch in the <code>tensorflow-transform</code> versions of your local (or master) machine and the workers one (specified in the setup.py file). </p>
<p>In my case I was running <code>tensorflow-transform==0.13</code> on my local machine wh... | tensorflow|apache-beam|tensorflow-transform | 0 |
8,978 | 55,348,786 | How can I change the values in a dataframe column based off the index of a list? | <p>lets say I have a data frame:</p>
<pre><code>x y
1 3
2 0
4 1
7 2
</code></pre>
<p>and I have a list:</p>
<pre><code>[1,2,7,5]
</code></pre>
<p>can I change the values of the Y column based on the value of the index of the list?</p>
<p>for instance, for value 2 of the y column its 0. is ... | <p>Just do with </p>
<pre><code>df.y=np.array(l)[df.y-1]# here i subtract 1 since the index from pandas or numpy is from 0 by default
df
Out[52]:
x y
0 1 7
1 2 5
2 4 1
3 7 2
</code></pre> | python|pandas|numpy | 1 |
8,979 | 55,274,076 | PyTorch - GPU is not used by tensors despite CUDA support is detected | <p>As the title of the question clearly describes, even though t<code>orch.cuda.is_available()</code> returns <code>True</code>, <code>CPU</code> is used instead of <code>GPU</code> by tensors. I have set the <code>device</code> of the tensor to <code>GPU</code> through the <code>images.to(device)</code> function call ... | <p><code>tensor.to()</code> does not modify the tensor inplace. It returns a new tensor that's stored
in the specified device.</p>
<p>Use the following instead.</p>
<pre class="lang-py prettyprint-override"><code> images = images.to(device)
labels = labels.to(device)
</code></pre> | python|python-3.x|pytorch|torch | 3 |
8,980 | 9,857,340 | Adding a colorbar and a line to multiple imshow() plots | <p>I have this source code:</p>
<pre><code>idx=0
b=plt.psd(dOD[:,idx],Fs=self.fs,NFFT=512)
B=np.zeros((2*len(self.Chan),len(b[0])))
B[idx,:]=20*log10(b[0])
c=plt.psd(dOD_filt[:,idx],Fs=self.fs,NFFT=512)
C=np.zeros((2*len(self.Chan),len(b[0])))
C[idx,:]=20*log10(c[0])
for idx in range(2*len(self.Chan)):
b=plt.psd... | <p>Your ticks variable appears to be all zeros:</p>
<pre><code>ticks=np.zeros((ii))
</code></pre>
<p>but it should enumerate X locations (in axis coordinates) where you'd like the tick marks to go. When you call set_xticklabels, the list gives the text to show for each tick.</p>
<p>Here's a simple example showing h... | python|numpy|matplotlib|scipy | 2 |
8,981 | 67,024,157 | Slicing pandas multiindex dataframe using max of second level | <p>Supposing that I have this MultiIndex dataframe called <code>df</code>:</p>
<pre><code> | |Value
Year |Month|
1992 | 1 | 3
| 2 | 5
| 3 | 8
-----------------
1993 | 1 | 2
| 2 | 7
----------------
1994 | 1 | 20
| 2 | 50
| 3 | 10
| 4 | 5
</code></pre>
<... | <p>you can group on the first level and take the last of the second level and then <code>df.loc[]</code>:</p>
<pre><code>df.loc[pd.DataFrame.from_records(df.index).groupby(0)[1].last().items()]
</code></pre>
<hr />
<pre><code> Value
Year Month
1992 3 8
1993 2 7
1994 4 5
</c... | python|pandas|multi-index | 2 |
8,982 | 47,297,585 | Building a Transition Matrix using words in Python/Numpy | <p>Im trying to build a 3x3 transition matrix with this data</p>
<pre><code>days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
'sun', 'clouds', 'clouds', ... | <p>If you don't mind using <code>pandas</code>, there's a one-liner for extracting the transition probabilities:</p>
<pre><code>pd.crosstab(pd.Series(days[1:],name='Tomorrow'),
pd.Series(days[:-1],name='Today'),normalize=1)
</code></pre>
<p>Output:</p>
<pre><code>Today clouds rain sun
Tom... | python|numpy|markov-chains | 20 |
8,983 | 68,358,751 | ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory* | I have cuda9.0 in my system and not cuda 8 | <p>I have cuda9.0 and tensorflow-gpu==1.5, while running a script I am getting below error.</p>
<pre><code> Traceback (most recent call last):
File "test.py", line 13, in <module>
from lib.networks.factory import get_network
File "/faster_rcnn/../lib/__init__.py", line 1, ... | <p>Particular version of Tensorflow is tested and configured with specific version of CUDA and cuDNN. In this case, Tensorflow version is demanding CUDA 8.0. Please take a look at the screenshot below for tested and build configuration.
<a href="https://i.stack.imgur.com/1QpjQ.png" rel="nofollow noreferrer"><img src="h... | python|tensorflow | 0 |
8,984 | 59,403,256 | Pandas not working: DataFrameGroupBy ; PanelGroupBy | <p>I have just upgraded python and I cannot get pandas to run properly, please see below. Nothing appears to work.</p>
<blockquote>
<p>Traceback (most recent call last): File
"/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tqdm/_tqdm.py",
line 613, in pandas
from pandas.cor... | <p>I guess you are using an older version of tqdm. Try using a version above tqdm>=4.23.4. </p>
<p>The command using pip would be,</p>
<p><code>pip install tqdm --upgrade</code> </p> | python-3.x|pandas | 3 |
8,985 | 59,277,637 | Installing TensorFlow with pipenv gives error | <p>I'm trying to install <strong>TensorFlow</strong> using <strong>pipenv</strong>.</p>
<p>This is my Pipfile:</p>
<pre><code>[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
pylint = "*"
[packages]
python-telegram-bot = "*"
imdbpy = "*"
matplotlib = "*"
scikit-image = "*"
s... | <p>As the comments pointed out, Tensorflow only supports up to python 3.7 (as March 2020). You can find more info in the <a href="https://www.tensorflow.org/install/pip#system-requirements" rel="nofollow noreferrer">system requirements page</a> of the documentation.</p>
<p>So, to fix your issue:</p>
<ol>
<li>Remove t... | python|tensorflow|pipenv | 4 |
8,986 | 59,243,087 | How to solve python import another python file but the its imports missing | <p>I want to import a python file called feature.py and call the functions in it, so I did the 'from feature import *'.</p>
<pre><code>from feature import *
</code></pre>
<p>In the feature.py, I import pandas as pd and define the functions that I would like to call in the main python file. </p>
<pre><code>import pan... | <p>When you import code from another file in the form “import filename” then it doesn’t do the same thing as when you extract functions/classes from a file in the form “from filename import *”.</p>
<p>The code you’ve shown appears to be taking the functions from the file you’re importing without actually running the i... | python|pandas|dataframe | 0 |
8,987 | 59,307,463 | Python Business Days within loop | <p>I am trying to loop through a dataframe, the dataframe has two columns, both with datetime variables inside. I am trying to loop through this data base and produce a new column with the count of business days between the two dates.I have tried using np.busdays_count < this returned errors like the following.</p>
... | <p>For np.busday_count to work both dates need to be cast in the 'M8[D]' format. </p>
<pre><code>import datetime
import pandas as pd
import numpy as np
# Create a toy data frame
dates_1 = pd.date_range(datetime.datetime(2018, 4, 5, 0,
0), datetime.datetime(2018, 4, 20, 7, 0),freq='D')
dates_2 ... | python|pandas|datetime|weekend | 3 |
8,988 | 13,857,769 | Better way to compare neighboring cells in matrix | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/13805286/numpy-python-array-iteration-without-for-loop">Numpy/Python: Array iteration without for-loop</a> </p>
</blockquote>
<p>Suppose I have a matrix of size 100x100 and I would like to compare each pixel to... | <p>I'm not 100% sure what you're aiming for with your code, which ignoring indexing issues at boundaries is equivalent to</p>
<pre><code>new_matrix = my_matrix > 0.5
</code></pre>
<p>but you can do advanced versions of these calculation quickly with morphological operations:</p>
<pre><code>import numpy as np
from... | python|matlab|matrix|numpy|scipy | 2 |
8,989 | 45,091,991 | How can I load a data frame saved in pandas as an HDF5 file in R without losing integers larger than 32 bit? | <p>I'm getting this warning message when I try to load data frame saved in pandas as an HDF5 file in R:</p>
<blockquote>
<p>Warning message: In H5Dread(h5dataset = h5dataset, h5spaceFile =
h5spaceFile, h5spaceMem = h5spaceMem, : NAs produced by integer
overflow while converting 64-bit integer or unsigned 32-b... | <p><a href="https://rdrr.io/github/Bioconductor-mirror/rhdf5/man/H5D.html" rel="nofollow noreferrer">HDF5 Dataset Interface's documentation</a> says:</p>
<blockquote>
<p>bit64conversion: Defines, how 64-bit integers are converted. Internally, R does not support 64-bit integers. All integers in R are 32-bit integers.... | python|r|pandas|dataframe|hdfs | 1 |
8,990 | 44,889,508 | If correlation is greater than 0.75 remove the column from dataframe of pandas | <p>I have a dataframe name <code>data</code> for which I plotted correlation matrix by using</p>
<pre><code>corr = data.corr()
</code></pre>
<p>I want if <code>corr</code> between two column is greater than 0.75, remove one of them from dataframe <code>data</code>. I tried some option </p>
<pre><code>raw =corr[(corr... | <p>Use <code>np.eye</code> to ignore the diagonal values and find all columns that have some value whose absolute value is greater than the threshold. Use the logical negation as a mask for the index and columns.</p>
<hr>
<p><strong>Your example</strong> </p>
<pre><code>m = ~(corr.mask(np.eye(len(corr), dtype=bool... | python|r|pandas|machine-learning|scikit-learn | 13 |
8,991 | 45,202,659 | ignore NaN in .diff() with Pandas | <p>I need to compute differences between elements along axis=1 for each row ignoring the missing values (NaN). For example:</p>
<pre><code> 0 1 2 3 4 5
20 NaN 7.0 5.0 NaN NaN 8.0
21 7.0 5.0 NaN NaN 8.0 NaN
22 5.0 NaN NaN 8.0 NaN 7.0
23 NaN NaN 8.0 N... | <p>I assume that you already know how to compute differences when all the values are filled in. Use that process, but modify the comparison step. Whatever you use to compare existing values, include a filter to accept only <code>item</code>s for which <code>item == item</code>.</p>
<p>By definition, <code>Nan</code>... | python|pandas|diff|nan | 2 |
8,992 | 57,293,542 | Pre-defined point colours in seaboarn scatter plot | <p>I am doing scatterplots with seaborn and I want the points to have 'pre-defined' colours. I am looping though my dataframe and when I set <code>hue=df['category']</code>it uses the default palette. This is fine but I would like the categories to carry the same colour through each plot i.e if one category is not bein... | <p>You can try:</p>
<pre><code>category_colour = {'Netflix':'Blue', 'TV':'Red', 'DVD':'Yellow', 'Radio':'Pink'}
plot = sns.scatterplot(x="Popularity",
y="Likelihood",
hue=df['category'].map(category_colour),
data=df)
</code></pre>
<p>but make su... | python|pandas|matplotlib|seaborn | 1 |
8,993 | 57,122,015 | How to read column of Nan from csvfile into python so data can be used? | <p>I am trying to read in columns of data from a csvfile, then use it to do some calculations. The problem is that my timestamps are in hexadecimal. I need to read them in and convert to decimal, but I don't know how to get it into python as anything but Nan. </p>
<p>I have tried making it a string first.</p>
<pre><c... | <p>Thank you for the example data. I post here, not because I am sure, I found the solution, but because I couldn't show the output in a comment. But I have a suggestion, which might help.</p>
<p>When I read your csv data as you show it in your post, I get the following output:</p>
<pre><code> sensor x y ... | python|pandas|csv|hex|nan | 0 |
8,994 | 45,873,063 | Pandas DataFrame from list/dict/list | <p>I have some data in this form:</p>
<pre><code>a = [{'table': 'a', 'field':['apple', 'pear']},
{'table': 'b', 'field':['grape', 'berry']}]
</code></pre>
<p>I want to create a dataframe that looks like this:</p>
<pre><code> field table
0 apple a
1 pear a
2 grape b
3 berry b
</code>... | <p>You can use a list comprehension to concatenate a series of dataframes, one for each dictionary in <code>a</code>. </p>
<pre><code>>>> pd.concat([pd.DataFrame({'table': d['table'], # Per @piRSquared for simplification.
'field': d['field']})
for d in a]).reset_i... | python|pandas | 4 |
8,995 | 45,947,505 | Is there a method to perform a derivative by inbuilt function in python 3.5? | <p>I don't want to use numpy because it isn't permitted in competitive programming.I want to take derivative of for instance m=a(a**2-24a).<br/>
Now,a=0 and a=8 are critical points. I want to find this value.Is it possible by using any python library function excluding numpy.</p> | <p><code>m=a(a**2-24a)</code> does not make sense as a Python expression, regardless of what <code>a</code> is. The first <code>a(</code> implies a function; <code>a**</code> implies a number, and <code>24a</code> is I-don't-know-what. </p>
<p>Derivative is a mathematical concept that's implemented in <code>sympy</c... | python-3.x|numpy|python-3.5|standard-library | 0 |
8,996 | 45,925,034 | Add a new column to a CSV file using python | <p>I have a <code>CSV</code> file that has the following headers :</p>
<pre><code>model ,years ,engine ,power_kW,power_hp,torque_Nm,torque_ft-lb,0-100 km/h
</code></pre>
<p>and I want to write the following list :</p>
<pre><code>power_hp = [113.99, 120.69, 127.4, 134.1, 140.81, 147.51, 154.22, 167.63, 170.31, 174.33... | <p>Using <code>pandas</code>, load in your dataframe using <code>pd.read_csv</code>, add the new column, and write to the same file using <code>df.to_csv</code>.</p>
<pre><code>import pandas as pd
power_hp = [113.99, 120.69, 127.4, 134.1, 140.81, 147.51, 154.22, 167.63, 170.31, 174.33, 199.81, 214.56, 214.56, 230.66,... | python|python-3.x|pandas|csv | 0 |
8,997 | 45,735,230 | How to replace a list of values in a numpy array? | <p>I have an unsorted array of numbers. </p>
<p>I need to replace certain numbers (given in a list) with specific alternatives (also given in a corresponding list) </p>
<p>I wrote the following code (which seems to works): </p>
<pre><code>import numpy as np
numbers = np.arange(0,40)
np.random.shuffle(numbers)
probl... | <p>EDIT: I implemented a TensorFlow version of this in <a href="https://stackoverflow.com/a/56805806/1782792">this answer</a> (almost exactly the same, except replacements are a dict).</p>
<hr>
<p>Here is a simple way to do it:</p>
<pre><code>import numpy as np
numbers = np.arange(0,40)
np.random.shuffle(numbers)
p... | python|arrays|performance|numpy | 4 |
8,998 | 23,012,455 | in Python trying to use cv2.matchShapes() from OpenCV | <p>I have done a random drawing on a whiteboard and NAO robot has taken a picture and tried to re-create the same drawing.</p>
<p>My drawing:</p>
<p><img src="https://i.stack.imgur.com/TFs44.jpg" alt="enter image description here" /></p>
<p>NAO's drawing:</p>
<p><img src="https://i.stack.imgur.com/Hm4Xd.jpg" alt="enter... | <p>I faced a similar problem. The match shapes function takes a single contour pair, not the whole contour container pair.</p>
<pre><code>cv2.matchShapes(drawnContours[i], originalContours[i], cv2.cv.CV_CONTOURS_MATCH_I1, 0.0)
</code></pre>
<p>Hope that helps.</p> | python|opencv|numpy | 4 |
8,999 | 23,314,500 | Best way to iterate through a numpy array returning the columns as 2d arrays | <p>EDIT: Thank you all for the good solutions, I think if I'd had to pick one, it would be <code>A[:,[0]]</code></p>
<p>I collected 7 approaches now and put them into an <a href="http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/benchmarks/timeit_tests.ipynb?create=1#row_vectors" rel="nofollow">IPy... | <p>My favorite solution is the slicing. You have different solutions :</p>
<pre><code>A[:,0:1] # not so clear
A[:,:1] # black magic
A[:,[0]] # clearest syntax imho
</code></pre>
<p>Concerning the <code>reshape</code> solution, you can enhance the syntax like this :</p>
<pre><code>A[:,0].reshape(A.shape[1],1)
A[:,0]... | python|numpy|matrix | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.