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
18,600
48,087,859
Why neural network suddenly converges to fixed result?
<p>I'm using tensorflow to train MLP &amp; CNN with AdamOptimizer as a default parameters. I found that it works well but after some training step, it converges to fixed results. For example, there's only two categories, </p> <pre><code>training step 0: 0.5 training step 1000:0.9 training step 2000: 0.953 .......... t...
<p>Because no code is posted, we can only presume likely asnswers. In my experience, when something like this happens (e.g. training collapses) this has to do with some kind of overflow in the network. Do you have training examples that produce nans? Plotting the output of your network shortly before it diverges helps ...
tensorflow|deep-learning
0
18,601
48,478,457
Pandas: General Data Imputation Based on Column Dtype
<p>I'm working with a dataset with ~80 columns, many of which contain NaN. I definitely don't want to manually inspect <code>dtype</code> for each column and impute based on that.</p> <p>So I wrote a function to impute a column's missing values based on its <code>dtype</code>:</p> <pre><code>def impute_df(df, col): ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>select_dtypes</code></a> for numeric and non numeric columns and then apply fillna for filtered columns:</p> <pre><code>df = pd.DataFrame({'A':list('abcdef'), ...
python|pandas
2
18,602
48,465,210
Pandas: Truth Value of a Series is Ambiguous Despite Using Bitwise
<p>I'm trying to find all rows in my DataFrame (<code>combined_df</code>) where the <code>Title</code> column is not any of <code>"Mr", "Miss", "Mrs", "Master"</code>. Here's my attempt:</p> <pre><code>combined_df[~ (combined_df.Title in ["Mr", "Miss", "Mrs", "Master"])] </code></pre> <p>I get this error:</p> <pre>...
<p>You can try with:</p> <pre><code>combined_df = combined_df[~combined_df['Title'].isin(['Mr', 'Mrs', 'Miss', 'Master'])] </code></pre>
python|pandas
0
18,603
70,996,317
Row-wise minimum of a DataFrame after applying a function
<p>I have a DataFrame that looks something like this:</p> <pre><code> Col1 Col2 Col3 0 7 11 17 1 13 12 15 2 19 23 14 3 22 19 21 </code></pre> <p>I want to find the row-wise minimum after applying a function, returning the original values before the function was applied, so...
<p>As <code>lookup</code> is now deprecated, you have to flatten your dataframe manually to retrieve one value per row with <code>loc</code>. The first line computes your operation and get the index of the minimum:</p> <pre><code>r = df.sub(sr, axis=0).abs().idxmin(axis=1) df['min_val_with_key'] = df.unstack().loc[zip(...
python|pandas|dataframe
1
18,604
64,430,499
Pandas: Compare two dataframes and replace with specific value if not available in column?
<pre><code>df1 = pd.DataFrame({'name': ['AUD','CAD', 'SMI','Joy', 'SHA', 'CHY', 'AUD', 'KRL'], 'sal': [200,300,600,500,300,200,100,350]}) df2 = pd.DataFrame({'name': ['SMI','Joy', 'SHA', 'CHY'], 'sal': [600,500,300,200]}) </code></pre> <p>I want to compare above two dataframes by 'name' column and if va...
<p>Let's try <code>where</code> and <code>isin</code>:</p> <pre><code>df1['name'] = df1['name'].where(df1['name'].isin(df2['name']), 'Others') </code></pre> <p>Output (<code>df1</code>):</p> <pre><code> name sal 0 Others 200 1 Others 300 2 SMI 600 3 Joy 500 4 SHA 300 5 CHY 200 6 Others 10...
pandas
1
18,605
64,223,873
I want to fill missing rows in a dataframe indexed by datetime with NAs across all columns
<p>I have some code where I can join two dataframes together, and overwrite the values in <code>df</code> with those in <code>df1</code></p> <pre><code>import pandas as pd import numpy as np #create two dataframes df = pd.DataFrame(np.random.randint(0,30,size=(10, 4)), columns=(['Temp', 'Precip', 'Wind', 'Pressure'])...
<p>One idea should be append only <code>Location</code> to <code>MuliIndex</code> and then add missing rows by <code>unstack</code> with <code>stack</code> methods:</p> <pre><code>df = df.set_index(['Location'], append=True) df1 = df1.set_index(['Location'], append=True) df = (df.combine_first(df1) .unstack() ...
python|pandas
0
18,606
64,212,524
Pandas .fillna() not working with .sample()
<p>I have a data set with a column <code>state</code> whose unique values consist of <code>['released', 'isolated', 'deceased', nan]</code>. I've tried to impute missing data using random sampling, like so:</p> <pre><code>for column in ['sex','state','city']: df[column].fillna(df[column].sample(), inplace=True) </c...
<p>You can not <code>fillna</code> with <code>Series</code> since it will match the <code>index</code></p> <pre><code>new=pd.DataFrame({'blank':[np.nan for i in range(0,100)]}) new['blank'].fillna(df['state'].sample().iloc[0]) </code></pre>
python|pandas|random|fillna
0
18,607
64,555,162
Pandas Dataframe: df.apply ignore error rows
<p>Good morning! I am trying to convert a column that has multiple dates in various formats into a datetime column.</p> <pre><code>import pandas as pd data = { 'c1':['2020/10/01','10/01/2020','10/1/2020','31/08/2020','12-21-2020','5-3-2020','05-03-2020','ERRER'] } df = pd.DataFrame (data, columns = ['c1']) </code...
<p>If use <code>errors='coerce'</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> get <code>NaT</code> (missing values for datetimes) if not datetime-like values - yoou can pass column for improve performance, not...
python|pandas|apply|string-to-datetime
2
18,608
64,311,262
Find nearest point on each line for all linestring intersections in geopandas df
<p>I have a geopandas dataframe containing several line strings created from lat, lon point data. For all line intersections, I need to find the nearest point within each line string to that intersection.</p> <p>Thus, if two lines in the dataframe intersect, I need to nearest point to that intersection in each linestri...
<p>Let's create n random lines :</p> <pre><code>import geopandas as gpd from shapely.geometry import LineString, Point, Polygon from shapely import wkt import numpy as np xmin, xmax, ymin, ymax = 0, 10000, 0, 10000 n = 100 xa = (xmax - xmin) * np.random.random(n) + xmin ya = (ymax - ymin) * np.random.random(n) + ymin x...
python|pandas|geopandas|shapely
1
18,609
64,531,656
Retrieving original data from PyTorch nn.Embedding
<p>I'm passing a dataframe with 5 categories (ex. car, bus, ...) into <code>nn.Embedding</code>.</p> <p>When I do <code>embedding.parameters()</code>, I can see that there are 5tensors but how do I know which index corresponds to the original input (ex. car, bus, ...)?</p>
<p>You can't as tensors are unnamed (only dimensions can be named, see <a href="https://pytorch.org/docs/stable/named_tensor.html" rel="nofollow noreferrer">PyTorch's Named Tensors</a>). You have to keep the names in separate data container, for example (<code>4</code> categories here):</p> <pre><code>import pandas as ...
pytorch|embedding
1
18,610
64,300,147
How to separate cells containing lists in a specific column that has a mixture of strings and lists of strings?
<p>I am trying to organise a pandas data frame in python that has the following pseudo structure (I have altered variable names for ease of understanding):</p> <p><a href="https://i.stack.imgur.com/ptEzU.png" rel="nofollow noreferrer">Initial_df</a></p> <p>What code is able to split the lists in col_1 so that only indi...
<p>If structure like this using list in col_1:</p> <pre><code>df = pd.DataFrame({'col_1':[['a'],[*'ab'],['c'],[*'bc'],['d'],[*'acd']] ,'col_2':[3,6,1,5,1,3]}) </code></pre> <p>Then you can use <code>explode</code>, <code>groupby</code> and <code>sum</code>:</p> <pre><code>df.explode('col_1').groupby('...
python|pandas|dataframe|rows
0
18,611
64,381,353
How can I get the normalized matrix out of this function?
<p>I am given a dataset called stocks_df. Each column has stock prices for different stocks in each day. I am trying to normalize it and return it as a matrix. So, each column will have normalized for a stock for each day. Wrote up this function-</p> <pre><code>def normalized_prices(stocks_df): normalized=np.zeros((...
<p>From your code, it looks you want to divide everything by the first column, so you can simply do:</p> <pre><code>import numpy as np import pandas as pd np.random.seed(123) stocks_df = pd.DataFrame(np.random.uniform(0,1,(20,10))) stocks_df.div(stocks_df[0],axis=0) 0 1 2 3 4 ...
python|pandas|dataframe|data-manipulation
0
18,612
47,641,956
Rearranging Table after PDF extraction with Tabula
<p>I have used Tabula to extract a table from a PDF. It worked will minus a little clean up. The last issue I have and I'm not sure how to overcome is that if a cell row is too large (i.e. it contains wrapped text) then Tabula splits it into two rows with the row containing almost all the information and the second row...
<p>I ran into a similar issue and wrote the following function (modified slightly to match your example):</p> <pre><code>def CleanRunResults(df): for row in range(len(df)-1, -1, -1): NoArea = pd.isnull(df['Area'].iloc[row]) NoShape = pd.isnull(df['Shape'].iloc[row]) YesType = pd.notnull(df[...
python|pandas|loops|pdf|tabula
1
18,613
49,008,508
How to filter dataframe for column with lists contains value
<p>We have dataframe with lists in one column. Couldn't find easy way to filter dataframe for rows contains value in their lists.</p> <pre><code>df = pd.DataFrame({'lists':[['a', 'c'], ['a', 'b', 'd'], ['c', 'd']]}) </code></pre> <p>For example I need only rows contains 'a' in their lists. I managed to get it only th...
<p>Simpliest is use <code>apply</code> with <code>in</code>:</p> <pre><code>df1 = df[df.lists.apply(lambda x: 'a' in x)] </code></pre> <p>But if want check <code>a</code> create <code>DataFrame</code>, but it is a bit complicated:</p> <pre><code>df1 = df[pd.DataFrame(df.lists.values.tolist()).eq('a').any(axis=1)] </...
python|list|pandas|filter
6
18,614
58,679,207
Flag holidays in DataFrame on python3
<p>I have a pandas DataFrame that have timestamp and have a set of datetimes of holidays </p> <pre><code>{datetime.date(2016, 1, 1), datetime.date(2016, 3, 25), datetime.date(2016, 3, 27), datetime.date(2016, 3, 28), datetime.date(2016, 5, 2), datetime.date(2016, 5, 30), datetime.date(2016, 8, 29), datetime.date(2016,...
<p>Ensure <code>timestamp</code> column is of type datetime and then use <code>date</code> to compare with the holidays set.</p> <pre><code>df['timestamp'] = pd.to_datetime(df['timestamp']) df['holidays'] = pd.np.where(df['timestamp'].dt.date.isin(holidays), 1, 0) </code></pre>
python-3.x|pandas|dataframe|timestamp|time-series
1
18,615
58,855,960
Converting multi-dimensional numpy array elements to strings WITHOUT converting to scientific notation
<p>I have a <strong>multi-dimensional</strong> numpy array with float elements. I want to convert the elements to strings, but NOT have the elements change to scientific notation. </p> <p>An example:</p> <pre><code>import numpy as np np.set_printoptions(suppress=True) x = np.array([0.000095]) # prints as "[0.000095]...
<p>you can use np.nditer to achieve this for multidimensional arrays</p> <p>let </p> <pre><code>my_multidimensional_array = np.ones((3,3,3)) * 0.000095 my_multidimensional_array Out[105]: array([[[0.000095, 0.000095, 0.000095], [0.000095, 0.000095, 0.000095], [0.000095, 0.000095, 0.000095]], ...
python|arrays|numpy
1
18,616
58,611,604
Mapping diagonal
<p>Let's say I have the following dataframe:</p> <pre><code>idx = ['H',"A","B","C","D"] idxp = idx[1:] + [idx[0]] idxm = [idx[-1]] + idx[:-1] idx, idxp, idxm j = np.arange(25).reshape(5,5) J = pd.DataFrame(j, index=idx, columns=idx) np.fill_diagonal(J.values, 0) J </code></pre> <p><a href="https://i.stack.imgur.com/4...
<p>Few methods are listed.</p> <p>I. Basic method</p> <pre><code>a = J.values p = np.r_[0,a.ravel()[1::a.shape[1]+1]] # or np.r_[0,np.diag(a,1)] n = len(p) out = np.triu(np.broadcast_to(p,(n,n)),1).cumsum(1) </code></pre> <p><code>p</code> and <code>n</code> would be re-used in alternatives listed next.</p> <p>A. A...
python|pandas|performance|numpy|vectorization
2
18,617
58,726,804
Assign same unique ID for all chaining element rows from pandas data frame
<p>I have pandas dataframe as below :</p> <pre><code> No IsRenew PrevNo 0 IAB19 TRUE - 1 IAB25 FALSE - 2 IAB56 TRUE IAB19 3 IAB22 TRUE IAB56 4 IAB81 TRUE IAB22 5 IAB82 TRUE - 6 IAB89 FALSE IAB82 </code></pre> <p>I want to generate ids unique for each group. for ...
<p>Use <code>networkx</code> with <a href="https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.components.connected.connected_components.html" rel="nofollow noreferrer"><code>connected_components</code></a> for dictionary and then <a href="http://pandas.pydata.org/pandas-docs/...
python|pandas|merge|pandas-groupby
3
18,618
70,346,398
How does pytorch L1-norm pruning works?
<p>Lets see the result that I got first. This is one of a convolution layer of my model, and im only showing 11 filter's weight of it (11 3x3 filter with channel=1)</p> <p><a href="https://i.stack.imgur.com/Vh8RB.png" rel="nofollow noreferrer">Left side is original weight Right side is Pruned weight</a></p> <p>So I was...
<p>The <code>nn.utils.prune.l1_unstructured</code> utility does not prune the whole filter, it prunes individual parameter components as you observed in your sheet. That is components with the lower norm get masked.</p> <hr /> <p>Here is a minimal example as discussed in the comments below:</p> <pre><code>&gt;&gt;&gt; ...
pytorch|conv-neural-network|pruning
0
18,619
70,285,005
Iterating a dataframe and updating (adding on to the existing) instead of it being replaced
<p>I have an empty dataframe which when passed through the loop, returns result that matches the condition present from the last value in the list instead of considering all of it's values.</p> <p>The dataframe gets replaced for each of the condition in list, instead of being added to it.</p> <p>I have tried empty_df.a...
<p>You can craete each time a new dataframe in the lopp and lastly can concatenate them using pd.concat([df_doc, df_phy,.. df_stat])</p>
python|pandas|dataframe|iteration
0
18,620
70,272,761
select based on row combinations on different columns pandas
<p>I have the following pandas data frame.</p> <pre><code>ID col1 col2 value 1 4 New 20 2 4 OLD 30 3 5 OLD 60 4 5 New 50 5 3 New 70 </code></pre> <p>I would like to select only rows which has the following rules. from <code>col1</code> value 4 and 3 should be in <co...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>DataFrame.query</code></a> with filter by <code>in</code> chained by <code>&amp;</code> for bitwise <code>AND</code> and second condition chain by <code>|</code> for bitwise <code>OR</c...
python|pandas
3
18,621
70,108,471
How to fill missing values using start and end values?
<p>I have start and end value and there are n missing values. The logic to fill missing value is find average between start and end value.</p> <p>psuedo-code is:</p> <pre><code>start_index = 0 end_index = len(l) while l[mid] = (l[start_index]+l[end_index])/2 update start_index and end_index repeat </code><...
<p>You can simply use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.interpolate.html" rel="nofollow noreferrer">pandas.DataFrame.interpolate</a></p> <p>What you want to do is simple linear interpolation between start and end values to fill the NA values. That is the definition of the <code>pd.D...
python|python-3.x|pandas|numpy
3
18,622
70,065,105
How to remove line if doesn't contain letter in python
<p>I want to remove line from string if doesn't contain any letter and pass if contain letter or numbers. I am try to solve this problem by using RegEx in python, but unable to remove line. example</p> <pre><code>string='''हिरासत में ली गई महिला 36 वर्षीय नूर सजात कमरुज़्ज़मा थीं British High Commissioner Gre...
<p>You can use a simple comprehension with a regex to match only the lines with ascii characters:</p> <pre><code>import re out = '\n'.join(s for s in string.split('\n') if re.match(r'^[\x00-\x7F]+$', s)) print(out) </code></pre> <p>output:</p> <pre><code> British High Commissioner Greets A...
python|python-3.x|pandas|string|data-structures
2
18,623
56,212,241
How to load .npy file contents into pandas dataframe?
<p>I have data files in .npy format and I want to load it to pandas dataframe library, in order to further processing.</p> <p>I tried read_csv method of pandas library, which I used in other scripts to load files.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv('Frequency.npy'...
<p>You can try <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.load.html" rel="nofollow noreferrer"><code>numpy.load</code></a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html#pandas-dataframe" rel="nofollow noreferrer"><code>pd.DataFrame</code></a> constructor:</p> ...
python-3.x|pandas
3
18,624
56,422,657
not able to use tf.metrics.recall
<p>I am very new to tensorflow. I am just trying to understand how to use tf.metrics.recall </p> <p>I am doing the following</p> <pre><code>true = tf.zeros([64, 1]) pred = tf.random_uniform([64,1], -1.0,1.0) with tf.Session() as sess: t,p = sess.run([true,pred]) # print(t) # print(p) rec, rec_op = tf....
<p>labels and predictions in your code return tensor outputs, which are numpy array. You can you numpy or your own implementation to calculate recall over them, if you wish. The benefit of using metrics is that you can run everything uniformly in one go with just tensorflow. </p> <pre><code>with tf.Session() as sess: ...
python-3.x|tensorflow|deep-learning
0
18,625
55,812,617
Different result of product of all numbers in a list with Numpy and using a for loop
<p>I have a list of numbers: </p> <pre><code>numbers = [12, 10, 32, 3, 66, 17, 42, 99, 20] </code></pre> <p>I want to print the product of all the numbers in the list (all multiplied together). I did this with Numpy: </p> <pre><code>import numpy print(numpy.product(numbers)) </code></pre> <p>and using a for loop:</...
<p>The correct answer is 1,074,879,590,400. You are getting a different result from <code>numpy</code> because you are supplying it integers and you are getting integer overflow. Python integers, on the other hand, do not overflow. Change your list to </p> <pre><code>numbers = [12., 10., 32., 3., 66., 17., 42., 99., 2...
python|numpy
0
18,626
64,739,756
python trouble using DateOffset
<p>below is my df</p> <pre><code>df = pd.DataFrame({ 'Year': ['03/03/2021', '22/01/2060', '04/03/2021', '22/07/2068'], 'offset' : [1, 9, 8, 1] }) </code></pre> <p>I was a 3rd column which will give me a new date taking into the offset (which is in years). i.e. the new column will ...
<p>You can use <code>.map()</code> on the column and then <code>.dt.strftime</code> to change format:</p> <pre><code>df['ExpiryDate'] = pd.to_datetime(df['Year']) + df['offset'].map(lambda y: pd.offsets.DateOffset(months=y)) df['ExpiryDate'] = df['ExpiryDate'].dt.strftime('%d/%m/%Y') </code></pre> <p>Column output:</p>...
python|pandas|dataframe|datetime
1
18,627
64,699,200
Python: conditional group by in pandas dataframe
<p>How can you perform a conditional group by operation in a dataframe in the sense that you only group those elements fulfilling a certain condition and leave the other elements untouched?</p> <p>Suppose I have the below dataframe:</p> <p><a href="https://i.stack.imgur.com/UcJ0j.png" rel="nofollow noreferrer">initial ...
<p>You can subset the data (by 'Type' here), group the required subset and union them back.</p> <pre><code>import pandas as pd df = pd.DataFrame({'type': [1, 1, 1, 1, 2, 2, 2, 2], 'value': [2, 3, 4, 1, 2, 4, 1, 1]}) df1 = df[df['type']==1] df2 = df[df['type']==2] df2_grouped = df2.groupby('type').mean().reset_index(F...
python|pandas|group-by
0
18,628
40,305,141
Outputs of the distributed version of MNIST model
<p>I am playing with the distributed version of the MNIST on CloudML and I am not sure to understand the logs displayed during the training phase:</p> <pre><code>INFO:root:Train [master/0], step 1693: Loss: 1.176, Accuracy: 0.464 (760.724 sec) 4.2 global steps/s, 4.2 local steps/s INFO:root:Train [master/0], step 1696...
<p>When you're doing distributed training you can have more than 1 worker. Each of these workers can compute an update to the parameters. So each time a worker computes an update that counts as 1 local step. Depending on the type of training, <a href="https://stackoverflow.com/questions/34349316/synchronous-vs-asynchro...
tensorflow|google-cloud-ml
2
18,629
40,045,632
Adding a column in pandas df using a function
<p>I have a Pandas df [see below]. How do I add values from a function to a new column "price"?</p> <pre><code>function: def getquotetoday(symbol): yahoo = Share(symbol) return yahoo.get_prev_close() df: Symbol Bid Ask MSFT 10.25 11.15 AAPL 100.01 102.54 (...) </code></pre...
<p>In general, you can use the apply function. If your function requires only one column, you can use:</p> <pre><code>df['price'] = df['Symbol'].apply(getquotetoday) </code></pre> <p>as @EdChum suggested. If your function requires multiple columns, you can use something like:</p> <pre><code>df['new_column_name'] = d...
python|function|pandas|dataframe|yahoo
75
18,630
39,901,550
Python: UserWarning: This pattern has match groups. To actually get the groups, use str.extract
<p>I have a dataframe and I try to get string, where on of column contain some string Df looks like</p> <pre><code>member_id,event_path,event_time,event_duration 30595,"2016-03-30 12:27:33",yandex.ru/,1 30595,"2016-03-30 12:31:42",yandex.ru/,0 30595,"2016-03-30 12:31:43",yandex.ru/search/?lr=10738&amp;msid=22901.25826...
<p>The alternative way to get rid of the warning is change the regex so that it is a matching group and not a capturing group. That is the <code>(?:)</code> notation.</p> <p>Thus, if the matching group is <code>(url1|url2)</code> it should be replaced by <code>(?:url1|url2)</code>.</p>
python|regex|pandas
46
18,631
69,527,087
how to add data in index column in panda dataframe
<p>I have below dataframe where the first column is without any header. and I need to add 14 days to each value in that column. How can I do it?</p> <pre><code> L122.Y 5121.Y 110.Y 2021-08-30 14:00:00 0.0 0.0 35.778441 2021-08-30 15:00:00 ...
<p>I think first column is called <code>index</code>, test it:</p> <pre><code>print (df.index) </code></pre> <p>If need convert it to <code>DatetimeIndex</code> and add days use:</p> <pre><code>df.index = pd.to_datetime(df.index) + pd.Timedelta('14 days') </code></pre> <p>If already <code>DatetimeIndex</code>:</p> <pre...
python|pandas
1
18,632
69,443,940
Retrieve only the last hidden state from lstm layer in pytorch sequential
<p>I have a pytorch model:</p> <pre><code>model = torch.nn.Sequential( torch.nn.LSTM(40, 256, 3, batch_first=True), torch.nn.Linear(256, 256), torch.nn.ReLU() ) </code></pre> <p>And for the LSTM layer, I want to retrieve only the last hidden state from the batch to pass through the rest of the l...
<p>You could split up your sequential but only doing so in the forward definition of your model on inference. Once defined:</p> <pre><code>model = nn.Sequential(nn.LSTM(40, 256, 3, batch_first=True), nn.Linear(256, 256), nn.ReLU()) </code></pre> <p>You can split it:</p> <pre>...
pytorch|lstm|tensorflow.js|tensorflowjs-converter
1
18,633
69,380,597
Numpy: access values of multidimensional array based on list of indices
<p>Say I have a multi-dimensional array:</p> <pre><code>np.array([[1, 0, 0], [0, 0, 1]]) </code></pre> <p>And I want to extract values given an additional list of indices:</p> <pre><code>np.array([0, 2]) </code></pre> <p>Where the expected output is:</p> <pre><code>[1, 1] </code></pre> <p>What's the best way to approac...
<p>Here,</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; desired_cols = np.array([0, 2]) &gt;&gt;&gt; desired_rows = np.arange(len(desired_cols)) &gt;&gt;&gt; x[desired_rows, desired_cols] array([1, 1]) </code></pre> <p>Your <code>np.array([0, 2])</code> doesn't provide enough information to index into...
python|numpy
0
18,634
40,936,115
How to structure multi row log data in one row data in python?
<p>Following is my data log</p> <pre><code>30/10/2016 17:18:51 [13] 10-Full: L 1490; A 31; F 31; S 31; DL 0; SL 0; DT 5678 30/10/2016 17:18:51 [13] 00-Always: Returning 31 matches 30/10/2016 17:18:51 [13] 30-Normal: Query complete 30/10/2016 17:18:51 [13] 30-Normal: Request completed in 120 ms. 30/10/2016 17:19:12 [15...
<p>with pandas you can do something like:</p> <pre><code>column_headers = ['Date', 'Time', 'Duration', 'IP', 'Request'] df = pd.DataFrame([], columns = column_headers) df.to_csv('out.log', index=None, sep=';') # if you don't want to include a header line, skip the previous lines and start here for df in pd.read_csv('...
python|pandas|data-mining|data-cleaning
1
18,635
54,190,994
How to convert spark rdd to a numpy array?
<p>I have read textFile using spark context, test file is a csv file. Below testRdd is the similar format as my rdd. </p> <pre><code>testRdd = [[1.0,2.0,3.0,4.0,5.0,6.0,7.0], [0.0,0.1,0.3,0.4,0.5,0.6,0.7],[1.1,1.2,1.3,1.4,1.5,1.6,1.7]] </code></pre> <p>I want to convert the the above rdd into a numpy array, So I can ...
<p>You'll have to <code>collect</code> the data to your local machine before calling <code>numpy.array</code>:</p> <pre class="lang-python prettyprint-override"><code>import numpy as np a = np.array(testRdd.collect()) print(a) #array([[ 1. , 2. , 3. , 4. , 5. , 6. , 7. ], # [ 0. , 0.1, 0.3, 0.4, 0.5, ...
python|numpy|apache-spark|pyspark
3
18,636
66,305,533
IndexError: index 1967 is out of bounds for axis 0 with size 1967
<p>By calculating the p-value, I am reducing the number of features in a large sparse file. But I get this error. I have seen similar posts but this code works with non-sparse input. Can you help, please? (I can upload the input file if needed)</p> <pre><code>import statsmodels.formula.api as sm def backwardEliminatio...
<p>Here is a fixed version.</p> <p>I made a number of changes:</p> <ol> <li>Import the correct <code>OLS</code> from statsmodels.api</li> <li>Generate <code>columns</code> in the function</li> <li>Use <code>np.argmax</code> to find the location of the maximum value</li> <li>Use a boolean index to select columns. In pse...
python|numpy|statsmodels|p-value|index-error
0
18,637
52,749,875
Pandas: Take rolling sum of next (1 ... n) rows of a column within a group and create a new column for each sum
<p>I have the following dataframe :</p> <pre><code>a = [1,2,3,4,5,6,7,8] x1 = ['j','j','j','k','k','k','k','k'] df = pd.DataFrame({'a': a,'b':x1}) print(df) a b 1 j 2 j 3 j 4 k 5 k 6 k 7 k 8 k </code></pre> <p>I am trying get the sum the "a" values for next n rows grouped within column "b" and s...
<p>Your example dataframe doesn't match your expected output, so let's go with the latter.</p> <p>I think you can combine a rolling sum with a shift:</p> <pre><code>for x in range(1, 5): c = pd.Series(df.groupby("b")["a"].rolling(x).sum().values, index=df.index) df[f"c{x}"]= c.groupby(df["b"]).shift(-x) </cod...
python|pandas|dataframe|pandas-groupby|cumulative-sum
1
18,638
46,429,033
How do I count the total number of words in a Pandas dataframe cell and add those to a new column?
<p>A common task in sentiment analysis is to obtain the count of words within a Pandas data frame cell and create a new column based on that count. How do I do this?</p>
<p>Assuming that a sentence with n words has n-1 spaces in it, there's another solution:</p> <pre><code>df['new_column'] = df['count_column'].str.count(' ') + 1 </code></pre> <p>This solution is probably faster, because it does not split each string into a list.</p> <p>If <code>count_column</code> contains empty string...
python|pandas|dataframe|count|words
9
18,639
58,415,623
Turn List of Dictionaries or Tuples into DataFrame. Actions - Column, Value - rows
<p>I am doing an API call to Facebook and one of the fields is "actions" which creates a dictionary that I would like to break up in to separate DataFrame columns. I have seen a few similar questions using pd.Series() to map them into separate columns or json.normalize(), but those don't exactly do what I'm looking for...
<p>I edited your API result slightly because I'm not sure what the tag at the beginning is for.</p> <p>The solution is a simple pandas method called from_records(), which converts a list to a dataframe. Here are some reference links:</p> <ul> <li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pan...
python|pandas|facebook|dictionary|series
0
18,640
58,499,114
Calculate a rolling regression in Pandas and store the slope
<p>I have some time series data and I want to calculate a groupwise rolling regression of the last n days in Pandas and store the slope of that regression in a new column.</p> <p>I searched the older questions and they either haven't been answered, or used Pandas OLS which I heard is deprecated.</p> <p>I figured that...
<p>I had some wrong assumptions, first I don't need to loop through the groups, and second I didn't really understand how <code>rolling.apply</code> worked...</p> <p>So here is the (seemingly) working code. I used the linregress function from scipy.stats:</p> <pre><code>import numpy as np import pandas as pd from scipy...
python|pandas|regression
4
18,641
69,115,837
How to concatenate a list of tensors on a specific axis?
<p>I have a list (my_list) of tensors all with the same shape. I want to concatenate them on the channel axis. Helping code</p> <pre><code>for i in my_list: print(i.shape) #[1, 3, 128, 128] =&gt; [batch, channel, width, height] </code></pre> <p>I would like to get a new tensor i.e. new_tensor = [1, 3*len(my_list), ...
<p>Given a example <em>list</em> containing <em>10</em> tensors shaped <code>(1, 3, 128, 128)</code>:</p> <pre><code>&gt;&gt;&gt; my_list = [torch.rand(1, 3, 128, 128) for _ in range(10)] </code></pre> <p>You are looking to concatenate your tensors on <code>axis=1</code> because the 2nd dimension is where the tensor to...
python|pytorch
0
18,642
68,889,783
pytorch indexing for pixel probabilities
<p>Suppose I need to classify each pixel into one of 3 classes. I wish to get the probability of each pixel. Here is a minimal example. Question is, how do I get those probabilities.</p> <pre class="lang-py prettyprint-override"><code>import torch import torch.nn.functional as F y = torch.randint(0, 3, (2, 1, 5, 5)) #...
<p>You are looking for <a href="https://pytorch.org/docs/stable/generated/torch.gather.html?highlight=gather#torch.gather" rel="nofollow noreferrer"><code>torch.gather</code></a>:</p> <pre class="lang-py prettyprint-override"><code>torch.gather(prob,1, y) </code></pre> <p>You <code>gather</code> the probabilities along...
pytorch
1
18,643
68,878,713
Get correct value counts for corresponding x tick label
<p>I am trying to add the counts on top of a bar in Seaborn.</p> <p>I tried it for one figure and it the following code worked.</p> <pre><code>fig, ax = plt.subplots(figsize=(20,10)) countplot_age = sns.countplot(ax=ax,x='Age', data=data4cap) countplot_age.set_xticklabels(countplot_age.get_xticklabels(),rotation=90) ...
<p>This error is caused by the fact that the order of the values to be annotated is different from the order obtained by value_counts(). So we can deal with it by aggregating the frequencies and reordering them by index. For the data, I used Titanic data to create the code.</p> <pre><code>import seaborn as sns import m...
python|pandas|matplotlib|seaborn
0
18,644
60,950,592
Error in Pandas 0.25, but was working in Pandas 0.20
<p>I get this error:</p> <pre><code>Traceback (most recent call last): File "SNOW Report with Plot.py", line 57, in &lt;module&gt; file1['Time in HH:MM:SS'] = file1['Total outage duration'].apply(convert) File "D:\Softwares\Python\lib\site-packages\pandas\core\series.py", line 4038, in apply mapped = lib....
<pre><code>def convert(seconds): hours = seconds // (60*60) seconds %= (60*60) minutes = seconds // 60 seconds %= 60 return "%02i:%02i:%02i" % (hours, minutes, seconds) def convert_to_strdate(create_date): # str = (create_date.split(" ")[0]) # date_object = datetime.strptime(str, '%Y-%m-%d...
python|python-3.x|pandas
0
18,645
60,880,042
From for loop on dict to multiprocessing
<p>I have a dictionary of 4 <code>pandas.DataFrame</code> where I loop over to finally produce ML model. It would be more efficient to parallelize the process and produce the 4 models at the same time.</p> <p>What's the best approach, using <code>multiprocessing</code> or some Dask feature (like multi pd.DataFrame wit...
<p>See the introductory example for custom workloads at <a href="https://examples.dask.org/delayed.html" rel="nofollow noreferrer">https://examples.dask.org/delayed.html</a> for probably the simplest answer. The solution may look like:</p> <pre><code>from dask import delayed, compute out = [delayed(produce_ml_model)(...
python|pandas|python-multithreading|dask
1
18,646
61,010,577
Selecting the Sub-columns In MultiIndex DataFrame Pandas
<p>This is Just in continuation to the <a href="https://stackoverflow.com/questions/61007592/pandas-selecting-the-values-from-multilevel-columns#61007621">Pandas selecting the values from Multilevel columns</a> , where i have multiIndex'd columns and I'm trying to fetch few columns out of it.</p> <h2>DatFrame :</h2> ...
<p>Problem is there is <code>verion</code> and <code>version</code>, so is possible simplify solution for select both:</p> <pre><code>a = [('Applicance Name', 'Unnamed: 0_level_1', 'Unnamed: 0_level_2'), ('Appliance FQDN', 'Unnamed: 1_level_1', 'Unnamed: 1_level_2'), ('Location', 'Unnamed: 2_level_1', 'Unnamed: 2_leve...
python-3.x|pandas
2
18,647
71,455,773
How to create a dataframe with aggregated categories?
<p>I have a pandas dataframe (<strong>df</strong>) with the following fields:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>name</th> <th>category</th> </tr> </thead> <tbody> <tr> <td>01</td> <td>Eddie</td> <td>magician</td> </tr> <tr> <td>01</td> <td>Eddie</td> <td>plumber</t...
<p>You can groupby your <code>id</code> and <code>name</code> columns and apply a function to the <code>category</code> one like this:</p> <pre><code>import pandas as pd data = { 'id': ['01', '01', '02', '03', '03'], 'name': ['Eddie', 'Eddie', 'Martha', 'Jeremy', 'Jeremy'], 'category': ['magician', 'plumber', 'a...
python|pandas|dataframe
1
18,648
71,632,371
Using keys from a dict to look for the same "keys" in a pandas dataframe, then assign value from dict to dataframe empty column
<p>I have a pandas dataframe with zipcodes. I also have a dictionary where keys = zipkode and values = regions</p> <p><strong>The dictionary</strong></p> <pre><code>my_regions = {8361: 'Central region', 8381: 'Central region', 8462: 'North region', 8520: 'South region', 8530: 'Central region', 8541: 'South region'} </c...
<p>You can use <code>.map()</code>:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({&quot;zipcode&quot;: [8462, 8361, 8381, 8660, 8530, 8530]}) my_regions = { 8361: &quot;Central region&quot;, 8381: &quot;Central region&quot;, 8462: &quot;North region&quot;, 8520: &quot;South reg...
python|pandas|dataframe|dictionary|key
1
18,649
71,483,823
pandas: Use truncated filename as header for column in new dataframe from multiple csv files, read specific columns, set date as index
<p>I read multiple questions similar to this one but not specifically addressing this use case.</p> <p>I have multiple ticker.csv files in a folder such as:</p> <p>ZZZ.TO.csv containing:</p> <pre><code> Date Open High Low Close Volume 0 2017-03-14 28.347332 28.347332 27.8710...
<p>You can try:</p> <pre><code>import pandas as pd import pathlib path = pathlib.Path(r'./data2') data = {} for filename in sorted(path.glob('*.csv')): data[filename.stem] = pd.read_csv(filename, index_col='Date', usecols=['Date', 'Close'], ...
python|pandas|dataframe|csv
1
18,650
42,286,645
How do I configure PyCharm to Pandas
<p>I am using a mac OS Sierra 10.12.3 using Pycharm Community Edition 2016.3.2 in PyCharm i am using Python 2.7.11 and tried to run the following </p> <p>import pandas as pd it gives me error saying no modules named pandas</p> <p>so i went to my terminal and typed pip install pandas</p> <p>here is the response</p> ...
<p>open PyCharm, go o preferences and then go to the Project Interpreter section. From there you can click the + button and then click on pandas and then click install packages</p>
pandas|pycharm
1
18,651
69,886,916
Taking the average of of columns for similar rows
<p><a href="https://i.stack.imgur.com/xjSTA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xjSTA.png" alt="enter image description here" /></a></p> <p>What I am trying to do if I have rows with the same prefix,fromMp, toMp then I take the average of each TPCSpeed 1</p> <p>for example I have</p> <pre...
<p>This is a good use for <code>groupby().agg()</code>.</p> <p>At it's simplest, you can try:</p> <pre><code>result.groupbby(['Prefix', 'FromMP', 'ToMP', 'Suffix').agg(np.mean) </code></pre> <p>This will collapse all rows that have the same values in all four named columns, and then replace them with a single row with ...
pandas
2
18,652
69,784,076
Xarray groupby according to multi-indexs
<p>The xarray supplies the groupby function which we can use to calculate the anomaly of the climate data. For example, the anomaly of the monthly weather data can be calculated accroding to <a href="http://xarray.pydata.org/en/stable/examples/weather-data.html" rel="nofollow noreferrer">http://xarray.pydata.org/en/sta...
<p>You can create a grouper array from a pandas MultiIndex:</p> <pre class="lang-py prettyprint-override"><code>In [9]: grouper = xr.DataArray( ...: pd.MultiIndex.from_arrays( ...: [da.date.dt.month.values, da.date.dt.day.values], ...: names=['month', 'day'], ...: ), dims=['date'], c...
python|pandas-groupby|python-xarray
1
18,653
43,333,340
Subtracting double counted values from rows in a DataFrame
<p>I am working with Pandas and have a DataFrame that looks like the following:</p> <pre><code>Module Position Layout Count x a Desktop 50 x a Mobile 20 y a Desktop 100 y a Mobile 30 z b Desktop 80 z b Mobile 20 </c...
<pre><code>d1 = df.set_index(['Module', 'Position', 'Layout']) d2 = d1.unstack().diff(-1, axis=1).stack().combine_first(d1).reset_index() print(d2) Module Position Layout Count 0 x a Desktop 30.0 1 x a Mobile 20.0 2 y a Desktop 70.0 3 y a Mobile 30.0 4...
python|pandas
3
18,654
43,324,974
How to collect samples in multiple csv files
<p>I have files below</p> <p><code>file1.csv,file2.csv....</code></p> <p>I would like to extract samples from each csv file.</p> <p>I tried</p> <p><code>f1=pd.read_csv(file1.csv)</code></p> <p><code>f1.sample(2)</code></p> <p><code>f1.append(f2)</code></p> <p>I tried to loop and append.</p> <p>I guess some solu...
<p>I think you can use:</p> <pre><code>files = glob.glob('files/*.csv') df = pd.concat([pd.read_csv(f).sample(2) for f in files], ignore_index=True) </code></pre>
python|pandas|dataframe
3
18,655
72,224,813
How do I change the values in a pandas column that are selected by a regex?
<p>I'm cleaning up data for a personal project and am standardizing the large number of categories. The seemingly low hanging fruit have similar enough names such as:</p> <blockquote> <p>'SUSPECIOUS CRAFT', 'SUSPECTED MILITANTS', 'SUSPECTED PIRATE','SUSPECTED TERRORISTS', 'SUSPICICIOUS APPROACH', 'SUSPICIOPUS APPROACH'...
<p>You can use a vectorized <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace</code></a> method directly to replace the whole string that starts with the pattern of your choice. Note that it is not efficient to use groups with single...
regex|pandas|dataframe
2
18,656
72,222,258
In Pandas sum columns and change values to proportion of sum
<p>If I have the following DataFrame, how can I convert the value in each row to the proportion of the total of the columns?</p> <p>Input:</p> <pre><code>pd.DataFrame( {'A': {0: 1, 1: 1}, 'B': {0: 1, 1: 2}, 'C': {0: 1, 1: 9},}) </code></pre> <p>Output:</p> <pre><code>pd.DataFrame( {'A': {0: 0.5, 1: 0.5}, 'B': {0: 0....
<p>How about <code>apply</code>?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( {'A': {0: 1, 1: 1}, 'B': {0: 1, 1: 2}, 'C': {0: 1, 1: 9},}) df = df.apply(lambda col: col / sum(col)) print(df) # A B C # 0 0.5 0.333333 0.1 # 1 0.5 0.666667 0.9 </code><...
python|pandas
1
18,657
72,211,476
What is the difference between `pandas.Series.ravel()`, `pandas.Series.to_numpy()`, `pandas.Series.values` and `pandas.Series.array`?
<p>Basically the title sums it up. I have created a dummy <code>pandas.Series</code> object and looked up all these properties and methods. Documentation states that all of them except maybe <code>pandas.array</code> return <code>numpy.ndarray</code> objects. What is the difference then and when should I use one method...
<p>By default, all of these return a view:</p> <pre><code>import pandas as pd s = pd.Series(range(10)) rav = s.ravel() # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) to_num = s.to_numpy() # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) values = s.values # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) array = s.array # &lt;PandasArray&gt...
python|pandas|series
1
18,658
72,154,002
Bezier MxN Surface in matrix form( with Python and numpy)
<p>I am trying to rewrite slow method(&quot;bezier_surf_eval&quot;) for bezier surface with quick one(in matrix form &quot;bezier_surface_M&quot;).</p> <p>Using this formula:</p> <p><img src="https://i.stack.imgur.com/O6aGd.png" alt="Q(u, w) = [U][N][B][Mt][W]" /></p> <p>Were [N] and [M] an bezier basis matrix (4x2 deg...
<p>Looks like i solved it. Problem was in bad order for matrices (in method &quot;bezier_surface_M&quot;) for dot product. Multiplication with per-axis matrices with correct orders do the job.</p> <p>Replaced:</p> <pre><code>u_vec.T.dot(BM_u).dot(cps).dot(BM_v.T).dot(v_vec) </code></pre> <p>With:</p> <pre><code>cps_x =...
python|numpy|bezier|surface
0
18,659
50,356,960
Extracting the detected class name - tensorflow object detection API
<p>My question is a follow up to <a href="https://stackoverflow.com/questions/45674696/tensorflow-object-detection-api-print-objects-found-on-image-to-console">this</a> extremely informative thread. I was to take this a step further and print only the detected class name. </p> <p>As answered in the thread,I am current...
<p>Try this: </p> <pre><code>def GetClassName(data): for cl in data: return cl['name'] #data processed data = [category_index.get(value) for index,value in enumerate(classes[0]) if scores[0,index] &gt; 0.9] print(GetClassName(data)) </code></pre>
python-2.7|tensorflow
1
18,660
50,655,213
Does input_ parameter matter to tf.Print?
<p>I read the description for the parameter <code>input_</code> of <code>tf.Print</code> in <a href="https://www.tensorflow.org/api_docs/python/tf/Print" rel="nofollow noreferrer">this link</a>. I tried a couple of experiments and got the results makes me so confused.</p> <p>I used this following code to experiment</p...
<p>Yes it matters. In your example the value of p will be input_ after the print op is run. </p> <pre><code>A = tf.constant([[1, 2, 3], [4, 5, 6]]) a1, a2 = tf.split(A, 2, axis=0) p = tf.Print(A, [a1, a2]) with tf.Session() as sess: p_val = sess.run([p]) print(p_val) </code></pre> <p>This will illustrate the dif...
python|tensorflow
2
18,661
50,558,911
ValueError: Input 0 is incompatible with layer conv2d_2: expected ndim=4, found ndim=5 in Keras
<p>I am trying to use a function to add layers to a very deep CNN using keras. Here is my function:</p> <pre><code>def add_layer(input_shape, kernel_size, filters, count): x = Conv2D(filters, (kernel_size, kernel_size), padding = 'same', activation= None)(Input(input_shape)) x = BatchNormalization()(x) x ...
<p>Pretty sure that your line,</p> <p><code>x = Conv2D(filters, (kernel_size, kernel_size), padding = 'same', activation= None)(Input(input_shape))</code></p> <p>should be </p> <p><code>x = Conv2D(filters, (kernel_size, kernel_size), padding = 'same', activation= None)(Input(batch_shape=input_shape))</code></p> <p>...
tensorflow|machine-learning|keras|deep-learning|conv-neural-network
0
18,662
45,382,484
If I resize images using Tensorflow Object Detection API, are the bboxes automatically resized too?
<p>Tensorflow's Object Detection API has an option in the <code>.config</code> file to add an <code>keep_aspect_ratio_resizer</code>. If I resize my training data using this, will the corresponding bounding boxes be resized as well? If they don't match up then the network is seeing incorrect examples. </p>
<p>Yes, the boxes will be resized to be compatible with the images as well!</p>
tensorflow
2
18,663
45,497,634
Grouping the data with pandas TimeGrouper with interval between 5 to 25 min, 25 to 45 min, 45 to 05 minutes
<p>I am new to python pandas and I am trying to group my data on 20 Minute interval. If I use <code>Data.groupby([pd.TimeGrouper('20Min'))</code> it is working but it is giving the grouped data from 0 to 20 min, 20-40 etc. But I want to group my data between 5 to 25 min, 25 to 45 min etc.</p> <p>Can you help how to ac...
<pre><code>Data.groupby([pd.TimeGrouper(freq='20Min',base=5, label='right') </code></pre> <p>will give you data grouped by 20 Min, starting with forward 5 min (since we are using <strong>base as 5</strong> and <strong>label as right</strong>. i.e, it will be grouped as 05 to 25, 25 to 45 etc. and if you use this:</p> ...
python|pandas
1
18,664
62,787,684
Understand the role of Flatten in Keras and determine when to use it
<p>I am trying to understand a model developed for time series forecasting. It uses a Con1D layer and two LSTM layers and after that, a dense layer. My question is, should it use <code>Flatten()</code> between the LSTM and the Denser layer? In my mind, the output should just have one value, which has a shape of <code>...
<p>Well, it depends on what you want to achieve. I try to give you some hints, because is not 100% clear for me what you want to obtain.</p> <p>If your LSTM uses <code>return_sequences=True</code>, then you are returning the output of each LSTM cell, i.e., an output for each timestamps. If you then add a dense layer, o...
python|tensorflow|machine-learning|keras
2
18,665
62,781,510
How to create a Frequency Distribution Matrix from a Pandas DataFrame of boolian values
<p>In short, I'm trying to translate a DataFrame like this</p> <pre><code>Patient Cough Headache Dizzy 1 1 0 0 2 1 1 1 3 0 1 0 4 1 0 1 5 0 1 0 </code></pre> <p>into a frequency distribut...
<p>Something like this?</p> <pre><code># extract columns of interest s = df.iloc[:,1:] # output ((s.T @ s)/s.sum()).T </code></pre> <p>Output:</p> <pre><code> Cough Headache Dizzy Cough 1.000000 0.333333 0.666667 Headache 0.333333 1.000000 0.333333 Dizzy 1.000000 0.500000 1.000000 </cod...
python|pandas|frequency-analysis|frequency-distribution
2
18,666
62,742,573
Is it possible to plot a barchart with upper and lower limits of the bins with Pandas,seaborn or Matplotlib
<p>I will like to know how I can go about plotting a barchart with upper and lower limits of the bins represented by the values in the <code>age_classes</code> column of the dataframe shown below with <code>pandas</code>, <code>seaborn</code> or <code>matplotlib</code>. A sample of the dataframe looks like this:</p> <p...
<p>If you want a chart like this:</p> <p><a href="https://i.stack.imgur.com/YzdtP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YzdtP.png" alt="enter image description here" /></a></p> <p>then you can make it with <code>sns.barplot</code> setting <code>age_classes</code> as <code>x</code> and one c...
python|pandas|matplotlib|seaborn
0
18,667
54,379,747
How do I check if np.array exist inside another np.array?
<p>I need to find if the np.array exists in another np.array. I have a np.array that is <code>doubles = [[ 0 3][ 0 11][ 1 1][ 1 13][ 2 2][ 2 6][ 2 8][ 2 12][ 3 0][ 3 3][ 3 7][ 3 11][ 3 14][ 4 4][ 4 10][ 6 2][ 6 6][ 6 8][ 6 12][ 7 3][ 7 7][ 7 11][ 8 2][ 8 6][ 8 8][ 8 12][10 4][10 10][11 0][11 3][11 ...
<p>simply use <code>.tolist()</code>,</p> <pre><code>if result in doubles.tolist(): print ("exists") </code></pre>
python|arrays|numpy
4
18,668
54,503,421
Faster 3D Matrix Operation - Python
<p>I am working with 3D matrix in Python, for example, given matrix like this with size of 2x3x4:</p> <pre><code>[[[1 2 1 4] [3 2 1 1] [4 3 1 4]] [[2 1 3 3] [1 4 2 1] [3 2 3 3]]] </code></pre> <p>I have task to find the value of entropy in each row in each dimension matrix. For example, in row 1 of dimensio...
<p>Using the definition of <code>entropy</code> for the second part and broadcasted operation on the first part, one vectorized solution would be -</p> <pre><code>p1 = matrix/matrix.sum(-1,keepdims=True).astype(float) entropy_matrix_out = -np.sum(p1 * np.log(p1), axis=-1) </code></pre> <p>Alternatively, we can use <c...
python|numpy|matrix|vector|scipy
1
18,669
54,459,557
how to remove the start of a link and add a forward slash in python
<p>I have some weblinks that I have scraped off a website, the problem is the links are not totally correct, as in they don't automatically download the data unless I make <strong>two</strong> changes:</p> <p><strong>1)</strong> I get rid of the <code>VM300:1</code> at the start</p> <p><strong>2)</strong> I put a <co...
<p>Use list comprehension with <code>split</code> and <code>replace</code>:</p> <pre><code>urls = [x.split()[1].replace('.au__', '.au/__') for x in urls] </code></pre> <p>Another idea with double <code>replace</code>:</p> <pre><code>urls = [x.replace('VM300:1 ','').replace('.au__', '.au/__') for x in urls] </code></...
python|pandas|numpy|urllib
4
18,670
73,827,275
Insert a 2d array into another 2d array at multiple positions
<p>I have an array like this, although much larger:</p> <pre><code>X = np.array([ [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], ]); </code></pre> <p>and I want to insert a 2d array every k positions. For example:</p> <pre><code>dim = 2 to_insert = np.zeros((dim, X.shape[1])) </code></pre> <p>I'm using ...
<p>Using a different example for clarity:</p> <pre><code># X array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) # to_insert array([[ -1, -2, -3, -4, -5], [ -6, -7, -8, -9, -10]]) </code></pre> <p>You can <code>tile</code> a destination array and use indexing to &quot;...
arrays|numpy
1
18,671
73,681,725
RuntimeError: The size of tensor a (38) must match the size of tensor b (34) at non-singleton dimension 3
<p>I studied Resnet 50 using cifar-10</p> <p>but, I faced RuntimeError.</p> <p>Here is code</p> <pre><code>class BasicBlock(nn.Module): def __init__(self, in_planes, planes, stride = 1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size = 1, stride = stride, p...
<p>You don't want padding in your <code>self.conv1</code> nor <code>self.conv3</code>, because you'll be increasing your image size by 2 (1 each size) each time. Padding should only be used to avoid <em>reducing</em> your image size when using a kernel size of above 1.</p>
python|pytorch|resnet
0
18,672
71,419,574
How to solve Axes3D error when plotting a function?
<p>I have a code to graph mi function f(x,y)=(x^4 + y^4). I already imported all the necessary libraries, but when i run it, the &quot;MatplotlibDeprecationWarning: Axes3D(fig) adding itself to the figure is deprecated since 3.4. Pass the keyword argument auto_add_to_figure=False and use fig.add_axes(ax) to suppress th...
<p>On my environment it actually works. Anyway you can obtain the same plot using the &quot;3d&quot; projection of pyplot:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt figura = plt.figure(figsize=(7,7)) ejes = plt.subplot(111, projection=&quot;3d&quot;) def f(x,y): return ((x**4)+(y**4)) ...
python|function|numpy|math
0
18,673
71,143,248
How do I apply conditional statements to multiple columns on Pandas Dataframe using iloc?
<p>Assuming I have a dataframe like this:</p> <pre><code># importing pandas and numpy import pandas as pd import numpy as np # create a sample dataframe data = pd.DataFrame({ 'A' : [ 1, 2, 3, -1, -2, 3], 'B' : [ -1, -2, -3, 12, -12, -3], 'C' : [ 1, -2, 3, -1, -2, 13], 'D' : [ -1, 2, 3, -1, 2, -3], ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.clip.html" rel="nofollow noreferrer"><code>DataFrame.clip</code></a> with <code>lower</code>:</p> <pre><code>df = data.clip(lower=0) print (df) A B C D E 0 1 0 1 0 1 1 2 0 0 2 12 2 3 0 3 3 3 3 0 ...
python|pandas|database|dataframe|inequalities
2
18,674
52,258,617
Mismatch in Python numpy.testing
<p>Is there any chance for storing the value os mismatch in one variable?</p> <pre><code>np.testing.assert_array_almost_equal(x,y,decimal=2) </code></pre> <p>As you see the ouput of the function is a boolean and an assertion error. The mismatch value appears within the message </p> <pre><code>AssertionError: Array...
<p>You can do: </p> <pre><code> try: np.testing.assert_array_almost_equal(x,y,decimal=2) except AssertionError as e: mismatch = e.args[0].split('\n')[3].split(' ')[1][:-2] </code></pre> <p>then mismatch will contain an str with the value you are looking for. In your example: </p...
python|numpy
0
18,675
60,400,837
How to convert the outcome from np.mean to csv?
<p>so I wrote a script to get the average grey value of each image in a folder. when I execute print(np.mean(img) I get all the values on the terminal. But i don't know how to get the values to a csv data.</p> <pre><code>import glob import cv2 import numpy as np import csv import pandas as pd files = glob.glob("/med...
<p>Is this what you're looking for?</p> <pre><code>files = glob.glob("/media/rene/Windows8_OS/PROMON/Recorded Sequences/6gParticles/650rpm/*.png") mean_lst = [] for file in files: img = cv2.imread(file) mean_lst.append(np.mean(img)) pd.DataFrame({"mean": mean_lst}).to_csv("path/to/file.csv", index=False) </co...
pandas|csv|image-processing
0
18,676
60,571,429
Need help comparing datetime objects derived from a dateframe in a conditional statement
<p>I have a csv file that contains the names of personnel and the times when they swipe their badges at work. I am trying to write a program that will evaluate the dateframe and pull the first time they swiped their badges and see if that time was more than 1 hour ago. The csv file looks like this.</p> <pre><code>,E...
<p>From your code, <code>check_time</code> is <code>datetime</code>: 1 hour prior to the current time</p> <pre><code>check_time = (datetime.today() - timedelta(hours=1)) </code></pre> <p>On the other hand, <code>in_time</code> is <code>timedelta</code>: time duration between the current time and the last swipe</p> <...
python|pandas
1
18,677
60,447,766
Which Visualization plot should i use?
<p>I have data like below and i want to create plot like added picture. I want to visulise this data like sample plot. I searched seaborn and matplotlib libraries but i can't find something like i want.</p> <p>Also in the sample plot, the intersection point is 0. But i need to change this point. For example the inters...
<p>Here is a simple implementation using matplotlib:</p> <pre><code>cost=[50,40,30,20,10] service=[60,30,25,10,20] fig, (ax) = plt.subplots() ax.spines['left'].set_position(('data', 25)) ax.spines['bottom'].set_position(('data', 30)) # Eliminate upper and right axes ax.spines['right'].set_color('none') ax.spines['top...
pandas|numpy|matplotlib|data-visualization|seaborn
4
18,678
60,588,197
pandas retain styling when reformatting cells - without reparsing string to numbers
<p>For a pandas data frame of:</p> <p><a href="https://i.stack.imgur.com/GNDJc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GNDJc.png" alt="enter image description here"></a></p> <p>I want to reformat it to:</p> <p><a href="https://i.stack.imgur.com/Dc6ap.png" rel="nofollow noreferrer"><img src...
<p>I found solution, idea is return <code>DataFrame of styles</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.apply.html" rel="nofollow noreferrer"><code>Styler.apply</code></a> for another modified <code>DataFrame</code>:</p> <pre><code>#removed st...
python|pandas|styling
1
18,679
60,566,498
CNN how to optimize hyperparameters to prevent overfitting
<p>I am currently developing a CNN for multiclassification (3 classes) using Tensorflow Keras. I had used sklearn to split my data to 9:1 train/validation (1899 training data, 212 validation data). </p> <p><a href="https://i.stack.imgur.com/cU2G2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cU2G2...
<p>To reduce overfitting you can try to <strong>increase</strong> the amount of Input Data then <strong>augment</strong> it (flip, rotate, scale, and etc.) this can improve generalization ability.</p> <p>As for the model, some ideas you can try are to increase the <strong>number of layers</strong>, increase the <stron...
python|tensorflow|keras|deep-learning
0
18,680
60,602,951
Pandas 1.0 create column of months from year and date
<p>I have a dataframe <code>df</code> with values as:</p> <pre><code>df.iloc[1:4, 7:9] Year Month 38 2020 4 65 2021 4 92 2022 4 </code></pre> <p>I am trying to create a new <code>MonthIdx</code> column as:</p> <pre><code>df['MonthIdx'] = pd.to_timedelta(df['Year'], unit='Y') + pd.to_timedelta(...
<p>So you can pad the month value in a series, and then reformat to get a datetime for all of the values:</p> <pre><code>month = df.Month.astype(str).str.pad(width=2, side='left', fillchar='0') df['MonthIdx'] = pd.to_datetime(pd.Series([int('%d%s' % (x,y)) for x,y in zip(df['Year'],month)]),format='%Y%m') </code></pre...
python-3.8|pandas-1.0
0
18,681
72,653,748
use pandas col to store % of values in dict format
<p>I have a dataframe like as below</p> <pre><code>name,id,AL A,1,22 A,2,22 B,5,21 B,5,23 B,4,24 C,6,21 </code></pre> <p>I would like to do the below</p> <p>a) Groupby <code>name</code></p> <p>b) get the unique count (nunique) of <code>id</code> and <code>PL</code> for each <code>name</code></p> <p>With the help of thi...
<p>You can do <code>groupby</code> with <code>value_counts</code> then convert to <code>dict</code></p> <pre><code>out = pd.concat([df.groupby('name')[x].value_counts(normalize=True).round(2).reset_index(level=0).groupby('name').agg(dict) for x in ['id','AL']],axis=1).add_suffix('_list').reset_index() Out[716]: name...
python|pandas|list|dataframe|pandas-groupby
1
18,682
72,699,430
Delete rows based on calculated number
<p>I have a dataframe that defines list of call (call)[List]. each call has an answer status (call)[Status]. I created a column to have a unique field (call)[Key]</p> <p>Call DataFrame which appears as following:</p> <pre><code>a = {'List':['List1','List1','List1','List1','List2','List3','List3','List1','List2','List2...
<p>EDIT:</p> <p>First repeat rows by number of deleted rows by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.repeat.html" rel="nofollow noreferrer"><code>Index.repeat</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofol...
python|pandas
2
18,683
72,801,906
Model training with tf.data.Dataset and NumPy arrays yields different results
<p>I use the Keras model training API and observed differences when training the model with NumPy arrays (<code>x_train</code> and <code>y_train</code>) and with <code>tf.data.Dataset.from_tensor_slices((x_train, y_train))</code>. A minimal working example is shown below:</p> <pre><code>import numpy as np import tensor...
<p>The behavior is due to the default parameter <code>shuffle=True</code> in <code>model.fit(*)</code> and not a bug. According to the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit" rel="nofollow noreferrer">docs</a> regarding <code>shuffle</code>:</p> <blockquote> <p>Boolean (whether to shuffl...
python|tensorflow|machine-learning|keras
1
18,684
59,682,464
Why does 0th layer mean for reduce_mean give wrong averages?
<p>I have 3rd layer array here</p> <pre><code>t = tf.constant([[[1., 1., 1.], [2., 2., 2.]], [[3., 3., 3.], [4., 4., 4.]]]) tf.reduce_mean(t,0) </code></pre> <p>I thought the 0th layer mean would be 1.5 and 3.5. However, it is giving me 2 and 3. Can someone help to explain what's happening here? </p> <pre><code>&lt;...
<p>Here's a depiction of how <code>tf.reduce_mean</code> works on <code>axis=0</code>.</p> <p><a href="https://i.stack.imgur.com/b2fyW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b2fyW.jpg" alt="enter image description here"></a></p> <p>You have a <code>(2,2,3)</code> array. <code>tf.reduce_mea...
arrays|tensorflow|layer|tensor
0
18,685
61,764,512
What does *variable.shape mean in python
<p>I know <code>"*variable_name"</code> assists in packing and unpacking.</p> <p>But how does <em>variable_name.shape work? Unable to visualize why the second dimension is squeezed out when prefixing with "</em>"?</p> <pre><code>print("top_class.shape {}".format(top_class.shape)) top_class.shape torch.Size([64, 1]) ...
<p>for <code>numpy.array</code> that is extensively used in math-related and image processing programs, <code>.shape</code> describes the size of the array for all existing dimensions:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.zeros((3,3,3)) &gt;&gt;&gt; a array([[[ 0., 0., 0.], [ 0....
python|pytorch
1
18,686
61,895,517
Replace outliers in a mixed dataframe with pandas
<p>I have a mixed dataframe with both str, int and float types. I have some outliers in the floats columns and tried to replace them to NaN using</p> <pre><code>df.mask(df.sub(df.mean()).div(df.std()).abs().gt(2)) </code></pre> <p>I've also tried with numpy's </p> <pre><code>v = df.values mask = np.abs((v - v.mean(0...
<p>You could try something like this (this is to change the "cases" column): </p> <pre><code>df.loc[abs(df.cases - df.cases.mean())/df.cases.std() &gt; 1, "cases"] = None </code></pre> <p>However, note that here I have used a Z value of 1 for the "Cases" column, since the largest Z value is 1.63 (instance with index ...
python|pandas|numpy|dataframe|outliers
1
18,687
61,941,827
SKLearn Ordinal Encoder with Pandas Dataframe - Accessing Columns with a variable
<p>I'm trying to implement a categorical naive bayes classifier for some data I have in a dataframe. My dataframe has 173 rows and 38 columns. The columns represent categorical characteristics such as degree (ex. Mechanical Engineering) and type (ex. Master of Science). There are many other columns and the number/va...
<p>Ugh, please excuse my raging stupidity. I guess there is part of me that likes to over-complicate things. Easy solution was simply:</p> <pre><code> dfOE = enc.fit_transform(dataframe.astype(str)) </code></pre> <p>-Gary</p>
python|pandas|scikit-learn|naivebayes
2
18,688
61,724,382
Pandas Dataframe How to extract rows of data before a specific row?
<p>I have a dataframe like,</p> <pre><code>A,B,C 1,2,'Balder' 3,4,'Vasquez' 5,6,'Hatala' 7,8,'Perron' </code></pre> <p>but the dataframe can also be something like,</p> <pre><code>A,B,C 1,2,'Balder' 3,4,'Vasquez' 7,8,'Perron' </code></pre> <p>I want to extract everything before the row,</p> <pre><code>7,8,'Perron'...
<p>Assuming your index are integer numbers, first find the index of the row that contains your data, then use <code>loc</code> to get all rows before that one.</p> <pre class="lang-py prettyprint-override"><code>idx = df[(df.A == 7) &amp; (df.B == 8) &amp; (df.C == 'Perron')].iloc[0].name subset = df.loc[:idx-1] sub...
python|pandas
3
18,689
57,893,415
PyTorch: Dataloader for time series task
<p>I have a Pandas dataframe with <code>n</code> rows and <code>k</code> columns loaded into memory. I would like to get batches for a forecasting task where the first training example of a batch should have shape <code>(q, k)</code> with <code>q</code> referring to the number of rows from the original dataframe (e.g. ...
<p>I ended up writing custom dataset as well, though it's a bit different from the answer above:</p> <pre><code>class TimeseriesDataset(torch.utils.data.Dataset): def __init__(self, X, y, seq_len=1): self.X = X self.y = y self.seq_len = seq_len def __len__(self): return self....
python|pandas|pytorch|torch
12
18,690
54,858,464
Looping through columns using number in column name
<p>I have the following columns in my pandas dataframe - client_1_name, client_2_name, clinet_3_name... all the way to client_10_name.</p> <p>I want to loop through the columns names using the number in the column name to identify whether the specific column contains a substring - "Nike".</p> <p>How I would ideally a...
<p>Consider this Dataframe,</p> <pre><code>df = pd.DataFrame(data = np.random.choice(list('ABCDEFGH')+['Nike'], 100).reshape(10,10), columns = ['Client_'+str(i)+'_name' for i in range(1,11)]) </code></pre> <p>You can check if the column contains Nike using</p> <pre><code>df.eq('Nike').any() Client_1_name True ...
python|regex|string|pandas
0
18,691
55,061,149
Importing the multiarray Numpy extension module failed Visual Studio 2019 Anaconda 1.9.6 Python 3.7.1
<p>I have a fresh install of Anaconda (1.9.6) and elected to install Visual Studio 2019 as part of this process. The code below executes without error in the Spyder IDE bundled with Anaconda, but in Visual Studio it returns the following error:</p> <p><em>"Importing the multiarray numpy extension module failed. Most ...
<p>I have the same problem. I haven't solved it properly, but if I instead create a virtual environment with python 3.6 it works fine..(I would have added this as a comment, but I'm unable to!)</p>
python|numpy|matplotlib|anaconda
0
18,692
49,560,443
tensorflow eager gradients_function() returns error "t is not in list"
<p>I am using Tensorflow in Eager mode to calculate the derivatives of the softmax manually. The design of the code was easy based on <a href="https://www.tensorflow.org/versions/r1.5/api_docs/python/tf/contrib/eager/gradients_function" rel="nofollow noreferrer" title="docu">the documentation provided by tensorflow</a>...
<p>There are two things going on with your sample:</p> <ol> <li><p>As per the documentation of <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/eager/gradients_function" rel="nofollow noreferrer">gradients_function</a>, <code>params</code> is supposed to be a sequence of parameter indices or names. In th...
python|tensorflow
1
18,693
73,402,383
Changing values of a 3D array based on 2D coordinates (Python)
<p>I have 2 arrays. Call them 'A' and 'B'. The shape of array 'A' is (10,10,3), and the shape of array 'B' is (10,10).</p> <p>Now, I have acquired the coordinates of certain elements of array 'B' as a list of tuples. Let's call the list 'TupleList'. I want to now make the values of all elements in array 'A' equal to 0,...
<p>Here is a solution by <a href="https://stackoverflow.com/a/19888067/13636407">transposing</a> the indices list into list of indices for the first dimension and list of indices for the second dimension:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np nrows, ncols = 5, 5 arr = np.arange(nrows ...
python|arrays|numpy|multidimensional-array
1
18,694
73,179,438
Assertion failed error in Tensorflow linear regression model
<pre><code># IMPORTS import os import numpy as np import tensorflow as tf import pandas as pd # IMPORT CSV FILES AS PANDASDB dfTrain = pd.read_csv('carPriceTrain.csv') dfEval = pd.read_csv('carPriceEval.csv') # RENAME COLUMN NAMES dfTrain = dfTrain.rename(columns={&quot;Gear box type&quot;: &quot;gearBoxType&quot;}) ...
<p>I think the problem is at this line:</p> <pre><code>linearEst = tf.estimator.LinearClassifier(feature_columns=featureColumns) </code></pre> <p>You should set the argument <code>n_classes</code> according to the Tensorflow documentation of the <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/LinearCla...
python|pandas|tensorflow|machine-learning
0
18,695
67,528,872
Stacking columns
<p>I have a df that looks like</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">L.1</th> <th style="text-align: center;">L.2</th> <th style="text-align: center;">G.1</th> <th style="text-align: right;">G.2</th> </tr> </thead> <tbody> <tr> <td style="text-align: left...
<p>You can make each column to list and concatenate them and create a new dataframe based on the new list:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'L.1': [1, 2, 3, 4], 'L.2': [5, 6, 7, 8], 'G.1':[9, 10, 11, 12], 'G.2': [13, 14, 15, 16]}) new_df = pd.DataFrame({'L':df...
python|pandas|dataframe
1
18,696
67,246,289
Writing TXT file from pandas DataFrame for position-based columns
<p>I need to write a position based text file from a Dataframe with varying column widths.Say my DF is</p> <pre class="lang-py prettyprint-override"><code>data=np.array([[9,df_transformed.shape[0],dfsum['Col2'],ff]]) hdrftr_conv=pd.DataFrame(data,columns=['RcdType','RcdCount','DRSum','FillerCol']) </code></pre> <pre cl...
<p>The short answer is <strong>np.savetxt</strong> with formatting &amp; other options.</p>
pandas|dataframe
0
18,697
67,511,773
Combining two dataframes based on two columns values in pandas
<p>I have a dafarame like this:</p> <p>df1:</p> <pre><code> col1 col2 data1 data2 data3 0 A A_1 2 4 5 1 A A_2 11 58 87 2 A A_3 14 24 54 3 B B_1 3 6 9 4 B B_2 ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html" rel="nofollow noreferrer"><code>pandas.merge</code></a> The <code>on</code> argument defines what column you want to merge the dataframes on and the <code>how</code> keyword defines what type of merge you want. Please look at ...
python|python-3.x|pandas|dataframe|merge
1
18,698
60,157,238
Pvlib: Problem with DatetimeIndex of ModelChain
<p>I am struggling with forwarding the time series to the ModelChain.</p> <p>The Code looks like that:</p> <hr> <pre><code>import pandas as pd import pvlib from pvlib.pvsystem import PVSystem from pvlib.location import Location from pvlib.modelchain import ModelChain from pvlib.temperature import TEMPERATURE_MODEL_P...
<p>Your code looks to be overly complicated. Why recreate the 'df' dataframe as 'weather' instead of renaming the columns? The brackets here 'index=[pd.DatetimeIndex(Timeseries, tz='Europe/Vienna')]' are not needed but I can't tell if that would resolve the issue.</p>
pandas|python-datetime|pvlib
0
18,699
59,986,056
Only keep column values if they equal a certain value or if they are in a row between this value (pandas)
<p>I want to filter out rows that do not equal a certain number OR do not have that number in the row before and/or after.</p> <p>For explanation an example. I have the following dataframe:</p> <pre><code>df_test= pd.DataFrame() df_test= df_test.assign(group='') df_test.group= [3,3,5,3,1,3,4,1,1,1,5,3,1,1,3,6,7] ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>Series.eq</code></a> for compare by <code>==</code> and chain by <code>&amp;</code> shifted Series with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift....
python|pandas
4