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 |
|---|---|---|---|---|---|---|
361,100 | 61,783,567 | Make API calls to model deployed on GCP | <p>We have trained a Nasnet model on GCP, and deployed it so that API calls can be made.</p>
<p>The model takes an image as input (numpy array), and returns an array of predictions. However, when we try to make API calls to the model sending a numpy array, an error occurs (Request payload size exceeds the limit). Anot... | <p>The “Request payload size exceeds the limit” error is due to a hard limit for the Cloud Machine Learning Engine API. There's a feature request to increase this limit which you can follow for updates here [1]. In the meantime, try using the following solution as it is similar to your case [2]. </p>
<p>[1] <a href="h... | python|numpy|tensorflow|google-cloud-platform|gcp-ai-platform-training | 1 |
361,101 | 61,827,130 | Filter imaginary numbers | <p>In this task, you will be filtering out complex elements from an array.</p>
<blockquote>
<p>Create a <code>(4,)</code> array with values 3, 4.5, 3 + 5j and 0 using
"np.array()". Save it to a variable array</p>
<p>Create a boolean condition real to retain only a real number using
<code>.isreal(array)</cod... | <p>You are not calling the <code>iscomplex</code> function properly. You should change <code>imag = array.iscomplex[array]</code> to <code>imag = array.iscomplex(array)</code>, also it was showing me error for <code>array.isreal</code>, I changed it to <code>np.isreal(array)</code> and it worked.</p>
<pre class="lang-... | arrays|python-3.x|list|numpy | 0 |
361,102 | 61,788,346 | Dataframe slicing with more than two dimensions | <p>So I'm going through a machine learning tutorial and I'm met with this line of code:</p>
<pre><code>pred_list = []
batch = train[-n_input:].reshape((1, n_input, n_features))
for i in range(n_input):
pred_list.append(model.predict(batch)[0])
batch = np.append(batch[:,1:,:],[[pred_list[i]]],axis=1)
</co... | <p>Seems to me <code>batch</code> is a numpy array with 3 dimensions of shape <code>(1, n_input, n_features)</code>, 1 row, <code>n_input</code> columns, and <code>n_features</code> depths. <code>batch[:,1:,:]</code> would be a slice of <code>batch</code> that gets from second to last columns of <code>batch</code> (pyt... | python|pandas|numpy|keras | 1 |
361,103 | 61,832,106 | How do I write the paragraph the file as I want in Python? | <p><a href="https://i.stack.imgur.com/vI3RA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vI3RA.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/ZRPSd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZRPSd.png" alt="enter image description here"></a><... | <ul>
<li>read all the lines that start with 1</li>
<li>read all the line that start with 16</li>
<li>zip them together and make strings</li>
<li>repeat for all other pairings</li>
</ul>
<p>If you have or make lists of strings</p>
<pre><code>a = ['1 abcd1',
'1 abcd2',
'1 abcd3']
b = ['16 efgh1',
'16 ef... | python|numpy|file|text | 1 |
361,104 | 61,961,318 | Drop partial duplicates in Pandas based on which has least information | <p>I am new to Pandas, and wondering if I can use it for something specific. I want to drop rows of a dataframe which have a partial duplicate entry in a certain column.</p>
<p>For example, if there are two rows, and one row has "Verrucomicrobia;phylum;" in a given column, and the second row has "Verrucomicrobia;phylu... | <pre><code># Generate some sample data
df = pd.DataFrame({
0: [';'.join([str(randint(0, 100)) for _ in range(randint(1, 5))]) for __ in range(100000)]
})
print(df)
0
0 71;39
1 72;75;92
2 45;74
3 55;94;95;3
4 27;93;4;33;52
... ...
999... | pandas|dataframe | 0 |
361,105 | 62,027,864 | pandas df loop through column resulting in KeyError 1 | <p>I have an if loop that's throwing a keyerror 1 when i try to reference a location in a dataframe, which has been imported with pandas. I only receive this error on windows, the loop runs in os - this command also works outside of a loop. what am I do wrong?
I am running though a column and if and of the string value... | <p>Your code has the following flaws:</p>
<ol>
<li><p>Your loop <code>for R in df:</code> iterates over <strong>column names</strong>.
So if your DataFrame has e.g. 3 columns, you attempt to process just 3 rows.</p></li>
<li><p><code>df['Data status']</code> is a <em>Series</em> - a column with this name.
It has <stro... | python|pandas | 0 |
361,106 | 61,623,257 | np.concatenate doesn't allow sequential concatenation | <p>I have been trying to concatenate two 1D arrays using np.concatenate but it doesn't work as expected. Can someone please let me know where I'm making a mistake?</p>
<p>My code is as follows:</p>
<pre><code>x = np.array([1.13793103, 0.24137931, 0.48275862, 1.24137931, 1.00000000, 1.89655172])
y = np.array([0.036666... | <p>You can use <code>np.concatenate</code> to concatenate along some axis if that dimension exists in the arrays that you want to concatenate:</p>
<pre><code>x = np.array([1,2,3])
y = np.array([4,5,6])
</code></pre>
<p>here, x and y have shape (3,) so only one axis.
This means you can only concatenate along that axis... | python|numpy | 2 |
361,107 | 61,893,149 | TypeError: unorderable types: tuple() > int() | <p>I am trying the following code for deskewing an image but I am recieving error :</p>
<pre><code>TypeError: unorderable types: tuple() > int()
</code></pre>
<p>The bug is in the following line :</p>
<p>coords = np.column_stack(np.where(thresh > 0))</p>
<p>The full code is :</p>
<pre class="lang-py prettyprint... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>coords = np.column_stack(np.where(thresh[1] > 0))
</code></pre> | python|numpy|typeerror | 1 |
361,108 | 61,771,741 | Store list of dictionaries as a DataFrame | <p>Suppose I have List of dictionaries as</p>
<pre><code> l = [{'car':'good'},
{'mileage':'high'},
{'interior':'stylish'},
{'car':'bad'},
{'engine':'powerful'},
{'safety':'low'}]
</code></pre>
<p>Basically these are noun-adjective pairs. </p>
<ol>
<li>How can I visualize whats the most ... | <p>Given that you want this to be done column-wise, then you have to re-structure your list of dictionaries. You need to have one dictionary to represent one row. Therefore, your example list should be (I added a second row for better explainability):</p>
<pre><code> l = [
{'car':'good','mileage':'high','interior... | python|pandas|list|dataframe|dictionary | 2 |
361,109 | 61,720,468 | filter condition for plotting | <p>I have 1000 text files and each file contains 6 columns. I want to plot 2 columns which are my x and y by applying a condition on the 6th column. I want to have x and y which have zero value in the 6th column. I could write how to plot all without considering the condition like below:</p>
<pre><code>import os
impor... | <p>Make the following change: (The 6th column in python has the index of 5)</p>
<pre><code>plt.plot(a[0][a[5]==0], a[1][a[5]==0], c=cmap.to_rgba(i+1),label=num[-3:], lw=0.75)
</code></pre> | python|numpy|matplotlib | 0 |
361,110 | 61,631,360 | Self-defined tensorflow decoder TypeError: __call__() missing 1 required positional argument: 'inputs' | <p>I am using tensorflow 2.0 for training my own attention model,
however I ran into one big issue when building my decoder class,
like this</p>
<pre><code>TypeError Traceback (most recent call last)
<ipython-input-19-3042369c4295> in <module>
9 enc_hidden_h=fw_sam... | <p>As discussed in the comments, the problem was that the poster was inheriting from <code>tf.keras.Model</code> while creating the <code>Decoder()</code> class. And this superclass was expecting an <code>inputs</code> argument in the <code>__call__()</code> operator.</p>
<p>So, this error can be resolved by change <c... | python|tensorflow|keras|encoder-decoder | 2 |
361,111 | 57,865,650 | How to make different color bar for value above and below 0 for plotly chart | <p>I have generated a bar chart through plotly and how can i make the bar above 0 green and the bar below 0 red? </p>
<pre><code>import plotly
import plotly.graph_objs as go
plotly.offline.init_notebook_mode(connected=True)
trace1 = go.Bar(
x=df.symbol,
y=df["percentageChange30dBtc"],
name='Top10',
m... | <p>you can pass a list of colors on your marker,
(assuming that df["percentageChange30dBtc"] values are numeric, if is string ending with <code>%</code> do <code>float(x.replace('%',''))>0</code> instead of <code>x>0</code></p>
<pre><code>import plotly
import plotly.graph_objs as go
plotly.offline.init_notebook_... | python|pandas|plotly | 0 |
361,112 | 58,018,953 | Trying to find a dataframe column name value in another df, bring it back to dataframe | <p>I have this dataframe from a crosstab called df2:</p>
<pre><code>paidmonth
201508 183323.0 NaN NaN NaN NaN NaN
201509 553608.0 145609.0 NaN NaN NaN NaN
201510 44... | <p>If I've understood well a merge will do the trick.
Have a look through the documentation <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">here</a>. </p>
<pre class="lang-py prettyprint-override"><code>pd.merge(df2, df5, how='left', left_on='p... | python|pandas | 0 |
361,113 | 57,795,721 | python select sub array with timedelta differ | <p>When I try to get a sub array by datetime delta as below:</p>
<pre><code>dx = dx[(dx[['ts']].diff() > threshold).any(axis=1)]
</code></pre>
<p>It should remove the too near labels in below example but it doesn't work.</p>
<p>Full code:</p>
<pre><code>#!/usr/bin/env python
import re
import pandas as pd
import ... | <p>If I understand you correctly, you want to drop rows whose time is too close to the previous row. Try this:</p>
<pre><code>lst = [
"09-04 11:55:05.011 5",
"09-04 11:55:15.011 2",
"09-04 11:55:16.011 3",
"09-04 11:55:20.011 4",
"09-04 11:55:25.011 4",
"09-04 11:55:30.011 4",
"09-04 11:55:... | python|pandas|dataframe | 1 |
361,114 | 57,758,514 | How to compare rows in Python to see difference in value? | <p>I want to essentially get a list of all the items where the total does not match the sum of the weekly items.</p>
<p><a href="https://i.stack.imgur.com/emBo9.png" rel="nofollow noreferrer">Click here for image of the data</a></p>
<p>The column headers of the csv are Name, Type, EMPID, Year, Period, UniqueID, and V... | <p>Let me suggest that you pivot by ID and Period, and iteratively compare the sum of weeks to Total. This is what the following code does, and if the sum of Weeks is not equal to Total, it prints the unique ID. Please let me know if this helps.</p>
<p>Say that your dataset's name is df:</p>
<pre><code>for ID, Period... | python|pandas | 0 |
361,115 | 57,943,944 | Is there any function in TensorFlow equivalent to python reduce? | <p>I want a function in TensorFlow which has the same effect as Pythion <code>reduce()</code></p>
<p>For example, if I have a tensor <code>a</code> with value <code>[a1, a2, a3]</code> and a function <code>func()</code>, I want <code>[func(a1, a2), func(func(a1, a2), a3)]</code>. If <code>a</code> is a Python list I c... | <p>If you actually mean reduce, so the tensorflow equivalent are <a href="https://www.tensorflow.org/api_docs/python/tf/foldl" rel="nofollow noreferrer">tf.foldl</a> and <a href="https://www.tensorflow.org/api_docs/python/tf/foldr" rel="nofollow noreferrer">tf.foldr</a>.
Example:</p>
<pre><code>elems = tf.constant([&qu... | python|tensorflow|machine-learning | 3 |
361,116 | 57,875,033 | Turning values into columns | <p>Apologies for the vague question name, but I'm not really sure how to call this operation.</p>
<p>I have the following data frame:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'A': [1, 3, 2, 1, 2],
'B': [2, 1, 3, 2, 3],
'C': [3, 2, 1, 3, 1],
})
print(df)
# A B C
# 0 1 2 3
# 1 3 1 ... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow noreferrer">argsort</a>:</p>
<pre><code>pd.DataFrame(df.columns.values[np.argsort(df.values)])
</code></pre>
<hr>
<pre><code> 0 1 2
0 A B C
1 B C A
2 C A B
3 A B C
4 C A B
</code></pre> | python|pandas|numpy | 8 |
361,117 | 58,040,789 | Custom binary crossentropy loss in keras that ignores columns with no non-zero values | <p>I'm trying to segment data where the label can be quite sparse. Therefore I want to only calculate gradients in columns that have at least one nonzero value.</p>
<p>I've tried some methods where I apply an extra input which is the mask of these nonzero columns, but given that all the necessary information already i... | <p>Use <code>tf</code>-compatible operations, via <code>tf</code> and <code>keras.backend</code>:</p>
<pre><code>import tensorflow as tf
import keras.backend as K
from keras.losses import binary_crossentropy
def custom_loss(y_true, y_pred):
indices = K.squeeze(tf.where(K.sum(y_true, axis=1) > 0))
y_true_sp... | python|tensorflow|keras|casting | 0 |
361,118 | 58,134,888 | Select rows when 2 cells appear the same in another dataframe | <p>I'm looking for a way to select the rows from Dataframe 1 where the values of column 'A' and 'B' appear the same as in Dataframe 'a' and 'b'. The corresponding column names are different, so 'A' is not the same as 'a'.</p>
<p>Example:</p>
<p>Dataframe 1:</p>
<pre><code> A B C
0 10 20 30
1 40 50 60
2 ... | <p>You need a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html" rel="nofollow noreferrer"><code>merge</code></a> and index on the columns of <code>df1</code>:</p>
<pre><code>df1.merge(df2, left_on=['A', 'B'], right_on=['a','b'])[df1.columns]
A B C
0 10 20 30
1 70 80 9... | python|pandas | 3 |
361,119 | 58,044,331 | Pandas non correct saving to CSV | <p>I have CSV file:</p>
<pre><code>lang
12345,it
77777,en
</code></pre>
<p>The first line is headers. My table have one column <code>lang</code>. In each of the next lines there are two values: index and value for this index.</p>
<p>When I am reading this table with Pandas by <code>pd.read_csv(path)</code> I am get... | <p>First line mimics your df example where 12345 is in the index. Then I save that as a normal csv. Upon reading it back in, simply set <code>index_col=0</code> to point <code>pandas</code> to read column at position 0 as the index. </p>
<pre><code>df.set_index(df.columns[0],inplace=True)
df.to_csv('test.csv')
df_n... | python|pandas|csv | 1 |
361,120 | 57,758,652 | Creating row combinations (dyads) with a condition | <p>I have the following database. Agreement_id represents the agreement. If two firms have the same agreement_id, it means that they have signed an agreement. The first and second rows have agreements_id = 1. The 3rd, 4th, 5th and 6th rows have agreement_id = 2 which means these 4 firms have entered the agreements.</p>... | <p>I solved the problem using R:</p>
<pre><code>colnames(df) <- c("X", "ID","Agreement", "Firm", "FirmID", "Year") # assigning column names to dta_out
dta_inp <- df
# merging dta_inp with itself on agreement and year
dta_out <- merge(dta_inp, dta_inp, by.x = c("Agreement", "Year"), by.y = c("Agreement", "Y... | python|pandas|loops|numpy|jupyter-notebook | 1 |
361,121 | 57,899,443 | How to universally flatten different formats of dictionaries into dataframes? | <p>I have a API response object that returns different dictionary formats depending on input to the system. </p>
<p>As an example these are two formats:</p>
<p>----------------------1------------------------------</p>
<pre><code>{'0': {'cdate': '2019-09-11 22:29:17',
'email': 'z1@z1.com',
'phone': '',
'first_n... | <p>Try the below code, Hope this will help</p>
<pre><code> {0:{'subscriber_id': 4184, # <-- Here add key
'sendlast_should': 0,
'sendlast_did': 0,
'result_code': 1,
'result_message': 'Contact added',
'result_output': 'json'}}
</code></pre>
<p>In second json you have to add key for which this whole data is ... | python-3.x|pandas|dictionary|python-3.7|jsonresponse | 1 |
361,122 | 58,070,084 | Python error: could not broadcast input array from shape (20,10) into shape (10) | <p>I have the following code and get this error:
S[i+1,:] = (S[i,:] + np.cumsum(np.sqrt(dt)<em>np.random.randn(nsims),axis=0)) + epsilon_plus</em>np.random.poisson(lambda_plus,(M,nsims))</p>
<p>ValueError: could not broadcast input array from shape (20,10) into shape (10)</p>
<pre class="lang-py prettyprint-overrid... | <p>The problem is this expression:</p>
<pre><code>S[t-1] + sigma*math.sqrt(dt)*A + epsilon_plus*B-epsilon_minus*C
</code></pre>
<p>All three terms you're adding <code>sigma*math.sqrt(dt)*A</code>, <code>epsilon_plus*B</code>, and <code>epsilon_minus*C</code> have shape <code>(201,)</code>, and so does the result aft... | python|numpy | 1 |
361,123 | 58,098,123 | Read the data from the csv file while keeping a watch on the folder for changes | <p>I have a code which keeps a watch on a folder for any alterations. It checks for newly added and removed files and promptly displays the name of the file when such cases happen. This is my code:</p>
<pre><code>import os, time
import pandas as pd
import glob
path_to_watch = os.path.abspath('C:/Folder for violation c... | <ul>
<li>To begin with, it is better to use the <strong>pathlib</strong> package for accessing
the file system.</li>
<li>Use <strong>set</strong> to collect the file names.</li>
</ul>
<pre><code>from pathlib import Path
path_to_watch = Path('C:/Folder for violation csv/')
before = set(path_to_watch.glob('**/*'))
whil... | python|pandas|csv|dataframe|dictionary | 1 |
361,124 | 58,106,189 | Change color of pie chart according to section label (pandas/matplotlib) | <p>I am working from a DataFrame called <code>plot_df</code> that looks like this:</p>
<p><a href="https://i.stack.imgur.com/UuvFu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UuvFu.png" alt="plot_df"></a></p>
<pre><code> Country Visual Format $
0 ... | <p>You can use the <code>colors</code> parameter for pie charts. Since this takes an array, you'll have to create an array that corresponds to your input data for each plot.</p>
<pre><code>cdict = {'DIGITAL': 'r', 'DIGIMAX3D': 'y', 'DIGITAL3D': 'b', ...}
for country in plot_df.index.get_level_values(0).unique():
... | python|pandas|matplotlib|colors|pie-chart | 1 |
361,125 | 57,975,374 | Encoding categorical numeric data to different columns | <p>I am new to data science and machine learning. I have a column with three values 0,1,2 and I want to encode these 3 values to 3 different columns with prefix predict_.</p>
<p>I have tried get_dummies and label encoder but it didn't workout</p>
<pre><code>import pandas as pd
Y = pd.get_dummies(Y,prefix='predict_')
... | <p>make sure to pass only the column</p>
<pre><code>pd.get_dummies(Y['column_name'],prefix='predict_')
</code></pre> | pandas|scikit-learn|data-science | 0 |
361,126 | 58,170,585 | Select pandas rows, if row element is contained in another row element | <p>I have a pandas dataframe that looks like that:</p>
<pre><code>real_value, prediction
'invalid', 'inv'
'invalid', 'neg'
'invalid', 'inv'
'negative', 'neg'
'negative', 'neg'
'negative', 'neg'
'positive', 'pos'
'positive', 'pos'
'positive', 'inv'
</code></pre>
<p>I would like to select all the rows in which the pred... | <p>Use the following condition:</p>
<pre><code>df[df['real_value'].str[:3].ne(df['prediction'])]
</code></pre>
<p>Output:</p>
<pre><code> real_value prediction
1 invalid neg
8 positive inv
</code></pre>
<p><code>ne</code> returns Not equal to of series and other. This is element-wise. You cannot use ... | python|pandas|dataframe | 2 |
361,127 | 57,907,570 | Replace cell values in df based on complex condition | <p><strong>Hello friends,</strong></p>
<ul>
<li>I would like to iterate trough all the numeric columns in the df (in a generic way).</li>
<li><p>For each unique df["Type"] group in each numeric column:</p>
<p>Replace all values that are greater than each column mean + 2 standard
deviation values with "nan"</p></li>
<... | <p>Logically, it can go like this:</p>
<pre><code>test_cols = ['Test1', 'Test2']
# calculate mean and std with groupby
groups = df.groupby('Type')
test_mean = groups[test_cols].transform('mean')
test_std = groups[test_cols].transform('std')
# threshold
thresh = test_mean + 2 * test_std
# thresholding
df[test_cols] ... | pandas | 2 |
361,128 | 58,115,169 | Calculate Max Frequency for every Sequence_ID in full Dataframe | <p>I have a Dataframe Like:</p>
<pre><code>Time Frq_1 Seq_1 Frq_2 Seq_2 Frq_3 Seq_3
12:43:04 0.00 30668.00 0.00 30670.00 4620.00 30671.00
12:46:05 0.00 30699.00 0.00 30699.00 3280.00 30700.00
12:46:17 4200.00 30700.00 0.00 30704.00 0.00 30704.00
12:... | <p>If need max value of <code>Frq</code> per groups first reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer"><code>wide_to_long</code></a>, filter out <code>0</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/ap... | python|python-3.x|pandas | 2 |
361,129 | 58,089,867 | Whats the best way to combine a pandas.datframe.plot() with a matplotlib.pyplot.plot()? | <p>I was looking to format the ticks in my y-axis (this thread <a href="https://stackoverflow.com/questions/31357611/format-y-axis-as-percent">Format y axis as percent</a> is great) but a lot of the solutions were causing an AttributeError for my particular code</p>
<pre><code>#Example code
import pandas as pd
import ... | <p>I think you are getting mixed up, when you do:</p>
<pre><code>ax=df.plot()
</code></pre>
<p>you've already made the ax object. if you want to add more to it (like another plot) you can simply just use its methods to do this, such as:</p>
<pre><code>ax.plot([0,100],[0,0])
</code></pre> | python|pandas|matplotlib|plot | 1 |
361,130 | 58,167,925 | Module not found error in Python while trying to import pandas | <p>I am trying to import pandas on Python (Linux) but it is giving me the following error:</p>
<blockquote>
<p>ModuleNotFoundError<br>
Traceback (most recent call
last) in ()
1 import pandas as pd
ModuleNotFoundError: No module named 'pandas'</p>
</blockquote> | <p>try below code to install pandas.</p>
<pre><code>sudo pip3 install pandas
</code></pre>
<p>Above code work for me .</p> | python|pandas | 5 |
361,131 | 58,138,099 | softmax score by a cnn model | <p>I have build a CNN model for image classification. I want to pick five images that are correctly classified by the network and have the maximum softmax scores(for each class).</p>
<p>I have tried to check the model.evaluate(X_test,y_test) but it gives the overall softmax score of model.</p>
<pre class="lang-py prett... | <p>For this you have to use <code>model.predict</code>, not <code>model.evaluate</code>:</p>
<pre><code>model.predict(X_test)
</code></pre> | python|tensorflow|keras|softmax | 0 |
361,132 | 58,000,302 | Checking and deleting duplicate neighbor values in a series of rows for a DataFrame | <p>I have a set of rows in a dataframe that have some duplicate neighboring values which are all located in <strong>the same position of each column</strong> and looks like this:</p>
<pre><code>row_data = pd.DataFrame({0 : [1.1, 1.2, 1.2, 1.3, 1.4, 1.5, 1.5, 1.6],
1 : [2.3, 2.2, 2.2, 2.3, 2.4, 2.5, 2.5, 2.6],
2 : [2.4... | <p>IIUC, here's what I would try:</p>
<pre><code>non_dups = row_data.ne(row_data.shift(1,axis=1)).any()
row_data.loc[:,non_dups]
</code></pre>
<p>Output: </p>
<pre><code> 0 1 3 4 5 7
0 1.1 1.2 1.3 1.4 1.5 1.6
1 2.3 2.2 2.3 2.4 2.5 2.6
2 2.4 2.2 2.3 2.4 2.6 2.7
3 7.1 7.2 7.... | python|python-3.x|pandas|duplicates|rows | 1 |
361,133 | 57,766,309 | How to extract value corresponding to a date from a Pandas dataframe? | <p>I have this stock market P/E dataframe from which I want to get the data corresponding to a single date. However the following code throws an error. </p>
<pre><code>from nsepy import get_index_pe_history
from datetime import date
nifty_pe = get_index_pe_history(symbol="NIFTY",
start=da... | <p>The Key error is thrown as the dataframe formed using <code>get_index_pe_history</code> has set the <code>Date</code> column as the index. The index cannot be called as a column name as you are trying in <code>nifty_pe["Date"]</code>. You can reset the index and then use the code you wrote as follows</p>
<pre><code... | python|pandas | 1 |
361,134 | 57,915,609 | Split a list into n randomly sized chunks | <p>I am trying to split a list into n sublists where the size of each sublist is random (with at least one entry; assume <code>P>I</code>). I used numpy.split function which works fine but does not satisfy my randomness condition. You may ask which distribution the randomness should follow. I think, it should not ma... | <p>The problem can be refactored as choosing <code>I-1</code> random split points from <code>{1,2,...,P-1}</code>, which can be viewed using <a href="https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)" rel="nofollow noreferrer">stars and bars</a>.</p>
<p>Therefore, it can be implemented as follows:</p>
<pre... | python|list|numpy|sublist|numpy-random | 3 |
361,135 | 58,137,968 | Deleting values conditional on large values of another column | <p>I have a timeseries df comprised of daily Rates in column A and the relative change from one day to the next in column B.</p>
<p>DF looks something like the below:</p>
<pre><code> IR Shift
May/24/2019 5.9% -
May/25/2019 6% 1.67%
May/26/2019 5.9% -1.67
... | <p>You can also <code>np.where</code> function from numpy as follows:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'Date':[datetime(2019,5,24), datetime(2019,5,25), datetime(2019,5,26), datetime(2019,5,27), datetime(2019,5,28),datetime(2019,5,29),datetime(2019,5,30)], 'IR':[0.059,0.06,0.05... | python|pandas|loops|time-series | 1 |
361,136 | 57,844,540 | Resampling Hz in a pandas dataframe | <p>I'm working on a project in pandas on python. I receive as input a .csv file like this:</p>
<pre><code>Name Timestamp Data
A1 259 [1.1,1.0,0.1]
A1 260 [-0.1,1.2,0.3]
A1 261 [0.1,0.2,-0.3]
...
A1 14895 [1.4,0.3,1.8]
...
A2 278 ... | <p>I cannot answer the question exactly in its entirety as not even you are sure about the timestamp, but I will try to give you some general guidelines.<br>
What you have here is called <strong>panel data</strong>, many different time series for each "name".<br>
<code>groupby(['Name']).apply(<func>)</code> can i... | python|pandas|time-series|data-science|resampling | 1 |
361,137 | 57,854,683 | Single positional indexer is out-of-bounds on while loop pandas | <p><a href="https://i.stack.imgur.com/KKRHJ.png" rel="nofollow noreferrer">[Here is how my last data from my dataframe and at the end errors which are occuring]</a> I am printing out data within a specific range. For example, <code>now + 200 sec</code>, so here I am printing data within 200 seconds from now. </p>
<p>I... | <pre><code>df2 = df.loc[df.loc[:,'time'] < date+200,:]
</code></pre> | python|pandas | 0 |
361,138 | 58,053,142 | How to interpolate so that I can 'stretch' a 20-item array into a 30-item array, but keeping the total and the percentiles the same? | <p>If I have this numpy array:</p>
<pre><code>x = np.array([10,20])
</code></pre>
<p>and I want to "stretch" it by doubling its size, I can very easily do it with</p>
<pre><code>y = np.repeat(x,2)/2
</code></pre>
<p>and get</p>
<pre><code>[5,5,10,10]
</code></pre>
<p>However, <strong>what if I want to stretch it ... | <p>Using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html" rel="nofollow noreferrer"><strong><code>np.interp</code></strong></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html" rel="nofollow noreferrer"><strong><code>np.linspace</code></strong></a>:<... | python|numpy|scipy|interpolation | 2 |
361,139 | 57,906,413 | plotting pandas dataframe date | <p>I have a pandas dataframe with 27 columns for electricity consumption, the first column represents the date and time for a two year duration and the other columns have a recorded hourly values for electricity consumption for 26 houses during two years. What I'm doing is clustering using k-means. Whenever I try to ... | <p>I think what you are essentially doing is a time series clustering of all households to find similar electricity usage pattern over time.</p>
<p>For that, each timestamp becomes a 'feature', while each household's usage becomes your data row. This will make it easier to apply sklearn clustering methods, which are t... | python|python-3.x|pandas|cluster-analysis | 1 |
361,140 | 34,071,227 | How to apply drop_duplicates to grouped dataframe? | <p>I'm trying to drop the duplicate rows in each chunk of a grouped dataframe. A toy example is </p>
<pre><code>import pandas as pd
import numpy as np
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], \
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays)... | <p>Pass <code>group_keys=False</code> to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html#pandas.DataFrame.groupby" rel="nofollow"><code>groupby</code></a>:</p>
<pre><code>In [273]:
df.groupby(level='first', group_keys=False).apply(lambda d: d.drop_duplicates())
Out[273... | python|pandas|dataframe|grouping | 0 |
361,141 | 34,009,397 | Appending arrays by array names | <p>I am working with a function which outputs a numpy array around 600 elements long. </p>
<pre><code>array = function_output()
array.shape # this outputs (600,)
</code></pre>
<p>I have to work with around 50 outputs this function. Each output is distinct. The goal is to concatenate each of these arrays together into... | <p>Whenever you have numbered variable names, think of using a list instead:</p>
<pre><code>output = [function_output() for i in range(50)]
</code></pre>
<p>Instead of accessing the first array with <code>array1</code> you would use <code>output[0]</code> instead (since Python uses 0-based indexing.)</p>
<p>To combi... | python|arrays|numpy | 3 |
361,142 | 34,192,691 | Working with a csv file and outputting json in python | <p>I'm using pandas in python to take a csv file, do some minor transformations on it and then outputting the two columns as a json file. I want two values <code>timestamp</code> and <code>value</code>. I only want the two new columns and to drop the rest of the file so that it looks like:</p>
<p><code>{"timestamp[0]"... | <p>What if you change this:</p>
<pre><code> f["timestamp"] = hmCols["timestamp"]
f["value"] = hmCols["value"]
f.to_json(outfile, orient="records")
</code></pre>
<p>to:</p>
<pre><code> pd.DataFrame(hmCols).to_json(outfile, orient="records")
</code></pre>
<p><strong>Edit to add:</strong>... | python|json|csv|pandas | 1 |
361,143 | 33,972,315 | pandas: find the first shipped product from a DataFrame | <p>I have the following DataFrame:</p>
<pre><code>product_id shipping_date price quantity
AX-11 2014-11-02T01:00:04+00:00 200 1
BA-45 2012-05-23T01:00:02+00:00 4000 5
XF-55 2011-01-12T01:00:07+00:00 400 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmin.html" rel="nofollow"><code>idxmin()</code></a> to get the row index of the earliest shipping date. You can then use <code>loc</code> to fetch the value at that row from the product ID column: </p>
<pre><code>>>> df.l... | python|pandas|dataframe | 1 |
361,144 | 34,376,778 | Shape returned by Pandas ValueError does not match the dataframe shape? | <p>My understanding is <code>pd.DataFrame().shape</code>returns <strong>(n_rows, n_columns)</strong>.
However when constructing a dataframe and the indices do not match with the data shape, pandas raises a <code>ValueError</code> with the shape as <strong>(n_columns, n_rows)</strong>.</p>
<p>Example:</p>
<pre><code>d... | <p>When pandas says "indices" here it means the index and the columns (they are both of type Index).</p>
<pre><code>In [11]: df = pd.DataFrame(np.random.randn(3,2))
In [12]: df.index
Out[12]: Int64Index([0, 1, 2], dtype='int64')
In [13]: df.columns
Out[13]: Int64Index([0, 1], dtype='int64')
</code></pre>
<p>You are... | python|pandas | 1 |
361,145 | 34,139,350 | struct.pack is much slower in python 2.6 when working with numpy arrays | <h1>The basic question</h1>
<p>Hello everyone. I believe that I found an issue with python 2.6, struct.pack, and numpy arrays. The issue is that the following code is incredibly slow when I run it using python 2.6 (but it is sufficiently fast when I run it using python 2.7 or 2.5).</p>
<pre><code>import numpy as np... | <p>Why not avoid the <code>struct</code> module altogether and let <code>numpy</code> handle the binary conversion for you?</p>
<p>For example:</p>
<pre><code>import numpy as np
x = np.random.randint(0, 3200, (1000, 1000))
z = x.astype('<u2').tostring()
</code></pre>
<p><code>'<u2'</code> specifies little-end... | python|numpy|python-2.6|binary-data | 2 |
361,146 | 34,320,268 | Valid parameters for astype in NumPy | <p>I'm new to NumPy and SciPy.
Unlike Matlab, it seems like there is a data type associated with each array in NumPy.</p>
<p>Suppose that we have an integer array <code>x</code>:</p>
<pre><code>import numpy as np
x = np.array([1, 2, 3])
</code></pre>
<p>If I want to convert the array into float, then it seems like t... | <p>The other expressions work, you just need to import the types from numpy. You don't need to do this for <code>float</code> because it is a built-in type for Python.</p>
<pre class="lang-py prettyprint-override"><code>y5 = x.astype(np.float64)
y6 = x.astype(np.float_)
</code></pre>
<p>Both the string-type and type-... | python|arrays|numpy|types | 7 |
361,147 | 34,370,040 | How to find duplicated elements in a 1D Tensor | <p>I want to get elements that appear more than one time in a 1D tensor. Precisely, I want to create a function that does the opposite of <code>tf.unique</code>. For example if <code>x = [1, 1, 2, 3, 4, 5, 6, 7, 4, 5, 4]</code> I need the output to be <code>[1,1,4,4,4,5,5]</code> and at the same time also retrieve the ... | <p>You can do it using existing Tensorflow operations in a slightly round-about way, by counting the unique items to create a dense set of indexes of the unique items, and then counting them using <code>tf.unsorted_segment_sum</code>. Once you have the count, select the items with <code>> N</code> using <code>tf.gr... | python|tensorflow | 5 |
361,148 | 33,990,955 | Combine pandas DataFrame query() method with isin() | <p>So I want to use <code>isin()</code> method with <code>df.query()</code>, to select rows with <code>id</code> in a list: <code>id_list</code>. Similar <a href="https://stackoverflow.com/questions/24237211/pandas-query-rows-by-list">question</a> was asked before, but they used typical <code>df[df['id'].isin(id_list)]... | <p>You can also include the list within the query string:</p>
<pre><code>>>> df.query('a in ["a", "b", "c"]')
</code></pre>
<p>This is the same as:</p>
<pre><code>>>> df.query('a in @id_list')
</code></pre> | python|pandas|dataframe | 76 |
361,149 | 34,321,467 | TensorFlow failed to pip-install on RedHat 6 | <p>I have a RedHat 6 machine with python installed using <code>miniconda</code>, so</p>
<pre><code>]]] which python
/export/home/my-home-dir-etc-etc-etc/miniconda/bin/python
]]] which pip
/export/home/my-home-dir-etc-etc-etc/miniconda/bin/pip
</code></pre>
<p>and</p>
<pre><code>Python 2.7.10 |Continuum Analytics, In... | <p>Seems like You are missing the cblas libraries:</p>
<pre><code>/usr/bin/ld: cannot find -lcblas
...
distutils.errors.LinkError: Command "cc /tmp/tmp72IZmg/tmp/tmp72IZmg/source.o -L/usr/lib64 -lblas -o /tmp/tmp72IZmg/a.out" failed with exit status 1
</code></pre>
<p>try running <code>yum install blas blas-devel</c... | python|installation|redhat|tensorflow | 1 |
361,150 | 34,138,634 | Pandas GroupBy : How to get top n values based on a column | <p>forgive me if this is a basic question but i am new to pandas. I have a dataframe with with a column A and i would like to get the top n rows based on the count in Column A. For instance the raw data looks like </p>
<pre><code>A B C
x 12 ere
x 34 bfhg
z 6 bgn
z 8 rty
y 567 hmmu,,u
x 545 fghfgj
x 44 zxcbv
<... | <p>IIUC you can use function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.nlargest.html" rel="noreferrer"><code>nlargest</code></a>.</p>
<p>I try your sample data and get top 2 rows by column <code>C</code>:</p>
<pre><code>print df
A B C
0 x 12 ere
1 x 34 ... | python|pandas|count|group-by|dataframe | 5 |
361,151 | 36,937,051 | Selecting by row from pd.df.ix[] view? | <p>Given the following, <code>multiIndex</code>ed <code>pd.DataFrame</code>:</p>
<pre><code>Type p&l position rolldate value vola
Date Symbol
2008-01-02 AC 1757.2168 1 1201132800 45588.9161 480... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> - see <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="nofollow">docs - using slicers</a>:</p>
<pre><code>print df
... | python|pandas|python-3.5 | 2 |
361,152 | 36,728,531 | How do I use pandas dataframes to select the first column as array? | <p>I would like to collect the values of the first column of a pandas dataframe into an array. How can I accomplish this?</p>
<p>So far I have tried this: </p>
<pre><code>first_column_values = df.iloc[:,[0]]
</code></pre>
<p>But it is not the result I wish to have.</p> | <p>You're close. It should be:</p>
<p><code>first_column_values = df.iloc[:, 0].values</code></p> | python|pandas|dataframe | 2 |
361,153 | 36,883,949 | In Tensorflow, get the names of all the Tensors in a graph | <p>I am creating neural nets with <code>Tensorflow</code> and <code>skflow</code>; for some reason I want to get the values of some inner tensors for a given input, so I am using <code>myClassifier.get_layer_value(input, "tensorName")</code>, <code>myClassifier</code> being a <code>skflow.estimators.TensorFlowEstimator... | <p>You can do</p>
<pre><code>[n.name for n in tf.get_default_graph().as_graph_def().node]
</code></pre>
<p>Also, if you are prototyping in an IPython notebook, you can show the graph directly in notebook, see <code>show_graph</code> function in Alexander's Deep Dream <a href="http://nbviewer.jupyter.org/github/tensor... | python|tensorflow|tensorboard|skflow | 200 |
361,154 | 36,751,217 | How to rotate a point using transformations.py | <p>How do you use the popular <a href="http://www.lfd.uci.edu/~gohlke/code/transformations.py.html" rel="nofollow"> transformations.py library</a> to rotate a point around an axis?</p>
<p>I'm trying to rotate a point 90 degrees about the z-axis, but I'm not getting the expected results, and although the file's docs ha... | <p><code>transformations.py</code> works with <code>np.array</code> objects, not <code>np.matrix</code>, even in the <code>whatever_matrix</code> functions. (This is a good thing, because <code>np.matrix</code> is horrible.) You need to use <code>dot</code> for matrix multiplication:</p>
<pre><code>point1 = R.dot(poin... | python|numpy|matrix|rotation | 2 |
361,155 | 37,115,369 | Extract non- empty values from columns of a dataframe in python | <p>This is a follow up of this question: <a href="https://stackoverflow.com/questions/37099920/extract-non-empty-values-from-the-regex-array-output-in-python">Extract non- empty values from the regex array output in python</a></p>
<p>I have a DF with columns "col" and "col1" of type 'numpy.ndarray' and looks like :</p... | <p>Try the following:</p>
<pre><code>import pandas as pd
def parse_nested_max(xss):
return max(
(max((int(x) for x in xs if x), default=0) for xs in xss),
default=0
)
df['col'] = df.col.apply(parse_nested_max)
df['col1'] = df.col1.apply(lambda s: ','.join(s) or 'NOT FOUND')
</code></pre>
<... | python|regex|numpy|pandas | 0 |
361,156 | 37,085,430 | tf.shape() get wrong shape in tensorflow | <p>I define a tensor like this:</p>
<p><code>x = tf.get_variable("x", [100])</code></p>
<p>But when I try to print shape of tensor :</p>
<p><code>print( tf.shape(x) )</code></p>
<p>I get <strong>Tensor("Shape:0", shape=(1,), dtype=int32)</strong>, why the result of output should not be shape=(100)</p> | <p><a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/array_ops.html#shape" rel="noreferrer">tf.shape(input, name=None)</a> returns a 1-D integer tensor representing the shape of input.</p>
<p>You're looking for: <code>x.get_shape()</code> that returns the <code>TensorShape</code> of the <code>x</code> ... | python|python-3.x|tensorflow|tensor | 132 |
361,157 | 37,036,980 | Reading several arrays in a binary file with numpy | <p>I'm trying to read a binary file which is composed by several matrices of float numbers separated by a single int. The code in Matlab to achieve this is the following:</p>
<pre><code>fid1=fopen(fname1,'r');
for i=1:xx
Rstart= fread(fid1,1,'int32'); #read blank at the begining
ZZ1 = fread(fid1,[Nx Ny]... | <p>The cleanest way to read all your matrices in a single vectorized statement is to use a struct array:</p>
<pre><code>dtype = [('start', np.int32), ('ZZ', np.float32, (Ny1, Nx1)), ('end', np.int32)]
with open(fname1, 'rb') as fh:
data = np.fromfile(fh, dtype)
print(data['ZZ'])
</code></pre> | python|matlab|numpy|io|binary | 2 |
361,158 | 36,975,326 | How to store data in CSV file? | <p>I have some data I want to store in a csv file:</p>
<pre><code>result | DataFrame | (90422, 17) | Column names: age, job, marital
</code></pre>
<p>However, my script only creates an empty csv file. How can I get it to actually output the data that I want?</p>
<pre><code>for row in result:
counter[row[0]... | <p>use the <code>to_csv</code> method integrated in the <code>pandas</code> library</p>
<pre><code>my_dataframe.to_csv('name_of_file', sep=',')
</code></pre> | python|csv|pandas | 1 |
361,159 | 37,098,728 | numpy savetxt only saving to 3 significant figures | <p>I have a code which uses np.savetxt to save arrays which have floats and strings in them. But when i save them they only save to 3 significant figures. When i print <code>z</code> it gives my the full floats, so they problem is when i save it. what is causing this? for example <code>z[0]=(55798.879999999997, 14.08, ... | <p><code>savetxt</code> does a row by row write of your array, using an expression like</p>
<pre><code> f.write(fmt % tuple(row))
</code></pre>
<p>where <code>fmt</code> is derived from your input parameter. In your example I expect the <code>fmt</code> will be something like</p>
<pre><code>In [179]: '%.3s %.3s %.3... | python|numpy | 0 |
361,160 | 37,081,288 | Performance issue in python with nested loop | <p>I was able to improve a code written in python a lot with numpy because of the dot product. Now I still have one part of the code which is still very slow. I still don't understand multithreading and if this could help here. In my opinion this should be possible here. Do you have a nice idea what to do here?</p>
<p... | <p>I'm attempted to re-create the conditions that the question was interested in, but first a smaller test case to illustrate a strategy. First the author's original implementation:</p>
<pre><code>import numpy as np
import numba as nb
import numpy
def func(re, ws, a, l, r):
for x1 in range(a**l):
for x2 ... | python|multithreading|performance|numpy|python-multithreading | 2 |
361,161 | 54,954,191 | How to import the numpy module on AWS lambda? | <p>I am new beginner for AWS system, I am doing my python project, want to use AWS lambda function to run my serverless python program, I have all my resource on AWS S3 bucket, I would like to simply take one of my images from S3 bucket (let's say source-bucket), turn it to grey color and save it back to the other S3 b... | <p><strong>Method 1</strong></p>
<p>Run this command in your project root directory</p>
<pre><code>pip install --target="." package_name
</code></pre>
<p>Zip your project folder and upload it on AWS</p>
<p><strong>Method 2</strong></p>
<p><a href="https://gist.github.com/joseph-zhong/372a47bb618111dcd2c81008d00357... | python|numpy|aws-lambda|serverless | 0 |
361,162 | 55,091,244 | Iterate through CSV rows with Pandas, Perform Selenium Action | <p>I have a CSV file that was created using Pandas. Below is the output from the following code:</p>
<pre><code> test = pd.read_csv('order.csv', header=0)
print(test.head())
3 16258878505032
0 3 16258876670024
1 3 16258876899400
2 3 16258876997704
</code></pre>
<p>The only data I need to b... | <p>First use parameter <code>names</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="noreferrer"><code>read_csv</code></a> for avoid convert first row of data to columns names:</p>
<pre><code>test = pd.read_csv('order.csv', names=['quantity','sku'])
print (test)
... | python|pandas|selenium | 6 |
361,163 | 55,075,715 | How to load images with multiple JSON annotation in PyTorch | <p>I would like to know how I can use the data loader in PyTorch for the custom file structure of mine. I have gone through PyTorch documentation, but all those are with separate folders with class.</p>
<p>My folder structure consists of 2 folders(called training and validation), each with 2 subfolders(called images a... | <p>You should be able to implement your own dataset with <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset" rel="nofollow noreferrer"><code>data.Dataset</code></a>. You just need to implement <code>__len__</code> and <code>__getitem__</code> methods.</p>
<p>In your case, you can iterate throu... | python|python-3.x|opencv|deep-learning|pytorch | 2 |
361,164 | 54,994,047 | Simple keras model shape issue | <p>Starting to learn Keras and TensorFlow. Why is the shape wrong, and how can I fix it?</p>
<p>(temperature input to predict electricity load output)</p>
<pre><code>load = data.loc[:35063,'Load'].values
temp = data.loc[:35063,'Temperature'].values
load.shape
(35064,)
from keras.layers import Input,Dense
input_ten... | <p>In the line,</p>
<pre><code>load.shape()
# Output is ( 35064 , )
</code></pre>
<p>The number 35064 shows the number pf samples in the <code>load</code> array. The subarrays don't have a definite shape and hence there is a <code>,</code> after 35064. The unknown dimension in Keras is treated as None. So the fix cou... | python|tensorflow|keras | 0 |
361,165 | 54,896,588 | Building TensorFlow package for AWS Lambda in python | <p><a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html#python-package-dependencies" rel="nofollow noreferrer">https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html#python-package-dependencies</a></p>
<p>Above link helps to ... | <p>Don't build large dependencies into your lambda function. Use lambda layers to carry heavy dependencies. Lots of examples for this now. eg., <a href="https://github.com/antonpaquin/Tensorflow-Lambda-Layer" rel="nofollow noreferrer">https://github.com/antonpaquin/Tensorflow-Lambda-Layer</a></p> | python|python-3.x|tensorflow|aws-lambda | 0 |
361,166 | 54,710,331 | populate new rows by comparing two dataframes | <p>I have two dataframe:</p>
<pre><code>df = pd.DataFrame({'ID': ['1','1','1','2','2','3','4','4'], \
'ward': ['icu', 'surgery','icu', 'neurology','neurology','obstetrics','OPD', 'surgery'], \
'start_date': ['2016-10-22 18:19:19', '2016-10-24 10:20:00','2016-10-24 12:41:30', '2016... | <p>By interpretting the guidance from <a href="https://stackoverflow.com/a/46526249/8259064">here</a> I have the following method:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'ID': ['1','1','1','2','2','3','4','4'], \
'ward': ['icu', 'surgery','icu', 'neurology','neurology','obstetrics','... | pandas|merge|python-3.5 | 1 |
361,167 | 54,971,085 | How to solve linear equations with parametrization? | <p>I am trying to solve my equasions this way:</p>
<pre><code>a = np.array([[1,2,4,1,0,2],[0,1,2,0,0,1],[0,0,0,2,2,0],[0,0,0,0,14,4],[0,0,0,0,0,-2]])
b = np.array([3,0,1,0,14])
x = np.linalg.solve(a,b)
</code></pre>
<p>However, as they are not full ranked there is no one solution, but instead endless solutions. Usual... | <p>There's a math side of this and a programming side of this. On the math side, it's important to note that if ax=b has multiple solutions, then those solutions are {y + b1 * t1 + b_2 * t_2 + ... + bN * tN | t1, ..., tN in the real numbers} where y is any solution to ax=b (such as the least-squares solution) and b1, .... | python|numpy|linear-equation | 1 |
361,168 | 55,064,953 | comparing two columns in the same csv file | <p>I have a CSV file with two columns. </p>
<p>One has values like size XL, size L, size M and size S. In the other I only have XL and L. </p>
<p>What I want to do is that when my loop finds XL in the first column it overwrites that cell value with XL and when it doesn't find XL in the next cell it should just skip i... | <p>I don't understand the question, and would be very confusing for others too.
However, it seems like a simple loop and condition code. Try using PANDAS with Python, the library to process the CSV in case this helps you. </p> | python|numpy-slicing | 0 |
361,169 | 54,803,170 | I am unable to sum my array because I think that it is being stored as multiple arrays | <pre><code>for i in range(1,n):
for j in range(1, m-1):
a = np.sum(u[i][j])
print("sum = ", a)
</code></pre>
<p>When I run this code it just prints out the values of u[i][j] and not the sum of these values. </p>
<pre><code>u[i][j] = 10.0
10.006282725965008
10.018656940304817
10.036934387954467
10.... | <p>This code is correctly taking the <code>sum</code> of <code>u[i][j]</code>, the trivial sum of <em>one item</em>, one cell in the two-dimensional array of numbers.</p>
<p>This code sums everything in the 2-d array.</p>
<pre><code>a = np.sum(u)
print("sum = ", a)
</code></pre>
<p>This code prints the sum of <e... | python|arrays|numpy|sum | 4 |
361,170 | 54,879,523 | Iterating deeply nested pandas json object? | <p>I have a pretty big json object which is of the format</p>
<pre><code>[
{
"A":"value",
"TIME":1551052800000,
"C":35,
"D":36,
"E":34,
"F":35,
"G":33
},
{
"B":"value",
"TIME":1551052800000,
"C":36,
"D":56,
"E":44,
"F":75,
"G":38
}, ...
...
]
</code></pre>
<p>Converted to jso... | <p>First, pd.read_sql_query returns pd.DataFrame and not json.</p>
<p>As per your question:</p>
<p>Say you have a sample function calculate:</p>
<pre><code>def update_calculation(time):
return time
</code></pre>
<p>You could update time so:</p>
<pre><code>df["TIME"] = df["TIME"].apply(update_calculation)
</cod... | python|json|pandas | 1 |
361,171 | 54,820,406 | Remove Specific Indices From 2D Numpy Array | <p>If I have a set of data that's of shape (1000,1000) and I know that the values I need from it are contained within the indices (25:888,11:957), how would I go about separating the two sections of data from one another?</p>
<p>I couldn't figure out how to get np.delete() to like the specific 2D case and I also need ... | <p>Is this how you want to divide the array?</p>
<pre><code>In [364]: arr = np.ones((1000,1000),int)
In [365]: beta = arr[25:888, 11:957]
In [366]: beta.shape
Out[366]: (863, ... | python|numpy|multidimensional-array | 0 |
361,172 | 54,800,979 | Keras: data generator | <ul>
<li>I saw this code to use the keras generator (*) <br> </li>
<li>but when I run "__data_generation", python complain about the asterix in "*self.dim" with the message "SyntaxError: invalid syntax". Do you know if I should use the "asterix?" <br> </li>
<li>if I remove it and that I use only "self.dim" then I got a... | <p>Well, <code>*self.dim</code> is used to unpack a container as argument. This basically means that you pass <code>self.dim</code> and the function treats it as a tuple to be unpacked inside the function. See <a href="https://medium.com/understand-the-python/understanding-the-asterisk-of-python-8b9daaa4a558" rel="nofo... | python|tensorflow|keras | 0 |
361,173 | 55,000,460 | how to get pose coordinates from posenet of tensorflow tflite model | <p>I have used tflite model file of posenet provided by tensorflow.<br>
I am getting output as 4 arrays of 4d which are:</p>
<pre><code>[1, 23, 17, 17]
[1, 23, 17, 34]
[1, 23, 17, 64]
[1, 23, 17, 1]
</code></pre>
<p>My input image size is 353x257.<br>
Now how to get pose coordinated from this output?</p>
<p>Blog I a... | <p>You can reference this new blog that came out which shows how to use PoseNet for Android, it includes a library that does the postprocessing to find key point coordinates, which should be helpful to guide your code logic.
Basically with the first array had an output of scores, with the dimensions being batch size *... | java|android|python|tensorflow | 1 |
361,174 | 54,802,692 | Flow_from_dataframe - number of classes differs from actual number of classes | <p>I'm using pandas to make use of the .txt file and flow_from_dataframe to help me read in the images from the folders. </p>
<p>This is my code: </p>
<pre><code>import keras
import pandas as pd
from keras_preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
datagen = image.ImageDataG... | <p>Your dataset seems to be splitted by keras and keras internally does build a mapping. If you don´t pass the <code>classes</code> param, while the mapping is built it takes all the uinque classes present in the data and creates the mapping itself. If some classes are missing, they are missing in the mapping later on.... | pandas|dataframe|keras|label | 3 |
361,175 | 55,137,387 | Trying to create a fully connected neural network for CIFAR-10 | <p>I am a relative beginner when it comes to machine learning. </p>
<p>I have been playing with Keras with TensorFlow as a backend and for some reason I am not getting good accuracy when I am using the CIFAR-10 dataset. </p>
<p>This is my code.</p>
<pre><code>model = Sequential()
batch_size = 250
model.add(Den... | <p>There are a number of issues with your model:</p>
<ul>
<li><p>Layers 2 and 3 have no activation, and are thus linear (useless for classification, in this case)</p></li>
<li><p>Specifically, you need a softmax activation on your last layer. The loss won't know what to do with linear output.</p></li>
<li><p>You use <... | python|tensorflow|keras|neural-network | 1 |
361,176 | 54,793,406 | how to train a predict in python given this aplhanumeric dataset? | <p>I got this example dataset, with thousands of rows like this.
I need to train a model that predict the Price value based on the other 5 Values.</p>
<p>Im new in python, and Im using python 3.6 with Jupyter.</p>
<p>in other projects i was able to predict values but all the cell where numerics. </p>
<p>How can i do... | <p>I agree with Jordan's answer above. Not sure which tool you've used for modelling, but in python you can deal with such cases as follows:</p>
<ol>
<li><p>If the alphanumeric fields are categories (not unique, repeated values), you will have to create dummies.
Refer: <a href="https://towardsdatascience.com/the-dumm... | python|tensorflow|predict | 0 |
361,177 | 54,976,216 | Pandas filter values from multiple columns | <p>I want to find id which has different prod.
Here, The answer would be id-1,2, and 4 coz it has different prod.
and the answer is not id 3 coz, id 3 has similar prod.</p>
<p>How do I write a program in Python to filter the result?</p>
<pre><code> id prod
0 1 a
1 1 l
2 2 l
3 2 a
4 3 a
5 ... | <p>IIUC, you can use:</p>
<pre><code>df.loc[~df.duplicated(['id','prod'],keep=False),'id']
#or df.drop_duplicates(keep=False)['id']
0 1
1 1
2 2
3 2
7 4
8 4
</code></pre> | pandas|filter|multiple-columns | 1 |
361,178 | 54,805,301 | Changing type of entire dataframe using Lambda Function | <p>I'm trying to convert an entire dataframe into integer, i.e. all Variables to type(int), the data has NaNs present, so was going for pd.to_numeric and coercing the errors to NaN, where I can handle them later.</p>
<blockquote>
<p>But pd.to_numeric takes a list, tuple, 1-d array, or Series.</p>
</blockquote>
<p>I... | <p>You can simply do this
<code>df_copy.apply(lambda x : pd.to_numeric(x, errors='coerce'))</code></p>
<p>[<a href="https://stackoverflow.com/questions/34844711/convert-entire-pandas-dataframe-to-integers-in-pandas-0-17-0]">convert entire pandas dataframe to integers in pandas (0.17.0)</a></p> | python|pandas|lambda|data-analysis | 0 |
361,179 | 55,019,180 | Rename specific rows in pandas | <p>I would to like to rename two jobs of my datasets to "pastry". I created a dictionary with as a key the new name and as a list the previous categories</p>
<pre><code># dataframe for artificial dataframe
salary = [100, 200, 125, 400, 200]
job = ["pastry Commis ", "line cook", "pastry Commis", "pastry chef", "line co... | <p>you can use: </p>
<pre><code>df_test.job.replace({i:k for i in v for k, v in cat_ac.items()})
0 pastry Commis
1 line cook
2 pastry
3 pastry
4 line cook
</code></pre>
<p><strong><em>Note</strong>: i think you have kept a space for the first record so it didnot replace whic... | python|pandas | 2 |
361,180 | 54,981,449 | Assigning ID values to obs that share multiple characteristics | <p>have the followign dataset </p>
<pre><code>data = {'Country': ['UK','Ireland', 'Ireland', 'South Africa','Botswana','Italy','Greece'],
'Sub_ISO': ['Europe', 'Europe', 'Europe', 'Southern Africa','Southern Africa','Europe', 'Europe'],
'Language': ['EN', 'EN', 'IR', 'EN', 'EN', 'ITA', 'GRE'],
... | <p>This one seems to work!</p>
<pre><code>df['new_id'] = df.groupby(['ISO_Sub_Region','Official language']).ngroup()
</code></pre> | python|pandas|identify | 0 |
361,181 | 55,062,445 | Remove the duplicates with particular condition | <p>Data frame :</p>
<p><a href="https://i.stack.imgur.com/v6fwH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v6fwH.png" alt="enter image description here"></a></p>
<p>here i want to remove duplicates and the output should when it hits india.
<a href="https://i.stack.imgur.com/tVsAs.png" rel="nof... | <p>Or maybe like @anky_91 said but with <code>subset</code>:</p>
<pre><code>df[df.Region.str.contains('india',case=False,na=False)].drop_duplicates(subset='ticket')
</code></pre> | python-3.x|pandas|numpy | 2 |
361,182 | 54,908,785 | Generating random data iusing multiindex grouped_by dataframe object in Python | <p>The table below has summary statistics about the expense for each leader and expense type. I have the stable stored in python as a multi-index data frame object. My goal is to generate random data for each of the leaders and expense type using the mean and standard deviation under each category (run code snippet bel... | <p>This is my solution:</p>
<pre><code># Dictionary to hold generated data
rand_expenses_dict = {}
# Loop over each unique leader
for leader in agg_data.index.get_level_values("Leader").unique():
# Loop over each unique expense type
for expense_type in agg_data.index.get_level_values("Expense_Type").unique():
#... | python|pandas|numpy|pandas-groupby | 0 |
361,183 | 55,094,049 | Can't seem to drop duplicates on one dataframe but can do it for another | <p>For one Pandas dataframe in the same code, my drop_duplicates() seems to work and for the other it does not work. I can't seem to figure this out. </p>
<p>The situation where it is not working:</p>
<pre><code>df_select
df_select= #Cont on the next line
df_select.drop_duplicates(subset='RoundDown',keep='first'... | <p>You can <code>fillna</code> and using <code>duplicated</code></p>
<pre><code>df_select1=df_select1[~df_select1.RoundUp.fillna('NaN').duplicated()]
df_select1
Out[212]:
RoundDown RoundUp
0 0.10000 0.01000
1 0.20000 nan
2 0.30000 0.40000
</code></pre> | python|pandas|numpy | 2 |
361,184 | 54,858,893 | Python create combinations of ID's based on conditions | <p>Hi I would like to create combinations of ID's. I know how to create all possible combinations but am stuck on one final part of the operation. Any help will be greatly appreciated.</p>
<p>I have a dataset as follows:</p>
<p>import pandas as pd
from itertools import combinations_with_replacement</p>
<pre><code>d... | <p>I think this is one way to do what you want:</p>
<pre><code>import itertools
import pandas as pd
import numpy as np
d1 = {
'Subject': ['Subject1', 'Subject1', 'Subject1', 'Subject2', 'Subject2', 'Subject2',
'Subject3', 'Subject3', 'Subject3', 'Subject4', 'Subject4', 'Subject4',
... | python|pandas|random|data-manipulation | 1 |
361,185 | 54,859,750 | Pandas map according to values in multiple columns | <p>I want to use a mapping that maps a unique value to a DataFrame based on corresponding values for 2 or more series
For example if c is the mapping that uses values of columns 'a' and 'b' as shown</p>
<p><a href="https://i.stack.imgur.com/SLsP8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SLsP8.... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">merge</a>:</p>
<pre><code>df2.merge(df1, how="left")
</code></pre>
<p>See also the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html" rel="nofollow nore... | python|python-3.x|pandas|pandas-groupby|data-manipulation | 1 |
361,186 | 54,905,812 | how to move values in a pandas column from some position to another? | <p>I have a dataframe <code>df</code></p>
<pre><code> df:
A I
Time
7 3 7
14 2 6
21 5 5
28 7 2
35 3 0
42 0 23
49 -1 28
</code></pre>
<p>I would like to move the last two values of <code>df['I']</code> in the column from position <code>Time=21</code> ... | <p>No special Pandas way but you can do it like this:</p>
<pre><code>def swapper(old, new, df, col_name):
if len(old) != len(new):
return "Lists must be equal"
else:
for i in zip(old,new):
temp = df.loc[i[0], col_name]
df.loc[i[0], col_name] = df.loc[i[1], col_name]
... | python|pandas | 3 |
361,187 | 55,065,026 | Add 24 hours to time in python | <p>A dataframe column with values in 'time' format needs to be added with 24 hours.
eg: if 24 hours is getting added with value 10:30:30 then result expected is 34:30:30,the below code piece(added as image) generates '0 days 10:30:30' </p>
<p><a href="https://i.stack.imgur.com/Q5G31.png" rel="nofollow noreferrer">ente... | <p><strong>Sample</strong>:</p>
<pre><code>N = 10
np.random.seed(2019)
rng = pd.date_range('2017-04-03 15:30:20', periods=N, freq='13.3T')
df = pd.DataFrame({'vstime': np.abs(np.random.choice(rng, size=N) -
np.random.choice(rng, size=N))})
print (df)
vstime
0 00:39:54
1 00:13:18
... | python-3.x|pandas|dataframe | 1 |
361,188 | 54,858,841 | Why do I receive a permission error in Python while trying to write to a file as admin? | <p>I am trying to write to a file in a directory in Python. This file is also edited by another program (MT4). The file will write successfully when the MT4 program is not doing any actions within that directory. However, whenever the MT4 program is run, the python program throws an error.</p>
<p>Here is the python er... | <p><code>Running cmd.exe as an administrator</code></p>
<p>Since in Windows there is no <code>sudo</code> command you have to run the terminal (cmd.exe) as an administrator to achieve to the level of permissions equivalent to <code>sudo</code>. </p>
<pre><code>Find cmd.exe in C:\Windows\system32
Right-click on it and... | python|numpy|mql4 | 0 |
361,189 | 54,930,069 | Get the synonyms out of a dataframe | <p>I have a dataset that is comprised of {question, answer} for a chatbot training, I loaded it with pandas.
I'm trying to get a bag of synonyms for each word in each question with wordnet.synsets. and I'am having some difficulities doing so, here is the attempt that i've tried. </p>
<pre><code>import pandas as pd... | <p>You may try:</p>
<pre><code>df['synonyms_beta'] = df['synonyms'].apply( lambda x:[(y[0].name()) if len(y) >0 else "no_syn" for y in x])
</code></pre> | python|pandas|dataframe|wordnet|synset | 0 |
361,190 | 54,759,434 | Python - x-axis labels not lining up with tick marks | <p>I've successfully created the code to generate a bunch of charts. However, the x axis labels are slightly offset (to the left) from the x axis tick marks.</p>
<p><strong>Dataframe</strong></p>
<pre><code> stationId date variable value prefix uom
0 site 1 2016-04-07 pH 6.90 NaN pH
1 site... | <p>Without seeing the dataframe you are using (or at least a chunk of it) I have to speculate a bit, but it should suffice to simply adjust the alignment of the tick labels manually using </p>
<pre><code>for tick in ax1.xaxis.get_major_ticks():
tick.label1.set_horizontalalignment('center')
</code></pre>
<p>Withou... | python|pandas|matplotlib | 2 |
361,191 | 54,831,667 | How to use pandas UDF in pyspark and return result in StructType | <p>How can I drive a column based on panda-udf in pyspark. I've written udf as below:</p>
<pre><code>from pyspark.sql.functions import pandas_udf, PandasUDFType
@pandas_udf("in_type string, in_var string, in_numer int", PandasUDFType.GROUPED_MAP)
def getSplitOP(in_data):
if in_data is None or len(in_data) < 1... | <p>This will work:</p>
<pre><code>df = spark.createDataFrame([("input/variable.12-2017",), ("output/invariable.11-2018",)], ("in_data",))
df.show()
from pyspark.sql.functions import pandas_udf, PandasUDFType
@pandas_udf("in_type string, in_var string, in_numer int", PandasUDFType.GROUPED_MAP)
def getSplitOP(pdf):
... | python|pandas|pyspark | 0 |
361,192 | 54,836,257 | How to unpack a pkl file? | <p>I need to unpack a pkl file, but since I'm not familiar with pickle and pandas, I'm having a very hard time trying to do that.</p>
<p>The content of the pkl file is something like:</p>
<pre><code>{
'woodi': array([-0.07377538, 0.01810472, 0.03796827, -0.01185564, -0.12605625,
-0.03709966, 0.07863396, 0.0424... | <p>martineau is most of the way there. pickle.load() returns a dictionary that you need to do additional work on to get the words and embeddings.</p>
<p>You can start with</p>
<pre><code>import pickle
fin = 'SGlove.pkl'
data_dict = pickle.load(open(fin, 'rb'), encoding='latin1')
</code></pre>
<p>The list of words ... | python|pandas|csv|dataframe|pickle | 0 |
361,193 | 54,995,695 | In python,how to get the rows from a data frame where a particular string is present in any of the column (String value) | <p>My data frame contains <code>name</code>, <code>age</code>, <code>Task1</code>, <code>Task2</code>, <code>Task3</code>.
Now I need to get all the rows that satisfy a string value in either of <code>Task1</code>, <code>Task2</code>, <code>Task3</code> columns. Say I want to check 'Drafting', key word. If 'Drafting' ... | <p>Or just(Note this will check entire df not specific columns):</p>
<pre><code>df[df.astype(str).apply(lambda x: x.str.contains('Drafting')).any(axis=1)]
#for case insensitive use below
#df[df.astype(str).apply(lambda x: x.str.contains('Drafting',case=False)).any(axis=1)]
Name Age Task1 Task2 ... | python|string|pandas | 4 |
361,194 | 55,066,226 | How to set the minimum and maximum value for each item in a Numpy array? | <p>Suppose I have a numpy array</p>
<pre><code>a = np.array([1, 100, 123, -400, 85, -98])
</code></pre>
<p>And I want to limit each value between <code>-100</code> and <code>90</code>. So basically, I want the numpy array to be like this:</p>
<pre><code>a = np.array([1, 90, 90, -100, 85, -98])
</code></pre>
<p>I kn... | <p>There are several ways of doing so. First, using a numpy function as proposed by Sridhar Murali :</p>
<pre><code>a = np.array([1, 100, 123, -400, 85, -98])
np.clip(a,-100,90)
</code></pre>
<p>Second, using numpy array comparison :</p>
<pre><code>a = np.array([1, 100, 123, -400, 85, -98])
a[a>90] = 90
a[a<-... | arrays|python-3.x|numpy | 21 |
361,195 | 54,753,393 | Finding rows with highest means in dataframe | <p>I am trying to find the rows, in a very large dataframe, with the highest mean. </p>
<p>Reason: I scan something with laser trackers and used a "higher" point as reference to where the scan starts. I am trying to find the object placed, through out my data. </p>
<p>I have calculated the mean of each row with: </p>... | <p>Here is one way without using <code>groupby</code> </p>
<pre><code>moy=base.sort_values('Mean').tail(1)
</code></pre> | python|pandas|group-by|filtering|identity-column | 0 |
361,196 | 54,809,506 | How can I compute a Count Morgan fingerprint as numpy.array? | <p>I would like to use rdkit to generate count Morgan fingerprints and feed them to a scikit Learn model (in Python). However, I don't know how to generate the fingerprint as a numpy array. When I use </p>
<pre><code>from rdkit import Chem
from rdkit.Chem import AllChem
m = Chem.MolFromSmiles('c1cccnc1C')
fp = AllChe... | <p>Maybe a little late to answer but these methods work for me</p>
<p>If you want the bits (0 and 1):</p>
<pre><code>from rdkit.Chem import AllChem
from rdkit.Chem import DataStructs
mol = Chem.MolFromSmiles('c1cccnc1C')
fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=1024)
array = np.zeros((0, ), dtype=np.... | python|c++|numpy|scikit-learn|rdkit | 5 |
361,197 | 49,409,988 | Creating dataframe rows from keys of underlying dict | <p>I have the following dataframe:</p>
<pre><code>'A' 'B' 'Dict'
a f {'k1': 'v1', 'k2': 'v2'}
b h {}
c g {'k3': 'v3'}
… … …
</code></pre>
<p>And I would like the following:</p>
<pre><code>'A' 'B' 'Keys'
a f k1
a f k2
c g k3
… … …
</code></pre>
<p>That is, ... | <p>Or you can <code>set_index()</code></p>
<pre><code>df.set_index(['A','B'])['Dict'].apply(pd.Series).stack().reset_index()
</code></pre> | python|pandas|dataframe | 3 |
361,198 | 49,497,998 | iterative append previous value in python | <p>I have the following dataframe:</p>
<pre><code> Date A B
=====================
2015-01-01 A 0
2015-01-02 A 1
2015-01-03 A 0
2015-01-01 B 0
2015-01-02 B 0
2015-01-03 B 0
2015-01-04 B 1
2015-01-05 B 1
</code></pre>
<p>Require:</p>
<pre><code> Date ... | <p>Try</p>
<pre><code>df1['C'] = df1.groupby('A').B.apply(lambda x: x.astype(str).cumsum())
Date A B C
0 2015-01-01 A 0 0
1 2015-01-02 A 1 01
2 2015-01-03 A 0 010
3 2015-01-01 B 0 0
4 2015-01-02 B 0 00
5 2015-01-03 B 0 000
6 2015-01-04 B 1 0001
7 2015... | python|pandas | 5 |
361,199 | 49,551,603 | Select rows with the same order of values in python dataframe? | <p>I'm working on a dataframe with a column events that contains 3 values 'event1', 'event2', and 'event3'. and I'm looking for a way to select just the rows with events in a certain order ['event1', 'event2', 'event3'].</p>
<p>I tried: </p>
<pre><code>df[df['Event'].isin(['event1', 'event2', 'event3'])]
</code></pre... | <p>You'll need 3 conditons:</p>
<pre><code>m = df.Events.eq('event1')
& df.Events.shift(-1).eq('event2')
& df.Events.shift(-2).eq('event3')
</code></pre>
<p>Now shift the mask forwards:</p>
<pre><code>df[(m | m.shift() | m.shift(2))]
Events Time
4 event1 10:22:02.134
5 event2 06:... | python|pandas|dataframe | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.