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
7,600
65,522,467
Find if there are two columns with different names but identical values using pandas
<p>I have table with 30 columns, mainly numericalm with 500k rows. I would like to check if I have two columns inside this table that have the same values for all rows. for example :</p> <p>I have this table:</p> <pre><code>&gt;&gt;&gt; num1 num2 num3 num4 0 5.1 2.3 7 5.1 1 2.2 4.4 3.1 2.2 2 3...
<p>Try <code>duplicated</code></p> <pre><code>out = df.loc[:,~df.T.duplicated()] Out[397]: num1 num2 num3 0 5.1 2.3 7.0 1 2.2 4.4 3.1 2 3.7 11.1 5.9 3 4.2 1.5 0.3 </code></pre> <p>Or</p> <pre><code>out = df.T.drop_duplicates().T Out[399]: num1 num2 num3 0 5.1 2.3 7.0 1 2.2 4...
python|pandas|duplicates
2
7,601
63,469,435
Draw line chart and highlight minimum point in matplotlib or seaborn and with the help of pandas
<p>I have a data frame as shown below</p> <p>df</p> <pre><code>Threshold Total_cost 0.7 150040 0.8 150843 0.9 149410 1 148981 1.1 149163 1.2 150017 </code></pre> <p>By using above df I would like to plot a line graph in python with y axis as Total cost and x axis as T...
<p>You can use <code>idxmin</code> to locate the row with minimum cost:</p> <pre><code>ax = df.plot(x='Threshold') (df.loc[[df['Total_cost'].idxmin()]] .plot.scatter(x='Threshold', y='Total_cost', color='r', ax=ax) ) </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/Kt2Ju.png" rel=...
python-3.x|pandas|dataframe|matplotlib|seaborn
2
7,602
53,549,408
Modifying values in pandas dataframe with a condition
<p>Given this dataframe;</p> <pre><code>df = pd.DataFrame({'col1': ['apple','lemon','orange','grape'], 'col2':['franceCNTY','italy','greeceCNTY','spain']}) </code></pre> <p>I'd like to change the values in col2 with this rule; if the value contains CNTY, then leave it as it is else set the value to...
<h3><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.where.html" rel="nofollow noreferrer"><code>where</code></a></h3> <p>You can use <code>where</code> in-place or not in-place:</p> <pre><code>df['col2'] = df['col2'].where(df['col2'].str.contains('CNTY')) print(df) col1 col...
python|pandas|dataframe
0
7,603
53,439,773
Extract data from a pandas series if the values are in a dictionary-like format
<p>I try the solution in <a href="https://stackoverflow.com/questions/45927936/extracting-dictionary-values-from-a-pandas-dataframe">Extracting dictionary values from a pandas dataframe</a> But it didn't work.</p> <p>I have a pandas.core.series.Series with the following general format:</p> <pre><code>0 {'hashtag...
<p>Here is an example with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer">apply</a>, for each <code>entities</code> returns a list with a tuple for each <code>user_mention</code>: </p> <pre><code>def find_user_mention(user_mention): return (us...
python|pandas
0
7,604
53,414,785
Delete 1st and 3rd row of Df while keeping 2nd row as header
<p>started learning this stuff today so please forgive my ignorance.</p> <p>My data is in csv and as described in the title, I would like to exclude the first and third row while keeping the second row as headers. The csv looks like this:</p> <pre><code>"Title" Date, time, count, hours, average "empty row" </code></p...
<p>Using the <code>skiprows</code> parameter of <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>pd.read_csv</code></a>:</p> <pre><code>from io import StringIO x = StringIO("""Title Date, time, count, hours, average 2018-01-01, 15:23, 16, 10, 5.5 2...
python|pandas|csv
3
7,605
72,019,016
Subtract number from dataframe depending on a corresponding number in the dataframe
<p>I have a dataframe of 2 columns, say df:</p> <pre><code> year cases 1.1 12 1.2 14 1.4 19 1.6 23 1.6 14 2.1 26 2.5 27 2.7 35 3.1 21 3.3 24 3.8 28 </code></pre> <p>and a list of false cases, say f</p> <pre><code> f...
<p>You can do something like this:</p> <pre><code>df['cases'] - (df['year']//1).astype(int).map({e:i for e, i in enumerate(f, 1)}) </code></pre> <p>or</p> <pre><code>df['cases'] - pd.Series(f).reindex(df['year']//1-1).to_numpy() </code></pre>
python|pandas|dataframe|loops
1
7,606
71,942,740
How to iterate rows and check for multiple changes in column?
<p>I have multiple columns in my data frame but three columns are important.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>Date</th> <th>Answer</th> </tr> </thead> <tbody> <tr> <td>12222</td> <td>2020-05-01</td> <td>N</td> </tr> <tr> <td>12222</td> <td>2020-05-02</td> <td>Y</t...
<p>You can try <code>transform</code> then <code>drop_duplicates</code></p> <pre class="lang-py prettyprint-override"><code>df['Count'] = df.groupby('id', as_index=False)['Answer'].transform(lambda col: col.ne(col.shift()).sum() - 1) </code></pre> <pre><code>print(df) id Date Answer Count 0 12222 2020-...
python|pandas
0
7,607
55,422,449
Save pandas.DataFrame.hist with multiple axes in one figure
<p>I have a pandas dataframe with 24 columns, and I use the function <code>pandas.DataFrame.hist</code> to generate a figure with some subplots.</p> <pre><code>plot = df.hist(figsize = (20, 15)) plot array([[&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0000000018D47EB8&gt;, &lt;matplotlib.axes._subp...
<p><code>savefig</code> is not a method of the <code>plot</code> object returned by the <code>df.hist</code>. Try the following</p> <pre><code>import matplotlib.pyplot as plt # rest of your code plot = df.hist(figsize = (20, 15)) plt.savefig(os.path.join(folder_wd, folder_output, folder_dataset,'histogram.png')) </c...
python-3.x|pandas|matplotlib
1
7,608
56,655,197
can't Ordinal Encode my data using fit_transform of category_encoders
<p>I'm trying to fit_transform the <code>OrdinalEncoder</code> of <code>category_encoders</code> to one of the columns of my <a href="https://www.kaggle.com/stevezhenghp/airbnb-price-prediction" rel="nofollow noreferrer">data</a>.<br> what I've tried seeing <a href="http://contrib.scikit-learn.org/categorical-encoding/...
<p>The documentation is incorrect. The syntax for <code>mapping</code> is now different. See here: <a href="https://github.com/scikit-learn-contrib/categorical-encoding/issues/193" rel="nofollow noreferrer">https://github.com/scikit-learn-contrib/categorical-encoding/issues/193</a></p>
python|pandas|machine-learning|categorical-data|ordinal
1
7,609
56,471,928
How to use only one GPU for tensorflow session?
<p>I have two GPUs. My program uses TensorRT and Tensorflow.</p> <p>When I run only TensorRT part, it is fine. When I run together with Tensorflow part, I have error as</p> <pre><code>[TensorRT] ERROR: engine.cpp (370) - Cuda Error in ~ExecutionContext: 77 (an illegal memory access was encountered) terminate called a...
<p>I could manage to load only one GPU be placing the following lines at the first line of the python code.</p> <pre><code>import sys, os os.environ["CUDA_VISIBLE_DEVICES"]="0" </code></pre>
python|tensorflow|cuda|tensorrt
11
7,610
66,928,491
Why the two outputs aren't equal in Pytorch derivation?
<p>I thought from the view in the derivation of composite functions(Chain rule), these two representations should be equal.</p> <pre><code>import torch x = torch.rand(3, requires_grad=True) y = x + 2 z = 2 * y * y z = z.mean() z.backward() print(4 * (x + 2)) print(x.grad) </code></pre> <p>But the outputs are as follow...
<p>They are the same, just off by a constant factor of 3. That is because when you take mean of <code>z</code>, that essentially sums each element of <code>z</code> and divides by 3 (because here your tensor is a 3 element vector). So essentially a 1/3 factor appears in the gradient, which is multiplied upstream.</p>
python|pytorch|derivative
0
7,611
47,134,210
Pandas and Dictionary: Convert Dict to DataFrame and use inner keys in values as DataFrame column headers
<p>I have the following dictionary: </p> <pre><code>{ 0: [{1: 0.0}, {2: 0.0}, {3: 0.0}, {4: 0.0}, {5: 0.0}, {6: 0.0}, {7: 0.0}, {8: 0.0}], 1: [{1: 0.0}, {2: 0.0}, {3: 0.0}, {4: 0.0}, {5: 0.0}, {6: 0.0}, {7: 0.0}, {8: 0.0}], 2: [{1: 0.21150571615476177}, {2: 0.20021993193784904}, {3: 0.24673408701244148}, {4: 0.2...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with list comprehension and then little hack - sum of all columns by second level, what join all non <code>NaN</code>s column:</p> <pre><code>df = pd.concat({k: pd.DataFrame(v) fo...
python|pandas|dictionary
1
7,612
68,439,695
Pandas highlight specific number with different color in dataframe
<p>I'm trying to highlight specific number with different color in my dataframe below:</p> <pre><code>import pandas as pd df = pd.DataFrame([[10,3,1], [3,7,2], [2,4,4]], columns=list(&quot;ABC&quot;)) </code></pre> <p>I can highlight a specific number by one color, for example:</p> <pre><code>def HIGHLIGHT_COLOR(x): cr...
<p>An option with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer">Series.map</a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer">Series.fillna</a>:</p> <pre><code>def HIGHLIGHT_COLOR(x): ...
python|pandas|pandas-styles
2
7,613
68,378,928
how to reset index during `ngroups` to display group by column?
<p>I have a dataframe like as shown below</p> <pre><code>df = pd.DataFrame({'sub_id': [101,101,101,102,102,103,104,104,105], 'test_id':['A1','A1','C1','A1','B1','D1','E1','A1','F1']}) </code></pre> <p>I am numbering each of the unique groups of <code>sub_id</code> and <code>test_id</code> using below...
<p>wrap up code in brackets <code>()</code> then use <code>reset_index()</code>:</p> <pre><code>out=(df.set_index(['sub_id','test_id']).groupby(['sub_id','test_id'],sort=False).ngroup()+1).reset_index() </code></pre> <p>OR</p> <p>Instead of <code>+1</code> use <code>add(1)</code> method then use <code>reset_index()</co...
python|python-3.x|pandas|dataframe|pandas-groupby
1
7,614
68,069,432
Pandas - Converting columns in percentage based on first columns value
<p>There is a data frame with totals and counts:</p> <pre><code>pd.DataFrame({ 'categorie':['a','b','c'], 'total':[100,1000,500], 'x':[10,100,5], 'y':[100,1000,500] }) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>categori...
<p>try via <code>div()</code>,<code>mul()</code> and <code>astype()</code> method:</p> <pre><code>df[['x%','y%']]=df[['x','y']].div(df['total'],axis=0).mul(100).astype(int) </code></pre> <p>output of <code>df</code>:</p> <pre><code> categorie total x y x% y% 0 a 100 10 100 ...
pandas|percentage
0
7,615
68,132,300
Select most recent example of multiindex dataframe
<p>I have a similiar problem as in <a href="https://stackoverflow.com/questions/37905060/getting-the-last-element-of-a-level-in-a-multiindex">Getting the last element of a level in a multiindex</a>. In the mentioned question the multiindex dataframe has for each group a start number which is always the same.</p> <p>How...
<p>Assuming values in level 1 are sorted try with <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.tail.html" rel="nofollow noreferrer"><code>groupby tail</code></a>:</p> <pre><code>out = df.groupby(level=0).tail(1) </code></pre> <p><code>out</code>:</p> <pre><code> ...
python|pandas
1
7,616
59,098,078
"AttributeError:" After converting script to TF2
<p>I used to the automatic update script but am still running into some issues. This area seems to be the part which is causing the issues, any help would be appreciated.</p> <p>Error issued:" AttributeError: 'BatchDataset' object has no attribute 'output_types' "</p> <pre><code># network parameters n_hidden_1 = 50 n...
<p>Replace:</p> <pre><code>ds_train.output_types </code></pre> <p>with:</p> <pre><code>tf.compat.v1.data.get_output_types(ds_train) </code></pre> <p>similarly you may need <code>tf.compat.v1.data.get_output_shapes(ds_train)</code></p>
tensorflow|machine-learning|neural-network|tensorflow2.0
2
7,617
59,449,797
tensorflow working on the anaconda prompt but not on the command prompt
<p><a href="https://i.stack.imgur.com/iskOL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iskOL.png" alt="Example"></a></p> <p>I've just installed tensorflow in my machine and I decided to install it with anaconda. It works just fine there but when I try to run it with the command prompt it acts a...
<p>From the anaconda window you activated your <code>env</code>, <code>base</code> in your case. When you open command prompt you have to activate that <code>env</code></p> <p><code>activate base</code></p> <p>then run <code>python</code></p>
tensorflow|installation|anaconda
0
7,618
56,946,779
Pandas: Comparing a row value and modify next column's row values
<p>I have this Pandas Dataframe:</p> <pre><code> A B 0 xyz Lena 1 NaN J.Brooke 2 NaN B.Izzie 3 NaN B.Rhodes 4 NaN J.Keith ..... </code></pre> ...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.startswith.html" rel="nofollow noreferrer"><code>Series.str.startswith</code></a> if n...
python|pandas|csv
2
7,619
57,163,222
pandas list of dataframes to group by
<p>Having a list of pandas dataframes, how to concat them together into a single groupby object to have vectorized calculations on them?</p> <p>The dfs are similar and there is no chance to groupby them after concatination.</p> <p>group n:</p> <pre><code>index some_values 0 2 1 3 2 2 3 2 </code></pr...
<p>You can use something like:</p> <pre><code>s=np.where(~df.boolean,df.boolean.ne(df.boolean.shift()).cumsum(),np.nan) final=df.assign(group=pd.Series(pd.factorize(s)[0]+1).replace(0,np.nan)) </code></pre> <hr> <pre><code> index boolean group 0 0 False 1.0 1 1 False 1.0 2 2 False ...
pandas|pandas-groupby
3
7,620
57,287,934
Construct DataFrame from list of dicts
<p>Trying to construct pandas DataFrame from list of dicts</p> <p>List of dicts:</p> <pre><code>a = [{'1': 'A'}, {'2': 'B'}, {'3': 'C'}] </code></pre> <p>Pass list of dicts into pd.DataFrame():</p> <pre><code>df = pd.DataFrame(a) Actual results: 1 2 3 0 A NaN NaN 1 NaN B NaN 2 NaN NaN C </code><...
<p>Something like this with a list comprehension:</p> <pre><code>pd.DataFrame(([(x, y) for i in a for x, y in i.items()]),columns=['Key','Value']) </code></pre> <hr> <pre><code> Key Value 0 1 A 1 2 B 2 3 C </code></pre>
pandas
1
7,621
56,964,557
bazel tensorflow target name misunderstanding
<p>I try to understand bazel dependency tree in tensorflow 2.0 project.<br> In tensorflow/tensorflow/BUILD:598 there is a target: </p> <pre><code>tf_cc_shared_object( name = "tensorflow_cc", </code></pre> <p>When I try to query it with bazel</p> <pre><code>bazel query //tensorflow:libtensorflow_cc --output lo...
<p>Shouldn't that be:</p> <pre class="lang-sh prettyprint-override"><code>bazel query //tensorflow:tensorflow_cc --output location </code></pre> <p>which produces the following output for me:</p> <pre><code>[...]/tensorflow/tensorflow/BUILD:611:1: filegroup rule //tensorflow:tensorflow_cc Loading: 0 packages loaded ...
tensorflow|build|bazel
0
7,622
66,372,469
Is there a way to fix this import error for geopandas?
<p>I am trying to get GemGIS to work. During the installation process I installed the libaries <em><strong>geopandas</strong></em> and <em><strong>gemgis</strong></em> in my enviroment through:</p> <p><code>conda install -c conda-forge geopandas</code></p> <p>and</p> <p><code>pip install gemgis</code></p> <p>I used the...
<p>Your installation of <code>rtree</code> is corrupted. You can either try reinstalling it or using <code>pygeos</code> instead.</p> <p>The recommended way (since I see that you're using conda):</p> <pre><code>conda install rtree -c conda-forge </code></pre> <p>or</p> <pre><code>conda install pygeos -c conda-forge </c...
python|dll|importerror|geopandas
0
7,623
66,387,188
Is there an easy way to extract rows from pandas DataFrame from a boolean expression?
<p>I'm currently struggling trying to extract rows from a DataFrame using vectorization. I'm pretty sure there's an easy way, expression or function to achieve this, but I couldn't find it. I have this dataframe (from a mysql database):</p> <pre class="lang-py prettyprint-override"><code> date_taux taux ...
<p>Let us try <code>numpy</code> broadcasting:</p> <pre><code>x, y = df[['taux_min', 'taux_max']].values.T mask = (x[:, None] &lt;= arr) &amp; (arr &lt;= y[:, None]) df['amount_lines'] = mask.sum(1) </code></pre> <hr /> <pre><code> date_taux taux taux_min taux_max amount_lines 0 2021-02-15 13:55:00...
python|pandas|numpy|vectorization|numpy-ndarray
2
7,624
66,488,155
Captioning a pandas dataframe from sqlite and outputing with a web browser with Python
<p>I have a function in my Python script which picks values from an sqlite database into a pandas (pd) dataframe to be outputted in a web browser.</p> <p>I want the outputted table to display a caption for the table in the browser.</p> <p>The caption should look like</p> <blockquote> <p>&quot;This table shows the rate ...
<p>There is no direct option to add <code>&lt;caption&gt;</code> tag to table from pandas, but you can just append heading(&lt;h#&gt; tag) like</p> <pre class="lang-py prettyprint-override"><code>heading_template = '&lt;h3&gt;This table shows the rate of collections for the month of {month} in the year {year}&lt;/h3&gt...
python|html|pandas|sqlite
0
7,625
66,399,668
which object detection algorithms can extract the QR code from an image efficiently
<p>I am new to Object Detection, for now, I want to predict the QR code in images. I want to extract the QR code from the images, and only predict the QR code without the background information, and finally predict the exact number the QR code is representing, since I am using PyTorch, is there any object detection alg...
<p>There are two ways for this task:</p> <p><strong>Computer Vision based approach:</strong></p> <p>OpenCV library's <code>QRCodeDetector()</code> function can <strong>detect</strong> and <strong>read</strong> QR codes easily. It returns <strong>data</strong> in QR code and bounding box information of the QR code:</p> ...
pytorch|qr-code|object-detection
1
7,626
66,669,168
unsupported operand type(s) for +: 'float' and 'numpy.str_'
<p>I have the following 2 lists.</p> <pre><code>['4794447', '1132804', '1392609', '9512999', '2041520', '7233323', '2853077', '4297617', '1321426', '2155664', '13310447', '6066387', '3551036', '4098927', '1865298', '20153634', '1323783', '6070500', '4661537', '2342299', '1302946', '6657982', '2807002', '3032171', '592...
<p>I think need both numeric, so use:</p> <pre><code>population_by_region = result['Population'].astype(int).tolist() </code></pre> <p>Also converting to list is not necessary, pass both columns like:</p> <pre><code>corr, val = stats.pearsonr(result['Population'].astype(int), result['wl_ratio']) print (corr, val) -0.04...
python|pandas|numpy
3
7,627
57,434,435
"Could not compute output" error using tf.keras merge layers in Tensorflow 2
<p>I'm trying to use a merge layer in tf.keras but getting <code>AssertionError: Could not compute output Tensor("concatenate_3/Identity:0", shape=(None, 10, 8), dtype=float32)</code>. Minimal (not)working example: </p> <pre><code>import tensorflow as tf import numpy as np context_length = 10 input_a = tf.keras.lay...
<p>Ok well the error message was not helpful but I eventually stumbled upon the solution: the input to <code>model</code> needs to be an iterable of tensors, i.e. </p> <pre><code>pred = model((a, b)) </code></pre> <p>works just fine. </p>
tensorflow|keras|tensorflow2.0|tf.keras
5
7,628
73,048,757
python pandas regex find pattern from another row
<p>I have a python pandas dataframe with the following pattern:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>file_path</th> </tr> </thead> <tbody> <tr> <td>/home</td> </tr> <tr> <td>/home/folder1</td> </tr> <tr> <td>/home/folder1/file1.xlsx</td> </tr> <tr> <td>/home/folder1/file2.xlsx</t...
<p>Use <a href="https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parent" rel="nofollow noreferrer"><code>pathlib.Path.parent</code></a> to extract the parent, as follows:</p> <pre><code>import pandas as pd import pathlib df = pd.DataFrame([&quot;/home&quot;, &quot;/home/folder1&quot;, &quot;/home/folder...
python|pandas|string|path
2
7,629
73,168,950
incompatible shapes error using datagen.flow_from_directory() in a functional API keras model
<p>I am a super n00b attempting to learn TF and keras. I would like to create a model using the Functional API and fed by ImageDataGenerator() and flow_from_directory(). I am limited to using spyder (5.1.5) and python 3.7, keras 2.8.0, tensorflow 2.8.0.</p> <p>I have organized sample patches into labelled folders to su...
<p>As it turns out I solved the issue with the following:</p> <p>changed optimizer to Adam in compiler, added a flatten() layer prior to my final dense(7) output</p>
python|tensorflow|keras
0
7,630
70,503,950
creating and filling empty dates with zeroes
<p>I have a dataframe <code>df</code></p> <pre><code>df=pd.read_csv('https://raw.githubusercontent.com/amanaroratc/hello-world/master/x_restock.csv') df </code></pre> <p><a href="https://i.stack.imgur.com/9ZivM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ZivM.png" alt="enter image description h...
<p>Use:</p> <pre><code>#added parse_dates for datetimes df=pd.read_csv('https://raw.githubusercontent.com/amanaroratc/hello-world/master/x_restock.csv', parse_dates=['Date']) </code></pre> <p>First solution is for add complete range of datetimes from minimal and maximal datetimes in <a href="http://pand...
python|pandas|dataframe|group-by
2
7,631
70,506,146
Does pandas loc generates a copy in itself but it is a view with assignment?
<h1>Question</h1> <p>Does <code>.loc</code> generate both view and copy depending on the context?</p> <h2>Background</h2> <p>A bit confused with pandas <code>.loc</code> behaviour as I had thought it should generate a view. However, it looks it generates a copy in the example below.</p> <pre><code>import numpy as np im...
<p>Interesting question, it seems that is more about assignment vs copy. <code>df_for_view.loc[:, ['B']]</code> is essentially a new dataframe, as it's proved by</p> <pre><code>print(df_for_view.loc[:, ['B']].values.base is back_for_view.values.base) False </code></pre> <p>so <code>df_for_view = df_for_view.loc[:, ['B...
python|pandas
0
7,632
70,737,867
Pandas Conditional value fill, dependant on precious row's value
<pre><code>Current Input: import pandas as pd import numpy as np # initialize list of lists data = [ ['2017-08-17 04:00:00', 1 ], ['2017-08-17 04:01:00', 2 ], ['2017-08-17 04:02:00', None ], ['2017-08-17 04:03:00', None ], ...
<p>Your column seems to contain strings, maybe this should work:</p> <pre><code>df['entry'] = df.loc[df['price'].ne('') &amp; df['price'].shift(fill_value='').eq(''), 'price'].reindex(df.index).fillna('') print(df) # Output date price entry 0 2017-08-17 04:00:00 1 1...
python|pandas|dataframe|conditional-statements|rows
0
7,633
70,975,406
Split regex strings into new column in pandas
<p>I have a redirect file in a pandas dataframe with a number of regex &quot;or&quot; expressions.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>regex_no</th> <th>regex</th> </tr> </thead> <tbody> <tr> <td>Regex4</td> <td>/shop/accessories/jewellery/necklaces/(brand-|)jon-richard/</td> </...
<p>You can iterate through the rows of the dataframe like <a href="https://stackoverflow.com/a/39370553/5229301">this</a>, then use <a href="https://stackoverflow.com/a/39370553/5229301">exrex</a> to grab each possible result of your regex expressions.<br /> You would need to construct a new dataframe, adding a new row...
python|pandas|dataframe
0
7,634
70,755,391
In numpy, how to efficiently build a mapping from each unique value to its indices, without using a for loop
<p>In numpy, how to efficiently build a mapping from each unique value to its indices, without using a for loop</p> <p>I considered the following alternatives, but they are not efficient enough for my use case because I use large arrays.</p> <p>The first alternative, requires traversing the array with <code>for</code> ...
<p>I advise you to check out <code>numba</code> which can speed up <code>numpy</code> code on python significantly - it supports <code>numpy.invert()</code> and <code>numpy.unique()</code> - <a href="https://numba.pydata.org/numba-doc/dev/reference/numpysupported.html#" rel="nofollow noreferrer">documentation</a></p> <...
python|arrays|numpy|image-processing|image-segmentation
2
7,635
51,761,961
Dropping Columns in python pandas
<p>I'm trying to drop all the columns in a pandas dataframe, except for these few, but when I run this code all the columns are dropped. The dataset is so big, that it would be tedious to list them all, any ideas?:</p> <pre><code>for columns in df: if not columns == 'Carbohydrates' or columns == 'Description' or c...
<p>Just <strong>select the columns</strong> that you want to keep:</p> <pre><code>df = df[['Carbohydrates','Description','1st Household Weight','Sugar Total','Kilocalories']] </code></pre>
python|pandas
1
7,636
51,977,881
pd.to_datetime inconsistent with time.mktime
<pre><code>import time import pandas as pd x=pd.to_datetime('2017/01/01',yearfirst=True) print('x:', x) y=pd.to_datetime(time.mktime(x.timetuple()),unit='s') print('y:', y) </code></pre> <p>The result is: </p> <pre><code>x: 2017-01-01 00:00:00 y: 2016-12-31 16:00:00 </code></pre> <p>I'd expect them to be the same, s...
<p>I have found out that the problem is because time.mktime assumes that the timetuple is a local time. Since I am at UTC+8, time.mktime would first -8 hours to convert it to UTC, then convert it to seconds. </p> <p>Thanks to @abarnert, I found that we can just use x.value (it's nano seconds), and if we need the secon...
python|pandas|datetime|time
1
7,637
36,220,200
is the year-month part of a datetime variable still a time object in Pandas?
<p>consider this</p> <pre><code>df=pd.DataFrame({'A':['20150202','20150503','20150503'],'B':[3, 3, 1],'C':[1, 3, 1]}) df.A=pd.to_datetime(df.A) df['month']=df.A.dt.to_period('M') df Out[59]: A B C month 0 2015-02-02 3 1 2015-02 1 2015-05-03 3 3 2015-05 2 2015-05-03 1 1 2015-05 </code></pre> <p>...
<p>It is a pandas period object</p> <pre><code>In [5]: df.month.map(type) Out[5]: 0 &lt;class 'pandas._period.Period'&gt; 1 &lt;class 'pandas._period.Period'&gt; 2 &lt;class 'pandas._period.Period'&gt; Name: month, dtype: object </code></pre>
python|pandas
1
7,638
35,819,771
Applying complex function to several timeseries
<p>What I am trying to achieve is this: I have several Timeseries, which I need to combine on a per-point-basis and return the result as a single new timeseries. </p> <p>I understand that you can use various <code>numpy</code> functions on Series in <code>pandas</code>, but I am unclear on how to apply complex functio...
<p>You can use <code>map</code>:</p> <pre><code>ts.map(direction_day) 2016-1-1 0.166667 2016-1-2 0.000000 2016-1-3 0.166667 2016-1-4 0.666667 2016-1-5 0.000000 2016-1-6 -0.166667 </code></pre> <p>Or <code>apply</code> (produce the same result)</p> <pre><code>ts.apply(direction_day) </code></p...
python-3.x|pandas|dataframe
3
7,639
35,834,913
Extract indices of array outside of a slice
<p>I want to perform statistics on an annulus around a central portion of a 2D array (performing statistics on the background around a star in an image,for instance). I know how to obtain a 2D slice of a region inside of the array and return the indices of that slice, but is there any way of obtaining the indices of t...
<p>I hope this represents roughly what you want to do, ie. get the elements of an annulus in your 2d data. If you like the data outside the annulus just change the condition.</p> <pre><code>import numpy as np #construct a grid x= np.linspace(0,1,5) y= np.linspace(0,1,5) xv,yv = np.meshgrid(x, y, sparse=False, indexin...
python|arrays|numpy|data-structures
1
7,640
36,065,021
Ordered coordinates
<p>I have a list of 2D unordered coordinates :</p> <pre><code>[[ 95 146] [118 146] [ 95 169] [ 95 123] [ 72 146] [118 169] [118 123] [141 146] [ 95 100] [ 72 123] [ 95 192] [ 72 169] [141 169] [118 100] [141 123] [ 72 100] [ 95 77] [118 192] [ 49 146] [ 48 169]] </code></pre> <p><a href="https://i.s...
<p>By putting them inside a pseudo regular grid:</p> <pre><code> c = [[ 95, 146],[118, 146],[ 95, 169],[ 95, 123],[ 72, 146],[118, 169], [118, 123],[141, 146],[ 95, 100],[ 72 ,123] ,[ 95 ,192],[ 72 ,169] ,[141 ,169],[118 ,100],[141 ,123],[ 72 ,100],[ 95 , 77],[118 ,192] ,[ 49 ,146],[ 48 ,...
python|opencv|numpy|coordinates
2
7,641
37,310,141
Python Pandas merge if numbers equal
<p>Im trying to merge two csv's based on a condition. The Value 'KEYS' on csv2 has to match the 'TCNUM' on CSV1, and append it the third column. The csv's are very large and it has to be done through code.</p> <p>df1 - CSV1:</p> <pre><code>ID TC_NUM dialog_testcase_0101.0001_gr...
<p>You can after <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> remove first <code>3</code> char from column <code>TC_NUM</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="n...
python|csv|pandas
1
7,642
37,323,546
Python data frame apply filter on multiple columns with same condition?
<p>Here is my pandas data frame. </p> <pre><code>new_data = name duration01 duration02 orz01 orz02 ABC 1 years 6 months 5 months Nan Google XYZ 4 months 3 years 2 months Google Zensar TYZ 4 months 4 years ...
<p>Consider reshaping using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow">pandas.melt</a>, then conditionally parsing out values for years and months using <code>np.where()</code>. Finally, aggregate by the <em>Google</em> organization.</p> <pre><code>import pandas as ...
python|pandas|filter|group-by|multiple-columns
0
7,643
41,839,522
Time series: EWMA pandas forecast
<p>I have searched extensively in Google and here but cannot seem to find the answer I am looking for or at least, some thing I understand. Is it possible to use EWMA in Pandas for forecasting ? For example, if I had daily data of website clicks for 2 months 1st Feb to 31st Mar. and don't see any trend or seasonality i...
<p>It's a one-liner to implement, but you're going to be a little bored by EWMA's predictions of the future (the mean is simply the most recent observation). If you'd like a python package that lets you experiment with EWMA level, trend and seasonality, try my Holt Winters implementation:</p> <p><a href="https://gith...
python|pandas|time-series
4
7,644
41,979,933
Python Groupby part of a string
<p>I'm grouping a list of transactions by UK Postcode, but I only want to group by the first part of the postcode. So, UK post codes are in two parts, outward and inward, separated by a [space]. e.g. W1 5DA.</p> <pre><code>subtotals = df.groupby('Postcode').count() </code></pre> <p>Is the way I'm doing it now, the wa...
<p>I think you need <code>groupby</code> by <code>Series</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> by first space:</p> <pre><code>subtotals = df.groupby(df['Postcode'].str.split().str[0]).count() </cod...
python|pandas
4
7,645
41,795,640
Merge pandas Data Frames based on conditions
<p>I have two files which show information about a transaction over products</p> <p>Operations of type 1 </p> <pre><code>d_op_1 = pd.DataFrame({'id':[1,1,1,2,2,2,3,3],'cost':[10,20,20,20,10,20,20,20], 'date':[2000,2006,2012,2000,2009,2009,2002,2006]}) </code></pre> <p><a href="https://i.stack....
<p>You can use:</p> <pre><code>#concat DataFrames together df4 = pd.concat([d_op_1.rename(columns={'cost':'cost1'}), d_op_2.rename(columns={'cost':'cost2'})]).fillna(0).astype(int) #print (df4) #find max and min dates per goups df3 = d_op_2.groupby('id')['date'].agg({'start':'min','end...
python|pandas|dataframe
3
7,646
37,815,007
Pandas Series - set data between date ranges to a constant
<p>I have a very simple problem which might be a bit long-winded to explain but I'll do my best.</p> <p>I have a pandas Series <code>daily</code> data which has an entry for each day and a corresponding value of False (see daily in code below).</p> <p>I have two other Series objects, <code>start</code> and <code>end<...
<p>You can use:</p> <pre><code>daily = pd.Series(False, pd.bdate_range("20150101", "today", freq="D")) monthly = pd.Series(False, pd.bdate_range("20150101", "today", freq="MS") + pd.DateOffset(9)) start = [i + pd.DateOffset(random.choice([1, 2, 3, 4])) for i in monthly.index] end = [i + pd.DateOffset(random.choice([1...
python|datetime|pandas
1
7,647
38,038,393
File size increases after converting from .mat files to .txt files
<p>I have a lot of .mat files which contain the information about the radial part of some different wavefunctions and some other information about an atom. Now I successfully extracted the wavefunction part and using numpy.savetxt() to save it into .txt file. But the size of the file increases so much: After I ran </p>...
<p><code>.mat</code> is a binary format whereas <code>numpy.savetxt()</code> writes a plain text file. The binary representation of a double precision number (IEEE 754 double precision) takes 8 bytes. By default, numpy saves this as plain text in the format <code>0.000000000000000000e+00</code> resulting in 24 bytes.</...
python|numpy|filesize|file-type|mat
3
7,648
31,368,918
With Pandas in Python, how do I sort by two columns which are created by the agg function?
<p>For this sort of data</p> <pre><code> author cat val 0 author1 category2 15 1 author2 category4 9 2 author3 category1 7 3 author4 category1 9 4 author5 category2 11 </code></pre> <p>I want to get</p> <pre><code> cat mean count category2 13 2 category1 8 2 catego...
<p>You should use <code>.agg</code> instead <code>.apply</code> if you just want to pass two aggregate functions <code>mean</code> and <code>count</code> to your data. Also, since you've applied two functions on the same column <code>val</code>, it will introduce a multi-level column index. So before sorting on newly c...
python|pandas
3
7,649
31,593,157
Convert custom class to standard Python type
<p>I was working with a <code>numpy</code> array called <code>predictions</code>. I was playing around with the following code:</p> <pre><code>print type(predictions) print list(predictions) </code></pre> <p>The output was:</p> <pre><code>&lt;type 'numpy.ndarray'&gt;` [u'yes', u'no', u'yes', u'yes', u'yes'] </code><...
<blockquote> <p>I have answered from the pure Python perspective below, but <code>numpy</code>'s arrays are actually implemented in C - see e.g. <a href="https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/arrayobject.c#L1760" rel="nofollow">the <code>array_iter</code> function</a>.</p> </blockqu...
python|numpy|casting
2
7,650
31,675,610
Csr_matrix.dot vs. Numpy.dot
<p>I have a large (<em>n=50000</em>) block diagonal <code>csr_matrix</code> <strong>M</strong> representing the adjacency matrices of a set of graphs. I have to have multiply <strong>M</strong> by a dense <code>numpy.array</code> <strong>v</strong> several times. Hence I use <code>M.dot(v)</code>.</p> <p>Surprisingly,...
<p>I don't have enough memory to hold a <code>50000x50000</code> dense matrix in memory and multiply it by a <code>50000</code> vector. But find here some tests with lower dimensionality.</p> <p>Setup:</p> <pre><code>import numpy as np from scipy.sparse import csr_matrix def make_csr(n, N): rows = np.random.choi...
python|numpy|scipy|sparse-matrix
4
7,651
31,616,695
Convert Json data to Python DataFrame
<p>This is my first time accessing an API / working with json data so if anyone can point me towards a good resource for understanding how to work with it I'd really appreciate it. </p> <p>Specifically though, I have json data in this form:</p> <pre><code>{"result": { "code": "OK", "msg": "" },"report_name":"DAILY","...
<p>Looking at the structure of your <code>json</code>, presumably you will have several rows for your data and in my opinion it will make more sense to build the dataframe yourself.</p> <p>This code uses <code>columns</code> and <code>data</code> to build a dataframe:</p> <pre><code>In [12]: import json import panda...
python|json|pandas
1
7,652
47,858,023
"unfair" pandas categorical.from_codes
<p>I have to assign a label to categorical data. Let us consider the iris example:</p> <pre><code>import pandas as pd import numpy as np from sklearn.datasets import load_iris iris = load_iris() print "targets: ", np.unique(iris.target) print "targets: ", iris.target.shape print "target_names: ", np.unique(iris.targ...
<blockquote> <p>Do you know why?</p> </blockquote> <p>If you will take a closer look at the error traceback:</p> <pre><code>In [128]: pd.Categorical.from_codes(target, target_names) --------------------------------------------------------------------------- ValueError Traceback (most ...
python|pandas|categorical-data|python-iris
1
7,653
47,758,806
How do I merge one nested dictionary and one simple dictionary while changing the value in python?
<p>I have two dictionaries like this:</p> <pre><code>dict1 = {'foo': 3.0, 'bar': 2.69, 'baz': 3.0} dict2 = {'foo': {'11-abc1': 0.47}, 'bar': {'11-abc1': 0.30, '12-abc1': 0.0}, 'baz': {'14-abc1': 0.47}} </code></pre> <p>Now I want to merge these two dictionaries while multiplying the values. The output should look li...
<p>You can try this:</p> <pre><code>dict1 = {'foo': 3.0, 'bar': 2.69, 'baz': 3.0} dict2 = {'foo': {'11-abc1': 0.47}, 'bar': {'11-abc1': 0.30, '12-abc1': 0.0}, 'baz': {'14-abc1': 0.47}} new_dict = {a:{c:d*dict1[a] for c, d in b.items()} for a, b in dict2.items()} </code></pre> <p>Output:</p> <pre><code>{'bar': {'12-a...
python|pandas|dictionary|merge|zip
0
7,654
47,878,894
Subclass a DataFrame without mutating original object
<p>As <a href="https://stackoverflow.com/a/45246289/7954504">mentioned a while back by @piRSquared</a>, subclassing a pandas DataFrame in the way suggested in the docs, or by <a href="https://github.com/geopandas/geopandas/blob/master/geopandas/geodataframe.py#L18" rel="nofollow noreferrer">geopandas' GeoDataFrame</a>,...
<p><code>Self</code> is not the dataframe you are passing. Regardless, you can perform the copy in the init function.</p> <p>For example</p> <pre><code>import copy def __init__(self, farg, **kwargs): farg = copy.deepcopy(farg) attr = kwargs.pop('attr', None) super().__init__(farg) self.attr = attr </...
python|python-3.x|pandas|inheritance
1
7,655
47,876,828
How to optimize a nested for loop in Python
<p>So I am trying to write a python function to return a metric called the Mielke-Berry R value. The metric is calculated like so: <a href="https://i.stack.imgur.com/mL77o.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mL77o.png" alt="enter image description here"></a></p> <p>The current code I have written...
<p>Here's one vectorized way to leverage <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="noreferrer"><code>broadcasting</code></a> to get <code>total</code> -</p> <pre><code>np.abs(forecasted_array[:,None] - observed_array).sum() </code></pre> <p>To accept both lists and arrays al...
python|arrays|numpy
9
7,656
47,954,564
Printing numpy with different position in the column
<p>I have following numpy array</p> <pre><code>import numpy as np np.random.seed(20) np.random.rand(20).reshape(5, 4) array([[ 0.5881308 , 0.89771373, 0.89153073, 0.81583748], [ 0.03588959, 0.69175758, 0.37868094, 0.51851095], [ 0.65795147, 0.19385022, 0.2723164 , 0.71860593], [ 0.783003...
<p>If "elegant" means "no loop" the following would qualify, but probably not under many other definitions (<code>arr</code> is your input array):</p> <pre><code>m, n = arr.shape arrf = np.asanyarray(arr, order='F') padded = np.r_[arrf, np.zeros_like(arrf)] assert padded.flags['F_CONTIGUOUS'] expnd = np.lib.stride_tri...
python|numpy
3
7,657
47,635,788
np.insert error in numpy version '1.13.3'
<p>I try to insert specific values in an array at given indices, with the use of <code>np.insert</code>. Before I used Numpy 1.12 and the code was running fine but with the new Numpy 1.13.3 the following error occurs</p> <pre><code>ValueError: shape mismatch: value array of shape () could not be broadcast to indexing ...
<p>Early <code>numpy</code> can replicate <code>values</code> as needed to fit the index size:</p> <pre><code>&gt;&gt;&gt; x = numpy.arange(10) &gt;&gt;&gt; numpy.insert(x,[1,3,4,5],[10,20]) array([ 0, 10, 1, 2, 20, 3, 10, 4, 20, 5, 6, 7, 8, 9]) &gt;&gt;&gt; numpy.__version__ '1.12.0' </code></pre> <p>New nu...
numpy|insert
0
7,658
59,017,002
Transforming every training points without using dataloaders
<p>I just found out that even though <code>torchvision.dataset.MNIST</code> accepts the <code>transformer</code> parameter, ...</p> <pre class="lang-py prettyprint-override"><code>transform = transforms.compose( [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))] ) mnist_trainset = datasets.mnist( ro...
<p>Transforms are invoked when you sample the dataset using its <code>__getitem__</code> method. So you could do something like the following to get all the transformed data.</p> <pre><code>imgs_transformed = [] for img, label in mnist_testset: imgs_transformed.append(img[0,:,:]) </code></pre> <p>or using list co...
python|pytorch
1
7,659
58,988,771
passing a dataframe to a thread
<p>Inside a function, I created a local dataframe with name resamp_df. I am trying to pass this local dataframe to a thread function as an argument for running some algorithm on it. Here is my code:</p> <p>main function</p> <pre><code>if readyForOrder: order_thread = threading.Thread(target=order_management, name...
<p>Pass in arguments as a tuple</p> <pre><code>args=(resamp_df, ) </code></pre>
python|pandas|dataframe|python-multithreading
1
7,660
58,770,711
python3 - pandas determine if events occurrence are statistically significant
<p>I have a large dataset that looks like the below. I'd like to know if there is a significant statistical difference between when the event occurs vs when it does not occur. The assumption here is that the higher the percent change the more meaningful/better. </p> <p>In another dataset the "event occurs" column is "...
<blockquote> <p>Load Packages, Set Globals, Make Data.</p> </blockquote> <pre><code>import scipy.stats as stats import numpy as np n = 60 stat_sig_thresh = 0.05 event_perc = pd.DataFrame({"event occurs": np.random.choice([True,False],n), "percent change": [i*.1 for i in np.random.randint(...
python-3.x|pandas
3
7,661
70,371,902
Pandas: Looking to create a multiple nested dictionary
<p>Here is what I am looking to generate:</p> <pre><code>{A: {1: [1,2], 2: [2,5]}, B: {3: [1,4], 4: [7,8]}} </code></pre> <p>Here is the df:</p> <pre><code>id sub_id A 1 A 2 B 3 B 4 </code></pre> <p>and I have the following array:</p> <pre><code>[[1,2], [2,5], [1,4], [7,8]] </code></pre> <p>So far, I have the foll...
<p>With a simple loop this can be done like:</p> <pre><code>from collections import defaultdict sub_id_array_dict = defaultdict(dict) for i, s, a in zip(df['id'].to_list(), df['sub_id'].to_list(), arrays): sub_id_array_dict[i][s] = a </code></pre>
python|json|pandas
0
7,662
56,394,009
Python cx_Oracle loading CSV using executemany() gives "Required argument 'parameters' (pos 2) not found"
<p>My intention is to load the csv file in a Oracle table using Python.</p> <ol> <li><p>I'm truncating table, if data already exists - This is working</p> </li> <li><p>I'm checking the count for testing purpose - This is working</p> </li> <li><p>I'm trying to Insert data from file in to Oracle. I'm getting issue:</p> <...
<p>The parameters to executemany() are indeed required. See the <a href="https://cx-oracle.readthedocs.io/en/latest/cursor.html#Cursor.executemany" rel="nofollow noreferrer">documentation</a> for more information.</p> <p>You've put the parameters inside the SQL, but instead they should be specified as bind variables, ...
python|database|oracle|pandas|cx-oracle
0
7,663
55,830,420
invalid value error in get_report function
<pre><code>def get_report(analytics): return analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}], 'metrics': [{'expre...
<blockquote> <p>"Invalid value 'project-id@appspot.gserviceaccount.com' for viewId parameter."</p> </blockquote> <p><a href="https://i.stack.imgur.com/WiH2z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WiH2z.png" alt="enter image description here"></a></p> <p>The view Id should be the view id ...
pandas|google-api|google-analytics-api
0
7,664
55,922,680
Renaming files based on Dataframe content with Python and Pandas
<p>I am trying to read a <code>xlsx</code> file, compare all the reference numbers from a column to files inside a folder and if they correspond, rename them to an email associate with the reference number.</p> <p><strong>Excel File</strong> has fields such as:</p> <pre><code> Reference EmailAddress 1123 ...
<p>based on sample data:</p> <pre><code>Reference EmailAddress 1123 bob.smith@yahoo.com 1233 john.drako@gmail.com nan jane.smith#example.com 1334 samuel.manuel@yahoo.com </code></pre> <p>First you assemble a <code>dict</code> with the set of references as keys and the new ...
python|pandas
3
7,665
55,699,204
How to check if numpy array contains empty list
<p>Here is a sample code for data</p> <pre><code>import numpy as np myList1 = np.array([1,1,1,[1],1,1,[1],1,1]) myList2 = np.array([1,1,1,[],1,1,[],1,1]) </code></pre> <p>To see if elements in myList1 equals to [1] I could do this:</p> <pre><code>myList1 == [1] </code></pre> <p>But for myList2, to see if elements i...
<p>An array with a mix of numbers and lists (empty or not) is <code>object dtype</code>. This is practically a <code>list</code>; fast compiled <code>numpy</code> math no longer works. The only practical alternative to a list comprehension is <code>np.frompyfunc</code>.</p> <p>Write a small function that can distingui...
python|numpy
2
7,666
39,790,830
Getting a tuple in a Dafaframe into multiple rows
<p>I have a Dataframe, which has two columns (Customer, Transactions). The Transactions column is a tuple of all the transaction id's of that customer.</p> <pre><code>Customer Transactions 1 (a,b,c) 2 (d,e) </code></pre> <p>I want to convert this into a dataframe, which has customer and transaction id'...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>DataFrame</code></a> constructor:</p> <pre><code>df = pd.DataFrame({'Customer':[1,2], 'Transactions':[('a','b','c'),('d','e')]}) print (df) Customer Transactions 0 1 ...
python|pandas|dataframe|tuples|reshape
4
7,667
44,264,443
Why should be the function backward be called only on 1 element tensor or with gradients w.r.t to Variable?
<p>I am new to pytorch. I want to understand as to why we can't call the backward function on a variable containing a tensor of say size say [2,2]. And if we do want to call it on a variable containing tensor of say size say [2,2], we have to do that by first defining a gradient tensor and then calling the backward fun...
<p>from the tutorial on <code>autograd</code> </p> <blockquote> <p>If you want to compute the derivatives, you can call .backward() on a Variable. If Variable is a scalar (i.e. it holds a one element data), you don’t need to specify any arguments to backward(), however if it has more elements, you need to spec...
python|pytorch
5
7,668
69,641,623
Replace column value based other column values pyspark data frame
<p>I have the following spark data frame.</p> <pre><code>Date_1 Value Date_2 20-10-2021 1 Date 20-10-2021 2 Date 21-10-2021 3 Date 23-10-2021 4 Date </code></pre> <p>I would like to fill <code>Date_2</code> values by adding <code>Date_1 + (Value-1)</c...
<p>You would need to parse SQL function DATE_ADD like this:</p> <pre><code>( df .withColumn(&quot;Value&quot;, F.col(&quot;Value&quot;).cast(&quot;int&quot;)) .withColumn(&quot;Date_2&quot;, F.expr('DATE_ADD(Date_1, Value - 1)') ) ) </code></pre> <p>DATE_ADD(Date_1, Value - ...
python|pandas|dataframe|pyspark
1
7,669
69,535,075
write filename when iterating through dataframes
<p>I am passing to a function several pandas <code>df</code>:</p> <pre><code>def write_df_to_disk(*args): for df in args: df.to_csv('/transformed/'+str(df)+'.table',sep='\t') write_df_to_disk(k562,hepg2,hoel) </code></pre> <p><code>df</code> here will be a pandas dataframe.</p> <p>How can I assign the dif...
<p>ok I think I managed.</p> <pre><code>def write_df_to_disk(l,*args): for l,df in zip(l,args): df.to_csv('transformed/'+l+'.table',sep='\t') write_df_to_disk(['k562','hepg2','hoel'],k562,hepg2,hoel) </code></pre>
python|pandas
0
7,670
69,508,015
using Numpy for Kmean Clustering
<p>I'm new in machine learning and want to build a Kmean algorithm with k = 2 and I'm struggling by calculate the new centroids. here is my code for kmeans:</p> <pre><code>def euclidean_distance(x: np.ndarray, y: np.ndarray): # x shape: (N1, D) # y shape: (N2, D) # output shape: (N1, N2) dist = [] for ...
<p>Changing inputs to NumPy arrays should get rid of errors:</p> <pre class="lang-py prettyprint-override"><code>x = np.array([[1., 0.], [0., 1.], [0.5, 0.5]]) y = np.array([[1., 0.], [0., 1.]]) </code></pre> <p>Also seems like you must change <code>for i in iterations</code> to <code>for i in range(iterations)</code> ...
python|numpy|k-means
1
7,671
41,157,482
Group average of a numpy array?
<p>I have a large numpy array, with dimensions <code>[1]</code>. I want to find out a sort of "group average". More specifically,</p> <p>Let my array be <code>[1,2,3,4,5,6,7,8,9,10]</code> and let my <code>group_size</code> be <code>3</code>. Hence, I will average the first three elements, the 4th to 6th element, the ...
<p>A good smoothing function is the <a href="https://en.wikipedia.org/wiki/Kernel_(image_processing)" rel="nofollow noreferrer">kernel convolution</a>. What it does is it multiplies a small array in a moving window over your larger array. </p> <p>Say you chose a standard smoothing kernel of <code>1/3 * [1,1,1]</code>...
python|numpy|matplotlib
3
7,672
54,083,349
Efficient PyTorch DataLoader collate_fn function for inputs of various dimensions
<p>I'm having trouble writing a custom <code>collate_fn</code> function for the PyTorch <code>DataLoader</code> class. I need the custom function because my inputs have different dimensions.</p> <p>I'm currently trying to write the baseline implementation of the <a href="https://arxiv.org/abs/1712.06957" rel="noreferr...
<p>Very interesting problem! If I understand you correctly (and also checking the abstract of the paper), you have <em>40,561 images from 14,863 studies, where each study is manually labeled by radiologists as either normal or abnormal.</em></p> <p>I believe the reason why you had the issue you faced was, say, for exam...
python-3.x|machine-learning|pytorch|mini-batch
1
7,673
38,166,804
Subset a 2D array by a 2D array in python
<p>I want to use a 2D array to subset another 2D array(they have the same length), for example:</p> <pre><code>import numpy as np tmp = np.array([[0.33, 0.67], [0.67, 0.33]]) index = np.array([[1], [0]]) </code></pre> <p>What I want is something like this:</p> <pre><code>In[91]: np.array([tmp[i][index[i]] for i in r...
<p>You can create the indices of the rows using <code>shape()</code> of your <code>index</code> array and the <code>inedx</code> itself as the the columns, then use a simple indexing to get the intended items:</p> <pre><code>&gt;&gt;&gt; tmp[(np.array(index.shape[::-1])-1)[:,None], index] array([[ 0.67], [ 0.67...
python|arrays|numpy
0
7,674
38,101,009
Changing multiple column names but not all of them - Pandas Python
<p>I would like to know if there is a function to change specific column names but without selecting a specific name or without changing all of them.</p> <p>I have the code:</p> <pre><code>df=df.rename(columns = {'nameofacolumn':'newname'}) </code></pre> <p>But with it i have to manually change each one of them writing...
<p>say you have a dictionary of the new column names and the name of the column they should replace:</p> <pre><code>df.rename(columns={'old_col':'new_col', 'old_col_2':'new_col_2'}, inplace=True) </code></pre> <p>But, if you don't have that, and you only have the indices, you can do this:</p> <pre><code>column_indic...
python|pandas|dataframe
58
7,675
66,040,089
Pandas aggregations in python
<p>I have the following data set. I want to create a dataframe that contains all teams and include the number of games played, wins, losses, and draws, and average point differential in 2017 (Y = 17).</p> <pre><code> Date Y HomeTeam AwayTeam HomePoints AwayPoints 2014-08-16 14 Arsenal Cr...
<p>Melting the dataframe granting us two new lines per old line, this allows us to have a line for the <code>HomeTeam</code> and a line for the <code>AwayTeam</code>.</p> <p>Please find the documentation for the <code>melt</code> method here : <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel=...
python|pandas
0
7,676
46,549,825
Tensorflow convolution
<p>I'm trying to perform a convolution (<code>conv2d</code>) on images of variable dimensions. I have those images in form of an 1-D array and I want to perform a convolution on them, but I have a lot of troubles with the shapes. This is my code of the <code>conv2d</code>:</p> <pre><code>tf.nn.conv2d(x, w, strides=[1,...
<p>You can't use <a href="https://www.tensorflow.org/api_docs/python/tf/nn/conv2d" rel="nofollow noreferrer"><code>conv2d</code></a> with a tensor of rank 1. Here's the description from the doc:</p> <blockquote> <p>Computes a 2-D convolution given <strong>4-D</strong> input and filter tensors.</p> </blockquote> <p>...
python|image|tensorflow|reshape|convolution
3
7,677
58,224,316
Convert panda column to a string
<p>I am trying to run the below script to add to columns to the left of a file; however it keeps giving me </p> <pre><code>valueError: header must be integer or list of integers </code></pre> <p>Below is my code:</p> <pre><code>import pandas as pd import numpy as np read_file = pd.read_csv("/home/ex.csv",header='tr...
<p>According to pandas docs <code>header</code> is row number(s) to use as the column names, and the start of the data and must be int or list of int. So you have to pass <code>header=0</code> to <code>read_csv</code> method. </p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.h...
python-3.x|pandas|numpy|dataframe
0
7,678
58,496,987
Filter forward col 1 without iteration
<p>I am dealing with a "waterfall" structure DataFrame in Pandas, Python.</p> <p>Column 1 is full, while the rest of the data set is mostly empty representing series available for only a subset of the total period considered:</p> <pre><code>Instrument AUPRATE. AIB0411 AIB0511 AIB0611 ... AIB1120 AIB1220 AIB0121 AIB0...
<p>Maybe someone would find a 'cleaner' solution, but what I thought about was first iterating over the columns, to check for each row which is the column whose value you need to replace (backwards, so that it'll end up with the first occurance) with:</p> <pre><code>df['column_to_move'] = np.nan cols = df.columns.toli...
python|pandas|iteration
1
7,679
58,294,319
Using np.where returns error after using .any()
<p>I'm working on a dataframe that needs to create a large amount of flags, depending on multiple conditions. I'm using <code>np.where</code> but now I'm running into this error </p> <pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p>...
<p>Try replacing</p> <pre><code>(df['day_a1'] &gt; 27 or df['day_a1'] &lt; 4) </code></pre> <p>by</p> <pre><code>((df['day_a1'] &gt; 27) | (df['day_a1'] &lt; 4)) </code></pre> <p>Note the use of <code>|</code> and the additional parenthesis for the precedence.</p>
python|pandas|numpy|where-clause
3
7,680
69,287,891
how do I append an array in python?
<p>I have some arrays of different sizes (such as (140,9), (120,9),...,(123,9)). I need to merge all of them into one array. I used the following code, but it said NumPy array does not have <code>append</code> attribute. could you please tell me how can I do it?</p> <pre><code>os.chdir(&quot;E:/pythoncode/feature&quot;...
<p>Hope this helps! Comments are added too.</p> <pre><code>os.chdir(&quot;E:/pythoncode/feature&quot;) #change directory to downloads folder files_path = [os.path.abspath(x) for x in os.listdir()] fnames_transfer = [x for x in files_path if x.endswith(&quot;.npy&quot;)] feature=np.zeros((2000,9)) feature_new = []#Adde...
python|python-3.x|numpy
1
7,681
69,225,532
Pandas df.values causes additional memory consumption
<p>I have a big pandas dataframe with about 300 columns and the column types are all float32. I would like to try machine learning algorithms with the data, so I call <code>df[x_columns].values</code> to create the numpy ndarray which will then be used as input to machine learning algorithms. By looking at memory consu...
<p>The first time, use this.</p> <pre><code>np_values = (df[x_columns].values).to_numpy np.savez('values.npz', values=np_values) # saves a .npz file to disk </code></pre> <p>For all future runs with this program, comment out any lines dealing with your pandas df and directly read in from the saved numpy array.</p> <pre...
python|pandas|numpy
0
7,682
69,041,135
Cummulative sum with repsect to feature with dtype = interval
<p>I have a dataset for which I want to transform to give cummulative percentages. In normal cases, this isn't a hard thing do do, but in this case the cummulation needs to be done on distance bins. So, here is my dataframe:</p> <pre><code>distance_bin objects in bin percentage 0 (-0.001, 0.5] 12054 3...
<p>Try:</p> <pre><code>right = pd.IntervalIndex(df['distance_bin']).right df['distance_bin'] = pd.IntervalIndex.from_tuples(list(zip([-0.001]*len(right), right))) df[['ESL:s in bin', 'percentage']] = df[['ESL:s in bin', 'percentage']].cumsum() </code></pre> <pre><code>&gt;&gt;&gt; df distance_bin ESL:s in bin p...
python-3.x|pandas
1
7,683
44,728,747
Adding multiple json data to panda dataframes
<p>I am using a api to get 3 json data and I would like to add those datas to 1 panda dataframes</p> <p>This is my code I am passing in books which contains the book id as x and those 3 id returns me 3 different json objects with all the book information.</p> <pre><code>for x in books: newDF = pd.DataFrame() bookinfo...
<p>IIUC:</p> <pre><code>pd.concat( pd.DataFrame([requests.get( http://books.com/?x}).json() for x in books]), ignore_index=True) </code></pre> <p>Alternatively you can collect JSON responses into a list and do the following:</p> <pre><code>In [30]: pd.concat([pd.DataFrame(x['bookInfo']) for x in d], ignore_i...
python|json|pandas
4
7,684
44,578,571
Intersect two boolean arrays for True
<p>Having the numpy arrays</p> <pre><code>a = np.array([ True, False, False, True, False], dtype=bool) b = np.array([False, True, True, True, False], dtype=bool) </code></pre> <p>how can I make the intersection of the two so that only the <code>True</code> values match? I can do something like:</p> <pre><code>a...
<p>Numpy provides <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html" rel="noreferrer"><code>logical_and()</code></a> for that purpose:</p> <pre><code>a = np.array([ True, False, False, True, False], dtype=bool) b = np.array([False, True, True, True, False], dtype=bool) c = np.l...
python|python-3.x|numpy
39
7,685
44,414,721
Numpy delete rows of array inside object array
<p>I am trying to delete rows from arrays which are stored inside an object array in numpy. However as you can see it complains that it cannot broadcast the smaller array into the larger array. Works fine when done directly to the array. What is the issue here? Any clean way around this error other than making a new ob...
<p>The fact that <code>np.array</code> creates as high a dimensional array as it can has been discussed many times on SO. If the elements are different in size it will keep them separate, or in some cases raise an error.</p> <p>In your example</p> <pre><code>In [201]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))...
python|arrays|numpy
1
7,686
61,141,833
Get rid of initial spaces at specific cells in Pandas
<p>I am working with a big dataset (more than 2 million rows x 10 columns) that has a column with string values that were filled oddly. Some rows start and end with many space characters, while others don't.</p> <p>What I have looks like this:</p> <pre><code> col1 0 (spaces)string(spaces) 1 ...
<pre><code>df['col1'].apply(lambda x: x.strip()) </code></pre> <p>might help</p>
python|pandas|loops|for-loop
1
7,687
60,853,680
Compute grads of cloned tensor Pytorch
<p>I am having a hard time with gradient computation using PyTorch. </p> <p>I have the outputs and the hidden states of the last time step <code>T</code> of an RNN. </p> <p>I would like to clone my hidden states and compute its grad after backpropagation but it doesn't work. </p> <p>After reading <a href="https://s...
<p>Based on the comments the problem is that <code>hidden_copy</code> is never visited during the backward pass.</p> <p>When you perform backward pytorch follows the computation graph backwards starting at <code>loss_T</code> and works backwards to all the leaf nodes. It only visits the tensors which were used to comp...
python|pytorch|gradient|tensor
1
7,688
60,919,734
Marking Integer points on plot in python
<p>In the code below, I would like to mark the integer points. I tried many options and different functions, but couldn't achieve the desired outcome.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from matplotlib import pyplot as plt n = np.arange(-3,3,0.1) x = n**2 plt.plot(n,x,'-ok') </code...
<p>Here is an appraoch:</p> <ul> <li>use x-values in a dense linspace to draw the smooth curve</li> <li>use n-values of integers to draw the dots</li> </ul> <p>A polynomial with integer coefficients gives integer values for all integer input.</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pypl...
python|numpy|matplotlib|plot|spyder
1
7,689
71,549,711
Python Pandas - Vlookup - Update Existing Column in First Data Frame From Second Data Frame
<p>I am searching for the most pythonic way to achieve the following task:</p> <p>first data frame:</p> <pre><code>df1 = dataA dataB key info dataC 0 ABC 123 a1b aaa 1 DEF 456 b57 bbb 2 GHI 789 a22 ccc </code></pre> <p>second data frame:</p> <pre><code>d...
<p>Use Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> over <code>df1</code> and <code>df2</code> on columns <code>['key','info']</code>, then, use column <code>key</code> as column name to join on and use only the keys from left...
python|pandas
0
7,690
43,309,508
Slicing array with numpy?
<pre><code>import numpy as np r = np.arange(36) r.resize((6, 6)) print(r) # prints: # [[ 0 1 2 3 4 5] # [ 6 7 8 9 10 11] # [12 13 14 15 16 17] # [18 19 20 21 22 23] # [24 25 26 27 28 29] # [30 31 32 33 34 35]] print(r[:,::7]) # prints: # [[ 0] # [ 6] # [12] # [18] # [24] # [30]] print(r[:,0]) # pri...
<p>Because the step argument is greater than the corresponding shape so you'll just get the first "row". However these are not identical (even if they contain the same numbers) because the scalar index in <code>[:, 0]</code> flattens the corresponding dimension (so you'll get a 1D array). But <code>[:, ::7]</code> will...
python|python-2.7|numpy
2
7,691
43,192,626
pandas Series getting 'Data must be 1-dimensional' error
<p>I'm new to pandas &amp; numpy. I'm running a simple program</p> <pre><code>labels = ['a','b','c','d','e'] s = Series(randn(5),index=labels) print(s) </code></pre> <p>getting the following error</p> <pre><code> s = Series(randn(5),index=labels) File "C:\Python27\lib\site-packages\pandas\core\series.py", line...
<p>I suspect you have your imports wrong.</p> <p>If you add this to your code:</p> <pre><code>from pandas import Series from numpy.random import randn labels = ['a','b','c','d','e'] s = Series(randn(5),index=labels) print(s) a 0.895322 b 0.949709 c -0.502680 d -0.511937 e -1.550810 dtype: float64 </code>...
python|pandas|numpy
5
7,692
72,311,901
Retrieving values from a DataFrame
<p>My DataFrame (<code>df = df.sort_values('market_name').iloc[:1]</code>):</p> <pre><code> competition event_name event_id country_code market_name market_id total_matched Home Home_id Away Away_id Draw Draw_id 7 CONMEBOL Copa Libertado...
<p>If you use <code>.iloc[0]</code> instead of <code>.iloc[:1]</code> then you get single row as <code>pandas.Series</code> and you can get value from <code>Series</code> using only header. And this doesn't need <code>.reset_index()</code></p> <pre><code>import pandas as pd data = { 'A': [1,2,3], 'B': [4,5,6]...
python|pandas|dataframe
1
7,693
72,422,392
How to create a new column from existed column which is formatted like a dictionary pandas dataframe
<p>In my pandas dataframe, I have a column formatted like a dictionary:</p> <p><a href="https://i.stack.imgur.com/j9kU4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j9kU4.png" alt="enter image description here" /></a></p> <p>What I want to do is extract data from this column and add two columns li...
<p>If 'column1' holds only one key: value per dictionary, then you can add new columns by calling the items method and using the first tuple:</p> <pre><code>df[['column2', 'column3']] = pd.DataFrame(df['column1'].apply(lambda x: list(x.items())[0]).tolist(), index=df.index) </code></pre>
python|pandas
2
7,694
72,203,065
Passing numpy ndarray as keras input
<p>I have a dataset that consists of numpy array and I need to pass this data as input for keras.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Idx</th> <th style="text-align: center;">Target</th> <th style="text-align: center;">RF</th> <th style="text-align: rig...
<p>As discussed in the comments, it would be best if you created your arrays directly instead of having a DataFrame in the middle.</p> <p>The problem is that even if <code>X</code> is a numpy array, it contains other arrays because Pandas returns an array for each row and each cell. An example:</p> <pre><code>import pa...
python|numpy|tensorflow|keras
0
7,695
72,395,708
How do I create a DataFrame with an empty pandas Series in a column?
<p>I'm trying to append each row of a DataFrame separately. Each row has Series and Scalar values. an example of a row would be</p> <pre><code>row = {'col1': 1, 'col2':'blah', 'col3': pd.Series(['first', 'second'])} </code></pre> <p>When I create a DataFrame from this, it looks like this</p> <pre><code>df = pd.DataFram...
<p>Ultimately, I reworked my code to avoid having this problem. My solution is as follows:</p> <p>I have a function <code>do_data_stuff()</code> and it used to return a pandas series, but now I have changed it to return</p> <ul> <li>a series if there's stuff in it <code>Series([1, 2, 3])</code></li> <li>or nan if it wo...
python|pandas|dataframe|initialization|series
0
7,696
50,592,013
Separating a tricky string throughout a whole dataframe
<pre><code>0 NC_000001.10:g.955563G&gt;C 1 NC_000001.10:g.955597G&gt;T 2 NC_000001.10:g.955619G&gt;C 3 NC_000001.10:g.957640C&gt;T 4 NC_000001.10:g.976059C&gt;T 5 NC_000003.11:g.37090470C&gt;T 6 NC_000012.11:g.133256600G&gt;A 7 NC_012920.1:m.15923A&gt;G </code></pre> <p>I have a column in a dat...
<p>The following works for your example:</p> <pre><code>df[0].str.extract(':\w\.(\d+)(.+)') # 0 1 #0 955563 G&gt;C #1 955597 G&gt;T #2 955619 G&gt;C #3 957640 C&gt;T #4 976059 C&gt;T #5 37090470 C&gt;T #6 133256600 G&gt;A #7 15923 A&gt;G </code></pre> <p>If the last "c...
python|string|pandas|series
3
7,697
45,560,672
Tf-slim: ValueError: Variable vgg_19/conv1/conv1_1/weights already exists, disallowed. Did you mean to set reuse=True in VarScope?
<p>I am using tf-slim to extract features from several batches of images. The problem is my code works for the first batch , after that I get the error in the title.My code is something like this:</p> <pre><code>for i in range(0, num_batches): #Obtain the starting and ending images number for each batch batch_...
<p>You should create your graph <strong>once</strong>, not in a loop. The error message tells you exactly that - you try to build the same graph twice.</p> <p>So it should be (in pseudocode)</p> <pre><code>create_graph() load_checkpoint() for each batch: process_data() </code></pre>
deep-learning|tensorflow|tf-slim
1
7,698
45,299,596
Tensorboard : Error metadata.tsv is not a file
<p>I am manually trying to link <code>embedding</code> tensor with <code>metadata.tsv</code>, but I am getting following error: <code>"$LOG_DIR/metadata.tsv is not a file."</code> </p> <p>I am running Tensorboard with following command : <code>tensorboard --logdir default/</code> and my <code>projector_config.pbtxt<...
<p>It cannot recognize <code>$LOG_DIR</code> the way you have used it. Either edit <code>projector_config.pbtxt</code> manually to provide the full path, or use this in your code:</p> <pre><code>import os embedding.metadata_path = os.path.join(LOG_DIR, 'metadata.tsv') </code></pre> <p>where again <code>LOG_DIR</code>...
tensorflow|tensorboard
2
7,699
45,479,091
Getting error slicing time series with pandas
<p>I'm trying to slice a time series, I can do it perfectly this way :</p> <pre><code>subseries = series['2015-07-07 01:00:00':'2015-07-07 03:30:00'] . </code></pre> <p>But the following code won't work</p> <pre><code>def GetDatetime(): Y = int(raw_input("Year ")) M = int(raw_input("Month ")) D = int(ra...
<p>change <code>def GetDatetime()</code> function return value to:</p> <pre><code>return str(d) </code></pre> <p>This will return datetime string which times series will be able to deal with.</p>
python|pandas|numpy|time-series
4