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 |
|---|---|---|---|---|---|---|
376,200 | 61,925,035 | TensorflowException: Invalid GraphDef (TensorFlow 2.0) | <p>I'm building a model using tf.keras.models.Sequential and saving it as a SavedModel object which contains a saved_model.pb file. The model is then going to be used in a C# service using ML.net.</p>
<p>Here is the code (pulled and adapted from docs)</p>
<pre><code>(train_images, train_labels), (test_images, test_la... | <p>I don't know answer for you problem but you can save your model in .h5 format and load it easily.</p>
<p>Example:</p>
<p>save your model using</p>
<blockquote>
<p>model.save('/content/saved_model.h5') </p>
</blockquote>
<p>and load it using</p>
<blockquote>
<p>loaded_model= models.load_model('/content/saved... | tensorflow|keras | -1 |
376,201 | 61,998,848 | print column position of a dataframe | <p>this is my dataframe:</p>
<pre><code>c_id string1 age salary string2
1 apple 21 21.22 hello_world
2 orange 41 23.4 world
3 kiwi 81 20.22 hello
</code></pre>
<p>i need to print the string value which has max_len along with the column datatype, name and its position.so my... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_loc.html" rel="nofollow noreferrer"><code>Index.get_loc</code></a> for position of column:</p>
<pre><code>out = []
for col in df.select_dtypes([np.object]):
max_len = max(df[col], key=len)
print('position:', df.colum... | python|pandas|list|numpy|dataframe | 1 |
376,202 | 61,856,994 | Pandas split cell tex to columns | <p>I have a dataframe with 1 row. </p>
<pre><code> col1
</code></pre>
<p>0 Term: Fall 2020 New Student: First-time Freshmen Run Date: 5/13/2020 </p>
<p>How can I split the text into three columns like below? </p>
<p>My code got an error - 'tuple' obje... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>data['Term'], data['Type'], data['Date'] = data['col1'].str[:4], data['col1'].str[18:29], data['col1'].str[53:61]
data1=pd.DataFrame([], columns=data.columns)
data1['Term'], data1['Type'], data1['Date'] = data['col1'].str[6:15], data['col1'].str[31:50], data['... | python|pandas | 0 |
376,203 | 61,933,773 | Data cleaning/sorting | <p>Fairly new to coding, learning Python as my first language. I have an Excel file full of data. I'm trying to drop columns I don't need and then sort them by Name maybe. Each column would have its title, and I want to keep a few specific columns and delete the rest. Unsure of how to do that. So far :</p>
<pre><code>... | <p>Almost all of your questions about pandas are covered in the docs <a href="https://pandas.pydata.org/pandas-docs/stable/index.html" rel="nofollow noreferrer">here</a>.</p>
<p><code>usecols</code> should help to read only specific columns, you can use ranges like "A:F" or specific column names or a combination of bo... | python|pandas | 0 |
376,204 | 61,832,851 | How do I solve this kind of problem through pandas.cut()? | <p>I have my data as</p>
<pre><code>data = pd.DataFrame({'A':[3,50,50,60],'B':[49,5,37,59],'C':[15,34,43,6],'D':[35,39,10,25]})
</code></pre>
<p>If I use cut this way</p>
<pre><code>p = ['A','S','T','U','V','C','Z']
bins = [0,30,35,40,45,50,55,60]
data['A*'] = pd.cut(data.A,bins,labels=p)
print(data)
</code></pre>
... | <p>Convert column <code>A</code> to strings and categoricals from <code>pd.cut</code> too and join together:</p>
<pre><code>p = ['A','S','T','U','V','C','Z']
bins = [0,30,35,40,45,50,55,60]
data['A*'] = data.A.astype(str) + pd.cut(data.A,bins,labels=p).astype(str)
print(data)
A B C D A*
0 3 49 15 35 ... | pandas | 1 |
376,205 | 62,010,883 | How to create a dictionary dynamically based on number of attributes? | <p>I have a CSV file with 6 attributes and 1 class which I read with Pandas.</p>
<pre><code>CsvFile = "/path/to/file.csv"
df = pd.read_csv(CsvFile)
</code></pre>
<p>First 5 rows of my CSV:</p>
<pre class="lang-none prettyprint-override"><code>x,y,x1,y1,x2,y2,class
92,115,120,94,84,102,3
84,102,106,79,84,102,3
84,102... | <p>If number of keys is the problem you can use</p>
<pre><code>n=0
with open('filename.csv','r') as f:
l=f.readline().strip()
n=len(l.split(','))
</code></pre>
<p>where n holds number of keys</p> | python|pandas|dataframe|dictionary|k-means | 1 |
376,206 | 61,618,893 | Turn pandas dataframe into dictionary | <p>I am running a for loop over a pandas dataframe that takes each row and creates a dictionary (of a sort) then uploads to an internal system. </p>
<p>The for loop isn't a problem, neither is the upload to the internal system. I cannot seem to get the format of the dictionary correct for the upload to proceed. </p>
... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html#pandas-dataframe-to-dict" rel="nofollow noreferrer"><code>to_dict</code></a> with orient="index" </p>
<blockquote>
<p>‘index’ : dict like {index -> {column -> value}}</p>
</blockquote>
<pre><code>d = df.to_dict(... | python|pandas|dictionary | 1 |
376,207 | 61,791,060 | Fill a pandas column according to the value of two other columns | <p>I am trying to fill a column: if the value of a row A is contained in the row of column B, then fill the column C with the value A</p>
<p><strong>I tried:</strong></p>
<pre><code>import pandas
df = pandas.DataFrame([{'A': "a", 'B': ["a"], 'C': ''},
{'A': "b", 'B': ["a", "b"], 'C': ''},
... | <p>Use <code>in</code> statemenet for test values in list:</p>
<pre><code>def fill_row(df):
if df["A"] in df['B']:
val = df["A"]
else:
val = ""
return val
df['C'] = df.apply(fill_row, axis=1)
print (df)
A B C
0 a [a] a
1 b [a, b] b
2 d []
3 c [d, e]
</cod... | python|pandas | 2 |
376,208 | 61,865,420 | Testing and validation of the model | <p>friends. I have a question for you regarding object detection. I trained my model and it works perfectly. Now, I have to make a presentation of my work. The problem is that I saw some things about testing and validation. The problem is that after training, I used the model, but I do not remember to use the test set ... | <p>Here is the main idea of train, test and validation data:</p>
<p>In the beginning you have only one original data set, this set is divided into three distinct subsets: <em>train set</em>, <em>validation set</em> and <em>test set</em>.</p>
<p>You train your model on the train set multiple times, each time with a di... | python|tensorflow|object-detection | 0 |
376,209 | 61,937,985 | Python Pandas, make date time rounding based on value in another column | <p>I need to only select the cases for sensor type == air to be rounded to the nearest 5 seconds but do not how I should use a function to make this happen. </p>
<p>I do have the following lines: </p>
<pre><code>In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'timestamp' : ['2020-04-14 00:00:23', '2020-04-14 0... | <p>One way of solving this is with the <code>apply()</code> function to the DataFrame (not a series). What this does is lets you operate on a per-row basis if you set <code>axis=1</code>. This way, you can specify operations that need to apply to one column but can still access any other column you need to for that row... | python|pandas|function | 1 |
376,210 | 61,946,901 | How to create a column and change it value by for loop? | <p>I am new to python and pandas. I have searched many posts talking about how to change the value of dateframe by condition. However, how if I got a dataframe with a lot of condition?</p>
<p>I have the following dataframe:</p>
<pre><code>import pandas as pd
import datetime as dt
data = {"Project":["A","A","A","B","... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#transformation" rel="nofollow noreferrer"><code>groupby.transform</code></a> with <code>min</code> and <code>max</code> like:</p>
<pre><code>gr = df.groupby('Project')['Date'] #create the grouped object
df['Start'] = gr.transf... | python|pandas | 2 |
376,211 | 61,992,535 | python pandas fill NaN or blanket with max value | <p>I have a problem with a big data frame. Here is a small snippet. I want to fill the last columns E with the maximal value, if there ist some value or let it empty. That is the data:</p>
<pre><code>d = {'A': [4000074, 4000074, 4000074, 4000074, 4000074, 4000074, 4000074, 4000074, 4000074,
4000074, 4000074, 400007... | <p>you can do it with <code>groupby.transform</code> the <code>max</code> of the groups made with a new -1 in column D and <code>cumsum</code>. Then <code>fillna</code> the original column.</p>
<pre><code>df['E'] = df['E'].fillna(df['E'].groupby(df['D'].eq(-1).cumsum()).transform('max'))
</code></pre>
<p>EDIT: to fil... | python|pandas|dataframe | 2 |
376,212 | 61,998,882 | Annotate city names | <p>I would like to annotate the city name Berlin at the coordinates <code>xy=(52.52, 13.405)</code>. I've tried <code>ax.annotate()</code> which yields a strange map. Maybe it has to do with the CRS of the coordinates?</p>
<pre><code>import geopandas as gpd
import contextily as ctx
world = gpd.read_file(gpd.datasets.... | <p>According to <a href="https://matplotlib.org/3.2.1/tutorials/text/annotations.html" rel="nofollow noreferrer">Annotations docpage</a> your code should look like this:</p>
<pre><code>ax.annotate("Berlin", xy=(52.52, 13.405))
</code></pre> | python|matplotlib|geopandas|contextily | 2 |
376,213 | 61,705,858 | Keras: UnboundLocalError: local variable 'logs' referenced before assignment | <p>I am relatively new to python, and while attempting to train a chatbot I received the error: ‘UnboundLocalError: local variable 'logs' referenced before assignment‘. I used model.fit to train:</p>
<pre><code>model.fit(x_train, y_train, epochs=7)
</code></pre>
<p>And I received the error:</p>
<pre><code>UnboundLoc... | <p>This issue looks similar to the problem I had while working with small datasets and it is covered in this thread: <a href="https://github.com/tensorflow/tensorflow/issues/38064" rel="noreferrer">#38064</a>.
I solved my particular issue setting a smaller batch_size, in my case:</p>
<pre><code>batch_size = 2
</code><... | python|tensorflow|keras | 20 |
376,214 | 61,785,498 | multiply dataframes based on timestamp intervals overlap | <p>I have two pandas dataframes, each with two columns: a measurement and a timestamp. I need to multiply the first differences of the measurements, but only if there is a time overlap between the two measurement intervals. How can I do this efficiently, as the size of the dataframes gets large?
Example:</p>
<pre><cod... | <p>Edit: the original answer did not work, so I came up with another version that is not vectorize but they need to be sorted by date.</p>
<pre><code>arrA = dfA.timeA.to_numpy()
startA, endA = arrA[0], arrA[1]
arr_mesA = dfA.mesA.diff().to_numpy()
mesA = arr_mesA[1]
arrB = dfB.timeB.to_numpy()
startB, endB = arrB[0],... | python|python-3.x|pandas|numpy|numexpr | 1 |
376,215 | 61,701,432 | Pandas: Mapping column name from a particular table to a row in another table | <p>Let's say I have the following DataFrames:</p>
<pre><code>table_a = pandas.DataFrame({ 'employee' : ['a','b','c','d','e','f'], 'department' : ['developer', 'test engineer', 'network engineer', 'manager', 'hr','intern']})
dept_mapping = pandas.DataFrame({'department':['developer','test engineer','network engineer',... | <p>You can try <code>idxmax</code> on <code>axis=1</code> with <code>series.map()</code>:</p>
<pre><code>table_a['general department'] = table_a['department'].map(
dept_mapping.set_index('department').idxmax(1))
print(table_a)
</code></pre>
<hr>
<pre><code> employee department g... | python|pandas | 2 |
376,216 | 61,791,032 | How to solve index column issue in Panda while converting to json file? | <p>There is a pandas dataframe as follow :</p>
<p><a href="https://i.stack.imgur.com/jIPLF.png" rel="nofollow noreferrer">df</a></p>
<p>I wanted to create a json file by using this command <code>df.to_json(os.path.join(path, 'test.json'))</code></p>
<p>My desired output is </p>
<pre><code>{"Big": {"A": "Big", "B": ... | <p>It seems that you read your Excel file invoking a command like:</p>
<pre><code>df = pd.read_excel('Input.xlsx', skiprows=2, index_col=0, names=[None, 'A', 'B'])
</code></pre>
<p>i.e.:</p>
<ul>
<li><code>skiprows=2</code> - skip 2 initial empty rows,</li>
<li><code>index_col=0</code> - set column <em>0</em> (in Ex... | json|pandas | 0 |
376,217 | 61,751,704 | Cython min and max on Arrays | <p>I want to speed up a quite simple Python code by converting some functions into cython.
However, in the loop body, I need to find the min and max values of an array and that seems to be the critical point. According to the .html file, these lines need to be translated into very much c-code.. Why is that?</p>
<p>Tha... | <p>Using <code>np.min</code> and <code>np.max</code> will probably be quicker than the Python <code>min</code> and <code>max</code> functions (possibly depending on the size of the array). The Numpy functions will use the C buffer protocol and operate on the C numeric type while the Python ones will use the Python iter... | python|arrays|numpy|cython | 1 |
376,218 | 61,811,257 | Split a multiple dimensional pytorch tensor into "n" smaller tensors | <p>Let's say I have a 5D tensor which has this shape for example : <strong>(1, 3, 10, 40, 1)</strong>. I want to split it into smaller equal tensors (if possible) according to a certain dimension with a <strong>step</strong> equal to <strong>1</strong> while preserving the other dimensions.</p>
<p>Let's say for exampl... | <p>This creates overlapping tensors which what I wanted : </p>
<pre><code>torch.unfold(dimension, size, step)
</code></pre> | python|pytorch|tensor | 2 |
376,219 | 61,616,810 | How to do cubic spline interpolation and integration in Pytorch | <p>In Pytorch, is there cubic spline interpolation similar to <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.CubicSpline.html" rel="noreferrer">Scipy's</a>? Given 1D input tensors <code>x</code> and <code>y</code>, I want to interpolate through those points and evaluate them at <code>xs... | <p>Here is a <a href="https://gist.github.com/chausies/c453d561310317e7eda598e229aea537" rel="nofollow noreferrer">gist</a> I made doing this with <a href="https://en.wikipedia.org/wiki/Cubic_Hermite_spline" rel="nofollow noreferrer">Cubic Hermite Splines</a> in Pytorch efficiently and with autograd support.</p>
<p>For... | python|pytorch|interpolation|numeric | 6 |
376,220 | 62,010,428 | Plotly: How to add vertical lines at specified points? | <p>I have a data frame plot of a time series along with a list of numeric values at which I'd like to draw vertical lines. The plot is an interactive one created using the cufflinks package. Here is an example of three time series in 1000 time values, I'd like to draw vertical lines at 500 and 800. My attempt using "ax... | <h3>The answer:</h3>
<p>To add a line to an existing plotly figure, just use:</p>
<pre><code>fig.add_shape(type='line',...)
</code></pre>
<h3>The details:</h3>
<p>I gather <a href="https://stackoverflow.com/questions/40166463/is-there-a-simple-way-to-plot-vertical-lines-on-scatter-plots-in-plotly">this</a> is the p... | python|pandas|plotly|cufflinks | 6 |
376,221 | 61,611,024 | Python: I would like to return a subset of dataframe based on a list, if the records are ordered the same way the list is | <p>I have a dataframe that has more that a thousand records and I would like to return a sliced dataframe where the values are ordered similarly to the list.</p>
<p>e.g.</p>
<pre><code>lst = [0,1,0,0,0,1]
</code></pre>
<h1>Input</h1>
<pre><code> date season hot_or_cold
0 2012-01-01 Winter 0
1 2012-01-02 Wi... | <p>Define 2 following functions:</p>
<ol>
<li><p>Find match between <em>s</em> (a <em>Series</em>, longer) and <em>lst</em> (a list, shorter).</p>
<pre><code>def fndMatch(s, lst):
len1 = s.size
len2 = len(lst)
for i1 in range(len1 - len2 + 1):
i2 = i1 + len2
if s.iloc[i1:i2].eq(lst).all():... | python|python-3.x|pandas|list | 0 |
376,222 | 61,778,100 | Counting a list of words in a list of strings using python | <p>So I have a pandas dataframe with rows of tokenized strings in a column named story. I also have a list of words in a list called selected_words. I am trying to count the instances of any of the selected_words in each of the rows in the column story. </p>
<p>The code I used before that had worked is </p>
<p><code>... | <p><code>.find()</code> function can be useful. And this can be implemented in many different ways. If you don't have any other purpose for the raw article and it can be a bunch of string. Then try this, you can also put them in a dictionary and loop over.</p>
<pre><code>def find_words(text, words):
return [word f... | python|pandas|count | 0 |
376,223 | 62,031,478 | Updating value of one column in dataframe if ID match found in column of another dataframe | <p>I have two dataframes. The second dataframe is a derived from the first dataframe. I update a column in the second dataframe, and then I want to put the updated values back in the first dataframe. I have tried "merge", but it gives me two columns with suffixes "_x" and "_y"</p>
<pre><code>import pandas
lotQtyQuery... | <p>Please Try use outer merge and drop unrequired rows after you do your filters. Code below. </p>
<pre><code>result=pd.merge(dataFrameOfLots, dataFrameFiltered, how='outer', on=['Customer', 'Stage', 'ProdType', 'Brand', 'ProdName', 'Size',
'Strength', 'Lot', 'PackedOn', 'Qty', 'Available'],suffixes=('_x', ''))... | python|pandas|dataframe|join|merge | 1 |
376,224 | 61,912,391 | Tuning the Model to Obtain Better Performance | <p>I made a model for regression problem which is to predict a value from 9 input variables.
Development of the model is ANN with library of Keras</p>
<p>In this model with compile and fit method, I already predicted the output value.
However, I got the bad evaluate score. I evaluated the model using RMSE and R2</p>
... | <p>There are different techniques to improve performance: </p>
<ul>
<li>you can add more hidden layers; </li>
<li>you can change layers number of units, activation functions and other hyperparameters;</li>
<li>you can try different type of neural network. Where are different types: ResNet, inception blocks, RNN, etc... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
376,225 | 61,867,945 | Python import error: cannot import name 'six' from 'sklearn.externals' | <p>I'm using numpy and mlrose, and all i have written so far is:</p>
<pre><code>import numpy as np
import mlrose
</code></pre>
<p>However, when i run it, it comes up with an error message:</p>
<pre><code> File "C:\Users\<my username>\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mlrose\neural.py"... | <h3>Solution: The real answer is that the dependency needs to be changed by the <code>mlrose</code> maintainers.</h3>
<h3>A workaround is:</h3>
<pre><code>import six
import sys
sys.modules['sklearn.externals.six'] = six
import mlrose
</code></pre> | python|numpy|scikit-learn|python-import|six | 61 |
376,226 | 62,007,858 | If a timestamp in one table is between two time stamps in another table, then increment by 1 using Python Pandas | <p><strong>Summary of the Problem:</strong></p>
<p>I would like to calculate the number of ambulances on a response at any given minute of the day over an entire calendar year.
Two pandas dataframes are generated; The first is the emergency responses of ambulances showing the starting time stamp of the emergency and t... | <p>Using your data I found the following solution. I used only the <strong>first 200 minutes of the year 2020</strong> but you can change that easily by adjusting <code>periods=200</code> to the number of minutes per year.</p>
<p>I used the following <code>variables</code> :
<code>df</code> corresponds to your coinci... | python|pandas|dataframe|datetime|increment | 0 |
376,227 | 61,830,226 | How to add new row in time series dataframe | <p>My dataframe has an index column of dates and one column</p>
<pre><code> var
date
2020-03-10 77
2020-03-11 88
2020-03-12 99
</code></pre>
<p>I have an array and I want to append it to the dataframe one by one. I have tried a few methods but anything isn't working.
my code is something like this... | <p>Try this</p>
<pre><code>tmpdf = pd.DataFrame({"var":[77,88,99]},index=pd.date_range("2020-03-10",periods=3,freq='D'))
for i in range(1,21):
idx = tmpdf.tail(1).index[0] + pd.Timedelta(days=1)
tmpdf.loc[idx] = i*i
</code></pre>
<p>output</p>
<pre><code>2020-03-10 77
2020-03-11 88
2020-03-12 99
2020-0... | python|pandas|python-2.7|dataframe|time-series | 1 |
376,228 | 61,970,972 | How to put image uploaded in tkinter into a function? | <p>I am trying to create a Python tkinter application where the user can upload an image from file and the image is put through a image segmentation function which outputs an matplotlib plot.</p>
<p>I have the image segmentation function, it takes two parameters: neural network, image file pathway.</p>
<pre><code>fro... | <p>Firstly import <code>filedialog</code> and <code>PIL</code>:</p>
<pre><code>from tkinter import filedialog
from PIL import Image
</code></pre>
<p>Now use a variable path (or anything) to define the path that is returned when you choose inside of a GUI.</p>
<pre><code>path = filedialog.askopenfilename(initialdir='/Do... | python|numpy|tkinter|pytorch | 1 |
376,229 | 61,802,666 | Multiplying columns with missing values in Python (pandas) | <p>I have a dataset with multiple columns which i need to multiply. One of these columns have missing values in them, what I would like is that when I am multiplying the columns, the missing values are skipped, and the columns which do have values in them are used for the result.</p>
<p>For example,</p>
<pre><code>A B ... | <p>Here's an example of utilizing <code>.fillna()</code>:</p>
<pre><code>import pandas as pd
import numpy as np
data = pd.DataFrame({"a":[3,6,7],"b":[2,5,7],"c":[5,np.nan,np.nan]})
</code></pre>
<p>A quick look at <code>data</code>:</p>
<pre><code>a b c
3 2 5.0
6 5 NaN
7 7 NaN
</code></pre>
<p>Then... | python|python-3.x|pandas|dataframe | 2 |
376,230 | 61,917,991 | Finding highest n values of every column in dataframe | <p>I want to find the highest 3 values of each column in a dataframe, and return the index names, ordered by value. The dataframe looks like this:</p>
<pre><code>df = pd.DataFrame({"u1":[1,2,-3,4,5],
"u2":[8,-4,5,6,7],
"u3":[np.NaN,np.NaN,np.NaN,np.NaN,np.NaN]},
... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.nlargest.html" rel="nofollow noreferrer"><code>pandas.Series.nlargest</c... | python|python-3.x|pandas | 5 |
376,231 | 61,642,363 | No module named 'torch.autograd' | <p>Working with torch package:</p>
<pre><code>import torch
from torch.autograd import Variable
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]
w = Variable(torch.Tensor([1.0]), requires_grad = True)
def forward(x):
return x*w
def loss(x,y):
y_pred = forward(x)
return (y_pred-y)*(y_pred-y)
print("my prediction ... | <p>It seems to me that you have installed pytorch using conda.
Might be you have <strong>torch</strong> named folder in your current directory.
Try changing the directory, or try installing pytorch using pip.
This <a href="https://github.com/pytorch/pytorch/issues/1851" rel="nofollow noreferrer">https://github.com/pyt... | python|pytorch|conda | 1 |
376,232 | 61,774,477 | plotting points with list logical comparison | <p>I have a file containing 6 columns. I want to separate some parts of this file and then plot them so I have read them by numpy and defining empty space to store the points which I needed. To fill the array I have defined a condition then filling array. I faced an error of </p>
<pre><code>ValueError ... | <p>Try the following using <code>all()</code> since <code>near</code> seems to be a list:</p>
<pre><code>for i in range(1,len(x)):
if all(ii>=0.0 for ii in near):
xx.append(x[i])
yy.append(y[i])
</code></pre> | python|numpy|matplotlib | 1 |
376,233 | 61,954,571 | How to add unbalanced List into a dataFrame in Python? | <p>Here is My dataframe and List</p>
<pre><code>
X Y Z X1
1 2 3 3
2 7 2 6
3 10 5 4
4 3 7 9
5 3 3 4
list1=[3,5,6]
list2=[4,3,7,4]
</code></pre>
<p>I want to add the lists into a data frame, I have tried some code but it gives an error and something is not working</p>
<pre><code>#Expected Output
X ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.append.html" rel="nofollow noreferrer"><code>series.append()</code></a> to create the new series (<code>X</code> & <code>X1</code>), and create the output <code>df</code> using <a href="https://pandas.pydata.org/pandas-docs/sta... | python|pandas | 3 |
376,234 | 61,990,016 | Efficiently check if an array is jagged | <p>I'm looking for an efficient way to check if an array is jagged, where "jagged" means that an element of the array has a different shape from one of it's neighbors in the same dimension.</p>
<p>e.g. <code>[[1, 2], [3, 4, 5]]</code> or <code>[[1, 2], [3, 4], [5, 6], [[7], [8]]]</code></p>
<p>Where I'm using list sy... | <p>Perhaps not the most efficient but it works nicely in numpy. <code>and</code> will short circuit as soon as one of the conditions is <code>False</code>. If the first three conditions are <code>True</code>, we have no choice but to iterate through the rows.</p>
<p>Thankfull, <code>all</code> will shortcircuit as soon... | python|arrays|numpy | 1 |
376,235 | 61,793,268 | Pytorch Siamese Network not converging | <p>Good morning everyone</p>
<p>Below is my implementation of a pytorch siamese network. I am using 32 batch size, MSE loss and SGD with 0.9 momentum as optimizer.</p>
<pre><code>class SiameseCNN(nn.Module):
def __init__(self):
super(SiameseCNN, self).__init__() # 1, 40,... | <p>I think that your approach is correct and you are doing things fine. What looks a bit weird to me is the last layer which has a RELU activation. Usually with Siamese networks you want to output a high probability when the two input images belong to the same class and a low probability otherwise. So you can implement... | python|pytorch|convergence|siamese-network | 1 |
376,236 | 62,022,108 | Ordering hierarchical data in a pivot-like way | <p>I have a hierarchical dataset which needs to be presented in a certain way. Items of the same hierarchy paths needs to be presented in successive order. Further parents should be listed above their children.<br />
Appreciate any guidance to achieve the same..</p>
<p>Thank You</p>
<p>** sample dataset **</p>
<pre><co... | <p>As the title states that the question is about hierarchies, the solution is should be found in some network packages like <a href="https://networkx.org/" rel="nofollow noreferrer">networkx</a> or <a href="https://igraph.org/" rel="nofollow noreferrer">igraph</a>. I am not an expert in that tools, so I give an abstra... | python|pandas | 0 |
376,237 | 61,633,602 | Binary classification using Keras always give wrong predictions: The acc is always 0.5 | <p>Hi~ I am using Keras to make a simple binary classification. And I am using TF as backend.</p>
<p>I checked:</p>
<ul>
<li>data shuffle: I set the param in model.fit() shuffle = True</li>
<li>network structure: The NN take a vector with 1024 elements and makes a prediction 0 or 1.</li>
</ul>
<p>ENV: tensorflow 1.1... | <p>Root-cause of the issue is related to numerical instabilities of sigmoid activation in the final layer of model when used with tensorflow-cpu version.I changed two lines in your code as follows and got the similar as you get with TF1.15. Please check the <a href="https://github.com/jvishnuvardhan/Stackoverflow_Quest... | python|tensorflow|keras|deep-learning | 1 |
376,238 | 58,151,934 | Convert an object datatype column with format mm:ss to a time format pandas | <p>I have a dataframe that has an column that has an object datatype with the format mm:ss. I want to convert that column to a time format so that I could turn the time into seconds instead of mm:ss. However, I have not been able to convert the column into a time format. </p>
<p>Example of my data:</p>
<pre><code>... | <p>Just add '00:' to the beginning.</p>
<pre><code>df['time'] = pd.to_timedelta('00:' + df['time'])
df['total seconds'] = df['time'].dt.total_seconds()
</code></pre> | python|python-3.x|pandas | 0 |
376,239 | 58,107,652 | Comparing one dataframe against another with pandas | <p>Good Afternoon,</p>
<p>I want to compare dataframe "new" against dataframe "old" to get a new dataframe with data that <em>only</em> exists in "new" but <em>not</em> old. For example</p>
<pre><code>New Old Desired Output
--- --- --------------
1 1 4
3 2 7
4 3
5 5
7 8
8 9
9 0
</code>... | <p>Utilizing <code>set()</code> here will help with providing values in <code>New</code> and not in <code>Old</code>. Then filter based on the resulting list.</p>
<pre><code>df1 = pd.DataFrame(data=[1,2,3,4,5,7,8,9], columns=['New'])
df2 = pd.DataFrame(data=[1,2,3,5,8,9,0], columns=['Old'])
df1_unique = set(df1['New... | python|pandas|dataframe | 1 |
376,240 | 57,955,558 | Python Pandas : Unable to return dictionary in two different columns based on groupby | <p>I have dataframe which is like below,</p>
<pre><code>df1:
mac gw_mac building rssi type payload
0 0010403bf0db b827eb36fb0b main -45 iBeacon e2c56db5dffb48d2b060d0f5a71096e0
1 0010403bf0db d827fc36gc0c main -67 other 02010612ff590080bc2c01001d0b3a00000005000000
2 bf0d... | <p>First let's see how to add one column of dictionary from groupby object:</p>
<pre><code>df.groupby(['mac','building']).apply(lambda x: dict(zip(x['gw_mac'],x['rssi'])))
</code></pre>
<p>Then for two columns simultaneously generated, we need to return <code>pandas.Series</code> from the lambda function, then it bec... | python-3.x|pandas|dictionary|pandas-groupby | 3 |
376,241 | 58,067,594 | Getting the image name using autoencoder on tensorflow | <p>I'm using this tensorflow image search script:
<a href="https://www.kaggle.com/jonmarty/using-autoencoder-to-search-images" rel="nofollow noreferrer">https://www.kaggle.com/jonmarty/using-autoencoder-to-search-images</a></p>
<pre><code>def search(image):
hidden_states = [sess.run(hidden_state(X, mask, W, b),
... | <p>You need to modify the search function.</p>
<p>Specifically, look at the line:</p>
<pre><code>best_states.append(imported_images[i])
</code></pre>
<p>If you want to map between the images returned and the filenames, you need to record and return that index, <code>i</code>. Consider adding a <code>best_states_ind... | python|tensorflow | 0 |
376,242 | 57,797,021 | I have question about group by how to use it? | <p>so, how to split it
as I want to know the group by and by split </p> | <p>You'll need to 'chunk' it into groups of 30. To do this, you can use the // operator on the index, which divides by 30 and rounds down to the nearest whole number.</p>
<p>Using 'unstack()' at the end will reshape the dataframe into the format you want. </p>
<pre><code>df.groupby([df.index // 30,'sex']).sum().unsta... | python|python-3.x|pandas|pandas-groupby|sklearn-pandas | 0 |
376,243 | 58,099,214 | bokeh: How to edit a df or CDS-object through box_select? | <p>I'm trying to label a pandas-df (containing timeseries data) with the help of
a bokeh-lineplot, box_select tool and a TextInput widget in a jupyter-notebook. How can I access the by the box_select selected data points?</p>
<p>I tried to edit a similar problems code (<a href="https://stackoverflow.com/questions/341... | <p>The main thing to note is that BokehJS can only <em>automatically</em> notice updates when actual assignments are made, e.g. </p>
<pre><code>source.data = some_new_data
</code></pre>
<p>That would trigger an update. If you update the data "in place" then BokehJS is not able to notice that. You will have to be expl... | python|bokeh|pandas-bokeh | 1 |
376,244 | 57,975,173 | How to extract values from json-like text | <p>I want to extract values from json-like text which look like:</p>
<pre><code>df.head()
budget genres homepage id keywords original_language original_title overview popularity production_companies ... runtime spoken_languages status tagline title vote_average vote_count movie cast ... | <p>I think problem is with bad values, one possible solution is create custom function with <code>try-except</code> statement:</p>
<pre><code>df = pd.DataFrame({'genres':['[{"id": 28, "name": "Action"}]',
'[{"id": 28, "name": "Action"}, {"id": 12, "n]']})
print (df)
... | python|json|pandas | 2 |
376,245 | 58,013,898 | Problem with Keras LSTM input_shape: expected lstm_1_input to have shape (500, 2) but got array with shape (500, 5) | <p><code>x_train</code> and <code>y_train</code> are input and output of my model with shapes of <code>(6508, 500, 5), (6508, 5)</code> respectively.</p>
<p>And the model is like this:</p>
<pre class="lang-py prettyprint-override"><code>model = Sequential()
model.add(LSTM(units=96, return_sequences=True, input_shape=... | <p>Mentioning the Solution in Answer Section for the Benefit of the Community.</p>
<p>Using <code>tf.keras</code> instead of <code>keras</code> has resolved the problem.</p> | python|tensorflow|keras|deep-learning|lstm | 0 |
376,246 | 57,964,805 | Offset groupby difference by one row | <p>I have a dataframe that looks like this:</p>
<pre><code>first client last_visit theme_type days_borrowed
----------------------------------------------------------
Y A 4/23/2019 Candy 0
N A 5/5/2019 Jewel 12
N A 5/8/2019 Chocolat... | <ol>
<li>Use <code>-1</code> for the <code>periods</code> argument of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.html" rel="nofollow noreferrer"><code>diff</code></a> then take the absolute value.</li>
<li><code>fillna</code> with your desired calculation.</li>
</ol>
<h3>C... | python|python-3.x|pandas|pandas-groupby | 2 |
376,247 | 57,890,719 | Merge similar strings together in pandas column | <p>I have pandas crosstab dataframe which looks like this:<a href="https://i.stack.imgur.com/Jl6MP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jl6MP.png" alt="enter image description here"></a></p>
<p>This is a small sample of the whole dataframe. As you can see, sku1_entity has some strings lik... | <p>Not a universal solution but it should give you an idea how you could tackle it: use some function to 'normalize' your <code>sku1_entity</code> column and group on these normalized values like that:</p>
<pre><code>df = pd.DataFrame( {'sku1_entity': ['4 Cheese W Verm','4 Cheese w Verm','4Cheese w Verm', 'something e... | python|string|pandas|dataframe|fuzzywuzzy | 0 |
376,248 | 58,075,544 | Groupby for selecting multiple columns Pandas python | <p>I have a table pandas dataframe df with 3 columns lets say:</p>
<pre><code>[IN]:df
[OUT]:
Tree Name Planted by Govt Planted by College
A Yes No
B Yes No
C Yes No
C Yes No
A No ... | <p>First create boolean mask by compare both column chained with <code>&</code> for bitwise <code>AND</code> and then convert to numeric with aggregate <code>sum</code>:</p>
<pre><code>s = df['Planted by Govt'].eq('Yes') & df['Planted by College'].eq('No')
out = s.view('i1').groupby(df['Tree Name']).sum()
#alt... | python|pandas|group-by | 1 |
376,249 | 57,989,716 | Loading .npy files as dataset for pytorch | <p>I have preprocessed data in .npy files, let's call it X.npy for raw data and Y.npy for labels. They're organized to match every element from both files (first element from X has first label from Y etc.). How can I load it as dataset using <code>torch.utils.data.DataLoader</code>? I'm very new to pytorch, and any hel... | <p>You could also use DatasetFolder, which basically is the underlying class of ImageFolder. Using this class you can provide your own file extensions and loader to load the samples.</p>
<pre class="lang-py prettyprint-override"><code>def npy_loader(path):
return torch.from_numpy(np.load(path))
</code></pre> | python|numpy|serialization|pytorch | 5 |
376,250 | 57,838,944 | Read Excel file with blank cells as Pandas dataframe with multiindex | <p>Suppose there is a Excel file:</p>
<p><a href="https://i.stack.imgur.com/3DnEB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3DnEB.png" alt="enter image description here"></a></p>
<p>Is there a way to read it directly as a Pandas dataframe with multiindex, without filling blank spaces in the f... | <h2>Data:</h2>
<p><a href="https://i.stack.imgur.com/GeAjv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GeAjv.png" alt="enter image description here"></a></p>
<h2>Code:</h2>
<pre><code>df = pd.read_excel('test.xlsx')
</code></pre>
<p><a href="https://i.stack.imgur.com/wfgpm.png" rel="nofollow ... | python|pandas | 2 |
376,251 | 57,836,849 | Tensorflow.Keras: Custom Constraint Not Working | <p>Im trying to implement the Weights Orthogonality Constraint showed <a href="https://towardsdatascience.com/build-the-right-autoencoder-tune-and-optimize-using-pca-principles-part-ii-24b9cca69bd6" rel="nofollow noreferrer">here</a>, in section 2.0. when i try to use it on a Keras Dense Layer, An Value Error is raised... | <p>I manage to solve this problem:</p>
<p>the function causing the error was tf.keras.backed.eye() on line 14. I read out there that the implementation in the keras backend of this function use numpy array for the identity matrix, but tensorflow and other backends already have their impementation for this function usi... | python|python-3.x|tensorflow|tf.keras | 3 |
376,252 | 58,050,020 | Is there a handy way to dump the running_stats for a pytorch model? | <p>I'm writing a C version of the pytorch model to run it on my special hardware.
Everything looks ok so far, except the running_mean and running_var in every batchnorm layer.</p>
<p>We have a python code to dump all named_parameters, but nothing to do for the running_stats, although we need to use it in the forwardin... | <p><code>running_mean</code> and others are <code>registered_buffers</code> in PyTorch. You can save (as you say dump) them with <code>torch.nn.Module</code>'s <a href="https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict" rel="nofollow noreferrer"><code>state_dict</code></a>:</p>
<pr... | pytorch | 1 |
376,253 | 57,732,470 | Sort dates of multiple json files with python | <p>I got multiple json files and I am trying to sort them by date. I managed to print them out in 2 columns, DATE and TEXT, but the DATES are not in order. </p>
<p>When I try to mess around with datetime, nothing happens. I'm sure there's an easy solution, but I just can't find it. </p>
<pre class="lang-py prettyprin... | <pre><code>jsons_data['DATE'] = pd.to_datetime(jsons_data['DATE'])
jsons_data = jsons_data.sort_values('DATE')
</code></pre>
<p>This might help.</p> | python|json|pandas|datetime | 0 |
376,254 | 57,828,510 | Value Error: time data '12:00:01 AM' does not match format '%I:%M:00 %p' using time.strptime | <p>I'm a bit new to python so any help is greatly appreciated. Thanks in advance (and sorry for any mislabel).</p>
<p>I'm working on a csv file containing columns with Date, Time, CO, CO2 and CH4. What I want to achieve is to make a loop so that every time there is a time with zero seconds (ex: "12:00:00 AM", "3:05:00... | <p>If you want to skip errors, then you should use <code>try</code> and <code>except</code></p>
<pre><code>for i in data1["TIME"]:
try:
time.strptime(i,"%I:%M:%S %p")
if time.strptime(i,"%I:%M:%S %p") == time.strptime(i,"%I:%M:00 %p"):
print("Found a number!", i)
... | python|pandas|dataframe|time|jupyter-notebook | 0 |
376,255 | 58,170,435 | Generate dictionary from a pandas dataframe with multiple columns combined as the keys, remaining columns as values? | <p>I'm trying to generate a dictionary from a pandas dataframe. Specifically, I need to:</p>
<ol>
<li><p>Take the first (x) columns and use the data points in each of their rows, together, as keys. </p></li>
<li><p>Compile a dictionary for each key using the remaining data points in the row as values, as a list. </p><... | <p>Assuming the following DataFrame:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([
{'c1': 'a1', 'c2': 110, 'c3': 'xyz', 'c4': 24},
{'c1': 'b2', 'c2': 100, 'c3': 'jdf', 'c4': 15},
{'c1': 'a1', 'c2': 110, 'c3': 'kjl', 'c4': 125},
{'c1': 'b2', 'c2': 100, 'c3': 'abc', 'c4': 71},
])
</code></pre>
... | python|pandas|list|dictionary | 1 |
376,256 | 57,909,222 | Pandas Shift Row Value to Match Column Name | <p>I have a sample dataset that has a set list of column names. In shifting data around, I have each row printing letters in each row as seen below.</p>
<p>I am trying to shift the values of each row to match either respective column. I have tried doing pd.shift() to do so but have not had much success. I am trying to... | <p>This is more list <code>pivot</code> problem </p>
<pre><code>s=df.mask(df=='').stack().reset_index()
s.pivot(index='level_0',columns=0,values=0)
Out[34]:
0 A B C D
level_0
0 A B C D
1 A NaN C NaN
2 A NaN C D
</code></pre> | python|pandas|pandas-groupby | 3 |
376,257 | 57,795,370 | Data resolution change in Pandas | <p>I have a dataframe whose data has a resolution of 10 minutes as seen below:</p>
<pre><code> DateTime TSM
0 2011-03-18 14:20:00 26.8
1 2011-03-18 14:30:00 26.5
2 2011-03-18 14:40:00 26.3
... ... ...
445088 2019-09-03 11:40:00 27.6
445089 2019-09-03 11:50:00 ... | <p>Your dataframe should have datetime index in order to use <code>resample</code> method. Also you need to apply an aggregate function, for example <code>mean()</code></p>
<pre><code># Make sure DateTime type is datetime
df['DateTime'] = df['DateTime'].astype('datetime64')
# Set DateTime column as index
df.set_inde... | python-3.x|pandas | 2 |
376,258 | 58,042,419 | Unexpected results on groupby([]).sum() | <pre class="lang-py prettyprint-override"><code>n = df1.groupby(['Year', 'State', 'Regulator', 'Industry','Product', 'Count']).sum() # <-- this produces the error
</code></pre>
<p>Problem description
[Hi, I think there's a problem dropping/excluding data points with groupby.sum function. I've performed the foll... | <p>Problem solved. I've had ran the code including and excluding the Column ['Count'] from the code which gave me a mix of good and bad results. For some reason the CSV wasn't being read correctly if that makes any sense. Column ['Count'] was dtypes int, but it seems was being read as string. So i did a .apply(pd.to_nu... | pandas|pandas-groupby | 0 |
376,259 | 58,117,330 | I need to insert a row at nth index that will take summation of all rows that are underneath it | <p>I have a dataframe with 30 rows. I need to insert a row at the 10th index, give it a name and then have all the cells in it, be the summation of all cells that are underneath it. It will represent a total of the lower performing parts. </p>
<pre><code>pd.DataFrame(np.insert(df.values, 0,)
</code></pre>
<p>I would... | <p>I pandas exist <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html" rel="nofollow noreferrer"><code>DataFrame.insert</code></a>, but working only for columns, so is necessary something more complicated:</p>
<pre><code>df = pd.DataFrame({
'B':[4,5,4,5,5,4],
... | python|pandas|dataframe | 2 |
376,260 | 57,801,680 | How can I use GPU for running a tflite model (*.tflite) using tf.lite.Interpreter (in python)? | <p>I have converted a tensorflow inference graph to tflite model file (*.tflite), according to instructions from <a href="https://www.tensorflow.org/lite/convert" rel="nofollow noreferrer">https://www.tensorflow.org/lite/convert</a>.</p>
<p>I tested the tflite model on my GPU server, which has 4 Nvidia TITAN GPUs. I u... | <p><a href="https://github.com/tensorflow/tensorflow/issues/34536" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/34536</a></p>
<p>CPU is kind of good enough for tflite, especially multicore. </p>
<p>nvidia GPU likely not updated for tflite, which is for mobile GPU platform. </p> | python|tensorflow|interpreter|tensorflow-lite | 0 |
376,261 | 57,891,587 | Sorting dataframe based on multiple columns and conditions | <p>I am trying to sort the following dataframe based on <code>rolls</code> descending first, followed by <code>diff_vto</code> ascending for positive values, finally by <code>diff_vto</code> ascending for negative values. This is the original dataframe:</p>
<pre><code> day prob vto rolls diff diff_vto
0 1 ... | <p>You want to sort by <code>diff_vto>0</code> and <code>abs(diff_vto)</code>, both decreasing:</p>
<pre><code>df['pos'] = df['diff_vto'].gt(0)
df['abs'] = df['diff_vto'].abs()
df.sort_values(['rolls', 'pos', 'abs'], ascending=[False, False, False])
</code></pre>
<p>Output (you can drop <code>pos</code> and <code... | python|pandas|sorting | 2 |
376,262 | 58,165,203 | KeyError: 'class' while using ImageDataGenerator.flow_from_dataframe | <p>I am trying to create data generator using ImageDataGenerator.flow_from_dataframe but facing keyerror: class</p>
<p>Before using flow_from_dataframe, i created a pivot of training dataframe where class labels are converted to columns</p>
<pre><code>train_df = train[['Label', 'filename', 'subtype']].drop_duplicates... | <p>Can you try this, basically setting <code>class_mode</code> to <code>other</code> </p>
<pre><code>columns=["any", "epidural", "intraparenchymal","intraventricular", "subarachnoid", "subdural"]
train_generator=datagen.flow_from_dataframe(
directory="/kaggle/input/rsna-intracranial-hemorrhage-detection/stage_1_train_... | python-3.x|pandas|tensorflow|keras|conv-neural-network | 0 |
376,263 | 58,007,391 | Attention Text Generation in Character-by-Character fashion | <p>I am searching the web for a couple of days for any <strong>text generation</strong> model that would use only attention mechanisms.</p>
<p>The <strong>Transformer</strong> architecture that made waves in the context of <strong>Seq-to-Seq</strong> models is actually based solely on <strong>Attention</strong> mechan... | <p>Building a character-level self-attentive model is a challenging task. Character-level models are usually based on RNNs. Whereas in a word/subword model, it is clear from the beginning what are the units carrying meaning (and therefore the units the attention mechanism can attend to), a character-level model needs t... | neural-network|nlp|pytorch|transformer-model|attention-model | 1 |
376,264 | 57,901,697 | Keras model evaluation accuracy unchanged, and designing model | <p>I'm trying to design a CNN in Keras to classify small images of emojis in other images. Below is an example of one of the 13 classes. All images are the same size and all the emojis are of the same size as well. I would think that one should rather easily be able to achieve VERY high accuracy when classifying, as em... | <p>I think the main issue currently is that your model has way too many parameters relative to how few samples you have for training. For image classification nowadays, you generally want to just have conv layers, a Global<em>Something</em>Pooling layer, and then a single Dense layer for your outputs. You just need to ... | python|tensorflow|keras|deep-learning|multiclass-classification | 0 |
376,265 | 57,868,723 | How to replace a loop that looks at multiple previous values with a formula in Python | <p><strong>My Problem</strong></p>
<p>I have a loop that creates a column using either a formula based on values from other columns or the previous value in the column depending on a condition ("days from new low == 0"). It is really slow over a huge dataset so I wanted to get rid of the loop and find a formula that i... | <p>Try this one:</p>
<pre class="lang-py prettyprint-override"><code>df["mB_temp"] = (df["RSI on new low"].shift() - df["RSI on new low"]) / -df["days from new low"].shift()
df["mB"] = df["mB"].shift()
df["mB"].loc[df["days from new low"] == 0]=df["mB_temp"].loc[df["days from new low"] == 0]
df.drop(["mB_temp"], axis=... | python|database|pandas|loops | 1 |
376,266 | 57,820,916 | Pandas pivot_table: `margins=True` shows `NaN` with `Period` columns | <p>The following code reproduces the issue I'm having:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame(
{
"a": [1, 1, 2, 2],
"b": [
pd.Period("2019Q1"),
pd.Period("2019Q2"),
pd.Period("2019Q1"),
pd.Period("20... | <p>If anyone else stumbles across this issue, it is indeed a bug, the relevant GitHub issues are <a href="https://github.com/pandas-dev/pandas/issues/28323" rel="nofollow noreferrer">#28323</a> and <a href="https://github.com/pandas-dev/pandas/issues/28337" rel="nofollow noreferrer">#28337</a></p>
<hr>
<p>The underly... | python|pandas | 0 |
376,267 | 58,107,700 | Raise Elements of Array to Series of Exponents | <p>Suppose I have a numpy array such as:</p>
<pre><code>a = np.arange(9)
>> array([0, 1, 2, 3, 4, 5, 6, 7, 8])
</code></pre>
<p>If I want to raise each element to succeeding powers of two, I can do it this way:</p>
<pre><code>power_2 = np.power(a,2)
power_4 = np.power(a,4)
</code></pre>
<p>Then I can combine ... | <p>One thing to observe is that x^(2^n) = (...(((x^2)^2)^2)...^2)
meaning that you can compute each column from the previous by taking the square.</p>
<p>If you know the number of columns in advance you can do something like:</p>
<pre><code>import functools as ft
a = np.arange(5)
n = 4
out = np.empty((*a.shape,n),a... | python|numpy | 1 |
376,268 | 58,077,373 | Use numpy structured array instead of dict to save space and keep speed | <p>Are <code>numpy</code> structured arrays an alternative to Python <code>dict</code>?</p>
<p>I would like to save memory and I cannot affort much of a performance decline.</p>
<p>In my case, the keys are <code>str</code> and the values are <code>int</code>.</p>
<p>Can you give a quick conversion line in case they ... | <p>Maybe a bit late, but in case others have the same question, I did a simple benchmarking:</p>
<pre><code>In [1]: import random
In [2]: import string
In [3]: import pandas as pd
In [4]: import sys
In [5]: size = 10**6
In [6]: d = {''.join(random.choices(string.ascii_letters + string.digits, k=32)): random.randra... | python|numpy|dictionary|time-complexity|structured-array | 2 |
376,269 | 57,982,349 | Writing dataframes to multiple sheets in existing Excel file. Get 'We Found Problem with some content in X.xlsx' when opening excel file | <p>I'm creating a few dfs based on existing excel files. I'm then writing each of those dfs to their own separate sheet in a different (existing excel) file. Script executes fine, but when I open the excel file the dfs were written to I get the following error msg: "We found a problem with some content in 'X.xlsx'...</... | <p>Hit the same issue with openpyxl, but actually it might not be the problem of openpyxl.</p>
<p>Based on my experience, after I got a pop window with "Alert We found a problem with some content in......". Just look into what was the error, and finally found that, in Excel if the data format is "General", you cannot ... | excel|pandas|openpyxl | 1 |
376,270 | 57,758,267 | Pandas rolling aggregate list of functions. ValueError: no results | <p>Aggregate method after rolling doesn't work for list of functions.</p>
<p>This code rises an Valueerror.</p>
<pre><code>df = pd.DataFrame({'col1':range(3), 'date':pd.date_range('2018-01-01', '2018-01-03')})
df.rolling('6D', min_periods=1, on='date', closed='left').agg([sum])
</code></pre>
<p>BUT this code works f... | <p>I find a workaround. I don't know why but we need to use date columns as index in that case.</p>
<pre><code>df.set_index('date').rolling('6D', min_periods=1, closed='left').agg(['sum','max'])
</code></pre>
<p>result</p>
<pre><code> col1
sum max
date
2018-01-01 NaN 0.0... | python|pandas|aggregate|rolling-computation | 0 |
376,271 | 34,228,138 | Doesn't work example with Keras framework | <p>I am trying to study <code>Keras</code> library and created follow script as example:</p>
<pre><code>from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
from keras.utils import np_utils
import pandas as pd
import numpy as np
import time
impo... | <p>Check this line in your code</p>
<pre><code>model.add(Dense(64, input_dim=20, init='uniform'))
</code></pre>
<p>Why 20 input dimensions? MNIST has 28X28 images, i.e. an input dimension of <code>784</code>. The error message confirms that as well:</p>
<pre><code>ValueError: ('shapes (9,784) and (20,64) not aligned... | python|pandas|theano|deep-learning|keras | 2 |
376,272 | 34,212,605 | pandas v0.17.1 not working with py2exe | <p>I Have a problem with python pandas v0.17.1. I upgraded from v0.16.2.
System:</p>
<p>Win10 x64, Python 3.4 64Bit, using PyCharm Community Edition for coding.
(numpy 1.9.3+mkl)</p>
<p>I'm using py2exe to create a stand-alone of a statistics program, using pandas to hold the data, matplotlib for plotting and pyqt4 f... | <p>I solved my problem. It was my AVAST Anti-Virus. It's 'deepscreen' feature started the programm in the background as a sandbox and analysed the .exe but never informed me about it running in the back (no info baloon etc.).</p>
<p>By chance, i had it deactivated while looking into Calvin's Answer.</p>
<p>It works o... | python|pandas|pyqt4|py2exe | 1 |
376,273 | 34,192,927 | How to modify the time that 'date' changes (00:00:00) in an index in Pandas dataframe? | <p>I have a dataframe that looks like this:</p>
<pre><code>Date and Time Close dif
2015/01/01 17:00:00.211 2030.25 0.3
2015/01/01 17:00:02.456 2030.75 0.595137615
2015/01/01 23:55:01.491 2037.25 2.432613592
2015/01/02 00:02:01.955 2036.75 -0.4
2015/01/02 00:04:04.887 2036.5 -0.391144414
2015/01/02 15:14:5... | <p>Is this what you are looking for?</p>
<pre><code># read in your dataframe
import pandas as pd
df = pd.read_csv('dt_data.csv', skipinitialspace=True)
df.columns = ['mydt', 'close', 'dif'] # changed your column name to 'mydt'
df.mydt = pd.to_datetime(df.mydt) # convert mydt to datetime so we can operate on it
# keep... | python|python-2.7|pandas|indexing | 1 |
376,274 | 34,132,279 | numpy build with mingw fails on Window with AttributeError: Mingw32CCompiler instance has no attribute 'compile_options', How to resolve this? | <p>I've downloaded the numpy source from <a href="https://github.com/numpy/numpy" rel="nofollow">git-hub</a>, I also have mingw installed and all the paths set on Windows, I can compile C files with mingw just fine so this is also working.<br>
I'm following instructions on <a href="http://www.scipy.org/scipylib/buildin... | <p>In your distribution, add the following code at line 194 of file numpy\core\setup_common.py and rebuild. It should allow you to build.</p>
<pre><code> except AttributeError:
pass
</code></pre> | python|windows|numpy | 1 |
376,275 | 34,298,129 | Select values in Pandas groupby dataframe that are present in n previous groups | <p>I have a Pandas dataframe <code>groupby</code> object which looks like the following:</p>
<pre><code> ID
2014-11-30 1
2
3
2014-12-31 1
2
3
4
2015-01-31 2
3
4
2015-02-28 1
3
4
5
2015-03-31 1
2
4... | <p>This would seem to work:</p>
<pre><code>def filter_unique(df, n):
data_by_date = df.groupby('date')['ID'].apply(lambda x: x.tolist())
filtered_data = {}
previous = []
for i, (date, data) in enumerate(data_by_date.items()):
if i >= n:
if len(previous)==1:
filte... | python|pandas|group-by | 1 |
376,276 | 34,213,946 | Force Python Pandas DataFrame( read_csv() method) to avoid/not consider first row of my csv/txt file as header | <p>I am reading a txt file (data.txt) using pandas read_csv method. The file has 16 columns and 600 rows. However, after reading the csv into dataframe, I observed that first row in my data.txt file has been taken as the column headings in the dataframe. This reduces the size of my dataframe to 599 from 600 in my text ... | <p>Just add header=None: </p>
<pre><code>import pandas as pd
df = pd.read_csv("C:\<my_directory_path>\data.txt",header=None)
</code></pre> | python|csv|pandas|dataframe | 1 |
376,277 | 34,127,559 | Finding intersection of points on a python graph generated by a list of points | <p>I'm trying to find the intersection between two lines that were generated by a list of points.</p>
<p>I had two list of points, and then I plotted them using</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
a = arrayOfPoints1
plt.plot(*zip(*a))
b = arrayOfPoints2
plt.plot(*zip(*b))
plt.show()
</c... | <p>If both graphs use the same X-axis values (different functions evaluated on the same array), you could do it manually by direct computation of the intersection of each consecutive pair of segments. You have to consider several cases (if the segments are parallel, etc). Intersection can be calculated with the equatio... | python-2.7|numpy|matplotlib | 1 |
376,278 | 34,001,816 | Scipy: Partition array into 3 subarrays | <p>I am trying to figure out whether there's a numpy/scipy function to efficiently partition an array into subarrays using a certain rule.</p>
<p>My problem is the following:
I have a nxn matrix, lets call it W. And I have a vector h.
I now want to partition the column vectors of W into 3 arrays:</p>
<ul>
<li>W_pos, ... | <pre><code>w=np.random.random((10,10))-0.5 # example array
</code></pre>
<p>.</p>
<pre><code>wneg = w[w<0]
wzero = w[w==0]
wpos = w[w>0]
</code></pre> | python|arrays|numpy|scipy | 2 |
376,279 | 34,205,659 | Speed up Newtons Method using numpy arrays | <p>I am using Newton's method to generate fractals that visualise the roots and the number of iterations taken to find the roots.</p>
<p>I am not happy with the speed taken to complete the function. Is there are a way to speed up my code?</p>
<pre><code>def f(z):
return z**4-1
def f_prime(z):
'''Analytic der... | <p>You can simply vectorize the loops for fairly large speed gains:</p>
<pre><code>def newton_raphson(x, y, max_iter=20, eps = 1.0e-20):
z = x + y * 1j
nz = len(z)
iters = np.zeros((nz, nz))
for i in range(max_iter):
z_old = z
z = z-(f(z)/f_prime(z))
mask = (iters == 0) & (z... | python|arrays|performance|numpy|newtons-method | 2 |
376,280 | 33,985,392 | `ValueError: operands could not be broadcast together` when attempting to plot a univariate distribution from a DataFrame column using Seaborn | <p>I'm trying to plot the univariate distribution of a column in a Pandas <code>DataFrame</code>. Here's the code:</p>
<pre><code>ad = summary["Acquired Delay"]
sns.distplot(ad)
</code></pre>
<p>This throws:</p>
<pre><code>ValueError: operands could not be broadcast together with shapes (9,) (10,) (9,)
</code></pre>... | <p>This is happening because the seaborn function <code>distplot</code> includes lines</p>
<pre><code> if bins is None:
bins = min(_freedman_diaconis_bins(a), 50)
</code></pre>
<p>to set the number of bins when it's not specified, and the <code>_freedman_diaconis_bins</code> function can return a non-intege... | python|numpy|pandas|matplotlib|seaborn | 2 |
376,281 | 34,075,094 | Python struct like Matlab | <p>I seem to have found lots of hack answers, without a 'standardized' answer to this questions. I am looking for an implementation of Matlab's struct in Python, specifically with the two following capabilities:</p>
<ol>
<li>in struct 's', access field value 'a' using dot notation (i.e. s.a)</li>
<li>create fields on ... | <p>If you're on 3.3 and up, there's <a href="https://docs.python.org/3/library/types.html#types.SimpleNamespace" rel="nofollow"><code>types.SimpleNamespace</code></a>. Other than that, an empty class is probably your best option.</p> | python|matlab|numpy|scipy | 4 |
376,282 | 34,291,023 | Pandas: rounding halfway values in dataframe using np.round and applymap | <p>I want to understand why I get different values when using 1) np.round and 2) applymap on the same DF</p>
<p>my df</p>
<pre><code> df1 = pd.DataFrame({'total': [25.23, 3.55, 76.55, 36.48, 45.59]}, index=['cat1', 'cat2', 'cat3', 'cat4', 'cat5'])
total
cat1 25.23
cat2 3.55
cat3 76.55
cat4 36.48
cat5 45.... | <p>This is documented behaviour in python 2: <a href="https://docs.python.org/2/library/functions.html#round" rel="nofollow"><code>round</code></a> and <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.around.html#numpy.around" rel="nofollow"><code>np.around</code></a> in python 3 you get the sa... | numpy|pandas|decimal|rounding | 1 |
376,283 | 34,418,668 | Numpy and Pandas interpolation also changes the original data | <p>I am trying to interpolate data for some missing days. The orginal data is;</p>
<pre><code>2012-06-27 00:00:00 17
2012-06-27 01:00:00 17
2012-06-27 02:00:00 18
2012-06-27 03:00:00 18
2012-06-27 04:00:00 19
2012-06-27 05:00:00 20
2012-06-27 06:00:00 22
2012-06-27 07:00:00 23
2012-06-27 08:00:00 25
2012-06-27 09:00:0... | <p>I cannot reproduce the problem, but this works for me (assuming your data frame is indexed on datetime):</p>
<pre><code>df_resampled = df.resample('1H').interpolate(method='linear')
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/nHHcP.png" rel="nofollow noreferrer"><img src="https://i.stack.im... | python|numpy|pandas|interpolation | 0 |
376,284 | 36,926,443 | How to unpack a pandas Panel created with a dictionary? | <p>I have several <code>.txt</code> files in a subdirectoy, <code>/subdirect/</code></p>
<p>These files are </p>
<pre><code>file1.txt
file2.txt
file3.txt
file4.txt
...
</code></pre>
<p>Using glob, I can put these into a three-dimensional panel, using the filename as the key for key-value pairs. </p>
<pre><code>impo... | <p>How about reading the data files individually instead, since you don't seem to be interested in the <code>Panel</code> structure per se:</p>
<pre><code>import glob
import pandas as pd
for filename in glob.glob('*.txt'):
df = pd.read_csv(filename)
df['total_sum'] = df[["column1", "column2", "column3"]].sum(... | python|csv|dictionary|pandas|panel | 1 |
376,285 | 36,715,110 | import nested data into pandas from a json file | <p>I have a generated file as follows:</p>
<pre><code>[{"intervals": [{"overwrites": 35588.4, "latency": 479.52}, {"overwrites": 150375.0, "latency": 441.1485001192274}], "uid": "23"}]
</code></pre>
<p>I simplified the file a bit for space reasons (there are more columns besides for the "overwrites" and "latency" ). ... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html" rel="nofollow"><code>json_normalize</code></a>:</p>
<pre><code>import pandas as pd
from pandas.io.json import json_normalize
data = [{"intervals": [{"overwrites": 35588.4, "latency": 479.52},
... | python|json|pandas | 1 |
376,286 | 37,025,485 | Getting only top values within each group that have the same column value | <p>I have a table that looks something like this:</p>
<pre><code>Column 1 | Column 2 | Column 3
1 a 100
1 r 100
1 h 200
1 j 200
2 a 50
2 q 50
2 k 40
3 a ... | <p>I think you need first need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow"><code>first</code></a> and then ... | python|pandas|dataframe | 1 |
376,287 | 36,928,487 | A value is trying to be set on a copy of a slice from a DataFrame | <p>I have a dataframe column period that has values by Quarters(Q1,Q2,Q3,Q4) that I want to convert into associated month (see dict). My code below works however wondering why I'm getting this warning.</p>
<p>A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] ... | <p>"A value is trying to be set on a copy of a slice from a DataFrame" is a warning. SO contains many posts on this subject.</p>
<p><code>df.assign</code> was added in Pandas 0.16 and is a good way to avoid this warning.</p>
<pre><code>quarter = {"Q1": "Mar", "Q2": "Jun", "Q3": "Sep", "Q4": "Dec"}
df = pd.DataFrame(... | python|dictionary|pandas|dataframe | 12 |
376,288 | 36,973,544 | TensorFlow ValueError Dimensions are not compatible | <p>I have a simple program, mostly copied from the MNIST tutorial on Tensorflow. I have a 2D array 118 items long, with each subarray being 13 long. And a 2nd 2D array that is 118 long with a single integer in each sub array, containing either 1, 2, or 3 (the matching class of the first array's item)</p>
<p>Whenever... | <p>First, it's not clear how many labels you have (3 or 13), and what is the size of input (X) vector (113 or 13)? I assume you have 13 labels, and 118 X vectors based on:</p>
<pre><code>W = tf.Variable(tf.zeros([118, 13]))
y_ = tf.placeholder(tf.float32, [None, 13])
</code></pre>
<p>Then, you may change your code so... | python|arrays|numpy|neural-network|tensorflow | 1 |
376,289 | 36,728,111 | Update Jupyter to Python 3.4 in default Tensorflow docker container | <p>I am using gcr.io/tensorflow/tensorflow docker image and need to update jupyter to python version 3.4 within the container. I've tried searching online but haven't really found how to do this. Could someone help me with this by explaining step-by-step?</p> | <p>There are now python3 builds available in the nightly docker images as of <a href="https://github.com/tensorflow/tensorflow/pull/6030" rel="nofollow noreferrer">pull 6030</a>. See the <a href="https://hub.docker.com/r/tensorflow/tensorflow/tags/" rel="nofollow noreferrer">TensorFlow public docker repository</a>
fo... | python-3.x|docker|tensorflow|jupyter | 0 |
376,290 | 36,818,832 | pandas plot bar chart -- Unexpected layout | <p>I am trying to plot bar char with line chart. I created 2 subplot.
Using the below code </p>
<pre><code> RSI_14 = df['RSI_14']
df['ATR_14'] = df['ATR_14'].astype(float)
ATR_14 = df['ATR_14']
fig5 = plt.figure(figsize=(14,9), dpi=200)
ax1 = fig5.add_subplot(211)
a... | <p>I'm not sure if you want to see this as a primary and secondary axis but here's how you'd do that.</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
from pandas import Timestamp
df = pd.DataFrame(
{'ATR_14': {Timestamp('2014-10-15 00:00:00'): 0.01737336,
Timestamp('2014-10-16 00:00:0... | python|pandas|matplotlib | 0 |
376,291 | 36,771,245 | python datetime extract hour minute fast | <p>I have a 878000*1 dataframe, where the 1 column is date in several years. I have the following code to create new columns and store year,month,day,hour,min,week in different new columns:</p>
<pre><code>for i in train.index:
train['Year'][i] = train.Dates[i].year
train['Month'][i] = train.Dates[i].month
... | <h3>Setup</h3>
<pre><code>In [15]: train = pd.DataFrame(pd.date_range('2015-12-31', '2016-12-31'), columns=['Dates'])
In [16]: train.head()
Out[16]:
Dates
0 2015-12-31
1 2016-01-01
2 2016-01-02
3 2016-01-03
4 2016-01-04
</code></pre>
<h3>Solution</h3>
<pre><code>In [17]: fields = ['Year', 'Month', 'Day', 'Ho... | python|pandas | 2 |
376,292 | 37,113,556 | TensorFlow: dimension error. how to debug? | <p>I'm a beginner with TF</p>
<p>I've tried to adapt a code which is working well with some other data (noMNIST) to some new data, and i have a dimensionality error, and i don't know how to deal with it. </p>
<p>To debug, i'm trying to use <code>tf.shape</code> method but it doesn't give me the info i need...</p>
<p... | <p>In debug mode you can check shapes of you Tensors.
by the way you error is valid_prediction assignment. to make it better for debugging and reading it's better to define each step in a separate line. you are using 4 operation in 1 line. BTW in debug mode (for example in Pycharm) you can inspect the element and check... | runtime-error|tensorflow|dimension | 1 |
376,293 | 36,933,308 | Generate image data from three numpy arrays | <p>I have three numpy arrays, <code>X</code>, <code>Y</code>, and <code>Z</code>.</p>
<p><code>X</code> and <code>Y</code> are coordinates of a spatial grid and each grid point <code>(X, Y)</code> has an intensity <code>Z</code>. I would like to save a PNG image using this data. Interpolation is not needed, as <code>X... | <p>To begin with, you should run this piece of code:</p>
<pre><code>import numpy as np
X = np.asarray(<X data>)
Y = np.asarray(<Y data>)
Z = np.asarray(<Z data>)
Xu = np.unique(X)
Yu = np.unique(Y)
</code></pre>
<hr>
<p>Then you could apply any of the following approaches. It is worth noting that... | python|numpy | 2 |
376,294 | 54,998,630 | Write Real Raw Binary File from Python | <p>I've tried multiple different variations, but for some reason I keep getting invalid binary digits (human readable) being output to the file:</p>
<pre><code>img_array = np.asarray(imageio.imread('test.png', as_gray=True), dtype='int8')
img_array.astype('int8').tofile("test.dat")
</code></pre>
<p>But this doesn't p... | <p>This gave a workable solution which converts to a string of hex values. It's not exactly what I wanted, but it created a valid work around since my original question has yet to be answered. Although I didn't find this solution so I can reference where it came from, I'll share it here anyways. Apparently this handles... | python|python-3.x|numpy|binary | 0 |
376,295 | 54,795,015 | Why does gcloud ml-engine submit command give "requested cpu s exceed quota"? | <p>I am running a tensorflow object detection job on GCP with the folowing command: <br/></p>
<p>gcloud ml-engine jobs submit training <code>whoami</code>_object_detection_<code>date +%s</code> --job-dir=gs://${YOUR_GCS_BUCKET}/train --packages dist/object_detection-0.1.tar.gz,slim/dist/slim-0.1.tar.gz,/tmp/pycocotool... | <p>This option in your code is setting the size and type of your ml instance:</p>
<pre><code>--scale-tier BASIC_TPU
</code></pre>
<p>The BASIC_TPU costs $6.8474 per hour. I am not sure of the formula, but a Cloud TPU translates into N CPUs in equivalent billing. You also need to add the cost of the Cloud ML Engine ma... | python|tensorflow|google-cloud-platform | 0 |
376,296 | 54,842,256 | reshape np array for deep learning | <p>I want to use keras to apply a neural network to my time-series data. TO improve the model I want to have 50 time states of input per output. The final input should have 951 samples with 50 time points of 10 features (951, 50, 10)</p>
<p>Therefore, I have to reshape my data. I do that doing a for loop, but is awful... | <p>We can leverage <a href="http://www.scipy-lectures.org/advanced/advanced_numpy/#indexing-scheme-strides" rel="nofollow noreferrer"><code>np.lib.stride_tricks.as_strided</code></a> based <a href="http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_windows" rel="nofollow noreferrer"><code>sciki... | python|numpy|keras|reshape | 2 |
376,297 | 54,725,031 | Tensorflow: Manipulate bias during training | <p>I train a model and want to manipulate all bias terms during training. For this reason, I build the graph using a parameter <code>change_bias</code></p>
<pre><code>change_bias = tf.placeholder(tf.float32)
b = change_bias * b
</code></pre>
<p>To manipulate the bias term, I want to be able to feed <code>change_bias=... | <p>because of b is defined as variable this is wrong:</p>
<pre><code>b = change_bias * b
</code></pre>
<p>try something like this:</p>
<pre><code>import tensorflow as tf
x=tf.placeholder(tf.float32,shape=[-1,26])
change_bias=tf.placeholder(tf.float32,shape=[])
b=tf.Variable(tf.zeros([26]),name="bias")
output=x+tf.... | python|tensorflow | 0 |
376,298 | 54,961,109 | Multiply Matrix by column vector with variable entry that has range (1,101) | <p>I want to multiply Matrix AB. To get the vector Y,
Where A is 3x4 and B is 4x1
x= range(1,101)
B = [2,x,3,x]
Since B contains the variable x we will get 100 different vectors for Y. I want to add them to a list so I can use these vectors for computations later on. </p>
<p>This is what i've tried but i get an er... | <p>Okay first, you forgot to make B a numpy matrix, second you need to use f-strings to use x as a variable instead of the character x which is an incompatible type.</p>
<pre><code>AB = list()
for x in range (1,100):
A = np.matrix('1 9 2 3; 7 2 1 4; 4 2 5 2')
B = np.matrix(f'2; {x}; 3; {x}')
AB.append(A @ B)... | python|numpy | 0 |
376,299 | 55,017,879 | pandas list manipulation and fill NA | <p>I am trying to use this function in order to extract the <code>AdjClose</code> value from a dataframe.</p>
<pre><code>def get_sell_price(data):
buy_date = get_buy_date(data)
sell_date = get_sell_date(buy_date)
l=[]
for i in range(0,len(buy_date)):
sell_price = data[(data.Date == sell_date[i]... | <p>You can use <code>next</code> with <code>iter</code> for first value if exist, else default value (here <code>NaN</code>) is returned.</p>
<p>Better for select column with filter is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>Data... | python|pandas|function|filter | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.