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 |
|---|---|---|---|---|---|---|
17,700 | 68,812,349 | Convert an Object form date to interger and sample from years | <p>In a date frame, I have a column called <code>publish_time</code> (e.g., 2001-07-04) in <code>Object</code> format. Say, in a new data frame, I want randomly keep (or sample) 100 rows from year 2019, 2020, and 2021. I would also like to know the number of lines in each year. Could you help me with this process? Than... | <p>Your question is not very precise and does not state your expected output. Note that it is much easier to provide you with help if you provide us with code examples and expected output.</p>
<p>However, here is a way how you could sample from a dataframe based on specified years. This is not a very concise version, b... | python|pandas | 1 |
17,701 | 68,644,896 | Numpy.array dtype assignment failure | <p>I am entirely new to numpy and am attempting to create a structured array. My inputs are as follows:</p>
<pre><code>data = [2, 0, '1431.033', '436.7573', '170.9705', 0, '', 0]
dt = [('ID', 'int'),
('CP', 'int'),
('X1', 'float'),
('X2', 'float'),
('X3', 'float'),
('CD', 'int'),
('P... | <p>From the <a href="https://numpy.org/doc/stable/user/basics.rec.html#indexing-and-assignment-to-structured-arrays" rel="nofollow noreferrer">documentation</a>, The simplest way to assign values to a structured array is using python native tuples. By organizing my data as tuple within list, the structured array can be... | python|arrays|numpy|dtype | 0 |
17,702 | 52,999,850 | How does pandas concat function do column joins without specify common key? | <p>Greetings to my dear fellow Pythoners!</p>
<p>Today, when I was going through a Python course on data camp, a simple data join with pd.concat() really stood up to me. I couldn't seem to understand the logic behind the join. I need your help!</p>
<p>Consider the following case which is a simplified version, and we ... | <p><code>pd.concat</code> is base on the <code>index</code> </p>
<p>For example you have </p>
<pre><code>df1=pd.DataFrame({'A':[1,2,3,4]})
df2=pd.DataFrame({'A':[1,2,3,4]},index=[2,3,4,5])
</code></pre>
<p>When you do <code>concat</code> , you are doing <code>join</code> by index , or <code>merge</code> by index </p... | python|pandas|join | 2 |
17,703 | 65,796,631 | replacing a list of numbers with a list of their multiplications | <p>I have a list of numbers <code>arr</code> and a window size <code>n</code>.
I want to efficiently (possibly with numpy) compute a new list, where each new element in the list is the multiplication of all the element in the window.
For example, if <code>arr = [1, 2, 3, 4, 5]</code> and <code>n = 3</code> I want it to... | <p>My solution involves Pandas.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
arr = pd.Series([1, 2, 3, 4, 5])
window_size = 3
rolling = arr.rolling(window_size)
result = rolling.apply(np.prod)
</code></pre>
<p>The resulting array has the same length of the original array... | python|list|performance|numpy|multiplication | 2 |
17,704 | 65,821,719 | Creating roll rate matrix from pandas dataframe | <p>apologies if I am asking a very basic question. I want to replicate a simple roll matrix in python however I am struggling and I was wondering if I can get some help.</p>
<p>Ageing ( already imported as DF)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Month</th>
<th>NYD</th>
<th>DPD30... | <pre><code>import pandas as pd
df=pd.read_excel(r"D:\Stack_overflow/test1.xlsx")
#TAKING OUT ALL THE COLUMNS WITH HAVING INT TYPE
cols=df.select_dtypes(exclude=['object']).columns
cols=cols.to_list()
#CREATING ANOTHER LIST WITH _tmp ADDED TO THE LIST ELEMNETS
cols2=[x + '_tmp' for x in cols]
cols2=cols... | python|python-3.x|pandas|dataframe | 0 |
17,705 | 21,295,506 | Join flat index with hierarchical indexed DataFrame | <p>I have two dataframes, dataframe A:</p>
<pre><code> col1
level1 level2
a 1 1
2 2
b 1 3
2 4
</code></pre>
<p>and dataframe B:</p>
<pre><code> col2
level1
a 5
b 6
</code></pre>
<p>I want to join them to receive:<... | <p>This doesn't look that general to me, and I believe their is a way to do a merge directly, though maybe not w/o modifying the 2nd frame (to make a merge key, e.g. this is kind of like cross merging).</p>
<pre><code>In [49]: df1 = DataFrame({ 'A' : [1,2,3,4]})
In [50]: df1.index = pd.MultiIndex.from_tuples([ ('a',1... | python|pandas | 2 |
17,706 | 21,208,420 | Why does X.dot(X.T) require so much memory in numpy? | <p>X is a n x p matrix where p is much larger than n. Let's say n = 1000 and p = 500000. When I run:</p>
<pre><code>X = np.random.randn(1000,500000)
S = X.dot(X.T)
</code></pre>
<p>Performing this operation ends up taking a great deal of memory despite the result being of size 1000 x 1000. The memory use goes back do... | <p>The issue is not that <code>X</code> and <code>X.T</code> are views of the same memory space <em>per se</em>,
but rather that <code>X.T</code> is F-contiguous rather than C-contiguous. Of course, this must
necessarily be true for at least one of the input arrays in the case
where you're multiplying an array with a v... | python|numpy|scipy|linear-algebra | 7 |
17,707 | 63,411,435 | is there pytorch's max operation in tensorflow2.0? | <pre><code>overlap-> tensor([[0.0000, 0.0000, 0.0000, ..., 0.6466, 0.7945, 0.5389]],
device='cuda:0')
overlap_for_each_prior, object_for_each_prior = overlap.max(dim=0) # (8732)
</code></pre>
<p>this .max(dim=0) return the two returns.<br/>
is there any equivalence method in tensorflow 2.0?</p> | <p>No, you have to use <a href="https://www.tensorflow.org/api_docs/python/tf/math/argmax" rel="nofollow noreferrer"><code>tf.math.argmax</code></a>. Using it, you can get maximum element(s) as well:</p>
<pre><code>A = tf.constant([2, 20, 30, 3, 6])
maximum_index = tf.math.argmax(A)
A[maximum_index], maximum_index
# &g... | tensorflow|pytorch | 0 |
17,708 | 63,432,702 | numpy performace: custom elementwise operation in numpy over variable same size ndarray | <p>I am trying to write an efficient vectorized numpy custom function that essentially performs elementwise mean sans -1 if at all present.</p>
<p>The idea is given list/tuple of same size ndarray as input produce a single same size ndarray which is effectively a (elementwise) mean of all ndarray provided as input.
The... | <p>I've streamlined <code>mean_with_dont_knows_from_1d</code> a bit:</p>
<pre><code>def mean_1(arr):
arr1 = arr[arr!=-1] # simpler than np.delete
n = arr1.size
if n==0:
return -1
return int(arr1.mean() >= 0.5)
</code></pre>
<p>Applied with:</p>
<pre><code>def foo(*argv):
temp = np.stac... | python|arrays|python-3.x|numpy|scipy | 0 |
17,709 | 63,689,759 | Union of 2d array in Python by row according to first column | <p>I'm trying to find a union of two 2d arrays based on the first column:</p>
<pre><code>>>> x1
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> x2
array([[ 7, -1, -1],
[10, 11, 12]])
</code></pre>
<p>If two rows have a matching first value, I want the one from <code>x2</code>. I.e. t... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>np.unique</code></a> and <a href="https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer"><code>np.concatenate</code></a>, placing <code>x2</code> first.... | python|numpy | 1 |
17,710 | 24,879,156 | Pandas to_sql with sqlAlchemy duplicate entries error in mysqldb | <p>I am using PANDAS with a SQLAlchemy to write to MYSQL DB using <code>DataFrame.to_sql</code>. I like to turn on the flag for <code>'append' --> df.to_sql(con=con, name='tablename', if_exists='append')</code> Since the program does several small writes to the tables during the day, I don't want the entire table o... | <p>Not sure if you found an answer but here's a workaround that worked for me:</p>
<p>call the <code>.to_sql()</code> on a temporary table then use a query to update the main table with the temp table. Then you can drop the temp table. So for example:</p>
<pre><code>df.to_sql(con=con, name='tablename_temp', if_exists... | pandas|sqlalchemy | 13 |
17,711 | 30,103,983 | How to get a subarray in numpy | <p>I have an 3d array and I want to get a sub-array of size (2n+1) centered around an index indx. Using slices I can use</p>
<pre><code>y[slice(indx[0]-n,indx[0]+n+1),slice(indx[1]-n,indx[1]+n+1),slice(indx[2]-n,indx[2]+n+1)]
</code></pre>
<p>which will only get uglier if I want a different size for each dimension. ... | <p>You don't need to use the <code>slice</code> constructor unless you want to store the slice object for later use. Instead, you can simply do:</p>
<pre><code>y[indx[0]-n:indx[0]+n+1, indx[1]-n:indx[1]+n+1, indx[2]-n:indx[2]+n+1]
</code></pre>
<p>If you want to do this without specifying each index separately, you c... | numpy|sub-array | 2 |
17,712 | 53,714,356 | how to read image into tensor from url directly | <p>I'm new to tensorflow, so please bear with me. </p>
<p>I want to convert the <code>read_tensor_from_image_file</code> function from tensorflow tutorial to be able to read a image from url.</p>
<p>So instead of passing in the file location as <code>file_name</code>, I can pass in a url as file_name such as <code>ht... | <p>You can use <code>response.content</code> directly with <code>tf.image.decode_jpeg</code>. The following code proves that you will get the same array:</p>
<pre><code>import numpy as np
import requests
import tensorflow as tf
def read_tensor_from_image_url(url,
input_height=299,
... | python|image|tensorflow | 2 |
17,713 | 53,552,234 | replace loop for iteration with two rows with multiple if condition python | <p>I have following code, I am using loop for further operation.</p>
<pre><code>for i in range(0,(len(dff1)-1)):
lat1=dff1.latitude.values[i]
lon1=dff1.longitude.values[i]
lat2=dff1.latitude.values[i+1]
lon2=dff1.longitude.values[i+1]
if((lat1!=0)&(lon1!=0)&(lat2!=0)&(lon2!=0)):
... | <p>So if I understand you correctly, you have a dataframe with longitude and latitude, and you want to calculate the distance to the long and lat located in the following row, and store that value as distance.</p>
<p>Dummy dataframe:</p>
<pre><code>df = pd.DataFrame({'Long':[-2986.242495,-3383.296608,0,0],'Lat':[-880... | python|python-3.x|pandas|for-loop | 0 |
17,714 | 53,394,523 | Fastest way to drop rows / get subset with difference from large DataFrame in Pandas | <h1>Question</h1>
<p>I'm looking for the fastest way to drop a set of rows which indices I've got or get the subset of the difference of these indices (which results in the same dataset) from a large Pandas DataFrame.</p>
<p>So far I have two solutions, which seem relatively slow to me:</p>
<ol>
<li><p><code>df.loc[df.... | <p>I believe you can create boolean mask, inverting by <code>~</code> and filtering by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>df1 = df[~df.index.isin(indices)]
</code></pre>
<p>As @user3471881 men... | python|pandas|dataframe | 7 |
17,715 | 15,819,050 | Pandas DataFrame concat vs append | <p>I have a list of 4 pandas dataframes containing a day of tick data that I want to merge into a single data frame. I cannot understand the behavior of concat on my timestamps. See details below:</p>
<pre><code>data
[<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 35228 entries, 2013-03-28 00:00:07.089000... | <h1>Pandas concat vs append vs join vs merge</h1>
<ul>
<li><p><strong>Concat</strong> gives the flexibility to join based on the axis( all rows or all columns)</p>
</li>
<li><p><strong>Append</strong> is the specific case(axis=0, join='outer') of concat (<a href="https://pandas.pydata.org/docs/whatsnew/v1.4.0.html#what... | python|pandas | 165 |
17,716 | 71,895,095 | How to split a dataframe column into two columns and transform values in one expression using Python? | <p>I need to split a column containing strings into two columns which in this particular case I could do like</p>
<p><code>df[['col1','col2']] = df['col1'].str.split('-', expand=True)</code>.</p>
<p>But I also need to apply a transformation to the second string before storing it in <strong>col2</strong> and this transf... | <p>As pointed out in @Ynjxsjmh's comment you can use <code>.assign()</code>, but you'd need a <code>lambda</code> function to give you access to the current state of the dataframe (you need access to both new columns):</p>
<pre><code>df = pd.DataFrame({"Col1": ["123-abc"] * 3 + ["12345-abcde&qu... | python|pandas|dataframe | 1 |
17,717 | 16,613,437 | Stacking Numpy Arrays repeatedly | <p>This might be an easy question, nevertheless I'm trying to get an answer ;)
I want to create a 3D numpy array, which is a repeated copy of another subarray, with a given number of copys.</p>
<p>In 1-D this is what I wanna do: a=[0,1,0], factor=3 leads to b=[0,1,0,0,1,0,0,1,0]</p>
<h2>My ideas so far:</h2>
<p>-Cre... | <p>You probably want to take a look at <code>np.tile</code>:</p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html</a></p>
<p>For your simple 1d example:</p>
<pre><code>In [1]: a=[0,1,0]
In [3]: np.tile(... | arrays|numpy|stack|repeat | 2 |
17,718 | 17,820,384 | Understanding indexing issues in Pandas 0.8.1 (and 0.11) | <p>Here is an example from an IPython session where some straightforward indexing and assignments to a Pandas DataFrame work and some don't work when they seem straightforward:</p>
<pre><code>In [652]: dfrm = pandas.DataFrame(np.random.rand(10,3), columns=['A', 'B', 'C'])
In [653]: dfrm
Out[653]:
A ... | <p><em>Assigning with two or more getitems/slices (chaining) may or may not work depending on the situation...<br>
so you should <strong>avoid</strong> doing it!! You should rewrite to do each in one pass.</em></p>
<p>There was quite a substantial amount of work in 0.11 (possibly before) to clear up this behaviour... ... | python|indexing|pandas | 1 |
17,719 | 8,652,785 | Why does numpy.apply_along_axis seem to be slower than Python loop? | <p>I'm confused about when numpy's <code>numpy.apply_along_axis()</code> function will outperform a simple Python loop. For example, consider the case of a matrix with many rows, and you wish to compute the sum of each row:</p>
<pre><code>x = np.ones([100000, 3])
sums1 = np.array([np.sum(x[i,:]) for i in range(x.shape... | <p><code>np.sum</code> take an <code>axis</code> parameter, so you could compute the sum simply using </p>
<pre><code>sums3 = np.sum(x, axis=1)
</code></pre>
<p>This is much faster than the 2 methods you posed.</p>
<pre><code>$ python -m timeit -n 1 -r 1 -s "import numpy as np;x=np.ones([100000,3])" "np.apply_along_... | python|numpy | 10 |
17,720 | 55,245,388 | Retrieve specific time intervals of pandas dataframe with datetime index | <p>I have a pandas dataframe with a datetime index. Suppose the datetime index starts at time t1, is there a way in pandas to return the rows of the dataframe for every say 15-minute time interval starting from time t1?</p>
<p>Further, is it possible to average all the entries between those 15-minute intervals and ret... | <blockquote>
<p>"I have a pandas dataframe with a datetime index. Suppose the datetime
index starts at time t1, is there a way in pandas to return the rows
of the dataframe for every say 15-minute time interval starting from
time t1?"</p>
</blockquote>
<p>This is best to be solved by using <a href="https://pan... | python|pandas|datetime|time-series | 0 |
17,721 | 7,217,606 | How can I mask elements of a record array in Numpy? | <p>I understand how to create a masked array, and I would like to use masking in a record array so that I can access this data using named attributes. The masking seems to be "lost" when I create a record array from a masked array:</p>
<pre><code>>>> data = np.ma.array(np.ma.zeros(30, dtype=[('date', '|O4'),... | <p>I haven't found much documentation on numpy.ma.mrecords.MaskedRecords, except for a brief mention <a href="http://projects.scipy.org/numpy/wiki/MaskedArrayAlternative" rel="nofollow">here</a>. You can find some examples on how to use it by studying the unit tests that come with numpy. (e.g.
<code>/usr/lib/python2.6... | python|numpy|structured-array|masked-array | 4 |
17,722 | 56,752,412 | Randomize numpy.argsort output in case of ties | <p>I have a numpy array with some elements same as others i.e. there are ties, and I am applying <code>np.argsort</code> to find the indices which will sort the array:</p>
<pre><code>In [29]: x = [1, 2, 1, 1, 5, 2]
In [30]: np.argsort(x)
Out[30]: array([0, 2, 3, 1, 5, 4])
In [31]: np.argsort(x)
Out[31]: array([0, 2,... | <p>One trick would be to add uniform noise in <code>[0,1)</code> range and then perform argsort-ing. Adding such a noise forces sorting only within their respective bins and gives randomized sort indices restricted to those bins -</p>
<pre><code>(x+np.random.rand(len(x))).argsort()
</code></pre> | python|arrays|numpy|sorting|random | 3 |
17,723 | 56,453,817 | Pandas dataframe to Orange table with setting role (feature or target) | <p>I have a dataframe as follows</p>
<pre><code>df = pd.DataFrame({"A": ["a", "b", "c"], "B": ["d", "e", "f"], "C": ["yes", "no", "yes"]})
</code></pre>
<p>I would like to convert df to orange table and set A and B as categorical attributes and then set C as the class variable (target variable). Currently, I can con... | <p>You can simply output the Orange table from the Python Script widget.</p>
<pre class="lang-py prettyprint-override"><code>out_data=orange_table
</code></pre>
<p>Then use the <strong>Select Column</strong> widget to select the features and target variable.</p>
<p><img src="https://orange3.readthedocs.io/projects/oran... | python-3.x|pandas|orange | 2 |
17,724 | 56,830,117 | Get item of list in dataframe column using loop | <p>I have dataframe <code>df</code> like this :</p>
<pre><code> date item
2019-03-29 [book,pencil]
...
</code></pre>
<p>I want to get every item in list using loop. this is what I've tried:</p>
<pre><code> for i in range(len(df)):
for x in df['attributeName'][i]:
print(x)
<... | <pre><code>df2['item'].apply(pd.Series).unstack().reset_index(drop=True)
</code></pre>
<p>A better alternative.. <a href="https://stackoverflow.com/questions/54432583/when-should-i-ever-want-to-use-pandas-apply-in-my-code">A Common Pitfall: Exploding Columns of Lists</a></p>
<pre><code>pd.DataFrame(df2['item'].tolist... | python|python-3.x|pandas|dataframe | 3 |
17,725 | 56,609,470 | How to use numpy where on each element of test array without a for-loop? | <p>I would like to use a numpy function in a routine without using a for-loop. Consider the example below:</p>
<pre><code>import numpy as np
data = np.linspace(1, 10, 10).astype(int)
test_elements = np.array([1, 2])
for test_elem in test_elements:
print(np.where(test_elem == data))
</code></pre>
<p>...</p>
<pr... | <p>Here is one method using <code>.outer</code> and <code>np.split</code> I've made the example a bit more interesting.</p>
<pre><code>data = np.linspace(1, 5, 10).astype(int)
test_elements = np.array([1, 2, 4, 6])
y, x = np.where(np.equal.outer(test_elements,data))
np.split(x, y.searchsorted(np.arange(1,test_element... | python-3.x|numpy|for-loop|vectorization|where | 0 |
17,726 | 56,744,618 | Improve for loop efficiency | <p>I'm trying to convert 12,000 JSON files, containing event web data, into a single pandas dataframe.
The code is taking too long to run.
Any ideas on how to improve its efficiency?</p>
<p>Example of loaded JSON file:</p>
<pre><code>{'$schema': 12,
'amplitude_id': None,
'app'... | <p>The fastest way of converting JSON strings to dataframes seems to be <code>pd.io.json.json_normalize</code>. Depending on the number of JSONs it is about 15 to >500 times faster than appending to an existing dataframe. It beats <code>pd.concat</code> by a factor of 13 to 170.</p>
<p>The side effect is that the nest... | python|json|pandas|performance | 0 |
17,727 | 56,718,458 | How to find the occupancy each hour? | <p>I'm trying to show how many people are in the gym in any given time.</p>
<p>I've been provided the sign-in data and would like to display the occupancy for each hour like so:</p>
<pre><code>Date/Time | Occupants
1/1/2018 7:00AM | 4
1/1/2018 8:00AM | 12
1/1/2018 9:00AM | 16
1/1/2018 10:00AM | 13
1/1/2018 11:00AM | ... | <p>Are you just looking for help with the aggregation?</p>
<p>You can use groupby, with a count.</p>
<pre><code>In = df['Sign In'].groupby([df['Sign In'].apply(lambda x: x.strftime('%B %d, %Y, %H'))]).count()
Out = df['Sign In'].groupby([df['Sign Out'].apply(lambda x: x.strftime('%B %d, %Y, %H'))]).count()
Sign In
J... | python|pandas|datetime|aggregate | 0 |
17,728 | 56,823,250 | Subsetting NYC shapefile to Manhattan using Geopandas | <p>I have a shapefile of NYC which I would like to reduce to cover only Manhattan, using geopandas. (source: <a href="https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page" rel="nofollow noreferrer">https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page</a>). </p>
<p>Thanks for any suggestions!!!</p>
<... | <p>Assume you're using the following shapefile:
<a href="https://i.stack.imgur.com/8YKK7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8YKK7.png" alt="enter image description here"></a></p>
<p>Except for the geometry column in your <code>GeoDataFrame</code>, it acts just like a Pandas <code>DataFr... | python|shapefile|geopandas | 4 |
17,729 | 25,450,387 | Select elements of a numpy array based on the elements of a second array | <p>Consider a numpy array A of shape (7,6)</p>
<pre><code>A = array([[0, 1, 2, 3, 5, 8],
[4, 100, 6, 7, 8, 7],
[8, 9, 10, 11, 5, 4],
[12, 13, 14, 15, 1, 2],
[1, 3, 5, 6, 4, 8],
[12, 23, 12, 24, 4, 3],
[1, 3, 5, 7, 89, 0]])
</code></pre>
<p>together ... | <p>You can select a section of <code>A</code> by doing something like <code>A[r == 1]</code>, to get all the sections as a list you could do <code>[A[r == i] for i in range(r.max() + 1)]</code>. This will work, but may be inefficient depending on how big the values in <code>r</code> go because you need to compute <code... | numpy|matrix | 1 |
17,730 | 67,137,194 | How to ignore nan values in a dataframe | <p>I'm trying to check if my last close is higher (or lower) then the support or resistince an my dataframe.
The problem is that i have a lot of nan values. How can i ignore those values and just check the last integer value of the colum? below just a short line of code to check if the close is below the support.
I hav... | <p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dropna.html" rel="nofollow noreferrer"><strong><code>dropna()</code></strong></a> before indexing with <code>iloc</code>:</p>
<pre class="lang-py prettyprint-override"><code>close_condition = df["Close"].dropna().iloc... | python|pandas|dataframe|nan | 2 |
17,731 | 67,073,910 | Using len() on TensorFlow ragged tensor | <p>Normally in TensorFlow you can not use len() on a ragged tensor e.g.</p>
<pre><code>import tensorflow as tf
x = tf.ragged.stack([[1],[1,2]])
print(len(x))
</code></pre>
<p>As ragged tensor does not implement a length method so you get the following expected error:</p>
<pre><code>TypeError: object of type 'RaggedTens... | <p>Ragged tensor usually holds variable size sequence lists. The exact length is quite ambiguous. We need to iterate to get each sequence length.</p>
<pre><code>import tensorflow as tf
x = tf.ragged.stack([[1],[1,2]])
len(x.to_list()) # total 2
for i in x:
print(len(i))
</code></pre>
<p>If we pass this to <code>... | python|tensorflow|tensorflow2.0 | 0 |
17,732 | 66,907,507 | Visual Studio: unresolved import 'numpy' | <p>I am trying to run the code below which requires numpy. I installed it via <code>pip install numpy</code>. However, numpy gets highlighted in the editor with the note <em>unresolved import 'numpy'</em>. When I try to run it I get the error <em>No module named 'numpy'</em>. After I got the error the first time I unin... | <p>Make sure you have installed NumPy in the same python environment that you use to run the program. (Check the PATH variable if it includes the path to the correct python environment)</p> | python|numpy|visual-studio-2019 | 0 |
17,733 | 67,035,615 | Pandas not recognising older dates (pre-1600) | <p>I'm entering data in csv format. The majority of dates are after 1900, but some are earlier than this. The oldest that I've seen so far is 1518.</p>
<p>The 1518 date actually came up with an out of bounds error. I know that python should be able to cope with dates up to around 584 years old, but it didn't in this ca... | <p>According the <a href="https://pandas-docs.github.io/pandas-docs-travis/user_guide/timeseries.html#timestamp-limitations" rel="nofollow noreferrer">documentation, there's limitation</a> (<em>the time span that can be represented using a 64-bit integer is limited to approximately 584 years</em>).</p>
<p>You can <a hr... | python|python-3.x|pandas|datetime | 0 |
17,734 | 47,492,450 | Nested JSON to Pandas Dataframe in python | <p>I'm trying to convert nested JSON data into a pandas dataframe. I know there is ample material on here about this but I still can't seem to get this working.
As you can see, I created a dataframe with the intent of grabbing only certain pieces of data (bedrooms, price, size, longitude, latitude).</p>
<p>Any help is... | <p>The request that you are making has no attribute 'size'. The properties in the data are: </p>
<pre><code>['address', 'address_hidden', 'availability', 'avdate', 'baths',
'bedrooms', 'cats', 'city', 'community', 'den', 'dogs', 'email', 'id',
'intro', 'latitude', 'link', 'location', 'longitude', 'marker... | python|json|pandas | 0 |
17,735 | 47,537,614 | Using Pandas series values as index for assigning values to another series | <p>I am trying to find a shortcut to assigning a pandas series from elements in a list.</p>
<p>My code:</p>
<pre><code>import pandas as pd
df=pd.DataFrame([[1,2,2183],[1,4,2235],[2,3,6123],[3,4,4213]],columns=['month','staff','sales'])
goals=[1346,4456,4574]
df['goals']=goals[df['month']-1]
</code></pre>
<p>The la... | <pre><code>In [80]: mapping = pd.Series(goals, index=df.month.unique())
In [81]: mapping
Out[81]:
1 1346
2 4456
3 4574
dtype: int64
In [82]: df['goals'] = df.month.map(mapping)
In [83]: df
Out[83]:
month staff sales goals
0 1 2 2183 1346
1 1 4 2235 1346
2 2 3 61... | python|pandas | 3 |
17,736 | 47,377,522 | Finds all rows fitting to combinatorial condition | <p>I'm looking for the best way to do this using python\excel\sql\google sheets -
I need to find all rows which fits to k values from list of n values.</p>
<p>For example I have this table called Animals:</p>
<pre><code>| Name | mammal | move | dive |
+----------+--------+--------+-------+
| Giraffe | 1 ... | <p>Here's a pure Python 3 solution. </p>
<pre><code>data = [
('Giraffe', 1, 1, 0),
('Frog', 0, 1, 1),
('Dolphin', 1, 1, 1),
('Snail', 0, 1, 0),
('Bacteria', 0, 0, 0),
]
probes = [
((1, 1, 1), 3),
((1, 1, 1), 2),
((1, 1, 1), 1),
((1, 1, 0), 2),
((0, 1, 1), 2),
((0, ... | python|sql|excel|pandas|google-sheets | 5 |
17,737 | 68,198,439 | TypeError: can't pickle _thread._local objects when trying to fit a KerasRegressor | <p>So I'm trying to train a neural network and at no point does it appear that <code>pickle</code> is even being used, so I'm somewhat confused. Here's the details:</p>
<pre><code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.wrappers.scikit_learn import ... | <p>You need to pass a callable function as <code>build_fn</code> in <code>KerasRegressor</code>. Removing the rounds brackets should make it works.</p>
<p>Following your code, chage:</p>
<pre><code>estimator = KerasRegressor(build_fn=baseline_model(), epochs=100, batch_size=5, verbose=2)
</code></pre>
<p>into:</p>
<pre... | python|tensorflow|keras | 1 |
17,738 | 68,113,413 | How to count rows in a dataframe that satisfy multiple conditions? | <p>I have a dataframe (lets call it df) that looks a bit like this.</p>
<pre><code>Offer | Country | Type | Cancelled
------|---------|------|----------
111 | UK | A | N
222 | UK | A | Y
333 | UK | B | N
444 | UK | C | N
555 | UK | D | N
666 | UK | E | N
777 ... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>x = df.loc[
df.Country.eq("UK") & df.Type.isin(["A", "B", "C"]) & df.Cancelled.eq("N")
]
print(len(x))
</code></pre>
<p>Prints:</p>
<pre><code>3
</code></pre>
<hr />
<p>Step-by-step:</p>
<ol>
<li>Cr... | python|pandas|dataframe | 1 |
17,739 | 68,310,615 | How do I refer to an unnamed columns in query string in Pandas? | <p>How do I refer to an unnamed DataFrame column in a query string when using pandas.DataFrame.query? I know I can to column names that are not valid Python variable names by surrounding them in backticks. However, that does not address unnamed columns.</p>
<p>For example, I would like to query for all rows in a DataFr... | <p>There are ways to achieve what you are looking for:</p>
<h2>Dummy DataFrame:</h2>
<pre><code>>>> df
0 1 2
0 0.210862 0.894414 0.713472
1 0.804793 0.656390 0.842293
2 0.617104 0.763162 0.697050
3 0.158506 0.190683 0.740970
4 0.380092 0.984326 0.138277
5 0.665413 0.4... | python|pandas|dataframe | 0 |
17,740 | 68,232,429 | K-Means classification by group | <p>I'm trying to do a K-means analysis in a dataframe like this:</p>
<pre><code> URBAN AREA PROVINCE DENSITY
0 1 TRUJILLO 0.30
1 2 TRUJILLO 0.03
2 3 TRUJILLO 0.80
3 1 LIMA 1.20
4 2 LIMA 0.04
5 1 LAMBAYEQUE 0.90
6 2 ... | <p>try this</p>
<pre><code>def k_means(row):
clustering=KMeans(n_clusters=2, max_iter=300)
model = clustering.fit(row[['DENSITY']])
row['KMeans_Clusters'] = model.labels_
return row
df = df.groupby('PROVINCE').apply(k_means)
</code></pre>
<p>results</p>
<pre><code>URBAN AREA PROVINCE DENSITY KM... | python|pandas|k-means|sklearn-pandas | 2 |
17,741 | 59,274,543 | Increment or reset counter based on an existing value of a data frame column in Pandas | <p>I have a dataframe imported from csv file along the lines of the below: </p>
<pre><code> Value Counter
1. 5 0
2. 15 1
3. 15 2
4. 15 3
5. 10 0
6. 15 1
7. 15 1
</code></pre>
<p>I want to increme... | <p>Here's my approach:</p>
<pre><code>s = df.Value.ne(15)
df['Counter'] = (~s).groupby(s.cumsum()).cumsum()
</code></pre> | pandas | 2 |
17,742 | 59,450,071 | how do you keep leading zeros in a csv file using python? | <p>Lets say my csv file looks something like this:</p>
<pre><code>acc_num,pincode
023213821,23120
002312727,03131
231238782,29389
008712372,00127
023827812,23371
</code></pre>
<p>when I open this file in excel , it removes the leading zeros , but here I need to keep them . This is how it looks when i open it in excel... | <p>Did you format the cells in the excel document as 'text', so that when you open it in excel it displays the leading zeros, then when you bring it into Python, ensure you're bring it in and storing as a string, as python3 does not allow leading zeros in ints. </p> | python|pandas|csv|openpyxl | 0 |
17,743 | 45,233,907 | Pandas DataFrame: How to change a column into an index, but this new index is a combination of both the current columns and indexes | <p>As per title, I have a similar dataframe such as this:</p>
<pre><code> c0 c1 c2
i0 1 2 3
i1 40 50 60
</code></pre>
<p>And I would like transform it into something like this:</p>
<pre><code> items
i0 c0 1
i0 c1 2
i0 c2 3
i1 c0 40
i1 c1 50
i1 c2 60
</code></pre>
<p>I think this has to do wi... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> only:</p>
<pre><code>df = df.stack()
print (df)
i0 c0 1
c1 2
c2 3
i1 c0 40
c1 50
c2 60
dtype: int64
</code></pre>
<p>Get <code>Mult... | python|pandas|dataframe | 0 |
17,744 | 45,216,381 | tensorflow static_rnn error: input must be a sequence | <p>I'm trying to feed my own 3D data to a LSTM. The data have: height = 365, width = 310, time = unknown / inconsistent, consist of 0 and 1, each block of data that produce an output are separated to a single file.</p>
<pre><code>import tensorflow as tf
import os
from tensorflow.contrib import rnn
filename = "C:/Kuli... | <p>When you call <code>pred = RNN(data, weights, biases)</code>, the <code>data</code> argument should be a sequence of length the length of your RNN. But in your case, it's a <code>data = tf.placeholder(tf.bool, name='data')</code>.</p>
<p>You could try <code>pred = RNN([data], weights, biases)</code>.</p>
<p>See th... | python|tensorflow|lstm|rnn | 7 |
17,745 | 44,915,954 | Map values from a dataframe | <p>I have a dataframe with the correspondence between two values:</p>
<p><a href="https://i.stack.imgur.com/293Kt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/293Kt.png" alt="enter image description here"></a></p>
<p>A another list with only one of the variables:</p>
<pre><code>l = ['a','b','c'... | <p>Another way is map by <code>Series</code> or by <code>dict</code> but is necessary unique value of <code>key</code>s, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>drop_duplicates</code></a> helps:</p>
<pre><code>df = pd.DataFra... | pandas|dictionary | 1 |
17,746 | 45,102,465 | pandas select specific groups | <p>I have a dataframe with an ID column and a measurement column</p>
<pre><code>ID measurement
1 A
1 B
1 C
1 D
2 A
2 B
2 C
2 D
3 A
4 A
4 B
4 C
4 D
4 E
</code></pre>
<p>I want to select only rows which have full measurements (A-D) per ID and remove rows which either have fewer (for example ID 3) or more measurements (... | <pre><code>In [92]: df.groupby('ID').filter(lambda x: set(x['measurement']) == set('ABCD'))
Out[92]:
ID measurement
0 1 A
1 1 B
2 1 C
3 1 D
4 2 A
5 2 B
6 2 C
7 2 D
</code></pre> | python|pandas|pandas-groupby | 2 |
17,747 | 45,106,398 | How to construct nested numpy record arrays? | <p>The <a href="https://docs.scipy.org/doc/numpy/neps/npy-format.html#use-cases" rel="nofollow noreferrer">numpy manual</a> mentions use case for <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html" rel="nofollow noreferrer">numpy.save</a></p>
<blockquote>
<p>Annie Analyst has been using la... | <p>Yes, like so:</p>
<pre><code>engine_dt = np.dtype([('volume', float), ('cylinders', int)])
car_dt = np.dtype([('color', int, 3), ('engine', engine_dt)]) # nest the dtypes
cars = np.rec.array([
([255, 0, 0], (1.5, 8)),
([255, 0, 255], (5, 24)),
], dtype=car_dt)
print(cars.engine.cylinders)
# array([ 8, 24... | python|arrays|numpy | 4 |
17,748 | 56,970,330 | Convert integer array to binary representation matrix | <p>Given a 1d integer array, e.g.:</p>
<p><code>[1, 0, -1]</code></p>
<p>looking for a binary representation matrix, desired output:</p>
<p><code>[[0 1], [0 0], [1 1]]</code></p>
<p>possibly using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.binary_repr.html" rel="nofollow noreferrer">np.bina... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unpackbits.html" rel="nofollow noreferrer">np.unpackbits</a>:</p>
<pre><code>a=np.array([-1,0,1]) # dtype is np.int32
</code></pre>
<p>You have to input your data as <code>np.uint8</code> because that is the only data type supported by... | python|numpy | 1 |
17,749 | 57,071,068 | loop to label multiple axes | <p>I need to run a loop to label 76 axes in a facetgrid plot I am creating. I am labelling the axes in a recurrent way - after each 6 axes, I will start again from the label "Overall Score". If I were to do it manually, it would be like this:</p>
<pre><code>axes[0].set_title("Overall Score")
axes[1].set_title("Busine... | <pre><code>titles = (
"Overall Score", "Business Ethics", "Environment",
"Health & Safety", "Labour", "Management System"
)
for ax in axes:
ax.set_title(titles[i % len(titles)])
</code></pre> | python|pandas|loops | 1 |
17,750 | 45,919,377 | What is the format of my training data file? | <p>I am new to Python and machine learning. I have this data <a href="https://drive.google.com/file/d/0Bxp_iuoQMgPVWjBGaWJSUUp2OXc/view?usp=sharing" rel="nofollow noreferrer">file</a> on which I want to apply binary classification. But I am unable to guess its format and to load it in Python. Can someone help me out he... | <p>It's a pure text file. By looking at the first row, it looks like a libsvm format.
See <a href="https://stats.stackexchange.com/questions/61328/libsvm-data-format">this</a> for a reference.</p> | python|pandas|machine-learning | 0 |
17,751 | 46,127,117 | Extracting and Grouping Sets of Columns in a Pandas DataFrame | <p>I have a DataFrame structure derived from a CSV file on population statistics over a number of years. Namely, the columns in the file are monthly time intervals (1999-01, 1999-02 ... 2016-12) and the rows are different population centers in the world (e.g. London, Toronto, Boston etc.):</p>
<pre><code>df = pd.DataF... | <p>You can convert columns <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> and then to <code>month period</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.to_period.html" rel="no... | python|pandas|dataframe|pandas-groupby | 0 |
17,752 | 45,821,617 | Python - TensorFlow - ModuleNotFoundError: No module named x | <p>I'm trying to run a TensorFlow program using python3.6 but I'm facing this error:</p>
<blockquote>
<p>ModuleNotFoundError: No module named 'tensorflow.python.pywrap_tensorflow_internal'</p>
</blockquote>
<p>I found out that I should run the script from another directory, other than the TensorFlow's. However, whe... | <p>I received this error when I was running tensorflow-gpu instead of tensorflow on windows with a machine that didn't have a graphics card.</p> | python|tensorflow | 0 |
17,753 | 23,064,899 | Compiler problems with pip during numpy install under Windows 8.1, 7 Enterprise and 7 Home Editions | <p>I am unable to install numpy via pip install numpy on my computer running Python 3.4 due to various errors I receive linked to compilation issues (This is only the case on a 64-bit installation of Python). </p>
<p>This is a problem that has been reported extensively and I had <a href="https://stackoverflow.com/ques... | <p>I was able to reproduce all these errors in Windows 7 Professional (64 bit).</p>
<p>Your final issue (Broken toolchain) is caused by more manifest related issues. I was able to work around this by changing the following line (in msvc9compiler.py):</p>
<pre><code>mfinfo = self.manifest_get_embed_info(target_desc, ... | python|windows|numpy|pip|python-3.4 | 9 |
17,754 | 28,617,430 | Numpy.cumsum in reverse | <p>Here is cumsum in the forward direction:</p>
<pre><code>> import numpy as np
> np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
> np.cumsum(np.arange(10))
array([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
</code></pre>
<p>I would like to perform cumsum in the reverse direction, which would give me</p>
<... | <p>Simplest I can think of and that produces your result is</p>
<pre><code>import numpy as np
x = np.arange(10)
x[::-1].cumsum()[::-1]
</code></pre>
<p>which gives</p>
<pre><code>array([45, 45, 44, 42, 39, 35, 30, 24, 17, 9])
</code></pre>
<p><strong>EDIT</strong>: As <em>dg99</em> pointed out, there's also <a hre... | python|numpy | 7 |
17,755 | 50,946,906 | combine int64 into list of integers after groupby in pandas | <p>There is a df with 2 columns </p>
<pre><code>goods_id int64
properties_id int64
dtype: object
df
goods_id properties_id
0 3588 1
1 3588 2
2 3588 3
3 3588 4
4 3588 5
5 3588 6
6 3589 1
7 3589 2
8 3589 3
</code></pre>
... | <p>In one line:</p>
<pre><code>df.groupby('goods_id').agg(lambda col: col.tolist()).reset_index()
</code></pre>
<p>Gives the following dataframe:</p>
<pre><code> goods_id properties_id
0 3588 [1, 2, 3, 4, 5, 6]
1 3589 [1, 2, 3]
</code></pre>
<p>If you have more columns in your dataframe... | pandas|python-3.5 | 1 |
17,756 | 50,716,935 | Finding value in a range in a pandas dataframe | <p>I have a dataframe and have a column named <code>BOL</code>. This value is between 2.0 and -2.0. I am trying to find, once BOL value reaches up to 0, if it reaches to 1.0 in 10 rows after current row. And would like to findout in how many rows BOL reaches to 1.0 after it's value 0.</p>
<p>Here is the dataframe:</p>... | <p>Here is a different approach where we create a function that accepts an array and turns it into an iterator. If a <code>>=0</code> value if found it will run for another 10 iterations looking for <code>>=1</code> to return <code>True</code>. Else <code>False</code>.</p>
<pre><code>import pandas as pd
df = pd... | python|pandas | 2 |
17,757 | 50,826,140 | Check if any value is 0 in Python DataFrame | <p>I have some csv files like:</p>
<pre><code>Time Test Two Three Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fifteen Sixteen
0 0 0 0 0 0 0 0 0 -0.3 0 0 100 0 0
0.02 0 0 0 0 0 0 0 0 -0.1 0.05 0 99 28 ... | <p>The problem statement, if I understand correctly, is to return a value <em>for each dataframe</em> in a list depending on whether a 0 exists in each dataframe's <code>Test</code> series.</p>
<p>Simply printing <code>'true'</code> or <code>'false'</code> may not be enough, since you will then have to link these back... | python|pandas | 1 |
17,758 | 20,529,619 | Renaming index values in multiindex dataframe | <p>Creating my dataframe: </p>
<pre><code>from pandas import *
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = zip(*arrays)
index = MultiIndex.from_tuples(tuples, names=['first','second'])
data = DataFrame(randn(8,2),ind... | <p>Use the <code>set_levels</code> method (<a href="http://pandas.pydata.org/pandas-docs/dev/whatsnew.html#what-s-new" rel="noreferrer">new in version 0.13.0</a>):</p>
<pre><code>data.index.set_levels([[u'cat', u'dog', u'foo', u'qux'],
[u'one', u'two']], inplace=True)
</code></pre>
<p>yields</... | python-2.7|pandas | 20 |
17,759 | 33,377,182 | How to find the number of days between two dates for dataframe manipulation | <p>How do I go about finding the number of days between the all the particular start date ranges in df1 and the according end date in df2. Then dividing the particular row in df1 by the number of days within the specific row (including the division of the particular kWh value and writing if to df1).</p>
<p>For example... | <p>Join the two dataframes, convert to datetime and subtract: </p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Start Date':['5/3/2013', '6/5/2013'], 'End Date':['6/5/2013', '7/2/2013'], 'kWh':[59120, 60400]})
pd.to_datetime(df['Start Date']) - pd.to_datetime(df['End Date'])
</code></pre>
<p>Result:</p>
<pr... | python|date|pandas | 2 |
17,760 | 66,398,202 | sort values using calculation in pandas python | <p>i wanted to sort the length of the message of the column without adding new column in dataframes.tried the below method and didnt work ..is there any way to sort values based on the any custom function.</p>
<pre><code>df.sort_values(df['message'].apply(len),ascending=False)
</code></pre>
<p>Regards,
Michael</p> | <p>You can use the <code>len()</code> of the string (message) as the <code>key</code> parameter in <code>sort_values()</code>.</p>
<p>Consider a random <code>df</code>:</p>
<pre><code>df = pd.DataFrame({'messages':['come here please as I need you','why would i come there','fine i will be there soon']})
df
... | python|pandas|dataframe | 1 |
17,761 | 66,395,551 | Unable to export tflite_ssd_graph in tensorflow 2 | <p>I trained the model using TensorFlow object detection API. It's working fine I am trying to export for low-end devices. I am unable to export it using.</p>
<pre class="lang-sh prettyprint-override"><code>python models/research/object_detection/export_tflite_ssd_graph.py
--input_type image_tensor
--pipeline_config_... | <p>It can be solved by install tf-nightly.</p>
<pre class="lang-sh prettyprint-override"><code>python -m pip install tf-nightly
</code></pre>
<p>for more reference check the <a href="https://github.com/tensorflow/models/issues/9767" rel="nofollow noreferrer">Issue</a> on Tensorflow Model Repo.</p> | python|tensorflow|object-detection-api | 0 |
17,762 | 66,419,016 | Get the first column of a dataframe using iloc[0] throws "IndexError : Single positional indexer out of bounds" | <p>I have a structure dataframe and I am trying to get the first column using</p>
<p>offset = 128</p>
<pre><code>row = struct.loc[struct['Offset']==offset].iloc[0]
</code></pre>
<p><a href="https://i.stack.imgur.com/xwhxm.png" rel="nofollow noreferrer">enter image description here</a></p> | <p>If this is your df:</p>
<pre><code>struct = pd.DataFrame({
'Offset': [164, 128],
'size': [128,36],
'param': ['Data1', 'Data2'],
'Address': ['0x0A', '0x0A']
})
</code></pre>
<p>And what you want is subset the first column with <code>iloc</code>, this should do it:</p>
<pre><code>struct.iloc[:,0]
<... | pandas|dataframe | 0 |
17,763 | 66,501,209 | Replace the max value for each column to 0 in Pandas | <p>For example, I have a data set of this:</p>
<pre><code>data = {
"A": [1, 2, 3],
"B": [3, 5, 1],
"C": [9, 0, 1]
}
data_df = pd.DataFrame(data)
</code></pre>
<pre><code>data_df
A B C
0 1 3 9
1 2 5 0
2 3 1 1
</code></pre>
<p>I want to replace the max value fo... | <p>You can interate through columns, get the max value and replace row with max value:</p>
<pre class="lang-py prettyprint-override"><code>for col in data_df.columns:
data_df[col] = data_df[col].apply(lambda x: 0 if x==data_df.max()[col] else x)
</code></pre> | python|pandas|data-manipulation | 2 |
17,764 | 66,481,614 | Merging two dataframes with multiple conditions in Pandas | <p>For some reason, I can't quite determine why Pandas is not merging my two dataframes. I've followed several other solutions, but I'm still not getting the expected output.</p>
<p>My main dataframe, <code>df</code>, has basketball player data and is quite large with 10000+ rows. Here is a snippet of <code>df</code>:<... | <p>This works for me:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Date': ['12/10/2020']*3 + ['12/11/2020']*3,
'Team': ['BOS', 'ATL', 'PHI', 'BOS', 'ATL', 'PHI']})
ps = pd.DataFrame({'Date': ['12/10/2020']*3 + ['12/11/2020']*3,
'Team': ['ATL', 'PHI', 'BOS', 'BOS', 'PHI... | python|pandas | 1 |
17,765 | 16,485,200 | Speed up while loop matching pattern in array | <p>I have the following data array, with 2 million entries:</p>
<pre><code>[20965 1239 296 231 -1 -1 20976 1239 299 314 147 337
255 348 -1 -1 20978 1239 136 103 241 154 27 293
-1 -1 20984 1239 39 161 180 184 -1 -1 20990 1239
291 31 405 50 ... | <p>Sounds like all you want is to do some boolean indexing magic to get rid of the invalid frame stuff, and then of course add the pixels up.</p>
<pre><code>rdata = rdata.reshape(-1, 2)
mask = (rdata != -1).all(1)
# remove every x, y pair that is after a pair with a -1.
mask[1:][mask[:-1] == False] = False
# remove f... | python|numpy | 6 |
17,766 | 57,357,040 | Modify all the values in the column of a Pandas Series | <p>I have a column with 9-char long numbers. I need to perform some operations on all values in that column to reach a length of 12. Here is the original data:</p>
<pre><code>493 123456789
494 123456789
496 115098765
497 123456789
498 987654321
499 987654321
</code></pre>
<p>Now, I need to perform s... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html#indexing-with-str" rel="nofollow noreferrer">indexing with str</a> for slice values:</p>
<pre><code>s = df['col'].astype(str)
df['new'] = s.str[0] + '20' + s.str[1:-5] + '0' + s.str[-5:]
print (df)
col new
493 12345... | python|arrays|pandas | 7 |
17,767 | 57,387,036 | Creating new pdf based on mean, standard deviation and skewness | <p>I have two time series with their mean and standard deviations and skewness computed. </p>
<p>How can I generate new probability density function(pdf) based on the mean and standard deviation of the first time series but skewness of the second time series. </p>
<pre><code> ts1 = [[ 0.24795413, 0.51981795, -1.128... | <pre><code>df = pd.DataFrame({'ts1': ts1, 'ts2': ts2})
df.describe()
</code></pre>
<p><a href="https://i.stack.imgur.com/v1AAk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v1AAk.png" alt="enter image description here"></a></p>
<h2>Data Plot:</h2>
<pre><code>df.plot()
</code></pre>
<p><a href="... | python|pandas|scipy|distribution|statsmodels | 0 |
17,768 | 43,624,299 | python - vlookup in pandas applying %LIKE% | <p>I am new to Python, and I am trying to join two CSV files (delimited by ";")</p>
<pre><code>CSV1
Sender;Recipient
Adam;123
Alex;234
John;123
Adam;888
CSV2
Name;Phone
Winnie;123,234,456
Celeste;777,888,999
</code></pre>
<p>Intended Output:</p>
<pre><code>Sender;Recipient;RecipientName
Adam;123;Winnie
Alex;234;Win... | <ul>
<li>Use <code>str.split</code> to turn <code>Phone</code> column into lists</li>
<li>Use <code>str.len()</code> to find the length of each of those lists. We'll use this to explode the <code>'Name'</code> column</li>
<li>Push all those lists together into one. Make sure to filter out zero length lists</li>
<li>U... | python|pandas | 3 |
17,769 | 43,898,026 | plotting pandas points with different colors | <p>I have a pandas data frame of two columns ['frequency','color'] and it looks like this:</p>
<pre><code> name frequency color
0 351 r
1 122 r
2 30 g
3 85 r
4 195 r
5 88 g
6 130 r
7 85 r
8 41 r
9 9 g
</code></pre>
<p>I want to plot the 'frequency' sorted and depending... | <p>The following figure<br>
<a href="https://i.stack.imgur.com/FnpJ8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FnpJ8.png" alt="enter image description here"></a></p>
<p>is produced by this code:</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
frequency =... | pandas|matplotlib | 4 |
17,770 | 73,066,172 | Unable to find nan value in numpy array even though it exists | <p><img src="https://i.stack.imgur.com/9mmor.png" alt="The problem that I am facing" /></p>
<p><code>brands</code> is a numpy array with 2314 elements. I am checking if there is a nan value in the array. The output shows false but when I tried intersection function with <code>np.nan</code>, it shows the common element ... | <p>The issue is that numpy's nan cannot be compared to itself, or in other words <code>numpy.nan == numpy.nan</code> returns False. Use instead <code>numpy.isnan()</code>.</p> | python|arrays|pandas|numpy|nan | 2 |
17,771 | 72,912,575 | Is FastAI performing transfer learning when calling a vision learner? | <pre><code>learn = vision_learner(dls, models.resnet18)
</code></pre>
<p>In the above code snippet, I am calling a Vision Learner Resnet 18 model using FastAI and passing in a Dataloader containing my data.</p>
<p>I wonder if this process is performing any transfer learning within this call? As I am passing in my data... | <p>FastAI's <a href="https://docs.fast.ai/vision.learner.html#vision_learner" rel="nofollow noreferrer">vision_learner</a> has a <code>pretrained</code> argument designed specifically for that purpose. By default it is set to <code>True</code>, so in your case you would want to disable it:</p>
<pre><code>learn = vision... | deep-learning|pytorch|transfer-learning|fast-ai | 0 |
17,772 | 73,125,716 | Tensorflow Lite Android: Both GPU delegate and NNAPI delegate are slower than CPU | <p>I am currently evaluating and comparing the performance of some tensorflow models on different smartphones. I am testing the MNIST and CIFAR10 databases. The strange thing is, when i try to speed up the inference times with hardware acceleration, they always perform worse than before.
For example, these are the resu... | <p>It seems that both models are already performing well on CPU with the inference latency < 1ms.</p>
<p>Accelerators are not always faster than CPU. Often, there is some overhead when accessing the accelerators. Also, accelerators could run certain models / operators really well, but they may not support all the op... | java|android|tensorflow-lite|hardware-acceleration|nnapi | 1 |
17,773 | 73,093,208 | What is properway to specify numpy masked array maksed value? | <p>I basically want to run something like the following</p>
<pre><code>x = np.array([1,2,3,4,5])
a = ma.masked_array(x, mask=[0, 0, 0, 1, 0])
for i in range(5):
if (a[i] == "--"):
print("a[{0:d}] is masked value".format(i))
</code></pre>
<p>I am not sure how I should specify the <code>--<... | <p>A masked array has two key attributes, <code>data</code> and <code>mask</code>.</p>
<pre><code>In [63]: a.mask
Out[63]: array([False, False, False, True, False])
In [64]: a.data
Out[64]: array([1, 2, 3, 4, 5])
</code></pre>
<p><code>getmask</code> docs say its equivalent to getting the attribute:</p>
<pre><code>In ... | python|numpy | 1 |
17,774 | 73,106,233 | Pandas - Setting new column - ["from-to"] - finding the first and last Date Time appearance | <p>Let's say that those columns are already in place - ["time","startTime","endTime","source"] and I also have more columns that are not related for this question in this df.<br />
I want to set up new Column that find the first appearance of an instance with the same startTime... | <ol>
<li><strong>Groupby</strong> source,endTime,startTime to account for all possible combinations.</li>
<li><strong>Sorting</strong> can be done first,since groupby maintains order.</li>
<li><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transform.html" rel="nofollow noreferrer">transform</a> ... | python|pandas | 0 |
17,775 | 70,492,693 | Removing numbers from dataframe that lie within range | <p>I have a pandas dataframe that contains values between -1000 to 1000. I want to eliminate all the numbers between the range of -0.00001 to 0.00001 i.e replace them with NaN. It is worth mentioning that my df contains numerous instances of very small positive and negative numbers that I want to include within this ra... | <p>IIUC use if need less like <code>-0.00001</code> and <code>0.00001</code>:</p>
<pre><code>df = df.mask(df.lt(-0.00001) | df.lt(0.00001))
</code></pre>
<p>is same like below <code>0.00001</code>:</p>
<pre><code>df = df.mask(df.lt(0.00001))
</code></pre>
<p>Or if need values between:</p>
<pre><code>df = df.mask(df.gt(... | python|pandas|dataframe|filtering | 1 |
17,776 | 70,643,616 | Create composite variable from multiple variables and add to dataframe | <p>I have a dataframe with three median rent variables. The dataframe looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>region_id</th>
<th>year</th>
<th>1bed_med_rent</th>
<th>2bed_med_rent</th>
<th>3bed_med_rent</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2010</td>
<td>... | <p>Here <code>set_index</code> combined with <code>apply</code> applied to the rest of the row ought to do it:</p>
<pre><code>(df.set_index(['region_id','year'])
.apply(lambda r:r.median(), axis=1)
.reset_index()
.rename(columns = {0:'med_rent'})
)
</code></pre>
<p>produces</p>
<pre><code> region_id ye... | python|pandas|aggregate-functions | 1 |
17,777 | 70,501,267 | Representing a state-space model as Neural Network in TensorFlow | <p>How does one represent a State-Space model with a Neural Network in TensorFlow?</p>
<p>I would say the simplest way would be to use a Recurrent Neural Network, but I'm not exactly sure how to do this in TensorFlow...</p> | <p>You can use SimpleRNN. The following sources deal with this.</p>
<p><a href="https://aleksandarhaber.com/using-recurrent-neural-networks-and-keras-tensorflow-to-learn-input-output-behaviour-of-dynamical-systems/" rel="nofollow noreferrer">https://aleksandarhaber.com/using-recurrent-neural-networks-and-keras-tensorfl... | tensorflow|state-space | 0 |
17,778 | 70,426,153 | How to resolve problems with pandas in juypter notebook? | <p>I am working my way down through the chapter 3 of book hands on machine learning with scikit learn. I have imported the mnist dataset, but when I am trying to get some image it is showing me an error: <a href="https://i.stack.imgur.com/242Zt.jpg" rel="nofollow noreferrer">screenshot of the error and code!</a> I have... | <p>I would suggest a different way of resolving this, something that may be helpful in other machine learning projects when you work with Pandas. When slicing data, try to use <code>iloc</code> function instead. In your case, I have tried using <code>X.iloc[0]</code> with the same code and it works, no need to reinstal... | python|pandas|scikit-learn|mnist | 0 |
17,779 | 70,612,349 | Pandas: Create a new column based on a list of other values in my dataframe | <p>By using the following dataframe, I would like to create a new column based on a list of other values in my dataframe</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1... | <p>It's a simple case of creating a <strong>list</strong> from defined columns</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
... | python|pandas | 2 |
17,780 | 70,618,801 | How to replace NaN values with values from another row | <p>I have a table</p>
<pre><code>df = pd.DataFrame({'car': ['toyota', 'toyota', 'ford', 'ford'],
'doors': [nan, 2.0, nan, 4.0],
'seats': [2.0, nan, 4.0, nan]})
</code></pre>
<p>that looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>car</th>
<th>doors</th>
<th>seats</th>
</t... | <p>Another option is to use <code>groupby_first</code> method. <code>first</code> method skips <code>NaN</code> values by default.</p>
<pre><code>out = df.groupby('car', as_index=False).first()
</code></pre>
<p>Output:</p>
<pre><code> car doors seats
0 ford 4.0 4.0
1 toyota 2.0 2.0
</code></pre> | python|pandas|dataframe | 2 |
17,781 | 70,593,265 | How to subtract the columns after the first column, from the first column in a loop? | <p>It seems simple but I can't seem to find an efficient way to solve this in Python 3: Is there is a loop I can use in my dataframe that subtracts every column after the first column, from the first column, so that I can add that new subtracted column to a new dataframe?</p>
<p>Then I would like to move on to subtract... | <p>I think you can use a (if you have a row for an id you can get your items by)
select from where statement. make sure the 1 is whatever your first item's id is.</p>
<p><code>DELETE FROM mytable WHERE ID!=1</code></p>
<p>This will remove everything except the first row!</p> | python|pandas|dataframe|loops|calculated-columns | -1 |
17,782 | 70,700,576 | Filter Numpy array based on different size mask array | <p>I'm trying to mark regions of an image array (224x224) to be ignored based on the value of a segmentation network's class mask (16x16). Previous processing means that unwanted regions will be labelled as -1. I want to be able to set the value of all regions of the image where the class mask reports -1 to some nonsen... | <p>Here's some code I got to work. It does require the mask and the image to have the same aspect ratio, and be integer multiples of each others sizes.</p>
<pre><code>import numpy as np
image = np.array([[1,2,3,4],
[5,6,7,8],
[9,1,2,3],
[4,5,6,7]])
mask = np.arra... | python|numpy|image-processing|image-segmentation | 3 |
17,783 | 42,623,077 | python replace string in a specific dataframe column | <p>I would like to replace any string in a dataframe column by the string 'Chaudière', for any word that starts with the string "chaud". I would like the first and last name after each "Chaudiere" to disapper, to anonymize the NameDevice</p>
<p>My data frame is called df1 and the column name is NameDevice.</p>
<p>I h... | <p>You can do the matching by calling <code>str.lower</code> first, then you can use <code>str.startswith</code>, and then just <code>split</code> on the spaces and take the first entry to anonymise the data:</p>
<pre><code>In [14]:
df.loc[df['NameDevice'].str.lower().str.startswith('chaud'), 'NameDevice'] = df['NameD... | python|pandas|dataframe | 0 |
17,784 | 42,597,531 | Why GPUs comes more into play than CPUS when it comes to dealing with Deep Learning? | <p>In almost most of the cases, I come across about GPUs while dealing with any execution part in Deep Learning. </p> | <p>This has to do with GPU architecture versus CPU. It turns out gaming requires a lot of matrix multiplications, hence the GPU architecture was optimized for these types of operations, specifically they are optimized for high rate floating-point arithmetic. More on this <a href="https://graphics.stanford.edu/papers/gp... | machine-learning|tensorflow|gpu|deep-learning|cpu | 2 |
17,785 | 27,189,014 | PANDAS efficient large dataframe iteration? | <p>I'm just starting with Python and because I'm an experienced R user I found that PANDAS would fit to the following situation. I tried to describe it clearly, so </p>
<p>The situation is: </p>
<blockquote>
<ul>
<li>Large dataframe (filled with 0s) with colnames and rownames (dimensions 85558 x 85558)</li>
<li... | <p>I'm a bit confused as to why you have the <code>CHR-1</code> and <code>CHR-2</code> columns, they don't seem to add anything. Here's my example <code>DataFrame</code>:</p>
<pre><code>df = pandas.DataFrame([[500, 200], [600,1100], [500, 2200]], columns=['a','b'])
>>> df
a b
0 500 200
1 600 11... | python|pandas|dataframe | 0 |
17,786 | 26,506,204 | Replace sub part of matrix by another small matrix in numpy | <p>I am new to Numpy and want to replace part of a matrix. For example, I have two matrices, A, B generated by numpy</p>
<pre><code>In [333]: A = ones((5,5))
In [334]: A
Out[334]:
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
... | <p>Here is how you can do it:</p>
<pre><code>>>> A[3:5, 3:5] = B
>>> A
array([[ 1. , 1. , 1. , 1. , 1. ],
[ 1. , 1. , 1. , 1. , 1. ],
[ 1. , 1. , 1. , 1. , 1. ],
[ 1. , 1. , 1. , 0.1, 0.2],
[ 1. , 1. , 1. , 0.3, 0.4]])
</code></pre> | python|numpy|matrix | 34 |
17,787 | 39,230,220 | openpyxl module does not have attribute '__version__' when imported by pandas | <p>My traceback from running pandas takes me to: <br/>
<code>site-packages\pandas\io\excel.py line 58, in get_writer
AttributeError: 'module' object has no attribute '__version__'</code></p>
<p>I found this link to a git issue in the PyInstaller repo
<a href="https://github.com/pyinstaller/pyinstaller/issues/1890" rel... | <p>I will add my workaround to this discussion as I was having the same problem using openpyxl 2.4.0 and maybe a few others are stuck too.
I found that to create a .exe file you have to revert to an older version of openpyxl. To do so:</p>
<ol>
<li>Open the command prompt and uninstall openpyxl with 'pip uninstall ope... | python|pandas|openpyxl|conda | 2 |
17,788 | 19,616,277 | Python: negative numbers, when multiplying a matrix by a vector with numpy | <pre><code>A = numpy.matrix([[36, 34, 26],
[18, 44, 1],
[11, 31, 41]])
X1 = numpy.matrix([[46231154], [26619349], [37498603]])
</code></pre>
<p>Need multiplying a matrix by a vector. I tried:</p>
<pre><code>>>>A*X1
matrix([[ -750624208],
[ 2040910731],
[-1423782060]])
>... | <p>I believe you're on a 32-bit system, and you're seeing an integer overflow. Try defining the matrix and vector with the keyword argument <code>dtype=np.int64</code>, and see if you get a more meaningful answer.</p>
<p>On my 64 bit machine, I have the following output</p>
<pre><code>In [1]: import numpy
In [2]: A ... | python|numpy | 4 |
17,789 | 29,005,612 | ipython Pandas : why I cannot print the legend for matplot graphs? | <p>I am using this code to put legend on my graph but it is not possible.</p>
<pre><code> for key in ['cluster0', 'cluster1', 'cluster2', 'cluster3']:
mask = e['cluster'] == key
ax.scatter(e['count_sbwip'][mask],e['perc_of_seen_ip'][mask],
c=LABEL_COLOR_MAP[key], label=LAB... | <ol>
<li><p>It's just a typo. As the traceback shows, you were calling <code>ax.scatter</code> with the argument <code>lebel</code> instead of <code>label</code>. </p></li>
<li><p>If you want four legends on the same plot, you can simply call <code>ax.scatter</code> 4 times with the corresponding <code>label</code> arg... | python|pandas|matplotlib | 1 |
17,790 | 29,136,485 | Plotting a Network Graph with all edges clearly visible | <p>I have a graph network data (using adjacency matrix) of 30 nodes. The graph currently looks like this: </p>
<p><img src="https://i.stack.imgur.com/Oih5Y.png" alt="enter image description here"></p>
<p>Each cluster has 15 nodes and each node is connected to other node within the same cluster. Only two pair of nodes... | <p>Have you tried applying a node-positioning layout to it? The <code>networkx</code> library has support for layouts. Take a look <a href="http://networkx.github.io/documentation/networkx-1.9.1/reference/drawing.html#module-networkx.drawing.layout" rel="nofollow noreferrer">here</a>. I would personally recommend the s... | python|numpy|pandas|matplotlib | 3 |
17,791 | 29,010,597 | Pandas Rolling Functions with Groupby | <p>I am having a problem trying to implement the 'rolling' functions in Pandas (i.e. rolling_std() and rolling_corr()) when using the group by functions. I have tried using the below formulas but I keep getting 'ValueError: cannot reindex from a duplicate axis'.</p>
<p><code>df</code> is my dataframe:</p>
<pre><code... | <p>In newer versions of pandas the syntax of <code>rolling</code> has changed, for example, from <code>rolling_std()</code> to <code>rolling().std()</code> and works well when combined with <code>groupby</code>:</p>
<pre><code>df.groupby('ID').rolling(2).std()
ID Date Val1 Val2
ID ... | python|pandas|group-by|correlation|standard-deviation | 0 |
17,792 | 29,081,942 | Python : creating an array, weighed by sine function | <p>I can create an array of 100 <strong>evenly spaced numbers</strong> from 0 to 30 by doing -</p>
<pre><code>theta = linspace(0,30,100)
</code></pre>
<p>Is it possible to get an array of 100 numbers from 0 to 30, which is not evenly spaced, but weighed by their sine function??</p>
<p><strong>EXPLANATION:</strong> H... | <p>I think I've got your solution. It takes an originally linearly spaced array and takes the <code>sine</code> of it, it then returns the sines scaled to have the same end as the linear array.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def sinespace(m=90, n=10):
x = np.linspace(0, m, n)
... | python|arrays|numpy | 3 |
17,793 | 33,725,159 | Understanding Variable scope example in Tensorflow | <p>I was looking at the mechanics section for Tensorflow, specifically on <a href="https://chromium.googlesource.com/external/github.com/tensorflow/tensorflow/+/r0.7/tensorflow/g3doc/how_tos/variable_scope/index.md" rel="nofollow noreferrer">shared variables</a>. In the section "The problem", they are dealing with a co... | <p>One has to create the variable set only once per whole training (and testing) set. The goal of <em>variable scopes</em> is to allow for modularization of <em>subsets of parameters</em>, such as those belonging to layers (e.g. when architecture of a layer is repeated, the same names can be used within each layer scop... | tensorflow | 10 |
17,794 | 33,756,187 | Wrong fit using scipy curve_fit | <p>I am trying to fit some data to a power law function with exponential cut off. I generate some data with numpy and i am trying to fit those data with scipy.optimization.
Here is my code:</p>
<pre><code>import numpy as np
from scipy.optimize import curve_fit
def func(x, A, B, alpha):
return A * x**alpha * np.e... | <p>Whilst xnx gave you the answer as to why <code>curve_fit</code> failed here I thought I'd suggest a different way of approaching the problem of fitting your functional form which doesn't rely on a gradient descent (and therefore a reasonable initial guess)</p>
<p>Note that if you take the log of the function that y... | python|numpy|scipy|curve-fitting | 5 |
17,795 | 23,824,758 | Dictionary versus NumPy array performance Python | <p>I am working with multiple NumPy 2-dimension arrays (matrices), and I want to get some rows, or columns, from them (same rows or columns indexes for each of the 3 matrices, each time). I was wondering if I should use dictionary or not. </p>
<p>If I do it with a dictionary, then each row of each matrix would be inde... | <p>For matrix operation, I strongly recommend numpy, to justify my choice, I want first to quote wikipedia:</p>
<p><a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">http://en.wikipedia.org/wiki/NumPy</a></p>
<p><em>"... any algorithm that can be expressed primarily as operations on arrays and matrices can r... | python|arrays|numpy|dictionary|matrix | 2 |
17,796 | 23,667,024 | Pythonic way to convert a dictionary to a numpy array | <p>This is more of a question about programming style.
I scrap webpages for fields such as: "Temperature: 51 - 62", "Height: 1000-1500"...etc The results are saved in a dictionary </p>
<pre><code>{"temperature": "51-62", "height":"1000-1500" ...... }
</code></pre>
<p>All key and values are string type. Every key ca... | <p>Try a pandas Series, it was built for this.</p>
<pre><code>import pandas as pd
s = pd.Series({'a':1, 'b':2, 'c':3})
s.values # a numpy array
</code></pre> | python|numpy|dictionary | 7 |
17,797 | 15,397,943 | Input via a plot in matplotlib | <p>I wrote some code that has a few boolean statements at the beginning, and depending on which ones are True/False different problems are solved, and different plots are created (currently using imshow and some animation). </p>
<p>How would I run the code, have some sort of interactive window (be in a plot or some ot... | <p>This is called widgets in matplotlib:</p>
<p><a href="http://matplotlib.org/api/widgets_api.html" rel="nofollow">http://matplotlib.org/api/widgets_api.html</a></p>
<p>And here are some examples:</p>
<p><a href="http://matplotlib.org/examples/widgets/index.html" rel="nofollow">http://matplotlib.org/examples/widget... | python|input|numpy|matplotlib|scipy | 2 |
17,798 | 62,114,182 | Slicing a multiindex on Pandas | <p>I've got a dataframe with a multiindex of the form: </p>
<pre><code>(label, date)
</code></pre>
<p>where <code>label</code> is a string and <code>date</code> is a DateTimeIndex.</p>
<p>I want to slice my dataframe by <code>date</code>; say for example, I want to get all the rows between 2007 and 2009:</p>
<pre><... | <p>You can check <a href="https://pandas.pydata.org/docs/user_guide/timeseries.html#partial-string-indexing" rel="nofollow noreferrer">partial string indexing</a>:</p>
<blockquote>
<p>DatetimeIndex partial string indexing also works on a DataFrame with a MultiIndex:</p>
</blockquote>
<pre><code>df = pd.DataFrame(np... | python|pandas | 1 |
17,799 | 62,159,437 | Pytorch: Recover network with customized VGG model that was saved improperly | <p>I am currently doing work with customizing the forward method for models. I was using some tutorial code that ran VGG. I did a few runs with the baseline model and it seemed to work fine. Afterwards, I replaced the forward method for the VGG using:</p>
<p><code>net.forward = types.MethodType(forward_vgg_new, net)</... | <p>To solve the problem, I went directly into the VGG library and temporarily added my function so that I could load the saved models and save only their state dicts. I reverted the changes to the VGG library after I recovered the saves. Not the most graceful way of fixing the problem, but it worked.</p> | pytorch | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.