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
369,600
72,085,899
How to use all() and any() function in pandas with multiple columns
<p>I need one help regarding: How to use <code>all</code> and <code>any</code> function in Pandas with multiple columns. Below is my data frame:</p> <pre><code> ResolutionCodeMapID CauseCodeMapID TicketTypeMapID multiple ApplicationID 1292...
<p>Solution generate <code>True</code> if all values are greater or equal like <code>10</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.all.html" rel="nofollow noreferrer"><code>DataFrame.all</code></a>:</p> <pre><code>cols = ['CauseCodeMapID','CauseCodeMapID','TicketType...
python|pandas
1
369,601
71,817,573
Keras Model early stops even though min_delta condition is not achieved
<p>I am training a Keras Sequential Model as follows. It is for the mnist dataset for 5 numbers. In goes the 28x28 images flattened and out comes a one hot notation for the class that they belong to.</p> <pre><code>model = keras.Sequential([ keras.layers.InputLayer(input_shape = (784, )), keras.layers.Dense(32, activat...
<p>You should set <code>patience</code> to <code>1</code> in the callback definition. If you don't, it defaults to <code>0</code>.</p> <pre><code>es = keras.callbacks.EarlyStopping(monitor='loss', min_delta=1e-4, verbose=2, patience=1) </code></pre>
tensorflow|keras
1
369,602
71,879,050
How to extract the last year (YYYY) from a YYYY-YY format column in Pandas
<p>I am trying to extract the last year (YY) of a fiscal date string in the format of YYYY-YY. e.g The last year of this '1999-00' would be 2000.</p> <p>Current code seems to cover most cases other than this.</p> <pre><code>import pandas as pd import numpy as np test_df = pd.DataFrame(data={'Season':['1996-97', '1997...
<p>This should work too:</p> <pre><code>pd.to_numeric(test_df['Season'].str.split('-').str[0]) + 1 </code></pre> <p>Output:</p> <pre><code>0 1997 1 1998 2 1999 3 2000 4 2001 5 2002 6 2003 7 2004 8 2005 9 2006 10 2007 11 2008 12 2009 13 2010 14 2011 15 2012 </cod...
python|pandas|string|datetime|apply
2
369,603
71,883,566
Pandas counting number of rows based on data of two columns
<p>I am working on a dataset with format similar to this :-</p> <pre><code>Name Sex Survived random_cols . . . . Akshit Male 1 rand_val ....... Hema Female 0 ................. Rekha Female 1 ................. . . . </code></pre> <p>I want to ...
<p>You can use boolean indexing to filter by the <code>Survived</code> column to get only survived rows then <code>value_counts</code> on <code>Sex</code> column:</p> <pre class="lang-py prettyprint-override"><code>s = df[df['Survived'].eq(1)].value_counts(subset=['Sex']) </code></pre> <pre><code>print(s) Sex Female ...
python|pandas|dataframe
1
369,604
72,084,171
How to create dummy variable for specifc values in a column?
<p>I want to create a dummy variable for a specific value in a column. Let's say my database looks like this :</p> <p><img src="https://i.stack.imgur.com/AFTeR.png" alt="database" /></p> <p>I want a dummy variable just for the museums.</p> <pre><code>pd.get_dummies (df,['Buildings']) </code></pre> <p>gives me a dummy ...
<p>If need only one column simpliest is create it manually with casting boolean to integers:</p> <pre><code>df['museum'] = df['Buildings'].eq('museum').astype(int) </code></pre> <p>With your solution is possible replace non <code>museum</code> values to missing values, then <code>pd.get_dummies</code> omit missing valu...
pandas|dummy-variable
0
369,605
71,917,358
Why can not pass the validation of type of the series
<p>I do not know why it can not pass the validation of each variable.</p> <pre><code>marvel_df = rate_df.loc[rate_df['Company']== &quot;Marvel&quot;] mean_marvel =marvel_df[['Rate']].mean() std_marvel =marvel_df[['Rate']].std() n_marvel = marvel_df[['Rate']].count() dc_df = rate_df.loc[rate_df['Company']== &quot;DC&qu...
<p>Try it with this cleaned up code:</p> <pre><code>marvel_df = rate_df[rate_df['Company'] == &quot;Marvel&quot;] mean_marvel = marvel_df['Rate'].mean() std_marvel = marvel_df['Rate'].std() n_marvel = marvel_df['Rate'].count() dc_df = rate_df[rate_df['Company'] == &quot;DC&quot;] mean_dc = dc_df['Rate'].mean() std_dc ...
python|pandas
0
369,606
71,941,228
More Epoch make loss rising
<p>I have a time-series dataset and I trained it using LSTM. I train using 200 epochs and the result is the loss value and val_loss value is pretty good (IMO)</p> <p><a href="https://i.stack.imgur.com/u3828.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3828.png" alt="enter image description here" ...
<p>This is probably because your lr(learning rate) is too large. You could try to reduce your lr. From the graph, the training loss is increased so I think this case is not the problem of overfitting.</p>
tensorflow|machine-learning|keras|time-series|lstm
0
369,607
71,873,074
DF return a date column with 2 formats
<p>I have a df with a column with date, but the outcome is different for the lines, some lines outcomes <strong>ddmmyy</strong> some lines <strong>mmddyy</strong>. The database is all equal <strong>ddmmyy</strong>.</p> <blockquote> <p>12/20/2021 12/21/2021 12/22/2021 12/22/2021 12/27/2021 12/27/2021 12/27/2021 12/27/20...
<p>you can simply change the format of the entire column to dd-mm-yy format</p> <pre><code>import datetime as dt import pandas as pd df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '1/26/2015'}}) df['DOB_1'] = pd.to_datetime(df.DOB).dt.strftime('%d/%m/%Y') df DOB DOB_1 0 26/1/2016 26/01/2016 1 1/26/201...
python|pandas
0
369,608
72,092,973
Error applying a weighted rolling average by group in Python
<p>I have the following dataframe for which I'm trying to compute a weighted rolling average:</p> <pre><code>import pandas as pd df = pd.DataFrame({'player_ID': {0: 123, 1: 123, 2: 123, 3: 123, 4: 123, 5: 456, 6: 456, 7: 456, 8: 456, 9: 456}, 'hole_sg': {0: 3.14, 1: 2.70, 2: 5.20, 3: -0.02, 4...
<p>When you <code>groupby</code> and use <code>rolling</code> you get a MultiIndex. To align with the original DataFrame, you can use:</p> <pre><code>df[&quot;rolling&quot;] = df.groupby('player_ID')['hole_sg'].rolling(3).apply(lambda x: (np.dot(x, weights))/weights.sum()).droplevel(0) &gt;&gt;&gt; df player_ID ho...
python|pandas|statistics|rolling-computation
2
369,609
71,898,481
Dask map_blocks is running earlier with a bad result for overlap and nested procedures
<p>I'm using Dask to create a simple pipeline of data manipulation. I'm basically using 3 functions. The first two uses a simple <code>map_blocks</code> and the third one uses a <code>map_blocks</code> also but for an overlapped data.</p> <p>For some reason, the third <code>map_blocks</code> is executing earlier than I...
<p>Like many dask operations, da.overlap operations can either be passed a <code>meta</code> argument specifying the output types and dimensions, or dask will execute the function with a small (or length zero) subset of the data.</p> <p>From the <a href="https://docs.dask.org/en/stable/array-overlap.html" rel="nofollow...
python|numpy|dask
1
369,610
71,962,073
extract emotions from text in dataframe in senticnet
<p>I am very novice in python and I treat to extract emotions from sentence in datafram though senticNet<br /> this my code but its not correct<br /> I don't know what's the wrong</p> <pre><code>from senticnet.senticnet import SenticNet def emotion_list1(text): Emotion_list=[] Emotion = pd.DataFrame(columns=...
<p>Are you facing any specific errors? I am able to extract the emotions using sn.moodtags() from a sentence.</p> <pre><code># import from senticnet.senticnet import SenticNet from nltk.tokenize import word_tokenize # define sentinet() sn = SenticNet() # create empty list to store results emotion_list = [] # tokeni...
python|pandas|dataframe
2
369,611
72,047,493
Type error on Python: not all arguments converted during string formatting
<p>i am trying to multiply the image for image data set using pytorch random transform.</p> <p>the code used to work however today it seems to produce error for formatting.</p> <p>the loop for the data into a larger sample.</p> <pre><code>or _ in range(80): for img, label in dataset: save_image(img, 'img'+s...
<p>When you use the <code>%</code> operator on a string, the first string needs to have formatting placeholders that will be replaced by the values after <code>%</code>. But you have no <code>%s</code> in the first string.</p> <p>When you're creating pathnames, you should use <code>os.path.join()</code> rather than str...
python|loops|pytorch|data-augmentation
0
369,612
71,842,607
MUJOCO_PY:Computed torque control for kuka iiwa14 robot
<p>I'm new with mujoco_py.I already installed it successfully on linux and I have the URDF file of the robot(kukaiiwa14) but I don't know how can I manipulate the joints.For example I want to know the commands of how can I apply a force on a joint . I have to apply optimal control on this robot so that he throws a ball...
<p><code>mujoco_py</code> is unsupported and deprecated, you should probably use MuJoCo's <a href="https://mujoco.readthedocs.io/en/latest/python.html" rel="nofollow noreferrer">native Python bindings</a>.</p> <p>Regarding applying forces to joints, the actuation model is described <a href="https://mujoco.readthedocs.i...
python|numpy|controls|robotics|mujoco
1
369,613
72,078,224
How to get Centroid in GeoPandas
<p><strong>Centroid in Geopandas</strong></p> <p>I have two location so I want get centroid from geopandas by python? How I do it?</p>
<p>You can use <a href="https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoSeries.centroid.html" rel="nofollow noreferrer"><code>geopandas.GeoSeries.centroid</code></a>:</p> <pre class="lang-py prettyprint-override"><code>import geopandas as gpd df = gpd.read_file(&quot;polygons.shp&quot;) df[&quot;centro...
python|jupyter-notebook|geopandas
2
369,614
71,931,102
Trying to find a graph in matplotlib
<p>I have data that show the difference of temperatures from 1955 to 2020 from an average. I want to make a graph in matplotlib that looks like this: <a href="https://i.stack.imgur.com/7SbkV.jpg" rel="nofollow noreferrer">It shows temperature differences.</a></p> <p>My data look like this:</p> <pre><code>DATE TAVG ...
<p>You can use the pandas plotting (basicly, it's matplotlib). For the plot, I just created some fake data. I also assumed the line plot is a moving average.</p> <pre><code>import random import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import seaborn as sns # Cre...
python|pandas|matplotlib|plot|graph
1
369,615
71,833,877
Using a function in a loop and storing all the results
<p>So I created a function that returns the returns of quantile portfolios as a time series.</p> <p>If I call Quantile_Returns(2014), the result (DataFrame) looks like this.</p> <pre><code>Date Q1 Q2 Q3 Q4 Q5 2014-02-28 6.20 4.87 5.41 5.04 4.91 2014-03-31 -0.50 0.05 ...
<p>Try replacing the whole loop with</p> <pre><code>Quantile = pd.concat(Quantile_Returns(j) for j in range(1960, 2021)) </code></pre> <p><code>pd.concat</code> is expecting a sequence of pandas objects, and in the second pass through your loop you are giving it a DataFrame as the first argument (not a sequence of Data...
python|pandas|function|loops|concatenation
1
369,616
72,042,131
Model cannot fit on Tensorflow data pipline with unknown TensorShape
<p>I have a data loader pipeline for video data. Although I specify the output of the pipeline, I still get the following error when calling model.fit. &quot;ValueError: as_list() is not defined on an unknown TensorShape&quot;. I searched for the error and most people say it is because of the tf.numpy_function that ret...
<p>Okay I found another solution. I do not exactly know why it works, just calling the following function does the job.</p> <pre><code> def set_shape(video, label): video.set_shape((40,160,160, 3)) label.set_shape([]) return video, label </code></pre>
python|tensorflow|pipeline|dataloader
1
369,617
72,123,367
Remove specific data from a Python pandas dataset
<p>We wrote this code in order to plot a charge spectrum like this (histo from HG (columun) for a specific CH (another column)):</p> <p><a href="https://i.stack.imgur.com/SJxwn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SJxwn.png" alt="enter image description here" /></a></p> <p>This plot was ob...
<p>You can delete them basing on boolean conditions. In your case this should work:</p> <pre><code>df = df[df['Ts(ns)'] != '-'] # or change the '-' with the value you want filter on </code></pre> <p>You can have a look at <a href="https://datascienceparichay.com/article/pandas-delete-rows-based-on-column-values/" rel=...
python|pandas|dataframe|matplotlib
1
369,618
71,899,677
Extract specific words from dataframe
<p>I have the following dataframe named marketing where i would like to extract out source= from the values. Is there a way to create a general regex function so that i can apply on other columns as well to extract words after equal sign?</p> <pre><code>Data source=book,social_media=facebook,ads=Facebook source=b...
<p>You can split the column value of string type into dict then use <code>pd.json_normalize</code> to convert dict to columns.</p> <pre class="lang-py prettyprint-override"><code>out = pd.json_normalize(marketing['Data'].apply(lambda x: dict([map(str.strip, i.split('=')) for i in x.split(',')]))).dropna(subset='source'...
python|pandas|dataframe
1
369,619
71,946,460
Pandas Merge On Multiple Columns
<p>I need to merge the below two dataframes to yield the below result.</p> <p>Table_1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>foo1</th> <th>foo2</th> <th>date</th> <th>value1</th> <th>value2</th> </tr> </thead> <tbody> <tr> <td>a</td> <td>b</td> <td>4/20</td> <td>6</td> <td>NaN</td>...
<p>you could do this:</p> <pre><code>pd.merge(Table_1, Table_2, how=&quot;outer&quot;, on=['foo1','foo2','date']) </code></pre>
python|pandas|dataframe
0
369,620
71,806,589
Write a function that takes one row and returns a list of 2-dimension tuples: song title and points database
<p>I need to preprocess some data so that I can start analyzing it. I currently have a data frame which contains data of Eurovision winners. I need to create a new data frame which contains the words from each of the songs, with the points of each song assigned to each word in a tuple. For example, if the song name is ...
<p>You have the right idea, only right now you are iterating over every character in the string <code>row[&quot;Song&quot;]</code>. You need to split this string up into a sequence of substrings where each substring represents a word from the song. Then iterate over this sequence. This code shows how one might do that<...
python|pandas|dataframe
0
369,621
71,867,499
AttributeError: 'tuple' object has no attribute 'set_xlim' matplotlib python
<p>I am trying to plot plot hist with dates in x axes and adjust dates. My code is</p> <pre><code> ax=plt.hist(df[ (df['disease']==1) &amp; (df['FARM_NUM']==1282000)]['DATE'],bins=20) ax.set_xlim([datetime.date(2020, 3, 15), datetime.date(2021, 7, 1)]) plt.xticks(rotation=90) plt.show() </code></pre> <p>and...
<p><code>plt.hist</code> does not return the axis, it returns the bins of the histogram and other metadata. Just call xlim on <code>plt</code> itself.</p> <pre><code>plt.xlim(left=leftValue, right=rightValue) </code></pre> <p>Caution: This solves the problem when the axes has numbers... I do not know how it will behave...
python|pandas|matplotlib
2
369,622
71,848,640
Pandas Timeseries reindex producing NaNs
<p>I am surprised that my reindex is producing NaNs in whole dataframe when the original dataframe does have numerical values init. Don't know why?</p> <p>Code:</p> <pre><code>df = A ... D Unnamed: 0 ... 2...
<p>From the documentation you can see that df.reindex() will <code>Places NA/NaN in locations having no value in the previous index.</code></p> <p>However you can also provide a value that you want to replace missing values with (It defaults to NaN):</p> <pre><code>df.reindex(onesec_idx, fill_value='') </code></pre> <p...
python|pandas|dataframe|reindex
1
369,623
71,916,043
Creating multiple dataframe using loop or function
<p>I'm trying to extract the hash rate for 3 cryptocurrencies and I have attached the code for the same below. Now, I want to pass three urls and in return I need three different different dictionaries which should have the values. I'm stuck and I don't understand how should I go about it. I have tried using loops but ...
<p>You can use next example how to get data from all 3 URLs and create a dataframe/dictionary from it:</p> <pre class="lang-py prettyprint-override"><code>import re import requests import pandas as pd url = { &quot;Bitcoin&quot;: &quot;https://bitinfocharts.com/comparison/bitcoin-hashrate.html#3y&quot;, &quot...
python|pandas|database|dataframe|dictionary
0
369,624
72,070,520
Is there a way to plot a histogram with given bin widths with Mathplotlib?
<p>I have two lists given. One, named &quot;bin_edge&quot;, represents the lower and upper borders of 24 bins by 25 values. The second, named &quot;counts&quot;, represents the according counts (=values) of each bin.</p> <p>My aim is, if possible, to get a Matplotlib histogram that should look like somewhat that:</p> <...
<p>As you already have the heights for each bin, you should create a bar plot.</p> <p>The x-values should be the bin edges, except for the last. By default, the bars are centered; you need <code>align='edge'</code> to align them with the bin edges. The widths of the bars are the differences of the bin edges.</p> <pre ...
python|numpy|matplotlib|histogram|bokeh
2
369,625
71,859,978
Pandas Step function with rank
<p>I am trying to rank a column with the following function:</p> <p><code>f(x) = if x=0, then y=0 else if x&lt;0 then y=0.5 else y=rank(x) </code> Any ideas on how can I achieve this?</p>
<p>You can use basic indexing</p> <pre><code>df = pd.DataFrame({&quot;x&quot;: [2, 3, 1, -1, 0]}) df[&quot;y&quot;] = df[&quot;x&quot;].rank() df[&quot;y&quot;][df[&quot;x&quot;] == 0] = 0 df[&quot;y&quot;][df[&quot;x&quot;] &lt; 0] = .5 </code></pre> <p>or <code>loc</code></p> <pre><code>df[&quot;y&quot;] = df[&quot;x...
python|pandas|rank
1
369,626
71,810,148
Using numpy to construct an array with rows extracted from another 2D array as 2x2 blocks
<p>Suppose I have the following 2D array:</p> <pre><code>x = np.array([[10,20,30,40], [50,60,70,80],[90,100,110,120]]) print(x) array([[ 10, 20, 30, 40], [ 50, 60, 70, 80], [ 90, 100, 110, 120]]) </code></pre> <p>I would like to construct a new array, <code>y</code>, where each row has the value...
<p>First, create a <a href="https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.sliding_window_view.html" rel="nofollow noreferrer"><code>sliding_window_view</code></a> into <code>x</code> with the 2x2 boxes you want to see:</p> <pre><code>b = np.lib.stride_tricks.sliding_window_view(x, (2, 2)) </c...
python|numpy|sliding-window
3
369,627
17,044,808
Python - Pandas: AttributeError: 'numpy.ndarray' object has no attribute 'start'
<p>Python - Pandas: AttributeError: 'numpy.ndarray' object has no attribute 'start'</p> <p>Code that generates the error:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import time data = pd.read_csv('/temp/zondata/pvlog.csv', delimiter=';', parse_dates=True, inde...
<p>It looks like it's important to include the <code>0</code>:</p> <pre><code>In [11]: df1['2010-7':'2010-10'] Out[11]: Empty DataFrame Columns: [value] Index: [] In [12]: df1['2010-07':'2010-10'] Out[12]: value date 2010-08-31 12:36:53 30.37 2010-08-31 12:45:08 28.03 2010-08-31 12:55:09 25.16...
python|numpy|matplotlib|pandas
2
369,628
16,705,598
Python 2.7 - statsmodels - formatting and writing summary output
<p>I'm doing logistic regression using <code>pandas 0.11.0</code>(data handling) and <code>statsmodels 0.4.3</code> to do the actual regression, on Mac OSX Lion.</p> <p>I'm going to be running ~2,900 different logistic regression models and need the results output to csv file and formatted in a particular way.</p> <p...
<p>There is no premade table of parameters and their result statistics currently available.</p> <p>Essentially you need to stack all the results yourself, whether in a list, numpy array or pandas DataFrame depends on what's more convenient for you. </p> <p>for example, if I want one numpy array that has the results f...
python|python-2.7|pandas|statsmodels
8
369,629
16,988,526
Pandas reading csv as string type
<p>I have a data frame with alpha-numeric keys which I want to save as a csv and read back later. For various reasons I need to explicitly read this key column as a string format, I have keys which are strictly numeric or even worse, things like: 1234E5 which Pandas interprets as a float. This obviously makes the key c...
<p><em>Update: this has <a href="https://github.com/pydata/pandas/issues/3795" rel="noreferrer">been fixed</a>: from 0.11.1 you passing <code>str</code>/<code>np.str</code> will be equivalent to using <code>object</code>.</em></p> <p>Use the object dtype:</p> <pre><code>In [11]: pd.read_csv('a', dtype=object, index_c...
python|pandas|casting|type-conversion|dtype
63
369,630
16,923,281
Writing a pandas DataFrame to CSV file
<p>I have a dataframe in pandas which I would like to write to a CSV file.</p> <p>I am doing this using:</p> <pre><code>df.to_csv('out.csv') </code></pre> <p>And getting the following error:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128) </cod...
<p>To delimit by a tab you can use the <code>sep</code> argument of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html"><code>to_csv</code></a>:</p> <pre><code>df.to_csv(file_name, sep='\t') </code></pre> <p>To use a specific encoding (e.g. 'utf-8') use the <code>encoding</cod...
python|csv|pandas|dataframe
1,356
369,631
19,161,512
Numpy extract submatrix
<p>I'm pretty new in <code>numpy</code> and I am having a hard time understanding how to extract from a <code>np.array</code> a sub matrix with defined columns and rows:</p> <pre><code>Y = np.arange(16).reshape(4,4) </code></pre> <p>If I want to extract columns/rows 0 and 3, I should have:</p> <pre><code>[[0 3] [12...
<p>Give <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html" rel="noreferrer"><code>np.ix_</code></a> a try:</p> <pre><code>Y[np.ix_([0,3],[0,3])] </code></pre> <p>This returns your desired result:</p> <pre><code>In [25]: Y = np.arange(16).reshape(4,4) In [26]: Y[np.ix_([0,3],[0,3])] Out[26]...
python|numpy
107
369,632
18,876,022
How to format IPython html display of Pandas dataframe?
<p>How can I format IPython html display of pandas dataframes so that</p> <ol> <li>numbers are right justified</li> <li>numbers have commas as thousands separator</li> <li>large floats have no decimal places</li> </ol> <p>I understand that <code>numpy</code> has the facility of <code>set_printoptions</code> where I c...
<p>HTML receives a custom string of html data. Nobody forbids you to pass in a style tag with the custom CSS style for the <code>.dataframe</code> class (which the <code>to_html</code> method adds to the table).</p> <p>So the simplest solution would be to just add a style and concatenate it with the output of the <cod...
python|html|pandas|ipython
26
369,633
18,774,388
re-import aliased/shadowed python built-in methods
<p>If one has run </p> <pre><code>from numpy import * </code></pre> <p>then the built-in <code>all</code>, and several other functions, are shadowed by <code>numpy</code> functions with the same names. </p> <p>The most common case where this happens (without people fully realizing it) is when starting <code>ipython...
<p>you can just do</p> <pre><code>all = __builtins__.all </code></pre> <p>The statement <code>from numpy import *</code> basically do two separate things</p> <ol> <li>imports the module <code>numpy</code></li> <li>copies all the exported names from the module to the current module</li> </ol> <p>by re-assigning the ...
python|numpy
12
369,634
19,178,762
Python using lambda to apply pd.DataFrame instead for nested loop is it possible?
<p>I'm trying to avoid nested loop in python here by using lambda apply to create a new column using this argument below : </p> <pre><code>from pandas import * import pandas as pd df = pd.DataFrame((np.random.rand(100, 4)*100), columns=list('ABCD')) df['C'] = df.apply(lambda A,B: A+B) </code></pre> <p>TypeError:...
<p>Do you want to add column <code>A</code> and column <code>B</code> and store the result in <code>C</code>? Then you can have it simpler:</p> <pre><code>df.C = df.A + df.B </code></pre> <hr> <p>As @EdChum points out in the comment, the argument to the function in <code>apply</code> is a series, by default on axis ...
python|performance|nested|pandas
11
369,635
18,795,489
How do I construct a tuple in Cython?
<p>I am new to cython and I am just looking for an easy way of casting a numpy array to a tuple that can then be added to and/or looked up in a dictionary.</p> <p>In CPython, I can use PyTuple_New and iterate over the values of the array (adding each one to the tuple as though I were appending them to a list). </p> <...
<p>Cython is a superset of Python so any valid Python code is a valid Cython code. In this case, if you have a NumPy array, just passing it to a <code>tuple</code> class constructor should work just fine (just as you would do in regular Python).</p> <pre><code>a = np.array([1, 2, 3]) t = tuple(a) </code></pre> <p>Cyt...
python|arrays|numpy|cython|cpython
3
369,636
18,986,822
How to use crosstab/pivot with multi dimensions
<p>I tried using pivot tables to have more than one values in the 'values' field for the pivot_table function but it doesnt work, so im trying to see if i can do it with crosstabs. Here is my code</p> <pre><code>table=pandas.pivot_table(xl2, values='Applications', rows='Sub-Product',cols='Application Date',aggfunc=n...
<p>Looks like you're really close to where you want to be. <code>table.stack(0)</code> will move the first level of the column index to the row index.</p> <pre><code>In [1]: import pandas as pd In [2]: from StringIO import StringIO In [3]: df = pd.read_csv(StringIO("""\ ...: Application-Date Sub-Product A...
python|csv|pandas|pivot-table|crosstab
2
369,637
22,169,783
Find list of values available in pandas dataframe with binary values
<p>I have a <code>DataFrame</code> like following:</p> <pre><code> session p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 0 1 1 0 0 1 1 0 1 0 1 0 1 2 1 0 0 0 1 0 1 0 1 1 2 3 1 0 1 0 1 0 0 0 1 0 3 4 0 1 1 1 0 1 0 1 ...
<p>Assuming by "all list values are included", you mean that the corresponding columns are 1:</p> <pre><code>&gt;&gt;&gt; df.session[df[listvals].sum(axis=1) == len(listvals)] 0 1 1 2 2 3 4 5 7 8 Name: session, dtype: int64 &gt;&gt;&gt; df.session[df[listvals].sum(axis=1) &gt;= 2] 0 1 1 2 2 ...
python|pandas|dataframe
2
369,638
22,340,999
Converting dates from HDF5 dataset to numpy array
<p>I have a HDF5 dataset having dates matrix which I'm loading in my Python script and want to use it as numpy array -</p> <pre><code>&gt;&gt;&gt; mat = h5py.File('xyz.mat') &gt;&gt;&gt; dates = mat['dates'] &gt;&gt;&gt; dates &lt;HDF5 dataset "dates": shape (11, 285), type "&lt;u2"&gt; </code></pre> <p>If I try to c...
<p>It seems that your dates are stored… <em>strangely</em>. Your dataset is a 11 x 285 matrix of 16 bit unsigned ints. (It smells like it was exported from Matlab).</p> <p>Basically the problem is that Numpy tries (and fails) to convert <em>each</em> element of the matrix (a.k.a. each individual character of the dates...
python|numpy|hdf5
1
369,639
22,180,981
Filtering content by whether field contains a value
<p>In my original code that processes csv files I was skipping the data from rows that contained a certain value:</p> <pre><code>df = df[df["ORGANIZATION"]!="Org1"] </code></pre> <p>Now I need to skip data that <strong>contains</strong> that value. The following determines if it contains the value...</p> <pre><code>...
<p>You can use <code>~</code> to negate your boolean Series:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({"ORGANIZATION": ["Org1", "Org1 - Dave", "Org1 - Lisa", "Org2 - Bob", "Org3 - Sally"]}) &gt;&gt;&gt; df ORGANIZATION 0 Org1 1 Org1 - Dave 2 Org1 - Lisa 3 Org2 - Bob 4 Org3 - Sally [5 rows x 1...
python|csv|pandas|filtering
3
369,640
22,015,363
How to get the index value in pandas MultiIndex data frame?
<pre><code>df = pd.DataFrame({'a':[2,3,5], 'b':[1,2,3], 'c':[12,13,14]}) df.set_index(['a','b'], inplace=True) display(df) s = df.iloc[1] # How to get 'a' and 'b' value from s? </code></pre> <p>It is so annoying that ones columns become indices we cannot simply use df['colname'] to fetch values.</p> <p>Does it encou...
<p>When I print s I get </p> <pre><code>In [8]: s = df.iloc[1] In [9]: s Out[9]: c 13 Name: (3, 2), dtype: int64 </code></pre> <p>which has a and b in the name part, which you can access with:</p> <pre><code>s.name </code></pre> <p>Something else that you can do is</p> <pre><code>df.index.values </code></pre...
python|pandas
18
369,641
21,978,584
Replace elements in 2nd column of array with new value from 2nd column of smaller array when 1st column matches
<p>I have two 2D arrays, e.g., </p> <pre><code>A = [[1,0],[2,0],[3,0],[4,0]] B = [[2,0.3],[4,0.1]] </code></pre> <p>Although the arrays are much larger, with A about 10x the size of B, and about 100,000 rows in A. I want to replace rows in A with the row in B whenever the 1st elements of the rows match, and leave th...
<p>We will have to iterate through the entire array A once in any case, since we are transforming it. What we could speed up though, is the look-up if a particular first element of A exists in B. To that end, it would be efficient to create a dictionary out of B. That way, lookup will be constant time. I am assuming he...
python|numpy
1
369,642
22,231,347
Array slice maximum that depends on the index of the previous axis
<p>So I have a large 2D array, coming from a tiff image, in which I want to calculate the center of mass. To do that, I am using the indices of the image (as coordinates) and the average function:</p> <pre><code>from PIL import Image from numpy import * Im = Image.open("32bit_grayscale.tif") imArr = array(Im, dtyp...
<p>What happens if you set <code>imArr[i,j]=0</code> for all points on one side or the other of your line? This is the simplest masking approach. </p> <pre><code>I = indx[0,...]*slope + indx[1,...]&gt;=M imArr1 = imArr.copy() imArr1[I]=0 print np.average(indx[0,...],weights=imArr1) print np.average(indx[1,...],weigh...
python|arrays|numpy|slice
1
369,643
22,214,985
MultiIndex Group By in Pandas Data Frame
<p>I have a data set that contains countries and statistics on economic indicators by year, organized like so: </p> <pre><code>Country Metric 2011 2012 2013 2014 USA GDP 7 4 0 2 USA Pop. 2 3 0 3 GB GDP 8 7 ...
<p>In this case, you don't actually need a <code>groupby</code>. You also don't have a <code>MultiIndex</code>. You can make one like this:</p> <pre><code>import pandas from io import StringIO datastring = StringIO("""\ Country Metric 2011 2012 2013 2014 USA GDP 7 4 0 2...
python|pandas|dataset|dataframe
31
369,644
22,077,328
Vectorized format function for Pandas series
<p>Say I start with a <code>Series</code> of unformatted phone numbers (as strings), and I would like to format them as (XXX) YYY-ZZZZ. </p> <p>I can get the sub-components of my input using regular expressions and <code>str.match</code> or <code>str.extract</code>. And I can perform the formatting using the result ...
<p>You can do this directly with <code>Series.str.replace()</code>:</p> <pre><code>In [47]: s = pandas.Series(["1234567890", "5552348866", "13434"]) In [49]: s Out[49]: 0 1234567890 1 5552348866 2 13434 dtype: object In [50]: s.str.replace(r"(\d{3})(\d{3})(\d{4})", r"(\1) \2-\3") Out[50]: 0 (123) ...
python|string|formatting|pandas
2
369,645
22,412,508
Python: Export a matrix in csv
<p>I have a 2D matrix with 13 rows and 13 columns (with headers except for the first column) named <code>correl</code> in Python. This <code>correl</code> matrix was generated from a <code>DataFrame</code> and I wish to populate a matrix <code>correlation</code> with multiple <code>correl</code>. For example: </p> <pr...
<p>It looks like <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.corr.html" rel="nofollow noreferrer"><code>correlation</code> is a DataFrame too</a>, so you can simply use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow noreferr...
python|pandas
7
369,646
22,249,620
Code optimisation cubic interpolation
<p>I've been reading for quite some time Stack questions and answers and find a lot of very useful optimisation. I'm kind of facing a bottleneck on the optimisation of the following code which is "just" for converting a cartesian map into a polar map. But with the particularity of increasing the density of angular poin...
<p>You can probably vectorize the for loops into something like:</p> <pre><code>nX,nY=data.shape for i in np.arange(-1,3): for j in np.arange(-1,3): condx = np.logical_and((ix + i) &lt; nX, (ix + i) &gt;=0) condx = np.logical_and((iy + j) &lt; nY, (iy + j) &gt;=0) cub = cubic(i-dx) * cubic(...
python|optimization|numpy
1
369,647
22,174,958
Sort a 2D numpy array by the median value of the rows
<p>If I have a 2D list in python, I can easily sort by the median value of each sublist like this:</p> <pre><code>import numpy as np a = [[1,2,3],[1,1,1],[3,3,3,]] a.sort(key=lambda x: np.median(x)) print a </code></pre> <p>Yielding...</p> <pre><code>[[1, 1, 1], [1, 2, 3], [3, 3, 3]] </code></pre> <p>Is there a way...
<p>I guess the numpythonic way would be to use fancy-indexing:</p> <pre><code>&gt;&gt;&gt; a = np.array([[1,2,3],[1,1,1],[3,3,3,]]) &gt;&gt;&gt; a[np.median(a,axis=1).argsort()] array([[1, 1, 1], [1, 2, 3], [3, 3, 3]]) </code></pre>
python|numpy
4
369,648
21,976,675
an efficient equivalent to numpy isnan or where that looks over a window of N values
<p>I have an operation I want to do in python on a 1D array with a finite but fairly large explicit stencil -- in other words, the output at [n] depends on the input from [t-N] to [t+N].</p> <p>My processing code doesn't deal graciously with nan values and an expedient way for me to handle the situation is to substitu...
<p>You could use <code>np.where</code> to find the index of the NaNs, then use <code>np.add.outer</code> to include all the neighboring indices:</p> <pre><code>import numpy as np x = np.arange(100, dtype='float') x[x % 13 == 0] = np.nan print(x) # [ nan 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. ...
python|numpy|functional-programming
1
369,649
22,439,929
Python equivalent for R's 'zoo' package
<p>Are there Python or perhaps <code>pandas</code> equivalents to R's <code>zoo</code> package?</p> <p>In particular, I'm looking for equivalents to:</p> <pre><code>dataLag2 = lag(zoo(train$data), -2, na.pad=TRUE) train$dataLag2 = coredata(dataLag2) </code></pre> <p>Are there equivalents on Python that would produce...
<p>Pandas has the TimeSeries class which implements all the functionalities available in zoo to manipulate and homogenize irregular time series data:</p> <p>if 'ts' is a TimeSeries object containing irregular hourly timestamped data I'd first create an homogeneous time series doing:</p> <pre><code>ts.resample('H').in...
python|r|pandas|time-series|zoo
2
369,650
22,346,552
Map string values in a Pandas Dataframe with integers
<p>In Pandas <code>DataFrame</code> how to map strings in one column with integers. I have around 500 strings in the <code>DataFrame</code> and need to replace them with integers starting with '1'. </p> <p>Sample <code>DataFrame</code>. </p> <pre><code> Request count 547 ...
<p>So what you could do is construct a temporary dataframe and merge this back to your existing dataframe:</p> <pre><code>temp_df = pd.DataFrame({'Request': df.Request.unique(), 'Request_id':range(len(df.Request.unique()))}) </code></pre> <p>Now merge this back to your original dataframe</p> <pre><code>df = df.merge...
python|pandas|dataframe
10
369,651
18,111,444
Extract non-main diagonal from scipy sparse matrix?
<p>Say that I have a sparse matrix in scipy.sparse format. How can I extract a diagonal other than than the main diagonal? For a numpy array, you can use numpy.diag. Is there a scipy sparse equivalent?</p> <p>For example:</p> <pre><code>from scipy import sparse A = sparse.diags(ones(5),1) </code></pre> <p>How wou...
<p>When the sparse array is in <code>dia</code> format, the data along the diagonals is recorded in the <code>offsets</code> and <code>data</code> attributes:</p> <pre><code>import scipy.sparse as sparse import numpy as np def make_sparse_array(): A = np.arange(ncol*nrow).reshape(nrow, ncol) row, col = zip(*n...
python|numpy|scipy|sparse-matrix
2
369,652
18,218,355
SciPy optimization with grouped bounds
<p>I am trying to perform a portfolio optimization that returns the weights which maximize my utility function. I can do this portion just fine including the constraint that weights sum to one and that the weights also give me a target risk. I have also included bounds for [0 &lt;= weights &lt;= 1]. This code looks as ...
<p>Not totally sure I understand, but I think you can add the following as another constraint:</p> <pre><code>def w_opt(W): def filterer(x): v = x.range.values tp = v[0] lower, upper = tp return lower &lt;= x[column_name].sum() &lt;= upper return not W.groupby(level=0, axis=0).f...
python|optimization|pandas|scipy|finance
3
369,653
18,062,135
Combining two Series into a DataFrame in pandas
<p>I have two Series <code>s1</code> and <code>s2</code> with the same (non-consecutive) indices. How do I combine <code>s1</code> and <code>s2</code> to being two columns in a DataFrame and keep one of the indices as a third column?</p>
<p>I think <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tools.merge.concat.html"><code>concat</code></a> is a nice way to do this. If they are present it uses the name attributes of the Series as the columns (otherwise it simply numbers them):</p> <pre><code>In [1]: s1 = pd.Series([1, 2], inde...
python|pandas|series|dataframe
535
369,654
4,543,201
Trouble Installing Numpy and Scipy
<p>I'm running into difficulty what I run <code>python setup.py install</code> in the numpy directory. It seems to be running alright, until it gets to a folder where permission is denied. The error it throws is <code>copying build/scripts.macosx-10.6-universal-2.6/f2py -&gt; /usr/local/bin error: /usr/local/bin/f2py...
<p>If you type in <code>sudo easy_install numpy</code> that solves the same problem that I have encountered. This may have occurred due to using an Apple Mac which have already installed <code>easy_install</code> in your <code>/usr/bin</code>. Typing <code>sudo easy_install numpy</code> if the package tries installin...
numpy
3
369,655
4,150,171
How to create a density plot in matplotlib?
<p>In R I can create the desired output by doing: </p> <pre><code>data = c(rep(1.5, 7), rep(2.5, 2), rep(3.5, 8), rep(4.5, 3), rep(5.5, 1), rep(6.5, 8)) plot(density(data, bw=0.5)) </code></pre> <p><img src="https://i.stack.imgur.com/YFEin.png" alt="Density plot in R"></p> <p>In python (with matplotlib) the...
<p>Five years later, when I Google "how to create a kernel density plot using python", this thread still shows up at the top! </p> <p>Today, a much easier way to do this is to use <a href="http://stanford.edu/~mwaskom/software/seaborn/">seaborn</a>, a package that provides many convenient plotting functions and good s...
python|r|numpy|matplotlib|scipy
185
369,656
8,554,673
How to implement "where" (numpy.where(...) )?
<p>I'm a functional programming newbie. I'd like to know how to implement numpy.where() in python, scala or haskell. A good explanation would be helpful to me.</p>
<p>In Haskell, doing it for n-dimensional lists, as the NumPy equivalent supports, requires a fairly advanced typeclass construction, but the 1-dimensional case is easy:</p> <pre class="lang-hs prettyprint-override"><code>select :: [Bool] -&gt; [a] -&gt; [a] -&gt; [a] select [] [] [] = [] select (True:bs) (x:xs) (_:ys...
python|scala|haskell|functional-programming|numpy
6
369,657
8,669,261
Indices of k-minimum values along an axis of a numpy array
<p>Is there a way to return the indices of k-minimum values along an axis of a numpy array without using loops?</p>
<pre><code>import numpy as np x = np.array([[5, 2, 3],[1, 9, 2]]) # example data k = 2 # return the indices of the 2 smallest values np.argsort(x, axis=1)[:,0:k] # by row array([[1, 2], [0, 2]]) </code></pre>
python|arrays|numpy|indices|minim
7
369,658
8,802,916
Using multi-threading to process an image faster on python?
<p>On a Python + Python Image Library script, there's a function called processPixel(image,pos) that calculates a mathematical index in function of an image and a position on it. This index is computed for each pixel using a simple for loop:</p> <pre><code>for x in range(image.size[0)): for y in range(image.size[1...
<p>You cannot speed it up using threading due to the <a href="http://docs.python.org/c-api/init.html#threads" rel="nofollow">Global Interpreter Lock</a>. Certain internal state of the Python interpreter is protected by that lock, which prevents different threads that need to modify that state from running concurrently....
python|image-processing|numpy|gpu|python-imaging-library
7
369,659
55,261,785
NVidia drivers stopped working on AWS EC2 instance with Ubuntu 16.04 and Tesla K80 GPU
<p>I've been using an AWS EC2 instance, with a Tesla K80 GPU, for a while to run TensorFlow code. I have CUDA 9.0 and cuDNN 7.1.4 installed, and I'm using TF 1.12, all of this on Ubuntu 16.04</p> <p>Everything worked well up to yesterday, but today it seems that the NVidia drivers have stopped running for some reason ...
<p>I fixed this problem by updating to the latest Nvidia drivers. Use:</p> <pre><code>nvcc --version </code></pre> <p>to get the cuda toolkit version number. For 9.0 the latest drivers are 384.183, and 410.104 for CUDA 10.0. </p> <p>Then run:</p> <pre><code> wget http://us.download.nvidia.com/tesla/384.183/NVIDIA-L...
amazon-web-services|tensorflow|amazon-ec2|gpu|nvidia
12
369,660
55,306,920
Make a plot by occurence of a col by hour of a second col
<p>I have this df :</p> <p>and i would like to make a graph by half hour of how many row i have by half hour without including the day. </p> <p>Just a graph with number of occurence by half hour not including the day. </p> <pre><code>3272 8711600410367 2019-03-11T20:23:45.415Z d7ec8e9c5b5df11df8ec7ee1305529...
<p>One way you could do this is split up coding for hours and half-hours, and then bring them together. To illustrate, I extended your data example a bit:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Created':['2019-03-11T20:23:45.415Z', '2019-03-11T20:23:51.072Z', '2019-03-11T20:33:03.072Z', '2019-03-11T21:...
pandas
1
369,661
55,231,351
New to tensorflow
<p>I want to learn tensorflow. I'm sorry for the questions but I learn In my own way. First, is there a list of definitions on terminology? Next, at my workplace we deal with a lot of flat files from different ecommerce sites. I want to build a bot that will do one of the following choices. I am not sure what is the be...
<p>I am taking this <a href="https://www.coursera.org/learn/introduction-tensorflow" rel="nofollow noreferrer">course</a>. I have taken a bunch of ml and nn courses that use tensorflow. This one is the easiest. It goes over using tensorflow and keras in a lot of detail using some mnist data sets.</p> <p>There are a lo...
tensorflow|machine-learning|google-colaboratory
0
369,662
55,317,559
how to improve neural network prediction, classification
<p>I am trying to learn some neural networks for fun. I decided to try to classify some pokemon legendary cards, from a data set from kaggle. I read up on documentations and followed machine learning mastery guides, while reading up on medium to try to understand the process. </p> <p>My problem/ question : i tried pr...
<h3>Problem:</h3> <p>The problem is that, as you stated, your dataset is heavily <strong>imbalanced</strong>. This means that you have a lot more training examples for class 0 than class 1. This causes the network, during training, to develop a heavy bias towards predicting class 0.</p> <h3>Evaluation:</h3> <p>The f...
python|tensorflow|keras|neural-network
1
369,663
55,172,965
Python delete all rows between the first view and the first click?
<p>So I've been trying an failing and am hoping for some help. What I want to do is</p> <ul> <li>Group by users and sort by time stamp (which is the way the dataframe belowis set up)</li> <li>Now I want to take every view prior to the first click, and group it into a single event with the earliest timestamp <ul> <li>...
<p>Follow below steps </p> <pre><code>s1=df.activity.eq('view').groupby(df['id']).transform('idxmax') # using idxmax find the first view s2=df.activity.eq('click').groupby(df['id']).transform('idxmax') # same logic here find the index of first click out=df.loc[(df.index&lt;=s1)|(df.index&gt;=s2)].copy() # filter t...
python|pandas|dataframe|timestamp
1
369,664
55,234,638
Dataframe shift moving data into random columns?
<p>I'm using code to shift time series data that looks somewhat similar to this:</p> <pre><code>Year Player PTSN AVGN 2018 Aaron Donald 280.60 17.538 2018 J.J. Watt 259.80 16.238 2018 Danielle Hunter 237.60 14.850 2017 Aaron Donald 181.0 ...
<p>I suggest use:</p> <pre><code>#first aggregate for unique MultiIndex res = df.groupby(['Player', 'Year']).sum() #MultiIndex idx = pd.MultiIndex.from_product(res.index.levels, names=['Player', 'Year']) #aded new missing years res = res.reindex(idx).sort_index() #shift all columns,...
python|pandas
2
369,665
55,142,231
Pandas Data Frame in Python. Proportions and Transpose
<p>I have the following data frame in Pandas. The idea is to generate an additional data frame IDs based on the proportion of the variable TYPE, transposing it into columns. Any help is appreciated!</p> <pre><code>d = {'ID': [1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2], 'TYPE': ['A','A','A','B','B','B','B','C','C','C','A','A...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.SeriesGroupBy.value_counts.html" rel="nofollow noreferrer"><code>SeriesGroupBy.value_counts</code></a> with parameter <code>normalize=True</code> and reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/ap...
python|pandas|dataframe
1
369,666
55,170,175
Need very different learning rate for manual updates vs. using model
<p>I am currently just trying to write some pedagogical material, in which I borrow from some common examples that have been reworked numerous times on the web.</p> <p>I have a simple bit of code where I manually create tensors for layers, and update them within a loop. E.g.:</p> <pre><code>w1 = torch.randn(D_in, H,...
<p>The crucial difference is <strong>the initialization</strong> of the weights. The weight matrix in a <code>nn.Linear</code> <a href="https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/linear.py#L58-L63" rel="nofollow noreferrer">is initialized smart</a>. I'm pretty sure that if you construct both the mo...
pytorch
1
369,667
55,396,415
Separate a Pandas dataframe based on contents of time column
<p>I have a pandas dataframe of which one column is datetime. The data spans over a month and is sorted on time in ascending order. Now I want to separate out weekend and weekday data, this is my code :</p> <pre><code>data = pd.read_csv('Data.csv') data.head() Time A B C 0...
<p>Use:</p> <pre><code>rng = pd.date_range('2019-03-29 11:00:00', periods=30, freq='3H') data = pd.DataFrame({'Time': rng, 'a': range(len(rng))}) print (data) Time a 0 2019-03-29 11:00:00 0 1 2019-03-29 14:00:00 1 2 2019-03-29 17:00:00 2 3 2019-03-29 20:00:00 3 4 2019-03-29 23:00:00 ...
python|python-3.x|pandas|datetime
1
369,668
55,225,174
Simple Data recall RNN in Pytorch
<p>I am learning Pytorch and am trying to make a network that can remember previous inputs. I have tried 2 different input/output structures(see below) but haven't gotten anything to work the way I would like. </p> <p>input 1:</p> <p>in:[4,2,7,8]</p> <p>output [[0,0,4],[0,4,2],[4,2,7],[2,7,8]]</p> <p>code:</p> <pr...
<p>The problem that your network presents, it's the fact that your input is of shape 1:</p> <pre><code>for i in range(0, data_amount, batch_size): inputs = data[i:i + batch_size] labels = labs[i:i + batch_size] print(inputs.shape,labels.shape) &gt;&gt;&gt;torch.Size([1]) torch.S...
pytorch|recurrent-neural-network
0
369,669
55,357,561
How do I unnest an array 2x2 within cells of a column in a Dataframe?
<p>I have a DataFrame that in one its column there are 2x2 np.arrays within each cell. I'm trying to extract these arrays to merge with the original Dataframe.</p> <p>Suppose I have the following df:</p> <pre><code>df=pd.DataFrame({'A':[101, 202],'B':[ [[1,2], [3,4]] ,[[5,6], [7,8]] ] }) </code></pre> <p>and I need ...
<p>Also,</p> <pre><code>df =df.set_index('A').B.apply(pd.Series).stack().reset_index().rename(columns={0:'B'}) df1 =pd.DataFrame(df.B.values.tolist()).add_prefix('B_') pd.concat([df['A'], df1], axis = 1) </code></pre>
python|pandas
1
369,670
55,503,006
1064, “You have an error in your SQL syntax” inserting in MySql
<p>I have the following error on my IDE:</p> <blockquote> <p>MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2102@lionstate.edu', '88zlsj5j', 'Kristopher O'Connell', '21', 'F', 'CMPSC'...
<p>Try taking the <code>'</code> off from all the variables inside the values section.</p> <p>Such as <code>values (%s, %s, %s .....)</code> instead of <code>values ('%s', '%s', ...)</code></p>
python|mysql|sql|pandas|pycharm
0
369,671
55,433,251
How can I select n rows preceding an index row in a DataFrame?
<p>I have a <code>DataFrame</code> and am trying to select a row (given a particular index) and the <code>n</code> rows preceding it.</p> <p>I've tried something like:</p> <pre><code>last_10 = self.market_data.iloc[index:-10] </code></pre> <p>But this appears to give everything from the <code>index</code> up until t...
<p>Use this:</p> <pre><code>n = 10 last_10 = self.market_data.iloc[index-n:index+1] </code></pre> <p>When slicing arrays, Python returns everything up until the last index, so you need to add one to include it.</p>
python|pandas|dataframe
2
369,672
55,269,547
CNN OCR Machine readable zone
<p>I am training a Convolutional Neural Network to recognize MRZ(Machine Readable Zone) characters, on a smartphone. I want to know if in order to improve accuracy I should train it with multiple fonts, even if MRZ only uses OCR-B. Also, the model does not perform on device with the same level of accuracy as in the pyt...
<p>If MRZ use only one font, then you should use only this font to train your CNN.<br> In order to improve results, you should preprocess the image before passing it to the CNN, for example, at first identify text zones in an image and then pass them through CNN.<br> <br> The accuracy of the model can change from a dev...
python|tensorflow|keras|conv-neural-network
1
369,673
55,443,173
Trying to matching a column of names in one df where they could be an exact or partial match of another df 'scolumn?
<p><strong>Goal</strong>: If the name in df2 in row i is a sub-string or an exact match of a name in df1 in some row N and the state and district columns of row N in df1 are a match to the respective state and district columns of df2 row i, combine.</p> <p><strong>Break down of data frame inputs:</strong></p> <ol> <l...
<p>We can use <code>difflib</code> for this to create an artificial <code>key column</code> to merge on. We call this column <code>name</code>, like the one in <code>df2</code>:</p> <pre><code>import difflib df1['Name'] = df1['CandidateName'].apply(lambda x: difflib.get_close_matches(x, df2['Name'])[0]) df_merge = df1...
python|regex|pandas|python-2.7
0
369,674
55,334,026
how to save image of loaded keras model as png/jpg?
<p>I have trained a keras model and saved it to later make predictions. However, I loaded the saved model using: </p> <pre><code>from keras.models import load_model #Restore saved keras model restored_keras_model = load_model("C:/*******/saved_model.hdf5") </code></pre> <p>Now I would like to save an image of...
<p>Yes, in addition to doing a restored_keras_model.summary(), you can save the model architecture as a png file using the plot_model API.</p> <pre><code>from keras.utils import plot_model plot_model(restored_keras_model, to_file='model.png') </code></pre> <p><a href="https://keras.io/visualization/#model-visualizati...
python-3.x|tensorflow|keras
8
369,675
55,466,634
Why the input of `keras.experimental.SequenceFeature` must be a `SpareTensor`?
<p>I'm trying to migrate my seq2seq model to TensorFlow 2.0. However, I have an issue in the feature column input layer. </p> <p>In TensorFlow 2.0, they provide an input layer for sequence data, <code>keras.experimental.SequenceFeatures</code>, but I HAVE TO PUT a SpareTensor.</p> <p>Actually, all sequence data is no...
<p>They use <code>SpareTensor</code> to represent sequence data which have an arbitrary sequence length. However, input sequence data must have the same maximum sequence length.</p>
tensorflow2.0
0
369,676
55,214,862
Pandas: Concatenating two Series to Pandas DataFrame
<p>How can I concatenate two Series and create one DataFrame ? For example, I have series like:</p> <pre><code>a=pd.Series([1,2,3]) b=pd.Series([4,5,6]) </code></pre> <p>And, I want to get a data frame like:</p> <pre><code>pd.DataFrame([[1,4], [2,5], [3,6]]) </code></pre>
<p>Shortest would be:</p> <pre><code>pd.DataFrame([a,b]).T </code></pre> <p>Or:</p> <pre><code>pd.DataFrame(zip(a,b)) 0 1 0 1 4 1 2 5 2 3 6 </code></pre>
python|pandas
4
369,677
55,350,988
How to calculate sums across matrix diagonals in Tensorflow?
<p>Say, I have matrix <code>4x4</code> like:</p> <pre><code>1 2 3 4 5 6 7 8 4 3 2 1 8 7 6 5` </code></pre> <p>I want to get matrix <code>2*4-1</code> with elements like:</p> <pre><code>8 4+7 5+3+6 1+6+2+5 2+7+1 3+8 4 </code></pre> <p>How can I do that in Tensorflow? With tensors, of course - I have tensor with shap...
<p>You can use <code>tf.py_func</code> to wrap a <code>numpy</code> function.</p> <pre><code>import tensorflow as tf import numpy as np def np_all_trace_sum(a): n = a.shape[-1] all_trace_sum = [a.trace(i,axis1=-1,axis2=-2) for i in range(n-1,-n,-1)] # shape = (2*n-1,a,b,c,..,l) return np.moveaxis(all_trac...
python|tensorflow
1
369,678
55,235,099
Iterating numpy array to find max value within subarray leaving the row index
<p>I wanted to find the max of 2D array along the axis=0 and I don't want to include the value at the row-index. I'm not happy with this solution because I need to run this on a million of rows and I don't want to use for-loop here. I tried <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html...
<p>This should do the trick:</p> <pre><code>a = np.array([[1, 0.5, 0.3, 0, 0.2], [0, 1, 0.2, 0.8, 0], [0, 1, 1, 0.3, 0], [0, 0, 0, 1, 0]]) # Create an array of ones the same size as a b = np.ones_like(a) # Fill the diagonal of b with NaN np....
python|arrays|numpy|max
3
369,679
55,147,039
Anaconda tensorflow packages incomplete? (just few kilobytes filesize)
<p>I am following the instruction at <a href="https://anaconda.org/anaconda/tensorflow-gpu" rel="nofollow noreferrer">https://anaconda.org/anaconda/tensorflow-gpu</a> to install "tensorflow-gpu" (currently 1.12.0 for linux64) by running</p> <pre><code>conda install -c anaconda tensorflow-gpu </code></pre> <p>in the ...
<p>Faced the same issue. You can get tensorflow working by installing it using pip instead of conda using:</p> <pre><code>pip install --upgrade tensorflow </code></pre>
python|linux|tensorflow|anaconda
0
369,680
55,491,686
Why are the parameters of my encoder and decoder not symmetric in my autoencoder?
<p>I'm trying to implement an autoencoder in Tensorflow using the Keras API. My code is inspired by examples on the Keras website: <a href="https://blog.keras.io/building-autoencoders-in-keras.html" rel="nofollow noreferrer">https://blog.keras.io/building-autoencoders-in-keras.html</a></p> <p>The goal is to be able to...
<p>As you already thought the problem here are the biases. If you take for example the weights between Dense 12 and Dense 13 you have <code>1024*8 = 8192</code> normal weights + <code>8</code> biases (<code>8200</code> in total).</p> <p>If you take the weights between Dense 17 and 18 you'll have <code>8*1024 = 8192</c...
python|tensorflow|keras|autoencoder
0
369,681
55,267,619
Tf Summary not giving the histograms but saves the session graph (pre-trained model)
<p>I am carrying out an analysis to visualize the distribution of weights for a pre-trained model available online. Its a Resnet18 model trained on CIFAR10. </p> <p>I have the following code to restore the model from <code>meta</code> and <code>ckpt</code> and then I try to create a histogram of all the <code>weights<...
<p>It's not enough to pass the merged summary node to <code>sess.run</code>. You need to take that evaluated result and pass it to the <code>add_summary</code> method of your <code>FileWriter</code> instance.</p> <pre><code># evaluate the merged summary node in the graph output, summ = sess.run([softmax, tf_fp_summari...
python|tensorflow|histogram|tensorboard|summary
1
369,682
55,577,773
Multiple fields using Pandas and Quandl
<p>I am using Quandl to download daily NAV prices for a specific set of Mutual Fund schemes. However it returns a data object instead of returning the specific value</p> <pre><code>import quandl import pandas as pd quandl.ApiConfig.api_key = &lt;Quandl Key&gt; list2 = [102505, 129221, 102142, 103197, 100614, 100474,...
<p>By default, quandl Time-series API returns you a dataframe with date as index, even if there is only one row. </p> <p>If you only need the value of first row, you can use <code>iloc</code>:</p> <pre class="lang-py prettyprint-override"><code>if not nav.empty: print (nav.iloc[0]) </code></pre> <p>or just plain...
python-3.x|pandas|quandl
1
369,683
55,331,148
Compare multiple columns in a dataframe and generate a similarity matrix
<p>Suppose that I have a dataframe consisting of four columns <em>Col1, Col2, Col3 and Col4</em>. Each column has 100 entries (assume timestamp), thus the overall shape of the dataframe is (100,4). For a given particular timestamp, these columns have similar values, thus making their overall variation with time very s...
<pre><code>import pandas as pd import numpy as np Fs = 100 f = 5 sample = 100 x = np.arange(sample) y = np.sin(2 * np.pi * f * x / Fs) y1 = np.sin(3 * np.pi * f * x / Fs) y2 = np.sin(4 * np.pi * f * x / Fs) y3 = np.sin(5 * np.pi * f * x / Fs) data=pd.DataFrame({"c":y,"c1":y1,"c2":y2,"c3":y3}) data.cov() </code></pre> ...
python|pandas|dataframe
1
369,684
55,147,511
Invalid combination of arguments - eq()
<p>I'm using a code shared <a href="https://gist.github.com/johnolafenwa/96b3322aabb61d4d36fd870a77f02aa3" rel="nofollow noreferrer">here</a> to test a CNN image classifier. When I call the test function, I got this error on <a href="https://gist.github.com/johnolafenwa/96b3322aabb61d4d36fd870a77f02aa3#file-simplenet-p...
<p>Why do you have <code>.numpy()</code> here <code>prediction = prediction.cpu().numpy()</code>? That way you convert PyTorch tensor to NumPy array, making it incompatible type to compare with <code>labels.data</code>.</p> <p>Removing <code>.numpy()</code> part should fix the issue.</p>
python|numpy|image-processing|machine-learning|pytorch
1
369,685
55,281,506
Python: How to pad with zeros?
<p>Assuming we have a dataframe as below:</p> <pre><code>df = pd.DataFrame({ 'Col1' : ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c'], 'col2' : ['0.5', '0.78', '0.78', '0.4', '2', '9', '2', '7',] }) </code></pre> <p>I counted the number of rows for all the unique values in <code>col1</code>. Like <code>a</co...
<p>You can create counter by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a>, create <code>MultiIndex</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.r...
python|pandas|numpy|zero-padding
3
369,686
55,286,915
Convert a dictionary which values are different-length lists into a dataframe
<p>I have a dictionary which the keys are years while the values are corresponding models. Below is a piece of data I printed out from the dictionary.</p> <pre><code>1975: ['MODEL9808533471'], 1985: ['MODEL0912768548'], 1980: ['MODEL1006230072', 'MODEL7898438988'], 1987: ['MODEL0848444339'], 1977: ['MODEL788939572...
<p>Perfectly fit the usage of <code>MultiLabelBinarizer</code> from <code>sklearn</code></p> <pre><code>from sklearn.preprocessing import MultiLabelBinarizer s = pd.Series(d) mlb = MultiLabelBinarizer() yourdf=pd.DataFrame(mlb.fit_transform(s),columns=mlb.classes_, index=s.index).T yourdf Out[121]: 1...
python|pandas|dataframe|dictionary|matrix
4
369,687
55,298,323
TensorFlow 2.0 returns unexpected output on dtype=int32 with GradientTape
<p>The following code should output the gradient of y=x*x for x=2, i.e. the value of 4. However the code prints a value of None when using TensorFlow 2.0.0-alpha0. When the definition of x changes to use <code>tf.float32</code> instead of <code>tf.int32</code> as shown in the next snippet, the output changes to the cor...
<p>The reason is that <code>tf.gradient</code> doesn't propagate the gradients through integer tensors. This has been referenced in this github issue:</p> <p><a href="https://github.com/tensorflow/tensorflow/issues/20524" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/20524</a></p>
tensorflow
1
369,688
55,196,713
Yolo Darkflow error. tensorflow.python.framework.errors_impl.InvalidArgumentError: Invalid name
<p>I am getting this output when i run my code:</p> <pre><code> %Run run_img.py /usr/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: compiletime version 3.4 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.5 return f(*args, **kwds) /usr/lib/python3.5/importlib/_boo...
<p>Try this solution. I was having the exact same problem as you and this solved it for me.</p> <pre><code>$ sudo apt-get install python-pip python3-pip $ sudo pip3 uninstall tensorflow $ git clone https://github.com/PINTO0309/Tensorflow-bin.git $ cd Tensorflow-bin $ sudo pip3 install tensorflow-1.11.0-cp35-cp35m-linu...
python|tensorflow|yolo|darkflow
0
369,689
55,487,704
Do I need a SWIG typemap to have a c function return a float to python?
<p>I'm trying to call a C function from python. This function takes a number of arrays as input and returns a float.</p> <p>Do I need a SWIG typemap to do this? One concern is that python doesn't make a distinction between <code>floats</code>, <code>double</code>, etc and I'm specifically interested in returning only ...
<p>Returning <code>float</code> "just works". You don't need additional typemaps:</p> <p><strong>test.i</strong></p> <pre><code>%module test %inline %{ float func(void) { return 1.5; } %} </code></pre> <p>After running swig and compiling the result:</p> <pre><code>&gt;&gt;&gt; import test &gt;&gt;&gt; test.fu...
python|c|numpy|swig
2
369,690
55,311,983
How to select bunch of rows
<p>I have dataframe with multiple columns , i want to select bunch of rows if column B have consecutive 1 and check in these rows if column A have any value equal to 0.04 then need this bunch of rows and extract start value and end value of column A for this bunch of rows</p> <p>Here is my dataframe <a href="https://...
<p><strong>filtter</strong> Consecutive groups <code>.diff().abs().cumsum().bfill()</code> not following the specific considitons <code>(x['B'].eq(1).any() and x['A'].eq(0.04).any()</code></p> <p><strong>agg</strong> first and last</p> <p>followed by grouping consecutivity column to extract first and last rows with u...
python-3.x|pandas|pandas-groupby
2
369,691
55,348,616
Create a tensor by calling a function in a loop in TensorFlow
<p>I need to create a tensor by calling some function <code>fn</code> over two other tensors and indices in a loop as follows:</p> <pre><code>tensor = [[fn(tensor1, tensor2, i, j) for i in range(3)] for j in range(4)] </code></pre> <p>Not sure how to approach this problem. Use <code>tf.map_fn</code> somehow?</p>
<p>So for your simple case your code will execute as it is.</p> <pre><code>import tensorflow as tf sess = tf.Session() a = tf.constant([1,2,3]) b = tf.constant([3,4,5,6]) def fn( tensor1, tensor2, i, j ): return tensor1[i] * tensor2[j] tensor = [[fn(a, b, i, j) for i in range(3)] for j in range(4)] init = tf....
tensorflow
1
369,692
55,576,608
Extracting weights from best Neural Network in Tensorflow/Keras - multiple epochs
<p>I am working on a 1 - hidden - layer Neural Network with 2000 neurons and 8 + constant input neurons for a regression problem.</p> <p>In particular, as optimizer I am using RMSprop with learning parameter = 0.001, ReLU activation from input to hidden layer and linear from hidden to output. I am also using a mini-ba...
<p>Use <code>ModelCheckpoint</code> callback from Keras.</p> <pre><code>from keras.callbacks import ModelCheckpoint checkpoint = ModelCheckpoint(filepath, monitor='val_mean_squared_error', verbose=1, save_best_only=True, mode='max') </code></pre> <p>use this as a callback in your <code>model.fit()</code> . This wil...
python|tensorflow|keras|neural-network|deep-learning
1
369,693
55,270,726
How to zip together lists of unequal length into a dictionary?
<p>I have three lists. </p> <pre><code>import pandas as pd author = ['mccoy.robert'] coauthors = [ 'hola.lubica', 'kundu.subiman', 'ntantu.ibula', 'fletcher.peter', 'jain.tanvi', 'jindal.varun', 'bankston.paul', 'di-maio.giuseppe', 'dickman.raymond-f-jun', 'holy.dusan', 'slover.rebecca', 'curtis.dou...
<p>You can do this with nested <code>for</code> loop, looping over the authors and the zipped coauthors and frequencies. Like so:</p> <pre><code>authors = ['mccoy.robert'] coauthors = [ 'hola.lubica', 'kundu.subiman', 'ntantu.ibula', 'fletcher.peter', 'jain.tanvi', 'jindal.varun', 'bankston.paul', 'di-mai...
python|pandas
0
369,694
55,306,040
How to overcome the Could not convert String to Float?
<p>Hi Everyone I'm Having This Two Columns:</p> <pre><code>Mi_Meteo['Measurement'] = Mi_Meteo['Measurement'].str.rstrip(' Measure') Mi_Meteo['Measurement'].head() 0 0.8 1 0.6 2 0.4 3 0.4 4 0 Name: Measurement, dtype: object </code></pre> <p>And:</p> <pre><code>Mi_Meteo['Sensor_ID'] = Mi_Meteo['Sens...
<p>One possible reason could be some white space in your data which didn't clear out. Add in <code>str.strip()</code> before converting to <code>float</code>.</p> <pre><code>Mi_Meteo['Measurement'] = Mi_Meteo['Measurement'].str.rstrip(' Measure').str.strip() Mi_Meteo['Measurement'] = Mi_Meteo['Measurement'].astype(flo...
python-3.x|string|pandas|multiple-columns
1
369,695
55,385,497
How can I convert my datetime column in pandas all to the same timezone
<p>I have a dataframe with a DataTime column (with Timezone in different formats). It appears like timezone is UTC but I want to convert the column to <code>pd.to_datetime</code> and that is failing. That is problem #1. Since that fails I cannot do any datetime operations on the time period such as group the column by ...
<p>I think that it is not necessary to apply lambdas:</p> <pre><code>df_res['DateTime'] = pd.to_datetime(df_res['DateTime'], utc=True) </code></pre> <p>documentation: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="noreferrer">https://pandas.pydata.org/pandas-docs/sta...
python|pandas|datetime|type-conversion|timezone
29
369,696
55,257,121
Is there a way to convert data frame styler object into dataframe in python
<p>I have extracted xlsx data into pandas dataframe and used style.format to format particular columns into percentages and dollars. So now my dataframe is converted to styler object, because I need to parse this data into csv. I have to convert this object into dataframe please help.</p> <p>below is the code and outp...
<p>You can retrieve the original dataframe from the styler object using the "data" attribute.</p> <p>In your example:</p> <p><code>df = final_df.data</code></p> <p><code>type(df)</code> yields</p> <p>pandas.core.frame.DataFrame</p>
python|pandas|pandas-styles
9
369,697
55,284,019
Create a month for every date between a period and make them columns
<p>I want to separate every month inside the period between the 'start' and 'end' column than I know I can use a pivot_table to make them columns:</p> <pre><code>subscription|values| start | end x |1 |5/5/2018 |6/5/2018 y |2 |5/5/2018 |8/5/2018 z |1 |5/5/2018 |9/5/2018 a ...
<p>Using simple <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>pd.Series.cumsum</code></a></p> <pre><code>import calendar df2 = pd.DataFrame(np.zeros(shape=[len(df),13]), columns=map(lambda s: calendar.month_abbr[s], ...
python|pandas|pivot-table
1
369,698
55,567,688
How to find the minimum distance .. when two points belongs to same distance
<p>I have a <code>dataframe</code> like this:</p> <pre><code>A B 1 0.1 1 0.2 1 0.3 2 0.2 2 0.5 2 0.3 3 0.8 3 0.6 3 0.1 </code></pre> <p>How can I find the minimum value belonging to each point 1,2,3 and there should be no conflict which means point 1 and 2 should not belong to same point 0.3..</p>
<p>If I understand correctly, you want to do two things: - find the minimum <code>B</code> per distinct <code>A</code>, and - make sure that they don't collide. You didn't specify what to do in case of collision, so I assume you just want to know if there is one.</p> <p>The first can be achieved with Rarblack's answer...
python|pandas|matching|pairwise
0
369,699
55,508,591
How to identify outliers in a column data about test scores and return country names for outliers
<p>~What I've done~</p> <p>In the first part of this assignment, I had to take data (from here: [a link] <a href="https://en.wikipedia.org/wiki/Programme_for_International_Student_Assessment_(2000_to_2012)" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Programme_for_International_Student_Assessment_(2000_to_...
<pre><code>tempDF = pd.DataFrame({'country': ['A']*1000+['B'], 'Income' : [10]*1000+[1000]}) def find_outlier(df, col): return df[abs((df[col]-df[col].mean())/df[col].std())&gt;1.8]['country'].values # OR #return df[np.abs((df[col]-np.mean(df[col]))/np.std(df[col]))&gt;1.8]['country'].values print ("The o...
python|pandas|dataframe|outliers
0