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 |
|---|---|---|---|---|---|---|
362,000 | 63,633,939 | Pandas Dataframe add values interating over columns with jumping values ahead | <p>I have a list called <code>_splitScenario</code>. I am trying to get the values of this list into a nice data frame. I have a data frame called <code>SummitVaRProd</code> . This dataframes has 545 columns. 45 trade attributes and then 500 scenario dates. I want to add scenario values from the list to scenario dates ... | <p>I can use <code>SummitVaRProd.iloc[j][j+46]</code></p> | python-3.x|pandas|dataframe|for-loop | 0 |
362,001 | 63,357,758 | Recurrent loss in tensorflow without executing eagerly | <p>I have the following very simple example for a loss (that probably doesnt make sense)</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
class Loss:
def __init__(self):
self.last_output = tf.constant([0.5,0.5])
def recurrent_loss(self, model_output):
now = 0.9*self.last_output ... | <p>in graph mode you have to use tf.Variable that is only created the first time the function is executed e.g :</p>
<pre><code>class Loss:
def __init__(self):
self.last_output = None
@tf.function
def recurrent_loss(self, model_output):
if self.last_output is None:
self.last_output = tf.V... | python|tensorflow|recurrent-neural-network | 1 |
362,002 | 63,424,687 | How to get difference of two pandas indices, but only those of the first index? | <p>I got two indices, <code>Ix1</code> and <code>Ix2</code>.<br />
I need the ones from <code>Ix1</code>, that are not in <code>Ix2</code>.</p>
<p>I only know</p>
<pre><code>Ix1.difference(Ix2).intersection(Ix1)
</code></pre>
<p>But it doesn't work. I still get indices from <code>Ix2</code>, which aren't in <code>Ix1</... | <p>Use first part only:</p>
<pre><code>Ix1 = pd.Index([1,2,3,6,7])
Ix2 = pd.Index([0,1,2,4,5])
print (Ix1.difference(Ix2))
Int64Index([3, 6, 7], dtype='int64')
</code></pre> | python|pandas|datetime|indexing|time | 1 |
362,003 | 63,379,298 | Comparing values in a panda dataframe and returning new value | <p>I have a panda dataframe like this:</p>
<pre><code> date id tier
0 2020-06-02 23 3
1 2020-06-02 23 2
2 2020-06-02 23 1
3 2020-06-02 7 3
23026 2020-06-20 7 3
41740 2020-07-07 9 3
</code></pre>
<p>I want to make a new column f... | <p>Use <code>numpy.select</code>:</p>
<pre><code>import numpy as np
conditions=[df['tier'].shift().fillna(df['tier']).eq(df['tier']),
df['tier'].shift().fillna(df['tier']).gt(df['tier'])]
choices=[0,1]
df['move']=np.select(conditions, choices, default=-1)
</code></pre>
<p>Output:</p>
<pre><code>df
... | python|pandas | 2 |
362,004 | 63,326,215 | How does the TensorFlow dataset handle large data that cannot fit into the memory in a server? | <h1>Question</h1>
<p>How does the TensorFlow dataset handle large data that cannot fit into the memory in a server?</p>
<p>Spark RDD can handle large large data with multiple nodes. For the question in <a href="https://stackoverflow.com/questions/56879198/tensorflow-transform-how-to-find-the-mean-of-a-variable-over-the... | <p>You need to use generator functions that pull in chunked data. Each chunk that took want to send is through a **yield ** operation. Tensorflow allows one to create a <code>Dataset</code> that returns Tensors as input yielded by a generator function. This dataset is finally viewed by the .fit methods as follows:</p>
... | tensorflow | 1 |
362,005 | 63,384,321 | How to get pandas series Value counts with a series in original index order after value preference | <p>Below I present Example:</p>
<pre><code>a = ['Ibrutinib', 'Ibrutinib', 'Ibrutinib',
'Ibrutinib-containing product', 'Ibrutinib 140 MG',
'Ibrutinib Oral Product',
'Ibrutinib-containing product in oral dose form', 'Ibrutinib Pill',
'Ibrutinib Oral Capsule', 'Ibrutinib 140 MG Oral Capsule',
... | <p>To sort by the original list, convert it to a dataframe, then create a rank column to sort by.</p>
<pre><code>import pandas as pd
a = ['Ibrutinib', 'Ibrutinib', 'Ibrutinib',
'Ibrutinib-containing product', 'Ibrutinib 140 MG',
'Ibrutinib Oral Product',
'Ibrutinib-containing product in oral dose ... | python|pandas | 1 |
362,006 | 63,575,102 | Generate dataframe based on specific condition and input dictionary - pandas | <p>I have a dictionary as shown below.</p>
<pre><code>d1 = { 'start_date' : '2020-10-01T20:00:00.000Z',
'end_date' : '2020-10-05T20:00:00.000Z',
'n_days' : 6,
'type' : 'linear',
"coef": [0.1,0.1,0.1,0.1,0.1,0.1]
}
</code></pre>
<p>From the above dictionary as inpu... | <p>Using timedelta and generating a list of lists can help here:</p>
<pre><code>from datetime import timedelta
d1 = { 'start_date' : '2020-10-01T20:00:00.000Z',
'end_date' : '2020-10-05T20:00:00.000Z',
'n_days' : 6,
'type' : 'linear',
"coef":[0.1,0.1,0.1,0.1,0.1,0.1]
... | python-3.x|pandas|dataframe|dictionary | 1 |
362,007 | 63,325,561 | Create new column in df1 by mapping the same column in df2 and apply specific calculation in pandas | <p>I have two dfs as shown below.</p>
<p>df1:</p>
<pre><code> Date t_factor plan plan_score
0 2020-02-01 5 NaN 0
1 2020-02-02 23 NaN 0
2 2020-02-03 14 start 0
3 2020-02-04 23 start 0
4 2020-02-05 ... | <p>Use <code>merge.asof</code> on the dates, then get score by <code>groupby</code> and <code>count</code>, finally do a <code>cumsum</code>:</p>
<pre><code>df["Date"] = pd.to_datetime(df["Date"])
df2["From"] = pd.to_datetime(df2["From"])
new = pd.merge_asof(df, df2[["From&... | python-3.x|pandas|dataframe | 1 |
362,008 | 63,568,412 | RNN on Colab TPU runs at the same speed as local CPU version | <p>I implemented a local version of an RNN and a Colab TPU version of an RNN(code-below). When I execute the Colab TPU version(code-below), the training speed is very slow like my local version running on my laptop's CPU.</p>
<p>Does Colab TPU support RNN networks?</p>
<p>Am I missing something here?</p>
<pre><code>imp... | <p>ctrl-f on <a href="https://cloud.google.com/tpu/docs/faq" rel="nofollow noreferrer">this page</a> for RNN. It seems like it should work if you can make the RNN static enough.</p>
<p>In general, dynamic operations don't work well with TPUs since it needs to recompile the model graph for each new training example.</p> | google-colaboratory|tensorflow2.0|recurrent-neural-network|google-cloud-tpu | 1 |
362,009 | 63,669,539 | How to filter a pandas dataframe using the result of pandas query of another dataframe | <p>I have a <code>pandas</code> df:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col_a' : ['a','a', 'b'], 'col_b': [1,2,3]})
df.index = [4,5,6]
</code></pre>
<p>On this <code>df</code> i apply a query:</p>
<pre><code>df_subset = df.query('col_a == "b"')
</code></pre>
<p>Now I have a second dataframe... | <p>If there are same index values use:</p>
<pre><code>print (df_numpy[df_numpy.index.isin(df_subset.index)])
0
2 0.3
</code></pre>
<p>EDIT: One idea is create same index values in both, because same length:</p>
<pre><code>df = pd.DataFrame({'col_a' : ['a','a', 'b'], 'col_b': [1,2,3]})
df.index = [4,5,6]
df_s... | python|python-3.x|pandas|dataframe | 2 |
362,010 | 63,627,969 | Using Groupby and remove groups that contain certain characteristics | <p>I have the following DataFrame</p>
<pre><code>import pandas as pd, numpy as np
df = pd.DataFrame({'Instrument':['AAA','BBB','BBB','BBB','BBB','BBB','CCC','CCC'],
'Date':['2020-01-02','2020-01-02','2020-01-02','2020-01-02','2020-01-02','2020-01-02','2020-01-03','2020-01-03'],
'Time':['00:00:00.000','00:00:00.000','0... | <ul>
<li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.filter.html" rel="nofollow noreferrer"><code>.filter</code></a> for groups where the minimum <code>Time</code> is not <code>'00:00:00.000'</code>
<ul>
<li>This answer assumes <code>Time</code> is <code>str<... | python|pandas|dataframe | 1 |
362,011 | 63,569,924 | How to move values into new columns based on values in another column | <p>I have a data set of patient observations (Obs) (e.g Blood pressure, Heart rate, Resp Rate etc (this is isn't exhaustive and can change to I would need to generate this list by pulling unique values from the Obs column).</p>
<p>Currently each row of data represents a value that corresponds to a time point that the r... | <p>We can do:</p>
<pre><code>#only if index is a columns
#df = df.set_index('Index')
</code></pre>
<hr />
<pre><code>new_df = df.pivot_table(index=['VisitID', 'Obs_DTM'],
columns='Obs',
aggfunc='first')
new_df = new_df.set_axis([f'{y}_{x}' for x, y in new_df.columns], axi... | python|pandas|pivot|grouping|transpose | 0 |
362,012 | 63,373,895 | Avoid reloading Pandas dataFrame if already in name space | <p>Everytime i run my script the (very large) dataset is being reloaded. This is a time consuming and inefficient process which i want to avoid. So I was trying to get around the reloading by checking if the dataFrame already exists in the name space with the <code>try/except</code> command, looking like this:</p>
<pre... | <p>you could check using:</p>
<pre><code>cond = 'df' in dir()
if cond:
# operate on data
else:
# load the data
</code></pre> | python|pandas | 0 |
362,013 | 63,404,994 | Using one dataframe to create groups on other dataframe then taking averages | <p>The premise of my question is I would like to use one dataframe (peergroups) to create groups of stocks that are peers of other stocks and then calculate averages on another dataframe (fun_data) but I do not know how to use one dataframe to create the groups by year and ticker and then apply the groups, find the ave... | <p>I think you need <code>merge</code>s. First to create the mean per groups, you can <code>merge</code> df1 on the column year created from the date and ticker, and in df2 year and peer. then groupby the tocker column from df2 in this merged dataframe:</p>
<pre><code>df_ = (df1.assign(year=pd.to_datetime(df1['data']).... | python|pandas|numpy|dataframe|quantitative-finance | 2 |
362,014 | 63,705,826 | Flatten and reshaping input to an encoder | <p>I have dataset containing 3D fixed length segments shaped <code>(1,200,4)</code> which I would like to feed in to an Antoencoder with fully connected layers, similar to:</p>
<pre><code> encoder
autoencoder.add(Dense(200, input_shape=(self.input_dim,), activation='relu'))
autoencoder.add(Dense(100, input_shape=(sel... | <p>here a possibility... you need to simply take care or dimensionality in the end and operate a proper reshape</p>
<pre><code>encoding_dim = 20
input_shape = (1,200,4)
n_sample = 100
X = np.random.uniform(0,1, (n_sample,) + input_shape)
autoencoder = Sequential()
autoencoder.add(Flatten(input_shape=input_shape))
au... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
362,015 | 63,378,196 | Matrix reduction to echelon form exercise using Python | <p>I'm defining variables to convert a given matrix to its echelon form, the exercise ask me to define different variables to check whether a matrix is singular or not, and to convert it to its echelon form, this is the exercise and what I've done so far:</p>
<pre><code>import numpy as np
# Our function will go throug... | <p>I'm probably late to answer this question. But let's clarify a few things for those who might encounter this exercise.</p>
<p>From the way I see it, you did not understand the task at hand:</p>
<pre><code># set the sub-diagonal elements of row three to zero.
</code></pre>
<p>If you return to the function fixRowOne... | python|numpy|matrix|linear-algebra | 3 |
362,016 | 63,564,466 | Pandasql with conditions | <p>I have two dataframes:</p>
<ul>
<li><p>First one i have student information. I will call it df1</p>
<pre><code>user_id | plan | subplan | matrix_code | student_semester
102532 | GADMSSP | GSP10 | 1501 | 8
106040 | GRINTSP | | 1901 | 4
106114 | GCSOSSULA | | 1901 ... | <p>Consider adding a <code>CASE</code> statement in SQL query:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT d1.user_id
, d1.plan
, d1.subplan AS student_subplan
, d1.matrix_code
, d1.student_semester
, d2.subplan AS matrix_subplan
, CASE
WHEN d1.stu... | python|sql|pandas|merge | 2 |
362,017 | 63,560,159 | Find a row in a dataframe based on a column value from another dataframe and apply filter to it | <p>I have two dataframes df1 and df2.</p>
<pre><code>df1 = pd.DataFrame({'type_id' : [1,2,3,4,3], 'count' : [12,11,15,16,2], 'unique_id' : ['1|12','2|11','3|15','4|16','3|2']})
df2 = pd.DataFrame({'type_id' : [1,3,76,12,11,1], 'count' : [8,6,15,16,5,17], 'col3' : [1,5,7,3,4,7], 'unique_id' : ['1|8','3|6','76|12','12|1... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> for match by <code>id</code> columns to get <code>Series</code> with same length like <code>df2</code>, so possible compare by <code>df2['count']</code> and filter by <... | python|pandas|dataframe | 3 |
362,018 | 63,673,773 | How to manipulate pandas dataframe rows / headers? How to label whether the price of a row is higher or lower than the previous price? | <p>I have a dataframe that looks like this:</p>
<pre><code> NDAQ NDAQ NDAQ NDAQ NDAQ Close_Price_Increase
open high low close volume
time
2020-08-26 09:30:00-04:00 130.71 130.87 130.39 130.86 1824
2020-08-26 09:... | <pre><code>df=df.reset_index() #now your first column date should go as column
new_names=['Date','Open','High','Low','Close','Volume','Close_Price_Increase']
df.columns=new_names #now you should replace old column names, remeber that number of elements in list (new_names) should be equal to number of columns in your ... | python|pandas|dataframe|header|rows | 1 |
362,019 | 63,426,644 | Convolution Neural Networks Intuition - Difference in outcome between high kernel filter size vs high number of features | <p>I wanted to understand architectural intuition behind the differences of:</p>
<p><code>tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1))</code></p>
<p>and</p>
<p><code>tf.keras.layers.Conv2D(32, (7,7), activation='relu', input_shape=(28, 28, 1))</code></p>
<p>Assuming,</p>
<ol>
<li>As ker... | <p>This can be answered from 3 different views.</p>
<p><strong>Parameters:</strong><br />
Since you comparing 2 different convolution2D layers with different sizes, it's important to see the number of training parameters <code>∗(∗∗)+</code> needed for each, which in-turn makes your model more complex, and easy/difficul... | tensorflow|neural-network|conv-neural-network | 3 |
362,020 | 63,685,033 | Python/Pandas: Unit testing with hypothesis - reproducing falsifying example | <p>Using the <code>hypothesis</code> library for unit testing, I am wondering how I can reproduce a falsifying example <code>pd.DataFrame</code>?</p>
<p>The output looks like this:</p>
<pre><code>Falsifying example: test_data_frame_data(
data= sec_1 sec_2 sec_3
2020-01-01 00:00:00.0... | <p>I got a hint on the hypothesis GitHub issues page (<a href="https://github.com/HypothesisWorks/hypothesis/issues/2584" rel="nofollow noreferrer">https://github.com/HypothesisWorks/hypothesis/issues/2584</a>). Credits to @Zac-HD.</p>
<p>First solution:<br />
Put <code>@settings(print_blob=True)</code> before a test. ... | python|pandas|debugging|python-hypothesis | 0 |
362,021 | 63,457,825 | Error_Bad_Lines Alternative? | <p>not sure if this is considered a double post, I apologize if it is.</p>
<p>I am having a bit of problem with using Pandas Error_Bad_Lines.
I am currently importing around 500 CSV files into a Dataframe and using Pandas Error_Bad_Lines to remove lines with bad data, this works until it reads a CSV file which has a ba... | <p>Adding <code>index_col=False</code> to your invocation of <code>pd.read_csv</code> gets you closer to the result you want. Without it Pandas tries to use your first two columns as indices. Like you, I'm not sure why <code>error_bad_lines=False</code> does not delete the second line.</p>
<pre><code>from io import Str... | python|pandas | 2 |
362,022 | 63,514,639 | Graph disconnected: cannot obtain value for tensor "x" Tensor at layer "x" . The following previous layers were accessed without issue: [] | <p>I am building a small network using some custom network boxes for each use case, It looks like this :</p>
<pre><code>def top_block(dropout = None, training = None):
# scaled input
input_1 = tf.keras.Input(shape=(1,15), dtype='float32')
input_2 = tf.keras.Input(shape=(1,15), dtype='float32')
... | <p>I just realized my input is coming from intermediate layer (dropout layer), It should come directly from Input layer :</p>
<pre><code>def top_block():
# scaled input
input_1 = tf.keras.Input(shape=(1,15), dtype='float32')
input_2 = tf.keras.Input(shape=(1,15), dtype='float32')
return [input... | python|tensorflow|machine-learning|keras|deep-learning | 0 |
362,023 | 63,329,989 | Finding column index of a PyTorch tensor that has most 1's | <p>I have a <code>PyTorch</code> tensor <code>a</code> shaped like below:</p>
<pre><code>import torch
a = torch.tensor([[[1., 0., 0., 0.]],
[[0., 1., 0., 0.]],
[[1., 0., 0., 0.]],
[[0., 0., 0., 1.]],
[[1., 0., 0., 0.]],
[[0., 0., 0., 1.]],
[[1., 0., 0., 0.]]])
</code></pr... | <p>If your matrix only contains 0 and 1, you can sum the elements of each column and then search for the sum that is the largest:</p>
<pre><code>import numpy as np
% sum over columns
sumsi = torch.sum(a, dim=1)
% find where maximum
col_idx = np.where(sumsi==np.max(sumsi))
</code></pre> | python|pytorch|tensor | 1 |
362,024 | 63,342,851 | Delete the rows of a DataFrame satisfying conditions evaluated against multiple columns | <p>I would like to filter my <code>DataFrame</code> by evaluating some conditions against several columns of the <code>DataFrame</code>. I illustrate what I want to do with the following eample:</p>
<pre><code>df = {'user': [1,1,1,2,2,2],
'speed':[10,20,90,15,39, 10],
'acceleration': [9.8,29,5,4,7, 3],
... | <p>You can use <code>reindex</code>, and then do the msk:</p>
<pre><code>threshold=threshold.reindex(df['mode'])
threshold=threshold.reset_index(drop=True)
msk=(df.acceleration.lt(threshold['acceleration','max']))&\
(df.speed.lt(threshold['speed','max']))&\
(df.jerk.ge(threshold['jerk','min'])&\
... | python|pandas|dataframe | 2 |
362,025 | 63,612,321 | Why does .apply() not apply rotation like I expect? | <pre><code>(Pdb) R.from_matrix(R_xy).apply(centered_points[599,:])
array([-0.02405325, 0.00502445, 0.06892317])
(Pdb) (R_xy @ centered_points[599,:].T).T
array([-0.02449478, 0.00437224, 0.06888685])
</code></pre>
<p>I would expect the second line to be proper application of a rotation to centered_points. centered_p... | <p>I discovered the issue: I was generating R_xy from non-perfectly orthogonal vectors. This messes up all calculations with rot.apply</p> | numpy|scipy | 1 |
362,026 | 63,403,689 | Concatenate DataFrame where the values are the same and drop values where values are different | <p>I am trying to merge two DataFrame columns <code>(A & B)</code> where column values are the same while dropping the remainder values (remainder values being those values where column values are not the same).</p>
<p>I have (DataFrame 1):</p>
<pre><code>A | B
-----
a | a
b | b
c | a
</code></pre>
<p>I need (DataF... | <p>Here is a variation on @AtanCSE's solution, in case the number of original columns is large. The difference is: provide list of columns to <em>drop</em>, versus list of columns to <em>keep</em>.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A': ['a', 'b', 'c'],
'B': ['a', 'b', 'a']})
... | python|pandas | 0 |
362,027 | 63,625,356 | Pandas : Extend rows based on column value | <p>I have one list of list dataset :</p>
<pre><code>data_set = [['note_a', 'mix'],['note_b', 'mix'], ['mix','leave','note_a','note_b','random'],['mix','random','note_a','note_b']]
</code></pre>
<p>I am taking the cartesian product of it :</p>
<pre><code>import itertools
all_method = pd.DataFrame(itertools.product(*data... | <p>You can consider <code>replace</code> then <code>concat</code>:</p>
<pre><code>pd.concat(all_method.replace('mix',copy) for copy in ['copy_a', 'copy_b', 'copy_c'])
</code></pre>
<p>Output:</p>
<pre><code> 0 1 2 3
0 note_a note_b copy_a copy_a
1 note_a note_b copy_a random
2 note... | python|python-3.x|pandas|numpy|loops | 1 |
362,028 | 63,687,067 | Pytorch: Mask dilation / extension | <p>I wonder how to extend / dilate binary mask in pytorch? i.e. it should be something like <a href="https://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html?highlight=dilate#dilate" rel="nofollow noreferrer">cv2.dilate</a> from opencv.</p> | <p>For rectangular neighborhoods, dilation is the same as max pooling.<br />
See <a href="https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html#torch.nn.MaxPool2d" rel="nofollow noreferrer"><code>nn.MaxPool2d</code></a> for implementation details.</p> | python|opencv|computer-vision|pytorch | 2 |
362,029 | 63,564,579 | Remove rows of one Dataframe based on one column of another dataframe | <p>I got two DataFrame and want remove rows in df1 where we have same value in column 'a' in df2. Moreover one common value in df2 will only remove one row.</p>
<pre><code>df1 = pd.DataFrame({'a':[1,1,2,3,4,4],'b':[1,2,3,4,5,6],'c':[6,5,4,3,2,1]})
df2 = pd.DataFrame({'a':[2,4,2],'b':[1,2,3],'c':[6,5,4]})
result = pd.Da... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</code></a> to ... | python|pandas|dataframe | 3 |
362,030 | 63,333,823 | Boxplot of a list of pandas dataframes | <p>I have the next list of dataframes</p>
<p>list = [df1, df2, df3, df4]</p>
<p>All the dfs has the same structure</p>
<p>df = [col1, col2, col3]</p>
<p>I want to make a boxplot with the same column in each df but i cant, im trying with:</p>
<pre><code>for df in dfs:
df.boxplot(column='col1', subplots=True)
</code>... | <p>You need to concat it.</p>
<pre><code>df = pd.concat(lst)
</code></pre>
<p>And then plot:</p>
<pre><code>for column in df:
plt.figure()
df.boxplot(['col1'])
</code></pre> | pandas|boxplot | 1 |
362,031 | 63,431,473 | Compare multiple rows values in Pandas Dataframe | <p>I have a dataframe that looks like this:</p>
<pre><code>Date Open High Low macd signal histogram
2020-08-10 11:37:00 21.0300 21.2900 20.8700 0.244226 0.226461 0.017765
2020-08-10 11:38:00 21.1350 21.1400 20.9100 0.225912 0.226339 -0.000427
2020-08-10 11:39:00 21.08... | <p>For your first question you can iterate over the range of rows <code>2:15</code> on <code>df['histogram']</code>:</p>
<pre><code>hist = df['histogram']
for idx in range(2, 15): # assuming not inclusive
if hist[idx] > 0.00000:
print("Data shows correct")
elif hist[idx] < 0.0000:
... | python|pandas|dataframe | 0 |
362,032 | 63,523,996 | Disable augmentation in tensorflow training pipeline | <p>I googled around a bit but I only found questions about enabling data augmentation.</p>
<p>I followed this <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html" rel="nofollow noreferrer">tutorial</a> but with my own dataset (only one class). I already performed data augmen... | <p>This is an issue with the normalization of the image. It does not affect your training.
However, if you want the images to be displayed correctly in tensorboard, then normalize them between (0, 1). Check <a href="https://github.com/tensorflow/models/pull/9019/commits/65c8a8ac3cc295f597789d436f39ea4b733140c2" rel="no... | tensorflow|object-detection-api | 2 |
362,033 | 63,420,924 | How to generate regional groups in pandas dataframe | <p>I'm new to Python and programming in general. I have posted a variation of this question before. I hope this time my presentation comes through somewhat better. I hope my formatting is par for the course.<br />
This is the code that reads my csv file in:</p>
<pre><code>import pandas as pd
import numpy as np
ef... | <p>Maybe because you are using an <code>&</code> for an AND between the values in the same column?</p>
<p>This means you are finding those rows, which have <code>ef["Stabr"]</code> value equal to "ME" and "VT" and "NH" and ..., at the same time which is not possible because a... | python-3.x|pandas|dataframe | 0 |
362,034 | 63,460,784 | Pandas Dataframes - Get the dataframe's overall top 5 values and their row and column labels, not by column or by row | <p>I have a pandas DataFrame, let's say its named "df", with numerical values inside it in all columns (floats). I want to retrieve the top 5 highest absolute values from the dataframe, together with their row and column labels.</p>
<p>I've seen suggestions like:</p>
<pre><code>df.abs().stack().nlargest(5)
</... | <p>The suggested solution contains the row and column labels in the index and are not lost.</p>
<p>A simple example where the appropriate names are reattached:</p>
<pre><code>df = pd.DataFrame({'a': np.random.random(100), 'b': np.random.random(100)})
df.abs().stack().nlargest(5).rename('value').rename_axis(['row', 'co... | python|pandas|dataframe | 1 |
362,035 | 63,489,767 | Matplotlib errorbar extra space at top and bottom | <p>When I run the following lines, I get a plot with a large space at the top and the bottom with no bars.
How can I remove this extra space?</p>
<pre><code>import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D
random.seed(1)
df = pd.DataFrame(np... | <p>If you mean the extra space below and above your smallest and largest data points along the y-axis then you can simply use <a href="https://matplotlib.org/3.3.1/api/_as_gen/matplotlib.pyplot.ylim.html" rel="nofollow noreferrer"><code>plt.ylim</code></a>, e.g:</p>
<pre><code>plt.ylim(0, 50)
</code></pre>
<p>Which wil... | python|pandas|matplotlib | 1 |
362,036 | 63,538,895 | Compute the mean of a Tensorflow Tensor keeping its shape | <p>I'm using Python 3.7.7 and Tensorflow 2.1.0.</p>
<p>I have this tensor:</p>
<pre><code>tf.Tensor([...], shape=(5, 512), dtype=float32)
</code></pre>
<p>And I want to compute its mean on each of its elements, getting a tensor with shape <code>(1, 512)</code> but I don't know how. I have tried <code>tf.math.reduce_mea... | <p>Just reshape..
<code>tf.reshape(tf.reduce_mean(your_tensor, axis=0), (1,512))</code></p> | python|numpy|tensorflow | 1 |
362,037 | 63,375,201 | Tensorflow ValueError: logits and labels must have the same shape ((None, 2) vs (None, 1)) | <p>I'm new to Machine Learning, thought I'll start with keras. Here I'm classifying movie reviews as three class classification (positive as 1, neutral as 0 and negative as -1) using binary crossentropy. So, when I'm trying to wrap my keras model with tensorflow estimator, I get the error.<br>
The code is as follows:</... | <p>There are several issues with your code.</p>
<ol>
<li>You are using the wrong loss function. The binary cross-entropy loss is used for <strong>binary classification</strong> problems but here you are doing a multi-class classification (3 classes - positive, negative, neutral).</li>
<li>Using the sigmoid activation f... | python|tensorflow|keras | 9 |
362,038 | 63,569,585 | Why do (complex) functions of the same numbers generated by numpy.arange() and range() differ? | <pre><code># necessary imports
import numpy as np
import matplotlib.pyplot as plt
</code></pre>
<hr />
<h1>REPRODUCIBLE SETUP</h1>
<p>Binet formula is the following, from <a href="https://youtu.be/ghxQA3vvhsk?t=275" rel="nofollow noreferrer">here</a>:</p>
<p><a href="https://i.stack.imgur.com/7mlTw.png" rel="nofollow n... | <p>The duplicate focused on <code>np.arange</code>. But that isn't the problem here.</p>
<p>Compare passing a float to <code>binet</code> versus a <code>np.float64</code>:</p>
<pre><code>In [52]: binet(0.1)
Out[52]: (0.06391735396852471-... | python|python-3.x|numpy|list-comprehension|fibonacci | 2 |
362,039 | 63,638,511 | Transform a Pandas series to be monotonic | <p>I'm looking for a way to remove the points that ruin the monotonicity of a series.</p>
<p>For example</p>
<pre><code>s = pd.Series([0,1,2,3,10,4,5,6])
</code></pre>
<p>or</p>
<pre><code>s = pd.Series([0,1,2,3,-1,4,5,6])
</code></pre>
<p>we would extract</p>
<pre><code>s = pd.Series([0,1,2,3,4,5,6])
</code></pre>
<bl... | <p>Here is a way to produce a monotonically increasing series:</p>
<pre><code>import pandas as pd
# create data
s = pd.Series([1, 2, 3, 4, 5, 4, 3, 2, 3, 4, 5, 6, 7, 8])
# find max so far (i.e., running_max)
df = pd.concat([s.rename('orig'),
s.cummax().rename('running_max'),
], axis=1)... | python|pandas|series | 0 |
362,040 | 63,402,045 | How do you identify which IDs have an increasing value over time in another column in a Python dataframe? | <p>Lets say I have a data frame with 3 columns:</p>
<pre><code>| id | value | date |
+====+=======+===========+
| 1 | 50 | 1-Feb-19 |
+----+-------+-----------+
| 1 | 100 | 5-Feb-19 |
+----+-------+-----------+
| 1 | 200 | 6-Jun-19 |
+----+-------+-----------+
| 1 | 500 | 1-Dec-19 |
+----+-------+... | <p>Perhaps group by the id, and check that the sorted values are the same whether sorted by values or by date:</p>
<pre><code>>>> df.groupby('id').apply( lambda x:
... (
... x.sort_values('value', ignore_index=True)['value'] == x.sort_values('date', ignore_index=True)['value']
... ).all()
... )
id... | python|pandas | 2 |
362,041 | 63,591,138 | lost numpy for Keras in R | <p>I installed Keras, Tensorflow and reticulate packages in R and when I check the version of Python used it's given 3.6 in the r-reticulate folder (so I cannot use Keras as need 3.7). So I run the following line to change the folder to pick up the latest Python version:</p>
<pre><code>use_python("C:/Users/PC/AppD... | <p>You have two installations of Python on your computer which can be thought of as completely different programs. That "program" supports installing "packages", like numpy and tensorflow. If you install numpy in one of those installations, it doesn't provide it in both of them - you have to also in... | r|numpy|tensorflow|keras | 1 |
362,042 | 21,841,952 | Pandas Dataframe to_csv format output | <p>I can't find a way to control the output of each column dataframe. From the following code:</p>
<pre><code>df.to_csv('dfnc.txt',
sep=' ',
float_format='%.8f',
cols=['cycle','passs','ip','lon','lat'],
index=False)
</code></pre>
<p>I'm getting this:</p>
<pre><code>1.00000000 1.0000... | <p>I think you can just convert the 1st to the 3rd <code>columns</code> to <code>int64</code> before writing the CSV file (if you check the <code>.types</code>, I am sure they are all <code>float64</code>):</p>
<pre><code>df[['cycle', 'passs', 'ip']]=df[['cycle', 'passs', 'ip']].astype(int64)
</code></pre> | python|pandas|format|dataframe | 3 |
362,043 | 21,612,175 | plotting in python with congruent x-values | <p>Goal: Get two different names on the same graph. Make sure that the years line up. Note, not the file has some years twice (when a name has been given to both girl & boy), in that case add the values for all split years per name.</p>
<p>Current status: one name is working. Two names changes the index to the row... | <p>I'm guessing you're using the Census baby names dataset? The one used in <a href="http://shop.oreilly.com/product/0636920023784.do" rel="nofollow noreferrer">Wes McKinney's book</a>? In the future it's a good idea to include a sample from your dataset so that others can reproduce your work.</p>
<p>I've just got 200... | python|matplotlib|pandas | 2 |
362,044 | 21,870,727 | Python: Divide values in cell by max in each column | <p>Is this an efficient or correct way to divide every cell in each column by the maximum value in that column within a table? Is there a better implementation (if this is correct)?
Note: All values >= 0</p>
<pre><code>new_data = [];
for row in np.transpose(data)[1::]: #from 1 till end
for elements in row:
... | <p>How do you handle <code>0</code>? Like the last column? It should be <code>nan</code> in theory. (<code>sum(elements) != 0</code>, what if it is -2 -1 0 1 2? That should be result in -1 -0.5 0 0.5 1, right?)</p>
<pre><code>In [138]:
A*1./np.max(A, axis=0)
Out[138]:
array([[ 0.33333333, 0.125 , 1. , ... | python|numpy | 6 |
362,045 | 21,624,217 | Pandas, dataframe with a datetime64 column, querying by hour | <p>I have a pandas dataframe <code>df</code> which has one column constituted by <code>datetime64</code>, e.g.</p>
<pre><code><class 'pandas.core.frame.DataFrame'>
Int64Index: 1471 entries, 0 to 2940
Data columns (total 2 columns):
date 1471 non-null values
id 1471 non-null values
dtypes: datetime64[ns... | <p>Found a simple solution. </p>
<pre><code>df['hour'] = df.date.apply(lambda x : x.hour)
df_sub = df[(df.hour > 8) & (df.hour) <20]
</code></pre>
<hr>
<p>EDIT:</p>
<p>There is a property <code>dt</code> specifically introduced to handle this problem. The query becomes:</p>
<pre><code>df_sub = df[ (df.d... | python|datetime|pandas|datetime64 | 5 |
362,046 | 21,489,945 | Indexing hierarchical columns | <p>I have a dataframe with hierarchical columns and I am trying to figure out how to index. How do I adopt the dataframe basic index <code>df.loc[row_indexer,column_indexer]</code> when there are 4 levels of column index? I am looking for some strategy like <code>df.loc['2014-01-02', DK='18757']</code> ... How can I ... | <p>Convert every level of columns into a Series, then you can use boolean mask to select what you want. </p>
<pre><code>a = list("EEEETTTT")
b = list("11223344")
c = list("XYXYXYXY")
mi = pd.MultiIndex.from_tuples(zip(a,b,c), names=["A","B","C"])
df = pd.DataFrame(np.random.randint(0, 10, (5, 8)), columns=mi)
A, B, C... | python|pandas|dataframe | 0 |
362,047 | 21,566,744 | Generate random array of 0 and 1 with a specific ratio | <p>I want to generate a random array of size N which only contains 0 and 1, I want my array to have some ratio between 0 and 1. For example, 90% of the array be 1 and the remaining 10% be 0 (I want this 90% to be random along with the whole array).</p>
<p>right now I have:</p>
<pre><code>randomLabel = np.random.randin... | <p>If you want an exact 1:9 ratio:</p>
<pre><code>nums = numpy.ones(1000)
nums[:100] = 0
numpy.random.shuffle(nums)
</code></pre>
<p>If you want independent 10% probabilities:</p>
<pre><code>nums = numpy.random.choice([0, 1], size=1000, p=[.1, .9])
</code></pre>
<p>or</p>
<pre><code>nums = (numpy.random.rand(1000)... | python|random|numpy | 51 |
362,048 | 21,843,513 | OpenCV multicolor thresholding | <p>I am trying to do a multicolor thresholding on a opencv cv2 image. The problem I am trying to solve is following:</p>
<ul>
<li>R, G, B each have a "valid" list</li>
<li>If a pixel's R, G, B all considered valid, then make the pixel (0,0,0), otherwise, make it (255, 255, 255)</li>
</ul>
<p>For example</p>
<ul>
<li... | <p>Please try this:</p>
<pre><code>z1 = np.dstack([np.in1d(img[...,0],B),np.in1d(img[...,1],G),np.in1d(img[...,2],R)]).reshape(img.shape)
q = np.all(z1,axis=2)
out = np.uint8(q)*255
</code></pre>
<p><code>np.in1d(a,b)</code> gives you a boolean array of same length as a with <code>True</code> if that element is in b,... | python|opencv|numpy | 2 |
362,049 | 24,904,822 | scipy.stats.ttest_ind without array (python) | <p>I have done a number of calculations to estimate μ, σ and N for my two samples. Due to a number of approximations I don't have the arrays that are expected as input to scipy.stats.ttest_ind. Unless I am mistaken I only need μ, σ and N to do a <a href="http://en.wikipedia.org/wiki/Welch%27s_t_test" rel="nofollow">wel... | <p>Here’s a straightforward implementation based on <a href="http://en.wikipedia.org/wiki/Welch's_t_test" rel="nofollow">this</a>: </p>
<pre><code>import scipy.stats as stats
import numpy as np
def welch_t_test(mu1, s1, N1, mu2, s2, N2):
# Construct arrays to make calculations more succint.
N_i = np.array([N1... | python|numpy|statistics|scipy | 3 |
362,050 | 24,619,856 | Circle Graphing Program Null Value Errors (Python 3.4) | <p>This is my program for graphing circles according to the radius and center coords that the user inputs.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def circle(r,h,k,domain):
x = np.array(domain)
y = eval(np.sqrt(r**2 - (x-h)**2) + k)
plt.plot(x,y)
plt.show
rad = float(input("Ra... | <p><code>eval</code> is not used for arithmetic evaluation in python, simply remove it from</p>
<pre><code>y = eval(np.sqrt(r**2 - (x-h)**2) + k)
</code></pre>
<p>to obtain a valid</p>
<pre><code>y = np.sqrt(r**2 - (x-h)**2) + k
</code></pre>
<p>also plotting each point as a separate data serie is rather a bad idea... | python|numpy|matplotlib | 0 |
362,051 | 24,799,487 | Python - mask multidimensional | <p>I would like to mask some values of an array. The array is 3D and the mask is 2D.</p>
<p>I want to mask all the coordonates in the direction of <code>frametemperature_reshape.shape[0]</code>. </p>
<p>I tried the following loop:</p>
<pre><code>for i in range(frametemperature_reshape.shape[0]):
frames_BPnegl = ... | <p>You can <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="noreferrer">broadcast</a> the 2D mask against the 3D array, so that its size is expanded along the 3rd dimension without actually duplicating it in memory:</p>
<pre><code>import numpy as np
x = np.random.randn(10, 20, 30)
mask = n... | python|numpy|mask | 7 |
362,052 | 24,771,384 | (Python) MVHR Covariance and OLS Beta difference | <p>I calculated the minimum variance hedge ratio (MVHR) of two securities' returns by:<br>
1. Calculating the optimal h* = Cov(S,F) / Var(F) using samples<br>
2. Running an OLS regression and obtain the beta value</p>
<p>Both values differ slightly, for example I got h* = 0.9547 and beta = 0.9537. But they are suppose... | <p>This is also a case of missing constant in OLS regression. The covariance and variance calculation subtracts the mean which is the same in the linear regression as including a constant. statsmodels doesn't include a constant by default unless you use the formulas.</p>
<p>For more details and an example see for exam... | python|numpy|statsmodels | 2 |
362,053 | 24,582,320 | Infinite path length of graph for networkx | <p>I'm making a graph from an adj matrix, here is my code, I try to first make the graph, then put a weight with that graph as seen here</p>
<pre><code>for element in elements:
senMatrix[int(element.matrix_row)-1,int(element.matrix_column)-1]=1
G=nx.from_numpy_matrix(senMatrix)
for element in element... | <p>try </p>
<pre><code>nx.is_connected(G)
</code></pre>
<p>if it returns False then you can separate the graph by components and find the diameter for each component, using</p>
<pre><code>connected_components(G)
</code></pre> | python|numpy|networkx | 6 |
362,054 | 24,860,457 | How to drop the index column of DataFrame? | <p>I want to get rid of the index column that the Pandas DataFrame prints out in default. Is this possible?</p>
<p>Thank you for your help!</p> | <p>As @EdChum noted, not sure there's any way to do this by default. For display purposes, you could do:</p>
<pre><code>print(df.to_string(index=False))
</code></pre> | python|pandas|indexing|dataframe|multiple-columns | 1 |
362,055 | 24,847,494 | why the dataframe generated using merge operation is not of 3x3 dimension rather than 3x5? | <p>i follow the instruction <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html</a>, <strong>but is confused when the merge colums is not of the same index</strong>. for example, colu... | <p>In your first merge you are merging lhs on column '0' and rhs on column '1' but you have no identical values so it has to create two columns with suffixes. The remaining columns have no matches either so you create additional columns.</p>
<p>In the second example you merge on column '0', whereby you do have identic... | python|pandas | 2 |
362,056 | 24,519,612 | Error in `/usr/bin/python': double free or corruption (out): 0x00007f7c3c017260 | <p>I'm developing a website in Python using the (excellent) Flask framework. In the backend code I use APScheduler to run some cron-like jobs every minute, and I use Numpy to calculate some Standard Deviations. Don't know whether the usage of these modules matter, but I thought I'dd better mention them since I guess th... | <p>I had a similar issue.</p>
<p>I had an unused dependency: spacy == 1.6.0
removing it solved the issue.
(maybe upgrading spacy version could also work)</p>
<p><a href="https://spacy.io/" rel="nofollow noreferrer">spacy</a> is written in <a href="http://cython.org/" rel="nofollow noreferrer">Cython</a> - an optimisi... | python|numpy|flask|race-condition|apscheduler | 1 |
362,057 | 24,899,604 | Bipartite projection and write to CSV with NetworkX -- how to speed up writing to handle large file | <p>I have a pretty big file (3 million lines) with each line being a person-to-event relationship. Ultimate, I want to project this bipartite network onto a single-mode, weighted, network, and write it to a CSV file. I'm using NetworkX, and I've tested my code on a much smaller sample dataset, and it works as it shou... | <p>Here is what I suggested on the networkx-discuss mailing list:</p>
<pre><code>import networkx as nx
B = nx.Graph()
B.add_edge('a',1)
B.add_edge('a',2)
B.add_edge('b',1)
B.add_edge('b',2)
B.add_edge('b',3)
B.add_edge('c',3)
nodes = ['a','b','c']
seen = set()
for u in nodes:
# seen=set([u]) # print both u-v, and... | python|pandas|networkx|bipartite | 1 |
362,058 | 30,113,118 | select elements of different columns at different rows of numpy array | <pre><code>In [62]: a
Out[62]:
array([[1, 2],
[3, 4]])
</code></pre>
<p>Is there an easy way to get [2,3], i.e. the second element of the first row, and the first element of the second row? I have the list of the indices for each row, i.e. [1,0] in this case. I have tried a[:,[1,0]], but it doesn't work.</p> | <p>You need to specify both i and j for all the elements you want. For example:</p>
<pre><code>import numpy as np
a = np.array([[1, 2],
[3, 4]])
i = [0, 1]
j = [1, 0]
print(a[i, j])
# [2, 3]
</code></pre>
<p>If you need one item from each row, you can use <code>i = np.arange(a.shape[0])</code></p> | python|arrays|numpy|indexing | 4 |
362,059 | 29,979,515 | Unable to interpolate data using Rbf in Scipy | <p>I tried to interpolate the data using Rbf.</p>
<pre><code>import numpy as np, matplotlib.pyplot as plt
from scipy.interpolate import Rbf
x = np.array([110, 112, 114, 115, 119, 120, 122, 124]).astype(float)
y = np.array([60, 61, 63, 67, 68, 70, 75, 81]).astype(float)
d = np.array([4, 6, 5, 3, 2, 1, 7, 9]).astype(... | <p>With your original data (from the SO with <code>griddata</code>), this works:</p>
<p>Clean up the <code>x</code>,<code>y</code>, removing the outliers:</p>
<pre><code>yreg=y.reshape(15,15)[:,[0]].repeat(15,1).flatten()
xreg=x.reshape(15,15)[[0],:].repeat(15,0).flatten()
ulx, lrx = np.min(xreg), np.max(xreg)
uly, l... | python-2.7|numpy|scipy | 2 |
362,060 | 29,989,224 | python pandas replacing column values conditional on string patterns and using split() | <p>long time lurker--I finally stuck to a project involving pandas and more than ever I need your help. </p>
<p>I have a dataframe like the following. Each row describe one retirement formula which may have more than one criteria (hence e1)</p>
<pre><code>index e0 e1
1 62/10 NaN
2 age 55 NaN
3 67/... | <p>Interesting problem, here I pass a function that removes the <code>NaN</code> values and then calls <code>sum</code> which will concatenate the rows of data.</p>
<p>We can then call the vectorised <code>str</code> method <code>findall</code> with regex <code>\d+</code> which returns all numbers as a list.</p>
<p>W... | regex|pandas | 0 |
362,061 | 29,926,691 | How to serialise Pandas to MessagePack format as a python buffer / memoryview? | <p>Pandas has a <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-msgpack" rel="nofollow noreferrer">DataFrame.to_msgpack()</a> method for serialising a dataframe to the <a href="http://msgpack.org" rel="nofollow noreferrer">MessagePack</a> format.</p>
<p>It requires a file path or a 'buffer-like' object... | <p>After perusing the pandas source code it appears that the way to do this is to use python's io.BytesIO() for the buffer:</p>
<pre><code>buffer = io.BytesIO()
df.to_msgpack(buffer, append=False, compress='zlib')
</code></pre>
<p>This appears to work nicely. Note that the compress option appears a bit spotty in rele... | python|python-3.x|pandas|msgpack|memoryview | 2 |
362,062 | 29,943,871 | How to draw an unit circle using numpy and matplotlib | <p>I want to draw an unit circle(cos+sin), using numpy and matplotlib.
I wrote the following:</p>
<pre><code>t = np.linspace(0,np.pi*2,100)
circ = np.concatenate((np.cos(t),np.sin(t)))
</code></pre>
<p>and I plotted, but failed.</p>
<pre><code>ax.plot(t,circ,linewidth=1)
ValueError: x and y must have same first dime... | <p><code>plot</code> does not do a parametric plot. You must give it the <code>x</code> and <code>y</code> values, not <code>t</code>.</p>
<p><code>x</code> is <code>cos(t)</code> and <code>y</code> is <code>sin(t)</code>, so give those arrays to <code>plot</code>:</p>
<pre><code>ax.plot(np.cos(t), np.sin(t), linewi... | numpy|matplotlib|geometry | 5 |
362,063 | 29,892,798 | Insert 1D NumPy array as column in existing 2D array | <p>I have a <code>2D</code> <code>NumPy</code> array:</p>
<pre><code>>>> import numpy as np
>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
</code></pre>
<p>and a <code>1D</code> array: </p>
<pre><code>>>> b = np.ara... | <p>You could use <code>column_stack()</code></p>
<pre><code>In [256]: np.column_stack((b, a))
Out[256]:
array([[0, 1, 2, 3],
[1, 4, 5, 6],
[2, 7, 8, 9]])
</code></pre> | python|arrays|numpy | 2 |
362,064 | 30,222,512 | Numpy repeating a row or column | <p>Suppose we have the matrix A:</p>
<pre><code>A = [1,2,3
4,5,6
7,8,9]
</code></pre>
<p>I want to know if there is a way to obtain:</p>
<pre><code>B = [1,2,3
4,5,6
7,8,9
7,8,9]
</code></pre>
<p>As well as:</p>
<pre><code>B = [1,2,3,3
4,5,6,6
7,8,9,9]
</code></pre>
<p>This is be... | <p>For your particular example you could use <code>numpy.hstack</code> and <code>numpy.vstack</code>:</p>
<pre><code>In [11]: np.vstack((A, A[-1]))
Out[11]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[7, 8, 9]])
In [12]: np.hstack((A, A[:, [-1]]))
Out[12]:
array([[1, 2, 3, 3],
[4, 5, 6, 6],... | python|numpy | 2 |
362,065 | 30,199,070 | How to create a 4 or 8 connected adjacency matrix | <p>I have been looking for a python implementation that returns a 4- or 8-connected adjacency matrix, given an array. I find it surprising that cv2 or networkx don't include this functionality. I came across this great Matlab <a href="https://stackoverflow.com/a/3283732/4663466">implementation</a> and decided to make s... | <p>Using the diagonal structure, as detailed in <a href="https://stackoverflow.com/a/3283732/4663466">this answer</a> regarding "Construct adjacency matrix in MATLAB", I create only the upper diagonals and add them in the appropriate positions to a sparse diagonal matrix using <a href="http://docs.scipy.org/doc/scipy-0... | python|image-processing|numpy|scipy|adjacency-matrix | 4 |
362,066 | 30,062,061 | python pandas min() not picking up minimum | <p>I've encountered a strange problem. I'm sure there is a logical reason behind this. </p>
<p>I have a dataframe called alloptions that has 4 columns, minage1, minage2, minage3, and minage4, which are all float64. the number of missing values increases from minage1 to minage4. </p>
<p>I create a fifth column that ta... | <p>You are using the builtin Python <code>min</code> function, which doesn't know about <code>nan</code> and treats it inconsistently:</p>
<pre><code>>>> min(1, np.nan)
1
>>> min(np.nan, 1)
nan
</code></pre>
<p>Instead, use the <code>min</code> method from <code>pandas</code>, which knows to ignore ... | python|pandas | 7 |
362,067 | 30,132,124 | Scipy ConvexHull and QHull: rank/dimension is not maximal | <p>I am trying to create a Convex Hull using the library Scipy and ConvexHull. As far as I know, it calls QHull.</p>
<p>The problem appears when the points I want to add do not have 'full dimension'. Example:</p>
<pre><code>from scipy.spatial import ConvexHull
import numpy as np
points = np.append([[0,2]],[[2,0]],axi... | <p>It seems that ConvexHull does not support degenerate convex hulls.</p>
<p>The number of points must be at least the number of dimensions plus one to have a non-degenerate convex-hull.</p>
<p>For example in a plane, you need 3 points in order to have a non-degenerate hull: the convex hull for 3 points would be a tr... | python|numpy|convex-hull|convex-polygon|qhull | 4 |
362,068 | 30,135,014 | TypeError: 'float' object is not subscriptable in matrix | <p>I have this error: </p>
<blockquote>
<p>"TypeError: 'float' object is not subscriptable"</p>
</blockquote>
<p>This is the part of the code that displays the error:</p>
<pre><code>nd_coord = random.uniform(npoints, 2)
nd_coord[:,0] = nd_coord[:,0] * ((xmax - xmin) + xmin)
nd_coord[:,1] = nd_coord[:,1... | <p>I take it you've imported NumPy as <code>from numpy import *</code> and so <code>random.uniform</code> is the NumPy method. Its <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html" rel="nofollow">call signature</a> is:</p>
<blockquote>
<p>numpy.random.uniform(low=0.0, high=1.0, ... | python|numpy | 1 |
362,069 | 29,888,831 | Combining multiple pandas read_csv and/or file.readline() | <p>I am trying to read a text-data file, that it is composed of many consecutive and alternating blocks of data, and each block is either with N rows and X columns or N+1 rows and Y columns.</p>
<p>My idea was to use <code>pd.read_csv</code> with two consecutive calls, the first using the option <code>nrow=N</code>, t... | <ol>
<li>About the null string in the last <code>fp.readline()</code>:</li>
</ol>
<blockquote>
<p>When you open a file with <code>open(filepath)</code> a file handle iterator is
returned. An iterator is good for one pass through its contents. So
<code>pd.io.parsers.read_csv(fp,nrows=2,header=None,sep='
',names... | python|pandas | 1 |
362,070 | 30,076,994 | Matlab fit() vs. Python numpy | <p>I have a matlab script I am converting to Python. Because I want to make a comparison of the programs (not of the individual computation) I want the individual computations to match in both Python and Matlab. The computation regards a polynomial surface fit to some data points.</p>
<p>Matlab: </p>
<pre><code>[xDat... | <p>The Python version is missing the <code>p11</code> term from MATLAB (as shown by your coefficients). From the <a href="http://www.mathworks.com/help/curvefit/list-of-library-models-for-curve-and-surface-fitting.html#btbcvnl" rel="nofollow">MATLAB documentation</a></p>
<blockquote>
<p>Poly12 : Z = p00 + p10*x + p0... | python|matlab|numpy|surface|data-fitting | 0 |
362,071 | 30,170,361 | Opening Images as Arrays | <p>I have a script that should open an image as a 2D array but I can't seem to make it work. I have tried using the numpy an PIL libraries. I tried this on different computers. The issue is that it opens the image as a 2D array on one computer but opens them ups as objects on a different compute running the same versio... | <p>Have you tried the imread function from matplotlib? </p>
<pre><code>from matplotlib.image import imread
image = imread(image_path)
</code></pre>
<p>Returns a numpy array and works fine for me (python 3.4). </p> | python|arrays|image|numpy|python-imaging-library | 6 |
362,072 | 29,971,269 | Cumsum and vectorized slicing | <p>I have a matrix <code>J</code> of size <code>(j,v)</code> and a vector <code>JTildeIDX</code> of size <code>v</code>. The vector contains the <em>start</em> for a cumsum operation over <code>J</code>. That is, given</p>
<pre><code>>>> JTildeIDX
array([0, 0, 9, 9, 9])
>>> J
array([[ 1. , 1.... | <p>One approach with <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>braodcasting</code></a> and <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html" rel="nofollow"><code>boolean indexing</code></a> -</p>
<pre><code>import numpy as np
# Mask of elements from... | python|numpy|vectorization | 2 |
362,073 | 30,189,799 | Fastest way to replace values in a numpy array with a list | <p>I want to read a list into a numpy array. This list is being replaced in every iteration of a loop and further operations are done on the array. These operations include element-wise subtraction from another numpy array for a distance measure, and checking a threshold condition in this distance using the numpy.all()... | <p>As you "know the size of the list and it is invariable", you can set up an array first:</p>
<pre><code>b = np.zeros((7,))
</code></pre>
<p>This then works faster:</p>
<pre><code>%timeit b[:] = a
1000000 loops, best of 3: 1.41 µs per loop
</code></pre>
<p>vs</p>
<pre><code>%timeit b = np.array(a)
1000000 loops, ... | python|arrays|performance|numpy | 1 |
362,074 | 29,854,398 | Seeding random number generators in parallel programs | <p>I am studing the multiprocessing module of Python.
I have two cases:</p>
<p>Ex. 1</p>
<pre><code>def Foo(nbr_iter):
for step in xrange(int(nbr_iter)) :
print random.uniform(0,1)
...
from multiprocessing import Pool
if __name__ == "__main__":
...
pool = Pool(processes=nmr_parallel_block)
p... | <p>If no seed is provided explicitly, <code>numpy.random</code> will seed itself using an OS-dependent source of randomness. Usually it will use <code>/dev/urandom</code> on Unix-based systems (or some Windows equivalent), but if this is not available for some reason then it will seed itself from the wall clock. Since ... | python|numpy|random|multiprocessing | 31 |
362,075 | 53,363,504 | In Pandas, how can I reduce the rows so that I only accept rows of a certain sub group's max values? | <pre><code>a 1
a 2
a 3
b 3
b 4
a 3
b 5
b 6
b 4
b 10
b 11
a 10
b 2
b 3
</code></pre>
<p>ignore a's till there is a change to b. Only consider groups where a changes to b, and get max of that group?</p>
<p>final output</p>
<pre><code> a 1
a 2
a 3
b 4
b 11
a 10
</code></pre>
... | <p>Using <code>shift</code> and <code>cumsum</code> with <code>eq</code> to create the group key , then using <code>groupby</code> <code>sort_values</code>+<code>tail</code> </p>
<pre><code>m=(df.C1.shift().ne(df.C1)&df.C1.eq('a')).cumsum()
df.sort_values('C2').groupby(m).tail(1)
Out[62]:
C1 C2
4 b 4
11 ... | python|pandas | 1 |
362,076 | 53,498,097 | Sampling points from multiple Gaussians | <p>If I have one Gaussian with center=[x, y] and std=z I can sample one point using:</p>
<pre><code>np.random.normal(loc=[x, y], scale=std)
</code></pre>
<p>But if I'm given two Gaussians with centers=[[x1, y1], [x2, y2]] and stds=[z1, z2] how can I sample points from these Gaussians together (or for n Gaussians)</p> | <p>You could just loop,</p>
<pre><code>import numpy as np
x1 = 0.; y1=0.; z1 = 1.
x2 = 1.; y2=0.; z2 = 1.
centers=[[x1, y1], [x2, y2]]
stds=[z1, z2]
np.random.seed(1)
smpl = []
for c, std in zip(centers, stds):
smpl.append(np.random.normal(loc=c, scale=std))
print(smpl)
</code></pre>
<p>but passing as lists al... | python|numpy | 0 |
362,077 | 53,593,081 | Applying .rolling to a pandas dataframe with objects | <p>I have two pandas dataframes with one column each. One has floating values as entries:</p>
<pre><code>a=pandas.DataFrame([[2],[5],[7]])
</code></pre>
<p>whist the other one consists of tuples of values, such as:</p>
<pre><code>b=pandas.DataFrame([[(1,2)],[(4,5)],[(6,7)]])
</code></pre>
<p>I want to use a rolling... | <p>something like this will help - </p>
<pre><code>b[0].apply(pd.Series).rolling(2).apply(lambda x: x[1]-x[0]).apply(tuple, axis=1)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>0 (nan, nan)
1 (3.0, 3.0)
2 (2.0, 2.0)
dtype: object
</code></pre> | python|pandas | 0 |
362,078 | 53,657,219 | `Could not find method jackOptions() for arguments` when building Tensorflow Lite demo | <p>I'm trying to build the demo app in Tensorflow Lite:</p>
<p><a href="https://www.tensorflow.org/lite/demo_android" rel="nofollow noreferrer">https://www.tensorflow.org/lite/demo_android</a></p>
<p>Relevant versions:</p>
<ul>
<li>Tensorlow Lite: 1.12</li>
<li>Android Studio: 3.2.1</li>
<li>Android Sdk: android-28<... | <p>It appears that you can pass this build error by commenting out lines 15, 16, 17 in <code>tensorflow/lite/java/demo/app/build.gradle</code> in the demo app provided in the demo source.</p>
<pre><code>jackOptions {
enabled true
}
</code></pre>
<p>This moved me onto another build error at least. I may update thi... | android|tensorflow | 0 |
362,079 | 53,491,708 | How would I group by unique values that are in a list form? | <p>If I wanted to get the mean of the past 2 values based on column <code>id</code>, I would do the following:</p>
<pre><code>df['rolling_mean_2'] = df.groupby('id').apply(lambda x: x.rolling(2, min_periods=2).mean())
>> id value rolling_mean_2
0 b 1 NaN
1 b 3 2
2 d ... | <p>Using <code>concat</code> with dataframe constructor recreate the dataframe </p>
<pre><code>df=df.rename(columns={'value':'V'})
newdf=pd.concat([df.V,pd.DataFrame(df.id.tolist(),index=df.index)],axis=1)
</code></pre>
<p>Then , Using <code>melt</code> with <code>groupby</code> <code>rolling</code> <code>mean</code>... | python|python-3.x|pandas|lambda|pandas-groupby | 4 |
362,080 | 53,703,725 | python. matplotlib. plot values based on other column's values (parallel lines) | <p>lets say that i have following dataframe, and i want to time to x axis, and vls and id to y axis. but i want to group line ids, to see the separet line ids and their corresponding 'vls'. so far i used 'groupby'
'</p>
<pre><code>df = pd.DataFrame({'vls': [ -22.0390625, -22.03515625, -27.0, -15.99609375, -10.984375, ... | <p>You are still using the original dataframe, while you did use group correctly. I think you intended the following:</p>
<pre><code>from numpy import *
from matplotlib.pyplot import *
import pandas as pd
df = pd.DataFrame({'vls': [ -22.0390625, -22.03515625, -27.0, -15.99609375, -10.984375, -12.9765625, -12.97265625,... | python|pandas|matplotlib|plot|group-by | 1 |
362,081 | 53,786,591 | pandas groupby nlargest doesn't allow to see all the data set_index issue | <p>I want to see 2-top values for each year. </p>
<pre><code>df = pd.DataFrame({'year':[2018, 2018, 2018, 2017, 2017, 2006],'value':[1,2,3,4,5,6], 'title':['a', 'b', 'c', 'd','e','f'], 'smth1':[6,6,4,5,6,4],
'smth2':[9,8,7,6,5,2], 'smth3': [2,2,3,3,4,4]})
</code></pre>
<p>I use idea from here to prevent loosing cols... | <p>IIUC</p>
<pre><code>df.sort_values('value').groupby('year').tail(2)
Out[148]:
year value title smth1 smth2 smth3
1 2018 2 b 6 8 2
2 2018 3 c 4 7 3
3 2017 4 d 5 6 3
4 2017 5 e 6 5 4
5 2006 6 f 4... | python-3.x|pandas|pandas-groupby | 0 |
362,082 | 53,509,744 | pandas - read_excel efficiency on multiple large sheets | <p>I have an Excel workbook with multiple sheets. Some contain lots of data (f.e. 6000000 cells), and some do not. I'm attempting to read one of the sheets that's significantly smaller, a simple 2 column - 500 row sheet using the following line of code:</p>
<pre><code>df = pd.read_excel('C:/Data.xlsx', sheetname='Cont... | <p>I tried to look at the API to help on how the function works for processing it but didn't come up with anything big. Few things of note:</p>
<p>1) assuming you are using 0.21.0 on wards you want to use sheet_name instead of sheet name</p>
<p>2) according to: <a href="https://realpython.com/working-with-large-excel... | python|excel|pandas | 1 |
362,083 | 53,358,518 | Decoder targets required for RNN inference | <p>I have been trying to run some experiments using the deepfix tool (<a href="https://bitbucket.org/iiscseal/deepfix" rel="nofollow noreferrer">https://bitbucket.org/iiscseal/deepfix</a>) which is a <code>seq2seq</code> model for correcting common programming errors.
I made changes to the code so that it is compatible... | <ol>
<li><p>Well, <code>SampleEmbeddingHelper</code> does need decoder targets, since it mixes part of <code>GreedyEmbeddingHelper</code>(infer mode) and <code>tf.contrib.seq2seq.TrainingHelper</code>(teacher forcing). I think you just need to use <code>GreedyEmbeddingHelper</code>.</p></li>
<li><p>Since in the beginni... | python|tensorflow|lstm|rnn|seq2seq | 0 |
362,084 | 53,541,156 | How to remove all occurrences of an element from NumPy array? | <p>The title is pretty self-explanatory: I have an numpy array like (let's say ints)
<code>[ 1 2 10 2 12 2 ]</code> and I would like to remove all occurrences of <code>2</code>, so that the resulting array is <code>[ 1 10 12 ]</code>. Preferably I would like to do this as fastest as possible, because I am using relativ... | <p>You can use indexing:</p>
<pre><code>arr = np.array([1, 2, 10, 2, 12, 2])
print(arr[arr != 2])
# [ 1 10 12]
</code></pre>
<p>Timing is pretty good:</p>
<pre><code>from timeit import Timer
arr = np.array(range(5000))
print(min(Timer(lambda: arr[arr != 4999]).repeat(500, 500)))
# 0.004942436999999522
</code></pre> | arrays|python-3.x|numpy|scipy | 7 |
362,085 | 53,510,860 | numpy logical.xor on a 2D array | <p>I have a 2D numpy array with only <code>0</code> and <code>255</code> values (created from a black and white image) that i'd like to XOR with another similar 2D array.</p>
<p>The <code>dtype</code> of these arrays is <code>uint8</code> and their shapes are identical.</p>
<p>The only information and examples i've b... | <p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_xor.html" rel="nofollow noreferrer"><code>numpy.logical_xor</code></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bitwise_xor.html#numpy.bitwise_xor" rel="nofollow noreferrer"><code>numpy.bitwise_xor</code></a> w... | arrays|numpy|python-2.x | 3 |
362,086 | 53,640,124 | Select column from multiple DataFrames based on same header prefix | <p>I have a function that iterates over the rows of a <code>csv</code> for the <code>Age</code> column and if an age is negative, it will print the <code>Key</code> and the <code>Age</code> value to a text file.</p>
<pre><code>def neg_check():
results = []
file_path = input('Enter file path: ')
file_data =... | <p>I would do this in one step, but there are a few options. One is <code>filter</code>:</p>
<pre><code>v = df[df.filter(like='AgeAt').iloc[:, 0] < 0]
</code></pre>
<p>Or, </p>
<pre><code>c = df.columns[df.columns.str.startswith('AgeAt')][0]
v = df[df[c] < 0]
</code></pre>
<p>Finally, to write to CSV, use </p... | python|python-3.x|pandas|dataframe | 2 |
362,087 | 53,574,680 | Python - Count the number of exact matches between one list and multiple lists | <p>First, I have an excel file (or csv file) which I have converted to a dataframe (<code>df</code>).</p>
<p>Next, there is one master list of strings in the first column, which contains alphanumeric characters.</p>
<p>Then, there are lists of strings in subsequent columns, which can be the same length (<code>list1</... | <p>With :</p>
<pre><code> master_list list1 list2 list3
0 abc abc abc stu
1 def xxx def zzz
2 ghi xxx yyy zzz
3 jkl xxx yyy zzz
4 mno1 xxx yz1 zzz
5 pqr xxx NaN zzz
6 stu xxx NaN zzz
7 vwx xxx NaN z... | python|pandas|dataframe | 1 |
362,088 | 53,419,788 | Creating an array by adding to shape of existing array | <p>I have a numpy array:</p>
<pre><code>X = np.array([[1,0,1],
[1,1,1],
[0,1,0],
[1,0,1]])
</code></pre>
<p>which has a shape of <code>(4,3)</code></p>
<p>I would like to change this shape into <code>(4,4)</code> by adding 1 to the second dimension of the array, via:</p>
<p... | <p>To fix your code, do this instead:</p>
<pre><code>X_b = np.ones(X.shape + np.array((0,1)))
</code></pre>
<p>The catch here is that <code>X.shape</code> returns a plain Python <code>tuple</code>. By adding <code>(0,1)</code> you were actually performing tuple concatenation, instead of pairwise addition like you int... | python|arrays|numpy|shapes | 1 |
362,089 | 53,469,327 | Adding values to DataFrame from CSV file based on key identifier? | <p>I am currently merging three different data-sets, where all three sets contain a special identifier which in one of the sets can appear multiple times.</p>
<p>Now I created a dataFrame from my main .csv file, and want to add values to this data frame iff the identifier is the exact same in the other .csv files. </p... | <p>Use merge:</p>
<pre><code>df = df.merge(df_2, how='left', on='id_name')
</code></pre>
<p>where <code>on='id_name'</code> your identifier.</p>
<p>Your can read more here <a href="https://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/mergin... | python|pandas | 0 |
362,090 | 53,408,133 | Python - convert list of lists into matrix | <p>I am using python, I have a list which contains inside it group of lists
how can I convert it into one matrix?</p>
<p>for example, </p>
<pre><code>Root_List = [list1 list2 list3]
list1 = [1 2 3]
list2 = [1 5 9]
list3 = [2 4 1]
</code></pre>
<p>I need matrix to have below value</p>
<pre><code>[
1 2 3
1 5 9
2 4... | <p>If they all have the same length, try this:</p>
<pre><code>import numpy as np
list1 = [1,2,3]
list2 = [1,5,9]
list3 = [2,4,1]
Root_List = [list1, list2,list3]
np.array(Root_List)
</code></pre> | python|python-3.x|numpy|arraylist | 2 |
362,091 | 53,742,832 | Is there a way to use Lists as values in a DataFrame? | <p>I'm dealing with the famous Kaggle challenge "House prices".
I want to train my Dataset with sklearn.linear_model LinearRegression</p>
<p>After reading the following article:
<a href="https://developers.google.com/machine-learning/crash-course/representation/feature-engineering" rel="nofollow noreferrer">https://de... | <p><code>LinearRegression</code> does not support list as a feature. I saw you're using one-hot, and you can use each dimension as a column of features. By contrast, you can use the simpler method <code>pd.get_dummies</code> in pandas.</p>
<pre><code>print(df['feature'])
0 Ex
1 Gd
2 Ta
3 Po
Name: feature, ... | python|linear-regression|sklearn-pandas | 1 |
362,092 | 53,637,278 | How to use a good use of nb_train_samples in keras? | <p>I'm using keras with Tensorflow-gpu backend in Python. I'm trying to put the correct number of nb_train_samplesn nb_validation_ samples and epochs.
I am using the fit-generator-method.</p>
<ul>
<li><p>nb_train_samples has to be the same number that images that i have for training? Can be higher?</p></li>
<li><p>nb_... | <p>Yes, they have to be the same. These are the parameters you use to tell the process how many you have of each type of image. For instance, if you tell it that you have 5_000 validation samples, but there are only 3_000 in the data set, you will crash the run.</p> | python|tensorflow|keras|deep-learning | 1 |
362,093 | 53,650,422 | Matrix special multiplication in numpy | <p>I have two array m1 and m2 and I want to make a special multiplication :
1*8 + 2*6, 3*8 + 4*6, 1*2 + 2*6, 3*2 + 4*6, ...
So I want this output. result = [20, 48, 14,30,..]</p>
<pre><code>m1 = np.array([1,2,3,4])
m2 = np.array([8,6,2,6,2,5])
</code></pre>
<p>I'm sorry but I don't really know how to do that.
I think... | <p>So obviously, your scalar products must be done 2 by 2, so you need to start reshaping your data:</p>
<pre><code>m1 = np.array([1,2,3,4]).reshape(2,2)
m2 = np.array([8,6,2,6,2,5]).reshape(3,2)
</code></pre>
<p>So now, you want the dot product of on the last column, and flatten the result, so do:</p>
<pre><code>np... | python|numpy|matrix|multiplication | 1 |
362,094 | 53,763,147 | How to write strings into a csv file | <p>I am trying to create a csv file with a single column of file paths. I need a second column filled with ones.</p>
<p>The result I want to get is as follows;</p>
<pre><code>./1/a_1.csv, 1
./1/a_2.csv, 1
./1/a_3.csv, 1
</code></pre>
<p>The code I tried is this;</p>
<pre><code>import numpy as np
data=np.chararray(... | <p>You don't need Numpy for this. Just do something like</p>
<pre><code>with open('a.csv', 'w') as outf:
for i in range(650):
print('./1/a_%s.csv, 1' % (i + 1), file=outf)
</code></pre>
<p>and you're golden.</p> | python|python-3.x|csv|numpy | 5 |
362,095 | 53,770,841 | How to get JSON into Pandas dataframe with windows authentication | <p>I'm trying to read json from intranet site that's using windows authentication into pandas dataframe using read_json function but I'm getting 401 error. </p>
<p>A bit of googling showed that a similar issue with postman reading windows authenticated json was solved using Fiddler's "Automatically Authorize" functio... | <ul>
<li>Is the URL on your corporate intranet? </li>
<li><p>Do you normally enter it in the browser, then it pauses for a 10 .sec and you get the results without any password prompts?</p>
<p>If the above is true, it probably uses Kerberos authentication. You can certainly get it using python. Use here is the pac... | python|pandas | 1 |
362,096 | 53,583,255 | Seam insertion coordinates - Seam Carving | <p>I'm having some trouble understanding seam insertion for image enlarging with Seam Carving. AFIK to enlarge an image by k pixels it's necessary to remove k seams, recording their coordinates and using them to reproduce the process backwards, i.e. re-add the deleted seams but duplicating them and applying some kind o... | <p>As pointed out in the cooments, you have to fix indices anyway when inserting even if you can avoid "fixing" in removal part.</p>
<p>You can find a full implementation of seam carving and seam insertion in python <a href="https://github.com/andrewdcampbell/seam-carving/blob/master/seam_carving.py" rel="nof... | python|image|algorithm|numpy|seam-carving | 0 |
362,097 | 53,459,022 | Apply a dictionary to text data | <p>I have the following dictionary:</p>
<pre><code>{0: 'group',
1: 'still',
2: 'earnings',
3: 'shares',
4: 'make',
5: 'finally',
6: 'amazon',
7: 'deals',
8: 'comes',
9: 'york',
10: 'iphones'}
print(df)
0 1 2 ... 53 54 55
0 Group still sh... | <p>Use:</p>
<pre><code>print (df)
0 1 2 53 54 55
0 Group still shares deals york iphones
1 amazon shares make finally iphones aa
</code></pre>
<p>First swap keys with values to new dictionary:</p>
<pre><code>d1 = {v:k for k, v in d.items()}
</code></pre... | python|pandas|dictionary | 1 |
362,098 | 53,606,277 | How To ReShape a Numpy Array in Python | <p>I have a <code>numpy array</code> of images with the shape of <code>(5879,)</code>. Inside every index of the numpy array, I have the Pixels of the image with a shape of <code>(640,640,3)</code>.
I want to reshape the complete array in such a way that the shape of the numpy array becomes <code>(5879,640,640,3)</code... | <p>You want to stack your images along the first axis, into a 4D array. However, your images are all 3D.
So, first you need to <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.expand_dims.html" rel="nofollow noreferrer">add a leading singleton dimension</a> to all images, and then to <a href="... | python|python-3.x|numpy|image-processing|image-segmentation | 0 |
362,099 | 53,618,606 | pandas set and use new value of line before | <p>I want to reuse a pandas column value of a line and reusing this value for all the following lines. </p>
<pre><code>df = pd.DataFrame({'A' : [1,2,3,4,5,6],
'B' : [2,3,4,5,6,7]})
df.loc[df.A < df.B, 'C'] = df.B.shift(1)
print(df)
</code></pre>
<p>gives me:</p>
<pre><code> A B C
0 1 2 N... | <p>You can use idxmax. If the condition is True, get the most recent value in column C, else C = A * B. </p>
<pre><code>df = pd.DataFrame({'A' : [1,2,3,4,5,6],'B' : [2,3,4,5,6,7]})
df['C'] = df['A'] * df['B']
df['C'] = np.where(df.A < df.B, df.loc[(df.A < df.B).idxmax(), 'C'], df.C)
A B C
0 1 2 2
... | python|pandas | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.