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
16,800
47,179,863
Disparity map tutorial SADWindowSize and image can not float
<p>I am new to Python and have been following a basic tutorial (<a href="https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_calib3d/py_depthmap/py_depthmap.html#py-depthmap" rel="nofollow noreferrer">https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_calib3d/py_depthmap/py_depthmap.html#py-depthmap</a>) for creatin...
<p>Typo error :</p> <p>change </p> <pre><code> imgL = cv2.imread("C:\Python27\tsukuba_l.png,0") imgR = cv2.imread("C:\Python27\tsukuba_r.png,0") </code></pre> <p>to</p> <pre><code> imgL = cv2.imread("C:\Python27\tsukuba_l.png",0) imgR = cv2.imread("C:\Python27\tsukuba_r.png",0) </code></pre> <p>or better :</p> ...
python-2.7|numpy|opencv|matplotlib|disparity-mapping
1
16,801
47,289,757
Plotting lists in a Pandas dataframe
<p>Consider the following dataframe example:</p> <pre><code>df = pd.DataFrame({'date':['12-01', '12-02', '12-03'],'list1': np.random.randint(0, 10, (3,5)).tolist(), 'list2': np.random.randint(0, 10, (3,5)).tolist()}, index=list('ABC')) </code></pre> <p><a href="https://i.stack.imgur.co...
<p>Why not iterate the rows and plot the values?</p> <pre><code>for i, row in df.iterrows(): plt.plot(row['list1'], row['list2']) </code></pre>
python|list|pandas|dataframe|plot
3
16,802
47,102,258
How do I convert Pandas DateTime Quarter object into string
<p>I did some pivoting and got column headers formatted as datetime objects, more precisely as periods, looking like this Period('2000Q1', 'Q-DEC'). Now how could I convert this period back into a string i.e. for the above just '2000Q1'?</p> <p>realized this is a possible duplication of: <a href="https://stackoverflow...
<p>Just call <code>str()</code> on it</p> <pre><code>&gt;&gt; p = pd.Period('2001Q1') &gt;&gt; str(p) '2001Q1' </code></pre>
python|pandas|datetime
3
16,803
68,048,449
Ensure columns of a pandas dataframe have unique values
<p>Given the following:</p> <pre class="lang-py prettyprint-override"><code>information_dict_from = { &quot;v1&quot;: {0: &quot;type a&quot;, 1: &quot;type b&quot;}, &quot;v2&quot;: {0: &quot;type a&quot;, 1: &quot;type b&quot;, 3: &quot;type c&quot;}, &quot;v3&quot;: {0: &quot;type a&quot;, 1: &quot;type b...
<pre><code># copy *_to from *_from data_to = data_from.copy() information_dict_to = information_dict_from.copy() # set the unique increase counter val = 0 for col in data_from: # for each column (v1, v2, v3) u_val_map = {} # create the mapping dict for u in data_from[col].unique(): # get all posible value ...
python|pandas|algorithm|dataframe
0
16,804
59,125,088
groupby on multiple columns and filter and split into separate dataframes
<p>I have a dataframe that looks something like :</p> <pre><code>LastName Date ObjectCol1 ObjectCol2 ObjectCol3 NumCol1 NumCol2 NumCol3 Intermediate1 Intermediate2 ABC March NA NA ABC June ...
<p>First get all <code>LastName</code> values which not matched missing values by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Dat...
python|pandas
1
16,805
56,930,065
i have a list of images and images shape is (50,50,3) . how to convert into numpy.ndarray of shape (19929,50,50,3)
<pre><code>train_x=[] val_x=[] test_x=[] for image in train_list: train_x.append(skimage.data.imread(image)) for image in val_list: val_x.append(skimage.data.imread(image)) for image in test_list: test_x.append(skimage.data.imread(image)) </code></pre> <p>how to convert train_x list to ndarray of shape (l...
<p>You can use <code>numpy.stack()</code>:</p> <pre><code>import numpy as np arrs = [np.random.randn(10, 11, 3) for i in range(5)] arr = np.stack(arrs, axis=0) print(arr.shape) </code></pre>
arrays|list|numpy
1
16,806
51,095,025
How to train Actor-Critic (A2C) reinforcement learning
<p>I am currently been able to train a system using Q-Learning. I will to move it to Actor_Critic (A2C) method. Please don't ask me why for this move, I have to.</p> <p>I am currently borrowing the implementation from <a href="https://github.com/higgsfield/RL-Adventure-2/blob/master/1.actor-critic.ipynb" rel="nofollow...
<p><strong>I think you're making a mistake</strong>, if you really want to know how to implement Actor Critic algorithm you need first to master 2 things : - Implementing value based RL algorithms (such as DQN). - Implementing policy based RL algorithms (such as Policy Gradients).</p> <p><strong>You can't directly jum...
tensorflow|machine-learning|artificial-intelligence|pytorch|reinforcement-learning
3
16,807
66,631,748
Plotting data only from February 1, 2021 to March 15, 2021 without removing data before February
<p>Let me write down what I have done so far:</p> <pre><code>import matplotlib.pyplot as plt import pandas_datareader.data as web import pandas as pd import datetime start = datetime.datetime(2020, 8, 19) end = datetime.datetime(2021, 3, 15) KE = web.DataReader(&quot;BEKE&quot;, &quot;yahoo&quot;, start, end) ma5 = ...
<p>You can take a subset of the DataFrame using <code>.loc</code> like this:</p> <pre><code># KE.insert(len(KE.columns), &quot;MA5&quot;, ma5) # KE.insert(len(KE.columns), &quot;MA20&quot;, ma20) # KE.insert(len(KE.columns), &quot;MA60&quot;, ma60) # KE.insert(len(KE.columns), &quot;MA120&quot;, ma120) # above lines sh...
python|pandas
0
16,808
66,536,548
Splitting single-columned .CSV into multiple columns with Pandas
<p>I'm interested to know how to elegantly go about splitting a single-columned file of the following format into a more classic tabular layout using Pandas.</p> <p>(The file is received as an output from an eye tracker.)</p> <p><strong>Current Format:</strong></p> <pre><code>TimeStampGazePointXLeftGazePointYLeftGazePo...
<p><code>pandas.read_...</code> has several usefull parameters to play with.</p> <p>I believe you want something like this?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd columns_names = [ 'TimeStamp', 'GazePointXLeft', 'GazePointYLeft', 'GazePointXRight', 'GazePointYRight'...
python|pandas|data-cleaning
4
16,809
66,342,708
How to make the size of output image the same as the original one to compute loss in CNN?
<p>I am define the CNN model for autoencoder as follows:</p> <pre><code>filters = (32, 16) X = Input(shape = (32, 32, 3)) # encode for f in filters: X = Conv2D(filters = f, kernel_size = (3, 3), activation = 'relu')(X) X = MaxPooling2D(pool_size = (2, 2), strides = (2, 2), padding = 'same')(X) X = BatchNor...
<p>I suggest u use <code>padding='same'</code> in convolutions. Pay attention also to not overwrite your input layer with other variables. you miss also a final output layer with the number of channels equals to the channel of the input image</p> <pre><code>filters = (32, 16) inp = Input(shape = (32, 32, 3)) # encode ...
python|tensorflow|machine-learning|keras|deep-learning
2
16,810
66,369,147
how do i merge these date rows to months?
<p>i have a multiple csv files dataframes for covid cases that looks like this:</p> <pre><code> Region active Date 2020-03-20 Tabuk 1 2020-03-21 Tabuk 1 2020-03-22 Tabuk 1 2020-03-23 Tabuk 1 2020-03-24 Tabuk 1 ... ... ... 2021-02-04 Tabuk 8 2021-02-04 Tabuk 3 2021-02-04 Tabuk 34 202...
<p>First if necessary create <code>DatetimeIndex</code> and sorting:</p> <pre><code>df.index = pd.to_datetime(df.index) df = df.sort_index() </code></pre> <p>Aggregate <code>sum</code> with monh names generated by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.strftime.html" re...
python|pandas|dataframe|csv|data-cleaning
1
16,811
66,456,059
Compare consecutive rows and delete based on condition
<p>I would like to compare consecutive rows from the column <code>one</code> and delete based on this condition:</p> <ol> <li>if 2 or more consecutive rows are the same, keep them</li> <li>If one row it's different from the previous and the next delete it</li> </ol> <p>Example df:</p> <pre><code>a = [['A', 'B', 'C'], [...
<p>Try shifting up and down:</p> <pre><code>mask = (df.one == df.one.shift(-1)) | (df.one == df.one.shift(1)) adj_df = df[mask] </code></pre>
python|pandas
0
16,812
57,612,918
Subplot with pandas graphs
<p>I need to generate a subplot of a row and two columns to show a box diagram and a histogram of data from a dataframe. I tried this:</p> <pre><code>plt.subplot(1,2,1) df.boxplot(column=variable) plt.subplot(1,2,2) df.hist(column=variable) </code></pre> <p>But I got this :</p> <p><a href="https://i.stack.imgur.com...
<blockquote> <p>Use:</p> </blockquote> <pre><code>fig, axes = plt.subplots(nrows=1, ncols=2,figsize=(10,10)) axes[0].boxplot(df3[column]) axes[1].hist(df3[column]) </code></pre> <p><strong>Example</strong></p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df3 = pd.read_csv('df3') %matplotlib inlin...
python|pandas|matplotlib
1
16,813
70,438,122
Pandas dataframe - column with list of dictionaries, extract values and convert to comma separated values
<p>I have the following dataframe that I want to extract each numerical value from the list of dictionaries and keep in the same column. for instance for the first row I would want to see in the <strong>data</strong> column: <code>179386782, 18017252, 123452 </code></p> <div class="s-table-container"> <table class="s-t...
<p>Try:</p> <pre><code>df['data'] = df['data'].apply(lambda x: ', '.join([str(d['id']) for d in x])) print(df) # Output: id data 0 12345 179386782, 18017252, 123452 </code></pre> <p>Another way:</p> <pre><code>df['data'] = df['data'].explode().str['id'].astype(str) \ ...
pandas
1
16,814
70,674,437
Pandas replace NaN values with respect to the columns
<p>I have the following data frame.</p> <pre><code>df = pd.DataFrame({'A': [2, np.nan], 'B': [1, np.nan]}) </code></pre> <p>df.fillna(0) replaces all the NaN values with 0. But I want to replace the NaN values in the column 'A' with 1 and in the column 'B' with 0, simultaneously. How can I do that ?</p>
<p>Use:</p> <pre><code>df[&quot;A&quot;].fillna(1 , inplace=True) # for col A - NaN -&gt; 1 df[&quot;B&quot;].fillna(0 , inplace=True) # for col B - NaN -&gt; 0 </code></pre>
python|pandas|dataframe
0
16,815
70,781,193
How do I define a function to extract values from nested dictionary for each row in python
<p>I have a column named 'urls' in dataframe 'df' that each row consists of nested dictionaries with a URL and whether it is malicious or not. I'd like to extract only the value of the nested dictionary for each row.</p> <pre><code>0 {'url example 1': {'malicious': False}} 1 {'url example 2': {'malicious': False}...
<p>Given pandas series <code>s</code> (I'm assuming it's a pandas series)</p> <pre><code>s = pd.Series([{'url example 1': {'malicious': False}}, {'url example 2': {'malicious': False}}]) </code></pre> <p>you can use generator expression inside <code>next</code> to look for values of nested dicts.</p> <pr...
python|pandas|dataframe|dictionary
1
16,816
51,786,661
Keras/tensorflow 'ValueError: output of generator should be a tuple...' error after first epoch
<p>I'm trying to get the keras-based sequence to sequence example from here working: <a href="https://github.com/ml4a/ml4a-guides/blob/master/notebooks/sequence_to_sequence.ipynb" rel="nofollow noreferrer">https://github.com/ml4a/ml4a-guides/blob/master/notebooks/sequence_to_sequence.ipynb</a></p> <p>Here's the code I...
<p>You can test your generator with:</p> <pre><code>next(generate_batches(batch_size, one_hot=False)) </code></pre> <p>If it works in this case you should take a look at the memory consumption. Because your seq2seq2.py throws an MemoryError, which could also be the root of the problem. Probably your generator is retu...
python|tensorflow|keras
1
16,817
51,597,773
TypeError: to_excel() missing 1 required positional argument - despite using excel writer
<p>I've been having trouble saving to excel using pandas with the following error:</p> <pre><code>File "C:/Users/Colleen/Documents/Non-online code/kit_names.py", line 36, in save_sheet_names pd.DataFrame.to_excel(writer) </code></pre> <p>TypeError: to_excel() missing 1 required positional argument: 'excel_writer' he...
<p>Simply change the <code>to_excel()</code> function to be caled on <code>df</code></p> <pre><code>df =pd.DataFrame(arr) y=os.path.basename(os.path.normpath(path)) new_path = r"C:\Users\Colleen\Documents\\"+y writer = pd.ExcelWriter(new_path, engine='xlsxwriter') df.to_excel(writer) </code></pre>
python|pandas|xlrd|writer
5
16,818
36,050,686
How to save weights of training data from MNIST testing on tensorflow for future use?
<p>I am facing problems with saving the training weight (W) for MNIST tensorflow example as described here. <a href="https://www.tensorflow.org/versions/0.6.0/tutorials/mnist/beginners/index.html" rel="nofollow">MNIST tensorflow</a>. If my understanding is correct, we need the training weight in future for other testin...
<p>I've done something similar like so:</p> <pre><code>weight_values = session.run(W) numpy.savetxt("myfilename.csv", weight_values, delimiter=",") </code></pre>
python|neural-network|tensorflow|deep-learning|mnist
3
16,819
36,210,162
Tensorflow: Stopping threads via Coordinator seems not to work?
<p>Following a <a href="https://stackoverflow.com/questions/34594198/how-to-prefetch-data-using-a-custom-python-function-in-tensorflow">standard prefetching queue</a>, I extended the aformentioned example by some additional validation code, see attached code. That is, every ith training step, the learned model is evalu...
<p>There is a race condition in your code. The thread running <code>async_load()</code> will block forever if the following events happen:</p> <ol> <li><code>async_load()</code> calls <code>coord.should_stop()</code> which returns <code>False</code>.</li> <li><code>async_load()</code> calls <code>session.run(queue, .....
python|multithreading|queue|tensorflow
5
16,820
42,091,885
Python/Pandas: Unexpected indices when doing a groupby-apply
<p>I'm using Pandas and Numpy on Python3 with the following versions:</p> <ul> <li>Python 3.5.1 (via Anaconda 2.5.0) 64 bits</li> <li>Pandas 0.19.1</li> <li>Numpy 1.11.2 (probably not relevant here)</li> </ul> <p>Here is the minimal code producing the problem:</p> <pre><code>import pandas as pd import numpy as np a...
<p>This is happening because <code>sort_values</code> returns a DataFrame or Series so the index is being concatenated to the existing groupby index, the same thing happens if you did <code>shift</code> on the 'b' column:</p> <pre><code>In [99]: v = a.groupby(level=0).apply(lambda x: x['b'].shift()) v Out[99]: a a...
python|pandas
1
16,821
41,930,824
feeding data present in series seperated by , into a columns of data frame
<p>I am a beginner in python. I am working on a project where I have data in following pattern:</p> <p>Data in json file looks like this :</p> <p>"price_time":[1398823200,1403154000,1403247600,1403301600,1403380800],"price_value":[901,909,918,927,936],],"salesRank_value":[2176,2318,2192,1801,1829]</p> <p>df.head() c...
<pre><code>price_time = [1398823200, 1403154000, 1403247600, 140330160] price_value = [901, 909, 918, 927] salesRank_value = [2176, 2318, 2192, 1801] listdata = zip(price_time,price_value,salesRank_value) print listdata </code></pre>
python|json|pandas
0
16,822
37,899,572
Pandas: Charting 3 months of quotes with a benchmark
<p>I have a df with the daily "Adj Close" (from Yahoo) for many stocks that I want to chart compared to the SPY.</p> <pre><code> AAPL ABC ... SPY Date 2016-03-10 100.56 85.79 198.52 2016-03-11 101.64 89.14 201.72 ... 2016-06-09 99.65 76.17 212.08 2016-06-10 98.83 7...
<p>Are you looking for something along these lines - (divides all prices by the first row):</p> <pre><code>stockData = DataReader(['AAPL', 'AMZN', 'FB', 'SPY'], 'yahoo', datetime(2015, 1, 1), datetime.today()).loc['Adj Close'] stockData = stockData.div(stockData.iloc[0], axis=1) for stock in stockData.columns[:-1]: ...
python|pandas|matplotlib
2
16,823
37,999,944
ImportError running tensorflow with python on Heroku?
<p>I am trying to import tensorflow in my Heroku instance, and I keep getting the following error:</p> <pre><code>File "/app/tools/inception/classify_image.py", line 45, in &lt;module&gt; 2016-06-23T19:08:18.090957+00:00 app[clock.1]: import tensorflow as tf 2016-06-23T19:08:18.090979+00:00 app[clock.1]: File "/...
<blockquote> <p>ImportError: /app/.heroku/python/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so: invalid ELF header</p> </blockquote> <p>The most likely cause is that you are attempting to load <code>x86_64</code> TF shared library into <code>i386</code> Python executable.</p> <p>You can verify...
python-2.7|heroku|pip|tensorflow|elf
6
16,824
31,391,275
USING LIKE inside pandas.query()
<p>I have been using Pandas for more than 3 months and I have an fair idea about the dataframes accessing and querying etc.</p> <p>I have got an requirement wherein I wanted to query the dataframe using LIKE keyword (LIKE similar to SQL) in <strong>pandas.query().</strong></p> <p>i.e: Am trying to execute <strong>pan...
<p>If you have to use df.query(), the correct syntax is:</p> <pre><code>df.query('column_name.str.contains("abc")', engine='python') </code></pre> <p>You can easily combine this with other conditions:</p> <pre><code>df.query('column_a.str.contains("abc") or column_b.str.contains("xyz") and column_c&gt;100', engine='...
python|pandas|dataframe
84
16,825
64,177,669
How to split elements from a list, into different columns of a dataframe?
<p>I have a list of values <code>[0.1, 0.43, 0.58]</code> and a dataframe <code>df</code> with several columns. I added three new columns in my dataframe with <code>NaN</code> values, and I want to replace them with the ones from the list. Each list value split into each new column in that exact order.</p> <p>The dataf...
<p>If <code>l</code> is your list, then:</p> <pre><code>df.loc[df.Name=='Elem2', 'New1':'New3'] = l </code></pre>
python-3.x|pandas|dataframe
1
16,826
64,583,581
Combining multiple rows in Python by the same value in Column A
<p>I'm looking to use Python to join multiple rows of data, from a CSV, into a single row. Each row has the same columns but with null values in different columns. Finally export it again into a CSV. Hopefully the examples below help clarify what I'm looking to accomplish.</p> <p>Data Example:</p> <pre><code>Email ...
<p>data file tmp.csv:</p> <pre><code>Email,age,city,car JohnDoe@gmail.com,20,, JohnDoe@gmail.com,,San Francisco, JohnDoe@gmail.com,,,Mazda henry@gmail.com,25,, henry@gmail.com,,Miami, henry@gmail.com,,,Honda </code></pre> <p>Code:</p> <pre><code>import numpy as np import pandas as pd df = pd.read_csv(&quot;tmp.csv&quo...
python|pandas|dataframe|csv
0
16,827
47,929,077
Converting pandas dataframe with only one column to 1D list
<p>I am using pandas dataframe:</p> <pre><code>import pandas as pd a = [1,2,3] i = [5,2,3] df = pd.DataFrame( { "foo" : i, "bar" : a } ) df = df.set_index("foo") l = df.values.tolist() # l = [[1], [2], [3]] </code></pre> <p>This is annoying I'w like l = [1,2,3]. Why we get a list of list? How can just get a list?</p>
<p>Here's a nice little utility function, <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.squeeze.html" rel="noreferrer"><code>df.squeeze</code></a> introduced in v0.20 - </p> <pre><code>df.squeeze() foo 5 1 2 2 3 3 Name: bar, dtype: int64 df.squeeze().tolist() [1, 2, 3] </c...
python|list|pandas|dataframe
5
16,828
47,845,900
Reading a text file in pandas with separator as linefeed (\n) and line terminator as two linefeeds (\n\n)
<p>I have a text file of the form :</p> <p>data.txt</p> <pre><code>2 8 4 3 1 9 6 5 7 </code></pre> <p>How to read it into a pandas dataframe </p> <pre><code> 0 1 2 0 2 8 4 1 3 1 9 2 6 5 7 </code></pre>
<p>Try this:</p> <pre><code>with open(filename, 'r') as f: data = f.read().replace('\n',',').replace(',,','\n') In [7]: pd.read_csv(pd.compat.StringIO(data), header=None) Out[7]: 0 1 2 0 2 8 4 1 3 1 9 2 6 5 7 </code></pre>
python|pandas|file|dataframe|io
11
16,829
49,193,808
Install tensorflow1.2 with CUDA8.0 and cuDNN5.1 shows 'ImportError: libcublas.so.9.0'
<p>I want to install tensorflow1.2 on Ubuntu 16.04 LST, After installing with pip, I test it with <code>import tensorflow as tf</code> in terminal, error shows that </p> <blockquote> <p>ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory</p> </blockquote> <p>It seems that tens...
<p>Thanks to @Robert Crovella, you give me the helpful solution of my question! </p> <p>When I try to use a different way: <code>pip install tensorflo-gpu==1.4</code> to install again, It found my older version of tensorflow1.5 and uninstall tf1.5 for install new tensorflow, but <code>pip install --ignore-installed --...
python|tensorflow|cuda|ubuntu-16.04|cudnn
0
16,830
48,913,403
Python: Iterate over files in directory and use the filenames as variables
<p>Dear stackoverflow users,</p> <p>I'm struggling with figuring out the following problem:</p> <p>I have a directory with multiple files such as</p> <pre><code>datasets/ dataset1.txt dataset2.txt dataset3.txt dataset4.txt dataset5.txt </code></pre> <p>and to read out the files and assign their ...
<p>I would use dictionary for this situation:</p> <pre><code>fileSet = {} for root, dirs, files in os.walk('.'): for file in files: fileSet[file.split('.')[0]] = numpy.loadtxt(file) </code></pre> <p>Then you could access content with expression such as</p> <pre><code>dataset1Val = fileSet['dataset1'] </cod...
python-3.x|numpy
2
16,831
49,067,640
Python p value for panda row
<p>I am very new on Python. I have a panda dataframe here. It looks like a 2D matrix with 26 columns and 9047943 rows. Let say:</p> <pre><code>array([[123,234,345], [567,543,342], [735,276,697]]) </code></pre> <p>This time I want to calculate the correlation coefficient and the p-value for each row. i.e...
<p>May be something like this. Let's say your data frame is df and given that all the columns in your df are int/float:</p> <pre><code>import numpy as np df.apply(lambda x: np.corrcoef(x), axis=1) </code></pre>
python|pandas
0
16,832
49,289,179
In pandas, how to plot with multiple index?
<p>I have double index in Panda's dataframe like the example below. </p> <pre><code> c d a b 1 3 1.519970 -0.493662 2 4 0.600178 0.274230 3 5 0.132885 -0.023688 4 6 2.410179 1.450520 </code></pre> <p>How do I plot column 'c' as y-axis and index 'b' as x-axis. With one index, ...
<p><strong>Option 1</strong><br> Two options have been provided (in the comments) involving <code>reset_index</code>. They are</p> <pre><code>df.reset_index().plot(x="b",y="c") </code></pre> <p>Or,</p> <pre><code>df.reset_index(level=0, drop=True).c.plot() </code></pre> <p>Both of these should work as expected, but...
python|pandas|matplotlib|plot
4
16,833
49,102,304
Error when calling a groupby object inside a Pandas DataFrame
<p>I've got this dataframe:</p> <pre><code> person_code #CNAE growth size 0 231 32 0.54 32 1 233 43 0.12 333 2 432 32 0.44 21 3 431 56 0.32 23 4 654 89 0.12 89 5 764 32 0.20 211 6 ...
<p>There is one way, convert a to dict , then map it back </p> <pre><code>#a=df.groupby('#CNAE',group_keys=False).apply(pd.DataFrame.nlargest,n=3,columns='growth') df['top3growth']=df['#CNAE'].map(a.groupby('#CNAE').apply(lambda x : x.to_dict())) df Out[195]: person_code #CNAE growth size \ 0 231 ...
python|pandas|pandas-groupby
0
16,834
56,097,019
Improve performance calculating a random sample matching specific conditions in pandas
<p>For some dataset <code>group_1</code> I need to iterate over all rows <code>k</code> times for robustness and find a matching random sample of another data frame <code>group_2</code> according to some criteria expressed as data frame columns. Unfortunately, this is fairly slow. How can I improve performance?</p> <p...
<ol> <li><p>IIUC you want to end up with <code>k</code> number of random samples for each row (combination of metrics) in your input dataframe. So why not <code>candidates.sample(n=k, ...)</code>, and get rid of the <code>for</code> loop? Alternatively you could concatenate you dataframe <code>k</code> times with <code...
python|pandas|performance|sampling
0
16,835
55,667,837
How to check whether two three dimensional numpy arrays are the same?
<p>I have a numpy array with shape <code>(1,x,1)</code> and the second one also with shape <code>(1,x,1)</code>. I wonder how can I check whether they are the same? Examples:</p> <p>1. First:</p> <pre><code>[[[ 2] [ 3] [ 4] [ 5] [ 6] [ 7] [ 8] [ 9] [ 4] [ 6] [10]]] </code></pre> <p>Second:</p> <...
<p>There is already a SO question with that topic and a good answer by @Juh_ <a href="https://stackoverflow.com/questions/10580676/comparing-two-numpy-arrays-for-equality-element-wise#10580782">link</a>.</p> <p>The solution:</p> <pre class="lang-py prettyprint-override"><code>(A==B).all() </code></pre>
python|arrays|python-3.x|numpy|numpy-ndarray
0
16,836
55,823,197
Python interpeter uses previous version of numpy despite updated version being installed - how to fix?
<p>When I run <code>pip freeze</code> in the command line, I see: <code>numpy==1.16.3</code>. I am trying to run <code>numpy.isin(...)</code> (<a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isin.html" rel="nofollow noreferrer">documented here</a>), but I get the error </p> <blockquote> <p...
<p>Just in case somebody else has a similar problem, I followed the steps in <a href="https://www.youtube.com/watch?v=zDYL22QNiWk&amp;" rel="nofollow noreferrer">this tutorial</a> to familiarize myself with <code>pipvirtualenv</code>. I installed the updated version of <code>numpy</code> in the <code>pipvirtualenv</cod...
python-3.x|numpy|command-line|version-control|upgrade
0
16,837
55,765,006
From a Pandas Dataframe, return specific column values based on grouping and largest values of other columns
<p>Given the following code:</p> <pre><code># Import pandas library import pandas as pd # Data to lists. data = [{'Student': 'Eric', 'Grade': 96, 'Class':'A'}, \ {'Student': 'Caden', 'Grade': 92, 'Class':'A'}, \ {'Student': 'Sam', 'Grade': 90, 'Class':'A'}, \ {'Student': 'Leon', 'Grade': 88, 'Class':'A'}, \ {'St...
<p>IIUC, you can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a>, then apply <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html" rel="nofollow noreferrer"><code>head<...
python-3.x|pandas|dataframe
2
16,838
65,021,794
numpy - how to slice of an array passed the limit of the array and back to the beginning
<p><a href="https://i.stack.imgur.com/mZbNH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mZbNH.jpg" alt="enter image description here" /></a></p> <p>I have an image in a numpy array and I want to take the slice in red.</p> <p>I expect the output to look like this.</p> <p><a href="https://i.stack.i...
<p>You could use <a href="https://numpy.org/doc/stable/reference/generated/numpy.roll.html?highlight=numpy%20roll" rel="nofollow noreferrer"><code>np.roll()</code></a>, which does a cyclic permutation / cyclic shift, along the specified axis (or axes)</p> <p>If the shift happens along just axis1, use:</p> <pre><code>ne...
python|numpy
1
16,839
64,864,284
Replace just Filtered rows in Pandas DataFrame for another Dataframe
<p>I'm working with an Dataframe that have latitude and longitude columns. I found some problems with part of this dataframe. Filtering the columns = latitude and longitude with problem i found:</p> <p>The Orginal Dataframe filtered by latitude and longitude: df17</p> <p>input:</p> <pre><code> df17[['latitude','longitu...
<p><strong>Not an answer.</strong> Cannot reproduce your problem.<br /> My mre - I added a few rows that do not meet the condition:</p> <pre><code>import pandas as pd import io f = io.StringIO('''index latitude longitude 431460 -23.369520 309.935131 431461 -23.369520 309.935131 431609 -8.057838 -34.88...
python|pandas|dataframe
0
16,840
39,783,431
the error of Can not convert a list into a Tensor or Operation
<p>When running a <a href="https://github.com/jakeret/tf_unet/blob/master/tf_unet/unet.py" rel="nofollow">tensorflow program</a>, I keep having the following error messages, the major part of which is something like <code>TypeError: Fetch argument[....]has invalid type &lt;class 'list'&gt;, must be a string or Tensor. ...
<p>If you use Tensorflow version <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/client.html#Session" rel="nofollow">r0.9</a> or a previous version, Session.run didn't accept arbitrarily nested list or tuple in the fetches argument. So self.net.gradients_node (which is a list of tensor) in the tuple c...
tensorflow
0
16,841
39,798,002
Working with time series in Pandas/Python
<p>I have the following data:</p> <pre><code> AdjClose Chg RM Target date 2014-01-16 41.733862 0.002045 0 NaN 2014-01-17 41.695141 -0.000928 1 NaN 2014-01-21 42.144309 0.010773 1 NaN 2014-01-22 41.803561 -0.008085 1 NaN 2014-01-...
<p>I would do a <code>rolling_sum()</code> exactly as you have done, though I think the up/down and down/up are easily measured as <em>when the sign changes</em>:</p> <pre><code>dd['RM'] = np.int64(np.sign(dd['Chg']) != np.sign(dd['Chg'].shift(1))) dd['RM'].values[0] = 0 </code></pre>
python|pandas
2
16,842
39,732,421
Why does Pandas skip first set of chunks when iterating over csv in my code
<p>I have a very large CSV file that I read via iteration with pandas' chunks function. The problem: If e.g. chunksize=2, it skips the first 2 rows and the first chunks I receive are row 3-4.</p> <p>Basically, if I read the CSV with nrows=4, I get the first 4 rows while chunking the same file with chunksize=2 gets me ...
<p>Don't call <code>get_chunk</code>. You already have your chunk since you're iterating over the reader, i.e. <code>chunk</code> is your DataFrame. Call <code>print(chunk)</code> in your loop, and you should see the expected output.</p> <p>As @MaxU points out in the comments, you want to use <code>get_chunk</code> ...
python|csv|pandas|chunks
4
16,843
39,659,512
How to get key and value in well format and n/a values at the end in pandas
<p>Sort the data in ascending order and the keys which are not present need to be printed in the last.</p> <p>Please suggest a solution and also suggest if any modifications is required.</p> <p><strong>Input.txt-</strong></p> <pre><code>3=1388|4=1388|5=M|8=157.75|9=88929|1021=1500|854=n|388=157.75|394=157.75|474=157...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> for creating <code>Series</code>, which is splited by <code>=</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofol...
python|pandas
0
16,844
69,549,736
Sample from dataframe with conditions
<p>I have a large dataset and I want to sample from it but with a conditional. What I need is a new dataframe with the almost the same amount (count) of values of a boolean column of `0 and 1'</p> <p><strong>What I have:</strong></p> <pre><code>df['target'].value_counts() 0 = 4000 1 = 120000 </code></pre> <p><strong>...
<p>Since 1.1.0, you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.sample.html" rel="nofollow noreferrer"><code>groupby.sample</code></a> if you need the same number of rows for each group:</p> <pre><code>df.groupby('target').sample(4000) </code></pre> <p><em>Demo</em...
python|pandas|dataframe
1
16,845
69,334,329
How to select number columns in pandas dataframe
<p>How can I select number columns in the below column names</p> <pre><code>output_df.columns = Index(['EVENT_ID', 'Date', 'Time', 'Track', '#', 'Distance', 'Betfair Grade','Runners', 'Win Trap', 'Win BSP', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Trap1 Odds Band', 'Trap2 Odds Band', 'Trap3 Odds Band...
<pre><code>new_df = df[df.columns.isnumeric()] </code></pre> <p>This should work?</p>
python|pandas
4
16,846
69,306,796
Create an SQL Query that selects a limit of 10 from table in pyspark
<p>Can anyone help with the following:</p> <p>I have a csv file with data about the passengers on the titanic. I will put the code that I have so far and then the problem I'm having after.</p> <pre><code>#Initialise Sparksession and print the shell line to ensure Spark is running # You should get a print out something...
<p>There are four ways (or four APIs) to write Spark SQL code: SQL, Python, Scala, and R. I will only talk about SQL and Python here (Scala and R is pretty as similar as Python)</p> <p>To use Python &quot;interface&quot;, you can refer to this API document <a href="http://spark.apache.org/docs/3.0.1/api/python/pyspark....
python|sql|pandas|dataframe|pyspark
1
16,847
54,224,976
How to increase performance of for loop in python
<p>I'm doing a lot of simulations with python, simulating system responses.</p> <p>I've currently been using a Runge-Kutta scheme, but have stumbled upon another scheme I've been testing.</p> <p>When testing this in Matlab I achieve exceptional performance, compared to that of my Runge-Kutta. However, when I transfer...
<p>I suggested using <code>numba</code> in the comments. Here is an example:</p> <pre><code>import numba import numpy as np def py_func(dt, F, P1): f = np.random.randn(1, int(60 / dt)) ns = f.size yo = np.zeros((3)) y1 = np.zeros((3, ns), order='F') for i in range(ns-1): y1[:, i] = np.dot(...
python|matlab|numpy
2
16,848
38,187,808
How can I run Tensorflow on one single core?
<p>I'm using Tensorflow on a cluster and I want to tell Tensorflow to run only on one single core (even though there are more available).</p> <p>Does someone know if this is possible?</p>
<p>To run Tensorflow on one single CPU thread, I use:</p> <pre><code>session_conf = tf.ConfigProto( intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) sess = tf.Session(config=session_conf) </code></pre> <p><code>device_count</code> limits the number of CPUs being used, not the number of core...
tensorflow|core
32
16,849
66,017,648
Problem while trying to replace outliers in pandas
<p>Okay, so I've trying to clean data for the Machine Learning project. I'm using Z-Score for the outliers detection. Database contains different types of glass (from 1-7) and I want to go through each glass type, find the outliers and replace them with mean values of the sodium contained in a given type of glass (&quo...
<p>I can't comment so I'll post my comment as an answer.</p> <p>Are you trying to detect &quot;outliers&quot; or &quot;outliners&quot;. Not just being pedantic here as they are different statistical concepts.</p>
python|pandas|dataframe|numpy|outliner
0
16,850
66,317,763
change year of datetime column by the year of another column + 1
<p>I want to calculate the <strong>anniversary column</strong> by this way : keep the date and month, and change the year to the same year as <strong>start column</strong> + 1</p> <p><strong>This is my pandas dataframe :</strong></p> <pre><code>| index | start | end | anniversary| | ----- | --...
<p>You can use <code>dt.year</code> to get the year component of the datetime in <code>start</code> column then increment it by <code>1</code> and change the <code>dtype</code> to <code>str</code>. In the similar way, extract the <code>month</code> and <code>day</code> components from the <code>anniversary</code> colum...
python|pandas
4
16,851
66,069,637
Keras flow_from_directory autoencoder training
<p>I'm trying to train an autoencoder in Keras and I've my own dataset organized as follow:</p> <ul> <li>dataset: <ul> <li>train: <ul> <li>img1.jpg</li> <li>etc</li> </ul> </li> <li>valid:</li> <li>test:</li> </ul> </li> </ul> <p>I've seen how to use flow_from_directory for a classification task, where the dataset is o...
<p>I solved the problem; the solution may be useful for someone: I added a subfolder in which all the images are stored. So the dataset is structured in this way:</p> <p>dataset:</p> <ul> <li>train: <ul> <li>images: <ul> <li>img.jpg ...</li> </ul> </li> </ul> </li> </ul> <p>train_path = 'dataset/train/'</p> <p>As @Gerr...
python|tensorflow|machine-learning|keras|deep-learning
0
16,852
66,197,418
Curve fitting with scipy in python to find correction parameters (can't multiply sequence by non-int of type 'numpy.float64')
<p>I'm trying to fit the function h = a0<em>L(1-a1</em>L**(-w1) to my graph and find the parameters a0, a1, and w1. I cant figure out why it's not working. I keep getting the error: can't multiply sequence by non-int of type 'numpy.float64'. Here is a snippet of my code:</p> <pre><code>L = [8, 16, 32, 64, 128, 256] Ave...
<p>As hpaulj already mentioned, you should use numpy arrays. There was also a stray comma that must have been a typo because otherwise, you would have had different numbers of x- and y-values. Finally, you cannot generally use the Python power function <code>**</code> with numpy arrays - there is the dedicated numpy fu...
python|numpy|scipy|curve-fitting
0
16,853
66,063,146
Separate multiple variables in same column
<p>I have a dataset that looks as following:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Time</th> <th>Variable</th> <th>Unit</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>05-02-2021</td> <td>10:00:00</td> <td>Freq</td> <td>Mhz</td> <td>10</td> </tr> <tr> <td>05-02-2...
<p>You are close, need join columns and then convert <code>Value</code> to numeric, if not matched return NaNs:</p> <pre><code>df['datetime'] = pd.to_datetime(df['Date'] + &quot; &quot; + df['Time']) df['Variable'] = df['Variable'] + &quot;-&quot; + df['Unit'] df['Value'] = pd.to_numeric(df['Value'], errors='coerce') ...
python|pandas|pivot-table
4
16,854
46,615,264
Does Google Cloud ML only support distributed Tensorflow for Multiple GPU training jobs?
<p>I'd like to run a Tensorflow application using multiple GPU's on Cloud ML.</p> <p>My Tensorflow application is written in the non-distributed paradigm, that is outlined <a href="https://www.tensorflow.org/tutorials/using_gpu#using_multiple_gpus" rel="nofollow noreferrer">here</a> </p> <p>From what I understand if ...
<p>You can use CUSTOM tier with only a single master node, and no workers/parameter servers. Those are optional parameters. </p> <p>Then <code>complex_model_m_gpu</code> has 4 GPUs, and <code>complex_model_l_gpu</code> has 8. </p>
tensorflow|google-cloud-ml|google-cloud-ml-engine
1
16,855
46,235,057
pandas DF column max difference between pair of values recursively
<p>I have a DataFrame with a column 'col1' with integers in it. The DF may have anything from 100 up to 1mln rows. How to compute difference between pair of values in the col1 such as:</p> <p>row2 - row1 row3 - row2 row4 - row3 etc</p> <p>and return max difference? </p> <p>I know how to use loc, iloc but do not know...
<pre><code>max(df[col_name].shift(-1)-df[col_name]) </code></pre> <p>The function shift takes the value of the next row (or second next row if you take do shift(-2)). By doing df[col_name].shift(-1), you take for a certain row, the value which is in the row below it. Substracting the value from the current from the va...
python|pandas|dataframe|difference
1
16,856
46,496,652
Python 3 loop acting on arrays gives error message unless 'pointless' a print statement is added
<p>Basically I run a for loop and get an error message and it does not run, if I run the same for loop with a print statement within it the code seems to work correctly.</p> <p>This is my code, In this code I am primarily acting on one array <strong>magnitude_differences</strong> of shape (68, 4461, 2) to create a new...
<p>The print statement stops the error message from running that's all. I thought the code was not running without the print statement but it is. Apologies for the dum late night question but you helped me answer it! </p>
python|arrays|numpy
0
16,857
46,271,931
Tensorflow bazel build error: crt/device_runtime.h: No such file or directory
<p>I tried to build tensorflow from source using bazel, howerver it always failed and showed the same error as following no matter what version I used:</p> <p><code>/usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h:213:32: fatal error: crt/device_runtime.h: No such file or directory</code>.</p> <p>gcc version: 4.9 /...
<p>I think I somehow solve this issue by doing the followings:</p> <ol> <li><p>replace the <code>/usr/local/cuda-8.0/include</code> folder with the <code>usr/local/cuda-8.0/targets/x86_64-linux/include</code></p></li> <li><p>do the <code>bazel clean</code></p></li> <li><p>run <code>./configure</code>.</p></li> </ol> ...
gcc|tensorflow|bazel
0
16,858
46,464,989
Serving a feather file dynamically via flask
<p>I'm trying to provide a microservice based on flask to expose some data from a database. At the server side, the data is prehandled and put into a pandas DataFrame before being served. </p> <p>One option, the easy one, is to serve it as a json file. But that's boring and wasteful. My preferred option would be to us...
<p>The answer is to save the feather to a buffer instead to disk and send said buffer. In this way there is no need to deal with the path, which was the original issue. This also solves the issue of overwriting temporal files upon simultaneous requests.</p> <pre><code>from flask import Flask, send_file from io import ...
python|pandas|flask|feather
4
16,859
58,467,726
Python read_csv tokenizing error / Reading from an inconsistent csv file
<p>I have a csv file that has a few hundred rows and 13 columns. The csv file is structured as follows (example):</p> <pre><code>a  b  c  d  23 43 54 65 76 23 43 63 . . a  b  e  c  d 21 12 43 12 09  23 12 32 43 87 </code></pre> <p>Values of one header appear under another header. As a result, when I use read_c...
<p>If you don't particularly need to create a dataframe then you can deal with this easily by not using pandas. The standard csv module will happily read lines of different length. Each line is returned as a list. You can either use these directly or if you need to clean up the csv you can append empty strings to the l...
python|pandas|csv|sqlalchemy
0
16,860
58,530,221
Pythonic way to find max of columns in df within a dict
<p>I have a dictionary which contains several, identically formatted, dataframes. I would like to find the max value of a specific column in all dataframes. I could iterate through the dictionary, but I assume there must be a more pythonic way to do it.</p> <p>For example, say I have two dataframes (shortened for ex...
<p>Do the following:</p> <pre><code>from itertools import chain result = max(chain.from_iterable(df['age'] for df in d.values())) print(result) </code></pre> <p><strong>Output</strong></p> <pre><code>44 </code></pre> <p>Notice that I renamed the dictionary as <code>d</code> because you should not use built-in names...
python|pandas|dataframe|dictionary|max
4
16,861
58,414,474
Showing place where is the difference between two strings in two dataframe columns, pandas
<p>I am looking for solution to show place in strings where are difference between two columns</p> <pre><code>Input: df=pd.DataFrame({'A':['this is my favourite one','my dog is the best'], 'B':['now is my favourite one','my doggy is the worst']}) expected output: [A-B],[B-A] 0:4 ,0:3 #'this','no...
<p>Your question is quite untrivial and as mentioned in the comments, it's probably best to use the <code>difflib.Sequencematcher.get_matching_blocks</code> for this, but I couldn get it to work. So here's a working solution, which will not perform in terms of speed, but get's the output.</p> <p>First we get the diffe...
python|pandas
3
16,862
68,916,917
Reading flat file with combination of single- and multi-space delimiters
<p>I have a space-delimited file in which the spaces are variable and I would like to know the ideal method for reading such files. I have tried Pandas and tried setting up many delimiters but nothing has worked so far.</p> <p>Data format that I am currently working with:</p> <pre><code>STBID DOCUMENTNO DOCDATE CU...
<p>Here is a working solution considering the data as fixed width file, using <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_fwf.html" rel="nofollow noreferrer"><code>pandas.read_fwf</code></a>:</p> <pre><code>import re import numpy as np # not strictly required # read header with open('multi_spac...
python|pandas|delimiter
0
16,863
44,711,514
Creating series from a series of list using positional list memeber
<p>I have a data frame with a string column. I need to create a new column with 3rd element after col1.split(' '). I tried </p> <pre><code>df['col1'].str.split(' ')[0] </code></pre> <p>but all I get is error.</p> <p>Actually I need to turn col1 into multiple columns after spliting by " ".</p> <p>What is the correct...
<p>Another way is: <code>df["third"] = df['col1'].apply(lambda x: x.split()[2])</code></p>
python|pandas|dataframe
0
16,864
61,092,116
create a column which is the difference of two string columns in pandas
<p>I have pandas dataframe like below:</p> <pre><code>df = pd.DataFrame ({'col1': ['apple;orange;pear', 'grape;apple;kiwi;pear'], 'col2': ['apple', 'grape;kiwi']}) col1 col2 0 apple;orange;pear apple 1 grape;apple;kiwi;pear grape;kiwi </code></pre> <p>I need the data like below:</p...
<p>You can use set to find the differences. As a first step, you need to convert the strings to a set.</p> <pre><code>df['col3'] = ( df.apply(lambda x: ';'.join(set(x.col1.split(';')).difference(x.col2.split(';'))), axis=1) ) col1 col2 col3 0 apple;orange;pear apple ...
python|pandas
2
16,865
60,891,052
How can I trim a tensor based on a mask with PyTorch?
<p>I have a tensor <code>inp</code>, which has a size of: <code>torch.Size([4, 122, 161])</code>.</p> <p>I also have a <code>mask</code> with a size of: <code>torch.Size([4, 122])</code>.</p> <p>Each element in my <code>mask</code> looks something like:</p> <pre><code>tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ...
<p>I think advanced indexing would work. (I assume every mask has equally 23 1s)</p> <pre><code>inp_trimmed = inp[mask.type(torch.bool)].reshape(4,23,161) </code></pre>
python|pytorch
1
16,866
61,050,009
TypeError: 'numpy.int64' object is not iterable, Webpage Automation
<p>How can I input data extracted from excel into a specific webpage text box. See code below:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from pynp...
<p>From <a href="https://pythonhosted.org/pynput/keyboard.html#reference" rel="nofollow noreferrer">the documentation</a> of pynput:</p> <pre><code>Controller.type(string)[source] Types a string. This method will send all key presses and releases necessary to type all characters in the string. Parameters: string (st...
python|pandas|automation|webdriver|sendkeys
1
16,867
60,958,763
How do I create a DataFrame from a list so that the list will be shown as a column and not as one single row?
<p>Using jupyter notebook. I have scraped some data from the web which I named "graphValues". The type of graphValues is a list and the values within the list are string. I would like to put the data of graphValues as a column in a new dataframe named "data". When I do this the dataframe contains only one single elemen...
<p>Do not use print. Call the variable without any function like this:</p> <pre><code>data=pd.DataFrame(graphValues.split(',')) data </code></pre> <p>Or if the code above doesn't work, use this:</p> <pre><code>data = pd.DataFrame(graphValues) data </code></pre>
python|pandas
0
16,868
71,484,850
Python Xarray integrate a 2D array along datetime dimension
<p>I have very large 2D variables in Xarray. They have the form: counts(time, altitude) where time is a numpy datetime every 10 seconds, altitude is float, counts are floats with occasional NaNs.</p> <p>I would like to reduce the resolution to every 15 minutes by summing or averaging over the corresponding columns.</p...
<p>You could use the resample method from xarray (see examples in docs <a href="https://xarray.pydata.org/en/stable/generated/xarray.Dataset.resample.html" rel="nofollow noreferrer">https://xarray.pydata.org/en/stable/generated/xarray.Dataset.resample.html</a>).</p> <p>There are named time offsets based on pandas (see ...
python|pandas|python-xarray
0
16,869
71,614,072
pytorch reads frames from video for image classification, all predicting the same category
<p>I have 3 categories of fish images, each category has 1000 images, when I trained the model, the classification accuracy was 97%, and when I used the folder images for prediction, the accuracy was no problem.</p> <p>But when I replace the picture with a video, and cut out each frame from the video for image classifi...
<p>When I use this code,there is no problem.I convert image channel from BGR to RGB for pytorch.</p> <pre><code>import torch from torchvision import transforms import torchvision.models as models import cv2 import torch.nn.functional as F import copy CLASSES = {0:&quot;goldfish&quot;, 1:&quot;stingray&quot;, 2:&quot;t...
pytorch
0
16,870
71,443,270
Splitting list array by delimeters
<p>I need to loop through an array like the one below in Python and output a dataframe. I need to extract the text between delimiters under column headers. For a customer with 4 instances say the columns for the array below for instance would be</p> <pre><code>[&quot;&quot;13900979_UKI_UK-12/01/2022-03/09/2021&quot;&qu...
<p>You can read the strings as Series and split:</p> <pre><code>lst = [&quot;13900979_UKI_UK-12/01/2022-03/09/2021&quot;, &quot;14703087_UKI_UK-12/01/2022-10/01/2022&quot;, &quot;14929368_UKI_UK-27/01/2022-25/01/2022&quot;, &quot;14991771_UKI_UK-01/02/2022-30/01/2022&quot;] cols = ['Ref', 'Marke...
python|pandas
2
16,871
42,180,877
Writing to a csv using pandas with filters
<p>I'm using the pandas library to load in a csv file using Python.</p> <pre><code>import pandas as pd df = pd.read_csv("movies.csv") </code></pre> <p>I'm then checking the columns for specific values or statements, such as:</p> <pre><code>viewNum = df["views"] &gt;= 1000 starringActorNum = df["starring"] &gt; 3 df[...
<p>Combine the boolean masks using <code>&amp;</code> (bitwise-and):</p> <pre><code>mask = viewNum &amp; starringActorNum &amp; titleLen </code></pre> <p>Select the rows of <code>df</code> where <code>mask</code> is True:</p> <pre><code>df_filtered = df.loc[mask] </code></pre> <p>Write the DataFrame to a csv:</p> ...
python|csv|pandas|dataframe
5
16,872
43,057,777
Check if 2 floating point numbers are almost equal - Numpy Python
<p>I am trying to check if all the numbers in an array are almost equal to a particular number. I am using the Numpy.testing module on python Eg:</p> <p><code>array = [0.019968,0.020010,0.019975,0.019986,0.020021 ]</code> <code>number = 0.02</code></p> <p>I need the answer to be true for all the cases.</p> <p>This ...
<p>you have to setup decimal.</p> <pre><code>numpy.testing.assert_array_almost_equal(array[1], 0.02, decimal=2) </code></pre> <p>default value of decimal is 6 and the sample data you provide exceeds the gap.</p> <p>decimal can work up to 5 in your case.</p>
python|arrays|numpy
2
16,873
43,171,606
Unable to run Tensorboard from command prompt
<pre><code>tensorboard --logdir=./model/ted500/summaries Starting TensorBoard 28 on port 6006 </code></pre> <p>Sometimes it shows the url here and some times it's stuck there. I'm new to tensorboard, so have followed couple of tutorials in order to run it but seems its still not working. </p> <p>Can someone please a...
<p>Generally we launch Tensorboard by writing:-</p> <pre><code>tensorboard --logdir='/your/path/here' </code></pre> <p>It may happen that some processes are using the port currently you are invoking for tensorboard. So, you can try changing the port at which tensorboard starts by writing:-</p> <pre><code>tensorboard...
tensorflow|tensorboard
6
16,874
43,236,961
Forecast using R dataframes, zoo and real dates on results
<p>I have a CSV with values like</p> <pre><code>ref_date;wings;airfoil;turbines 2015-03-31;123,22;22,77;99,0 2015-04-30;123,22;28,77;99,0 2015-05-31;123,22;22,177;02,0 2015-06-30;56,288;22,77;99,0 </code></pre> <p>That I read into a data frame, and convert it to a time series, with</p> <pre><code>df_agg = aggregate(...
<p><strong>1) zoo</strong> The development version of the forecast package has <code>as.ts.forecast</code> and the development version of zoo (to become zoo version 1.8.0) has an enhanced <code>as.zoo.ts</code> which by default applies yearmon/yearqtr for ts series with frequencies of 4 and 12. Together these would al...
python|r|pandas|dataframe
4
16,875
43,453,707
Numpy dot too clever about symmetric multiplications
<p>Anybody know about documentation for this behaviour?</p> <pre><code>import numpy as np A = np.random.uniform(0,1,(10,5)) w = np.ones(5) Aw = A*w Sym1 = Aw.dot(Aw.T) Sym2 = (A*w).dot((A*w).T) diff = Sym1 - Sym2 </code></pre> <p>diff.max() is near machine-precision <strong>non-zero</strong>, e.g. 4.4e-16.</p> <p>...
<p>This behaviour is the result of a change introduced for NumPy 1.11.0, in <a href="https://github.com/numpy/numpy/pull/6932" rel="noreferrer">pull request #6932</a>. From the <a href="https://docs.scipy.org/doc/numpy/release.html#id11" rel="noreferrer">release notes</a> for 1.11.0:</p> <blockquote> <p>Previously, ...
python|numpy|floating-point|linear-algebra|floating-accuracy
26
16,876
72,336,233
I got an error when extracting data from a csv file by pandas
<p>I'm trying to get a signal out of aapl data but i got this error</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import datetime apple_stock = pd.read_csv('AAPL.csv') apple_stock = apple_stock.set_index(pd.DatetimeIndex(apple_stock['Date'].values)) ma30 = pd.Data...
<p>You cannot in one side use the [i] locator, and on the other side set it free. But, to do what you are expecting, here is a easy way :</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import datetime apple_stock = pd.read_csv('AAPL.csv') apple_stock = apple_stock.s...
python|pandas
2
16,877
72,328,976
python - finding cosine similarity between two groups of vectors in the most efficient way
<p>I am trying to calculate the average cosine similarity between two groups of sentences. After converting the sentences to embeddings, I need to calculate avg. similarities in the most efficient way. Here, what I have tried and the time is taken. Is there any way to improve this calculation?</p> <p>I also put the slo...
<p>I think the most efficient way is:</p> <ol> <li>Convert your data to two numpy ndarrays, an array for each group. I assume rows are embedding vectors and arrays are called X1 and X2.</li> <li>Do <code>X/np.linalg.norm(X, axis=1)</code> on each array.</li> <li>Then do <code>np.dot(X1, X2.T)</code></li> <li>Then flatt...
python|numpy|vectorization|cosine-similarity
0
16,878
50,335,019
Multi level index dataframe
<p>I have a dataframe which looks like this:</p> <pre><code> Repo Averages for 25 Apr 2018 Business Date Instrument 25/04/2018 GC_AUSTRIA_SUB_10YR 25/04/2018 GC_AUSTRIA_SUB_10YR 25/04/2018 R_RAGB_1.15_10/18 25/04/2018 R_RAGB_4.35_03/19 25/04/2018 R_RAGB_4.35_03/19 25/04/2018 R_RAGB_1.95_06/19 </code></p...
<p>That is not multiple index , try following</p> <pre><code>df.columns=df.iloc[0,:] df=df.iloc[1:,:] df </code></pre>
python-3.x|pandas|dataframe
1
16,879
62,805,572
Is there a better way to resize an image that is in the form of a numpy array?
<p>I'm new to neural networks, and have been practicing image preprocessing. I am trying to resize images that are in the form of numpy arrays, and this is my current method:</p> <pre><code># using tensorflow, resize the image im = tf.image.resize(img_as_array, [299, 299]) # then use .eval() which returns a numpy arr...
<p>To avoid having to convert between <code>tf.tensor</code> and <code>np.ndarray</code> tensor data types, you can use <code>skimage</code> (scikit-image) to resize the image directly on <code>np.ndarray</code> objects using the following code segment:</p> <pre><code>import skimage.transform kwargs = dict(output_shap...
numpy|tensorflow|image-preprocessing
1
16,880
62,539,081
How can I get the "shape" of some data so I can generate similar random numbers in numpy/scipy
<p>Apologies. I know what I want to do, but am not sure what it is called and so haven't been able to search for it.</p> <p>I am chasing down some anomalies in data (two reports which should add to the same total based on about 50K readings differ slightly). I therefore want to generate some random data which is the sa...
<p>You can use scipy's stats package to do this, if I'm interpreting your question correctly:</p> <p>First, we generate a histogram, and measure its histogram distribution using the scipy.stats.rv_histogram() method</p> <pre><code>import scipy.stats import numpy as np import matplotlib.pyplot as plt data = scipy.stats...
python|numpy|random
2
16,881
54,344,958
How to multiply multiple column dataframe by another single column df?
<p>I'm trying to multiply two dataframes:(3868 rows x 758 columns) and (3868 rows x 1 column)</p> <pre><code>free_float = pd.DataFrame(free_float) weights = pd.DataFrame(weights ) columns = weights.columns weights[columns] *= free_float['A'] </code></pre> <p>Above codes give me error: <code>operands could not be b...
<p>With pandas you need to specify <code>.values</code> to multiply your dataframe:</p> <pre><code>df1=pd.DataFrame(np.random.randint(0,1000,3868)) df2=pd.DataFrame(np.random.randint(0,1000,size=(3868,758))) pd.DataFrame(df1.values*df2.values) </code></pre>
python|pandas|dataframe|multiplication
0
16,882
54,300,900
Non-Assert Way To Compare Two 2D Arrays for Accuracy
<p>I am currently training a LSTM which classifies frames. What I am trying to do is compare two 2d numpy arrays to check for accuracy between my prediction and target. I have currently looked around for non-naive ways to solve this problem using NumPy / SciPy. </p> <p>I am aware that there is np.testing.assert_array_...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_equal.html" rel="nofollow noreferrer"><code>np.array_equal(x, y)</code></a> is roughly equivalent to <code>(x == y).all()</code>. You can use this to compute the discrepancies:</p> <pre><code>def array_comp(x, y): """ Return the statu...
python|python-3.x|numpy|multidimensional-array|scipy
0
16,883
73,542,612
AttributeError: module 'matplotlib' has no attribute 'AxesSubplot'
<p>When looking at the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.hist.html" rel="nofollow noreferrer">documentation</a> of the <code>pandas</code> method <code>.hist()</code>, it is written that it returns a <code>matplotlib.AxesSubplot</code> or <code>numpy.ndarray</code>. However when try...
<p>Lovely question, made me dive into some new stuff I did not know. Here is my understanding of it:</p> <p>It is not actually a class but a dynamic class created by a class factory, checking the <code>mro</code> (like <code>type(df.hist()).mro()</code>) of it you can see the whole inheritance.</p> <p><a href="https://...
python|pandas|matplotlib|type-hinting
1
16,884
71,399,709
How to plot lower boundary with a scatter plot with curve_fit and a linear line function?
<p>I use the following code to plot a scatter plot. I have been trying to plot the lower boundary for it. I tried following the other question but I was unable to replicate it for my objective function and data. The code is as follows :</p> <pre><code>from numpy import arange import pandas as pd from pandas import read...
<p>As you have a linear function, your upper and lower bound will have the same slope <code>a</code> but different <code>b</code>-values. So, we calculate them for all points and choose the lowest and highest:</p> <pre><code>import numpy as np from scipy.optimize import curve_fit from matplotlib import pyplot def...
python|pandas|numpy|matplotlib|scipy
1
16,885
71,254,980
pandas read_csv quote issue
<p>I have a data like this:</p> <pre><code>## df Col1 Col2 Col3 A234 B678 &quot;L&quot; shaped, cool 41 </code></pre> <p>The delimiter is <code>\t</code>.</p> <pre><code>df = pd.read_csv(filename, sep = &quot;\t&quot;, dtype = str, quotechar = '&quot;&quot;') </code></pre> <p>This i...
<p>Seems like a possible issue is the use of 4 spaces instead of a <code>\t</code> in your file. A possible solution is to use the <code>sep</code> to explicitly indicate that 4 spaces must be used a separator:</p> <pre><code> df = pd.read_csv(filename, sep=&quot; &quot;*4, engine=&quot;python&quot;) # Explicit engin...
python|pandas
0
16,886
71,304,356
Python bytes buffer only giving out zeros even though data is being correctly received through SPI on Raspberry Pi
<p>This is a follow up question from: <a href="https://stackoverflow.com/questions/71292480/class-typeerror-lp-c-long-instance-instead-of-list/71298738?noredirect=1#comment126036149_71298738">&lt;class &#39;TypeError&#39;&gt;: LP_c_long instance instead of list</a> but is a different issue so I am posting a new questio...
<p>As @Mark's suggested in comments, you would have to store the <em>data</em> into another variable/list, for example: <code>recv = spi.xfer2(data)</code>. Then you would need to use this <em>recv</em> in your <em>unpack</em> function. Further, you could also use a python library called <em>zlib</em> instead of using ...
python|numpy|raspberry-pi|ctypes
1
16,887
52,048,919
How to incrementally add linear regression column to pandas dataframe
<p>I got an example pandas dataframe like this:</p> <pre><code> a b 0 6.0 0.6 1 1.0 0.3 2 3.0 0.8 3 5.0 0.1 4 7.0 0.4 5 2.0 0.2 6 0.0 0.9 7 4.0 0.7 8 8.0 0.0 9 9.0 0.5 </code></pre> <p>I want to add a new column, <code>linear</code> to the column, which is the linear regression output of fi...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.expanding.html" rel="nofollow noreferrer">expanding</a> with some custom apply functions. Interesting way to do LR...</p> <pre><code>from io import StringIO import pandas as pd import numpy as np df = pd.read_table(StringI...
python|pandas
2
16,888
72,613,778
How to shade area under the intersection of two distribution plots in matplotlib?
<p>I'm trying to shade the area under the intersection of two distributions. I have this code so far, but I can't seem to figure out how to shade just the intersection with <code>fill_between</code>. How do I do this?</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np...
<p>In your example both distributions are evaluated over a different range (<code>p1</code> and <code>p2</code>). So the elements in <code>p1_pdf</code> &amp; <code>p2_pdf</code> aren't aligned, in terms of the x-coordinates.</p> <p>If you evaluate them the same, taking the minimum of both would work to get the interse...
python|numpy|matplotlib
2
16,889
72,493,974
How do I loop through a folder of PDF files to extract text from a fillable form with python
<p>I'd like to loop through a folder with several fillable PDF forms to extract the text from the fields. I've figured out how extract the text and append to a data frame. I need to create the loop to iterate through all the files in the folder, append to the same data frame and export to csv or xls.</p> <pre class="la...
<p>You can use <code>os</code> library visit <a href="https://www.geeksforgeeks.org/how-to-iterate-over-files-in-directory-using-python/" rel="nofollow noreferrer">here</a></p>
python|pandas|dataframe|pypdf2
-2
16,890
59,791,976
How to rank row values (float values)?
<p>In python, how to create Sales_rank column, values from 100 to 1.</p> <pre><code>if Sales_2019 &lt;= 0.00371665 then Sales_rank =100 ; else if Sales &lt;= 0.0071706859 then Sales_rank =99 ; else if Sales &lt;= 0.0122105282 then Sales_rank =98 ; ..... else if Sales &lt;= 0.9602417519 then Sales_rank =2 ; else if ...
<p>If you are looking for a way to rank a list of floating point values, then this might work for you:</p> <pre><code>import numpy as np from scipy.stats import rankdata n = 100 # Number of Ranks/Data points sales = np.random.rand(n) # create random values between 0 and 1 of size n as fake sales # Rank the data, rev...
python|pandas|numpy
0
16,891
59,538,373
Converting numpy list of images to mp4 video
<p>I have Numpy list of 1000 RGB images (1000, 96, 96, 3). I have used openCV to create a mp4 video out of these images. my road is brown and car is red but after I create the video they turned blue. Could you please tell me how could I avoid this problem?</p> <p>My code:</p> <pre><code>img_array = [] for img in brow...
<p>As mentioned in the comments , OpenCV uses BGR format by default, where your input dataset is RGB.</p> <p>Here is one way to fix it</p> <pre class="lang-py prettyprint-override"><code>img_array = [] for img in brown_dataset: img_array.append(img) size = (96,96) out = cv2.VideoWriter('project_brown.mp4',cv2.V...
image|numpy|machine-learning|video|cv2
1
16,892
59,884,011
Created Dataframe with dictionary
<p>I would like to create a dataframe with a dictionnary. I created my dictionnary, i would like convert this in Dataframe with one columns for the months and the second for value. </p> <p>Do you have an idea for to resolve my problem ? </p> <p>My dictionary : {'Jan': [1, 5], 'Apr': [2, 6], 'Mar': [3, 7], 'June': [4,...
<p>You can use <code>stack</code>:</p> <pre><code>pd.DataFrame(d).stack() \ .rename_axis([None, 'Month']) \ .to_frame('Day') \ .reset_index(level=1) \ .reset_index(drop=True) </code></pre> <p><code>stack</code> produces a Series so the last 4 lines are just trying to produce a DataFrame and get it int...
python|pandas|dataframe|dictionary|multi-index
1
16,893
32,175,250
Use temprary label for pandas.DataFrame.plot in legend
<p>I have a pandas.DataFrame object of which column names are very ugly:</p> <pre><code>df = pd.DataFrame({'ugly name1':[1,2,3], 'ugly name2':[2,3,4]}) </code></pre> <p>I'd like to plot that dataframe with pretty data name in the legend. I know how to rename the column but hope to keep that ugly name after plotting.<...
<p>You can manually alter the legend after the plot is drawn:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({'ugly name1':[1,2,3], 'ugly name2':[2,3,4]}) df.plot() plt.legend(['pretty1', 'pretty2'],loc='upper left') </code></pre>
python|pandas|plot
2
16,894
40,504,903
Python dataframe to SQL numbers are getting rounded
<p>I have a dataframe like this:</p> <pre><code> ID Value Value2 1079712667 169945540 18.103862 1079712668 NA 100.509234 1079712669 2600000 28.833578 1079712670 14362445 101.525284 1079712671 6834165 NA </code></pre> <p>I uplo...
<p>The issue was raised two years ago : <a href="https://github.com/pandas-dev/pandas/issues/9009" rel="nofollow noreferrer">here</a>.</p> <p>After that a new feature was introduced to allow you to override the default chosen type using the <code>dtype</code> kwarg in <code>to_sql</code>.</p> <p><code>dtype</code> ca...
python|sql-server|pandas
2
16,895
18,492,334
Calculating stats across 1000 arrays
<p>I am writing a python module that needs to calculate the mean and standard deviation of pixel values across 1000+ arrays (identical dimensions).</p> <p>I am looking for the fastest way to do this.</p> <p>Currently I am looping through the arrays and using numpy.dstack to stack the 1000 arrays into a rather large 3...
<p>Maybe you could calculate <code>mean</code> and <code>std</code> in a cumulative way something like this (untested):</p> <pre><code>im_size = (5000,4000) cum_sum = np.zeros(im_size) cum_sum_of_squares = np.zeros(im_size) n = 0 for filename in filenames: image = read_your_image(filename) cum_sum += image ...
python|numpy|arrays
2
16,896
61,864,244
How to avoid augmenting data in validation split of Keras ImageDataGenerator?
<p>I'm using the following generator:</p> <pre><code>datagen = ImageDataGenerator( fill_mode='nearest', cval=0, rescale=1. / 255, rotation_range=90, width_shift_range=0.1, height_shift_range=0.1, zoom_range=0.5, horizontal_flip=True, vertical_flip=True, validation_split = 0.5, )...
<p>The solution my friend found was using a different generator but with the same validation split and no shuffle. </p> <pre><code>datagen = ImageDataGenerator( #featurewise_center=True, #featurewise_std_normalization=True, rescale=1. / 255, rotation_range=90, width_shift_range=0.1, height_shif...
python|tensorflow|keras|data-augmentation
3
16,897
61,879,433
Create a new column with value in another in pandas
<p>Hel,lo I have a dataframe such as :</p> <pre><code>Groups Names COLs COLe G1 ABC_DEF.1:2-300():Canis_lupus 2 300 G1 SDDD1 NA NA G1 SKUD.2. NA NA G1 SEQUENCE3 NA NA G1 ABC_DEF.1:...
<pre><code>df1 = df[df.Names.str.contains('()', regex=False)] df2 = df[~df.Names.str.contains('()', regex=False)][['Groups', 'Names']] print( pd.merge(left=df1, right=df2, on='Groups').rename(columns={"Names_x": "Names", "Names_y": "Names2"}) ) </code></pre> <p>Prints:</p> <pre><code> Groups ...
python|pandas
0
16,898
57,839,265
How to create xml with headers and body in python
<p>I am trying rewrite my code written in vba to python to generate the xml is below format shown in the image below using python.</p> <p>Sample Data</p> <pre><code>ORDER_RELEASE_GID PTA XXXXXXXXXXX.254687058 15/11/2019 XXXXXXXXXXXXX.8000337937 10/10/2019 XXXXXXXXXXXXX.4501222542 27/9/2019 XXXXXXXXXXXX...
<p>This is a straightforward translation of your VBA code: I took the header, body and footer output from the VBA and inserted the formatted values at the necessary places. Empty date rows are dropped before processing the dataframe.</p> <pre><code>header = """&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;Tran...
python|xml|python-3.x|pandas|lxml
0
16,899
57,896,289
Vectorizing CONDITIONAL logic in Python?
<p>Old-school c programmer trying to get with the times and learn Python. Struggling to see how to use vectorization effectively to replace for loops. I get the basic concept that Python can do mathematical functions on entire matricies in a single statement, and that's really cool. But I seldom work with mathematical ...
<p>First thing's first, the vectorized version:</p> <pre class="lang-py prettyprint-override"><code>override_is_not_nan = np.logical_not(np.isnan(override)) np.where(override_is_not_nan, override, default) </code></pre> <p>As for your real question, vectorization is useful for multiprocessing.<br> And not just for mu...
python|numpy
2