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
9,500
70,351,366
fast.ai not using the GPU
<p>When I run training using fast.ai only the CPU is used even though</p> <pre><code>import torch; print(torch.cuda.is_available()) </code></pre> <p>shows that CUDA is available and some memory on the GPU is occupied by my training process.</p> <pre><code>from main import DefectsImagesDataset from fastai.vision.all imp...
<p>I had to specify the device when creating the dataloaders. Instead of</p> <pre><code>dls = DataLoaders.from_dsets( defects_dataset, defects_dataset, bs=BATCH_SIZE, num_workers=NUMBER_WORKERS) </code></pre> <p>I know have</p> <pre><code>dls = DataLoaders.from_dsets( defects_dataset, defect...
deep-learning|pytorch|fast-ai
2
9,501
70,363,430
difference between "function()" and "function"
<p>I see</p> <ol> <li><code>df[&quot;col2&quot;] = df[&quot;col1&quot;].apply(len)</code></li> <li><code>len(df[&quot;col1&quot;])</code></li> </ol> <p>My question is,</p> <ul> <li><p>Why use &quot;<code>len</code>&quot; function without parenthesis in 1, but use it with parenthesis in 2?</p> </li> <li><p>What is the d...
<p>The first example that you mentioned(the above code) <strong>maps</strong> the function <strong>len</strong> to the target variable <strong>df[&quot;col1&quot;]</strong></p> <pre><code>df[&quot;col2&quot;] = df[&quot;col1&quot;].apply(len) </code></pre> <p>Whenever we have to map a function to any <strong>iterable</...
python|pandas
1
9,502
56,229,534
Pandas - Filtering row based on value
<p>I have a Dataframe as below:</p> <pre><code>col1,col2,value1,value2 type_1,type_2,,NaN type_3,type_4,NaN, type_5,type_6,apples,oranges type_7,type_8,apples,apples </code></pre> <p>I am trying to filter out the above dataframe in which value1 is not the same as value2</p> <p>Expected output:</p> <pre><code>col1,c...
<p>There are several ways which you can do this:</p> <h1>Using <code>boolean indexing</code></h1> <p>I will use <code>.ne</code> here which stands for <code>not equal</code></p> <pre><code>df[df['value1'].ne(df['value2'])] col1 col2 value1 value2 0 type_1 type_2 NaN NaN 1 type_3 type_4 N...
pandas
2
9,503
56,187,899
Keras, calculating gradients of the loss wrt the input on an LSTM
<p>I am quite new to machine learning and I was messing around with adversarial-examples. I am trying to fool a binary character-level LSTM text classifier. Thus I need the gradient of the loss w.r.t. the input.</p> <p>The gradients function although returns <code>None</code>.</p> <p>I already tried to get the gradie...
<p>Gradients can only be computed for "trainable" tensors, so you might want to wrap your input into tf.Variable().</p> <p>As soon as you want to work with gradient, I would suggest doing it using tensorflow, which nicely integrates with Keras. Below is my example of doing it, note that it works in eager execution mod...
tensorflow|keras|gradient
1
9,504
56,139,738
Indexing in Pandas compared to dplyr
<p>I am a R/dplyr user who is switching to pandas. I noticed that a lot of books on pandas focus heavily on the index. I have not seen such intense focus on the index on R's dataframes. Life felt much more simple and easy. Does pandas' index play a large part on everyday data science tasks? </p> <p>I looked around on...
<p>Index is very important in <code>pandas</code>, for example </p> <pre><code>s=pd.Series([1,2],index=[0,1]) s2=pd.Series([1000],index=[0]) </code></pre> <p>You can add it , since it will match the index to get the row match base on that. </p> <pre><code>s.add(s2,fill_value=0) 0 1001.0 1 2.0 dtype: float64...
python|r|pandas|dplyr
3
9,505
55,587,233
how to store diffrent stocks data frame in some sort of container and could run some operation in one go on all data frame in that conatiner operation
<p>I would like to know how to store different stocks data frame in some sort of container and be able to run some operation in one go on all data frame in that container operation, and would like to calculate daily returns, cum returns etc </p> <p>I have been using <code>vars()</code> function to do it but that does...
<p>Lets talk about what you are currently doing in the hopes that it becomes clear to you what you need to change. So you are currently storing in vars and need to change that. Question 1 is what is <code>vars()</code> </p> <blockquote> <p>vars([object]) Return the <strong>dict</strong> attribute for a module, class...
pandas|algorithmic-trading
1
9,506
55,789,492
How to add multiple columns and assigning into new column name by using function in pandas dataframe?
<p>I have a data frame which has 50 columns. I would like to sum 10 columns and store the same into new column name (called savings to be created). I have 10 files, hence want to use function and apply the same to all the files.</p> <p>Right now I am using iloc and it's working fine. I don't know how to bring this int...
<p>I believe you need pass <code>DataFrame</code> to <code>function</code>:</p> <pre><code>def saving(x): x['savings'] = x.iloc[:,11:27].sum(axis = 1).round(2) return x </code></pre> <p>If need apply function to <code>DataFrame</code> use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pand...
python-3.x|pandas
0
9,507
64,679,865
Error while installing PyTorch using pip - cannot build wheel
<p>I get the following output when I try to run <code>pip3 install pytorch</code> or <code>pip install pytorch</code></p> <pre><code>Collecting pytorch Using cached pytorch-1.0.2.tar.gz (689 bytes) Building wheels for collected packages: pytorch Building wheel for pytorch (setup.py) ... error ERROR: Command error...
<p>From your error:</p> <blockquote> <p><code>Exception: You tried to install &quot;pytorch&quot;. The package named for PyTorch is &quot;torch&quot;</code></p> </blockquote> <p>which tells you what you need to know, instead of</p> <pre><code>pip install pytorch </code></pre> <p>it should be</p> <pre><code>pip install ...
python|python-3.x|linux|pip|pytorch
13
9,508
64,664,283
Importing any embedding layer from TensorFlow Hub gives URL error (Kaggle Kernel)
<p><code>import tensorflow as tf</code><br /> <code>import tensorflow_hub as hub</code><br /> <code>module_url = &quot;https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/1&quot;</code><br /> <code>bert_layer = hub.KerasLayer(module_url, trainable=True)</code><br /> I am using Kaggle Notebook for this work. I...
<p>Try turning on internet access of your kaggle kernel. Be default, your kernel has no internet access, you have to turn it on to get resources from other site. See: <a href="https://www.kaggle.com/product-feedback/63544" rel="nofollow noreferrer">https://www.kaggle.com/product-feedback/63544</a></p>
python|tensorflow|machine-learning|nlp|tensorflow-hub
1
9,509
64,805,224
Undefined references when trying to use Tensorflow-Lite C api built for ARM64, with Android - ndk standalone toolchain for ARM
<p>I cross compiled tensorflow lite C from source for ARM64 using Bazel (<a href="https://www.tensorflow.org/lite/guide/build_arm64" rel="nofollow noreferrer">https://www.tensorflow.org/lite/guide/build_arm64</a>) and got binary libtensorflowlite_c.so</p> <p>Now I am trying to compile my C code which uses TFLIte C api ...
<p>I'm unable to exactly reproduce your issue, but a good clue is this warning you got:</p> <pre><code>D:\ARM_TOOL\android-standalone\android-ndk-r17-arm64\bin/../lib/gcc/aarch64-linux-android/4.9.x/../../../../aarch64-linux-android/bin\ld: warning: libc.so.6, needed by Tlib/libtensorflowlite_c.so, not found (try using...
c++|c|arm|tensorflow-lite
0
9,510
40,035,276
Adding arrays to dataframe column
<p>Let's assume I have this dataframe <code>df</code>:</p> <pre><code> 'Location' 'Rec ID' 'Duration' 0 Houston 126 17 1 Chicago 338 19.3 </code></pre> <p>I would like to add a column with arrays corresponding to my recordings like:</p> <pre><code> 'Location' 'Rec ID' 'Dur...
<p>I think the easiest is to assign <code>list</code> of <code>lists</code>, only you need same length of <code>lists</code> as <code>length</code> of <code>DataFrame</code>:</p> <pre><code>arr = [[0.2, 0.34, 0.45, 0.28], [0.12, 0.3, 0.41, 0.39]] print (arr) [[0.2, 0.34, 0.45, 0.28], [0.12, 0.3, 0.41, 0.39]] print (l...
python|arrays|pandas|dataframe
1
9,511
44,100,289
DataFrame labyrinth game solution?
<p>So I wanted to test my pands skills by creating a labyrinth game, basically create a dataframe with 0s and 1s, where the 0s represent an open square and the 1s represent a wall:</p> <pre><code>df = pd.DataFrame(np.random.randint(0, 2, (10,11))) 0 1 2 3 4 5 6 7 8 9 10 0 0 1 0 0...
<p>I'd do it recursively:</p> <ul> <li><code>where_next</code> takes an array and location. If it's in the last column, then it returns <code>True</code>. Otherwise, it set's the current location to <code>1</code> and finds all adjacent locations that are <code>0</code> and recurses at that location.</li> <li>I init...
python|pandas|dataframe
1
9,512
69,360,486
Fast slicing of dataframe/list/numpy array of tuples
<p>I have a dataframe where one column consists of tuples, i.e</p> <pre><code>df['A'].values = array([(1,2), (5,6), (11,12)]) </code></pre> <p>Now I want to split this into two different columns. A working solution is</p> <pre><code>df['A1'] = df['A'].apply(lambda x: x[0]) </code></pre> <p>But this is extremely slow. O...
<pre><code>n: int = 2 df = pd.DataFrame(df[&quot;A&quot;].apply(lambda x: (x[:n], x[n:])).tolist(), index=df.index) </code></pre> <p>you can have a look into pandarallel also.</p>
python|pandas|numpy
0
9,513
69,354,341
Matplotlib clip or trim lines and polygon
<p>How can I efficiently &quot;trim&quot; or &quot;clip&quot; or remove the portion of the red line outside of the purple box? Is there a trick with numpy masks?</p> <p>Using Python 3.8.3 and Matplotlib</p> <pre><code>x = [10,15.5,12.5,7.5,5,10] y = [15,10,5,5,10,15] fig, ax = plt.subplots() ax.fill_between(x,y, facec...
<p>This is done not using numpy masks. If I understand correctly, this is the code:</p> <pre class="lang-py prettyprint-override"><code>fig, ax = plt.subplots() x = [10,15.5,12.5,7.5,5,10] y = [15,10,5,5,10,15] ax.fill_between(x,y, facecolor=&quot;blue&quot;, alpha=0.25) ax.axis(&quot;equal&quot;) myinterval = 1.5 xv...
numpy|matplotlib|crop|mask
0
9,514
40,821,099
How to use Blackman Window in numpy to take a part of values from an array?
<p>I want to take a part of values (say 500 values) of an array and perform some operation on it such as take sum of squares of those 500 values. and then proceed with the next 500 values of the same array.</p> <p>How should I implement this? Would a blackman window be useful in this case or is another approach more s...
<p>It depends on several criteria:</p> <ol> <li><p>Is the number of elements per operation an integer divisor of your array length?</p></li> <li><p>Is the number of elements a significant fraction of your array length?</p></li> </ol> <p>If 1. is True then you can reshape your array to use reduce-functions like <code>...
python|arrays|numpy
0
9,515
54,024,671
error while installing tensorflow in conda environment (CondaError: Cannot link a source that does not exist.)
<p>trying to install tensorflow using conda package manager using following command</p> <blockquote> <p>conda install -c conda-forge tensorflow</p> </blockquote> <p>but it gives following error while executing transaction</p> <blockquote> <p>CondaError: Cannot link a source that does not exist. C:\ProgramData\...
<p>I faced the same issue and </p> <pre><code>conda update -n root conda </code></pre> <p>Solved the problem. The env name "root" is for conda &lt;= 4.3, otherwise use:</p> <pre><code>conda update -n base conda </code></pre> <p>I hope this helps.</p>
python|tensorflow|anaconda|conda
1
9,516
53,870,552
How to put filenames into an array from os.listdir
<p>Lets say you input: <code>os.listdir(r'filepath')</code></p> <p>and the output is: <code>['a.txt','b.txt','c.txt','d.txt','e.txt']</code></p> <p>How could you put the file names, <code>['a', 'b', 'c', 'd', 'e']</code> into a pandas dataframe? </p>
<p>Use list comprehension with <code>DataFrame</code> contructor:</p> <pre><code>L = ['a.txt','b.txt','c.txt','d.txt','e.txt'] df = pd.DataFrame({'col':[x.split('.')[0] for x in L]}) print (df) col 0 a 1 b 2 c 3 d 4 e </code></pre> <p>Thank you for suggestion @Joe Halliwell, main advantage is general sol...
python-3.x|pandas
2
9,517
54,248,557
Appending status to dataframe in pandas
<p>I want to create a status based off dates but I'm having a problem appending the data. I have the data pulling in from a spreadsheet.</p> <p>I have tried the append function but it gives me error. I have looked online but I cannot find how to do this.</p> <pre><code>#import pandas import pandas as pd import numpy...
<p>I believe you need:</p> <pre><code>#add variable row def marvin(row): result = [] ... ... else: result.append('DATE EXCEPTION') #add return list result return result #add apply per rows df['new'] = df.apply(marvin, axis=1) </code></pre> <p>Yoour solution should be rewritte...
python|pandas
1
9,518
53,952,713
How to fill in a table using 2 data frames
<p>I have one data frame that looks like a table like follows: </p> <pre><code>1. DueDate | item1 | item2 | item3 | item4 2. 1/1/2018 | nan | nan | nan | nan 3. 1/2/2018 | nan | nan | nan | nan 4. 1/3/2018 | nan | na...
<p>You can use the below <code>get_dummies</code> with assigning to <code>df1</code>:</p> <pre><code>df1[df2['items'].str.get_dummies().columns]=df2['items'].str.get_dummies().replace(1,'YES').replace(0,pd.np.nan) </code></pre> <p>And now:</p> <pre><code>print(df1) </code></pre> <p>Is:</p> <pre><code> DueDate i...
python|pandas|dataframe
2
9,519
54,044,589
Analogue function of Wolfram Mathematica in Python in NumPy or SciPy
<p>I am rewriting some code writed in Wolfram Mathematica to Python. And, in some moment I needed an analogue of function <a href="https://reference.wolfram.com/language/ref/ArrayResample.html" rel="nofollow noreferrer"><code>ArrayResample[array,dspec]</code></a>. May be you know a function from any package (NumPy or S...
<p>You could use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html#scipy.ndimage.map_coordinates" rel="nofollow noreferrer"><code>scipy.ndimage.map_coordinates</code></a>. Here are <code>map_coordinate</code> equivalents of the <a href="https://reference.wolfram.com/langu...
python|python-3.x|numpy|scipy|wolfram-mathematica
2
9,520
66,154,374
Retrieving only one element of a tuple when the tuple is the value of a dictionary
<p>I am trying to map a column of my df with a dictionary, where the dictionary contains tuples as values. I want to be able to only return the first value of the tuple in the output column. Is there a way to do that?</p> <p>The situation:</p> <pre><code>d = {'key1': (1, 2, 3)} df['lookup_column'] = 'key1' df['return_c...
<p>Use <code>str</code> for first element of <code>Iterable</code>, here <code>tuple</code> - it return <code>NaN</code> if no match:</p> <pre><code>df['return_column'] = df['return_column'].str[0] </code></pre> <p>All together:</p> <pre><code>df = pd.DataFrame({'lookup_column':['key1','key2']}) d = {'key1': (1, 2, 3)...
pandas|dataframe|dictionary|tuples
1
9,521
66,043,792
How can I combine the part-duplicate data in a DataFrame?
<p>I'm processing my data from MIMIC dataset. Some of my data are like that: (the data type is pandas.dataframe)</p> <pre><code>time A B C D 01:00 2 NaN 3 4 02:00 2 NaN 3 4 03:00 2 NaN 3 4 01:00 NaN 4 3 4 </code></pre> <p><code>NaN</code> means missing data.</p> <p>Obviously line 1 and line 4(they are token in same ...
<p>If you want to sum the other rows , here is the code :</p> <pre><code>df.groupby(['time']).sum() </code></pre> <p>or</p> <pre><code>df.groupby(['time']).max() </code></pre> <p>for more : <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">htt...
pandas|dataframe|machine-learning|scikit-learn|deep-learning
0
9,522
66,276,304
Creating own type from numpy.dtype for structured array. What is the cleanest way to obtain this?
<p>I would like to derive an own class from <code>numpy.dtype</code> like this:</p> <pre><code>import numpy as np class A(np.dtype): def __new__(cls): cls.fields = [(&quot;field1&quot;, np.int32), (&quot;field2&quot;), np.int64)] </code></pre> <p>However, <code>numpy</code> won't let me do this:</p> <blockq...
<p>You don't need to create another &quot;dtype&quot; class there - just a dtype instance.</p> <p>And your journey through metaclass land, in fact, do just that - as your <code>__new__</code> method returns a dtype instance, that is what replaces the <code>class A</code> statement in your body. As ou pass <code>**args...
python-3.x|numpy|metaclass|dtype|structured-array
0
9,523
52,609,374
How to classify data for Tensorflow.js as 2d, 3d etc?
<p>Before I begin, I am completely new to machine learning and just starting to get my feet wet. I am sufficiently comfortable at JavaScript, and hence I thought I would give tensorflow.js a run. So please forgive my naivety.</p> <p>I have data which contains information for an individual sample as:</p> <pre><code>Pr...
<p>Since the probe ids(1-10) of your input data are consistant over each sample, you don't need to pass them to your model.</p> <p>So your data is only one-dimensional, more specific it has the shape: <code>[10]</code>, which is also the shape of your first layer.</p> <p>But since <code>model.fit()</code> and <code>m...
tensorflow|tensorflow.js
1
9,524
52,865,279
Why numpy fft return incorrect phase information?
<p>I compare phase and amplitude spectrum in Matlab and numpy. I think Matlab work correct, but numpy compute correct amplitude spectrum, but phase spectrum is strange. How i must change python code for correct computing fft by numpy?</p> <p>Matlab:</p> <pre><code>fs = 1e4; dt = 1 / fs; t = 0:dt:0.5; F = 1e3; y = co...
<p>It's a problem in understanding <code>np.arange</code>. It stops one <code>dt</code> <em>before</em> reaching the desired value (the interval you pass is open on the right side). If you define </p> <pre><code>t = np.arange(0, 0.5+dt, dt) </code></pre> <p>everything will work fine.</p>
python|matlab|numpy|spectrum|phase
5
9,525
58,321,617
How to convert a pandas series into a numericals only series?
<p>I have a pandas series which contains float, integer and alphanumerical elements. The float and integer elements are also of type string like below:-</p> <pre><code>sr = pd.Series(['80', '25.1', '08!shashi123', '2!shekhar45@!#', '6.23']) </code></pre> <p>I want to convert this series into just a numerical series ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer">to_numeric</a> with error coercion:</p> <pre><code>import pandas as pd sr = pd.Series(['80', '25.1', '08!shashi123', '2!shekhar45@!#', '6.23']) result = pd.to_numeric(sr, errors='coerce') pri...
python|pandas
3
9,526
58,192,050
Keras multiple input, output, loss model
<p>I am working on super-resolution GAN and having some doubts about the code I found on Github. In particular, I have multiple inputs, multiple outputs in the model. Also, I have two different loss functions. </p> <p>In the following code will the mse loss be applied to img_hr and fake_features?</p> <pre><code># Bu...
<blockquote> <p>In the following code will the mse loss be applied to img_hr and fake_features?</p> </blockquote> <p>From the documentation, <a href="https://keras.io/models/model/#compile" rel="nofollow noreferrer">https://keras.io/models/model/#compile</a></p> <p>"<em>If the model has multiple outputs, you can ...
python|tensorflow|keras
1
9,527
58,482,434
How can convert a range of numerical data to a particular categorical data?
<p>I have data in this range in a negative float from -100 to 100, and i want change this data of this way:</p> <pre><code>from 0 to 1 - ss from 1 to 2 - sm from 2 to 3 - sa &gt; 3 s from 0 to -1 - bs from 1 to -2 - bm from 2 to -3 - ba &lt; 3 b </code></pre> <p>How can do this?</p> <p>Thanks</p>
<p>Please check the following solution:</p> <pre><code>import pandas as pd y = pd.DataFrame({"Data": [1.1, 1.3, 2.5, 3.9, -0.7, -1.3, -2.6, -9]}) def change_func(x): if x &lt;= -3: return "b" elif -3 &lt; x &lt;= -2: return "ba" elif -2 &lt; x &lt;= -1: return "bm" elif -1 &l...
python|pandas
1
9,528
68,919,424
Pandas ValueError: Columns must be same length as key for now apparent reason
<p>I have a test dataframe, consisting of a reduced sample size of data with the following properties:</p> <pre><code>dataframe = pd.read_csv('Data/bookstore_0.txt', sep= ' ', header=None) dataframe.columns = ['Timestamp', 'ID', 'X', 'Y'] dataframe.insert(4, 'X_Diff', None) dataframe.insert(5, 'Y_Diff', None) #datafram...
<p>Try using <code>groupby.transform</code> instead:</p> <pre><code>ped_data[['X_Diff', 'Y_Diff']] = ped_data.groupby('ID')[['X', 'Y']].transform('diff') </code></pre>
python|pandas|dataframe|diff
2
9,529
44,713,364
Tensorflow windows error
<p>I am trying to install tensorflow(GPU) for windows using Python 3.5 but I get error when I try to import the tensorflow package.</p> <pre><code>I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:119] Couldn't open CUDA library cublas64_80.dll I c:\tf_jenkins\ho...
<p>Did you follow the instructions for installing CUDA Toolkit? You can find a link to the instructions <a href="https://www.tensorflow.org/install/install_windows" rel="nofollow noreferrer">here</a>.</p> <blockquote> <p>Requirements to run TensorFlow with GPU support</p> <p>If you are installing TensorFlow with GPU su...
python|tensorflow|pip
0
9,530
44,500,493
tensorflow multi gpu sharing variables
<p>I'm using multi gpu on tensorflow. And I'm confusing about sharing variable under same scope.</p> <p>According to <a href="https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_multi_gpu_train.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/tutorials/image/c...
<p>Yes, you are right. For the first device, the <code>reuse</code> flag should be set to <code>False</code>. In the tutorial, <code>tf.get_variable_scope().reuse_variables()</code> is called after <a href="https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_multi_gpu_train.py#L178" rel="no...
tensorflow
1
9,531
44,679,069
BitwiseXOR for Tensorflow
<p>My project requests a new layer, which needs the new operator of Tensor to compute bitwiseXOR between input x and constant Key k. E.g. x = 4 (bit form: 100), k = 7 (111), the bitwiseXOR(x, k) expects as 3 (011).</p> <p>As far as I know, Tensor only has LogicXOR operator for bool type. Luckily, Tensorflow has the ex...
<p>If you don't want to implement your own C++ op, you can try with <a href="https://www.tensorflow.org/api_docs/python/tf/py_func" rel="nofollow noreferrer">tf.py_func</a> which allows you to define a python function that operates on <code>numpy</code> arrays and is then used as a Tensorflow operation in the graph.</p...
c++|tensorflow|xor|tensor
0
9,532
61,013,042
How to change a regular timeseries to a date light saving timeseries?
<p>I am creating a time series as follows:</p> <pre><code>import pandas as pd dti = pd.date_range('2020-01-01 00:00', '2021-01-01 00:00', freq='0.25H') </code></pre> <p>Now, I want to modify this timeseries based on Day Light saving in <code>Europe/Berlin</code>. Meaning: on <strong>29th march 2020</strong> the clock...
<p>add the timezone when you create your datetime index:</p> <pre><code>dti = pd.date_range('2020-01-01 00:00', '2021-01-01 00:00', freq='0.25H', tz='Europe/Berlin') dti[8450:] DatetimeIndex(['2020-03-29 00:30:00+01:00', '2020-03-29 00:45:00+01:00', '2020-03-29 01:00:00+01:00', '2020-03-29 01:15:00+01...
python|python-3.x|pandas|datetime|dst
3
9,533
61,084,204
Creating pandas pivot table with new column names based on condition
<p>Say I have a dataframe of addresses like</p> <pre><code> user_id AddressLine1 AddressLine2 City address_type 0 u68472 PO Box 354 None LOREDO Mailing 1 u68472 154 Cedar Park Apt. 39 LOREDO Residential </code></pre> <p>I want to create a new d...
<p>You can create two dataframes based on address type and then join them on user_id and set rsuffix for the overlapping columns.</p> <pre><code>mailing = df.loc[df.address_type == 'Mailing', :].set_index('user_id') residential = df.loc[df.address_type == 'Residential', :].set_index('user_id') new_df = mailing.join(...
python|pandas
3
9,534
61,124,508
Product Inventory project using pandas
<p><br> Am trying to make a simple python program where we have to Create an application which manages an inventory of products.To create a product class which has a price, id, and quantity on hand. Then create an inventory class which keeps track of various products and can sum up the inventory value.<br><br> Please c...
<p>Try this</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd class Product: def __init__(self): self.price = None self.id = None self.qty = None self.data = pd.DataFrame(([]),columns=['ID','Cost','Quantity']) class inventory(Product): def value(self): ...
python|pandas|project
0
9,535
61,109,186
Python Pandas to match rows with overlapping coordinates
<p>I am a python newbie, trying to figure out a problem using pandas.</p> <p>I have two .csv files that I have imported as pandas dataframes.</p> <p>one of these files is a file with rows for ID number, Start and End coordinates:</p> <pre><code>ID Start End 1 45 99 3 27 29 6 13 23 19 11 44 <...
<p>So to start out,you should probably rename your columns so that you can tell which belongs to which dataframe, it'll make things easier when comparing them later.</p> <pre><code>df1 = df1.rename(columns={'Start': 'Start_1', 'End': 'End_1'}) df2 = df2.rename(columns={'Start': 'Start_2', 'End': 'End_2'}) </code></p...
python|pandas|dataframe
0
9,536
71,669,024
Numpy 2D Matrix showing list type for nested matrix elements
<p>Currently I am trying to pass a 2D matrix into the sklearn OneHotEncoder. Whenever I try to pass the matrix I get this error:</p> <pre><code>Encoders require their input to be uniformly strings or numbers. Got ['list'] </code></pre> <p>After a bit of investigation, I see the matrix being returned is showing:</p> <pr...
<p>Using a copy-n-paste from your question:</p> <pre><code>In [239]: [list(['e2', 'e4', 'e5']), list(['e1', 'e2', 'e3', 'e4']), ...: list(['e1', 'e2']), list(['e1', 'e2', 'e3', 'e4', 'e5']), ...: list(['e1', 'e2', 'e3', 'e4', 'e5']), ...: list(['e1', 'e2', 'e3', 'e4', 'e5', 'e6'])] Out[239]: [['e2', ...
python|arrays|pandas|numpy
0
9,537
70,012,861
Pandas groupby with no function and display each unique value only once
<p>I'm not sure Pandas does this or not.</p> <p>Given a dataframe that looks like this:</p> <p><a href="https://i.stack.imgur.com/YddNl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YddNl.png" alt="enter image description here" /></a></p> <p>I want to group by <code>Id</code> and then list sorted b...
<p>You could do this:</p> <pre class="lang-py prettyprint-override"><code>df = df.sort_values('Id').set_index(['Id', 'Name']) </code></pre> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; print(df) Score Index Id Name 11 Jon-Smithson 0.80 AM 12 Jon-Smyth...
pandas|pandas-groupby
2
9,538
69,711,020
How to merge two individuals cells into a singular combined value in Pandas
<p>I have a program that I need to merge two cells into a singular cell. The input .csv file is shown below</p> <pre><code>12 00 0E 00 57 23 57 23 02 23 57 0A 2D 16 0C 5A 2D 16 </code></pre> <p>This is a small excerpt of the input file I have. I am currently trying to create a new column where the values are</p> <pre><...
<p>You can use the underlying numpy array and <code>reshape</code>:</p> <pre><code>import io t = '''12 00 0E 00 57 23 57 23 02 23 57 0A 2D 16 0C 5A 2D 16''' # using io here for the example but use a file in the real use case df = pd.read_csv(io.StringIO(t), sep=' ', header=None, dtype=str) x,y = df.shape (pd.DataFr...
python|pandas|merge
1
9,539
69,997,177
Pandas show both unique counts and unique values?
<p>Let's say I have a dataframe like this:</p> <pre><code>import pandas as pd df = pd.DataFrame([ ('a', 'aa'), ('b', 'aa'), ('c', 'bb'), ('d', 'bb'), ('e', 'cc'), ('f', 'cc'), ('h', 'cc') ], columns=['group', 'id']) </code></pre> <p>I do a groupby to show the count of unique values and also...
<pre><code>res = df.groupby('id')['group'].agg(count='nunique', values='unique') </code></pre> <p><strong>Output</strong></p> <pre><code>&gt;&gt;&gt; res count values id aa 2 [a, b] bb 2 [c, d] cc 3 [e, f, h] </code></pre>
python|pandas|pandas-groupby
3
9,540
69,830,999
How to use tf.random.uniform and not generate duplicates
<p>I need to creare a random list of integer values that rappresent indices for other operation, the problem is that <code>tf.random.uniform</code> can generate the same value multiple times, and i don't want this behavious. Is there a way to change it?</p> <pre><code>indices = tf.random.uniform(shape=[size_for_layer_s...
<p>What you want is sampling without replacement.</p> <p>Try something like this.</p> <pre><code>sorted_indices = tf.range(size_for_layer_submodel[index]) shuffled_indices = tf.shuffle(sorted_indices) </code></pre>
python|tensorflow
0
9,541
43,082,314
What is the correct setting for pandas.read_csv to read a very raw CSV file with first three numbers compiled into datetime.datetime object?
<p>To be more explicit, I have this type of data</p> <pre><code>2011,1,14, Orange ,Buy,1500, 2011,1,19, Apple ,Sell,1500, 2011,1,19, Banana ,Buy,4000, </code></pre> <p>I am trying to read it directly into DataFrame with a columns=['date','fruit', 'trade','quantity'] shape like this.</p> <pre><code>print df_groce...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><strong><code>pd.read_csv</code></strong></a></p> <blockquote> <p>parse_dates : boolean or list of ints or names or list of lists or dict, default False </p> <ul> <li>boolean. If True -> try pars...
python|csv|pandas|dataframe
3
9,542
43,137,549
Run multiple tensorflow ops with shared memory in parallel
<p>I am trying to run multiple instances of an op which depend on a shared kernel (a tensorflow variable) <code>K</code>, in parallel.</p> <p>From the tensorflow FAQ:</p> <blockquote> <p>The Session API allows multiple concurrent steps (i.e. calls to tf.Session.run in parallel. This enables the runtime to get highe...
<p>It looks like your <code>op_list</code> contains <code>n_experiments</code> copies of the same <code>tf.Tensor</code>. If that is the case, calling <code>sess.run(op_list)</code> will execute the op once, then make <code>n_experiments</code> copies of the result. If you want to invoke multiple instances of <code>som...
parallel-processing|tensorflow
2
9,543
50,346,992
Slicing Data from two columns and outputting a new values in Pandas Advice
<p>Lets assume we have the following Dataframe:</p> <pre><code>import pandas as pd df = pd.read_csv('subjects.csv') Col A, Interest, Col Start, Col Go, Col Learn, Learn English Lit Go Mathematics Start Science Learn Science Go English Start Math Learn Mat...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.findall.html" rel="nofollow noreferrer"><code>findall</code></a> if need extract all values by list with list comprehention and <code>join</code> for append string <code>Learn</code>:</p> <pre><code>#better is use loc for ...
python|pandas|csv|dataframe
1
9,544
45,620,845
Calculate the distance between two .vtk files in (Python)
<p>Applying a transformation in the following .vtk file:</p> <p><strong>im1.vtk:</strong></p> <pre><code># vtk DataFile Version 3.0 vtk output ASCII DATASET POLYDATA POINTS 10 float -61.2 40.8 0.0 -55.3 39.3 0.0 -49.2 39.3 0.0 -43.2 40.4 0.0 -37.3 42.1 0.0 67.6 44.3 0.0 63.4 49.8 0.0 57.7 53.6 0.0 51.0 55.3 0...
<blockquote> <p>Is there an optimal one that is faster and cleaner?</p> </blockquote> <p>Sure - instead of filling rows, fill columns and use full power of numpy</p> <p>Along the lines</p> <pre><code>import sys import numpy as np def read_vtk(fname): """ """ with open(fname, 'rt') as f: lines ...
python|numpy|vtk
1
9,545
45,634,254
How can I create a (None,299,299,3) from (299,299,3)?
<p>I am trying to use the Keras 2 incepctionV3 based trained model to predict an image for testing purpose. My original model work well, then I try to create a model with specified input_shape (299,299,3)</p> <pre><code>base_model = InceptionV3(weights='imagenet', include_top=False, input_shape=(299,299,3)) </code></...
<p>here the problem is image size, set the require size to <code>299, 299</code></p> <pre><code>target_size = (299, 299) #fixed size for InceptionV3 architecture </code></pre>
python|tensorflow|keras|keras-2
2
9,546
62,660,423
Most efficient one-hot-encoder
<p>Say, I have a Numpy array <code>target</code> that looks as follows:</p> <pre><code>target = np.array([1, 2, 3, 2, 3, 2, 3, 1, 1, 3]) </code></pre> <p>I know the range of the values in target: namely 1-3.</p> <p>Now, I want to create a one hot encoding of target for which the length is the same as target.</p> <p>To ...
<p><strong>Approach #1</strong></p> <p>Create a mask (for memory + perf. efficiency), assign <code>1s</code>/<code>True</code> at indices given by target (one-offsetted as they start with <code>1</code>) and finally use view for conversion to <code>int</code> array -</p> <pre><code>mask = np.zeros((len(target), 3), dty...
python-3.x|numpy|for-loop|one-hot-encoding
1
9,547
62,814,427
Extract tensor from string
<p>Is it possible to extract directly the tensor included in this string <code>tensor([-1.6975e+00, 1.7556e-02, -2.4441e+00, -2.3994e+00, -6.2069e-01])</code>? I'm looking for some <code>tensorflow</code> or <code>pytorch</code> function that can do it, like the <code>ast.literal_eval</code> function does for dictiona...
<p>You can use <a href="https://docs.python.org/3/library/functions.html#eval" rel="nofollow noreferrer"><code>eval</code></a>:</p> <pre><code>import torch.tensor as tensor eval(tensor_list) &gt;&gt;&gt; tensor([-1.6975, 0.0176, -2.4441, -2.3994, -0.6207]) </code></pre>
string|pytorch|tensor
3
9,548
54,609,960
python 3 get the column name depending of a condition
<p>So i have a pandas df (python 3.6) like this</p> <pre><code>index A B C ... A 1 5 0 B 0 0 1 C 1 2 4 ... </code></pre> <p>As you can see, the index values are the same as the columns names.</p> <p>What i'm trying to do is to get a new column in the dataframe that has the nam...
<p>If new column should be string compare by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.gt.html" rel="nofollow noreferrer"><code>DataFrame.gt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dot.html" rel="nofollow noreferrer"><code>dot...
python|python-3.x|pandas
4
9,549
54,657,630
Inserting default rows into Pandas Dataframe based on condition/missing data
<p>I have a dataframe that looks like this:</p> <pre><code>import pandas as pd data = {'TABLE_NM': ['TABLE_A', 'TABLE_A', 'TABLE_A', 'TABLE_A', 'TABLE_B', 'TABLE_B', 'TABLE_B', 'TABLE_C', 'TABLE_C', 'TABLE_C', 'TABLE_C' ], 'TEST_TABLE_NM': ['TEST_...
<p>You can chain pivot table to get all columns with all rows, fillna to fill zeros for missing data, stack to get the columns back to rows, and reset the index (you can skip this step to get a multiindex of table/test_table)</p> <pre><code>df=df.pivot_table(index=['TABLE_NM','TEST_TABLE_NM'], columns=['TYPE']).fillna...
python|pandas
3
9,550
54,466,196
Descriptive statistics in Python /with Pandas with std in parentheses
<p>This question concerns the best-practice to do descriptive statistics in Python with a formatted output that correspond to tables found in academic publications: means with their respective standard deviations in parenthesis below. Final goal is to be able to export it in a Latex tabular format (or an other format, ...
<p>I just ran into a similar problem and found your post, so here's how I dealt with the issues you mentioned.</p> <p><strong>Problem 1: Hide second index column</strong></p> <p>I prefer solution <em>b)</em>, but leave <em>a)</em> here for illustrative purposes.</p> <p><em>a)</em> droplevel &amp; set_index</p> <pre><co...
python|pandas|statistics|statsmodels|standard-deviation
5
9,551
73,708,335
Ploting 2D Histogram in 3D Axes Matplotlib/Pyplot
<p>I'm kinda new to python..</p> <p>I have a dataframe on which if I call df.hist() it would result in this following pictures. <a href="https://i.stack.imgur.com/NRqfA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NRqfA.png" alt="Result of " /></a></p> <p>I would like to plot these histogram in 3d...
<p>I think you want to plot the histograms as bars:</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(111, projection='3d') nbins = 5 for y, c in enumerate(df.columns): hist, bins = np.histogram(df[c]) print(hist, bins) ax.bar3d(bins[1:], y-.2, 0, .8, .4, hist) ax.set_yticks(np.arange(len(df.columns))...
python|pandas|matplotlib|jupyter-notebook
0
9,552
73,589,400
assign min values based on iloc and its range from another two column
<p><strong>df</strong></p> <pre><code> A idx1 idx2 2022/1/1 0 2 4 2022/1/2 1 1 3 2022/1/3 2 0 3 2022/1/4 3 3 4 2022/1/5 4 0 4 </code></pre> <p><strong>expected df</strong></p> <pre><code> A idx1 idx2 lowest 2022/1/1 0 2 4 2 2022/1/2 1 1 3 1 202...
<p>The fastest way I can think of is doing it the following way. Did try to time it and it was 10 times faster than normal apply:</p> <p>Change values of column <code>A</code> to numpy array first. Then still use apply along axis=1 but <code>raw=True</code> which passes each row as numpy array. See <a href="https://pan...
pandas
0
9,553
71,339,388
How do i identify an entity (merchant) and perform operations on the entries for that entity in pandas dataframe?
<p>I am trying to perform operations on the time column for each unique merchant (calculate time between transactions). How do I access the individual merchants in an iteration? is there a way to do that in python?</p> <p>Thank you.</p> <p><a href="https://i.stack.imgur.com/pO5kn.png" rel="nofollow noreferrer"><img sr...
<p>Assuming, <code>time</code> is already a <code>datetime64</code>. Use <code>groupby_diff</code>:</p> <pre><code>df['delta'] = df.groupby('merchant')['time'].diff() print(df) # Output merchant time delta 0 A 2022-01-01 16:00:00 NaT 1 A 2022-01-01 16:30:00 0 days 0...
python|pandas|dataframe
1
9,554
52,370,345
Returning Synset('') wrapper when using DataFrame.apply() to generate values
<p>When I pass a function via DataFrame.apply() I'm getting values wrapped in what I assume is their object type. I've seen this error for two applications now: one using NLTK's Wordnet library (returns Synset('value'), and the other with Datetime (Datetime('value')).</p> <p>I've drawn on a number of examples to produ...
<p>Solved it by adding .name() to x[0]. See answer by Alvas <a href="https://stackoverflow.com/questions/27517924/extract-word-from-synset-using-wordnet-in-nltk-3-0">here</a>.:</p> <pre><code>df_agri_clean['Synsets'] = [x[0].name() for x in df_agri_clean['Category'].apply(wordnet.synsets)] print(df_agri_clean['Synsets...
python|pandas|nltk
0
9,555
60,416,978
Simple Imputer cannot impute by column
<p>I have X_train that shapes (14599, 13), i'm trying to impute NaN with column's median but somehow it imputes with row resulting error because in a row there are date, and other than integer values. I already lookup if SimpleImputer has axis parameter but could not find that it exists. How to solve this? </p> <pre><...
<p>Maybe try and drop the date column when imputating:</p> <pre><code>X_train = imp.fit_transform(X_train.drop('date_column', axis=1) </code></pre> <p>Change the name 'date_column' to the right name.</p> <p>Otherwise maybe transform the column with date column from string to date object:</p> <pre><code>X_train['date_co...
python|numpy|machine-learning|imputation
0
9,556
72,785,812
How do I use pandas.dataframe functions of python in Apache IoTDB
<p>Since I deal with massive time series data, I want to switch our database to Apache IoTDB. My original coding involves Python, and I use the pandas.dataframe function in Python to do some data analysis. I want to know if Apache IoTDB can execute pandas.dataframe? And how do I enable this feature?</p>
<p>The SessionDataSet has a method .tof() which consumes the dataset and transforms it to a pandas dataframe.</p>
python|pandas|apache-iotdb|iotdb
1
9,557
72,666,906
Error in importing MobilenetV2 model in Azure ML Studio notebook
<p>I am trying the import MobilenetV2 in the Azure ML Studio notebook, but I am getting an error. Please note that I can import the model running the same command via Jupyter notebook on my local machine.</p> <pre><code>import tensorflow as tf from tensorflow import keras model = tf.keras.applications.MobileNetV2() </...
<p>According to this <a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-troubleshoot-auto-ml" rel="nofollow noreferrer">MSFT document</a>, fixes for Attribute errors such as <code>python AttributeError: 'str' object has no attribute 'decode' </code> are based on the training version of your <code>...
python-3.x|azure|tensorflow|keras|computer-vision
0
9,558
72,620,934
How do I remove rows of a Pandas DataFrame based on a certain condition?
<pre><code>import yfinance as yf import numpy as np import pandas as pd ETF_DB = ['QQQ', 'EGFIX'] fundsret = yf.download(ETF_DB, start=datetime.date(2020,12,31), end=datetime.date(2022,4,30), interval='1mo')['Adj Close'].pct_change() df = pd.DataFrame(fundsret) df </code></pre> <p>Gives me: <a href="https://i.stack.im...
<pre><code>df.reset_index(inplace=True) # Convert the date to datetime64 df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d') #select only day = 1 filtered = df.loc[df['Date'].dt.day == 1] </code></pre>
python|pandas|dataframe|yfinance
1
9,559
72,495,998
Get and assign value to rows in group with index greater than those from idxmax()
<p>The objective is to assign 1s to any index in the group that is a higher value than the one retrieved from idxmax()</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'id':[1, 1, 1, 2, 2, 2, 3, 3, 3], 'val':[1,np.NaN, 0, np.NaN, 1, 0, 1, 0, 0]}) id val 0 1 1.0 1 1 NaN 2 1 0.0 3 ...
<p>If i understand correctly the problem, you can use <code>apply</code> and <code>np.where</code></p> <pre><code>nd = df.groupby('id')['val'].idxmax().tolist() df['val'] = df.groupby('id')['val'].transform(lambda x: np.where(x.index&gt;nd[x.name-1], 1, x)) df Output: id val 0 1 1.0 1 1 1.0 2 1 1.0 ...
python|pandas
3
9,560
72,688,301
Filtering in Pandas by index and column value
<p>I have a dataframe similar to this one:</p> <pre><code>value_1 value_2 1 2 9 6 2 5 7 2 2 5 </code></pre> <p>What I need to do is to only get the rows that have a value_1 greater than 3 for example, but also get the first and last row of the dataframe. Like this:</p> <pre><code>value_1 v...
<p>Assuming a range index, you could use boolean indexing:</p> <pre><code># is value_1 &gt; 3? m1 = df['value_1'].gt(3) # is the index the first or last value? m2 = df.index.isin([0, len(df)-1]) # keep if any condition above is True out = df[m1|m2] </code></pre> <p>If you don't have a range index or if you have duplica...
python|pandas
1
9,561
72,764,980
I am stack with errors using this command pip install nvidia-tensorflow[horovod]
<pre><code>(tensorholo) C:\Users\alaba\Desktop\MIT PROJECT\tensor_holography-main&gt;pip install nvidia-tensorflow[horovod] Collecting nvidia-tensorflow[horovod] Downloading nvidia-tensorflow-0.0.1.dev5.tar.gz`` (7.9 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setu...
<p><code>nvidia-tensorflow[horovod]</code> package doesn't support the Windows platform. You'd need to run it inside a WSL2 (Windows Subsystem for Linux version 2) to make it work on Windows.</p> <p>Like <a href="https://github.com/NVIDIA/tensorflow#install" rel="nofollow noreferrer">the official docs say</a>:</p> <blo...
python|tensorflow|pip|nvidia
2
9,562
72,756,437
Count how many blocks in dataframe
<p>I would like to count how many down and up trends there are in this dataframe containing simple moving average data:</p> <pre><code>Date SMA_50 SMA_200 Trend Trend CumCount T 2019-09-24 35.559013 38.942979 Down 1 2019-09-25 35...
<p>Use a combination of <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.replace.html" rel="nofollow noreferrer"><code>replace</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.diff.html" rel="nofollow noreferrer"><code>diff</code></a>, and <a href="https://pandas.pydata...
python|pandas
0
9,563
59,656,334
How to make a multiplication of a dask.Dataframe from dask.Series over rows?
<p><code>normalised = data.mul(alpha, axis=1)</code> </p> <p>In the snippet above <code>data</code> is a dask.Dataframe and <code>alpha</code> is a dask.Series. </p> <p>Dask raises a <code>ValueError: Unable to mul dd.Series with axis=1</code> error while performing this multiplication. This operation works if I comp...
<p>The operation can be performed using <code>.map_partitions()</code>. Assuming series.index == ddf.columns then:</p> <pre><code>in_pandas = df.mul(dv, axis=1) in_dask = ddf.map_partitions(pd.DataFrame.mul, other=series, axis=1, meta=ddf._meta) import pandas.testing as pdt pdt.assert_frame_equal(in_pandas, in_dask.c...
python|pandas|dask
0
9,564
59,778,132
How does a process of optimization go with tensorflow?
<p>I have simple graph in <code>tensorflow</code></p> <pre><code>(1) X = tf.Variable(dtype=tf.float32, shape=(1, 3), name=&quot;X&quot;, initial_value=np.array([[1,2,3]])) (2) y = tf.reduce_sum(tf.square(X)) - 2 * tf.reduce_sum(tf.sin(tf.square(X))) (3) training_op = tf.train.GradientDescentOptimizer(0.3).minimize(y) ...
<p>You have <code>fetches=[X, y, training_op]</code>. These don't respect the order (At least you shouldn't expect <code>sess.run()</code> to respect the order). Which means, all of the,</p> <ul> <li>Evaluates <code>X</code> (so the <code>training_op</code> hasn't happened yet)</li> <li>Evaluate <code>y</code> (still ...
tensorflow
1
9,565
59,797,259
How to read a excel file without taking its first row as header ? Pandas, Python
<p>The excel</p> <pre><code> A B C 1 apple tometo grape 2 beer wine juice </code></pre> <p>Reading by pandas, the first row will be the columns of DataFrame.</p> <pre><code> apple tometo grape 0 beer wine juice </code></pre> <p>How can I read the excel like this: </p> <pre>...
<p>The file can be read using the file name as string or an open file object:</p> <pre><code>pd.read_excel('test.xlsx', index_col=0) </code></pre> <p>if you want to read particular sheet.</p> <pre><code>pd.read_excel(open('test.xlsx', 'rb'),sheet_name='Sheet3') </code></pre> <p>Index and header can be specified via...
python|pandas
2
9,566
61,885,392
Vectorising Pandas - Assigning Column to Array Value using another Column
<p>I have a Pandas Dataframe with some values to match against location data. I want to use values from one of my columns to grab the location datafrom a 2d array, using the column data as an array index.</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'ExistingColumn': [0,2,3,1,2,3,0,0,2,3]}) </code></pre> <p...
<p>If 2d array is <code>arr</code> and same length like column use indexing:</p> <pre><code>arr = np.array([['2_-34.0,140.95.kml', -34.0, -36.425, 143.575, 140.95], ['2_-34.0,143.575.kml', -34.0, -36.425, 146.2, 143.575], ['2_-36.425,140.95.kml', -36.425, -38.849999999999994, 143.575, 140.95], ['2_-36.425,143.575.k...
python|pandas|vectorization
0
9,567
61,990,793
How do I calculate the percentage of a particular response in groupby / pivot table?
<p>Trying to understand groupby and pivot_table better.</p> <p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({"Year": np.random.choice([2017,2018,2019], 1000), "Age":np.random.choice(['&lt;30','30-40','40-50','50+'], 1000), "Pref":np.random.choice(['Yes','No'],...
<pre><code>df.groupby(['Year', 'Age']).agg(lambda x: 100 * sum(i == 'Yes' for i in x) / len(x)) </code></pre>
python|pandas|jupyter-notebook
3
9,568
57,736,792
no attribute '_inbound_nodes' error even when using Lambda layer in Keras
<p>I have a <strong>(28,000 x 300)</strong> dimension matrix, let's call it <strong>label_embedding</strong>, which I want to do a dot product with the bottleneck layer of my model. I have created an architecture which gives a <strong>(batch_size x 300)</strong> at its bottleneck layer.</p> <p>I am using a generator f...
<p>Okay, I solved the problem. So all backend based functions need to be wrapped within the lambda layer. So instead of:</p> <pre><code>out = Lambda(dot_)([x1, K.transpose(inp7)]) </code></pre> <p>and</p> <pre><code>def dot_(tensors): return K.dot(tensors[0], tensors[1]) </code></pre> <p>I wrote:</p> <pre><cod...
tensorflow|keras|dot-product
0
9,569
58,069,691
How to create a train/test split of time-series data by year?
<p>I want to cross-validate my time-series data and split by the year of the timestamp.</p> <p>Here is the following data in a pandas dataframe:</p> <pre><code>mock_data timestamp counts '2015-01-01 03:45:14' 4 . . . '2016-01-01 13:02:14' 12 . . . '2017-01-01 09:56:54' 6 ...
<h2>Updated Response</h2> <p><strong>Generic approach for data with arbitrary number of points in each year.</strong></p> <p>First, some data with a few years of data with differing numbers of points in each, per the example. This is similar in approach to the original answer.</p> <pre class="lang-py prettyprint-overri...
python|pandas|scikit-learn|time-series|cross-validation
6
9,570
54,996,644
Advancing tensorflow dataset iterator in python multiprocessing Queue
<p>Is there any way to move the iterator in this example?</p> <pre><code>import tensorflow as tf import numpy as np from multiprocessing import Process, Queue def store(batch, queue): while True: queue.put(batch) if __name__=='__main__': pqueue = Queue() a1 = np.arange(1000) m = tf.data.Dat...
<h2>Tensorflow multithreading</h2> <p>The iterator is not advancing since you are technically only executing the get_next operation once: <code>sess.run(next_m)</code>. If you were only using tensorflow multithreading, you could have obtained the desired results by simply moving it into the <code>store</code> function...
python|tensorflow|tensorflow-datasets
2
9,571
49,748,902
Tensorflow: DecodeJpeg method gives different pixel values on desktop and mobile for the same image
<p>I have used <code>Tensorflow's</code> <code>DecodeJpeg</code> to read images while training a model. In order to use the same method on an android device, I compiled Tensorflow with Bazel for android with <code>DecodeJpeg</code>.</p> <p>I tried reading the same image on my desktop, which is an <code>x86_64</code> ma...
<p>According to <a href="https://www.tensorflow.org/api_docs/python/tf/image/decode_jpeg" rel="nofollow noreferrer">tensorflow image decode_jpeg documentation</a> I expect that it may be relative to some attribute when you decode the jpeg. Most probably the <code>channels</code> attribute and/or the <code>ratio</code> ...
android|tensorflow|arm|libjpeg
0
9,572
49,756,488
Defining different pandas xlsxwriter border types
<p>I would like to define different strengths for bottom-borders with xlsxwriter. My question is: How can I prevent the thick-bottom-HEADER-border from being overwritten in the example below? I would like to note, that if I start one row later with the conditional format, I get one row without bottom borders.</p> <pr...
<p>I've provided a workaround below. I added another conditional format for the second row only called 'format2'. It sets the top of the cells with the thick border and the bottom with the dotted lines.</p> <pre><code>import numpy as np import pandas as pd dates = pd.DataFrame(pd.date_range('2000-01-01', periods = 1...
python|pandas|xlsxwriter
4
9,573
49,756,909
InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1'
<p>I trained a simple neural network with TensorFlow on the MNIST dataset. The training portion of the code works fine. However, when I feed a single image into the network, it gives me the following traceback:</p> <pre><code>Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/...
<p>Your feed_dict only put value for the x and not for the label. you should also put for the y place_holder i.e.: {x:image, y:val}</p>
python|python-3.x|tensorflow|neural-network|invalid-argument
0
9,574
49,452,316
Numpy array: get upper diagonal and lower diagonal for a given element
<pre><code>import numpy square = numpy.reshape(range(0,16),(4,4)) square array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) </code></pre> <p>In the above array, how do I access the primary diagonal and secondary diagonal of any given element? For example 9.</p> <p>by...
<p>Base on your description, with <code>np.where</code>, <code>np.diagonal</code> and <code>np.fliplr</code></p> <pre><code>import numpy as np x,y=np.where(square==9) np.diagonal(square, offset=-(x-y)) Out[382]: array([ 4, 9, 14]) x,y=np.where(np.fliplr(square)==9) np.diagonal(np.fliplr(square), offset=-(x-y)) # ba...
python|arrays|numpy
2
9,575
73,410,542
Shifting every second value in a column to a new column for each unique index in pandas
<p>I have a large pandas dataframe as follows.</p> <p><strong>Input df</strong></p> <pre><code>member_id attribute1 1 AM 1 A 26 TSE 26 TSA 26 TSE ---- 97736 TMA 97736 TTE 97736 TMA 97736 ALM </code></pre> <p>Is there any way I can effi...
<p>Try:</p> <pre><code># shift the rows up df['attribute2'] = df.groupby('member_id')['attribute1'].shift(-1) # drop the last row for each `member_id` df = df[df['member_id'].duplicated(keep='last')] </code></pre> <p>Output:</p> <pre><code> member_id attribute1 attribute2 0 1 AM A 2 ...
python|pandas|dataframe|numpy|data-analysis
1
9,576
67,348,721
if condition using sympy equation solver/ sympy very slow
<p>I want to solve this equation witht the following parameters:</p> <pre><code>gamma = 0.1 F = 0.5 w = 0 A = symbols('A') a = 1 + w**4 -w**2 + 4*(gamma**2)*w**2 b = 1 - w**2 sol = solve(a*A**2 + (9/16)*A**6 + (3/2)*b*A**4 -F**2) list_A = [] for i in range(len(sol)): if(type( solutions[i] )==float ): pri...
<p>When it is able to validate solutions relative to assumptions on symbols, it will; so if you tell SymPy that <code>A</code> is real then -- if it can verify the solutions -- it will only show the real ones:</p> <pre><code>&gt;&gt;&gt; A = symbols('A',real=True) &gt;&gt;&gt; sol = solve(a*A**2 + (9/16)*A**6 + (3/2)*b...
python|list|numpy|sympy
1
9,577
60,011,722
How to chart aggregated time series data with matplotlib
<p>I have a csv file of errors with the timestamp of when each error occurred. Sample data looks like this</p> <pre><code>2020-01-06T02:54:01.012+0000, 500 Internal Server Error 2020-01-06T05:04:01.012+0000, 500 Internal Server Error 2020-01-06T05:44:01.012+0000, 500 Internal Server Error 2020-01-06T07:04:01.013+0000,...
<p>Start from defining the following fuction:</p> <pre><code>def counts(grp): codeList = ['500', '502', '503'] return pd.Series([np.count_nonzero(grp.eq(code)) for code in codeList], index=map(lambda x: 'Err_' + x, codeList)) </code></pre> <p>It will be applied soon, to each group resulting from resam...
python|pandas|datetime|matplotlib|timeserieschart
1
9,578
60,080,700
Is there any way to remove BatchToSpaceND from tf.layers.conv1d?
<p>As I get, tf.layers.conv1d uses pipeline like this: BatchToSpaceND -> conv1d -> SpaceToBatchND. So the question is how to remove (or disable) BatchToSpaceND and SpaceToBatchND from the pipeline?</p>
<p>As I've investigated it's impossible to remove BatchToSpaceND and SpaceToBatchND from tf.layers.conv1d without changing and rebuilding tensorflow source code. One of the solutions is to replace layers to tf.nn.conv1d, which is low-level representation of convolutional layers (in fact tf.layers.conv1d is a wrapper ar...
python|tensorflow|conv-neural-network
0
9,579
59,924,179
Could anyone explain the return of linalg.lstsq in details?
<p>Though the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html" rel="nofollow noreferrer">linalg.lstsq document</a> is offered. I still feel hard to understand since it is not quite detailed. </p> <blockquote> <p>x : {(N,), (N, K)} ndarray</p> <p>Least-squares solution. If b...
<p>Those tuples are the possible shapes of inputs and outputs. In your example, <code>A.shape = (4, 2)</code> and <code>y.shape = (4,)</code>. Looking at the documentation, <code>M = 4</code>, <code>N = 2</code>, and we are dealing with the cases without <code>K</code>. So the output's shapes should be <code>x.shape = ...
python|numpy|least-squares
4
9,580
65,382,902
How to iteratively call a variable which was defined iteratively in python
<p>I have iteratively define a variable containing x-coordinates as follows</p> <pre><code>import numpy as np xCoords = {&quot;%s&quot; % i: np.array([math.cos(2*math.pi*i/360),0,0,0,0,0,0,0,0,0], dtype = int) for i in range(0, 360)} </code></pre> <p>However, the <code>i</code> in <code>math.cos(2*math.pi*i/360)</code>...
<p>The <code>i</code> is actually iterating over the values as expected. The problem here is that you take as <code>dtype</code> <code>int</code>, which causes all values to be casted to an integer. If the value is between 0 and 1 this will result in 0.</p> <p>If you use for instance <code>float</code> you will not hav...
python|numpy
1
9,581
65,178,675
How to filter Delimited Variable using Pandas
<p>My Input Dataframe is</p> <pre><code>list_of_dicts1 = {&quot;Filter&quot;:[&quot;c&quot;,'a|b']} test1 = pd.DataFrame(list_of_dicts1) list_of_dicts2 = {&quot;C&quot;:[&quot;d&quot;,'a', 'b']} test2 = pd.DataFrame(list_of_dicts2) </code></pre> <p>Output Desired is</p> <pre><code>list_of_dicts3 = {&quot;C&quot;:['a', ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> with split and explode values splitted by <code>|</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html" rel="nofoll...
python|pandas|filter
1
9,582
65,316,550
GPyTorch, how to set initial value for "lengthscale" hyperparameter?
<p>I am using GPyTorch regressor according to the <a href="https://docs.gpytorch.ai/en/stable/examples/01_Exact_GPs/Simple_GP_Regression.html" rel="nofollow noreferrer">documentation</a>.</p> <p>I would like to set an initial value for the &quot;lengthscale&quot; hyperparameter in RBF kernel.</p> <p>I want to set a con...
<p>There are two cases that follow from your question:</p> <ol> <li><p><strong>You want to initialize your lengthscale with some value but the lengthscale is then optimized on further by the optimizer</strong></p> <p>Assuming you have the same model as given in the documentation you have linked, just add the following ...
kernel|hyperparameters|gpytorch
6
9,583
65,092,750
Transformers for action recognition: Resource exhausted
<p>I am trying to adapt a transformers code from <a href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/text/transformer.ipynb" rel="nofollow noreferrer">https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/text/transformer.ipynb</a> and use it ...
<p>Your sequence is too long: in transformer every element is attended to each other. As a result - you have to allocate a huge tensor ~8GB. Transformer is too complicated and needs a lot of memory for running. Looks like 24GB is not enough. Try less sequence length.</p>
tensorflow|machine-learning|keras
0
9,584
50,170,030
Python pandas Dataframe Regex
<p>I need a RegEx that can detect if the value of a cell in pandas dataframe is on the right date format. The value of the cell should be formatted like this "2018-04-01T06:21:48+00:00".</p> <p>Thanks,</p> <p>Peter</p>
<p>I think the following would match the format you are looking for:</p> <pre><code>\d{4}-\d{2}-\d{2}[T]\d{2}:\d{2}:\d{2}[+]\d{2}:\d{2} </code></pre> <p>From a high level </p> <ul> <li>\d{4} matches 4 digit</li> <li>\d{2} matches 2 digits</li> <li>[T] matches only the 'T' character</li> <li>[+] matches only the '+' ...
python-3.x|pandas
0
9,585
49,943,437
Truncated Backpropagation for Many-to-One RNN
<p>I have been looking at this article on RNNs:</p> <p><a href="https://medium.com/@erikhallstrm/hello-world-rnn-83cd7105b767" rel="nofollow noreferrer">https://medium.com/@erikhallstrm/hello-world-rnn-83cd7105b767</a></p> <p>But, my interest is in a many-to-one RNN. So I am confused in how to apply truncated back pr...
<p>Here is a post by Danijar that implements the many to one rnn in tensorflow. <a href="https://danijar.com/introduction-to-recurrent-networks-in-tensorflow/" rel="nofollow noreferrer">https://danijar.com/introduction-to-recurrent-networks-in-tensorflow/</a> Regarding the dynamic time steps, the <code>dynamic_rnn()</c...
tensorflow|neural-network|recurrent-neural-network|rnn
0
9,586
64,035,274
Train Object Detection Module Using Tensorflow
<p>When I am executing the following command to train model using tenserflow, I got below errors.</p> <p><strong>Command</strong> :</p> <pre><code>python legacy/train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config </code></pre> <p><strong>Errors</strong> :</p...
<p>Probably <em>tf-slim</em> package is not installed in your python environment. Try running below command in the conda prompt</p> <pre><code>pip install tf-slim </code></pre>
python|tensorflow
0
9,587
47,008,007
Panda- how can I conver dataframe in to table format?
<p>This is my output in Pandas from CSV file.</p> <pre> Total Schools Total Students Total Budget Average Math score Average Reading score 15 39,170 $24,649,428 78.99 81.88 </pre> <pre> d = {'Total Schools': [school_df['name'].count()], 'Total Students': [student_d...
<h2>If you want to save to csv and look at it in excel or openoffice</h2> <p>if by table format you mean a csv. then just do</p> <p><code>school_summary.to_csv(FILEPATH)</code></p> <p>where FILEPATH is where you want to save your new csv file (like <code>FILEPATH = r'C:\My Documents\myfile.csv'</code> if you're using w...
pandas|dataframe
0
9,588
62,973,586
DataFrame : Compare dates from two different columns
<p>Compare dates from different columns in a same day.</p> <p>df</p> <pre><code> a b 0 2020-07-17 00:00:01.999 2020-07-17 12:00:01.999 1 2020-06-15 13:14:01.999 2020-02-14 12:00:01.999 2 2020-09-05 16:14:01.999 2020-09-05 11:59:01.999 3 2020-11...
<p>Convert the datetime to datetime objects either by using <code>pd.to_datetime</code> or while reading from csv. Then use <code>dt.date</code> function to compare the dates</p> <pre><code>In [22]: df = pd.read_csv(&quot;a.csv&quot;, parse_dates=[&quot;a&quot;,&quot;b&quot;]) In [23]: df Out[23]: ...
python|pandas|numpy|dataframe
2
9,589
63,302,644
Add and fill missing columns with values of 0s in pandas matrix [python]
<p>I have a matrix of the form :</p> <pre><code>movie_id 1 2 3 ... 1494 1497 1500 user_id 1600 1.0 0.0 1.0 ... 0.0 0.0 1.0 1601 1.0 0.0 0.0 ... 1.0 0.0 0.0 1602 0.0 0.0 0.0 ... 0.0...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> along <code>axis=1</code> with <code>fill_value=0</code> to conform the dataframe columns to a new index range:</p> <pre><code>df = df.reindex(range(df.c...
python|pandas|matrix|indexing
1
9,590
62,932,315
How to build new columns based on the unique initial letters from a dataframe pandas
<p>I have thousands of hostname, those i want to be assigned into different columns based on their first initial three letters. I see this can be done if its small list ans i know the initial letters but i have huge list.</p> <p>I have google a lot but did not get any proper hint, tried <code>df.assign</code> but that'...
<p><code>cumcount</code> with <code>.groupby</code> of the first 3 characters in your column returns <code>0,1,2,3,4</code> for each group of letters. From there, pivot the dataframe and change the column headers:</p> <pre><code>df['a'] = df['hostnames'].str[0:3] df['index'] = df.groupby(['a'])['a'].transform('cumcount...
python-3.x|linux|pandas|dataframe
2
9,591
61,321,195
Pandas dataframe not acting as expected once deployed to heroku (Django project)
<p>I have created a program which does data entry and returns a pandas table (the info is saved in a list, called JOB_INFO, at the top of the views.py file - I will attach this below) with some results which can be downloaded. I also have the table rendering on the html page that has the data entry form - the table ren...
<p>I managed to solve this issue by replacing the JOB_INFO list with a new Django Model with the same field names, like this:</p> <pre><code>from django.db import models class JobInfoReport(models.Model): """The following are prefixed with 'r' to represent report""" r_plentific_job_number = models.CharField(max_leng...
python|django|pandas|heroku
0
9,592
61,581,409
Custom Aggregation on Fields in Data Frame
<p>I have a data frame like:</p> <pre><code>time action value -------------------------- 10:00 FG 2 10:00 Ast 0 09:45 Miss 0 09:40 TO 0 09:40 Steal 0 09:30 FG 2 09:30 FT 1 </code></pre> <p>I would like to group this off <code>time</code>, but in two diffe...
<p>Use <code>groupby.agg</code> :</p> <pre><code>df = df.groupby('time', as_index=False).agg({'action':list, 'value':np.sum}) print(df) time action value 0 09:30 [FG, FT] 3 1 09:40 [TO, Steal] 0 2 09:45 [Miss] 0 3 10:00 [FG, Ast] 2 </code></pre>
python|pandas|pandas-groupby
2
9,593
61,477,586
How to use apply and lambda to set value to a dataframe column based on the index matching another column in a second dataframe
<p>I have the following two dataframe </p> <pre><code>df1: item_id height weight 13 19902 1.56 54 28 20503 1.7 30 df2: height_2 weight_2 size-&gt; (not supposed to be modified) item_id 19902 1 50 8 20503 2 30 10 expected output: df2: heig...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html" rel="nofollow noreferrer"><code>DataFrame.update</code></a> with convert <code>item_id</code> to index by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofol...
python|pandas
0
9,594
61,420,721
Function that will go though a column, if the number is above 0 return column name, but when is 0 return "Not Available'
<p>I need some help.</p> <p>Let's say I have the below dataframe called <strong>venues_df</strong></p> <p><a href="https://i.stack.imgur.com/wAFJw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wAFJw.jpg" alt="enter image description here"></a></p> <p>I also have this function: <strong>return_mos...
<pre><code>def return_most_common_venues(df, row, cols): # Selects the row values row_values = df.loc[row] # Sorts the selected row values row_values_sorted = row_values[np.argsort(row_values)[-cols:]][::-1] # Returns the column name of the first 4 sorted values return [index if value &gt; 0...
python|arrays|pandas|function
0
9,595
61,535,668
how to Split data in 3 folds (train,validation,test) using ImageDataGenerator when data is in different directories of each class
<p>How do I split my data into 3 folds using <code>ImageDataGenerator</code> of Keras? <code>ImageDataGenerator</code> only gives <code>validation_split</code> argument so if I use it, I wont be having my test set for later purpose. </p> <p>My data is in the form of</p> <pre><code>&gt;input_data_dir &gt;class_1_dir ...
<p>A much better alternative is to use split-folders library. It will create train, validation and test set folders for you.</p> <p><strong>source</strong> - <a href="https://stackoverflow.com/questions/53074712/how-to-split-folder-of-images-into-test-training-validation-sets-with-stratified">How to split folder of ima...
tensorflow|keras|tensorflow2.0|tf.keras
2
9,596
68,448,206
Subtract and add values based on specific condition, considering baseline values
<p>I have a dataframe, where I would like to transform based on grouping ids, count and sum.</p> <pre><code>pod date1 pwr1 pwr2 position aa q122 2 2 100 aa q122 0 4 100 bb q122 5 0 50 bb q122 5 0 50 bb q222 0 0 50 bb q322 0 ...
<p>Try <code>(x['pwr2'] !=0).values.sum()</code> instead of <code>x['pwr2'].count()</code></p> <p>Corrected code:</p> <pre><code>def f(x): d = {'con': [x['pwr1'].sum()], 'retro': [x['pwr2'].sum()], 'final': [x['pwr1'].sum() - x['pwr2'].sum()], 're_space': [(x['pwr2'] !=0).values.sum() - (...
python|pandas|numpy
2
9,597
53,007,095
WRN Install python-prctl so that processes can be cleaned with guarantee
<p>I am getting this Warning "WRN Install python-prctl so that processes can be cleaned with guarantee." though I have installed 'python-prctl' from <a href="https://pythonhosted.org/python-prctl/" rel="nofollow noreferrer">this</a> site. But still getting this warning, I am using tensorpack to load data quickly by usi...
<p>Oh, a three year old question. I assume you've already solved it, but I'll tell how I did it.</p> <p>This warning means the package was not found, and it is generated by this function: <code>enable_death_signal(_warn=True)</code></p> <p><a href="https://tensorpack.readthedocs.io/en/latest/_modules/tensorpack/utils/c...
python-3.x|tensorflow
0
9,598
53,233,782
Problems with tensorflow hub: Table not initialized
<p>I am trying to use tf_hub for universal-sentence-encoder-large when I have the following problem:</p> <pre><code>FailedPreconditionError (see above for traceback): Table not initialized. </code></pre> <p>It seems that TensorFlow thinks I did not run init op, but actually, I have run the init op:</p> <pre><code>em...
<p>Looks like to use this tensorflow hub, I need to run an addtional initializer:</p> <pre><code>init = tf.global_variables_initializer() table_init = tf.tables_initializer() with tf.Session() as sess: sess.run([init, table_init]) embeddings_ = sess.run(embeddings) print(embeddings) </code></pre>
tensorflow|tensorflow-hub
3
9,599
53,232,258
Find the row associated with maximum date after groupby in Pandas
<p>I have a pandas DataFrame with 3 columns containing a PERSON_ID, MOVING_DATE AND PLACE as follows:</p> <pre><code>df = pandas.DataFrame( [[1,datetime.datetime(2018, 1, 1), 'New York'], [1, datetime.datetime(2018, 1, 20), 'Rio de Janeiro'], [1, datetime.datetime(2018, 2, 13), 'London'], [2, datetime.datetime(201...
<p>A one-liner using <code>DataFrame.groupby</code> and <code>Grouper.last</code>:</p> <pre><code>df.sort_values('MOVING DATE').groupby('PERSON ID').last() </code></pre> <p>output:</p> <pre><code> MOVING DATE PLACE PERSON ID 1 2018-02-13 London 2 2017-06-12 S...
python|pandas|pandas-groupby
16