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
368,000
72,187,147
How does pandas.DataFrame.replace works?
<p>I need to remove '$' symbol in 'price' column. I used pd.DataFrame.replace to do that.</p> <p><a href="https://i.stack.imgur.com/ZiYAi.png" rel="nofollow noreferrer">replace result.</a></p> <p>Why did nothing happen?</p> <p>If I use str.replace it works: <a href="https://i.stack.imgur.com/s3mw5.png" rel="nofollow no...
<p>Try this :</p> <pre><code>listings['price'].str.replace({'$':''},regex=True,inplace=True) </code></pre>
python|pandas|replace
0
368,001
72,237,585
Dataframe new columns to tell if the row contains column's header text
<p>2 columns dataframe as the first screenshot. I want to add new columns (by the contents in the Note column from the original dataframe) to tell if the Note column contains the new column's header text.</p> <p>Example as the second screenshot.</p> <p><a href="https://i.stack.imgur.com/PDXzx.png" rel="nofollow norefer...
<p>You can try <code>.str.get_dummies</code> then replace <code>1</code> with <code>Yes</code></p> <pre class="lang-py prettyprint-override"><code>df = df.join(df['Note'].str.get_dummies(', ').replace({1: 'Yes', 0: ''})) </code></pre> <pre><code>print(df) Name Note Bright Considerate Friendly Kin...
python|pandas|dataframe
2
368,002
72,187,066
Subtract values in a column in blocks
<p>Suppose there is the following dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Group': ['A', 'A', 'B', 'B', 'C', 'C'], 'Value': [1, 2, 3, 4, 5, 6]}) </code></pre> <p>I would like to subtract the values from group B and C with those of group A and make a new column with the difference. That is,...
<p>Assuming you want to subtract the first A to the first B/C, second A to second B/C, etc. the easiest might be to reshape:</p> <pre><code>df2 = (df .assign(cnt=df.groupby('Group').cumcount()) .pivot('cnt', 'Group', 'Value') ) # Group A B C # cnt # 0 1 3 5 # 1 2 4 6 df['new_col'] = df2.s...
python|pandas
0
368,003
72,432,747
Input layer 0 of sequence is incompatible with the layer - CNNs
<p>I am trying to create a CNN model using hyperparameterization for image classification. When I run the code I receive the following error:</p> <blockquote> <p>ValueError: Input 0 of layer &quot;sequential&quot; is incompatible with the layer: expected shape=(None, 32, 32, 32, 3), found shape=(32, 32, 32, 3)</p> </bl...
<p>You are getting this error due the input shape mismatch.</p> <p>Here i have implemented the hypermodel on the mnist fashion dataset which contains images of shape (28,282,1).</p> <pre><code>def build_model(hp): model = tf.keras.Sequential([ tf.keras.Input(shape=(28,28,1)), # adding first conv2d layer tf.kera...
tensorflow|conv-neural-network|valueerror
0
368,004
72,298,530
how can I solve RunTimeError of input and batch size?
<p>**</p> <h2>my input (feature) contains 1 column and 12454 rows whereas my target (label) contains 2 columns and 12454 rows and here's my full code:</h2> <h2>**</h2> <pre><code>import pandas as pd import numpy as np from numpy import genfromtxt import torch.nn as nn import torch from torch.utils.data import TensorDat...
<p>The Query is based upon the error due to the dimension mismatch during matrix multiplication.<br> Hence try to reshape the input before you put it in the model.</p> <pre><code>import pandas as pd import numpy as np from numpy import genfromtxt import torch.nn as nn import torch from torch.utils.data import TensorDat...
python|python-3.x|machine-learning|pytorch
0
368,005
72,211,891
How to count the occurrences of certain rows in a column from Python dataframe
<p>So I have a dataframe of wildfires in California by county. It looks a little something like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Year</th> <th style="text-align: center;">Counties</th> <th style="text-align: center;">Name</th> </tr> </thead> <tbod...
<p>Ideally filter before counting the values:</p> <pre><code>df.loc[df['Counties'].isin(relevant_counties), 'counties'].value_counts() </code></pre> <p>Unless you plan on reusing the counts with various lists of counties:</p> <pre><code>counts = df['counties'].value_counts() counts[relevant_counties] counts[relevant_...
python|pandas|dataframe|class
1
368,006
72,180,114
How to compare 2 dataframes and then output an ID to inform if a row has changed?
<p>I have 2 dataframes:</p> <p><code>df1 = pd.DataFrame({&quot;id1&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;], &quot;id2&quot;: [&quot;1&quot;, &quot;2&quot;, &quot;2&quot;, &quot;1&quot;], &quot;id3&quot;: [&quot;33&quot;, &quot;232&quot;, &quot;343&quot;, &quot;555&quot;]})</code></p> <p><cod...
<p>You can <code>merge</code> and build a boolean mask that returns True if a value didn't change (or was expanded) and <code>map</code> Y/N values according to it:</p> <pre class="lang-py prettyprint-override"><code>df2 = df2.merge(df1, on='id1', how='left', suffixes=('_','')) df2['Modified_ID'] = (df2['id2_'].eq(df2[...
python|pandas|dataframe
1
368,007
72,338,056
Can we fill missing values of different columns in a pandas dataframe in two/three lines of code
<p>I hope you are doing well. I am dealing with a steel dataset having different attributes. I wanted to fill their missing values with their mean. However, rather than doing it separately I want to do it with in two or three lines of codes in a single go. I am trying the following code:</p> <pre><code>empty_list = [] ...
<p><code>empty_list</code> here is not what you intend it to be. You should say</p> <pre><code>empty_list += list(df.columns[df.isnull().any()]) </code></pre> <p>or</p> <pre><code>empty_list = df.columns[df.isnull().any()], </code></pre> <p>depending on whether <code>empty_list</code> previously had any values in it.<...
python|pandas|dataframe|data-science
0
368,008
72,258,453
Fast pandas indexing: select on multiple columns for each date in date_range
<p>Given a large dataframe (&gt; 5.000.000 rows), with two datetime columns and an ID column:</p> <pre><code>df.head() ACQ START ID 0 2020-10-19 09:00:04.000 2020-10-19 16:00:07.800 0 1 2020-10-19 12:00:00.000 2020-10-19 16:00:07.800 2 2 2020-10-20 09:00:14.400 2020-...
<p>You can use:</p> <pre><code># START ≥ start_date ACQ ≤ end_date (df['START'].ge(start_date) &amp; df['ACQ'].le(end_date)).groupby(df['ID']).sum() </code></pre> <p><em>NB. use <code>gt</code> and <code>lt</code> for a strict comparison (after/before not including the date itself)</em></p> <p>output:</p> <pr...
python|pandas|dataframe|indexing
0
368,009
72,292,907
Filter data in pandas by a string date
<p>I have a DataFrame that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Parameter</th> </tr> </thead> <tbody> <tr> <td>2010-01-02</td> <td>some value</td> </tr> <tr> <td>2010-01-03</td> <td>some value</td> </tr> <tr> <td>2010-01-04</td> <td>some value</td> ...
<p><code>DataFrame.query</code> expects you to reference column names; <code>df.query('Date &lt; limit_date')</code> is trying to query rows where the value in the <code>'Date'</code> column is less than the value in the <code>'limit_date'</code> column. (How would it know <code>'Date'</code> is a column but <code>limi...
python|pandas|dataframe|bigdata
0
368,010
72,151,498
Unable to crop mask from original image
<p>I'm trying to remove the background from an image. For that, I'm using TensorFlow which provides me mask of an object. After that, I'm cropping the mask from the image but the result is not as good as I wanted.</p> <p>Using <code>TensorFlow</code> for <strong>masking</strong>: <a href="https://github.com/tensorflow/...
<p>After cropping the mask from an original bitmap. I'm SRC_OVER the result bitmap twice which hides the <strong>transparency</strong> issue.</p> <pre><code>fun creatingMasking(original: Bitmap?, mask: Bitmap?): Bitmap? { return try { var result: Bitmap? = mask?.let { ori...
android|tensorflow|kotlin
0
368,011
72,285,666
np.where: and condition over multiple columns of a 2d array
<p>I would like to use np.where on a array (arr) in order to retrieve the indices corresponding to the following condition: first column value must be <strong>1</strong>, third column value must be <strong>two</strong>, here is my code so far:</p> <pre><code>arr = np.array([ [0,0,0], [1,0,2], [0,0,0], [...
<p>This is an issue of operator precedence, you need to use parentheses:</p> <pre><code>np.where((arr[:,0]==1)&amp;(arr[:,2]==2)) </code></pre> <p>A more generic method (imagine you have 20 columns to compare) would be to use:</p> <pre><code>np.where((arr[:,[0,2]]==[1,2]).all(1)) </code></pre> <p>output: <code>(array([...
numpy
2
368,012
72,196,425
Identifying near duplicate keywords and replacing them
<p>I have a dataframe like as shown below</p> <pre><code>ID,Name,year,output 1,Test Level,2021,1 2,Test Lvele,2022,1 2,dummy Inc,2022,1 2,dummy Pvt Inc,2022,1 3,dasho Ltd,2022,1 4,dasho PVT Ltd,2021,0 5,delphi Ltd,2021,1 6,delphi pvt ltd,2021,1 df = pd.read_clipboard(sep=',') </code></pre> <p>My objective is</p> <p>a)...
<p>I suggest using a <code>dict</code> instead of a <code>pandas.DataFrame</code> for <code>map_df</code>.</p> <pre class="lang-py prettyprint-override"><code>ID,Name,year,output 1,Test Level,2021,1 2,Test Lvele,2022,1 2,dummy Inc,2022,1 2,dummy Pvt Inc,2022,1 3,dasho Ltd,2022,1 4,dasho PVT Ltd,2021,0 5,delphi Ltd,2021...
python|pandas|dataframe|nlp|nltk
2
368,013
72,391,840
If values in multiple columns match another dataframe, get sum based on range of dates pandas
<p>I have a two dfs:</p> <p><code>df1</code>:</p> <pre><code> item_code store_code start_1 end_1 0 11185 01 2022-03-06 2022-03-08 1 11185 02 2022-03-26 2022-03-28 2 118113 01 2022-02-02 2022-02-04 3 118113 02 2022-04-29 2022-04-30 4 ...
<p>You can use <code>merge</code> and <code>query</code>:</p> <pre><code>out = (df1.merge(df2, how='left', suffixes=('', '_')) .query('(start_1 &lt;= date_code) &amp; (date_code &lt;= end_1)') .groupby(df1.columns.tolist(), as_index=False, sort=False) ['sales_sum'].sum()) print(out) # Out...
python|pandas|datetime|sum|conditional-statements
1
368,014
72,174,683
Restructuring the Pandas dataframes
<p>I have a dataframe as follows:</p> <pre><code> A B C D E F timestamp 2022-05-09 11:28:00 15 45 NaN NaN 3.0 100 2022-05-09 11:28:01 5.0 20 3.0 25 NaN NaN 2022-05-09 11:28:02 NaN NaN 5.0 35 15 ...
<p>Try:</p> <pre><code>#reset_index if timestamp is the index instead of a column df = df.reset_index() #rename columns for compatibility with wide_to_long df.columns = [&quot;timestamp&quot;, &quot;Col1&quot;, &quot;Val1&quot;, &quot;Col2&quot;, &quot;Val2&quot;, &quot;Col3&quot;, &quot;Val3&quot;] #change from wide...
python|pandas|dataframe
1
368,015
72,145,226
Dividing a large file into smaller ones for training
<p>I have a very large file and I want to divide it into smaller ones for training. I've read about pickle files, so I split the large file into training-validation. Then, I divided the training file (about 1000000 datapoints) into ~60 pickle files. The testing file was divided into 5 pickles files.</p> <p>Now I am con...
<p>You should look into Tensorflows <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow noreferrer">data api</a>, specifically the tfrecords datatype. That might be easier to use than separate pickle files, since they are directly integrated into tensorflows data loaders.</p> <p>If you re...
python|tensorflow|machine-learning|keras|neural-network
0
368,016
72,398,324
How to get a new column count number of time appear of a date
<p>I have this dataframe with this datatypes</p> <pre><code> Date Time 0 2022-05-20 17:07:00 1 2022-05-20 09:14:00 2 2022-05-19 18:56:00 3 2022-05-19 13:53:00 4 2022-05-19 13:52:00 ... ... ... 81 2022-04-22 09:53:00 82 2022-04-20 18:20:00 83 2022-04-20 12:53:00 84 2022-04-20 12:12:00 85...
<p>You can use <code>nunique</code>:</p> <pre><code>df['count'] = df.groupby('Date').transform('nunique') print(df) # Output Date Time count 0 2022-05-20 0 days 17:07:00 2 1 2022-05-20 0 days 09:14:00 2 2 2022-05-19 0 days 18:56:00 3 3 2022-05-19 0 days 13:53:00 3 4 2022-0...
python|pandas|dataframe|date
0
368,017
72,187,686
Exception when converting Unet from pytorch to onnx
<p>I'm trying to convert a Unet model from PyTorch to ONNX.</p> <p>Running the following code:</p> <pre><code>import torch from unets import Unet, thin_setup net = Unet(in_features=3, down=[16, 32, 64, 64, 64], up=[64, 64, 64, 128 + 1], setup={**thin_setup, 'bias': True, 'padding': True}) net.eval() inputs...
<p>The problem is due to ONNX not having an implementation of the PyTorch 2D Instane Normalization layer. The solution was to copy the relevant UNet code and implement the layer myself:</p> <pre><code>class InstanceNormAlternative(nn.InstanceNorm2d): def forward(self, inp: Tensor) -&gt; Tensor: self._check...
python|pytorch|torch|onnx
1
368,018
72,484,101
Trying to extract table with hyperlinks from URL and save it in Excel [Python]
<p>I'm trying to extract the table from the URL and save hyperlinks also. Current code saves the table to Excel, but the hyperlinks are not saved. I know it's because <code>pd.read_html</code> extract data as text. How can I extract it with hyperlinks also?</p> <p>Current code:</p> <pre><code>from selenium import webdr...
<pre><code>urls=[x.get_attribute(&quot;href&quot;) for x in driver.find_elements(By.XPATH,&quot;//a[@href and text()='Report']&quot;)] </code></pre> <p>To get all 78 href values with the text Report you can do the above.</p>
python|excel|pandas|selenium
1
368,019
72,473,795
Calculate dates between today and pandas dataframe
<p>I am trying to subtract the date of today of a date set in a pandas dataframe. <br></p> <p>Example data frame : <br> 8 Emma Mike 1 2018/5/21 1654160303.597019<br /> 12 Emma Mike 3 2018/6/03 1654160303.597019<br /> 13 Emma Mike 1 2018/8/03 1654160303.597019<br /> 16 Emma ...
<p>I think need subtract today by original column converted to datetimes, if need days in numeric add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.days.html" rel="nofollow noreferrer"><code>Series.dt.days</code></a>:</p> <pre><code>time_difference = (pd.Timestamp.now().normalize(...
python|pandas|dataframe|timestamp
0
368,020
72,287,341
dataframe apply += if index does not exist
<p>For a dataframe, we know that</p> <pre><code>df.loc['a', 'col1'] = 1 </code></pre> <p>If index <code>'a'</code> does not exist, it will automatically create a row with index <code>'a'</code> and set column <code>col1</code> = 1. But it seems not work for</p> <pre><code>df.loc['a', 'col1'] += 1 </code></pre> <p>How t...
<p>Here is one way to do it:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame() # Empty dataframe </code></pre> <pre class="lang-py prettyprint-override"><code>def add_assign(df, idx, col): &quot;&quot;&quot;Define a helper function. &quot;&quot;&quot; try: ...
python|pandas|dataframe|dictionary
0
368,021
72,159,048
Print column and row name of cell if cell in table is greater than 0 using python pandas
<p>I am having trouble to retrive name of column and row of cell in a table</p> <p>my scenario is- if any element in my table is greater than 0 then print its column and rows name</p> <p>example i have attached a photo of my table i need to print date and slot time of cell if any cell is greater than 0</p> <p>response ...
<p>You can stack the columns first, then loop through each row and print rows that meet the requirement:</p> <pre><code># creating similar dataframe cols = [&quot;slot1&quot;, &quot;slot2&quot;, &quot;slot3&quot;, &quot;slot4&quot;, &quot;slot5&quot;, &quot;slot6&quot;, &quot;slot7&quot;, &quot;slot8&quot;] df = pd.Dat...
python|python-3.x|pandas|dataframe|html-table
0
368,022
72,322,428
how to replace NaN using lambda
<p>I have dataframe like this:</p> <pre class="lang-py prettyprint-override"><code>dict={'priorSaleYear':[2004, np.NaN],'lastSaleYear':[2008, 2009]} df=pd.DataFrame(dict, index=[1,2]) </code></pre> <p>I want to replace the np.nan with the lastSaleYear minor a number:</p> <pre class="lang-py prettyprint-override"><code>...
<p>You did not clarify if there are more than one continuous <code>NaN</code> how the fill should be. Here, I assume that for all <code>NaN</code>, they will use the most recent available value.</p> <pre><code>df['priorSaleYear'] = df['priorSaleYear'].ffill() </code></pre>
pandas
0
368,023
72,311,207
How to align two columns on their values with exact match?
<p>This is a little complicated, but I basically need to align the data from a second dataframe to the values of the first dataframe(DF). The first DF has different versions of the right name and the second DF has the correct names. The final product should have the original names with a column next to it with the corr...
<p>If what you want is to clean up <code>data1</code> and find the exact match in <code>data2</code>, you can try this:</p> <pre class="lang-py prettyprint-override"><code>data1[&quot;Cleaned&quot;] = ( data1[&quot;Name&quot;].str.replace(r&quot;\(|\)&quot;, &quot; &quot;, regex=True) .str.replace(&quot; {2,}&q...
python|pandas|dataframe
1
368,024
72,405,223
What is the difference between statistics.stdev() & numpy.std() and which is more precise?
<p>I used this dataset:</p> <pre><code>lst = [81922.00557103065, 82887.70053475935, 80413.01627033792, 81708.86075949368, 82997.38219895288, 84641.50943396226, 81929.82456140351, 82632.24181360201, 77667.98418972333, 73726.47427854454, 86113.2075471698, 83232.98429319372, 79866.66666666667, ...
<p><strong>They are calculating two slightly different things.</strong></p> <p>The standard deviation is the square root of the <a href="https://en.wikipedia.org/wiki/Variance" rel="nofollow noreferrer">variance</a>. NumPy is using the sample variance, whereas <code>statistics</code> is adjusting this with <a href="htt...
numpy|statistics|std|stdev
0
368,025
72,249,268
Pandas drop rows lower then others in all colums
<p>I have a dataframe with a lot of rows with numerical columns, such as:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> </tr> </thead> <tbody> <tr> <td>12</td> <td>7</td> <td>1</td> <td>0</td> </tr> <tr> <td>7</td> <td>1</td> <td>2</td> <td>0</td> <...
<p>An more memory-efficient and faster solution than the one proposed so far is to use <strong>Numba</strong>. There is no need to create huge temporary array with Numba. Moreover, it is easy to write a <em>parallel implementation</em> that makes use of all CPU cores. Here is the implementation:</p> <pre class="lang-py...
python|pandas|optimization
7
368,026
72,404,872
Remove rows in a 2d-numpy array if they contain a specific element
<p>I have a matrix as 2d-np.array and I would like to remove all rows that contain an element x in a specific column. My goal is to return a matrix without these rows, so it should be smaller. My function looks like this:</p> <pre><code>def delete_rows(matrix, x, col): for i in range(matrix.shape[0]-1): if(...
<p>Assuming you have an array like this:</p> <pre><code>array([[12, 5, 0, 3, 11, 3, 7, 9, 3, 5], [ 2, 4, 7, 6, 8, 8, 12, 10, 1, 6], [ 7, 7, 14, 8, 1, 5, 9, 13, 8, 9], [ 4, 3, 0, 3, 5, 14, 0, 2, 3, 8], [ 1, 3, 13, 3, 3, 14, 7, 0, 1, 9], [ 9, 0, 10,...
python|arrays|numpy|matrix|data-science
1
368,027
72,208,446
Searching Pandas column for words in list and adding found words into new column
<p>I have a list of words as well as a dataframe</p> <pre><code>data = {'test':['dog is happy', 'dog is hap', 'dog is hap']} df = pd.DataFrame(data) list = ['dog', 'hap', 'happy'] df test 0 dog is happy 1 dog is hap 2 doggy is hap </code></pre> <p>I'd like to add a column let's call it 'words' so...
<p>This is pretty straight forward using <code>set.intersection</code>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; words = {'dog', 'hap', 'happy'} &gt;&gt;&gt; df[&quot;matches&quot;] = df[&quot;test&quot;].str.split().apply(set(words).intersection) &gt;&gt;&gt; df test matches 0 ...
python|pandas
3
368,028
72,147,225
Pytorch model object has no attribute 'predict' BERT
<p>I had train a BertClassifier model using pytorch. After creating my best.pt I would like to make in production my model and using it to predict and classifier starting from a sample, so I resume them from the checkpoint. Otherwise after put it in evaluation and freeze model, I use .predict to make in work on my samp...
<p>Generally, people wrote the prediction function for you. If not, you need to handle the low level stuff. After this line, you loaded the trained parameters. model, optimizer, start_epoch, valid_loss_min = load_ckp(r&quot;./best_model/best_model.pt&quot;, bert_classifier, optimizer)</p> <p>After that, you need to do ...
python|pytorch|huggingface-transformers|bert-language-model|sentence-transformers
1
368,029
72,200,258
use Folium map in plotly subplots to create dashboard
<p>I have a plan area that covers several buildings. I want to map the plan and the building in a subplot using <code>gdf.explore()</code> method that creates a folium map object, and then use plotly to map a graph of building years histogram. Then put these two plots side by side.</p> <p>I could not find a way to add ...
<ul> <li>your question does not contain sample geometry or dataframe. Have synthesized some</li> <li>as per comments <strong>plotly</strong> and <strong>folium</strong> are very different libraries with no integration</li> <li>clearly with <strong>HTML</strong> you can integrate using <strong>IFrame</strong>. Have tak...
python|plotly|geopandas|subplot|folium
1
368,030
72,427,887
Create a plot showing the duration of time a player was in the team
<p>this is an example data frame, i will be working with much larger data frames. I need to create a plot to show the duration of time a player stayed at the club - the plot is not exclusive to each team in this plot. But my second plot will be showing the correlation between the team and the duration of staying. but I...
<p>As furas mentioned, this should be pretty direct once you convert the missing dates to today's dates and then apply a difference to extract the duration column.</p> <p><strong>Here's the complete code for the dataframe:</strong></p> <pre><code>import pandas as pd import numpy as np from datetime import datetime imp...
python|pandas
0
368,031
72,141,190
Renaming identical column names in Pandas
<p>I have a <code>cycle_2</code> df with the following column names:</p> <pre><code> 3ls 3rs 3ls 3rs 3 absolute_cost 3.00 9.40 9.40 0.00 6.00 </code></pre> <p>Now I need to rename them: I did the following:</p> <pre><code>cycle_2.rename(columns={cycle_2.columns[0]:'Email', c...
<p>This is one of the possible solutions</p> <pre><code>df.columns = ['Email', 'Flash', 'Sms', 'UPI', 'IVR'] </code></pre>
python|pandas
0
368,032
72,167,760
how do i solve Key 8 error while using pytorch?
<pre><code>from torch.utils.data import (TensorDataset, DataLoader, RandomSampler, SequentialSampler) def data_loader(train_inputs, val_inputs, train_labels, val_labels, batch_size=50): &quot;&quot;&quot; Convert train and validation sets to torch.Tensors and load them to Data...
<p>I was using the same code on my data set and had the same issue. I did 2 things. changed the random_state to not be 42 (which probably wasn't what fixed it) and I also changed my labels to np.array and now it works</p>
python|pytorch
0
368,033
72,317,098
How to create a column with updated max in a dataframe?
<p>I need to create a column with the max of the value in column A and the value of the row before of column B. This will provide a list of max values which is updated over the time.</p> <p><img src="https://i.stack.imgur.com/O9k7j.png" alt="Example in excel" /></p> <p>I was thinking writing this code:</p> <pre><code>S...
<p>I think <code>expanding</code> is what you are looking for.</p> <p><code>SPY['Peak Equity'] = SPY['Close Price'].expanding(1).max()</code></p> <p>You can see detail of <code>expanding</code> function here: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer">...
python|pandas
0
368,034
72,142,393
Calculating rolling XNPV in Python
<p>I need to calculate XNPV of cash flows at different future dates. Is there any function to do this in numpy, pandas or plain python?</p> <p>Consider a dataframe like so:</p> <pre><code>import pandas as pd df = pd.DataFrame({'ptf_id': [1,1,1,1,1], 'date': pd.date_range(&quot;2022-06-05&quot;, period...
<p>I don't know that there is something that can handle something more complicated than the simple <code>np.npv()</code>.</p> <p>The NPV values are not the same (I'm not entirely sure what your calculations were to get those results as they do not match Excel's XNPV() either), but here is how you could do it:</p> <pre>...
python|pandas
0
368,035
72,397,751
Converting Keys of Pandas DF of Dictionaries to Columns and values as Data
<p>I have a pandas DF with 5000 rows and 400+ columns containing identifiers as an index column with the remaining columns containing key value pairs in the form of a dictionary.</p> <p>eg.</p> <pre><code>Identifier 0 1 identifier 1 {'key':'value'} {'key2':'value2'} </code></pre> <p>I'...
<p><strong>UPDATED</strong>:</p> <p>Here is my understanding of the question (as updated, including in the comments, by OP):</p> <ul> <li>Given a dataframe with: <ul> <li>leftmost column <code>FileID</code> and an arbitrary number of additional columns with each value in each row containing either None or a dict with 0...
python|pandas|dataframe|dictionary
2
368,036
72,168,550
I am using dask dataframe to read csv file which quite large. I want to extract some specific columns from the df is there any method for that
<p>I have csv file about 3GB large I want to read it with dask. and I want to perform an operation on this data which is to select some columns which contain a specific data.</p> <p>For example:</p> <p>I want to get all the ids which are in df</p> <pre><code>ids = ['SW00003062', 'SW00003063', 'SW00003067', 'SW00003072...
<p>what about this</p> <pre><code>import pandas random_name = pandas.read_csv(&quot;insert file name&quot;) random_name[&quot;column title&quot;] #this should give you your column of choice list = random name[&quot;column title&quot;].to_list() #turns column to list </code></pre>
python|pandas|dataframe|dask-distributed
0
368,037
72,392,752
For loop with desired output in Python
<p>I am trying to write a for-loop. The desired output is attached.</p> <pre><code>import numpy as np for i in np.arange(0,5,1): sigma(0)=10 sigma(i+1)=sigma(i)+1 print(sigma) </code></pre> <p>The desired output is</p> <pre><code>sigma=np.array([10,11,12,13,14]) </code></pre>
<p>Here's the correct loop:</p> <pre><code>In [78]: sigma = [10] ...: for i in range(4): ...: sigma.append(sigma[-1]+1) ...: sigma Out[78]: [10, 11, 12, 13, 14] </code></pre> <p>But if you want to set values in an array:</p> <pre><code>In [79]: sigma = np.zeros(5,int) # initialize ...: sigma[0] = ...
python|numpy
1
368,038
72,201,276
Panda's evaluating NULL to NULL as false when comparing columns
<p>I am creating a python program to do adhoc comparisons of different source files in a OLD -&gt; NEW style compare. Currently I am merging the DF's and using np.where to evaluate differences, the issue I am facing is when the data in both comparison columns is null it evaluates as a difference rather than no differen...
<p>Why do you make a string and not a boolean out of your <code>diff</code> column? Besides why do you loop over <code>names</code>?</p> <p>I think what you're trying to achieve can be done without <code>where</code> and dropping rows with <code>None</code>/<code>NULL</code>/<code>NaN</code>:</p> <pre><code>dfResults =...
python|pandas|dataframe
0
368,039
72,221,037
How to split and keep all the values from a dataframe in new column?
<p>I need to split the <code>Product and Quantity</code> column. The new column name is <code>Quantity</code>.</p> <p>If you see the example below, some rows will begin with quantity information in [2] and others in [1]. Also, I cannot use [-] because in the below example, the second split on '-' will work, but 3rd and...
<p>Reliable method: use a regex!</p> <pre><code>regex = r'[^-]+-((?:[^-]+-){,2}[^-]+)$' df['Quantity'] = df['Product and Quantity'].str.extract(regex) </code></pre> <p>Output:</p> <pre><code> Product and Quantity Quantity 0 ABC-BBC-Bottle- 1 - 30 mg Bottle- 1 - 30 mg 1 BBC-44-Capsule- 10 - 50...
python|pandas|dataframe|split|delimiter
1
368,040
72,476,687
Hvplot multiple columns filter
<p>I am trying to plot a time-serie with a filter using hvplot. The only problems I have is that I want multiple columns in my filter. Here is the dataframe I have:</p> <pre><code>date city Prod1 Prod2 Prod3 Prod4 01/07/2012 Limoges 24 45 12 7 02/07/2012 Lyon 39 36 31 ...
<p>IIUC, using matias's suggestion in the <a href="https://stackoverflow.com/questions/72476687/hvplot-multiple-columns-filter?noredirect=1#comment128038943_72476687">comment</a>, you can use:</p> <pre><code>import pandas as pd import numpy as np import hvplot.pandas dates = pd.date_range(start='1/1/2012', periods=1...
python|pandas|hvplot
1
368,041
72,440,771
Parameters with unknown value
<p>So to be specific I m trying to compute the product scalar of two vectors but the problem is both vectors coordinates contain parameters for example</p> <pre><code> X=[alpha+beta,0,gamma] Y=[alpha,beta,alpha] </code></pre> <p>Value of <code>alpha</code> and <code>beta</code> are unknown so I can't /I don't know ho...
<p>Per some of the comments, is it simply a function with three parameters?</p> <pre><code>import numpy as np def func( alpha, beta, gamma ): x = np.array( [ alpha + beta, 0, gamma ] ) y = np.array( [ alpha, beta ,alpha ] ) return x @ y func( 5, 6, 7 ) # 90 = ( 5 + 6 ) * 5 + 5 * 7 = 55 + 35 </code></pre>
python|numpy
0
368,042
72,420,732
Combining ~ | and between in pandas filter
<p>The idea here is to keep all values except those between 4900-4999 and 6000-6999. However, this code does not work at all. It seems to work if I break it up into two lines. Now searching for the correct syntax.</p> <pre><code>crsp = crsp[~(crsp['SICCD'].between(4900, 4999)) | ~(crsp['SICCD'].between(6000, 6999))] <...
<p>I was able to accomplish this by using a <code>np.where()</code></p> <pre><code>test = np.arange(3000, 8000) df = pd.DataFrame(test, columns = ['Data']) df['Check'] = np.where((df['Data'].between(4900, 4999)) | (df['Data'].between(6000, 6999)), True, False) df.loc[df['Check'] == False] </code></pre>
python|pandas
1
368,043
72,378,764
Convert pandas groupby dataframe into heatmap
<p>I'm trying to find a nice way to visualize the data from publicly available cBioPortal mutation data. I want to plot the co-occurrence of Protein Change (so basically, for each sample ID, does that specific sample have any other mutation also). See the image below:</p> <p><a href="https://i.stack.imgur.com/wyqAb.png...
<p>You could do something like this:</p> <p>Sample data:</p> <pre><code>df = pd.DataFrame({'Sample ID': [1, 1, 1, 4, 4, 5, 6, 6], 'Protein Change': ['A', 'B', 'C', 'D', 'A', 'C', 'A', 'B'], 'Cancer Type Detailed': 'Some type'}) </code></pre> <pre><code> Sample ID Protein Change C...
python|pandas|plotly|pandas-groupby|heatmap
3
368,044
50,251,503
Convert (Fused)BatchNorm to convolution / add for running MobileNet on TensorflowLite
<p>I just finished the TensorFlow for Poets 2: TFLite tutorial (<a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets-2-tflite/#0" rel="nofollow noreferrer">https://codelabs.developers.google.com/codelabs/tensorflow-for-poets-2-tflite/#0</a>). At the end of the tutorial I was able to run the Mob...
<p>TOCO should automatically fold batch norms whether they are fused or unfused. This is the overall flow:</p> <ol> <li>Train model</li> <li>Make Eval model and freeze with with train checkpoint OR export saved model</li> <li>Provide frozen graph or SavedModel to tflite_convert</li> <li>Run inference</li> </ol> <p>Yo...
tensorflow|tensorflow-lite
0
368,045
50,301,880
How to iterate a vectorized if/else statement over multiple columns with a list that can change?
<p>The numbers in ltlist refer to ID numbers that can change, is it possible to literate through multiple columns for the items in ltlist assume the elements in ltlist in this example aren't constant. Hope to use loop instead of vectorized if/else too but couldn't get it to work. </p> <pre><code>import pandas as pd, n...
<p>Since you are using <code>0</code> as the default value, you can pass it as an <code>or</code> with against the data frame.</p> <pre><code>import pandas as pd import numpy as np ltset = set([1, 2]) org = pd.DataFrame({'ID': [1, 3, 4, 5, 6, 7], 'ID2': [3, 4, 5, 6, 7, 2]}) org['LT'] = 0 for col in org.columns.drop(...
python|pandas
0
368,046
50,640,339
How to bin a 2D data along the x-axis with Python
<p><a href="https://i.stack.imgur.com/tmh2b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tmh2b.png" alt=""></a></p> <p>I have two arrays of corresponding data (x and y) that I plot as above on a log-log plot. The data is currently too granular and I would like to bin them to get a smoother relati...
<p>You may use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binned_statistic.html" rel="nofollow noreferrer"><code>scipy.stats.binned_statistic</code></a> to get the mean of the data in each bin. The bins would best be created via <code>numpy.logspace</code>. You may then plot those means e...
python|numpy|matplotlib|histogram|binning
4
368,047
50,355,724
scipy ODE, what happens when nsteps exceeded?
<p>I am running a numerical integration using scipy ode on several million cases and occasionally I get the error: </p> <blockquote> <p>Excess work done on this call (perhaps wrong Dfun type).</p> </blockquote> <p>I increased nsteps a fair bit (500,000), and I also tried specifying the BDF method for 'stiff' proble...
<p>The return value is suspect when this error occurs. As a test case, I tried integrating dy/dt = y from 0 to 1 with mere 10 steps:</p> <pre><code>from scipy.integrate import ode r = ode(lambda t, y: y).set_initial_value(1, 0).set_integrator('lsoda', nsteps=10) print(r.integrate(1)) </code></pre> <p>This prints <cod...
numpy|scipy|ode|numerical-integration
1
368,048
50,438,738
Byte Embedding in mLSTM Conceptual Struggle
<p>I am trying to follow the <a href="https://arxiv.org/pdf/1704.01444.pdf" rel="nofollow noreferrer">OpenAI "Sentiment Neuron" experiment</a> by reading through the <a href="https://github.com/guillitte/pytorch-sentiment-neuron" rel="nofollow noreferrer">PyTorch code posted on Github</a> for training the model from sc...
<p>Even though the same symbols are being used for input and output, it's perfectly acceptable to have different representations used at each end. Cross entropy is a function of two probability distributions. In this case, the two distributions are the softmax distribution given by the model, and a point mass on the "c...
python|machine-learning|deep-learning|lstm|pytorch
1
368,049
50,493,811
How do you group, sort, and limit in Python Pandas? (i.e. Get Top 10)
<p>I have a Pandas dataframe that has columns actor_id and account_id. Actor is a person and account is simply an account. So a person can have more than one account and accounts can have multiple people.</p> <p>My goal is to group by actor_id and then rank the actor_ids by the number of accounts they have so that I c...
<p>You can do:</p> <pre><code>df_nb_acc = ( df.groupby('actor_id')['account_id'] #groupby actor_id, select the column account_id .count() # count the number of accout per actor .reset_index() # actor_id become a column and not indexes .rename(columns={'account_id':'Nb_account'}) # to rename the c...
python|pandas|pandas-groupby
2
368,050
50,387,110
How to make a new dataframe with original tweets
<p>I am performing a sentiment analyses on tweets. I have made an algorithm that removes emoji's and some special characters before calculating the sentiment of the tweet. After that, the tweet without emoji's and special characters is put into a dataframe with the sentiments. Here is the code:</p> <pre><code>x = 0 a ...
<p>Nevermind, I found the solution myself. Solution:</p> <pre><code>x = 0 a = 0 d = {} #df2 = pd.DataFrame(['Tweets', 'Sentiment']) df['Tweets'] = "" df['Sentiment'] = "" for vertaling in df['text']: df['Tweets'].iloc[x] = df['text'].iloc[x] bericht = re.sub('[^A-Za-z0-9]', ' ', df['text'].iloc[x]) beric...
python|pandas|dataframe|twitter
0
368,051
50,532,073
Sort, rank, groupby and sum combined -> Python pandas
<p>I have a pandas dataframe with paragraph pairs. There are around 500 paragraphs and each is listed as a pair in the following format (sorted by paragraphA and ranked by highest prediction):</p> <pre><code>ParagraphA | paragraphB | label | prediction Paragraph1 | Pragraph2 | 1 ----| 0.9890 Paragraph1 | Pragraph1...
<p>I haven't understood if column "label" has only numbers, or if the entries are like the one shown (i.e. '1 ----'). In this case I suggest to first create a new column in this way:</p> <pre><code>df['new_label'] = df['label'].astype(str).str[0] df['new_label'] = df['new_label'].astype(int) </code></pre> <p>Ignore t...
python|pandas|sorting|grouping
0
368,052
50,580,901
Merge two mirroring Pandas columns
<p>I need to be able to merge two columns which 'mirror' each other, creating a new column which holds the value from 'dest' in the case of 'A' and 'src' in the case of 'B'.</p> <p>I currently have:</p> <pre><code>src dest type time 1 2 A 76 1 3 A 176 1 4 ...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a> and last remove unne...
python|pandas
1
368,053
50,468,494
Numpy/Pandas clean way to check if a specific value is NaN
<p>How can I check if a given value is NaN?</p> <p>e.g. <code>if (a == np.NaN)</code> (doesn't work)</p> <p>Please note that:</p> <ul> <li>Numpy's <code>isnan</code> method throws errors with data types like string</li> <li>Pandas docs only provide methods to drop rows containing NaNs, or ways to check if/when DataFram...
<p>You can use the inate property that <code>NaN</code> != <code>NaN</code></p> <p>so <code>a == a</code> will return <code>False</code> if <code>a</code> is <code>NaN</code></p> <p>This will work even for strings</p> <p>Example:</p> <pre><code>In[52]: s = pd.Series([1, np.NaN, '', 1.0]) s Out[52]: 0 1 1 ...
python|pandas|numpy
12
368,054
50,432,189
Pandas get_dummies() on multilevel columns
<p>I would like to maintain the multilevel structure of my columns while applying <code>get_dummies()</code> to particular subcolumns.</p> <p>For example, given the dataframe:</p> <pre><code>In [1]: df = pd.DataFrame({('A','one'):['a','a','b'], ('A','two'):['b','a','a'], ...
<p>Panda-fu</p> <pre><code>pd.get_dummies(df.stack(0).one, prefix='one').stack().unstack(0).T.join( df.xs('two', axis=1, level=1, drop_level=False) ).sort_index(1) A B C one_a one_b two one_a one_b two one_a one_b two 0 1 0 b 0 1 a 0 1 ...
python|pandas
3
368,055
50,332,725
Spatial Pyramid Pooling - Input Size Error (? - None)
<p>I've been trying to implement the Spatial Pyramid Pooling (<a href="https://arxiv.org/abs/1406.4729" rel="nofollow noreferrer">https://arxiv.org/abs/1406.4729</a>), but I've been having a problem with the input size.</p> <p>My input has shape (batch_size, None, n_feature_maps) and I have the following code:</p> <p...
<blockquote> <p>I would like to know how I can work around this nondefined size. Is it possible to get the tensor's shape at runtime?</p> </blockquote> <p>Use <code>tf.shape()</code> op to get the dynamic shape of a tensor instead of the <code>x.get_shape()</code> which returns the static shape of x.</p> <p>This...
tensorflow|input|spatial|pooling
1
368,056
50,465,195
TensorFlow, Julia - Tensors and Floats
<p>Why can I convert a Float to a tensor, like this:</p> <pre><code>tensor = convert(TensorFlow.Tensor{Float32}, 0.05) &lt;Tensor Cast_8:1 shape=() dtype=Float32&gt; </code></pre> <p>But not the Tensor to a Float. The following command:</p> <pre><code>convert(Float32, tensor) </code></pre> <p>return the following e...
<p>In TensorFlow (unlike in actual mathematics) a <code>Tensor</code> is not really (only) a thing wrapping some numbers. It is in a <em>symbolic value</em> in the computation graph, which can happen to hold constants, as in your case, but also variables and placeholders. Thus, in general, <code>convert</code>ing back...
tensorflow|julia
2
368,057
50,472,136
Python code inconsistency on complex multiplication in MPI
<p>Assume an Python MPI program where a master node sends a pair of complex matrices to each worker node and the worker node is supposed to compute their product (conventional matrix product). The input matrices are constructed at the master node according to some algorithm which there is no need to explain. Now imagin...
<p>This is completely unrelated to MPI.</p> <pre><code>np.set_printoptions(precision=15) </code></pre> <p>To confirm that the computed <code>a</code> and <code>b</code> are in fact different from the one you feed into the "correct" version.</p> <p>I'm not sure what the ground truth for the results is. There may be r...
python|numpy|mpi|complex-numbers|mpi4py
0
368,058
50,276,911
How to split data by different classes in python 3.6
<p>since I have a dataset looks like this:</p> <hr> <pre><code>CLASS, value1 A, 1 A, 2 A, 3 A, 5 B, 4 B, 1 B, 2 C, 1 C, 5 </code></pre> <hr> <p>and I would like to split the dataset by CLASS into several sub-dataset.</p> <p>for now I'm doing it one by one:</p> ...
<p>For most applications, your <code>groupby</code> object returned by <code>df.groupby('CLASS')</code> <em>is</em> your collection of separate datasets, and there are lots of ways to do complex manipulations on a <code>groupby</code> object within <code>pandas</code> (see the two links at the bottom of this post). </p...
python|pandas|split
1
368,059
50,321,640
Joining edited images in python using numpy image slicer
<p>I am learning image manipulation as a beginner in python. My goal is to section my image into an nxn grid where each square is the average color (greyscale image) of the original, respectively. I succeeded in splitting the image, changing its pixel data and saving the new images. My problem is now stitching the imag...
<p>Your question seems to be missing the error you get with your current code.</p> <p>However, if I read it correctly, you will get back your original image, as was the problem in <a href="https://stackoverflow.com/questions/43565275/split-and-join-images-in-python">Split and Join images in Python</a>. Similar to the a...
image|numpy|python-3.6
0
368,060
50,477,206
Getting a variable using tf.get_variable after graph and session is restored in new file
<p>I am trying to train a model in file 1, and restore and analyze the weights in another file (file 2). </p> <p>In file 1, I have created a variable using get_variable </p> <pre><code>with train_graph.as_default(): softmax_wInit = tf.truncated_normal((n_vocab, n_embedding)) softmax_w = tf.get_variable('SMWei...
<p>You should use</p> <pre><code>tf.get_variable('MyVariableName') </code></pre> <p>(as you did in your example that works), not</p> <pre><code>tf.get_variable('MyVariableName:0') </code></pre> <p>which is the <em>output</em> of the variable operator, i.e its value (and the name of the tensor you will get back by c...
python|tensorflow
1
368,061
50,308,839
how to make two conv nets from a single class and do weight sharing[Siamese net]
<p>I am trying to implement a siamese network , similar to below image for representation.</p> <p><a href="https://i.stack.imgur.com/UpBJf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UpBJf.png" alt="enter image description here"></a></p> <p>In this I have made a class SiameseNet which implemen...
<ul> <li><p>When you set the <code>reuse</code> argument of <a href="https://www.tensorflow.org/api_docs/python/tf/variable_scope" rel="nofollow noreferrer">tf.variable_scope</a> to <code>True</code>, TensorFlow expects the variables (with the name that you provide) to exist within the scope, and that is not the case w...
tensorflow|deep-learning
0
368,062
50,430,493
Image processing: vectorize numpy array elements substitution
<p>The code works well but is very slow. How can I vectorize the color substitution to avoid usage of Python <code>for</code> loop?</p> <pre><code>processed_image = np.empty(initial_image.shape) for i, j in np.ndindex(initial_image.shape[:2]): l_, a, b = initial_image[i, j, :] idx = mapping[a + 128, b + 128] ...
<p>You can use advanced indexing:</p> <pre><code># chain the two maps chained = new_colors[(*np.moveaxis(mapping, 2, 0),)] # split color channels c1, *c23 = np.moveaxis(initial_image, 2, 0) # add 128 c23 = *map(np.add, c23, (128, 128)), # apply chained map processed_image_2 = np.concatenate([c1[..., None], chained[c23...
python|performance|numpy|image-processing|scikit-image
3
368,063
50,497,398
How to read .xls files in tensorflow-python
<p>I have a quite big problem with reading xls. file to my machine learning project. Data that i need to extract is saved in .xls file and i can't find any option to easy extract to tensorflow dataset model, can anyone help?</p> <p>link to this data: "<a href="http://archive.ics.uci.edu/ml/machine-learning-databases/0...
<p>Try to use Pandas module:</p> <pre><code>import pandas as pd In [24]: df = pd.read_excel(r'D:\download\BreastTissue.xls', sheet_name='Data') In [25]: df Out[25]: Case # Class I0 PA500 HFS DA Area A/DA Max IP DR P 0 1 car 524....
python|tensorflow|machine-learning|xls
1
368,064
50,260,642
Can a MultiLabelBinarizer represent counts of values?
<p>Lets say we have lists in a dataframe column</p> <pre><code>df['a'][0] = ['earth','mars','earth','moon'] df['a'][1] = ['jupiter','pluto','sun'] </code></pre> <p>is there a way to use a multilabelbinarizer to obtain</p> <pre><code> earth mars moon sun jupiter pluto df['a'][0] 2 1 1...
<pre><code>import pandas as pd from sklearn.preprocessing import MultiLabelBinarizer planet = pd.DataFrame() planet['planet_group'] = ['group_a', 'group_b'] planet['planet_list'] = [ ['earth', 'mars', 'earth', 'moon'], ['jupiter', 'pluto', 'sun']] g_planet = [] l_planet = [] for row in planet.itertuples(): f...
python|pandas|machine-learning|deep-learning|keras
0
368,065
50,242,276
split dataframe when number is lower than the previous number
<p>I have a series like this: <code>test = pd.Series([2.4,5.6,8.8,25.6,53.6,1.7,5.7,8.9])</code></p> <p>I want to split it into two series at the point where the next number is smaller than the previous one. This only happens once in any series, but it does not happen at a reliable location (could be the 7th place, 4t...
<p>You can find the position with</p> <pre><code>pos = (test - test.shift(-1)).argmax() </code></pre> <p>Now the series until that is</p> <pre><code>&gt;&gt;&gt; test[: pos + 1] 0 2.4 1 5.6 2 8.8 3 25.6 4 53.6 dtype: float64 </code></pre> <p>Similarly, the remainder is</p> <pre><code>&gt;&gt;&gt;...
python|pandas|dataframe
3
368,066
50,431,823
python pandas: find the top 3 frequent names
<p>For the dataframe below,find the top 3 frequent names</p> <pre><code>Index Name 1 Jack 2 Jack 3 Tom 4 Tom 5 Lucy 6 Lily 7 Lily The result should be Name Frequency Jack 2 Tome 2 Lily 2 </code></pre> <p>T...
<p>You can try using <code>groupby</code> with <code>apply</code> and <code>nlargest</code>:</p> <pre><code>result_df = df.groupby('Condition')['Name'].apply(lambda grp: grp.value_counts().nlargest(2)).reset_index() result_df.columns = ['Condition','Name','Frequency'] print(result_df) </code></pre> <p>Result:</p> <p...
python|pandas
1
368,067
50,482,884
module 'pandas' has no attribute 'rolling_mean'
<p>I am trying to build a ARIMA for anomaly detection. I need to find the moving average of the time series graph I am trying to use pandas 0.23 for this </p> <pre><code>import pandas as pd import numpy as np from statsmodels.tsa.stattools import adfuller import matplotlib.pylab as plt from matplotlib.pylab import rc...
<p>I believe need change:</p> <pre><code>moving_avg = pd.rolling_mean(ts_log,12) </code></pre> <p>to:</p> <pre><code>moving_avg = ts_log.rolling(12).mean() </code></pre> <p>because old pandas version code below <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.18.0.html#window-functions-are-now-metho...
python|pandas
116
368,068
50,497,029
Creating year, month, day from one data frame column of type datetime
<p>I have a pandas data frame <strong>data</strong> that has a column <strong>MFR_DATE</strong> that is of type datetime. I want to create additional columns, <strong>MFR_YEAR</strong>, <strong>MFR_MONTH</strong>, <strong>MFR_DAY</strong> and I use following 3 statements to do so. I was wondering if there is a better w...
<p>use vectorized <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html" rel="nofollow noreferrer"><code>Series.dt.</code> accessor</a>:</p> <pre><code>data['MFR_YEAR'] = data['MFR_DATE'].dt.year data['MFR_MONTH'] = data['MFR_DATE'].dt.month data['MFR_DAY'] = data['MFR_DATE'].dt.day </c...
python-3.x|pandas|dataframe
5
368,069
50,633,132
Only importing up to the maximum value of one of my columns
<p>I am using <code>matplotlib</code> and <code>numpy</code>, and I am making graphs. The data format I am using is <code>.csv</code>. In the <code>csv</code> file I am using there are three columns. I wonder, is there a way to only import data up until the peak/lowest values of one of my columns? </p> <p>Context: I a...
<p>Before reading the whole file, you cannot be sure which value is the highest. The simpler solution is to read the whole file and then drop rows.</p> <pre><code>import pandas as pd df = pd.read_csv('yourfile.csv', sep=',') rowmax = df.Intensity.idxmax() df[:(1 + rowmax)] </code></pre>
python|numpy|matplotlib
0
368,070
50,415,083
Add value from series index to row of equal value in Pandas DataFrame
<p>I'm facing bit of an issue adding a new column to my Pandas DataFrame: I have a DataFrame in which each row represents a record of location data and a timestamp. Those records belong to trips, so each row also contains a trip id. Imagine the DataFrame looks kind of like this:</p> <pre><code> TripID Lat Lon ...
<p>If I understand correctly, to get the length of the trip, you'd want to get the difference between the maximum time and the minimum time for each trip. You can do that with a groupby statement.</p> <pre><code># Groupby, get the minimum and maximum times, then reset the index df_new = df.groupby('TripID').time.agg([...
python|pandas|dataframe
0
368,071
50,430,742
How to change date format with two files
<p>I have two tables and want to use pandas to transpose them into one table that looks exactly like this. The order has to be the same and the dates the exactly same format.</p> <p>My table1.csv</p> <pre><code>Tweet, Month, Day, Year Hello World, 6, 2, 2013 I want ice-cream!, 7, 23, 2013 Friends will be friends, 9, ...
<p>Can't you simply</p> <pre><code>df1['Date'] = pd.to_datetime(df1[['Year', 'Month', 'Day']]) df2['Month'] = df2.Month.apply(lambda x: datetime.strptime(x, '%B').month) df2['Date'] = pd.to_datetime(df2[['Year', 'Month', 'Day']]) df = pd.concat([df1, df2])[['Date','Tweet']] </code></pre> <p>E.g.:</p> <pre><code>s1 ...
python|pandas|csv|dataframe
3
368,072
50,534,429
backpropagation trouble; getting higher and higher total cost up until its infinity
<p>I made a FC neural network with numpy based on the video's of welch's lab but when I try to train it I seem to have exploding gradients at launch, which is weird, I will put down the whole code which is testable in python 3+. only costfunctionprime seem to break the gradient descent stuff going but I have no idea wh...
<p>I think the problem lies in your Cost Function.</p> <pre><code>def costFunction(self): self.totalcost = 0.5*sum((self.trng_output-self.output)**2) return self.totalcost </code></pre> <p>Specifically this line,</p> <pre><code>self.totalcost = 0.5*sum((self.trng_output-self.output)**2) </code></pre> <p>You...
python|numpy|neural-network|backpropagation
2
368,073
50,335,858
Pandas Dataframe: Find the conditional mean of all observations that meet certain conditions that are DIFFERENT in each row
<p>Let's say that I have a dataframe like this:</p> <pre><code> date M1_start M1_end SimPrices_t0_exp 0 2017-12-31 2018-01-01 2018-01-31 16.151667 1 2018-01-01 2018-02-01 2018-02-28 45.138445 2 2018-01-02 2018-02-01 2018-02-28 56.442648 3 2018-01-03 2018-02-01 ...
<p>Here, one way to do this using cartesian merging (not a good choice for large dataset), filtering and <code>groupby</code>:</p> <pre><code>df = df.assign(key=1) df_m = df.merge(df, on='key') df_m.query('M1_start_x &lt;= date_y &lt;= M1_end_x').groupby(['M1_start_x','M1_end_x'])['SimPrices_t0_exp_y'].mean() </code>...
python|pandas|dataframe|conditional|mean
0
368,074
50,494,463
How to use Multiindex to be aggregated into list in pandas?
<p>I have a dataframe like this :</p> <pre><code> class1 class2 values values2 0 1 0 1 5 1 1 1 2 8 2 1 0 3 3 3 2 0 5 6 4 2 0 2 5 5 2 1 4 2 6 2 1...
<p>You can aggregate with <code>tuple</code> then convert to <code>list</code> with <code>applymap</code></p> <pre><code>df.groupby(['class1', 'class2']).agg(tuple).applymap(list).reset_index() class1 class2 values values2 0 1 0 [1, 3] [5, 3] 1 1 1 [2] [8] 2 ...
python|pandas|pandas-groupby
2
368,075
50,289,938
Error while reading csv file and returning dataframe in python
<p>My below code does no work. Is there a better way to filter by column?</p> <pre><code>import pandas as pd # To handle data file=pd.read_csv("C:\\Users\\Ankit\\Downloads\\file.csv",index_col=0) df = pd.DataFrame(data=[tweet.text for tweet in file], columns=['tweet']) print(df) </code></pre>
<p><code>file</code> is <em>already</em> a dataframe. To filter for specific column(s), you don't need to create a new dataframe and extract data from <code>file</code>.</p> <p>Instead, you can simply use your existing <code>pd.DataFrame</code> object and use standard <code>[]</code> indexing. Assuming you have a "twe...
python|pandas|csv|dataframe
0
368,076
50,416,918
Count most repeated pair of an get that pair in pandas
<p>I was working in a project for class and I don't know how can I get the direction (with the fields latitude and longitude) most repeated in the DataFrame. This is an example of the Dataframe I have:</p> <pre><code> coor lats longs 0 {-8.51114625, 42.90692115} -8...
<p>You can try with <code>reset_index</code> (<em>using only records shown in question above for dataframe</em>):</p> <pre><code>grouped_df = coords.groupby(['longs','lats']).size().sort_values(ascending=False).to_frame('value_count').reset_index()[:5] print(grouped_df) </code></pre> <p>Result for grouped:</p> <pre>...
python|pandas
0
368,077
50,337,237
Simple barplot of column means using seaborn
<p>I have a pandas dataframe with 26 columns of numerical data. I want to represent the mean of each column in a barplot with 26 bars. This is easy to do with pandas plotting function: <code>df.plot(kind = 'bar')</code>. However, the results are ugly and the column labels are often truncated, i.e.:</p> <p><a href="htt...
<p>You can try something like this:</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns sns.set() fig = df.mean().plot(kind='bar') plt.margins(0.02) plt.ylabel('Your y-label') plt.xlabel('Your x-label') fig.set_xticklabels(df.columns, rotation = 45, ha="right") plt.show() </code></pre> <p><a href="h...
python|pandas|seaborn
4
368,078
50,417,709
tensorflow.python.framework.errors_impl.NotFoundError: data/kitti_label_map.pbtxt; No such file or directory
<p>I'm trying to convert the kitti dataset into the tensorflow .record. After I typed the command:</p> <blockquote> <p>python object_detection/dataset_tools/create_kitti_tf_record.py --lable_map_path=object_detection/data/kitti_label_map.pbtxt --data_dir=/Users/zhenglyu/Graduate/research/DataSet/kitti/data_objec...
<p>I don't have a definitive solution to this but here is what resolved it.</p> <p>First, I copied the kitti_label_map.pbtxt into the <em>data_dir</em>. Then I also copied create_kitti_tf_record.py into the data_dir. And now I copied(this is what made it run in the end) the name and absolute path of the kitti_label_ma...
python|python-3.x|tensorflow
0
368,079
50,232,666
Grouping , cross section and sorting within cross section in python
<p>I have the below data:</p> <pre><code>player_id broadcast_month_id runs_tier 67 201803 100s 67 201803 400s 67 201802 50s 67 201802 100s 67 201801 50s 67 201712 50s 67 20171...
<p>Consider first creating a <em>latest</em> column in <em>df_tier</em> with <code>groupby().transform()</code>, then run <code>pivot_table</code> without need of <code>.xs()</code>, followed by a new column assignment on a conditional filtered <code>groupby().min</code>:</p> <pre><code># NEW COLUMN FOR LATEST broadca...
python|pandas
2
368,080
50,475,989
Efficiency of Numpy wheels and simple benchmark for Numpy installations
<p>Some months (or years?) ago, I installed a Numpy wheel which was very inefficient. Since, I avoid wheels for the computational packages and prefer to build them or to use conda.</p> <p>By " very inefficient", I mean that a code using this wheel was something like 10 times slower than usual. I guess this Numpy did n...
<p>It really depends on exactly what kind of math you're doing. Wheels on PyPI are built with OpenBLAS, whereas the default conda packages use MKL. The performance between the two is reasonably competitive. Intel has been doing more work lately on some low-level numpy stuff, and the conda packages will benefit from ...
python|numpy
2
368,081
50,394,519
How do I plot a non-stacked and non-side-by-side horizontal bar chart with matplotlib/pandas?
<p>Basically, I want all bars overlapping, but I don't want them to stack nor to be side-by-side. I want them overlapping, but if I try to do overlapping bars with pyplot, it doesn't automatically organize it so that the smaller bars are up front and the bigger ones are in the back. Some bars get completely hidden. I d...
<p>I understand that you want something like #3. This might lead to problems, if some values are similar within the same row. But otherwise, you can create your own sorting of the columns to prevent that larger values cover smaller ones.</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd from matplotli...
python|pandas|matplotlib
1
368,082
50,469,878
Restore Tensorflow Model Failed in Google Colab
<p>Restoring tensorflow model using saver.restore(sess,model_dir) is failing in Google Colaboratory. </p> <p><strong>Restore Code</strong></p> <pre><code> tf.reset_default_graph() sq_net = classifierNet(input_shape,out_classes,lr_rate,is_train) with tf.Session() as sess: sess.run(tf.global_variab...
<p>Download the model files into colab using the file id. Follow this - <a href="https://colab.research.google.com/notebook#fileId=/v2/external/notebooks/io.ipynb" rel="nofollow noreferrer">https://colab.research.google.com/notebook#fileId=/v2/external/notebooks/io.ipynb</a>. </p>
python|tensorflow|google-colaboratory
0
368,083
50,443,494
Error in removing punctuation: 'float' object has no attribute 'translate'
<p>I am trying to remove punctuations from a col in a data frame by doing the following: </p> <pre><code>def remove_punctuation(text): return text.translate(table) df['data'] = df['data'].map(lambda x: remove_punctuation(x)) </code></pre> <p>But I am getting the following error: </p> <blockquote> <p>'float'...
<p>Your df['data'] has NaN elements.<code>type(np.nan)</code> is float. Hence, you are getting an error "'float' object has no attribute 'translate'" while removing punctuations.To fix this issue, you can either </p> <ol> <li>Remove NaN elements from df['data'] or,</li> <li>Use <code>df['data'] = df.fillna({'data':''}...
string|python-3.x|pandas
4
368,084
50,495,057
Loop over all elements of an ndarray one by one
<pre><code>In [6]: a = np.array([[1,2,3,4],[5,6,7,8]]) In [7]: b = a In [8]: a[0] Out[8]: array([1, 2, 3, 4]) In [9]: a[0][0] Out[9]: 1 </code></pre> <p>But I would like to use <code>zip</code> and loop through <code>a</code> and <code>b</code> and get <code>a[0][0]</code> followed by <code>a[0][1]</code> and so un...
<p>If you <em>just</em> need to loop through all elements of <code>a</code> one by one, that's what <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html" rel="nofollow noreferrer"><code>ndarray.flat</code></a> is for:</p> <pre><code>In [11]: a = np.array([[1,2,3,4],[5,6,7,8]]) In [13]...
python|numpy|for-loop
6
368,085
50,641,631
Tensorflow, ValueError: setting an array element with a sequence
<p>When trying to train my tensorflow graph im getting the error message:</p> <blockquote> <p>ValueError: setting an array element with a sequence</p> </blockquote> <p>happening in this line of code, in the feed_dict function:</p> <pre><code># run the session and train the model _, c = sess.run([optimizer,...
<p>Try something like </p> <pre><code>y_train = [] for _ in range(len(dataframe)): string = dataframe.at[_, 'Product Categorization Tier 1'].strip() number = category_list.index(string) # saving as category vector vector = [0] * 25 vector[number] = 1 y_train.append(vector) </code></pre> <p...
python|pandas|tensorflow
0
368,086
50,352,935
Compact and natural way to write matrix product of vectors in Numpy
<p>In scientific computing I often want to do vector multiplications like</p> <p><strong>a</strong> x <strong>b</strong>^T</p> <p>with <strong>a</strong> and <strong>b</strong> being row vectors and <strong>b</strong>^T is the transpose of the vector. So if <strong>a</strong> and <strong>b</strong> are of shape [n, 1...
<p>In the comments, multiple solutions were proposed, which I summarize here:</p> <ul> <li><code>np.outer(a,b)</code>, which basically reformulates this multiplicaten as a set problem (thanks to <a href="https://stackoverflow.com/users/6091318/brenlla">Brenlla</a>)</li> <li><code>a[:,np.newaxis]*b</code> (thanks to <a...
numpy|vector|matrix-multiplication
1
368,087
45,601,932
split a dataframe column into equal parts
<p>I want to break this column into three components: city, state, zip. I was considering something like this: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html</a>. ...
<p>You can try something like this, </p> <pre><code>df = pd.DataFrame({'Name' : ('john','doe','smith'), 'address_1' : (105,305,505), 'address_2' : ('path','lane','route'),\ 'city_state_zip': ('Sahuarita, AZ, 85629', 'Sahuarita1, AZ1, 75629', 'Sahuarita2, AZ2, 65629')}) </code></pre> <p><code>df</code></p> ...
python|pandas
0
368,088
45,496,445
Pandas: check column values by ignoring cases (convert cases)
<p>I am trying to check values of a pandas column using the following condition:</p> <pre><code>my_df[my_df.name.str.contains('MY_TARGET')] </code></pre> <p>This works fine. But since I need to convert the name column to upper case, I did the following but didn't work:</p> <pre><code>my_df[my_df.name.str.upper.conta...
<p>You can simply use <code>case = False</code> parameter ie. </p> <pre><code>df = pd.DataFrame({'name': ['my_target', 'foo', 'bar', 'My_TarGet']}) #Coldspeed data df[df['name'].str.contains('my_target', case=False)] </code></pre> <p>Output : </p> <pre> name 0 my_target 3 My_TarGet </pre>
python-3.x|pandas|uppercase
7
368,089
45,357,661
Tensor returned by tf.tranpose() different when stored?
<p>I am writing an application using TensorFlow and I'm using the tf.transpose() function. The API states that the function returns a transposed tensor, which is what you'd expect. However, I noticed the following phenomenon:</p> <pre><code>&gt;&gt;&gt; tf.transpose([3, 5]) &lt;tf.Tensor 'transpose:0' shape=(2,) d...
<p>Oops, I answered my question as soon as I posted it... I think they are just not equivalent because they are two different tensor objects, even though they have the same value. I was thrown off by the naming convention. We can see this here:</p> <pre><code>&gt;&gt;&gt; a = tf.transpose([3, 5], name='a') &gt;&gt;&gt...
python|tensorflow
1
368,090
45,447,013
python multiindex assignment
<p>I have an issue with multiindex assignment and will like to store values as highlighted below</p> <p>I have a function called <strong>df_x</strong> that is a dataframe and looks like</p> <pre><code>print df_x serial P1 P2 P3 5 21 32 35 10 33 45 76 15 6...
<p><strong>Option 0</strong> </p> <pre><code>pd.concat([df_x], keys=['alpha']) serial P1 P2 P3 alpha 5 21 32 35 10 33 45 76 15 65 99 563 </code></pre> <hr> <p><strong>Option 1</strong> </p> <pre><code>pd.DataFrame( df_x.values, [['alpha'] * len(df_x), df_x.index], df_x.c...
python|python-2.7|pandas
1
368,091
45,631,925
C++ TensorFlow SoftmaxCrossEntropWithLogits returns (cost, gradients), how to access cost?
<p>I am trying to implement a simple neural network in C++ TensorFlow. </p> <p>I am unable to access loss returned by SoftmaxCrossEntropyWithLogits function (<a href="https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/softmax-cross-entropy-with-logits" rel="nofollow noreferrer">https://www.tensorflow.org/api_...
<p>here it doesn't return anything, its an attribute. You can access it from the class instance.</p> <pre><code>#define the loss class instance with your logits and labels softmax_loss_function = SoftmaxCrossEntropyWithLogits(const ::tensorflow::Scope &amp; scope, ::tensorflow::Input features, ::tensorflow::Input labe...
c++|tensorflow
0
368,092
45,503,965
Python pandas: Combine two dataframes by date index and a common column value
<p>There are two dateframes, one is df1, another is df2 as follows:</p> <p>df1:</p> <pre><code> a b id 2010-01-01 1 4 21 2010-01-01 2 5 22 2010-01-01 3 6 23 2010-01-01 4 7 24 2010-01-02 1 4 21 2010-01-02 2 5 22 2010-01-02 3 6 23 2010-01...
<p>IIUC:</p> <pre><code>In [388]: df2.set_index('id', append=True).join(df1.set_index('id', append=True)) \ .reset_index(level='id') Out[388]: id c d a b 2010-01-02 21 1 4 1 4 2010-01-02 22 2 5 2 5 2010-01-02 23 3 6 3 6 2010-01-02 24 4 7 4 7 2010-01-03 21 1 4 1 4 2...
python|python-2.7|pandas|inner-join
3
368,093
45,516,424
sklearn train_test_split on pandas stratify by multiple columns
<p>I'm a relatively new user to <code>sklearn</code> and have run into some unexpected behavior in <code>train_test_split</code> from <code>sklearn.model_selection</code>. I have a pandas <code>dataframe</code> that I would like to split into a training and test set. I would like to <code>stratify</code> my data by at ...
<p>If you want <code>train_test_split</code> to behave as you expected (stratify by multiple columns with no duplicates), create a new column that is a concatenation of the values in your other columns and stratify on the new column.</p> <pre><code>df['bc'] = df['b'].astype(str) + df['c'].astype(str) train, test = tra...
python|pandas|scikit-learn
41
368,094
45,283,811
Difference to group mean in a pandas data frame?
<p>Lets's assume I count how many oranges (<code>Orange</code>) and apples (<code>Apple</code>) people (<code>id</code>) eat in a certain time period. I also know if they are young or old (<code>group</code>). The pandas dataframe would maybe look like this:</p> <pre><code>df = pd.DataFrame({'id': ['1','2','3','7'], ...
<p>You need <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> for <code>mean</code> with same <code>length</code> as <code>df</code> and substract by <a href="http://pandas.pydata.org/pandas-docs/stable/generat...
python-3.x|pandas|group-by|mean|difference
11
368,095
45,376,000
Stacking dataframe columns (Pandas)
<p>I am looking for a way to pivot a dataframe in reverse direction. To the best of my knowledge, pandas provides a pivot or pivot_table method to transform an EAV df to a "normal" one. However, is there also a way to do the inverse?</p> <p>So given the dataframe:</p> <p><code>$df userid A B C 0 1 1 0 1 ...
<p>Assuming <code>userid</code> is the index, <code>df.stack</code> will do it:</p> <pre><code>In [133]: df.stack().reset_index().rename(columns={'userid' : 'E', 'level_1' : 'A', 0 : 'V'}) Out[133]: E A V 0 0 A 1 1 0 B 1 2 0 C 0 3 1 A 1 4 1 B 3 5 1 C 1 6 2 A 1 7 2 B 5 8 2 C 0 </code></...
python|pandas|pivot-table|entity-attribute-value
5
368,096
45,615,306
Get top rows from column value count with pandas
<p>Let's say I have this kind of data. It's a set of reviews of some products.</p> <pre><code>prod_id text rating AB123 some text 5 AB123 some text 2 AB123 some text 4 AC456 some text 3 AC456 some text 2 AD777 some text 2 AD777 some text 5 AD777 some text 5 AD777 some text 4 AE99...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with <code>left</code> join with <code>DataFrame</code> created with <code>index</code> of <code>s</code>:</p> <pre><code>df = pd.DataFrame({'prod_id':s.index...
python|pandas
4
368,097
45,457,061
Where is the bazel rule generating the `gen_io_ops.py` file when building TensorFlow from sources?
<p>I'm trying to determine how the <em>gen_io_ops</em> module is generated by bazel when building TensorFlow from source.</p> <hr> <p>In <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/io_ops.py" rel="nofollow noreferrer">tensorflow/python/ops/io_ops.py</a>, there is this piece of ...
<p>I finally got it.</p> <hr> <p>There is indeed a call to <code>tf_op_gen_wrapper_py</code> but it's hidden in a call to <code>tf_gen_op_wrapper_private_py</code>:</p> <pre><code>def tf_gen_op_wrapper_private_py(name, out=None, deps=[], require_shape_functions=True, ...
python|c++|tensorflow|bazel
1
368,098
45,462,754
Why does np.ndarray.__deepcopy__ require a superfluous argument?
<p>The duplicate will answer <code>what</code>, but will not adequately answer <code>why</code> or why it is not mentioned in the docs even though it is required. Read on for more... </p> <hr> <p>There are two ways of making a deep copy of a numpy array. One way is using <code>copy.deepcopy</code> from the <code>copy...
<p>Python requires the <code>__deepcopy__()</code> method to take one argument <code>memo</code> (<a href="https://docs.python.org/3/library/copy.html" rel="nofollow noreferrer">docs</a>):</p> <blockquote> <p>In order for a class to define its own copy implementation, it can define special methods <code>__copy__()</...
python|arrays|numpy|copy|deep-copy
1
368,099
45,338,657
Pandas Dataframe.Interpolate() gives different values for same index date
<p><strong>Using the DataFrame</strong></p> <pre><code>date_index value 2013-01-01 0.50 2013-01-01 0.50 2013-01-01 0.50 2013-01-01 0.50 2013-01-02 1.50 2013-01-02 1.50 2013-01-02 1.50 2013-01-02 1.50 2013-01-03 0.98 2013-01-03 0.98 2013-01-03 0.98 2013-01-03 0.98 2013-01-04 NaN 2013-01-04 1.00 2013-01-0...
<p>According to documentation:</p> <blockquote> <p>‘linear’: ignore the index and treat the values as equally spaced. default</p> </blockquote> <p>If you want to get the result considering the date you can select method like "time" or "index"</p>
python|pandas|interpolation
3