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
359,500
71,020,386
Flatten only part of a dataframe shape for Euclidean calculation?
<p>I have a data frame with shape:</p> <pre><code>(20,30,1024) </code></pre> <p>I want to find the Euclidean distance between every entry and every other entry in the dataframe (ideally non-redundantly, i.e. don't find the distance of row 1 and 5....and then row 5 and 1 but not there yet). I have this code:</p> <pre><c...
<p>The most straightforward way to reshape that I can think of, according to how you described the problem, is:</p> <pre><code>df_test.values.reshape(20, -1) </code></pre> <p>By calling <code>.values</code>, you are retrieving your dataframe data as a numpy array. From there, <code>.reshape</code> finishes your job. Si...
python|pandas|scipy
2
359,501
71,067,426
ValueError: Expected 2D array, got scalar array instead: array=750
<pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.linear_model import LinearRegression data=pd.read_csv('real_estate_price_size.csv') y=data['price'] x=data['size'] y.shape x.shape </code></pre> <p>both out put is same (100,)</p> <pre><code>x...
<p>You are missing a dimension. Your prediction input should have the shape <code>(n_samples, n_features)</code>. Try something like this:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.linear_model ...
python|pandas|numpy|sklearn-pandas
0
359,502
70,793,899
python - chained assignment - receive SettingWithCopyWarning but still changing the original df?
<p>I have a dataframe:</p> <pre><code>jb = pd.DataFrame([ ['No', 75, 2.0], ['Blofeld', 140, 1.9], ['Chiffre', 114, 1.7] ], index=['b1', 'b5', 'b21'], columns=['Name', 'Weight', 'Height']) </code></pre> <p>Then if I do chained assignment as below, it won't change the original value in <code>jb</code>. ...
<p>You should not try to do what you call <em>chained assignments</em>. Pandas documentation states that it is unspecified whether you get a view (and change the original value) or a copy (and do not). AFAIK, it depends on implementation details and on the internals on Pandas optimization code.</p> <p>That being said t...
python|pandas|dataframe|chained-assignment
1
359,503
70,950,011
Python: Perform math between two dataframes of different structure
<p>I have the coefficient results of regression in one DataFrame, and am looking to apply that to current data and later add the intercept to get a model value.</p> <p>Cofficient Result:</p> <pre><code> item value 0 ab 0.0145 1 bc -0.043 2 de 0.17 3 hi 0.006 </code></pre> <p>Current data:</p> <pre><code>...
<p>You can first <code>transpose</code> the current data df. Then <code>set_index</code> of the coefficient df to &quot;item&quot; and element-wise multiply the &quot;value&quot; column to its corresponding &quot;item&quot; value in current data df. Since some item values that are in the current data df don't exist the...
python|pandas|dataframe
3
359,504
70,842,706
Percentile on column in data frame
<p>Have following code w/ output. Looking to add percentiles for each %total for the 'event' category - 'GOAL' 'MISS' 'SHOT' in relation to all entries across the entire dataset for each event category.</p> <p><a href="https://i.stack.imgur.com/BqQne.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bq...
<p>You can do a <code>groupby</code> on the <code>'event'</code> column and then use the <code>.rank</code> method with the argument <code>pct=True</code>. Using a sample df:</p> <pre><code>event_perc = pd.DataFrame({'shooterName':['A']*3+['B']*3+['C']*3, 'event':[&quot;GOAL&quot;,&quot;MISS&quot;,&quot;SHOT&quot;]*3, ...
python-3.x|pandas|dataframe|numpy|percentile
1
359,505
70,985,930
python json to csv,csv repeat loop write
<p>I need to convert a large JSON file into a csv file and read it line by line, but the code will write to the csv file in a loop, the output of the 10MB JSON file gets a 1GB csv file, and the csv file is still increasing, and the code can only be stopped manually after running.</p> <p>my code</p> <pre><code>import pa...
<p>The output <code>.csv</code> shows that it is incrementally printing the output as each line comes in. In other words, the second time you write to csv, it also prints the first with it. The third time, it prints the first and second as well (etc). This is because your script loads each line separately (which is fin...
python|json|pandas|csv
0
359,506
71,014,894
How to disable some weights in keras?
<p>Imagine I am trying to fit a model the following way:</p> <pre><code>import tensorflow as tf x_in=tf.keras.layers.Input(shape=n) x_out = tf.keras.layers.Dense(m, use_bias=False)(x_in) model = tf.keras.Model(inputs=x_in, outputs=x_out) </code></pre> <p>Now the problem is that this will create nxm weights - in my mo...
<p>Could the following applied in suitable format solve your problem:</p> <pre><code>import tensorflow as tf import numpy as np n=1 m=1 x_in=tf.keras.layers.Input(shape=n) x_out = tf.keras.layers.Dense(m, use_bias=False,trainable=True)(x_in) x_out_disabledweights = tf.keras.layers.Dense(m, use_bias=False,trainable=Fa...
python|tensorflow|keras
0
359,507
71,023,118
pandas: combine columns if they share a partly similar name
<p>I have a DataFrame as follows,</p> <pre><code>import pandas as pd df = pd.DataFrame({'sent_a.1': [0, 3, 2, 1], 'sent_a.2': [0, 1, 4, 0], 'sent_b.3': [0, 6, 0, 8], 'sent_b.4': [1, 1, 8, 6] }) </code></pre> <p>I want to combine the columns that share a name. ...
<p>You can make the columns MultiIndex and <code>unstack</code> and <code>groupby</code> the index and apply <code>join</code> to get a Series similar to the desired outcome. <code>swaplevel</code> + <code>unstack</code> will fetch the desired DataFrame.</p> <pre><code>df.columns = pd.MultiIndex.from_tuples(col.split('...
python|pandas|dataframe
2
359,508
70,802,629
Can I use Tensorflow XLA with Tflite model
<p>As in the title, can I use XLA compilation with TF lite models - according to the documentation: <code>TF_XLA_FLAGS=--tf_xla_auto_jit=2 path/to/your/tf/program</code>, so can I use it with e.g. <code>benchmark_model</code> from this site: <a href="https://www.tensorflow.org/lite/performance/measurement" rel="nofollo...
<p>No. The TensorFlow Lite code and relevant benchmark does not support / use XLA in anyway now. Adding the flag has no effect.</p>
tensorflow|tensorflow-lite
2
359,509
70,912,899
numpy randint arguments exclusive
<p>In the <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html" rel="nofollow noreferrer">official NumPy documentation</a>, <code>numpy.random.randint</code> has an exclusive second argument.</p> <pre><code>random.randint(low, high=None, size=None, dtype=int) Return random inte...
<p>You’re conflating <code>numpy.random.randint</code> with Python’s <a href="https://docs.python.org/3/library/random.html#random.randint" rel="nofollow noreferrer"><code>random.randint</code></a> (from the <code>random</code> module in the standard library), the latter of which has an inclusive upper bound.</p>
python|numpy|random
3
359,510
70,857,710
Iterate through directory and return DataFrame with number of lines per file
<p>I have a directory containing several excel files. I want to create a DataFrame with a list of the filenames, a count of the number of rows in each file, and a min and max column.</p> <p>Example file 1:</p> <p><a href="https://i.stack.imgur.com/M1YoD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.co...
<p>You're using <code>str</code> wrong. It is a function in Python, but you don't need it at all. Here, you just mean to write <code>file.startswith</code>. Now, to store the data, at each iteration you'll want to append to a list. What you can do is use dictionaries to create the data:</p> <pre><code>import pandas as ...
python|pandas|dataframe
2
359,511
71,056,731
Pandas str, int, and float columns concatenation
<pre><code>import pandas as pd import numpy as np text1 = ['22211', '1111', np.NaN] Int1 = ['5555', np.NaN, '4444'] Float1 = [np.NaN, '3333.0', '231.0'] Text2 = ['222115555', '11113333', '4444231'] df = pd.DataFrame({'Text1': text1, 'Int1': Int1, 'Float1': Float1}) df_result = pd.DataFrame({'Text1': text1, 'Int1': In...
<p>IIUC, you could cast to dtype <code>str</code>, <code>join</code>, then use <code>str.replace</code> to get rid of <code>'nan'</code> values. Then perhaps use <code>str.rstrip</code> to get rid of the trailing &quot;.0&quot;s:</p> <pre><code>df['Result'] = df.astype(str).apply(''.join, axis=1).str.replace('nan','')....
python|pandas|dataframe
1
359,512
71,017,183
Is there a function (pandas or otherwise) to interpolate quarterly data to monthly while matching averages within each quarter?
<p>I have a dataframe with quarterly forecasts that I would like to interpolate to monthly, but with a few caveats: The monthly data <em>in each quarter</em> should average to the quarterly forecast, and the monthly data should trend towards the next quarterly forecast. We currently use an old linear excel macro to do ...
<p>Welcome to Stack Overflow. Nice first question with reproducible example!</p> <p>This is not an answer, but a long comment.</p> <p>Since we have one value and need to keep the average, you can't do much. You can have like two very high values, and 1 extremely low to match the average. I would like to have them linea...
python|pandas|interpolation
0
359,513
70,866,347
Series Error when using .dtypes() for pandas
<p>I am relatively new to Python / Pandas and I am trying to print out the type of values for each column in my data frame. However, when I try to use the .dtypes() function I am getting a series error.</p> <p>Here is some of the code I am using:</p> <pre><code>file = pd.read_csv('Nudge.csv', sep=&quot;,&quot;) data ...
<p>dtypes is not a function rather a variable. It should be called like this,</p> <pre><code>print(data.dtypes) </code></pre>
python|pandas|dtype
1
359,514
70,884,955
how to plot duplicated columns on python pandas
<p>i have this data where the year column is duplicated for every month from 2018 to 2022 i want to plot the ORDNUM on monthly basis with year as my legend</p> <p><a href="https://i.stack.imgur.com/FZ2tR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FZ2tR.png" alt="the data frame view of it" /></a>...
<p>The following code generates the following picture.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import seaborn data = pd.DataFrame({&quot;Year&quot;: [2018, 2018, 2018, 2019], &quot;Month&quot;: [3, 4, 5, 3], &quot;ORDNUM&quot;: [4459, 2332, 1224, 4322]}) seaborn.relplot(data=data, x=&quot;M...
python|pandas|dataframe
1
359,515
71,038,498
Plotting piecewise functions using Matplotlib
<p><strong>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</strong></p> <p>The above error is what I got for the below code intended to plot the piecewise function created. Can't figure it out.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def ...
<p>As per comments, you need to vectorize your method <code>f</code> (and also fix some mistakes):</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def f(x): y = np.empty_like(x) mask1 = (0 &lt;= x) &amp; (x &lt;= 1) mask2 = (1 &lt; x) &amp; (x &lt;= 2) mask3 = np.logical_not((0 &lt;= ...
python|arrays|numpy|matplotlib
1
359,516
70,913,073
Performing Regression for all DataFrames Inside a List
<p>I have a list called &quot;Data&quot; contained with 81 DataFrames (df1,df2...df81) with each DataFrame having the <strong>same</strong> <strong>shape</strong> and <strong>label</strong>. Let's say the independent variables <strong>(X)</strong> are 'a','b','c', and the dependent variable <strong>(Y)</strong> is 'y'....
<p>As I understand from your question, the important part is that you can process them in parallel to speed up the computation. Therefore, you could try using multiprocessing, which spins up various processes to execute your code. One very convenient way, that is also used under the hood in sci-kit learn would be to us...
python|pandas|list|dataframe|regression
1
359,517
70,819,368
Find out the row index at which the column value stays constant until its tail end
<p>I have pd.df that stores time-history of several sensors. Column 0 is 'Time' (common for all sensors) and columns 1:N are sensor1, sensor2 ... sensorN. Some sensors (when they fail) register a value of 0 and continue to register 0 for the remainder of time history. I would like to create a log of which sensors faile...
<pre><code>sensors_mask = df.columns[df.columns.str.contains(&quot;sensor&quot;)] df[sensors_mask].apply(lambda x: x == 0).cumsum().apply(lambda x : get_failure(x)).T def get_failure(x: pd.Series) -&gt; int: if x.max() == 1: return x.index[x==1][0] + 1 else: return x.index[x==2] + 1 </code>...
pandas|dataframe|loops|rows
0
359,518
70,964,778
Set value when row is maximum in group by - Python Pandas
<p>I am trying to create a column (is_max) that has either 1 if a column B is the maximum in a group of values of column A or 0 if it is not.</p> <p>Example:</p> <p>[Input]</p> <pre><code>A B 1 2 2 3 1 4 2 5 </code></pre> <p>[Output]</p> <pre><code>A B is_max 1 2 0 2 5 0 1 4 1 2 3 0 </code></pre> <p>What I'm ...
<p>Fix your code by remove the <code>reset_index</code></p> <pre><code>df['is_max'] = 0 df.loc[df.groupby('A')['B'].idxmax(),'is_max'] = 1 df Out[39]: A B is_max 0 1 2 0 1 2 3 0 2 1 4 1 3 2 5 1 </code></pre>
python|pandas|dataframe|pandas-groupby
2
359,519
70,910,763
Import identical txt files (same file name and same columns) from different subfolders and merging them as one dataframe in Python
<p>I am trying to read identical txt files from multiple subfolders (file names and columns are same but content is different) and merge them as a master data frame. Files are located in separate subfolders whose names indicate different periods. The first picture shows the subfolders under Main_Folder: <a href="https:...
<p>Try:</p> <pre><code>import pandas as pd import pathlib root_dir = './Main_folder/' data = {} for filename in pathlib.Path(root_dir).glob('**/Cells.txt'): period = filename.parent.name.split('_')[1] data[period] = pd.read_csv(filename) Cells = pd.concat(data).droplevel(1).rename_axis('Period').reset_index(...
python-3.x|pandas|loops|operating-system|listdir
0
359,520
70,962,774
'builtin_function_or_method' object is not iterable, for loop with list
<p>I wish to do the following iteratively for a list of files of the form 'name.csv':</p> <ol> <li>Read the file in with pandas,</li> <li>Apply a function &quot;datacropper&quot; to the file</li> <li>Generate a .csv of the updated file using the pandas .to_csv command, with name of the form 'cut-name.csv'.</li> </ol> <...
<p>Something more like this. Note that it is not necessary to use <code>str()</code> on your file names. They are already strings.</p> <pre><code>nameslist = ['pi89_1','pi89_ph7_1','pi89_ph7p48','pi89_ph6p49','pi89_ph7_2'] for name in nameslist: df = pd.read_csv(&quot;/path/to/file/&quot; + name + &quot;.csv&qu...
python|pandas
1
359,521
70,826,479
ModuleNotFoundError: No module named 'pandas._libs.interval'
<p>Suddenly, I can't import pandas in python. I am using anaconda as package manager, but it seems that no matter how many times I uninstall and install pandas, I still get the same error:</p> <pre><code>(base) C:\&gt;conda install pandas Collecting package metadata (current_repodata.json): done Solving environment: do...
<p>Yes, it appears to be loading <code>pandas</code> from a user-level installation. User-level installs can leak into Conda environments and lead to unpredictable behavior, such as what you are seeing.</p> <p>There are two routes of action of which I know. You may want to try the second one first, which would confirm ...
python|pandas|anaconda
1
359,522
70,947,160
optimize numpy python function to get orthogonal distance
<p>I have 3 arrays (x_array, y_array, p_array), the first two correspond to 2d arrays with coordinates points of random points, the third is an flatten array of points corresponding to lines.</p> <p>I need to calculate the minimum orthogonal distance for each x_array, y_array point to the lines form by p_array points.<...
<p>Numba can hardly speed up Numpy functions since they are already mostly optimized. However, the performance the Numpy codes can be improved by avoiding the creation/filling of <strong>many huge temporary array</strong>. Indeed, the RAM throughput is a precious scarce resource compared the processing power of modern ...
python|numpy|time|numba
2
359,523
70,822,906
How to loop through (none, 256) shape tensor array?
<p>I am trying to write a custom loss function to a Keras model. This loss function takes in the prediction and suppresses all the predictions except the highest one to zero. Something like this:</p> <pre><code> def loss_function(y_true, y_pred): s=tf.shape(y_pred) loop=tf.unstack(y_pred) th=[tf.math.a...
<blockquote> <p>This loss function takes in the prediction and suppresses all the predictions except the highest one to zero</p> </blockquote> <p>I think this can easily be solved with <code>tf.where</code>:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf y_true = [[0, 1, 0], [0, 0, 1]] y_p...
python|tensorflow|keras|deep-learning|tensorflow2.0
2
359,524
70,832,282
How to stop and restart cumsum using a marker in another column
<p>I have a pandas dataframe with values that needs to be totalized inside a period for each device, but the periods ends are marked in another column (an easy identifiable event line). The cumsum must go until it finds this end of period marker and then start again from zero(the first value on the next line).</p> <pre...
<p>IIUC, you want to <code>cumsum</code> per group until you reach a True. Then, <strong>after</strong> this row, restart the count.</p> <p>You can use an extra group based on the &quot;end&quot; value (also using a <code>cumsum</code>):</p> <pre><code>df['total'] = (df.groupby(['device_name', ...
python|pandas|cumsum
2
359,525
70,792,538
how to read csv file with missing columns and remove first and last delimiter of each row?
<p>Dataset looks like :</p> <p><a href="https://i.stack.imgur.com/WxrO5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WxrO5.png" alt="enter image description here" /></a></p> <p>how to read this and remove first and last delimiter of each row?</p>
<p>Looks like someone just saved lists of python with a csv extension. Maybe you can try to read those list and then transform them to a data frame. Just like this</p> <pre><code>with open('file.csv','r') as file: data = file.readlines() df = pd.DataFrame(data=data) </code></pre> <p>Any ways looks like your data doesn...
python|pandas
1
359,526
71,016,005
If statement: String starts with exactly 4 digitis in Python/pandas
<p>I have a column of a dataframe consisting of strings, which are either a date (e.g. &quot;12-10-2020&quot;) or a string starting with 4 digits (e.g. &quot;4030 - random name&quot;). I would like to write an if statement to capture the strings which are starting with 4 digits, which is similar to this code:</p> <pre>...
<p>Use <code>str.contains</code>: col&quot;</p> <pre class="lang-py prettyprint-override"><code>df[df[&quot;col&quot;].str.contains(r'^[0-9]{4}')] </code></pre>
python|pandas|if-statement
1
359,527
70,828,555
How to calculate cumulative missing values group by an ID (in python)?
<p>a) given the following &quot;id&quot; and &quot;freq&quot;</p> <pre><code>df = pd.DataFrame({'id':[1,1,1,1,1,1,2,2,2,2,2,3,3,3],'freq':[1,2,np.NaN, np.NaN, np.NaN, 6,7,8,9,10,np.NaN,np.NaN,13,14]}) </code></pre> <p>df</p> <p>b) how to calculate cumulative missing of &quot;freq&quot; group by &quot;id&quot;? with a ...
<p>If you case you can do <code>groupby</code> with <code>mask</code></p> <pre><code>df['cum_null'] = df.freq.isnull().groupby(df['id']).cumsum().where(df.freq.isnull(),0) 0 0 1 0 2 1 3 2 4 3 5 0 6 0 7 0 8 0 9 0 10 1 11 1 12 0 13 0 Name: freq, dtype: int64 </code></pr...
python|pandas|cumsum
0
359,528
70,958,520
flatten nested list in pandas containing nan
<p>I have a table like this:</p> <pre><code>index | country --------------- 1 | [nan] 2 | [nan, DE] 3 | [nan, [IT, DE]] 4 | [[FR]] 5 | [[AE], nan, [AE, MT], [MX]] </code></pre> <p>And i need to turn this column into a flat list of unique values without nans</p> <pre><code>index | country ----------...
<p>This should work for any nested lists</p> <pre><code>from collections.abc import Iterable def flatten(l): for el in l: if isinstance(el, Iterable) and not isinstance(el, (str, bytes)): yield from flatten(el) else: yield el </code></pre> <p>So recreating your df</p> <pre><c...
python|pandas|dataframe|nested-lists|flatten
1
359,529
71,056,144
How to return specified text if true in pandas column
<p>I am creating a dataframe that looks at the column 'Study Title' and returns a text category in a new column 'Categories' if the 'Study Title' column contains specific text in the string. For example, if the study title contains the text 'Child Care' or 'Head Start' then it will return a value if true in the new 'Ca...
<p>What you're trying to do is essentially a mapping, which a basic membership test is not suitable for. You need to define a mapping function:</p> <pre class="lang-py prettyprint-override"><code>In [8]: def determine_category(title): ...: if &quot;Child Care&quot; in title: ...: return &quot;Child&qu...
python|pandas
0
359,530
70,841,123
Merge different length dfs and preserve all values from "master" df
<p>Working on what I think should be a simple merge but I can't find quite the right solution.</p> <p>I have two dfs of Fortune 500 companies. df1 is 2 columns (Company and CIK), 117 rows long. df2 is 2 columns (Rank, and Company) and 225 rows long. The company order is different between the dfs.</p> <p>I want a datafr...
<p>Using:</p> <pre><code>df2.to_dict() </code></pre> <p>I saw there were extra characters in</p> <pre><code>df2['Company'] </code></pre> <p>This code block deleted the additional characters, &quot;\xa0&quot;:</p> <pre><code>df2['Company'] = df2[&quot;Company&quot;].apply(lambda x: str(x).replace(u'\xa0', u'')) </code><...
pandas|dataframe|merge
0
359,531
70,905,683
Pandas - creating new column based on data from other records
<p>I have a pandas dataframe which has the folowing columns - Day, Month, Year, City, Temperature.</p> <p>I would like to have a new column that has the average (mean) temperature in same date (day\month) of all previous years.</p> <p>Can someone please assist?</p> <p><strong>Thanks</strong> :-)</p>
<p>Try:</p> <pre><code>dti = pd.date_range('2000-1-1', '2021-12-1', freq='D') temp = np.random.randint(10, 20, len(dti)) df = pd.DataFrame({'Day': dti.day, 'Month': dti.month, 'Year': dti.year, 'City': 'Nice', 'Temperature': temp}) out = df.set_index('Year').groupby(['City', 'Month', 'Day']) \ ...
pandas
1
359,532
70,971,394
How to merge headers with same name into one single header?
<p>I'm going to add MultiIndex column to my dataframe. What I got:</p> <p><img src="https://i.stack.imgur.com/LOVqy.png" alt="enter image description here" /></p> <p>What would I like to get:</p> <p><img src="https://i.stack.imgur.com/i3Xg0.png" alt="enter image description here" /></p> <p>full code:</p> <pre class="la...
<p>First thing, note that hiding a label is probably a bad idea if you're going to work with the data. The will prevent you from logically selecting your data.</p> <p>That said, if you really want to do this, you could convert the MultiIndex to DataFrame and use <code>duplicated</code> to <code>mask</code> the duplicat...
python|pandas|dataframe|multi-index
1
359,533
70,815,217
Create depth map image as 24-bit (Carla)
<p>I have a depth map encoded in 24 bits (labeled &quot;Original&quot;). With the code below:</p> <pre><code>carla_img = cv.imread('carla_deep.png', flags=cv.IMREAD_COLOR) carla_img = carla_img[:, :, :3] carla_img = carla_img[:,:,::-1] gray_depth = ((carla_img[:,:,0] + carla_img[:,:,1] * 256.0 + carla_img[:,:,2] * 256....
<p><a href="https://carla.readthedocs.io/en/latest/ref_sensors/#depth-camera" rel="nofollow noreferrer">Docs say</a>:</p> <pre class="lang-py prettyprint-override"><code>normalized = (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1) in_meters = 1000 * normalized </code></pre> <p>So if you have a depth map <code>in_...
python|numpy|opencv|depth|carla
1
359,534
51,970,738
Improper cost function outputs for Vectorized Logistic Regression
<p>I'm trying to implement vectorized logistic regression on the Iris dataset. This is the implementation from Andrew Ng's youtube series on deep learning. My best predictions using this method have been 81% accuracy while sklearn's implementation achieves 100% with completely different values for coefficients and bias...
<p>You are likely getting strange results because you are trying to use logistic regression where <code>y</code> is not a binary choice. Categorizing the iris data is a multiclass problem, y can be one of three values:</p> <pre><code>&gt; np.unique(iris.target) &gt; array([0, 1, 2]) </code></pre> <p>The cross entropy...
python-3.x|numpy|logistic-regression
1
359,535
51,851,217
How to create a table with clickable hyperlink to a local file in pandas & Jupyter Notebook
<p>I learned from this post that I can link to a website in a Jupyter Notebook: <a href="https://stackoverflow.com/questions/42263946/how-to-create-a-table-with-clickable-hyperlink-in-pandas-jupyter-notebook/42264209#42264209">How to create a table with clickable hyperlink in pandas &amp; Jupyter Notebook</a></p> <p>S...
<p>Your browser is actually blocking this. You probably see an error message like "Not allowed to load local resource" in your browser's developer tools (<a href="https://developers.google.com/web/tools/chrome-devtools/" rel="noreferrer">Chrome</a>, <a href="https://developer.mozilla.org/en-US/docs/Tools" rel="noreferr...
python|python-3.x|pandas|jupyter-notebook
5
359,536
51,701,908
Issue with running a single prediction with PyTorch
<p>I have a trained model using PyTorch now I want to simpy run it on one example </p> <pre><code>&gt;&gt;&gt; model nn.Sequential { [input -&gt; (0) -&gt; (1) -&gt; (2) -&gt; (3) -&gt; (4) -&gt; (5) -&gt; (6) -&gt; (7) -&gt; (8) -&gt; (9) -&gt; (10) -&gt; output] (0): nn.SpatialConvolutionMap (1): nn.Tanh (2)...
<p>It seems like your model is not <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Sequential" rel="nofollow noreferrer"><code>nn.Sequential</code></a> (<strong>py</strong>torch <code>Sequential</code>), but rather <a href="https://pytorch.org/docs/stable/legacy.html" rel="nofollow noreferrer"><code>torch.leg...
pytorch|torch
1
359,537
51,588,717
How to save tensorboard projector checkpoint file on one machine and open on another machine?
<p>I visualize my embeddings by <a href="https://www.tensorflow.org/versions/r1.1/get_started/embedding_viz" rel="nofollow noreferrer">Tensorboard Projector</a>. Saving checkpoint file and visualizing on one machine is no problem. But when I copy the checkpoint file to another machine, tensorboard does not recognize it...
<p>It turns out I need to save checkpoint with relative path. But it is not enough, the relative metadata path in Projector config file is still not recognizable, so I have to use an adhoc relative path. </p> <p>In general, you need to go look into each path and fix it, depending on your checkpoint dir structure.</p>
python|tensorflow|visualization|tensorboard
0
359,538
51,631,021
python - What produces the same plot as autocorrelation_plot()?
<p>I need the values of the autocorrelation coefficients coming from the <code>autocorrelation_plot()</code>. The problem is that the output coming from this function is not accessible, so I need another function to get such values. That's why I used <code>acf()</code> from <code>statsmodels</code> but it didn't get th...
<p>This seems to be related to the <code>nlags</code> parameter of <code>acf</code>:</p> <blockquote> <p>nlags: int, optional Number of lags to return autocorrelation for.</p> </blockquote> <p>I don't know what exactly this does but in the <a href="https://github.com/statsmodels/statsmodels/blob/master/statsm...
python|pandas|statsmodels
0
359,539
51,833,943
How to plot on queried data of influxdb?
<p>I am using Influx DataFrameClient in python to retrive data:</p> <pre><code>from influxdb import DataFrameClient cli = DataFrameClient(host='localhost',port = 8086,database='rahul') q= cli.query('select * from cpu') print(q) </code></pre> <p>But the query retrieves data in <code>dict</code> format with a lot o...
<p>The DataFrameClient returns a Dictionary of DataFrames with the measurement names as keys.</p> <p>If you use <code>q["cpu"]</code> that should give you your Dataframe with correct header and you can do with it whatever you want.</p>
python|pandas|plot|data-analysis|influxdb-python
0
359,540
51,565,139
writing function in pandas/python
<p>I have just started to learn python and don't have much of dev background. Here is the code I have written while learning. </p> <p>I now want to make a function which exactly does what my "for" loop is doing but it needs to calculate different exp(exp,exp1 etc) based on different num(num, num1 etc)</p> <p>how can ...
<p>I think you are looking for <code>np.where</code></p> <pre><code>df['exp']=np.where(df.str=='a',df['num']*-1,df['num']*1) df Out[281]: str num num1 exp 0 a 1 3 -1 1 b 2 4 2 </code></pre>
python|pandas
1
359,541
51,902,887
python subplot plot.bar from one dataframe and legend from a different dataframe
<p>I have two data sets below</p> <p>Df1:</p> <pre><code> Cluster HPE FRE UNE 0 0 176617 255282 55881 1 1 126130 7752 252045 2 2 12613 52326 7434 </code></pre> <p>I draw a bar diagram. (This is not an exact code of mine, but it will give you an idea)</p> <pre><cod...
<p>Explicitly set the legend to strings obtained from second dataframe (if you want the color boxes of the bars): </p> <pre><code>subp.legend([str(a) + ' - ' + str(b) for a, b in zip(df2['Cluster'].tolist(), df2['HPE'].tolist())]) </code></pre> <p>Or just use a table:</p> <pre><code>plt.table(cellText=df2[['Cluster'...
python|pandas|dataframe|matplotlib|legend
0
359,542
51,732,472
Sort, groupby, and get a row and row+1 for a specific column value?
<pre><code> C1 route_Seq Connection_time Mod_trans R1 1 10 road R1 2 2 air R1 3 4 air R1 4 2 road R1 5 3 air R1...
<p>Let's try:</p> <pre><code>df['CumRoad'] = (df.sort_values('route_Seq') .groupby('C1') .apply(lambda x: (x['Mod_trans']=='road').cumsum()).values) df_out = (df.groupby(['C1','CumRoad']) .apply(lambda x: x.head(2)['Connection_time'].sum()) .reset_index())...
python|pandas|group-by|sum|multi-index
3
359,543
51,587,291
How to convert date stored in YYYYMMDD to datetime format in pandas
<p>I have a column in dataframe which is in YYYYMMDD format i want convert into datetime format . How can do in pandas.</p> <pre><code> Input 20180504 20180516 20180516 20180517 **Expected Output** Date datetime 20180504 04/5/2018 00:00:00 20180516 16/5/2018 00:00:00 20180516 16/5/2018 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a>:</p> <pre><code>df['datetime'] = pd.to_datetime(df['Input'], format='%Y%m%d') print (df) Input datetime 0 20180504 2018-05-04 1 20180516 2018-05-16 2 20180516 2018-05-...
python-3.x|pandas
8
359,544
51,612,463
Build tensorflow dataset iterator that produce batches with special structure
<p>As I mentioned in the title I need batches with special structure:</p> <pre><code>1111 5555 2222 </code></pre> <p>Each digit represent feature-vector. So there are <code>N=4</code> vectors of each classes <code>{1,2,5}</code> (<code>M=3</code>) and batch size is <code>NxM=12</code>.</p> <p>To accomplish this task...
<p>If you have the list of files ordered by class, you can interleave the datasets:</p> <pre><code>import tensorflow as tf N = 4 record_files = ['class1.tfrecord', 'class5.tfrecord', 'class2.tfrecord'] M = len(record_files) dataset = tf.data.Dataset.from_tensor_slices(record_files) # Consider tf.contrib.data.paralle...
python|tensorflow|dataset
3
359,545
51,981,095
How to change Keras/tensorflow version in Google colab?
<p>I'm using keras/tensorflow on google colaboratory and I need to go back to previous versions of them. </p> <p>The problem is when I run <code>!pip install q keras==1.2.2</code> , the kernel shows keras 1.2.2 installed but when I check it using <code>keras.__version_</code> it shows 2.1.6 . And same case is with ten...
<p>I had this issue yesterday. I was rather surprised that installing packages did not have an effect. But I realised then that I needed to restart the kernel. In Colab this is called <code>Restart runtime</code>. After restart the new version should be available for you.</p> <p><em>Here you find the restart:</em></p>...
python|tensorflow|keras|google-colaboratory
16
359,546
51,623,779
Delete columns but keep specific values pandas df
<p>I'm sure this is in SO somewhere but I can't seem to find it. I'm trying to remove or select designated <code>columns</code> in a <code>pandas df</code>. But I want to keep certain values or <code>strings</code> from those deleted <code>columns</code>. </p> <p>For the <code>df</code> below I want to keep <code>'Big...
<p>Seems like you want to keep only some values and have empty string on ohters</p> <p>Use <code>np.where</code></p> <pre><code>keeps = ['Big', 'Cat'] df['B'] = np.where(df.B.isin(keeps), df.B, '') df['C'] = np.where(df.C.isin(keeps), df.C, '') A B C 0 A Big Cat 1 Keep 2 A Big ...
python|pandas|dataframe
2
359,547
51,938,859
Neural Network Regression
<p>I had a question, For a given data set X with two classes {0,1}. If I train two separate neural networks NN0 and NN1 for each class 0 and 1 respectively. Can NN0 predict points in the dataset from class 1, even though it was trained on class 0?</p>
<p>In short, no. This isn't how neural networks, or machine learning in general works. You train your model to recognise both of the classes of your data and that one model can then be used to predict the class of data it hasn't seen.</p> <p>This is a great overview of what neural networks are, done by someone very sm...
python-3.x|tensorflow|neural-network|keras|regression
1
359,548
51,824,219
ImportError: Could not find 'cudnn64_7.dll'
<p>I am encountering the following error: </p> <pre><code> Traceback (most recent call last): File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\self_check.py", line 87, in preload_check ctypes.WinDLL(build_info.cudnn_dll_name) File "C:\Anaconda\envs\tensorflow\lib\ctypes\__init_...
<p>for me it was that i didn't install cuDNN. download it according to ur cuda version and extract it in cuda directory</p>
python|tensorflow|anaconda|cudnn
2
359,549
51,631,409
How to pass image urls to a feed_dict in tensorflow session?
<p>I was trying to pass image urls through feed_dict for inference from a tensorflow app deployed in Google Cloud Platform for a locally trained model as all my images are stored in Google cloud storage.</p> <p>I tried this:</p> <pre><code> logits = sess.run([pred], feed_dict = {image_paths_placeholder:urllib.urlop...
<p><a href="https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/inception.py#L353" rel="nofollow noreferrer">Here</a> is and example on how to use "feed_dict":</p> <pre><code> image_data = tf.gfile.FastGFile(image_path, 'rb').read() # Image is passed in as a jpeg-encoded image. feed_dict = {self...
tensorflow|google-cloud-platform
0
359,550
51,896,840
np.ma.average() to avoid DivideByZero error
<p>I am taking means of quantities like:</p> <pre><code>mean = np.ma.average(X,weights=weights, axis=1) </code></pre> <p><code>X</code> is a 2-dim array of 100 col, 1000 rows. <code>weights</code> has the same shape and the result <code>mean</code> is 1000 rows as expected. The advantage over np.average() is that for...
<p>You can find the index of rows where not all of the weights are zero, then filter the output using that:</p> <pre><code>ind=np.any(weights,axis=1) ans=np.mean(X*weights,axis=1)[ind] </code></pre> <p><strong>Edit:</strong></p> <p>To keep the dimension the same and skip invalid rows in plots, you can simply set the...
numpy|matplotlib
1
359,551
51,655,598
How to Select Top 1000 words using TF-IDF Vector?
<p>I have a Documents with 5000 reviews. I applied tf-idf on that document. Here <strong>sample_data</strong> contains 5000 reviews. I am applying tf-idf vectorizer on the sample_data with <strong>one gram range</strong>. Now I want to get the top 1000 words from the sample_data which have <strong>highest tf-idf values...
<p>TF-IDF values depend on individual documents. You can get top 1000 terms based on their count (Tf) by using the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html" rel="nofollow noreferrer"><code>max_features</code> parameter of TfidfVectorizer</a>:</p> <bl...
python-3.x|scikit-learn|tf-idf|sklearn-pandas|tfidfvectorizer
5
359,552
51,645,417
Assigning City Name by Latitude/Longitude values in Pandas Dataframe
<p>I have this data frame:</p> <pre><code> userId latitude longitude dateTime 0 121165 30.314368 76.384381 2018-02-01 00:01:57 1 95592 13.186810 77.643769 2018-02-01 00:02:17 2 111435 28.512889 77.088154 2018-02-01 00:04:02 3 129532 9.828420 76.310357 201...
<p>The code snippet that you are using was from 2013; the Google API has changed and <code>'postal_town'</code> is no longer available.</p> <p>You can use the following code which takes advantage of the <code>requests</code> library and places a guard in the case of no results being returned.</p> <pre><code>In [48]: ...
python|pandas|google-maps|numpy|dataframe
1
359,553
51,644,736
xlsxwriter and pandas for reporting
<p>I am trying to create a basic excel report.</p> <p>I am trying display a dataframe as well as some custom text/titles, not part of the dataframe.</p> <p>However, I can only get one or the other. I don't really understand the end of the code that is needed for the dataframe to appear (<code>workbook = writer.book</...
<p>It's not clear to me whether you're trying to write multiple sheets in one Excel file. If so, the problem may be that you're re-writing the same sheet called 'Reports' four times. Also, here are some basics to try. Put the <code>df.to_excel()</code> after <code>pd.ExcelWriter()</code>. Then remove from the <code>for...
python|pandas|xlsxwriter
1
359,554
51,906,144
Pytorch: Image label
<p>I am working on an image classifier with 31 classes(Office dataset). There is one folder for each of the classes. I have a python script written using PyTorch that loads the dataset using <code>datasets.ImageFolder</code> and assigns a label to each image and then trains. Here is my code snippet for loading data:</...
<p>The class ImageFolder has an attribute <code>class_to_idx</code> which is a dictionary mapping the name of the class to the index (label). So, you can access the classes with <code>data.classes</code> and for each class get the label with <code>data.class_to_idx</code>.</p> <p>For reference: <a href="https://github...
python-3.x|image-processing|machine-learning|pytorch
29
359,555
51,632,900
Pandas apply kruskal-wallis to numeric columns
<p>I have a dataframe of 27 columns (26 are numeric variables and the 27th column tells me which group each row is associated with). There are 7 groups in total I'm trying to apply the Kruskal-Wallis test to each variable, split by group, to determine if there is a significant difference or not.</p> <p>I have tried:</...
<p>With Scipy, you could do like that for each variable:</p> <pre><code>scipy.stats.kruskal(*[group["variable"].values for name, group in df.groupby("treatment")]) </code></pre>
python-3.x|pandas|apply|kruskal-wallis
6
359,556
51,747,591
Match word (starting with plus symbol) in pandas data frames
<p>I have two pandas data frames. I would like to find matching strings in one specific column ("keyword") exist in both data frames.</p> <pre><code>keyword adGroup goal6Value adCost [aaaa] (not set) 0 0.0 +bb +bb (not set) 0 ...
<p>I cannot recreate your issue, the below test works fine. I'd suggest casting your keyword column as dtype object in both dataframes (<code>df1['keyword'] = df1['keyword'].astype(object)</code> | <code>df2['keyword'] = df2['keyword'].astype(object)</code>)</p> <p>dtype object seems to work for me, as shown below:</p...
python|pandas
1
359,557
51,685,117
What kind of shape should I feed into this placeholder in tensorflow?
<pre><code>self.input_y = tf.placeholder(tf.int32, [None,],name="input_y") </code></pre> <p>[None,] is weird and I don't know what kind of shape of data should I feed in and I get error like this:</p> <pre><code>ValueError: Cannot feed value of shape (64, 1999) for Tensor 'input_y:0', which has shape '(?,)' </code><...
<p>1-D array is OK, whatever length is.</p> <p>If length is constrained, <code>None</code> should be replaced with a fixed number. Normaly, a Tensor has a <code>shape</code> attribute and <code>get_shape()</code> method to get the static shape.</p> <p>Details can be found at official tutorial like <a href="https://ww...
python|tensorflow
0
359,558
51,827,058
Pandas: average over duplicate index values in DataFrame
<p>Say I have the following DataFrame:</p> <pre><code>df = pd.DataFrame({'a':[0,1,2,3,1,2,3,4], 'b':[4,4,2,4,6,7,8,9]}, index = ['2010Q1', '2010Q1', '2010Q2', '2010Q2', '2010Q2', '2010Q3', '2010Q3', '2010Q4']) a b 2010Q1 0 4 2010Q1 1 4 201...
<p>I think @user3483203's <code>groupby</code> approach is the most straightforward. But one additional option is to use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table()</code></a>:</p> <pre><code>df.reset_index().pivot_ta...
python|pandas|dataframe
1
359,559
51,772,001
Optimizations to be had for numpy/scipy splines over large TIFF stack ndarrays?
<p>So I'm trying to remove <em>all</em> background from <em>all</em> frames of a TIFF stack. Basically, I want to fit a spline for every row for every frame.</p> <p>I know there are also ways to correct for local background to reduce overhead with naive background "rings" around located samples to quickly do it for mu...
<p>Without benchmarking it myself, I would guess that this line is perhaps the culprit: </p> <pre><code>ls = [Spline(ix, frame[i, :], k = deg, s = s)(ix) for i in range(rows)] </code></pre> <p>If you could vectorize that operation you would get a speedup. You could also try something like this <a href="https://docs.s...
python|numpy|optimization|scipy
1
359,560
51,950,049
How to change dataframe cells values with "coordinate-like" indexes stored in two lists/vectors/series?
<p>Apologize if this has been asked before, somehow I am not able to find the answer to this.</p> <p>Let's say I have two lists of values:</p> <pre><code>rows = [0,1,2] cols = [0,2,3] </code></pre> <p>that represents indexes of rows and columns respectively. The two lists combined signified sort of coordinates in th...
<p>Very simple! Exploit the fact that pandas is built on top of <code>numpy</code> and use <code>DataFrame.values</code> </p> <pre><code>df.values[rows, cols] = np.nan </code></pre> <p>Output:</p> <pre><code> 0 1 2 3 0 NaN 1.0 1.0 1.0 1 1.0 1.0 NaN 1.0 2 1.0 1.0 1.0 NaN 3 1.0 1.0 1.0 1....
python|pandas
5
359,561
51,652,911
Subsection of grid as input to cnn
<p>I have two huge grids (input and output) representing some spatial data of the same area. I want to be able to generate the output pixel-by-pixel by feeding a neural network a small part of the input grid, around the pixel of interest. </p> <p>The naive way of training and evaluating on the CNN would be to extract ...
<p>It seems to me that you are looking for a <a href="https://www.quora.com/How-is-Fully-Convolutional-Network-FCN-different-from-the-original-Convolutional-Neural-Network-CNN" rel="nofollow noreferrer">fully convolutional network</a> (FCN).</p> <p>By using only layers that scale in size with their inputs (banishing t...
tensorflow|machine-learning|keras|conv-neural-network
2
359,562
51,904,333
How to use Cross Entropy loss in pytorch for binary prediction
<p>In the pytorch docs, it says for cross entropy loss:</p> <blockquote> <p>input has to be a Tensor of size (minibatch, C)</p> </blockquote> <p>Does this mean that for binary (0,1) prediction, the input must be converted into an (N,2) tensor where the second dimension is equal to (1-p)?</p> <p>So for instance if ...
<p>Quick and easy: yes, just give 1.0 for the true class and 0.0 for the other class as target values. Your model should also generate two predictions for that case, though it would be possible to do that with only a single prediction and use the sign information to determine the class. In that case, you wouldn't get a...
pytorch
0
359,563
51,625,529
How to use tf.data's initializable iterator and reinitializable interator and feed data to estimator api?
<p>All the official google tutorials use the one shot iterator for all the estimator api implementation, i couldnt find any documentation on how to use tf.data's initializable iterator and reinitializable interator instead of one shot iterator.</p> <p>Can someone kindly show me how to switch between train_data and tes...
<p>To use either initializable or reinitializable iterators, you must create a class that inherits from tf.train.SessionRunHook. This class then have access to the session used by the tf.estimator functions. </p> <p>Here is quick example that you can adapt to your needs :</p> <pre><code>class IteratorInitializerHook(...
python|tensorflow|tensorflow-datasets|tensorflow-estimator
5
359,564
51,604,590
Array index inside vectorization
<p>Is there a way to utilize the array indices within a vectorized numpy equation?</p> <p>Specifically, I have this looping code that sets each value of a 2d array to the distance to some arbitrary center point.</p> <pre><code>img=np.ndarray((size[0],size[1])) for x in range(size[0]): for y in range(size[1]): ...
<p>You can solve this easily using broadcasting:</p> <pre><code>import numpy as np size = (64, 64) center = (32, 32) x = np.arange(size[0]) y = np.arange(size[1]) img = np.sqrt((x - center[0]) ** 2 + (y[:, None] - center[1]) ** 2) </code></pre>
python|numpy|array-broadcasting
3
359,565
51,938,666
How can I convert the name of a pandas series into a string?
<p>I am writing a function where the argument is a <code>pandas</code> Series and I want to be able to print the name of the <code>pandas</code> series. Here is the function I have so far:</p> <pre><code>def chi2_ind_reps(x): if chi2_ind(df['n_killed'], x) is True: print('n_killed is dependent on ') if...
<p>You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.name.html" rel="nofollow noreferrer"><code>name</code></a> attribute of the series.</p> <p>Look also at <a href="https://stackoverflow.com/questions/46120478/pandas-series-name">this question</a> for a similar case.</p>
python-3.x|pandas|dataframe|series
0
359,566
51,968,465
Converting the data file from the source sheet into the target sheet format using python.
<pre><code>import pandas data = pandas.read_csv("Source_Sheet.csv") data1 = pandas.read_csv("Target sheet.csv") #print(data.dtypes) data1["permanent address"] = data["Permanent Address"] data1["delhi address"] = data["Delhi Address"] name_party_area = data["Name of Member \nParty \nConstituency(State)"].str.split('\...
<p>I'm not sure if I understood your question correctly, but this is my suggestion.</p> <pre><code>import pandas as pd import re data = pd.read_csv(r"../notebooks/Source Sheet.csv") data.head() </code></pre> <p><a href="https://i.stack.imgur.com/jm359.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.co...
python|python-3.x|pandas|csv
2
359,567
51,918,136
not able to change object to float in pandas dataframe
<p>just started learning python. trying to change a columns data type from object to float to take out the mean. I have tried to change [] to () and even the "". I dont know whether it makes a difference or not. Please help me figure out what the issue is. thanks!!</p> <p>My code:</p> <pre><code>df["normalized-losses...
<p>Welcome to Stack Overflow, and good luck on your Python journey! An important part of coding is learning how to interpret error messages. In this case, the traceback is quite helpful - it is telling you that you cannot call <code>normalized</code> after <code>df</code>, since a dataframe does not have a method of th...
python|pandas|object|types
2
359,568
51,718,341
How to run prediction (using image as input) for a saved model?
<p><strong>Problem:</strong></p> <p>I am very new to Tensorflow. My specific question is what particular arguments should I put inside <code>sess.run(fetches, feed_dict)</code> function. For instance, how could find out what the values of the arguments?</p> <p><strong>Steps:</strong></p> <p>Here is my understanding of ...
<p>the arguments actually depend on what you're doing, but mostly the first argument is the weights and placeholders. Whenever you are working with Tensorflow, you define a graph which is fed examples(training data) and some hyperparameters like learning rate, global step etc. It’s a standard practice to feed all the t...
python|tensorflow
2
359,569
51,747,008
python: Returning mininum in numpy.ndarray
<p>I have an array [test] of type numpy.ndarray:</p> <pre><code>[' -0.1 ' ' -0.4 ' ' -0.6 ' ' -0.2 ' ' -3.4 ' ' 0.0 ' ' -1.9 ' ' -1.2 ' ' -0.5 '] </code></pre> <p>and want to find the minimum value.</p> <p>If I do <code>print min(test)</code> the value returned is -0.1 which is not the minimum (i.e. -3.4)</p> <p>Ho...
<p>Convert first:</p> <pre><code>test.astype(float).min() </code></pre>
python|arrays|numpy|minimum
4
359,570
51,727,095
How to calculate eigen values if hamiltonian contains some constants
<p>My hamiltonian is a matrix of the following form. I want to calculate eigen values from this hamiltonain. But I don't know how to deal with U and t? Should I put them 1?</p> <pre><code>`H=[[0 t t 0 0 0] [t U 0 t 0 0] [t 0 U t 0 0] [0 t t 0 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0]]` </code></pre>
<p>Sympy module provide operation on symbolic values</p> <pre><code>from sympy import * U = symbols('U') t = symbols('t') H = Matrix([[0, t, t, 0, 0, 0], [t, U, 0, t, 0, 0], [t, 0, U, t, 0, 0], [0, t, t, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) H.eigenvects() # eigenvectors H....
python|numpy
0
359,571
51,947,109
Calculate distinct values of column and its parallel value mapping in the next column
<p>Input:</p> <pre><code>df=pd.DataFrame( { 'BusId':['ABC1','ABC1','ABC2','ABC4','ABC5','ABC5'], 'Route':[101,102,102,104,104,106] }) df </code></pre> <p>Need to Calculate distinct values of BusId and its value mapping. </p> <p>Expected Output 1:</p> <pre><code> BusId Route 101 ABC1 ...
<p>You can create one <code>DataFrame</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.agg</code></a>:</p> <pre><code>df1 = df.groupby('Route')['BusId'].agg([','.join, 'size']).reset_index() print ...
python|pandas
1
359,572
51,843,541
Keras model to tensorflow.keras
<p>I have a model that I made with <code>Keras</code> (using <code>Tensorflow</code> as backend). Now I want to use the <code>Keras</code> inside the <code>Tensorflow</code> release.</p> <p>However, replacing this line</p> <pre><code>from keras.engine.topology import get_source_inputs </code></pre> <p>with this line...
<p>Updating Keras to version 2.2.4 seems to do the trick for me! </p> <p>You can then import the <code>get_source_inputs</code> function in one of the following ways:</p> <pre><code>from keras.utils import get_source_inputs from keras.utils.layer_utils import get_source_inputs </code></pre> <p>or if you are not usin...
python|tensorflow|keras
5
359,573
51,774,318
In pandas expanding/rolling function, how to use the index of the a dataframe or series?
<p>Let say I have a <code>pandas.Series</code> with a datetime index:</p> <pre><code>srs = pd.Series(index = pd.date_range('2013-01-01','2013-01-10' )).fillna(1) </code></pre> <p>I can use the <code>expanding</code> function to calculate say expanding sum of the series. </p> <pre><code>srs.expanding(5).sum() </code>...
<p>You can get access to the indices by using the expanding, but if the indices have the same type as values. For example it works:</p> <pre><code>s1 = pd.Series(index = range(10)).fillna(1) s1.expanding(5).agg(lambda x: x.index[-1]) </code></pre> <p>But it doesn't work:</p> <pre><code>srs = pd.Series(index = pd.dat...
python|pandas|datetime|dataframe
0
359,574
51,683,915
How can I limit regression output between 0 to 1 in keras
<p>I am trying to detect the single pixel location of a single object in an image. I have a keras CNN regression network with my image tensor as the input, and a 3 item vector as the output.</p> <p><strong>First item</strong>: Is a 1 (if an object was found) or 0 (no object was found)</p> <p><strong>Second item</stro...
<p>The sigmoid activation produces outputs between zero and one, so if you use it as activation of your last layer(the output), the network's output will be between zero and one.</p> <pre><code>output = Dense(3, activation="sigmoid")(dense) </code></pre>
python|tensorflow|machine-learning|keras|conv-neural-network
11
359,575
51,810,888
Convert the following time info to something that pyplot can recognise
<p>I have a DataFrame with two columns of time information. The first is the epoch time in seconds, and the second is the corresponding formatted str time like <code>"2015-06-01T09:00:00+08:00"</code> where <code>"+08:00"</code> denotes the timezone. </p> <p>I'm aware that time formats are <a href="https://stackoverfl...
<p><strong>UPDATE</strong> (per comments)<br> It seems like the confusion here is stemming from the fact that the call to <code>plt.plot()</code> takes positional <code>x</code>/<code>y</code> arguments instead of keyword arguments. In other words, <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.htm...
python|pandas|datetime|matplotlib|datetime-format
2
359,576
51,849,095
Wrong results with Pandas stack/unstack
<p>I have this Pandas DataFrame:</p> <pre><code> rnd non-rnd first last andrew wood 0 123 bob wood 0 234 charlie wood 0 345 </code></pre> <p>Can someone explain the difference between the following two operations:</p> <pre><code>In [1]: df.unstack(level=0).s...
<p>So my solution for this , always using <code>stack</code> before <code>unstack</code> , make the index or columns became simple index , rather than keep both of them are multiple index. <strong><em>(It is bug for sure , see the comments above , there are <a href="https://github.com/pandas-dev/pandas/issues/17225" re...
python|pandas
2
359,577
51,973,529
Python Regex-Keep Alpha Characters Continuously Adjacent/Inside Numeric Sequences
<p>I am trying to extract model numbers from a very messy string field in pandas. The complication is that these serial numbers are not just numeric but sometimes alphanumeric. What I am trying to accomplish is to create a regex capture group/combo that allows me to capture alpha characters ONLY when they continuousl...
<p>You may use</p> <pre><code>df['model_number_stripped'] = df['model_number'].str.replace(r'\W+|(?&lt;!\d)[^\W\d_](?![^\s\d]*\d)', '') </code></pre> <p>See this <a href="https://regex101.com/r/SCq3Tv/1" rel="nofollow noreferrer">regex demo</a></p> <p><strong>Details</strong></p> <ul> <li><code>\W+</code> - 1 or mo...
python|regex|pandas
1
359,578
35,980,747
AttributeError: 'numpy.ndarray' object has no attribute 'columns'
<p>I'm trying to create a function to remove the features that are highly correlated with each other. However, I am getting the error <code>''AttributeError: 'numpy.ndarray' object has no attribute 'columns' '' ...</code></p> <p>I just want to call pandas to read columns number. What can I do next?</p> <pre><code>...
<p>Check the Pandas documentation, but I think</p> <pre><code>X_train = df_train.drop(['ID','TARGET'], axis=1).values </code></pre> <p><code>.values</code> returns a <code>numpy</code> array, not a Pandas dataframe. An array does not have a <code>columns</code> attribute.</p> <p><code>remove_features_identical</code> ...
python|numpy|pandas
7
359,579
36,062,486
numpy 2d boolean array indexing with reduce along one axis
<p>This question is similar to <a href="https://stackoverflow.com/questions/26284846/multidimensional-boolean-array-indexing-in-numpy">this</a> one.</p> <p>I have a 2d boolean array "belong" and a 2d float array "angles". What I want is to sum along the rows the angles for which the corresponding index in belong is Tr...
<p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p> <pre><code>np.einsum('ij,ij-&gt;i',belong,angles) </code></pre> <p>You can also use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.bincount.h...
python|numpy
2
359,580
36,210,977
python numpy.savetxt header has extra character #
<p>I am using the following to save the numpy array x with a header:</p> <pre><code>np.savetxt("foo.csv", x, delimiter=",", header="ID,AMOUNT", fmt="%i") </code></pre> <p>However, if I open "foo.cv", the file looks like:</p> <pre><code># ID,AMOUNT 21,100 52,120 63,29 : </code></pre> <p>There is an extra <code>#</co...
<p>The header and footer text are added as comments. If you want to change the comment identifier, pass the <code>comments</code> option (the default is <code>#</code>):</p> <pre><code>np.savetxt("foo.csv", x, delimiter=",", header="ID,AMOUNT", fmt="%i", comments='') </code></pre> <p>As <a href="http://do...
python|numpy|header
37
359,581
36,197,842
Pandas indexer methods and tuples as parameters
<p>Let's say I have a pandas <code>Series</code>, and I want to access a set of elements at specific indices, like so:</p> <pre><code>In [1]: from pandas import Series import numpy as np s = Series(np.arange(0,10)) In [2]: s.loc[[3,7]] Out[2]: 3 3 7 7 dtype: int64 </code></pre> <p>The <code>.loc</code> metho...
<p>It's hard to answer this in a systematic way, so I'll just answer list-style:</p> <ol> <li>I think the bigger question may be what exactly are you trying to do but are not able to? I.e. why do you want to use <code>()</code> instead of <code>[]</code> when <code>[]</code> is the standard way?</li> <li>Your first q...
python|pandas
2
359,582
36,071,241
How to write a function that uses a pandas data frame variable as input?
<p>I would like to write a function that will generate a plot and take a variable as input. I am new to <code>Python</code> and have more experience with <code>R</code>. I have seen function that involve a variable from a <code>pandas</code> data frame generally use <code>apply()</code> but I don't know how to condit...
<pre><code>def mykdeplot(df, var, width): sns.kdeplot(np.array(getattr(df[df.Group == 'a'], var)), bw=width, label = "Group A") sns.kdeplot(np.array(getattr(df[df.Group == 'b'], var)), bw=width, label = "Group B") mykdeplot(df, 'X1', 3) </code></pre>
python|function|pandas|seaborn
1
359,583
36,072,042
Numpy tensor: Tensordot over frontal slices of tensor
<p>I'm trying to perform a matrix multiplication with frontal slices of a 3D tensor, shown below. If <code>X.shape == (N, N)</code>, and <code>Y.shape == (N, N, Y)</code>, the resulting tensor should be of shape <code>(N, N, Y)</code>.</p> <p>What's the proper <code>np.tensordot</code> syntax to achieve this?</p> <p>...
<p>Looks like the above is equivalent to the following:</p> <pre><code>np.tensordot(X, tensor, axes=1) </code></pre> <p><code>axes=1</code>, because (if the <code>axes</code> argument is a scalar) <code>N</code> should be the last axis of the first argument, and <code>N</code> should be the first axis of the second a...
python|numpy|matrix-multiplication
1
359,584
36,015,170
How can I add labels to TensorBoard Images?
<p>TensorBoard is a great tool, but can it be more robust? The image below shows the visualization in TensorBoard.</p> <p>It's called by the following code:</p> <pre><code>tf.image_summary('images', images, max_images=100) </code></pre> <p>As the API suggests, the last digit is the "image number", from 0 to 99 in th...
<p>I haven't been able to find a way to do this using only tensorflow, so instead I do the following:</p> <ol> <li>Create a placeholder for the summary images (e.g. like a (10, 224, 224, 3) for ten summary images).</li> <li>Create the image summary based on that placeholder.</li> <li>During validation (or training, if...
python|tensorflow|tensorboard
7
359,585
35,958,139
TensorFlow: how can I sum a list of tf.Variables?
<p>I've got a 3D array that is of <code>tf.Variable</code> type. <code>tf.reduce_sum</code> only works on individual tensors. I've tried doing:</p> <pre><code>tf.reduce_sum([tf.reduce_sum(mat) for mat in var_3Dlist]) </code></pre> <p>...but <code>tf.reduce_sum()</code> expects a tensor and not a list. Can I convert i...
<p>The <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/math_ops.html#reduce_sum" rel="noreferrer"><code>tf.reduce_sum()</code></a> op works on 3-D tensors and variables (and in general any rank or tensor or variable). However, if you have a <strong>list</strong> of 2-D tensors (or variables), you shou...
python|tensorflow
7
359,586
35,976,215
error in strpdate2num converter in matplotlib
<p>I am trying to read from file a datetime string followed by some data. It provide error. I reduced it to following task which produces error </p> <pre><code>import numpy as np from matplotlib.dates import strpdate2num from io import StringIO d = StringIO(u'16-03-13 20:13:55') date = np.loadtxt(d, converters={0:st...
<p>The problem is because <code>np.loadtxt</code> is trying to split your string up into two components, as its default delimiter is a space and you have a space in your string. </p> <p>If you change the delimiter to anything else, this will work, for example:</p> <pre><code>date = np.loadtxt(d, converters={0:strpdat...
python|numpy|matplotlib
1
359,587
36,094,261
How to use BS4 to detect no table data on page
<p>I am having difficulty parsing this HTML table using BS4. Sometimes the page doesn't have payment data and will say "There is no pending manifest payment". Other times, the page will list out all the pending payments due. I'd like to have this data output into an array. </p> <pre><code>def find_payment(html): s...
<p>Why not just soup lookup for the "td" with class either <strong>success</strong> or <strong>body10</strong>? </p> <pre><code> def find_payments(html): soup = BeautifulSoup(html) if soup.find("td", {"class":"success"}): payments = "There is no pending manifest payment" else:...
selenium|pandas|html-table|beautifulsoup
1
359,588
35,863,289
Pandas DataFrame won't reindex and transpose, returns NaN
<p>I am reading the first 9 lines from a .csv into a DataFrame, which works properly:</p> <pre><code>invoice_desc = pd.read_csv('path', sep=',', nrows = 9, header=None) </code></pre> <p>When printed, DataFrame looks like so:</p> <pre><code> 0 1 0 Bill to ...
<p>I think you can first select subset of <code>invoice_desc</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a>, transpose it by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html" rel="nofollow"><co...
python|pandas
1
359,589
36,129,452
mysql,how to back up data to another machine
<p>I have a large mysql database in server_1(<code>OS is Windows</code>), and I want to copy all the data in server_1 to server_2(<code>OS is Centos</code>). I tried export the data in server_1 to sql file and source the sql file in server_2, but it costs a lot of time. </p> <p>I think write code(<code>Pandas</code>) ...
<p>take backup from your windows machine by mysqldump from command line:</p> <pre><code>mysqldump -R --triggers --events -uroot -p&lt;root_pass&gt; --all-databases &gt; c:/backup/mybackup.sql </code></pre> <p>Now move this backup to your centos machine, you can take help of winscp (you can archive if required):</p> ...
python|mysql|pandas
2
359,590
36,008,648
Colorbar on Geopandas
<p>I am trying to create a Matplotlib colorbar on GeoPandas.</p> <pre><code>import geopandas as gp import pandas as pd import matplotlib.pyplot as plt #Import csv data df = df.from_csv('data.csv') #Convert Pandas DataFrame to GeoPandas DataFrame g_df = g.GeoDataFrame(df) #Plot plt.figure(figsize=(15,15)) g_plot = ...
<p><strong>EDIT:</strong> The PR referenced below has been merged into the geopandas master. Now you can simply do:</p> <pre><code>gdf.plot(column='val', cmap='hot', legend=True) </code></pre> <p>and the colorbar will be added automatically.</p> <p>Notes:</p> <ul> <li><code>legend=True</code> tells Geopandas to add...
python|pandas|matplotlib|geopandas
49
359,591
36,000,824
how to identify specific sequences (round-trips) in a pandas dataset?
<p>I have a simple, yet challenging algorithmic problem to solve.</p> <p>I have a dataset at the trader - stock - day level, and I want to identify the round-trips in the data. Round-trips are just specific sequences in the data. That is, if you cumulate over time the holding position of stock s for individual i, a ro...
<p>I would do something like this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'trader' : ['a','a','a','a','a','a','a'],'stock' : ['a','a','a','a','a','a','b'], 'day' :[0,1,2,4,5,10,1],'delta':[10,-10,15,-10,-5,5,6], 'cumq' : [10,0,15,5,0,6,11] ,'tag': [1,1,2,2,2,0,0]}) def proc_trader(_...
python|algorithm|pandas|finance
1
359,592
35,998,112
sklearn grid.fit(X,y) - error: “positional indexers are out-of-bounds” for X_train,y_train
<p>This is a question about scikit learn (version 0.17.0) in Python 2.7 along with Pandas 0.17.1. In order to split raw data (with no missing entries) using the approach detailed <a href="https://stackoverflow.com/questions/30023927/sklearn-cross-validation-stratifiedshufflesplit-error-indices-are-out-of-bou/30025025?n...
<p>You should pass <code>X</code> and <code>y</code> directly to <code>fit()</code>, like</p> <pre><code>grid.fit(X, y) </code></pre> <p>and <code>GridSearchCV</code> will take care of </p> <pre><code>xtrain, xtest = X.iloc[train_index], X.iloc[test_index] ytrain, ytest = y[train_index], y[test_index] </code></pre> ...
python-2.7|pandas|machine-learning|scikit-learn|grid-search
3
359,593
36,106,826
Why original numpy array gets updated after updating of its copy?
<p>I've been puzzled with unexpected Python behavior: when I make a copy of my original numpy array and replace some of its elements with a different value, the corresponding elements of my original array gets updated, too. Here's a simple test:</p> <pre><code>&gt;&gt;import numpy as np &gt;&gt;x = np.array([0,0,2,2])...
<p>Assignment <strong>is not a copy of an object</strong> in numpy. You are just coping the reference to an object, to make a copy of actual array use</p> <pre><code>x_adj = x.copy() </code></pre> <p>you can easily check it through <code>id</code> function</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; ...
python|arrays|numpy
1
359,594
36,187,607
Relative row selection in pandas?
<p>Is it possible in pandas to select the 5 rows <em>before/after</em> a specific row if they match a specific condition?</p> <p>For instance, is it possible to start from row 19, and then select the five preceding rows for which b is True (thus selecting 16,16,10,7, and 4). I would call this 'relative' location. (Is ...
<p>try this:</p> <pre><code>In [31]: df.ix[(df.b) &amp; (df.index &lt; df[df.a == 19].index[0])].tail(5) Out[31]: a b 2 4 True 3 7 True 5 10 True 6 13 True 7 16 True </code></pre> <p>Step by step:</p> <p>index of the element where a==19:</p> <pre><code>In [32]: df[df.a == 19].index[0] Out[32]: 9...
python|pandas
3
359,595
35,833,221
Python - How to perform indirect sorting with a user-defined function?
<p><code>numpy.argsort</code> returns a sorted list to perform an indirect sorting, but it doesn't seem to accept a user-defined function to compare two elements.</p> <p>I wonder how one can get the sorted list based on a comparison with a user-defined function.</p> <p>In my case, I have a table of results:</p> <pre...
<p>If you are using Python >= 3.4, you can use <code>statistics.median_low()</code>.</p> <pre><code>from random import randrange from statistics import median_low a = [[randrange(8) for _ in range(7)] for _ in range(10)] print("unsorted") for item in a: print(item) a.sort(key=median_low) print("\nsorted") for ...
python|sorting|numpy
1
359,596
37,150,084
How to prevent TensorFlow eval gradients
<p>Suppose that I have simple TensorFlow model for MNIST data like this</p> <pre><code>import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) x = tf.placeholder(tf.float32, [None, 784]) y_ = tf.placeholder(tf.float32, [None, 1...
<p><code>Tensor.eval</code> is just a shorthand for <code>Session.run</code> for single tensor, which will not improve performance here. </p> <p>In the <a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/client.html#Session" rel="nofollow">document</a> of <code>Session.run</code>, it says:</p> <blockquo...
python|machine-learning|tensorflow
1
359,597
37,297,367
How to do a simple groupby in pandas?
<p>Sorry for this noob question. I have a dataframe that looks like this:</p> <pre><code>df = pd.DataFrame({'chemical': ['A', 'A', 'A', 'B', 'B'], 'cost': [102, 104, 86, 20, 92], 'id': [1, 2, 3, 4, 5]}) </code></pre> <p>How can I get a ranked list of total cost by chemical?</p> <p>I know it involves starting with th...
<p>IIUC then you want the following:</p> <pre><code>In [18]: df.groupby('chemical')['cost'].sum().rank().reset_index() Out[18]: chemical cost 0 A 2.0 1 B 1.0 </code></pre> <p>Or</p> <pre><code>In [20]: df.groupby('chemical')['cost'].sum().reset_index() Out[20]: chemical cost 0 A ...
python|pandas
2
359,598
37,362,553
Group and merge similar entries together using Pandas
<p>I have a very large set of data currently stored into a vintage database. I want to extract them into a human readable format (YAML or JSON). The main goal here is to avoid redundancy by grouping similar entries.</p> <p>My data can be summarized like this: </p> <pre><code>raw = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, ...
<p>You could:</p> <pre><code>k = ['a', 'b'] result = {i: {} for i in df[k[0]].unique()} for vals, data in df.set_index(k).groupby(list(df.drop(k, axis=1).columns)): for a, df_a in data.groupby(level=k[0]): res = df_a.reset_index(k[0], drop=True).to_dict('index') keys = ','.join(map(str, tuple(res.k...
python|pandas|dataset
1
359,599
37,557,131
Python Pandas Only Compare Identically Labeled DataFrame Objects
<p>I tried all the solutions here: <a href="https://stackoverflow.com/questions/18548370/pandas-can-only-compare-identically-labeled-dataframe-objects-error">Pandas &quot;Can only compare identically-labeled DataFrame objects&quot; error</a> </p> <p>Didn't work for me. Here's what I've got. I have two data frames. ...
<p>In order to get around this, you want to compare the underlying numpy arrays.</p> <pre><code>import pandas as pd df1 = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'], index=['One', 'Two']) df2 = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'], index=['one', 'two']) df1.values == df2.values array([[ True, ...
python|pandas|numpy
13