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 |
|---|---|---|---|---|---|---|
375,300 | 52,543,312 | Iterate numbers in a df where a condition matches | <p>Playing around with different data frames whilst trying to teach myself Pandas, this has had me stumped fora while, which seems like a lack in programming comprehension, but could anyone help?</p>
<p>Consider the following df:</p>
<pre><code>ID Name Week
1 Matthew 1751
1 Mat... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>groupby.cumcount</code></a></p>
<pre><code>df['Week'] = df.Week.add(df.groupby('Name').cumcount())
ID Name Week
0 1 Matthew 1751
1 1 Matthew 1752
2 1 Ma... | python|pandas | 6 |
375,301 | 52,819,641 | Removing multiple characters and joining in pandas columns | <p>I am trying to format this string but excluding the characters: <strong>(</strong> <strong>)</strong></p>
<pre><code>My_name (1)
Your_name (2)
</code></pre>
<p>Desired output:</p>
<pre><code>My_name_ID_1
Your_name_ID_2
</code></pre>
<p>This is a column of my dataframe.I tried replacing but only one character at... | <p>You can use a regular expression with <code>str.replace</code>:</p>
<pre><code>s.str.replace(r'(\w+)\s+\(([^\)])\)', r'\1_ID_\2')
</code></pre>
<p></p>
<pre><code>0 My_name_ID_1
1 Your_name_ID_2
Name: 0, dtype: object
</code></pre>
<p>An alternative is:</p>
<pre><code>s.str.replace(r'\s+\(([^\)])\)', r'... | python|string|pandas|dataframe|join | 2 |
375,302 | 52,809,314 | How to plot multi-index, categorical data? | <p>Given the following data:</p>
<pre><code>DC,Mode,Mod,Ven,TY1,TY2,TY3,TY4,TY5,TY6,TY7,TY8
Intra,S,Dir,C1,False,False,False,False,False,True,True,False
Intra,S,Co,C1,False,False,False,False,False,False,False,False
Intra,M,Dir,C1,False,False,False,False,False,False,True,False
Inter,S,Co,C1,False,False,False,False,Fals... | <p><strong>Explanation</strong>: Remove rows where <code>TY1</code>-<code>TY8</code> are all <code>nan</code> to create your plot. Refer to <a href="https://stackoverflow.com/a/47166787/5492877">this answer</a> as a starting point for creating interactive annotations to display <code>Ven</code>.</p>
<p>The below code ... | python-3.x|pandas|matplotlib|data-visualization|bokeh | 1 |
375,303 | 52,640,036 | keras with tensorflow backend: layer implementation when batch_size is used, but it is None during graph construction | <p>I am implementing a keras layer <code>AnchorTargets</code> for retinanet in object detection, it inputs <code>anchors</code> and <code>annotations</code> (i.e. ground-truth bounding-boxes). The ideas for the codes are motivated by <a href="https://github.com/fizyr/keras-retinanet" rel="nofollow noreferrer">keras-ret... | <p>Never mind. I have figured it out. The basic idea is to avoid the use of input_shape[0] (i.e. batch size) in <code>call</code> function of <code>keras.layers.Layer</code>. My implementation is as follows if anyone is interested in it.</p>
<pre><code>def batch_anchor_targets_bbox(
anchors,
annotations,
num_classes,
... | python|tensorflow|keras | 0 |
375,304 | 52,451,797 | How does the reshape work before the fully connected layer in the following CNN model? | <p>Consider the convolutional neural network (two convolutional layers):</p>
<pre><code>class ConvNet(nn.Module):
def __init__(self, num_classes=10):
super(ConvNet, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
nn.BatchNo... | <p>If you look at the output of each layer you can easily understand what you are missing. </p>
<pre><code>def forward(self, x):
print ('input', x.size())
out = self.layer1(x)
print ('layer1-output', out.size())
out = self.layer2(out)
print ('layer2-output', out.size())
out = out.reshape(out.si... | python|deep-learning|conv-neural-network|pytorch | 3 |
375,305 | 52,588,827 | For loop - running 1 loop to completion then running next loop python | <p>this script needs to run all the way through RI_page_urls.csv, then run through all the resulting urls from RI_License_urls.csv and grab the business info. </p>
<p>it's pulling all the url's from RI_page_urls.csv, but then only running and printing the first of 100 urls from RI_License_urls.csv. Need help figurin... | <p>Well , The question is a bit unclear and also there are a couple of things wrong about the code </p>
<pre><code>data = r.get(url[0])
</code></pre>
<p>should be because its urls start with http or https not www</p>
<pre><code>data = r.get("http://"+url[0])
</code></pre>
<p>In the below code ,</p>
<p><code>info</... | python|pandas|loops|beautifulsoup|with-statement | 1 |
375,306 | 52,570,086 | Plotting numpy array using Seaborn | <p>I'm using python 2.7. I know this will be very basic, however I'm really confused and I would like to have a better understanding of seaborn.</p>
<p>I have two numpy arrays <code>X</code> and <code>y</code> and I'd like to use Seaborn to plot them.</p>
<p>Here is my <code>X</code> numpy array:</p>
<pre><code>[[ 1... | <p>You can use seaborn functions to plot graphs. Do dir(sns) to see all the plots. Here is your output in <code>sns.scatterplot</code>. You can check the api docs <a href="https://seaborn.pydata.org/generated/seaborn.scatterplot.html" rel="noreferrer">here</a> or example code with plots <a href="https://python-graph-ga... | python|numpy|matplotlib|machine-learning|seaborn | 10 |
375,307 | 52,716,910 | Cannot train a model with numpy array | <p>I am training the following autoencoder on float numbers. </p>
<pre><code>input_img = Input(shape=(2623,1), name='input')
x = ZeroPadding1D(1)(input_img)
x = Conv1D(32, 3, activation='relu', padding='same', use_bias=False)(input_img)
x = BatchNormalization(axis=-1)(x)
x = MaxPooling1D(2, padding='same')(x)
x = Con... | <p>Perhaps, as a preprocessing step, you can typecast your object type array to a float array using something like:</p>
<pre><code># if float32 is the desired & appropriate datatype
train = train.astype(numpy.float32)
</code></pre> | python|numpy|neural-network|deep-learning|autoencoder | 1 |
375,308 | 52,612,874 | Pandas - replace for loop for efficiency | <p>I have a data frame (df)</p>
<pre><code>df = pd.DataFrame({'No': [123,234,345,456,567,678], 'text': ['60 ABC','1nHG','KL HG','21ABC','K 200','1g HG'], 'reference':['ABC','HG','FL','','200',''], 'result':['','','','','','']}, columns=['No', 'text', 'reference', 'result'])
No text reference result
0 123 60 ... | <p>Instead of iterating rows, you can iterate your suffixes, which is likely a much smaller iterable. This way, you can take advantage of series-based methods and Boolean indexing.</p>
<p>I've also created an extra series to identify when a row has been updated. The cost of this extra check should be small versus the ... | python|pandas|performance|for-loop|dataframe | 2 |
375,309 | 52,783,479 | How does Pandas compute exponential moving averages under the hood? | <p>I am trying to compare <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ewm.html" rel="nofollow noreferrer">pandas EMA</a> performance to <a href="https://numba.pydata.org/numba-doc/dev/index.html" rel="nofollow noreferrer">numba</a> performance.</p>
<p>Generally, I don't write funct... | <blockquote>
<p>But here I am interested in how numba outperforms Pandas in calculating exponential moving averages.</p>
</blockquote>
<p>Your version appears to be faster solely because you're passing it a NumPy array rather than a Pandas data structure:</p>
<pre><code>>>> s = pd.Series(np.random.random(1... | python|arrays|pandas|time|numba | 1 |
375,310 | 52,715,499 | How to serve a tensorflow-module, specifically Universal Sentence Encoder? | <p>I have spent several hours trying to set up Tensorflow serving of the Tensorflow-hub module, "Universal Sentence Encoder." There is a similar question here:</p>
<p><a href="https://stackoverflow.com/questions/50788080/how-to-make-the-tensorflow-hub-embeddings-servable-using-tensorflow-serving">How to make the tenso... | <p>I was finally able to figure things out. I'll post what I did here in case someone else is trying to do the same thing.</p>
<p>My issue with the saved_model_cli run command was with the quotes (using Windows command prompt). Change <code>'text=["what this is"]'</code> to <code>"text=['what this is']"</code></p>
<p... | python|tensorflow|tensorflow-serving|tensorflow-hub | 17 |
375,311 | 52,750,553 | Having problems converting strings to floats in pandas data frame | <p>Trying to make a scatter plot with a pandas dataframe, but "ValueError: x and y must be the same size" kept popping up. Looks like Slaughter Steers data column are strings instead of floats so try to convert it, but ValueError: could not convert string to float: '1,062.6' happens. Tried to replace ' with a space sti... | <p>Believe the commas (thousands separators) are preventing the conversion. This question has possible solutions that may help you:</p>
<p><a href="https://stackoverflow.com/questions/1779288/how-do-i-use-python-to-convert-a-string-to-a-number-if-it-has-commas-in-it-as-th">How do I use Python to convert a string to a ... | python|pandas | 0 |
375,312 | 52,858,015 | Create series of tuples from pandas DataFrame efficiently | <p>I am using <code>apply()</code> to construct a Series of tuples from the values of an existing DataFrame. I need to construct a specific order of the values in the tuple, and replace <code>NaN</code> in all but one column with <code>'{}'</code>. </p>
<p>The following functions work to produce the desired result, bu... | <h3><code>zip</code>, <code>get</code>, <code>mask</code>, <code>fillna</code>, and <code>sorted</code></h3>
<p>One liner for what it's worth</p>
<pre><code>df.assign(
insert_vals=
[*zip(*map(df.mask(df.isna(), {}).get, sorted(df, key=lambda x: x != 'v2')))])
id v1 v2 insert_vals
0 1.0 foo ... | python|python-2.7|pandas | 3 |
375,313 | 52,564,644 | Pandas Dataframe Turned my Dictionaries into String | <p>I have a dataframe, each cell saves a dictionary. Before exporting the dataframe, I could call each cell as an individual dataframe. </p>
<p>However, after saving the dataframe as csv and reopening this each cell became string so I could not turn the cell I called into a dataframe anymore. </p>
<p><a href="https:/... | <p>CSV is not an appropriate format for saving dictionaries (and honestly, putting dictionaries into DataFrames isn't a great data structure). You should try writing the DataFrame to json instead: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html" rel="nofollow noreferrer">ht... | python|string|pandas|dictionary|dataframe | 2 |
375,314 | 52,507,748 | Using multiple CPU cores in TensorFlow | <p>I have extensively studied other answers on TensorFlow and I just cannot seem to get it to use multiple cores on my CPU.</p>
<p>According to htop, the following program only uses a single CPU core:</p>
<pre><code>import tensorflow as tf
n_cpus = 20
sess = tf.Session(config=tf.ConfigProto(
device_count={ "CPU... | <p>After some back and forth on the <a href="https://github.com/tensorflow/tensorflow/issues/22619" rel="noreferrer">TensorFlow issue here</a> we determined that the issue was that the program was being "optimized" by a constant folding pass, because the inputs were all trivial. It turns out this constant folding pass ... | python|multithreading|tensorflow|parallel-processing|affinity | 5 |
375,315 | 52,850,196 | Take an element of a tensor which is inside also in another tensor | <p>I have two tensors and I have to iterate on the first to take only the element that is inside the other tensor. There is only one element in <code>t2</code> that it is also inside <code>t1</code>. Here an example</p>
<pre><code>t1 = tf.where(values > 0) # I get some indices example [6, 0], [3, 0]
t2 = tf.where(v... | <p>Is that what you wanted ? I used just these two test cases.</p>
<pre><code>x = tf.constant([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 1]])
y = tf.constant([[1, 2, 3, 4, 3, 6], [1, 2, 3, 4, 5, 1]])
# x = tf.constant([[1, 2], [4, 5], [7, 7]])
# y = tf.constant([[7, 7], [3, 5]])
def match(xiterations, yiterations, yvalues,... | python|tensorflow | 1 |
375,316 | 52,524,851 | Broadcast a 1D array using a 2D array | <p>I have a 1D array <code>array_data</code> with ~10**8 elements. </p>
<p>I have a second array <code>array_index</code> which specifies the <strong>bound</strong>ing indices used to slice <code>array_data</code> with.</p>
<p>Below is Minimal, Complete, and Verifiable example of <code>array_data</code> and <code>arr... | <p>When I run your code I get a list of arrays of varying size:</p>
<pre><code>In [63]: [len(x) for x in array_sliced]
Out[63]: [3, 46, 38, 9, 73, 66, 3, 23, 40, 36]
</code></pre>
<p>(you also get this from <code>np.diff(array_index,axis=1)</code>)</p>
<p>A general observation is that when dealing arrays of differin... | python|list|numpy|list-comprehension|numpy-slicing | 1 |
375,317 | 52,711,175 | Restarting a countdown based on another column | <p>I have a data frame with a variable called 'Countdown' that counts down the days in my data frame even though some days have multiple entries (rows).</p>
<pre><code> full dates Countdown
0 2008-01-01 3652
1 2008-01-02 3651
2 2008-01-03 3650
3 2008-01-04 364... | <p>You can do this with <code>pd.merge_asof</code>. Create a <code>DataFrame</code> of your right bin edges, then merge the closest edge and calculate the number of days until. </p>
<pre><code>import pandas as pd
# Right bin edges for your countdowns.
dates = ['2008-01-03', '2008-01-06']
df_dates = pd.DataFrame({'da... | python|pandas|dataframe | 1 |
375,318 | 52,715,049 | Comparing numpy array of dtype object | <p>My question is "why?:"</p>
<pre><code>aa[0]
array([[405, 162, 414, 0,
array([list([1, 9, 2]), 18, (405, 18, 207), 64, 'Universal'],
dtype=object),
0, 0, 0]], dtype=object)
aaa
array([[405, 162, 414, 0,
array([list([1, 9, 2]), 18, (405, 18, 207), 64, 'Universal'],
dtype=object),
... | <p>To make an element-wise comparison between the arrays, you can use <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.equal.html" rel="nofollow noreferrer"><strong><code>numpy.equal()</code></strong></a> with the keyword argument <code>dtype=numpy.object</code> as in :</p>
<pre><code>In [60]... | python|python-3.x|numpy | 5 |
375,319 | 52,635,026 | pandas dataframe filtering multiple columns and rows | <p>Given a dataframe with the following format:</p>
<pre><code>TEST_ID | ATOMIC_NUMBER | COMPOSITION_PERCENT | POSITION
1 | 28 | 49.84 | 0
1 | 22 | 50.01 | 0
1 | 47 | 0.06 | 1
2 | 22 | 49.84 | 0... | <p>You can create a boolean series to capture test_ids and then index the df using the same.</p>
<pre><code>s = df[df['POSITION'] == 0].groupby('TEST_ID').apply(lambda x: ((x['ATOMIC_NUMBER'].count() == 2 ) & (sorted(x['ATOMIC_NUMBER'].values.tolist()) == [22,28])).all())
test_id = s[s].index.tolist()
df[df['TES... | python|pandas | 1 |
375,320 | 52,561,762 | Count occurrences of number from specific column in python | <p>I am trying to do the equivalent of a COUNTIF() function in excel. I am stuck at how to tell the .count() function to read from a specific column in excel.</p>
<p>I have</p>
<pre><code>df = pd.read_csv('testdata.csv')
df.count('1')
</code></pre>
<p>but this does not work, and even if it did it is not specifi... | <p>If all else fails, why not try something like this?</p>
<pre><code>import numpy as np
import pandas
import matplotlib.pyplot as plt
df = pandas.DataFrame(data=np.random.randint(0, 100, size=100), columns=["col1"])
counters = {}
for i in range(len(df)):
if df.iloc[i]["col1"] in counters:
counters[df.il... | python|pandas | 0 |
375,321 | 46,620,844 | how to compute pairwise distance among series of different length (na inside) efficiently? | <p><em>resuming this question</em>: <a href="https://stackoverflow.com/questions/24781461/compute-the-pairwise-distance-in-scipy-with-missing-values">Compute the pairwise distance in scipy with missing values</a></p>
<p>test case: I want to compute the pairwise distance of series with different length taht are grouped... | <p>Inspired by <a href="https://stackoverflow.com/a/44157144/"><code>this post</code></a>, there would be two solutions.</p>
<p><strong>Approach #1 :</strong> The vectorized solution would be -</p>
<pre><code>ar = a.values
r,c = np.triu_indices(ar.shape[0],1)
out = np.sqrt(np.nansum((ar[r] - ar[c])**2,1))
</code></pr... | python|numpy|scipy|vectorization|pdist | 3 |
375,322 | 46,606,633 | tensorflow: gradients for a custom loss function | <p>I have an LSTM predicting time series values in tensorflow.
The model is working using an MSE as a loss function.
However, I'd like to be able to create a custom loss function where one of the error values is multiplied by two (therefore producing a higher error value).</p>
<p>In my batch of size 10, I want the 3rd... | <p>I believe the psuedo code would look something like this:</p>
<pre><code>@tf.custom_gradient
def loss_function(y_true, y_pred, peak_value=3, weight=2)
## your code
def grad(dy):
return dy * partial_derivative
return loss, grad
</code></pre>
<p>Where <code>partial_derivative</code> is the analyt... | python|tensorflow|neural-network | 1 |
375,323 | 46,519,539 | How to select all non-NaN columns and non-NaN last column using pandas? | <p>Forgive me if the title a little bit confusing.</p>
<p>Assuming I have <code>test.h5</code>. Below is the result of reading this file using <code>df.read_hdf('test.h5', 'testdata')</code></p>
<pre><code> 0 1 2 3 4 5 6
0 123 444 111 321 NaN NaN NaN
1 12 234 113 67 ... | <p>You can use sorted to satisfy your condition i.e </p>
<pre><code>ndf = df.apply(lambda x : sorted(x,key=pd.notnull),1)
</code></pre>
<p>This will give </p>
<pre>
0 1 2 3 4 5 6
0 NaN NaN NaN 123.0 444.0 111.0 321.0
1 12.0 234.0 113.0 67.0 21.0 32.0 900.0
3 ... | python|pandas|numpy|dataframe | 6 |
375,324 | 46,590,163 | Numpy eigenvalues/eigenvectors seem wrong for complex valued matrix? | <p>This may be something really stupid, but I am getting a rather weird output with Numpy, version 1.12.1. I am trying to diagonalise a random symmetric matrix, then check the quality by transforming back the diagonal eigenvalue matrix, but it seems to fail for complex values. Basically:</p>
<pre><code>A = np.random.r... | <p>The answer to your question is that you failed to do the diagonalisation/matrix reconstruction properly. </p>
<pre><code>A = np.random.random((3, 3))+1.0j*np.random.random((3, 3))
A += A.T.conj()
evals, evecs = np.linalg.eig(A)
from scipy.linalg import inv
print(np.isclose(np.dot(evecs, np.dot(np.diag(evals), inv(e... | python|numpy|matrix | 2 |
375,325 | 46,590,920 | Deconvolutions/Transpose_Convolutions with tensorflow | <p>I am attempting to use <code>tf.nn.conv3d_transpose</code>, however, I am getting an error indicating that my filter and output shape is not compatible. </p>
<ul>
<li>I have a tensor of size [1,16,16,4,192]</li>
<li>I am attempting to use a filter of [1,1,1,192,192]</li>
<li>I believe that the output shape would be... | <blockquote>
<ul>
<li>I have a tensor of size [1,16,16,4,192]</li>
<li>I am attempting to use a filter of [1,1,1,192,192]</li>
<li>I believe that the output shape would be [1,16,16,4,192]</li>
<li>I am using "same" padding and a stride of 1.</li>
</ul>
</blockquote>
<p>Yes the output shape will be [1,16,16... | tensorflow|conv-neural-network|deconvolution | 1 |
375,326 | 46,175,344 | Parsing a column of JSON strings | <p>I have a tab seperated flatfile, one column of which is JSON data stored as a string, e.g.</p>
<pre><code>Col1 Col2 Col3
1491109818 2017-08-02 00:00:09.250 {"type":"Tipper"}
1491110071 2017-08-02 00:00:19.283 {"type":"HGV"}
1491110798 2017-08-02 00:00:39.283 {"type":"Tipper"}
1491110798... | <p>Using <em><code>np.vectorize</code></em> and <em><code>json.loads</code></em></p>
<pre><code>import json
def foo(x):
try:
return json.loads(x)['type']
except (ValueError, KeyError):
return None
v = np.vectorize(foo)
df.Col3 = v(df.Col3)
</code></pre>
<p>Note that it is never recommended t... | python|json|performance|pandas|dataframe | 2 |
375,327 | 46,501,934 | Using count occurrences of a string in a pandas series | <p>I have a pandas series of lists with collection of words in them.I am trying to find frequency of a particular word in each list For e.g.,
the series is </p>
<pre><code>0 [All, of, my, kids, have, cried, nonstop, when...
1 [We, wanted, to, get, something, to, keep, tra...
2 [My, daughter, had, her, 1st, b... | <p>On your original series, use <code>str.findall</code> + <code>str.len</code>:</p>
<pre><code>print(series)
0 All of my kids have cried nonstop when
1 We wanted to get something to keep tra
2 My daughter had her 1st baby over a y
3 One of babys first and favorite books
4 Very cute interactiv... | python|string|pandas|count|series | 2 |
375,328 | 46,545,401 | label in python docstring | <p>I'm using sphinx autodoc to translate my docstring to a nice documentation page. In the docstring I'm following numpy's docstring guideline by using the sphinx napoleon extension. I'm wondering about the following: If I have an equation like</p>
<pre><code>"""
This is a very important equation which is used in the ... | <p>Be careful with whitespace and indentation. This works:</p>
<pre><code>.. math::
:label: important_eq
a+b=c
</code></pre>
<p>This works too (when the math content is only one line of text, it can be given as a directive argument):</p>
<pre><code>.. math:: a+b=c
:label: important_eq
</code></pre> | python-sphinx|mathjax|autodoc|numpydoc | 1 |
375,329 | 46,194,971 | Add legend names to a SVM plot in matplotlib | <p>I made a SVM plot from the Iris-dataset by using matplotlib and mlxtend in Jupyter notebook. I am trying to get the Species name on the legend of the plot instead of 0, 1 and 2. So far my code is :</p>
<pre><code>from sklearn import svm
from mlxtend.plotting import plot_decision_regions
X = iris[['SepalLengthCm', ... | <p>Another one with the help of handles and labels of current plot axes i.e </p>
<pre><code>handles, labels = plt.gca().get_legend_handles_labels()
plt.legend(handles, list(map(d.get, [int(i) for i in labels])) , loc= 'upper left') #Map the values of current labels with dictionary and pass it as labels parameter.
pl... | python|pandas|matplotlib|jupyter-notebook | 2 |
375,330 | 46,557,241 | Pad a dataframe with pane data | <p>I have a dataframe like this.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'User':['A','A','A','A','B', 'B'],
'Month':['2017-01-01','2017-03-01','2017-05-01','2017-09-01','2017-01-01','2017-05-01'],
'count':[2,2,2,2,5,5]})
</code></pre>
<p>I want to pad the data so ... | <pre><code>mux = pd.MultiIndex.from_product([
df.User.unique(),
pd.date_range('2017-01-01', periods=12, freq='MS')
], names=['User', 'Month'])
df.set_index(['User', 'Month']).reindex(mux, fill_value=0) \
.swaplevel(0, 1).reset_index()
Month User count
0 2017-01-01 A 2
1 2017-02-01 A ... | python|python-3.x|pandas|indexing | 5 |
375,331 | 46,547,319 | Error when parsing graph_def from string | <p>I am trying to run a very simple saving of a Tensorflow graph as .pb file, but I have this error when parsing it back:</p>
<pre><code>Traceback (most recent call last):
File "test_import_stripped_bm.py", line 28, in <module>
graph_def.ParseFromString(fileContent)
File "/usr/local/lib/python3.5/dist-pa... | <p>The problem here is that you are trying to parse a <a href="https://github.com/tensorflow/tensorflow/blob/635196732151e6d8638c189c52f4c4336ede81b6/tensorflow/core/protobuf/saved_model.proto" rel="noreferrer"><code>SavedModel</code></a> protocol buffer as if it were a <a href="https://github.com/tensorflow/tensorflow... | python|python-2.7|python-3.x|tensorflow|protocol-buffers | 13 |
375,332 | 46,581,018 | Converting many string values to categories | <p>I have a data frame with one column full of string values. They need to be converted into categories. Due to huge amount it would be inconvenient to define categories in dictionary. Is there any other way in pandas to do that?</p> | <p>I applied below command and it works:
df['kategorie']=action['kategorie'].astype('category')</p> | python|pandas | 0 |
375,333 | 46,332,479 | Store netCDF data in GeoDataFrame | <p>I need to perform some geometric operations with geometries from another source on a netCDF-file. Therefore I store the geometries (<code>shapely.geometry.Polygon</code>) from the other source in a <code>geopandas.GeoDataFrame</code>.</p>
<p>Next is to read a <code>netCDF</code> file into a <code>GeoDataFrame</code... | <p>Like @jhamman mentioned in the comments, your lats and lons are indexes in your pandas frame. So starting with that</p>
<pre><code>import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
from io import StringIO
s = StringIO('''
lat,lon,hgt
-32.0,-73.00... | python|python-xarray|geopandas|shapely|netcdf4 | 3 |
375,334 | 46,550,371 | Python: np.nanpercentile, which datatype does my dataframe need to have? | <p>I have a panda dataframe of type object.</p>
<pre><code>df.dtypes
Out:
data object
stimulus object
trial object
dtype: object
df.head()
Out:
data stimulus trial
0 2 -2 1
1 2 -2 2
2 2 -2 3
3 2 -2 4
4 2 -2 ... | <p>This did the job for me in the end:</p>
<pre><code>df = df.astype(float)
</code></pre> | python|pandas|dataframe|percentile | 0 |
375,335 | 46,585,698 | Verify that points lie on a grid of specified pitch | <p>While I am trying to solve this problem in a context where numpy is used heavily (and therefore an elegant numpy-based solution would be particularly welcome) the fundamental problem has nothing to do with numpy (or even Python) as such.</p>
<p>The task is to create an automated test for an algorithm which is suppo... | <p>Change your assertion to:</p>
<pre><code>np.all(np.logical_or(np.isclose(x % y, 0), np.isclose((x % y) - y, 0)))
</code></pre>
<p>If you want to make it more readable, you should functionalize the statement. Something like: </p>
<pre><code>def is_multiple(x, y, rtol=1e-05, atol=1e-08):
"""
Test if x is a ... | numpy|floating-point | 1 |
375,336 | 46,588,641 | Python list into numpy array | <p>I have seen lots of example of lists into arrays, but no examples of lists in this format into arrays, which is strange because the list format I present is the standard go-to way of defining a graph, point-to-point mapping that you would find in any table, csv, database, etc. I tried everything <a href="https://doc... | <p>Here's one way to produce your adjacency matrix as a 2D Numpy array. It assumes that the input graph data is correct, in particular, that its length is a perfect square. </p>
<pre><code>import numpy as np
graph_data = [
['A', 'A', 0], ['A', 'B', 5], ['A', 'C', 3],
['B', 'A', 5], ['B', 'B', 0], ['B', 'C', ... | python|python-3.x|numpy | 2 |
375,337 | 46,244,901 | Tensorflow: GPU gradients for nested map_fn | <p>The piece of code below works fine when I am using the CPU as device, however it fails when using GPU. This is the error I am getting:</p>
<blockquote>
<p>InvalidArgumentError (see above for traceback): Cannot assign a device
for operation 'Adam/update_Variable/Cast_5': Could not satisfy
explicit device speci... | <p>I don't think this is related to the <strong>nested map_fn</strong> since the simple non-nested map_fn can cause that error: </p>
<pre><code>import numpy as np
import tensorflow as tf
def my_fn(x, y):
return x * y
with tf.device('/gpu:0'):
a = np.array([[1, 2, 3], [2, 4, 1], [5, 1, 7]])
b = np.array... | tensorflow|gpu|gradient | 0 |
375,338 | 46,269,294 | Convert a list of strings into a dataframe | <p>I have a list as follows:</p>
<pre><code>data_content=['Country', 'Capital', 'Currency', 'US', 'Washington', 'USD', 'India', 'Delhi', 'Rupee']
</code></pre>
<p>I want to have it as follows:</p>
<pre><code>Country Capital Currency
------------------------
US Washington USD
India Delhi Rupee
</code></pre>
... | <p>You can proceed as follows: </p>
<ol>
<li>Split the initial list into groups of 3 elements,</li>
<li>Take the first 3 elements as columns and the rest as data</li>
<li>Use the <code>pd.DataFrame</code> construct to create a <code>pandas.DataFrame</code>: </li>
</ol>
<p>Here's how the code looks like: </p>
<pre><... | python|list|pandas|numpy|dataframe | 1 |
375,339 | 46,268,344 | Numpy: Alternative ways to construct a matrix of points given the matrix of each coordinate separately | <p>Let x, y, z be matrix representations, so that (x[i, j], y[i, j], z[i, j]) corresponds to a certain point. </p>
<p>Instead of having 3 variables we want to have just one variable (Points) where "Points[i,j]=(x[i,j],y[i,j],z[i,j])" and "Points[i,j,0]=x[i,j]"</p>
<p>Example: </p>
<pre><code>import numpy as np
x = n... | <p>You can use numpy's <code>stack</code> function:</p>
<pre><code>import numpy as np
x = np.array([
[1, 1],
[2, 2],
])
y = np.array([
[1, 2],
[1, 2],
])
z = np.array([
[3, 4],
[5, 6],
])
points = np.stack([x, y, z], axis=2)
</code></pre>
<p><code>stack</code> with the <code>axis</code> k... | python|numpy|matrix|coordinates | 2 |
375,340 | 46,466,754 | Transposing each row data in to column data for each ID in Pandas dataframe | <p>My pandas datframe looks like this</p>
<pre><code>Id Length1 height1 Length2 height2
1 100 20 80 30
2 70 10 60 15
</code></pre>
<p>ALL Id's data need to be grouped for length/height of each measurement.</p>
<pre><code>Id 0 1 2 3
1 100 20 7... | <p><strong>Setup</strong> </p>
<pre><code>df = pd.DataFrame(dict(
Length1=[1, 2, 3],
Height1=[4, 5, 6],
Length2=[7, 8, 9],
Height2=[0, 1, 2]
))['Length1 Height1 Length2 Height2'.split()]
df
Length1 Height1 Length2 Height2
0 1 4 7 0
1 2 5 8 ... | python|pandas|dataframe | 3 |
375,341 | 46,498,784 | Some operations not respecting custom attributes in Series subclass | <p>According to <a href="https://pandas.pydata.org/pandas-docs/stable/internals.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/internals.html</a><br>
I should be able to sublcass a pandas Series</p>
<p>My <a href="http://stackoverflow.com/help/mcve">MCVE</a> is </p>
<pre><code>from panda... | <p>If you use <code>inspect.getsourcelines</code> to check the source code of these two functions <code>mul</code> and <code>__mul__</code>, you will find they actually have different implementations.</p>
<p>And using <code>s.mul(2).attr</code> still doesn't work as it just uses <code>__finalize__</code> to propagate... | python|pandas | 2 |
375,342 | 46,263,994 | Change decimal separator (Python, Sqlite, Pandas) | <p>I have an Excel spreadsheet (which is an extract from SAP) which has data in it (text, numbers). I turn this data into a DataFrame, do some calculations and finally save it to a sqlite database.
Whereas the excel spreadsheet has a comma as the decimal separator. The sqlite database includes the numbers with a dot as... | <p>You need to convert the <code>float</code> values before saving. Just loop through the column with values containing <code>.</code>, convert each value to string and then you can use <code>replace</code> method.</p>
<p>Here I converted all values in column <code>x</code></p>
<pre class="lang-py prettyprint-overrid... | python|excel|sqlite|pandas | 0 |
375,343 | 46,481,997 | How to use np.genfromtxt and fill in missing columns? | <p>I am trying to use <code>np.genfromtxt</code> to load a data that looks something like this into a matrix:</p>
<pre><code>0.79 0.10 0.91 -0.17 0.10 0.33 -0.90 0.10 -0.19 -0.00 0.10 -0.99 -0.06 0.10 -0.42 -0.66 0.10 -0.79 0.21 0.10 0.93 0.79 0.10 0.91 -0.72 0.10 0.25 0.64 0.10 -0.27 -0.36 0.10 -... | <p>Pandas has more robust readers and you can use the <code>DataFrame</code> methods to handle the missing values.</p>
<p>You'll have to figure out how many columns to use first:</p>
<pre><code>columns = max(len(l.split()) for l in open('data.txt'))
</code></pre>
<p>To read the file:</p>
<pre><code>import pandas
df... | python|numpy | 2 |
375,344 | 46,190,748 | Reformat Dataframe in pandas | <p>I have a Dataframe in a very weird format:</p>
<pre><code>id Code Week1 Week2 week3
sunday nan nan nan nan
id Code Week1 Week2 week3
1 100 y y n
2 200 n y n
3 300 n n y
Monday nan nan nan nan
id Code Week... | <p>Not my finest work... but I don't want to try anymore... it hurts my soul.</p>
<pre><code>d = df.query('id != "id"').replace(dict(id={'\d+': None}), regex=True).ffill()
s = d[d.duplicated('id')].set_index(['id', 'Code']).replace({'y': 1, 'n': np.nan}).stack()
s.rename_axis(['Day', 'Code', 'Week']).reset_index('Week... | python|pandas|dataframe | 3 |
375,345 | 46,579,435 | Fast way to calculate the average all the c grouped by (a, b) tuples from zip(a, b, c) | <p>I have <code>ddd</code> as <code>zip()</code> of three arrays; </p>
<pre><code>aaa = np.array([1, 1, 1, 1, 3, 2])
bbb = np.array([10, 10, 2, 2, 3, 2])
ccc = np.array([5, 15, 9, 11, 20, 10])
ddd = zip(aaa, bbb, ccc)
</code></pre>
<p>I would like to get average of elements in <code>ccc</code> grouped by the elements... | <p>I recommend you switch to using <a href="https://pandas.pydata.org/" rel="nofollow noreferrer">Pandas</a> for this task, as it makes it far simpler to reason about data in <em>rows</em>:</p>
<pre><code>>>> import pandas as pd
>>> df = pd.DataFrame({'aaa': aaa, 'bbb': bbb, 'ccc': ccc})
>>>... | python|python-2.7|numpy | 7 |
375,346 | 46,257,988 | using pandas to compare large CSV files with different numbers of columns | <p>I am new at python programming and I am trying to join two csv files with different numbers of columns. The aim is to find missing records and create a report with specific columns from the master column.</p>
<p>An example of two csv files copied directly from excel
SAMPLE CSV 1(combine201709.csv)</p>
<pre><code>... | <p>Try this:</p>
<pre><code>d2.merge(d1[['aitechid','grpdetails1/farmermobile','grpdetails1/farmername']],
left_on='farmermobile', right_on='grpdetails1/farmermobile')
</code></pre>
<p>or</p>
<pre><code>d2.merge(d1[['aitechid','grpdetails1/farmermobile','grpdetails1/farmername']] \
.rename(column... | python|pandas|csv | 1 |
375,347 | 46,225,831 | Pandas max date by row? | <p>The solution to the question asked <a href="https://stackoverflow.com/a/44304535/4764434">here</a> unfortunately does not solve this problem. I'm using Python 3.6.2</p>
<p>The Dataframe, <code>df</code>: </p>
<pre><code> date1 date2
rec0 2017-05-25 14:02:23+00:0... | <p>After some testing, it looks like there is something wrong with <code>pandas</code> and <code>psycopg2.tz.FixedOffsetTimezone</code>.</p>
<p>If you try <code>df.max(axis=0)</code> it will work as expected, but as you indicate <code>df.max(axis=1)</code> will return a series of <code>NaN</code>.
If you do not use <c... | python|pandas|datetime|dataframe|max | 1 |
375,348 | 58,284,012 | How to accelerate the code which convert tensor to numpy array in tensorflow_datasets? | <p>Although I want to convert tensor to numpy array in tensorflow_datasets, my code is progressively drastically slow down.
Now, I use the lsun/bedroom dataset which has over 3 million images.
How to accelerate my code?</p>
<p>My code saves tuple which has numpy array every 100,000 images.</p>
<pre><code>train_tf = t... | <p>Your <code>if</code> condition is never going to get executed after the first pass and consequently your <code>train</code> variable keeps accumulating.</p>
<p>I think you wish to have condition as:</p>
<pre><code>if d_cnt!=0 and d_cnt%100001==0:
train = (tfds.as_numpy(data["image"]), )
</code></pre> | python|numpy|tensorflow|tensor|tensorflow-datasets | 1 |
375,349 | 58,445,405 | Pandas JOIN/MERGE/CONCAT Data Frame On Specific Indices | <p>I want to join two data frames specific indices as per the map (<code>dictionary</code>) I have created. What is an efficient way to do this?</p>
<p><strong>Data:</strong></p>
<pre><code>df = pd.DataFrame({"a":[10, 34, 24, 40, 56, 44],
"b":[95, 63, 74, 85, 56, 43]})
print(df)
a b
0 1... | <p>Create <code>Series</code> and then <code>DaatFrame</code> by <code>dictioanry</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>DataFrame.join</code></a> both and last remove first 2 columns by positions:</p>
<pre><code>df = (pd.S... | python-3.x|pandas|data-structures | 2 |
375,350 | 58,496,948 | Python/Pandas is there a way to vectorize a comparison to all other points in an opposing category? | <p>I have a dataset of x,y points that are in two separate categories. There are many "frames" of ten or so points that I want to groupby (or split on) instead of iterate through. I want to compare each point in category A with all points in category B. Specifically I want the distance between them. I haven't found the... | <p>Figured it out eventually. It just required creative reshaping/repeating with numpy matricies.</p>
<pre><code>
df['loc'] = list(zip(df['x'],df['y']))
groupA = df.loc[df.Cat==1]
groupB = df.loc[df.Cat==0]
groupA = groupA[['frame_id','point_id','loc']]
groupB = groupB[['frame_id','point_id','loc'... | python|pandas|numpy | 0 |
375,351 | 58,452,300 | Is there a way of extracting indices from a pandas DataFrame based on value | <p>I have the following DataFrame:</p>
<pre><code>index col0 col1 col2
0 0 1 0
1 1 0 1
2 0 1 1
</code></pre>
<p>I would like to extract the following indices(those that contain ones(or any value)): </p>
<pre><code>[(0, 1), (1, 0), (1, 2), (2, 1), (2,2))]
</code></pre>
<p>Is there a met... | <p>Use <code>np.where</code> + <code>zip</code></p>
<hr>
<pre><code>[*zip(*np.where(df))]
</code></pre>
<p></p>
<pre><code>[(0, 1), (1, 0), (1, 2), (2, 1), (2, 2)]
</code></pre> | python|pandas | 7 |
375,352 | 58,358,862 | DataFrame Groupby two columns and get counts of another column | <p>Novice programmer here seeking help. I have a Dataframe that looks like this:</p>
<pre><code> Cashtag Date Message
0 $AAPL 2018-01-01 "Blah blah $AAPL"
1 $AAPL 2018-01-05 "Blah blah $AAPL"
2 $AAPL 2019-01-08 "Blah blah $AAPL"
3 $AAPL 2019-02-09 "Blah blah $AAPL"
... | <p>Try:</p>
<p>In case <code>Date</code> is <code>string</code>:</p>
<pre class="lang-py prettyprint-override"><code>>>> df.groupby([df["Cashtag"], df["Date"].apply(lambda x: x[:7])]).agg({"Message": "count"}).reset_index()
</code></pre>
<p>If <code>Date</code> is <code>datetime</code>:</p>
<pre class="lan... | python|dataframe|pandas-groupby | 0 |
375,353 | 58,468,290 | How can I cumulatively add or subtract values based on another column values using Pandas? | <p>I have a dataframe below that shows voltage output based on seconds. The <code>v_out</code> value is based on a displacement of either +/- 0.05 centimeters. </p>
<p>So when <code>v_out</code> gets more positive, then there is positive displacement compared to the last <code>v_out</code> value. When <code>v_out</cod... | <p>The method to <em>look at</em> a _lagged value is named <code>shift</code>, and then we inspect if the values is positive, negative, or zero with an if-else construct.</p>
<p>So, first we'd construct the column <code>sign</code>. The logic can be packed into 1 line.</p>
<pre><code>df['sign'] = (df.v_out - df.v_out... | python|pandas|cumulative-sum | -1 |
375,354 | 58,557,329 | Get the percentage of predicted values | <p>Using basic logistic regression i predicted 0 and 2 values</p>
<p>The DATA dataframe has the next structure: </p>
<pre><code>Duration | y
12.45 | 0
123.66 | 0
0.34 | 2
14.69 | 2
</code></pre>
<p>The logistic regression:</p>
<pre><code>x = DATA.Duration.values.reshape(-1,1)
y = DATA.y.values.resha... | <p>Using sklearn:
it is </p>
<pre><code>from sklearn.linear_model import LogisticRegression
clf = LogisticRegression().fit(X, y)
clf.predict(X)
</code></pre> | python|pandas | 1 |
375,355 | 58,368,120 | Conditional Change in Pandas Dataframe | <p>I would like to change the column days (which is a datetime column) conditional on the indicator column, i.e. when indicator is equal to either DTM or AMC, I would like to add 1 day to the days column. </p>
<pre><code> import pandas as pd
df = pd.DataFrame({'days': [1, 2, 3],
'indicator': ['BMO', 'DTM... | <p>Use a <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer">boolean mask</a>:</p>
<pre><code>df['days'] += (df.indicator.eq('AMC') | df.indicator.eq('DTM'))
print(df)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> days indicator
0 ... | python|pandas|datetime | 1 |
375,356 | 58,195,100 | Dealing with the Multiindex headers dataFrame - Python | <p>I have a dataframe which looks like this. In the header, it have 2 lines of header, like one heading in row 1 cover 5 subheaddings in row 2.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html pretty... | <h3>Given the following Excel Sheet:</h3>
<p><a href="https://i.stack.imgur.com/AREBO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AREBO.png" alt="enter image description here"></a></p>
<ul>
<li>Just specify the header row with the <code>header</code> parameter, and <code>usecols</code> to get t... | python|pandas|dataframe | 1 |
375,357 | 58,564,237 | Import a directory of CSV files at once and keep only oldest record per file | <p>I have database containing several csv files. Each csv file contains the last 7 days and only the oldest date is final data. </p>
<p>For example "variables_2019-08-12.csv" file contains data from 08-06 until 08-12 ( only 08-06 data is final data) and "variables_2019-08-13.csv" file contains data from 08-07 until 08... | <p>IIUC,</p>
<p>if you've already got your concatenated df you could possibly leverage the <code>.agg</code> function in groupby which lets you access columns </p>
<pre><code>df.groupby('source').agg({'date' : min})
</code></pre>
<p>note this would by the same as </p>
<pre><code>df.groupby('source')['date'].min().r... | python|pandas|numpy|pandas-groupby | 1 |
375,358 | 58,458,351 | with this code i could get list of author and book title from first url!! how to crawl multiple urls data using beautifulsoup? | <pre><code>import requests, bs4
import numpy as np
import requests
import pandas as pd
import requests
from bs4 import BeautifulSoup
from pandas import DataFrame
urls = ['http://www.gutenberg.org/ebooks/search/?
sort_order=title','http://www.gutenberg.org/ebooks/search/?sort_order=title&start_index=26']
for url ... | <p>Do you mean after the first 25 results, you want to navigate to the next page and get the next page's results? You can use beatufiulsoup to get the URL of the "Next" button at the bottom right of the page:</p>
<pre><code>next_url = soup.find('a', {'title': 'Go to the next page results.'})
</code></pre>
<p>and then... | python|pandas|web-scraping|beautifulsoup|web-crawler | 0 |
375,359 | 58,574,473 | Colab TPU error InvalidArgumentError: Cannot assign a device for operation | <p>in google colab when using TPU , i have the following error</p>
<p>InvalidArgumentError: Cannot assign a device for operation Adam/iterations/IsInitialized/VarIsInitializedOp: {{node Adam/iterations/IsInitialized/VarIsInitializedOp}} was explicitly assigned to /job:worker/replica:0/task:0/device:TPU:0 but available... | <p>Here is a reference TPU colab, make sure to change accelerator to a TPU:
runtime -> change run time -> TPU</p>
<p><a href="https://colab.research.google.com/notebooks/tpu.ipynb" rel="nofollow noreferrer">https://colab.research.google.com/notebooks/tpu.ipynb</a></p> | tensorflow|keras|google-colaboratory|tpu|google-cloud-tpu | 0 |
375,360 | 58,493,848 | Pandas: Merging two columns into one with corresponding values | <p>I have a large dataframe with a bunch of names which appear in two columns
It is in the following layout</p>
<pre><code>Winner Value_W Loser Value_L
Jack 5 Sally -3
Sally 2 Max -1
Max 4 Jack -2
Lucy 1 Jack -6
Jac... | <p>You could <code>wide_to_long</code> after renaming the columns slightly. This allows you to capture additional information, like whether that row is a Win or Loss. Or if you don't care do <code>df1 = df1.reset_index(drop=True)</code></p>
<pre><code>d = {'Winner': 'Person_W', 'Loser': 'Person_L'}
df1 = pd.wide_to_lo... | python|pandas | 4 |
375,361 | 58,419,436 | Extracting attention weights of each token at each layer of transformer in python | <p>I am doing some NLP and I am interested in extracting attention weights of individual test token at each layer of transformer via Python (PyTorch, TensorFlow, etc.)</p>
<p>Is coding up a Transformer (any transformers like Transformer-XL, OpenAL-GPT, GPT2 ,etc.) from the scratch the only way to get attention weights... | <p>The type of API you are probably is looking for is <a href="https://github.com/jessevig/bertviz" rel="nofollow noreferrer">BertViz</a> which is a tool for visualizing attention in the Transformer model (BERT, GPT-2, XLNet, and RoBERTa).</p>
<p>Also, Hugginface's <a href="https://github.com/huggingface/transformers"... | tensorflow|keras|deep-learning|nlp|pytorch | 0 |
375,362 | 58,560,304 | TimeDistributed(Dense) vs Dense in seq2seq | <p>Given the code below</p>
<pre><code>encoder_inputs = Input(shape=(16, 70))
encoder = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
# We discard `encoder_outputs` and only keep the states.
encoder_states = [state_h, state_c]
# Set up the decoder, using `encoder_stat... | <p>If your Data is dependent on Time, like <code>Time Series</code> Data or the data comprising different frames of a <code>Video</code>, then Time <code>Distributed Dense</code> Layer is effective than simple <code>Dense</code> Layer.</p>
<p><code>Time Distributed Dense</code> applies the same <code>dense</code> laye... | tensorflow|keras|lstm|seq2seq|encoder-decoder | 4 |
375,363 | 58,311,566 | reading multiple s3 objects in a numpy array and concatenate | <p>I have multiple objects in a s3 bucket (part files). I need to read them and concatenate to one single numpy array. I am using below code</p>
<pre><code>def read_and_concat(bucket, key_list):
length = len(key_list)
for index, key in enumerate(key_list):
s3_client.download_file(bucket, key, 'test.out... | <p>I <em>think</em> that <code>data</code> needs to be defined before you use it in this case. Assigning by index to a variable that doesn't exist throws a <code>NameError</code>. I'm not sure the extra step of creating the array is needed because <code>genfromtext</code> returns an ndarray.</p>
<pre><code>def read_... | python|numpy|amazon-s3 | 1 |
375,364 | 58,531,295 | convert pandas series AND dataframe objects to a numpy array | <h1>Series to Numpy Array:</h1>
<p>I have a <code>pandas</code> series object that looks like the following:</p>
<pre><code>s1 = pd.Series([0,1,2,3,4,5,6,7,8], index=['AB', 'AC','AD', 'BA','BB','BC','CA','CB','CC'])
</code></pre>
<p>I want to convert this series to a <code>numpy</code> array as follows:</p>
<pre><c... | <p>IIUC, you may try numpy transpose and <code>reshape</code></p>
<pre><code>df.values.T.reshape(-1, int(dimension_len), int(dimension_len))
Out[30]:
array([[[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]],
[[nan, -2., nan],
[ 2., nan, nan],
[nan, nan, nan]],
[[nan,... | python|arrays|pandas|numpy | 1 |
375,365 | 58,196,587 | how to save this Matplotlib drawing as a Numpy array? | <p>I have a function that takes an image stored as a Numpy array, draws a few rectangles on it, labels them, then displays the result.</p>
<p>The shape of the source Numpy array is (480, 640, 3) - it's an RGB image from a camera. This probably doesn't matter a lot, but I'm just showing you an example of the data I'm w... | <p>The problem is that your <code>fig</code> variable is not a figure but an <code>AxesImage</code> as the error is stating. Thus change the first line of your code with :</p>
<pre><code>fig, ax = plt.subplots()
ax = plt.imshow(imdata)
</code></pre>
<p>The complete function is then :</p>
<pre><code>def draw_boxes(im... | python|numpy|matplotlib | 1 |
375,366 | 58,546,554 | Query about pandas copy() method | <pre><code>df1 = pd.DataFrame({'A':['aaa','bbb','ccc'], 'B':[1,2,3]})
df2=df1.copy()
df1.loc[0,'A']='111' #modifying the 1st element of column A
print df1
print df2
</code></pre>
<p>When modifying <code>df1</code> the object <code>sf2</code> is not modified. I expected it because I used <code>copy()</code></p>
<pre><... | <p>This is occurring because your <code>pd.Series</code> is of dtype=object, so it essentially copied a bunch of references to python objects. Observe:</p>
<pre><code>In [1]: import pandas as pd
In [2]: s1=pd.Series([[1,2],[3,4]])
...:
In [3]: s1
Out[3]:
0 [1, 2]
1 [3, 4]
dtype: object
In [4]: s1.dtype
Out... | python|pandas | 5 |
375,367 | 58,257,738 | Custom Merge Function for Different Size Tensors in Tensorflow | <p>I have two tensors of different sizes and want to write a custom merge function </p>
<pre><code>a = tf.constant([[1,2,3]])
b = tf.constant([[1,1,2,2,3,3]])
</code></pre>
<p>I want to take the dot product of each point in tensor <code>a</code> with two points in tensor <code>b</code>. So in the example above elemen... | <p>I'm not exactly sure why you call this a merge function. You don't really need to define a custom function. You can do this with a simple lambda function. Here's my solution.</p>
<pre><code>import tensorflow as tf
from tensorflow.keras.layers import Lambda
import tensorflow.keras.backend as K
a = tf.constant([[1,2... | tensorflow | 2 |
375,368 | 58,255,449 | Unable to dynamically import TensorFlow.js | <p>I am trying to dynamically import TensorFlow.js using the <code>import</code> function. However, I always receive a <code>TypeError: t is undefined</code> error. The following code is a simple HTML file which recreates the error.</p>
<pre><code>!DOCTYPE html>
<html lang="en">
<head>
<meta charse... | <p>You could very well just add the script element dynamically ?</p>
<pre><code>const el = document.createElement('script')
el.src = "https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js";
el.onload = (() => {
const script = document.createElement('script');
script.innerHTML = "console.log(tf)";
... | javascript|tensorflow | 1 |
375,369 | 58,543,321 | Iterating Over Numpy Array for NLP Application | <p>I have a Word2Vec model that I'm building where I have a vocab_list of about 30k words. I have a list of sentences (sentence_list) about 150k large. I am trying to remove tokens (words) from the sentences that weren't included in vocab_list. The task seemed simple, but nesting for loops and reallocating memory is... | <p>Note that typical word2vec implementations (like Google's original <code>word2vec.c</code> or <code>gensim</code> <code>Word2Vec</code>) will often just ignore words in their input that aren't part of their established vocabulary (as specified by <code>vocab_list</code> or enforced via a <code>min_count</code>). So ... | python|numpy|nlp|word2vec | 1 |
375,370 | 58,574,610 | python3 recognizes tensorflow, but doesn't recognize any of its attributes | <p>I am getting the following errors:</p>
<pre><code>AttributeError: module 'tensorflow' has no attribute 'variable_scope'
AttributeError: module 'tensorflow' has no attribute 'squared_difference'
</code></pre>
<p><a href="https://www.tensorflow.org/install" rel="nofollow noreferrer">tensorflow</a> is installed:</p>
<p... | <p>TensorFlow 2.0 cleaned up some of the APIs. Mathematical functions such as <code>squared_difference()</code> are now under <code>tf.math</code>. </p>
<p>There is no <code>tf.variable_scope()</code> in TensorFlow 2.0. I suggest reading <a href="https://www.tensorflow.org/guide/migrate" rel="noreferrer">this post</a>... | tensorflow|attributeerror | 18 |
375,371 | 58,182,032 | You tried to call count_params on ..., but the layer isn't built. TensorFlow 2.0 | <p>I receive the following error in in Pyhotn 3 and TF 2.0.</p>
<p>"ValueError: You tried to call count_params on digits, but the layer isn't built. You can build it manually via: digits.build(batch_input_shape)." at line new_model.summary().</p>
<p>what is the problem and how to solve it?</p>
<pre><code>inputs = ke... | <p>For 2.0 version Model can be saved in .h5 format, please use <code>model.save('my_model.h5')</code> while saving.</p>
<p>Please find the link of working <a href="https://colab.sandbox.google.com/gist/oanush/0a1db97731b201717003d19c29257f08/tf_nightly.ipynb" rel="nofollow noreferrer">gist</a>.</p>
<p>Also issue see... | tensorflow2.0 | 1 |
375,372 | 58,507,814 | How do I stack certain columns and copy the others all the way down to fill the empty rows? | <p>I'm quite new to python and am learning by applying what I know to automate some tasks in Excel. </p>
<p>Basically what I'm trying to do is take certain columns (ex: <code>columns J:Z</code>) and stack them below each other i.e. <code>column J</code> goes under <code>column J</code>, and then column L goes under th... | <p>I think you are looking for pandas .stack(), .unstack(), or .melt().</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html</a></p>
<p><a href="https://p... | python|excel|pandas|multiple-columns | 0 |
375,373 | 58,400,004 | Load dtypes into Python via a separate mapping table that can be linked to the primary dataframe to specify the dtypes by column | <p>Although new to python, i seem to be getting the hang of it. </p>
<p>However, i will be dealing with massive databases with hundreds of columns and specifying dtypes for each seem to be a very code intensive excersize i.e. having to specifically write out column names and convert to a certain dtype. </p>
<p>Questi... | <p>if you have another dataframe with correct dtypes or you can create a dictionary of {columnname: dtype} then you can use it to change dtypes like below</p>
<pre class="lang-py prettyprint-override"><code>d = {
"A": np.random.choice("A B C".split(), 5),
"B": np.random.rand(5),
"C": np.arange(5)
}
df = p... | python|pandas | 0 |
375,374 | 58,202,580 | Replicating in pytorch https://www.d2l.ai/chapter_linear-networks/linear-regression-scratch.html | <p>I am trying to replicate the code in pytorch. However I am having some problems with the autograd function. I am having the following runtime error. </p>
<p>RuntimeError: Trying to backward through the graph a second time</p>
<p>The code is the following:</p>
<pre class="lang-py prettyprint-override"><code>for ep... | <p>Pytorch is quite different from Tensorflow by its dynamic computational graph. To save the memory, Pytorch will delete all intermediate nodes in the grpah once they are no longer used. That is, you will face troubles if you want to backprop your gradients through these intermediate nodes twice or more.</p>
<p>The s... | pytorch|linear-regression|autograd | 0 |
375,375 | 58,312,770 | Break a row into muliple rows based on the (string) content of a column | <p>One column of my dataframe has a variable number of <code>\n</code>s inside its content and I need each line to be on a single row on the final dataframe. </p>
<p>This is a minimal example:</p>
<pre><code>df = pd.DataFrame({'a': ['x', 'y'], 'b':['line 1\nline 2\nline 3', 'line 1' ]})
</code></pre>
<p>That produce... | <p>Try using <code>str.split</code> and <code>explode</code></p>
<pre><code>df = df.set_index('a').b.str.split('\\n').explode().reset_index()
Out[153]:
a b
0 x line 1
1 x line 2
2 x line 3
3 y line 1
</code></pre>
<hr>
<p><strong>For pandas < 0.25</strong></p>
<pre><code>df = (df.set_index('a')... | python|pandas | 3 |
375,376 | 58,206,559 | RuntimeError: expected device cpu and dtype Byte but got device cpu and dtype Bool | <p>As described in <a href="https://github.com/facebookresearch/inversecooking/issues/10" rel="nofollow noreferrer">the issue I opened</a>, I get the following error when running the Pytorch <a href="https://github.com/facebookresearch/inversecooking" rel="nofollow noreferrer">inverse-cooking</a> model on CPU:</p>
<p>... | <p>As stated by @iacolippo and in the comment session and <a href="https://github.com/facebookresearch/inversecooking/issues/10#issuecomment-537848360" rel="nofollow noreferrer">myDennisCode</a>, the problem really was dependency versions. I had <code>torchvision==0.4.0</code> (which confused me) and <code>torch==1.2.0... | pytorch|cpu|archlinux | 1 |
375,377 | 58,362,762 | extracting string from pandas | <p>I have dataframe, i want to extract number from it, if 'transfer' word is
on 8 column it should extract from position 13, 15 character and else it
should extract from position 21, 15 character</p>
<pre><code> =IF(LEFT(C10,8)="Transfer",MID(C10,13,15),MID(C10,21,15)) i want same excel from formula in panda... | <p>Try this:</p>
<pre><code>import pandas as pd
import numpy as np
df['new_extract_column'] = np.nan
df.loc[ df['column8'].str.contains('transfer'), 'new_extract_column' ] = df[ df['column8'].str.contains('transfer') ].apply(lambda x: x[13:16])
df.loc[ ~df['column8'].str.contains('transfer'), 'new_extract_column' ]... | python-3.x|pandas | 0 |
375,378 | 58,278,715 | Is it possible to set dtype to an existing structured array, or add "column name" to an existing array? | <p>this code (snippet_1) is to construct a <a href="https://docs.scipy.org/doc/numpy-1.14.0/user/basics.rec.html" rel="nofollow noreferrer">structured array</a></p>
<pre><code>>>> dt = np.dtype([('name', np.str_, 16), ('age', np.int)])
>>> x = np.array([('Sarah', 16), ('John', 17)], dtype=dt)
>>... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/user/basics.rec.html#numpy.lib.recfunctions.unstructured_to_structured" rel="nofollow noreferrer"><code>numpy.lib.recfunctions.unstructured_to_structured</code></a></p>
<pre><code>x = np.array([('Sarah', 16), ('John', 17)])
x
# array([['Sarah', '16'],
# [... | python|numpy | 1 |
375,379 | 58,439,345 | Efficient 2d numpy array construction from 1d array and function with conditionals | <p>I am creating a 2d numpy array from a function applied to a 1d numpy array (which contains a conditional) and would like to know a more efficient way of doing this. This is currently the slowest part of my code. x is a 1d numpy array, and the output is a 2d numpy array. There is a switch to construct a different ... | <p>With your function:</p>
<pre><code>In [247]: basis2(np.array([1,.5,0,-.5,-1]))
Out[247]:
[array([ 0., 0., 0., 0., -0., 1.]),
array([ 0., 0., 0., -0., 1., 0.]),
array([ 0., -0., 1., 0., 0., 0.]),
array([-0., 1., 0., 0., 0., 0.]),
array([ 1., 0., -0., 0., ... | python|arrays|numpy | 1 |
375,380 | 58,505,369 | How to partially transpose pandas a dataframe | <p>I have a question similar to this one <a href="https://stackoverflow.com/questions/38821985/processing-transposing-pandas-dataframe">here</a>. I'd like to partially transpose a pandas dataframe. I got my hands on a dataframe looking similar to the following: </p>
<pre><code>data = [{"Student" : "john", "Subject" : ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFr... | python|pandas|dataframe|transpose | 3 |
375,381 | 58,492,933 | Numpy delete() is deleting different arrays with same elements from 2D array | <p>I have a 2D numpy array like
<code>B = [[1. 0.], [0. 1.], [3. 1.]]</code>
and I want to delete <code>[0. 1.]</code>, but when I do:</p>
<pre><code>B = np.delete(B, [0, 1], 0)
print(B)
</code></pre>
<p>both <code>[1. 0.], [0. 1.]</code> are deleted and I'm left with<br>
<code>[[3. 1.]]</code></p>
<p>thus I suppo... | <p>You are asking delete() to remove first and second index by asking [0,1] as a parameter. This second arameter is the index from which you want to delete the value.
You should try: </p>
<pre class="lang-py prettyprint-override"><code>np.delete(B, 1, 0)
</code></pre> | python|numpy|numpy-ndarray | 3 |
375,382 | 58,314,905 | Extracting Audio channel from a video file to feed in decode_wav function of TensorFlow | <p>I want to feed audio channel of a video file to the following TenorFlow function:</p>
<pre><code>tf.audio.decode_wav(
contents,
desired_channels=-1,
desired_samples=-1,
name=None)
</code></pre>
<p>Where Args:</p>
<ul>
<li><p>contents: A Tensor of type string. The WAV-encoded audio, usually
from a file. </p></li>
... | <p>You can extract the audio of video by eg.:</p>
<pre class="lang-py prettyprint-override"><code>import subprocess
command = "ffmpeg -i C:/test.mp4 -ab 160k -ac 2 -ar 44100 -vn audio.wav"
subprocess.call(command, shell=True)
</code></pre>
<p>And pass the <code>*.wav</code> file as tensor to <code>tf.audio.decode_w... | python|tensorflow|wav | 1 |
375,383 | 58,226,715 | Eigenvalues not following order while changing parameter in Python | <p>I have a <code>6x6</code> matrix <code>H</code> of which two eigenvalues become complex at certain values of the parameter <code>l</code> (for lambda). Apparently they are the first two elements of the eigenvalue array <code>E</code> we after diagonalizing <code>H</code> (calling <code>np.linalg.eig</code> module). ... | <p>The answer is in the documentation:
<a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.linalg.eig.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.linalg.eig.html</a> </p>
<p>I quote:</p>
<blockquote>
<p>... The eigenvalues are not necessa... | python|python-3.x|numpy|eigenvalue | 0 |
375,384 | 58,426,684 | Drop column values | <p>How can I only keep top 20% (by ascending = False) values from a column in a dataframe? </p>
<pre><code>df10 = df9[df9['quality'] > df9['quality'].quantile(0.20)]
</code></pre>
<p>I tried this code but it doesn't seem to work</p> | <p>try:</p>
<pre><code>df = pd.DataFrame({'quality':[1,2,3,4,5,6,7,8,9,10]})
df.loc[df['quality'] > df['quality'].quantile(0.8) , : ].sort_values(by='quality', ascending=False)
</code></pre> | pandas | 0 |
375,385 | 58,557,964 | List Column Names if the value change from max is within certain % (in pandas) | <p>Apologies for unclear title. My data look like this. They always sum to 1</p>
<pre><code>>df
A B C D E
0.3 0.3 0.05 0.2 0.05
</code></pre>
<p>What i want to do it identify columns which:</p>
<p>1) Highest value</p>
<p>2) The % reduction for highest was less than threshold.</p>
<p>For example... | <p>I used the following test DataFrame:</p>
<pre><code> A B C D E
0 0.3 0.3 0.05 0.2 0.05
1 0.5 0.1 0.20 0.1 0.10
</code></pre>
<p>Start from defining the following function to get column names for the current row:</p>
<pre><code>def getCols(row, threshold):
s = row.sort_values(ascend... | python|pandas | 0 |
375,386 | 58,323,628 | For every row in pandas, do until sample ID change | <p>How can I iterarate over rows in a dataframe until the sample ID change?</p>
<p>my_df:</p>
<pre><code>ID loc_start
sample1 10
sample1 15
sample2 10
sample2 20
sample3 5
</code></pre>
<p>Something like:</p>
<pre><code>samples = ["sample1", "sample2" ,"sample3"]
out = pd.DataFrame()
for sample i... | <p>Based on the input & output provided, this should work.
You need to provide more info if you are looking for something else.</p>
<pre><code>df.pivot(columns='ID', values = 'loc_start').rename_axis(None, axis=1).apply(lambda x: pd.Series(x.dropna().values))
</code></pre>
<p><strong>output</strong></p>
<pre><co... | pandas | 0 |
375,387 | 58,435,657 | How to access column after pandas .groupby | <p>I have a data frame that I used the .groupby() along with .agg() function on. </p>
<p><code>movieProperties = combined_df.groupby(['movieId', 'title', 'genres']).agg({'rating': ['count', 'mean']})</code></p>
<p>This is the code to create the new data frame. However I can't seem to access columns the same way anymo... | <p>after you groupby, the columns you grouped by are now called <code>index</code>:</p>
<pre><code>movieProperties = pd.DataFrame({"movie": ["x", "x", "y"], "title":["tx", "tx", "ty"], "rating": [3, 4, 3]}).groupby(["movie", "title"]).agg({"rating":["count", "mean"]})
movieProperties.index.values
Out[13]: array([('x',... | python|pandas|pandas-groupby | 7 |
375,388 | 58,521,181 | Pandas sum over a date range for each category separately | <p>I have a dataframe with timeseries of sales transactions for different items:</p>
<pre><code>import pandas as pd
from datetime import timedelta
df_1 = pd.DataFrame()
df_2 = pd.DataFrame()
df_3 = pd.DataFrame()
# Create datetimes and data
df_1['date'] = pd.date_range('1/1/2018', periods=5, freq='D')
df_1['item'] = ... | <p>Total sales With <strong>2-days</strong> rolling window per item:</p>
<pre><code>z = df.sort_values('date').set_index('date').groupby('item').rolling('2d')['sales'].sum()
</code></pre>
<p>Output:</p>
<pre><code>item date
1 2018-01-01 2.0
2018-01-02 4.0
2018-01-03 4.0
2018-01-... | python|pandas|time-series|grouping|rolling-computation | 1 |
375,389 | 58,509,352 | Is it possible to make a csv file out of a non delineated list? | <p>I have over 100,000 pieces of data im working on and the issue is that it was written in a very non conducive format, pdf. I have no idea of how to separate the data. I'm using pandas and matplotlib to do some basic plotting on this data. I cannot figure out how to make a csv out of this. </p>
<p>For example:</p>
... | <p>1) You may be able to copy and paste the data into an excel file. You can then split the column by going into "Data" and then "Text to Column".</p>
<p>2) If you are already reading a dataframe in python and need to split one column into 2 - You could create additional columns in the dataframe from the original dat... | python|pandas|csv|matplotlib | 0 |
375,390 | 58,476,374 | error about using dict to split dataframe | <p>The training data looks like below :</p>
<pre><code>p,x,s,n,t,p,f,c,n,k,e,e,s,s,w,w,p,w,o,p,k,s,u
e,x,s,y,t,a,f,c,b,k,e,c,s,s,w,w,p,w,o,p,n,n,g
e,b,s,w,t,l,f,c,b,n,e,c,s,s,w,w,p,w,o,p,n,n,m
p,x,y,w,t,p,f,c,n,n,e,e,s,s,w,w,p,w,o,p,k,s,u
e,x,s,g,f,n,f,w,b,k,t,e,s,s,w,w,p,w,o,e,n,a,g
e,x,y,y,t,a,f,c,b,n,e,c,s,s,w,w,p,... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>pandas.read_csv</code></a> implies that your first line in the csv file is the header. Since your csv file has no header, you need to tell this during the import. You should also pass the column ... | python|pandas|dataframe | 0 |
375,391 | 58,430,530 | ValueError: multiclass format is not supported | <p>While I am trying to use metrics.roc_auc_score, I am getting <code>ValueError: multiclass format is not supported</code>.</p>
<pre><code>import lightgbm as lgb
from sklearn import metrics
def train_model(train, valid):
dtrain = lgb.Dataset(train, label=y_train)
dvalid = lgb.Dataset(valid, label=y_valid)
... | <p>It seems the task you are trying to solve is regression: predicting the price. However, you are training a classification model, that assigns a class to every input.</p>
<p>ROC-AUC score is meant for classification problems where the output is the probability of the input belonging to a class. If you do a multi-cla... | python|pandas|machine-learning|scikit-learn|training-data | 7 |
375,392 | 58,192,448 | How to plot a 3D graph with Z axis being the magnitude of values in a csv? | <p>I believe the X and Y values in the plot should be represented by the columns and lines in the csv, which looks like this:</p>
<pre><code>0,original,1.0000,0.9999,0.9998,0.9997,0.9996,0.9995... 0.9900
1,28663, 4144,6096,6859,7366,7876,8125...
2,11268, 1374,2119,2393,2615,2809,2904...
3,14734, 2122,3115,3466,3... | <p>A very minimal example, but I guess what you want to achieve is have each of your curves separated from the others in a 3D space. The code below generates two plots, one that draws curves individually, the other which treats the input as a surface. You can easily build onto this and achieve a more specific goal of y... | python|numpy|csv|matplotlib|3d | 1 |
375,393 | 58,192,599 | Python Pandas read_csv to dataframe without separator | <p>I'm new to the Pandas library.<br>
I have shared code that works off of a dataframe.</p>
<p>Is there a way to read a gzip file line by line without any delimiter (use the full line, the line can include commas and other characters) as a single row and use it in the dataframe? It seems that you have to provide a de... | <p>if you just want each line to be one row and one column then dont use read_csv. Just read the file line by line and build the data frame from it.</p>
<p>You could do this manually by creating an empty data frame with a single columns header. then iterate over each line in the file appending it to the data frame.</p... | python|pandas | 2 |
375,394 | 58,545,656 | Python match records where elements are the same but dollars are within % | <p>I am trying kickout exceptions from a s/s where most if not all elements match, with the exception of the dollar amounts associated with the record. So if for example, Column A - Column C match, but the dollar difference between the two is 10% or less, i would like to create logic to only highlight these examples w... | <p>Following code will filter any records within group client/instrument which "Dollars" field value has difference less than a threshold with a closest value within the group:</p>
<pre><code>import pandas as pd
import numpy as np
threshold = 0.01
df = pd.DataFrame({'Client_ID': [12345, 45678, 12345, 12345, 12345],
... | python|pandas | 1 |
375,395 | 58,560,297 | Python: How to import a .csv and run the content through the code? | <p>I'm quite new to Python and I've been trying to run "<strong>The CODE</strong>" (see below)</p>
<p>The code works perfectly although it generates random data. </p>
<p>I have my own data in csv file which I would like to run through it and see whether my manual calculations reconcile. So, what I have done is:</p>
... | <p>Ok, so reading your comments, you mention that <code>r</code> can have the same length as <code>m</code> <strong>or less</strong>. Therefore, my proposed solution is to just load 2 CSV files where the first file contains your <code>r</code> values and the second file contains your <code>m</code> values.</p>
<p>Make... | python|python-3.x|numpy | 2 |
375,396 | 58,600,556 | Insert an image onto a substrate | <p>please help me, I need to insert an image on the substrate.</p>
<p>substrate:</p>
<p><a href="https://i.stack.imgur.com/Da2VG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Da2VG.png" alt="enter image description here"></a></p>
<p>It png, and in the area that is blank with cities, you must ins... | <p>Here is one way to do it in Python/OpenCV, if I understand what you want.</p>
<pre><code>Read the substrate and trees images
Extract the alpha channel from the substrate
Extract the substrate image without the alpha channel
Use the alpha channel to color the base substrate image white where the alpha channel is ... | python|image|numpy|opencv|python-imaging-library | 2 |
375,397 | 58,210,841 | How to display my polynomial regression line? | <p>My plot has a very fat line, which I didn't expect and haven't been able to troubleshoot on my own. I don't know how to show the image.</p>
<p>Doing EDA on Kaggle's Craigslist Auto data set. I want to display and then compare and contrast a linear and polynomial regression fit correlating price and model year for e... | <h1>First, always clean and check the data:</h1>
<ul>
<li>Given data from <a href="https://www.kaggle.com/austinreese/craigslist-carstrucks-data#craigslistVehiclesFull.csv" rel="nofollow noreferrer">Kaggle: Vehicles listings from Craigslist.org</a></li>
<li>Incidentally, the plot generated by <code>sns.regplot</code> ... | python|pandas|matplotlib|scikit-learn|seaborn | 1 |
375,398 | 69,051,858 | Finding the first value of at least a certain value | <p>I spent a few hours on this, so any help would be amazing!</p>
<p>I have a pandas dataframe df. Then I group by one of the columns (A), focus on another column (B) and get the mean of each group:</p>
<pre><code>group_mean = df.groupby('A').B.agg('mean')
group = df.groupby('A').B
</code></pre>
<p>In the same order ab... | <p>You can use <code>apply</code> to check per group the values greater than the mean, and <code>idxmax</code> to get the first True value:</p>
<pre><code>df.groupby('A')['B'].apply(lambda x: x.ge(x.mean()).idxmax())
</code></pre> | pandas|pandas-groupby | 1 |
375,399 | 69,228,301 | put all the items containing a certain string in a dataframe in another column | <p>The dataframe I have right now looks like this</p>
<pre><code>In[1]: df
Out[1]:
index yesterday today tomorrow
1 apple_1 banana_3 cherry_4
2 pear_2 apple_4 blueberry_1
3 kiwi_3 orange_6 banana_2
4 apple_1 melon_3 banana_4
</code></pre>
<p>I wan... | <p>Try with <code>startswith</code> then <code>where</code> mask then as nan and do <code>ffill</code></p>
<pre><code>df['new'] = df.where(df.apply(lambda x : x.str.startswith('apple'))).ffill(1).iloc[:,-1]
df
Out[149]:
yesterday today tomorrow new
index
1 ... | python|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.