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
354,800
67,065,323
Rotation of 90, 180 and 270 using python and tensorflow
<p>I want to randomly rotate my images in 90, 180, and 270 degrees, that is, by multiples of 90 degrees.</p> <p>Currently, I am using the <code>ImageDatagenerator</code> to augment my data:</p> <pre><code>train_dataGen = ImageDataGenerator(rescale=None,horizontal_flip=True,rotation_range=90, ...
<pre><code>def rotate_image(image): return np.rot90(image, np.random.choice([-1, 0, 1])) train_dataGen = ImageDataGenerator( preprocessing_function=rotate_image) </code></pre> <p>This function will rotate by either -90, 0, or 90 degrees.</p>
python|tensorflow
6
354,801
67,041,984
Change last word after space in a dafaframe column
<p>I am working on a data frame that contains computer names and I am trying to anonymize the computer names. Here is an example of the dataframe, I am working with</p> <pre><code>df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'computer_name': [u'LENOVO 09 X32H0GB', u'LENOVO vmhsbpmh613.xyz.biz', u'Dell Inc. PowerEdge R910 ...
<h3><a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace</code></a></h3> <pre><code>df['computer_name'].str.replace(r'\S{3}(\S+?)(?:\.\S+|$)', r'xxx\1') </code></pre> <hr /> <pre><code>0 LENOVO 09 xxxH0GB 1 ...
python|pandas|python-re
4
354,802
67,043,612
How to Match multiple columns with given single column and get its name in new column?
<p>I want to match certain criteria across multiple columns . If Criteria matches return the column name:</p> <p>my demo df is :</p> <pre><code>df = pd.DataFrame({&quot;mtc&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;], &quot;C1&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;A&qu...
<h3>Solution</h3> <pre><code>m = df.filter(like='C').eq(df['mtc'], axis=0) df['Result'] = m.idxmax(1).mask(~m.any(1)) </code></pre> <h3>Explanations</h3> <p>Filter the <code>C</code> like columns then compare theses columns with the <code>mtc</code> column along <code>axis=0</code> to create a boolean mask.</p> <pre><c...
python|pandas
3
354,803
66,764,392
Unexpected mask shape in TensorFlow 2 Keras
<p>I have batch tensors of the shape <code>(batch_size, n_time_steps, n_features, n_channels)</code>. They arise from tensors of the shape <code>(n_time_steps, n_features, n_channels)</code>, where <code>n_time_steps</code> is <em>not constant</em>. When constructing the batches, the tensors are padded to the maximum v...
<p>In the implementation of <code>tensorflow.keras.layers.Masking</code>, only the last axis is requested to have all values equal to the <code>mask_value</code> in order to produce an entry <code>False</code> in the mask. Accordingly, the tensor rank of the mask becomes the tensor rank of the input tensor minus 1 (and...
tensorflow|keras|mask
2
354,804
67,106,396
Create a categorical variable for time containing categories
<p>I have a time column but I want to create a column 'Part of the Day' Creating a categorical variable for time containing the categories Midnight : (23:00 - 02:00) Early Morning : (03:00 - 06:00) Morning : (07:00 - 10:00) Noon : (11:00 - 14:00) Evening : (15:00 - 18:00) Night : (19:00 - 22:00)</p>
<p>Here is a way :</p> <p>Let's say that you have a pandas DataFrame containing a column date : <code>df.date</code>. I'm not sure what's the format of your column but you should transform it to a numeric format.</p> <p>Let's say that you have the same format as you mentioned <code>19:00</code>, then you can transform ...
python|python-3.x|pandas|analysis
0
354,805
67,063,918
Get indices from one randomly chosen true element in a boolean array
<p>I have a boolean array from which I would like the indices of one randomly chosen element that equals True. The output should be a tuple with the (x,y,z) indices of that element.</p> <p>Is there a more elegant and/or efficient way to do this instead of doing the following?</p> <pre><code>import numpy as np rng = np....
<p>Use <code>np.argwhere</code> instead of <code>np.where</code>:</p> <pre><code>true_idx = np.argwhere(m) random_idx = rng.randint(len(true_idx),size=1) random_index = true_idx[random_idx] # array([[0, 1, 2]]) </code></pre>
python|numpy|random
1
354,806
67,172,409
Is there a way to color individual elements in a list in Python?
<p>I would like to color elements in a <code>numpy.ndarray</code>, specifically ones which are of <code>numpy.int64</code> type.</p> <p>For example, how do I color each <code>1</code> in the following list, say, red?</p> <pre><code> L = [1,0,1,0,1] </code></pre> <p>I have tried using colorama. Here is my code. The r...
<p>Lists don't have a concept of color. Colorama characters understood by your computer to represent values in different color. If you want to make your list print with certain colors you need to print each item in the list.</p> <p>Let's say you want to make the 1's red:</p> <pre class="lang-py prettyprint-override"><c...
python|numpy-ndarray|colorama
2
354,807
67,114,477
Merger/join two tables, missing information from second tables
<p>The df1 I have</p> <pre><code>OBJECTID County State WeightedAverage 0 1 Allegan MI 33.088148 1 2 Arenac MI 15.000000 2 3 Branch MI 43.000000 3 4 Calhoun MI 12.931455 4 5 Charlevoix MI 7.679045 </code></pre> <p>The df2 I have</p> <pre><code> County ConfirmedCases ConfirmedDeaths...
<p>I believe that there might be blank spaces in County column. Try removing them <code>merged = pd.merge(df1, df2, on='County', how='left')</code> and then <code>merged.County = merged.County.apply(lambda cty: cty.strip())</code></p>
python|pandas|dataframe
1
354,808
66,824,304
Is it possible to alter the structure of DataFrame A to look like that of DataFrame B?
<p><a href="https://i.stack.imgur.com/7LCCe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7LCCe.png" alt="DATA FRAME A" /></a></p> <p><a href="https://i.stack.imgur.com/T4Mxa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T4Mxa.png" alt="DATA FRAME B" /></a></p> <p>I've tried us...
<p>It looks like you're trying to swap the column levels (<code>Symbols</code>/<code>Adjusted</code>), so you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.swaplevel.html" rel="nofollow noreferrer"><strong><code>swaplevel</code></strong></a> and <a href="https://pandas.pydata.org/docs/r...
python|pandas|dataframe
0
354,809
66,977,105
Merge two dataframe if col values are in within a group
<p>I would need help in order to merge two dataframe but only when some values are shared between them.</p> <p>So for instance I have 2 dataframes :</p> <p><strong>df1</strong></p> <pre><code>Values1 Values2 COL3 Canis_lupus:E YP_0E9E98E 12 Canis_lupus:o YP_0E9E98E 89 Canis_lupus:E YP_555555...
<p>Do an inner join. Code below:</p> <pre><code>df=pd.merge(df1, df2, how='inner', left_on='Values1', right_on='Values').drop_duplicates(subset='Values1') </code></pre>
python-3.x|pandas
3
354,810
66,788,463
How to move specific data from one column to a new column on Pandas?
<p>I have a set of data with 2 columns: Column1 = Hex Code and Column2= Current (A).</p> <p>The data in Column1 is Hex Code, 27 different codes which repeats and for each Hex Code have Current (A) value on Column2.</p> <p>I want to pick a set of 27 data points from Column1 &amp; Column2 and place them into Coulmn3 &amp...
<p>I am going tho show you my code. But I want to tell that you can not have repeating columns names. We suppose data is the name of your original dataset:</p> <pre><code>import pandas as pd col_name1=data.columns.values[0] col_name2=data.columns.values[1] two_columns = data[[col_name1,col_name2]][0:27].values two_c...
python|excel|pandas|dataframe
0
354,811
66,858,969
Difference between images of different sizes
<p>My problem is as follows. I have an image <code>img0</code> (array shape <code>(A,B,3)</code>) and then a face <code>img1</code> cut out from the middle of that image (by an algorithm I don't have access to: my input is only the whole image, and the face cut out from it), now an array shaped <code>(C,D,3)</code> whe...
<blockquote> <p>Or, failing that, if we can find the starting coordinate of the rectangular ?portion of an image (img0) which corresponds to a rectangular cutout available to us (img1)?</p> </blockquote> <p>One easy way to do that would be to cross-correlate your zero-mean cut-out with the zero-mean original image. As ...
python|image|numpy|opencv|image-processing
1
354,812
67,068,323
Why are my video files getting bigger after converting to np.array?
<p>I have video files around 700x200, and I'm using cv2 to perform preprocessing. The actual videos are .mp4 format and range from a couple mb depending on the length, but after scaling down the resolution, making the color videos grey, somehow my filesize almost 10x when I try to either save via <code>Pickle</code> or...
<p>A compressed video stream is decompressed by OpenCV and is saved as raw data. To reduce the size you need to encode the video stream. For example:</p> <pre><code>def opencv_replay(video_file: str, video_file_out: str): import cv2 video_in = cv2.VideoCapture(video_file) video_out = cv2.VideoWriter() ...
python|numpy|pickle
1
354,813
67,004,127
Why does python call builtins.compile when importing numpy?
<p>I ran this code with python 3.7 to see what happens when I call <code>import numpy</code>.</p> <pre><code>import cProfile, pstats profiler = cProfile.Profile() profiler.enable() import numpy profiler.disable() # Get and print table of stats stats = pstats.Stats(profiler).sort_stats('time') stats.print_stats() </c...
<p>User L3viathan pointed out in a comment that the code for <code>numpy</code> contains explicit calls to <code>compile</code>. This explains why <code>builtins.compile</code> is getting called. Thanks!</p>
python|numpy
0
354,814
66,979,939
pandas to_csv will lose information between NaN and None
<p>I want to do turn a pandas dataframe into CSV. If I just use <code>to_csv</code>, I get:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame.from_dict({&quot;a&quot;: [1,2,3], 2: [2,3,float(&quot;NaN&quot;)], 3: [&quot;a&quot;, None, &quot;b&quot;]}) &gt;&gt;&gt; df a 2 3 0 1 2...
<p>If need convert <code>None</code> to empty strings is possible this trick - convert values to strings and compare by <code>None</code>s:</p> <pre><code>df = df.mask(df.astype(str).eq('None') &amp; df.isna(), '') print (df.to_csv(index=False, na_rep=&quot;NaN&quot;)) a,2,3 1,2.0,a 2,3.0, 3,NaN,b </code></pre>
python|pandas|dataframe|csv
3
354,815
67,153,554
How to change the title size of a plot in pandas (matplotlib)?
<p>I read the documentation and even the github link to the source code and I don't see a kwarg to pass in for title size, only for the x and y axis labels. The code below increase size of everything in the figure besides the title. How do people usually increase the title size as well? Thanks!</p> <pre><code>import pa...
<p>You can save the axes handle and then call <code>.title.set_size()</code>:</p> <pre class="lang-py prettyprint-override"><code>ax = a_dataframe.plot(title='Some Title', figsize=(50,25), fontsize=40) ax.title.set_size(40) </code></pre> <p>Toy example:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFr...
python|pandas|matplotlib
1
354,816
66,951,130
How to calculate SUMPRODUCT and OFFSET in python
<p>This is first dataframe df1:</p> <pre><code> DP 1 DP 2 DP 3 DP 4 DP 5 DP 6 DP 7 DP 8 DP 9 DP 10 3.034 1.581 1.377 1.244 1.164 1.089 1.054 1.071 1.008 2.688 1.753 1.464 1.139 1.058 1.114 1.061 1.058 4.143 1.781 1.439 1.174 1.180 1.168 1....
<p>For the sumproduct you can see: <a href="https://stackoverflow.com/questions/46385482/python-sumproduct-of-elements-in-nested-list">Python SUMPRODUCT of elements in nested list</a>.</p> <p>Offset is a prerogative of spreadsheet, or in general of the data structure you are using. python doesn't have tabular concept,...
python|excel|pandas|dataframe|triangle
0
354,817
66,818,310
How to get the column names of an Excel where the rows are blank Using Python
<p>Out of multiple columns present in Excel sheet, Need to check find out the names of the specific columns for each rows from an excel sheet, and enter the name of the column in a different column. If none of the column is having any blank values it will be written as No Gaps.</p> <p>Input Data:</p> <pre><code>col1 ...
<p>With <strong><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dot.html" rel="nofollow noreferrer"><code>df.dot</code></a></strong> and <strong><a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a></strong> and some string...
python|pandas|dataframe
6
354,818
66,986,409
Pandas: How to highlight a cell value based on a Z-score value?
<p>In my <code>df</code> below, I want to :</p> <ol> <li>identify and flag the outliers in <code>col_E</code> using z-scores</li> <li>separately explain how to identify and flag the outliers using z-scores in two or more columns, for example <code>col_D</code> &amp; <code>col_E</code></li> </ol> <p>See below for the d...
<p>I assume the following meanings to demonstrate a broader range of usage.</p> <ul> <li>Q1 stands for calculating a single column</li> <li>Q2 stands for calculating over multiple columns pooled together.</li> </ul> <p>If Q2 is meant to calculated on multiple columns separately, then you can simply loop your Q1 solutio...
python|pandas|dataframe|scipy|statsmodels
2
354,819
66,783,488
Code efficiency/performance improvement in Pushshift Reddit web scraping loop
<p>I am extracting Reddit data via the Pushshift API. More precisely, I am interested in comments and posts (submissions) in subreddit X with search word Y, made from now until datetime Z (e.g. all comments mentioning &quot;GME&quot; in subreddit /rwallstreetbets). All these parameters can be specified. So far, I got i...
<p>I would suggest a bloom filter to check if values have already been passed through.</p> <p>There is a package on <a href="https://pypi.org/project/bloom-filter/" rel="nofollow noreferrer">PyPi</a>, which implements this very easily. To use the bloom filter you just have to add a &quot;key&quot; to the filter, this c...
python|pandas|performance|reddit
1
354,820
67,098,612
How to Iterate over a list of numpy arrays in Python 3
<p>I currently have a list of numpy arrays. These arrays contain sets of 2D points. I'd like to iterate over each array in this list as depending on the contents of the array two scenarios can occur. The issue I'm running into is that when I try to iterate over the list like so:</p> <p><code>for array in list:</code></...
<p>You can use <code>numpy.squeeze</code> to remove one dimension and use <code>.tolist()</code> to print in the format you want.</p> <pre><code>a = [array([[[1, 2]], [[3, 4]]], dtype=int32),array([[[5, 6]], [[7, 8]]], dtype=int32)] for array in a: print(squeeze(array).tolist()) </code></pre>
python|python-3.x|numpy|numpy-ndarray
2
354,821
66,911,980
How to apply a function that splits multiple numbers to the fields of a column in a dataframe in Python?
<p>I need to apply a function that splits multiple numbers from the fields of a dataframe.</p> <p>In this dataframe there a all the kids' measurements that are needed for a school: Name, Height, Weight, and Unique Code, and their dream career.</p> <ul> <li>The <strong>name</strong> is only formed of alpha-characters. B...
<p>Use <code>apply</code> for rows (<code>axis=1</code>) and choose 'expand' option. Then rename columns and concat to the original df:</p> <pre><code>pd.concat([df,(df.apply(lambda row : extract_measurements(row['Measurements'], class_code['Small']), axis = 1, result_type='expand') .rename(columns = {0:'height', 1:...
python|pandas|dataframe
1
354,822
66,958,687
Smoothing time seriesm, taking into account seasonality
<p>My time series has the following figure showing outliers:</p> <p><a href="https://i.stack.imgur.com/icgxZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/icgxZ.png" alt="X-axis is date and Y-axis is Load" /></a></p> <p>What the best way to smooth the time series in python pandas taking into consid...
<p>First, what you're asking about is called &quot;time-series anomaly detection,&quot; and it's a real-world problem with significant scientific and business applications. For a great overview of available libraries in modern programming languages (including Python), I recommend <a href="https://github.com/rob-med/aw...
python|pandas|time-series
1
354,823
66,945,876
pandas: assign to multiindex using .loc with mask
<p>Using the example from the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#using-slicers" rel="nofollow noreferrer">MultiIndex / advanced indexing: Using slicers</a> documentation.</p> <pre><code>def mklbl(prefix, n): return [&quot;%s%s&quot; % (prefix, i) for i in range(n)] miin...
<p>One option would be to filter by the indices of rows that meet all criteria using numpy's <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwji37Wyz-XvAhVFgf0HHTTLCK0QFjAAegQIBRAD&amp;url=https%3A%2F%2Fnumpy.org%2Fdoc%2Fstable%2Freference...
python|pandas|multidimensional-array|indexing|multi-index
1
354,824
67,030,330
Combining multiple models trained in different parts of the dataset in PyTorch
<p>In PyTorch, is it theoretically possible to 'merge' multiple models together into one model - effectively combining all the data learnt so far? The models are exactly identical, however, are trained with different parts of the training data.</p> <p>If so, would it be possible to split a dataset into equal parts and ...
<p>I believe what you are asking for is a distributed implementation of a tensorflow/pytorch model. Similar to distributed databases, chunks of data can be used on separate clusters to train a single model in parallel on each cluster. The resultant model will be trained on all the separate chunks of data on different c...
machine-learning|pytorch
0
354,825
66,900,239
Why does tf.reduce_mean() return NaN values? I'm trying to calculate the Mean Squared error, but I keep getting NaN values
<p>This is the code I'm using:</p> <pre><code>tf.reset_default_graph() self.sess = tf.InteractiveSession() self.X = tf.placeholder(tf.float32, [None, self.state_space]) self.Y = tf.placeholder(tf.float32, [None, self.action_space]) layer1 = tf.layers.dense(self.X, 128, activation = tf.nn.leaky_relu) layer2 = tf.lay...
<p>Finally got the loss function to work by changing the tensorflow version.</p> <pre><code>from tensorflow.python.framework import ops %tensorflow_version 1.x ops.reset_default_graph() </code></pre> <p>Then, while setting up my trader (which is defined as a class in my code), I added the following snippet:</p> <pre><...
python|tensorflow
0
354,826
66,831,999
How to import csv as a pandas dataframe?
<p>I have a csv file which is located on my computer, the path looks like: Macintosh HD/somefolder/anotherfolder/onemorefolder/file.csv</p> <p>However when I try to import that csv as a dataframe in pandas using the code:</p> <pre><code>df = pd.read_csv(&quot;/Macintosh HD/somefolder/anotherfolder/onemorefolder/file.cs...
<p>You can use relative path by putting the csv in the same folder with the script or notebook you are trying to read the csv.</p> <pre><code>df = pd.read_csv('file.csv', sep=';') </code></pre> <p>or in a folder that is in the same folder with the script/notebook:</p> <pre><code>df = pd.read_csv('name_of_the_folder/fil...
python|pandas|dataframe|csv|import
0
354,827
67,107,315
Exception has occurred: TypeError object of type 'float' has no len()
<p>I'm trying to execute this code</p> <pre><code>import pandas as pd df_schema = pd.read_csv('survey_results_schema.csv') df_results = pd.read_csv('survey_results_public.csv', index_col='Respondent') print(df_results['Country'].apply(len)) </code></pre> <p>And I should get this:</p> <pre><code>Respondent 1 ...
<p>Your problem is probably that you have NaN in your data. NaN type is recognized as a float so this is the reason for your error.</p> <p>The following code will set 0 for every NaN value else will set the len of the value:</p> <pre><code>print(df_results['Country'].apply(lambda x: 0 if pd.isna(x) else len(x))) </cod...
python|pandas
0
354,828
66,982,098
Plotly 25th and 75th Percentile is different from Pandas and Numpy 25th and 75th Percentile
<p>I am using plotly boxplot but I found that the Q1 and Q3 numbers are very different from the 25th Percentile and 75 Percentile numbers from pandas and numpy, which is what I wanted my plotly boxplot to show.</p> <p>Is there anyway to solve this issue?</p> <p>Percentile from Pandas describe function</p> <pre><code>Da...
<p>Refer to <a href="https://numpy.org/doc/stable/reference/generated/numpy.percentile.html#r08bde0ebf37b-1" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.percentile.html#r08bde0ebf37b-1</a></p> <p>Notice there are multiple methods (9 at the moment of writing) of calculating the perce...
python-3.x|pandas|numpy|statistics|plotly
0
354,829
66,992,396
Please make me understand the reason behind why numpy.isfinite function is used in the below code?
<p>** I have a CSV file, containing Oympics data for summers as well as winters for all the countries, the problem statement is -&gt; Which country has the biggest difference between their summer gold medal counts and winter gold medal counts relative to their total gold medal count?</p> <p>Only include countries that ...
<p>I Think i might got the solution in the third and fourth line of code <code>copy_df = copy_df.where(df['Gold'] &gt; 0)</code> and <code>copy_df = copy_df.where(df['Gold.1'] &gt; 0)</code> i am only allowing values greater than '0' so, apparently other rows for each columns where values are not &gt;0 are filled with ...
python|numpy
0
354,830
66,978,835
Accumulate sliding windows relative to origin
<p>I have an array <code>A</code> with the shape <code>(3,3)</code> which can be thought of as the sliding window view of an unkown array with the shape <code>(5,)</code>. I want to compute the inverse of windowing the array with the shape <code>(5,)</code>. The adjoint operation of this will be summation. What I mean ...
<p>As I mentioned in the comment, a vectorized solution doesn't always guarantee a better running time. If your matrix is large, you might prefer more efficient methods. And there are several reasons why matrix rotation is slow (though, intuitive), see comment.</p> <p>Performance comparison:</p> <pre><code>Solution: Wa...
python|python-3.x|numpy|vectorization
3
354,831
66,998,727
Python mapping two csv files
<p>I have a <strong>config file</strong> (csv) :</p> <pre><code>Column name;Function;Args Region;function1;arg1 Country;function2;arg1, arg2 email;function3;arg1 ... </code></pre> <p>And i want to apply a specific <strong>Function</strong> from my config file to a specific column in my csv file (<code>fileIn</code> <st...
<p>You can set up a dict with functions and apply it to the chunk dataframe on each iteration.</p> <p>Here's some code, please see comments for explanations:</p> <pre><code># set up functions, for example # - f1 to uppercase # - f2 to lowercase # - f3 to reverse string def f1(x): return x.upper() def f2(x): re...
python|pandas|dataframe|csv|dask
1
354,832
67,161,539
Faster way to sum all combinations of rows in dataframe
<p>I have a dataframe of 10,000 rows that I am trying to sum all possible combinations of those rows. According to my math, that's about 50 million combinations. I'll give a small example to simplify what my data looks like:</p> <pre><code>df = Ratio Count Score 1 6 11 2 7 ...
<p>After these improvements it takes <strong>~2 minutes</strong> to run for 10k rows.</p> <ol> <li><p>For the sum computation, you can pre-compute <code>cumulative sum(cumsum)</code> and save it. <code>sum(i to j)</code> is equal to <code>sum(0 to j) - sum(0 to i-1)</code>. Now <code>sum(0 to j)</code> is <code>cumsum[...
python|pandas|performance|numpy|combinations
3
354,833
47,483,480
flatten/un-stack excel pivot using python pandas
<p>I have an excel pivot with data like: </p> <pre><code>Code Region Detail Oct'17 Sep'17 Aug'17 AXISCGF zone 1 IND3D01024 -82,000 0 900,000 AXISDEF zone 5 INP467B029 85,000 182,000 0 AXISEAF zone 4 INZ514ELY4 -13,500 0 5,00,000 AXISEQF zone 2 INQ916D14E ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow noreferrer"><code>melt</code></a>:</p> <pre><code>df = df.melt(['Code','Region','Detail'], value_name='Change', var_name='Month') print (df) Code Region Detail Month Change 0 AXISCGF zone 1 IND3D...
python|excel|pandas|pivot-table
0
354,834
47,256,134
tensorflow: undefined symbol: cudnnSetRNNDescriptor_v6
<p>when I finished installing tensorflow (GPU_support,linux 14.04,python3.4) with virtualenv environment,under the instructions of the official website, i validated the installation with the command :python; import tensorflow; but there is an error:</p> <ul> <li><code>import tensorflow as tf Traceback (most recent cal...
<p>I had this same error, and so hopefully this solution will work for you...</p> <p>What version of CuDNN are you using? I found that versions of <code>tensorflow-gpu</code> > 1.2 would fail to load while I had CuDNN v5.1.10 installed.</p> <p>At the time I'm writing this, Tensorflow docs say you must have CuDNN v6. ...
python-3.x|tensorflow
3
354,835
47,493,567
Return column names as a list in dataframe for a given condition of values in python
<p>given 1xN dataframe table, need to pick 5 largest values from the row and return the corresponding column names into a list. this is the dataframe sample:</p> <pre><code> 5 2 13 15 37 8 89 PageRank 0.444384 0.44453 0.444695 0.444882 0.444759 0.4448...
<p>You can get some added performance by using Numpy's <code>np.argpartition</code>. I'll use it on the negative of the values in order to get the correct direction.</p> <p>I wanted to use <code>np.argpartition</code> instead of sorting because it is <code>O(n)</code> rather than sorting which is <code>O(nlogn)</code...
python-2.7|list|pandas|dataframe
6
354,836
47,361,889
Nodejs Tensorflow Serving Client Error 3
<p>I'm serving a pre-trained inception model, and I've followed the official tutorials to serve it up until now. I'm currently getting an Error Code 3, as follows:</p> <pre><code>{ Error: contents must be scalar, got shape [305] [[Node: map/while/DecodeJpeg = DecodeJpeg[_output_shapes=[[?,?,3]], acceptable_fraction=...
<p>Okay, so I finally managed to crack this. Posting it as an answer here in case someone faces this exact same problem.</p> <p>So the inception model expects a base64 encoded image:</p> <pre><code>fs.readFile('./test/Xiang_Xiang_panda.jpg', (err, data) =&gt; { if(err) { return res.json({message: "Not fou...
node.js|tensorflow|tensorflow-serving
0
354,837
47,113,596
Reproducing scikit-learn's MLPClassifier in TensorFlow
<p>I am new to Tensorflow, having previously extensively used scikit-learn. As one of my first exercises in trying to transition to TensorFlow, I'm trying to reproduce some of the results I obtained with scikit-learn's MLPClassifier.</p> <p>When I use the MLPClassifier with mostly default settings, I get up to 98% acc...
<p>A MLP Classifier is a neural network. In essence, it needs to be trained for multiple iterations (epochs) before it learns appropriate weights on the hidden layers using backpropagation, after which it can classify correctly.</p> <p>If you look at sklearns implementation, there is a default parameter called <code>ma...
python|tensorflow|scikit-learn
1
354,838
47,307,862
Why do scipy and numpy fft plots look different?
<p>I am currently doing some spectrum analysis for a piece of coursework, though we haven't been explicitly taught Fourier transforms yet. I have been playing around with the various fft algorithms in scipy and numpy on some data that I know what the answer should look like</p> <p>In this case its an AM signal at 8kHz...
<p>From NumPy's doc for <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.rfft.html#numpy.fft.rfft" rel="noreferrer">rfft</a>:</p> <blockquote> <p>Returns: </p> <p>out : complex ndarray</p> <p>The truncated or zero-padded input, transformed along the axis indicated by axis, or the ...
python|numpy|scipy|fft
14
354,839
47,321,797
Pandas: replace records based on conditional test in column
<p>I have unique records in a dataframe, with no duplicates, as determined by combination of values across several columns:</p> <pre><code>import pandas as pd d = {'Alpha' : ['C', 'B', 'C','D', 'A', 'A'], 'Beta' : ['G', 'F', 'G', 'H', 'A', 'A'],'Year': ['Base', 88, 94, 22, 'Base', 66], 'Zulu' : [1, 2, -3, 4, 5, -3]} d...
<p>One way would be to convert the negative values in Zulu to nan and then fillna</p> <pre><code>df.loc[df['Zulu'] &lt; 0, 'Zulu'] = np.nan df['Zulu'] = df.groupby(['Alpha', 'Beta']).Zulu.apply(lambda x: x.ffill().bfill()).astype(int) Alpha Beta Year Zulu 0 C G Base 1 1 B F ...
python|pandas|replace|conditional|records
3
354,840
47,112,381
Order legend in same order that the (last value of) the plots are displayed
<p>I am adding plots to a figure within a loop, so when I add a legend to the figure, it is ordered in the same order that the plots were added. Instead I would like to order the legend, intuitively, as the plots are displayed in the figure. Some of the plots overlap and cross over each other in some cases, so when I s...
<p>The idea would be to obtain the order of the elements from the last data row, e.g. using <code>numpy.argsort</code>, order the handles and labels accordingly and supply the ordered handles and labels to the legend.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = np.linspace(0.,3.4) phis = np....
python|numpy|matplotlib
1
354,841
47,338,980
Tensorflow-loss not decreasing when training
<p>I am using tensorflow object detection api for my own dataset I am facing some problem. I am using centos , with GPU Geforce 1080, 8 GB GPU memory, tensorflow 1.2.1 . I have 500 images in training set and 40 in test. I did the following steps and I have two problems. 1.I annotated my images using LabelImg tool 2.Cre...
<p>The loss curve you're seeing on Tensorboard is quite normal. Initially, the loss will drop very quickly, but will seemingly "bottom out" over time. Training is a slow process, you should see a steady drop over time after more iterations.</p>
tensorflow|deep-learning
2
354,842
47,437,966
How to transpose rows into single column based on time-stamp index in python?
<p><strong>Sample input dataset is:</strong></p> <blockquote> <p>0 2017-11-17 10:23:28.691 788 756 789 780</p> <p>1 2017-11-17 10:23:29.731 788 783 0 0</p> <p>2 2017-11-17 10:23:30.655 747 0 0 0</p> <p>3 2017-11-17 10:23:31.627 766 0 0 0</p> <p>4 2017-11-17 10:23:32.606 807 0 0 0</p> </blockquote...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a>, then filter out <cod...
python|pandas|ipython
2
354,843
47,371,439
Numpy: Imposing row dependent maximum on array
<p>Suppose I have the following array:</p> <pre><code>a = [[1, 4, 2, 3] [3, 1, 5, 4] [4, 3, 1, 2]] </code></pre> <p>What I'd like to do is impose a maximum value on the array, but have that maximum vary by row. For instance if I wanted to limit the 1st and 3rd row to a maximum value of 3, and the 2nd row to...
<p>With <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.clip.html" rel="nofollow noreferrer"><code>numpy.clip</code></a> (using the method version here):</p> <pre><code>a.clip(max=np.array([3, 4, 3])[:, None]) # np.clip(a, ...) # array([[1, 3, 2, 3], # [3, 1, 4, 4], # [3, 3, 1,...
python|arrays|numpy
3
354,844
47,343,044
Using patch from larger image as input dim to Keras CNN gives error 'Tensor' object has no attribute '_keras_history'*
<p>I am trying to create a CNN with keras to process 20x20 patches from a larger image of 600x600.</p> <p>When I attempt the run the code below I receive an error <em>AttributeError: 'Tensor' object has no attribute '_keras_history'</em> </p> <p>The below code is only intended to look at the first 20 x 20 patch out ...
<p>The error occurs because the slicing operation <code>Input_1R[:,0]</code> is not performed in a Keras layer. You can wrap it into a <code>Lambda</code> layer:</p> <pre class="lang-py prettyprint-override"><code>sliced = Lambda(lambda x: x[:, 0])(Input_1R) conv1 = Convolution2D(nb_filters, (5,5), activation='relu', ...
tensorflow|keras
1
354,845
47,526,056
Fast way to fill matrix from np.array of row index, column index, and max(values)
<p>I have quite large arrays to fill matrix (about <code>5e6</code> elements). I know the fast way to fill is something like</p> <p>(simplified example)</p> <pre><code>bbb = (np.array([1,2,3,4,1])) # row ccc = (np.array([0,1,2,1,0])) # column ddd = (np.array([55.5,22.2,33.3,44.4,11.1])) # values experiment = np.zero...
<p>You can use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ufunc.at.html" rel="nofollow noreferrer"><code>np.ufunc.at</code></a> on <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.maximum.html" rel="nofollow noreferrer"><code>np.maximum</code></a>.</p> <p><code...
python|arrays|python-2.7|numpy|matrix
5
354,846
47,299,196
How to set a colormap in interactive plot animations in python
<p>The code below creates an animation of 600k points by scatter plotting 30k of them per frame. The animation works flawlessly, except for the fact that I don't know how to include my colormap (Heatintensity) in the animation. The Xs and Ys are changing but the color of the points is just blue. </p> <pre><code>import...
<p>In order to change the colors, you need to use </p> <pre><code>sc.set_array(Heatintensity[(i*30000):(i*30000)+30000]) </code></pre> <p>in addition to changing the offsets.</p> <p>In order for the colors to represent the same numerical values for each animation step, the scatter must be normalized to all data,</p...
python|numpy|animation|matplotlib|scatter-plot
1
354,847
47,387,173
Plot a 3D plot for pandas data using matplotlib
<p>I'm trying to make a figure similar to <a href="https://matplotlib.org/examples/mplot3d/polys3d_demo.html" rel="nofollow noreferrer">this</a>. and the code is like </p> <pre><code>fig = plt.figure() ax = fig.gca(projection='3d') def cc(arg): return mcolors.to_rgba(arg, alpha=0.6) xs = np.arange(0, data.shape[0]...
<p>Since all other codes of yours are the same as the example's, the error must come from your coding tools (e.g., cterm or jupyter notebook) or your data. I wonder if you're using ssh or jupyter without interaction backend.</p>
python|pandas|matplotlib|plot
0
354,848
47,464,658
Python. Efficient way to remove emojis and some punctuation from a large dataset
<p>I have 200k rows with messages in a pandas dataframe. Each message on average contains 230 characters sprinkled with emojis like these .</p> <p>Now i want to filter out everything except lower and upper English and Russian letters and these symbols: <code>#@/:%.,_-</code> </p> <p>What would be the most efficient w...
<p>Use <code>str.replace</code> with <code>^</code> inversion.</p> <pre><code>df['col'] = df['col'].str.replace('[^\w\s#@/:%.,_-]', '', flags=re.UNICODE) </code></pre>
python|regex|string|pandas
6
354,849
47,415,306
Pandas: splitting dataframe into multiple dataframe based on threshold value
<p>I have dataframe like this<br></p> <pre><code> Transport Elapsed_Time gap_time gap_minutes 0 taxi 556.0 0 days 00:00:02 0.0 1 walk 95.0 0 days 00:53:34 53.0 2 taxi 44.0 0 days 02:02:00 ...
<p>Let's try this, 'listofdf' is a dictionary of dataframes with keys of 1 to 7 in this case. First let's make sure gap-time is pd.TimeDelta dtype, then group:</p> <pre><code>df.gap_time = pd.to_timedelta(df.gap_time) g = df.groupby((df.gap_time / pd.Timedelta('20 minutes')).ge(1)[::-1].cumsum()) for n,g in g: li...
python|pandas
5
354,850
47,426,241
speedup scipy custom continuous random variable
<p>I've created a <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.html#scipy.stats.rv_continuous" rel="nofollow noreferrer"><code>scipy.stats.rv_continuous</code></a> subclass, and it seems to be doing what I want, but it's extremely slow. Code and test results below.</p> <p>Th...
<p>One solution is to override the <code>_rvs</code> method itself and use the analytic formulae to draw samples using <a href="https://en.wikipedia.org/wiki/Inverse_transform_sampling" rel="nofollow noreferrer">inverse transform sampling</a>:</p> <pre><code>def _rvs(self, size=None): """Invert the CDF (semi)-anal...
python|numpy|optimization|random|scipy
4
354,851
47,304,422
How to make a python list from a .csv list?
<p>I want to know how to make a .csv list into a python list which I can do plotting and calculating:</p> <p>I used:</p> <pre><code> fpath = r'C:112017\temp\tT.csv' with open(fpath,'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: print(list(reader))...
<p>There is <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>pandas.read_csv()</code></a> method which will read the csv file and return a dataframe</p> <p>Eg:</p> <pre><code>fpath = r'C:112017\temp\tT.csv' df = pd.read_csv(fpath, delimiter=',', nam...
python|pandas|csv
4
354,852
47,388,570
pandas dataframe to_csv works with sep='\n' but not sep='\t'
<p>I try to print my large dataframe to csv file but the tab separation <code>sep='\t'</code> does not work. I then test with newline <code>sep='\n'</code>, it seems work ok, break all the elements by newline. What are possibly wrong here?</p> <p>The code is so simple like</p> <pre><code>df_M.to_csv('report'+filename...
<p>There is problem all rows are in <code>"</code> and then get one column <code>DataFrame</code>.</p> <p>So need <code>quoting=3</code> for <code>QUOTE_NONE</code> and then remove trailing <code>"</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow nore...
python|python-2.7|pandas|csv
1
354,853
47,411,754
could not broadcast input array
<p>I have a csv data, the first column of the data is 'label' and columns after the first one to the end 784 column contains a representation of an image (28*28) format.</p> <p>I created a tuple of numpy array using the following function. </p> <p>Next step is I am trying to split this dataset into desired 80% /20% s...
<p>From what I understand, you are passing a tuple consisting of one matrix and one array (that does not have the same shape) to <code>np.split</code> which is why you get the broadcast error. It works fine if you give <code>np.split</code> a single matrix:</p> <pre><code>train_data = np.zeros((5000, 784)) labels = np...
python|numpy|mnist
0
354,854
47,104,863
TensorFlow sparse_softmax_cross_entropy rank error
<p> I'm trying to build an RNN with LSTM on TensorFlow. Both the input and output are 5000 by 2 matrices, where the columns represent the features. Those matrices are then fed to the batchX and batchY placeholders which enable the backpropagation. The main definition of the code is at the bottom. I am getting the follo...
<p>Thanks to Maosi Chen, I found the issue. It was because the </p> <blockquote> <p>tf.nn.sparse_softmax_cross_entropy_with_logits</p> </blockquote> <p>Requires labels to have one less dimension than logits. Specifically, the labels argument takes values of the shape <code>[batch_size] and the dtype int32 or int64<...
tensorflow
3
354,855
47,337,534
Python - Call numpy method on strings of dataframe column?
<p>So I have a dataframe column that includes a <code>numpy</code> array, but its read in as a string. So, I end up with the following as a single element: </p> <pre><code>df['numpy_arr'].iloc[0] = ' 2 3 5 23 5 2 23 ' </code></pre> <p>I want to convert this to a numpy array, and have successfully done so for a singl...
<p>This works for me:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({"A": [' 2 3 5 23 5 2 23 ', ' 3 4 5 ']}) &gt;&gt;&gt; df A 0 2 3 5 23 5 2 23 1 3 4 5 &gt;&gt;&gt; df['A'].apply(lambda x: np.fromstring(x, sep = ' ')) 0 [2.0, 3.0, 5.0, 23.0, 5.0, 2.0, 23.0] 1 ...
python|arrays|pandas|numpy
1
354,856
47,469,947
as_strided: Linking stepsize (strides of conv2d) with as_strided strides parameter
<p>I found that for generating <code>(X - x + 1, Y - y + 1)</code> patches of size <code>(x,y)</code> from <code>(X,Y)</code> with stride 1, image requires us to give strides parameter as <code>img.strides * 2</code> or <code>img.strides + img.strides</code>. <em>I don't know how they quickly compute this knowing the n...
<p>Here's one approach -</p> <pre><code>def patchify(img, patch_shape, stepsize_x=1, stepsize_y=1): strided = np.lib.stride_tricks.as_strided x, y = patch_shape p,q = img.shape[-2:] sp,sq = img.strides[-2:] out_shp = img.shape[:-2] + (p-x+1,q-y+1,x,y) out_stride = img.strides[:-2] + (...
python|numpy|conv-neural-network|stride
2
354,857
11,237,527
I have a set of points along the oval. How do I create a filled binary mask
<p>I am trying to get an filled binary mask of a contour of this image. <img src="https://i.stack.imgur.com/rp469.png" alt="The contour of the image"></p> <p>I took a look this question <a href="https://stackoverflow.com/questions/3654289/scipy-create-2d-polygon-mask">SciPy Create 2D Polygon Mask</a>; however it does ...
<p>I'm not sure what you're plotting at the end, but your example works for me:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.nxutils import points_inside_poly from itertools import product, compress pv = [(1,1),(5,1),(5,9),(3,2),(1,1)] x, y = np.meshgrid(np.arange(10),np.arange(1...
python|image-processing|numpy|matplotlib
2
354,858
11,017,347
List comprehension for two variable loop in Python and numpy
<p>I have to create a 2D numpy array from the values x, y from a function return to plot using contourf from matplotlib, and so far I'm using a "C" like structure, that it seems to be <em>very</em> inefficient in Python:</p> <pre><code> dim_x = np.linspace(self.min_x, self.max_x, self.step) dim_y = np.linspace(...
<p>It would be ideal if you could rewrite <code>final_potential</code> as a vectorized function. A simple and, perhaps, too-obvious example:</p> <pre><code>&gt;&gt;&gt; dim_x = np.linspace(0, 2, 5) &gt;&gt;&gt; dim_y = np.linspace(0, 2, 5) &gt;&gt;&gt; X * Y array([[ 0. , 0. , 0. , 0. , 0. ], [ 0. , ...
python|list|numpy
2
354,859
11,265,518
ADF test in statsmodels in Python
<p>I am trying to run a Augmented Dickey-Fuller test in <code>statsmodels</code> in Python, but I seem to be missing something.</p> <p>This is the code that I am trying:</p> <pre><code>import numpy as np import statsmodels.tsa.stattools as ts x = np.array([1,2,3,4,3,4,2,3]) result = ts.adfuller(x) </code></pre> <p>...
<p>I figured it out. By default <code>maxlag</code> is set to <code>None</code>, while it should be set to integer. Something like this works:</p> <pre><code>import numpy as np import statsmodels.tsa.stattools as ts x = np.array([1,2,3,4,3,4,2,3]) result = ts.adfuller(x, 1) # maxlag is now set to 1 </code></pre> <p>...
python|numpy|statistics|statsmodels
7
354,860
68,156,449
Find bar plot using composite key
<p>I have a table like below:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'id': [a12,a12,b11,b113,c13,c13], 'A': [np.nan,np.nan,3,3,np.nan,np.nan],'B':[7,7,np.nan,np.nan,np.nan,np.nan],'C':[np.nan,np.nan,np.nan,2,4,4],'D':[np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]})``` ...
<p>You can <code>melt</code> the dataframe and <code>drop_duplicates()</code> and then <code>groupby</code> <code>size</code> from there:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame({'id': ['a12','a12','b11','b113','c13','c13'], 'A': [np.na...
python|pandas|bar-chart
0
354,861
68,156,222
Pandas: How to separate a large df into multiple dfs based on column value
<p>I was wondering whether there is a way to seperate the table below in multiple sub dfs using the periodicity in the first column e.g between ~5,..,~0</p> <pre><code>before: a b c 5.10 1.00 0.00 4.20 2.00 0.00 3.01 3.00 0.00 2.10 4.00 0.00 1.20 5.00 0.00 0.52 6.00 ...
<p>Try this:</p> <pre><code>listofdfs = [y for x,y in df.groupby(df['a'].diff().gt(0).cumsum())] </code></pre>
python-3.x|pandas
1
354,862
68,418,958
How do I explode a dict column? Explode() did not do the job
<p>I am loading the following CSV - <a href="https://www.drug.co.il/top.csv" rel="nofollow noreferrer">csv file</a>. I was trying to use explode() to explode the dict formatted column (brochure) into many columns. However, the code leaves the dict intact.</p> <pre><code>import pandas as pd df = pd.read_csv('top.csv', i...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code> from ast import literal_eval df = pd.read_csv(&quot;top.csv&quot;, index_col=0) df[&quot;brochure&quot;] = df[&quot;brochure&quot;].apply(literal_eval) df = df[&quot;brochure&quot;].explode().apply(pd.Series) print(df) </code></pre> <p>Prints:</p> <pre class...
pandas|dataframe
1
354,863
68,206,634
To change the output class label value of a predict function in OneclassSVM
<p>When I use OneClassSVM, we confirm that the results obtained by <code>estimator.predict (X_test)</code> derive the results as 1 and -1, respectively. Each means an outlier value and an internal value. But what I want is to label it with different values, like 0,1 not -1,1. I thought I could give a specific argument ...
<p>There is no built-in function to specify the labels. However, you can perform this operation using <code>np.where()</code>:</p> <pre><code>import numpy as np pred = np.array([-1, 1, -1, 1]) np.where(pred==-1, 'outlier_value', 'internal_value') </code></pre> <p>Output:</p> <pre><code>array(['outlier_value', 'interna...
scikit-learn|sklearn-pandas
2
354,864
68,193,521
Concatenate values and column names in a data frame to create a new data frame
<p>I have the following data frame(<code>df1</code>):</p> <pre><code> Value col1 col2 col3 0 a aa ab ac 1 b ba bb bc 2 c ca cb cc 3 d da db dc 4 e ea eb ec </code></pre> <p>I need to derive the data frame(<code>df2</code>) from <code>df1</code> such that column 1 of <c...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>x = df.melt(&quot;Value&quot;, value_name=&quot;Col 1&quot;) x.Value += &quot;_&quot; + x.variable x = x.drop(columns=&quot;variable&quot;) print(x) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> Value Col 1 0 a_col1 a...
python|pandas|dataframe|numpy
1
354,865
68,256,199
Plot the Graph with Dataframe with decreasing and increasing value
<p>I have dataframe like this:</p> <pre> Date Qty 2021-06-17 60 2021-06-17 -11 2021-06-18 -5 2021-06-19 -2 2021-06-20 20 2021-06-23 -8 2021-06-24 7 2021-06-25 -4 2021-06-26 2 2021-06-29 1 2021-06-30 8 </pre> <p><strong>What I need</strong> I need to plot like this graph, decreasing when the 'qty' number is n...
<p>You can continuously sum up the values with the <code>cumsum</code> function</p> <pre><code>In [6]: df2 = df.set_index('Date').cumsum() Out[6]: Qty Date 2021-06-17 60 2021-06-17 49 2021-06-18 44 2021-06-19 42 2021-06-20 62 2021-06-23 54 2021-06-24 61 2021-06-25 57 2021-06-26 ...
pandas|dataframe|matplotlib|seaborn
1
354,866
68,331,148
Tricky multiple transformations that create new dataframe in Python
<p>I have a large dataframe, df, where I would like to perform calculations and create new fields from.</p> <p><strong>Data</strong></p> <pre><code> location1 date1 type1 value1 positions location2 type2 date2 value2 sel1 Q1.22 lap1 10 50 sel1 fr1 Q1.22 10 ...
<p>Make a minor change in function:</p> <pre><code>def f(x): d = {'consumed': [x['value1'].sum()], 'retro': [x['value2'].sum()], 'finalconsumed': [x['value1'].sum() - x['value2'].sum()], 're_space': [x['type2'].count() - x['type1'].count()]} # &lt;&lt;&lt; HERE return pd.DataFrame(d)...
python|pandas|numpy
1
354,867
68,430,703
Create new columns from existing column values using Split function in Python
<p>While executing the code on the below data i am getting <strong>Error</strong> : SyntaxError: unexpected EOF while parsing</p> <p>I have a folder where multiple csv files are been placed, I need to process each file and split the column (Column2) value using the split function &quot;;&quot;. Once The values are spli...
<p><em>Just in case, If your error is not fixed you can try this code</em>:</p> <p>I tried it like this</p> <p><strong>solution:</strong></p> <pre><code>import pandas as pd # Assuming you can Loop on csv folder, then: df = pd.read_csv('data_.csv') df.dropna(subset = [&quot;Column2&quot;], inplace=True) new_data = {'I...
python|pandas
1
354,868
68,083,915
Why is the result different for same dataset in torchtext.legecy.text when i change the position of data in the csv file?
<p>I am trying to learn PyTorch NLP basic text classification and following Lazy Programmer's Tutorial and I got a different result from the tutorial and when I tried to change the data, I encountered a strange change in the output.</p> <pre class="lang-py prettyprint-override"><code> import torchtext.legacy.data as tt...
<p>I think you should use random seed for getting the same result for all of your runs (and also for comparing the results for your changes made in the model). The part of your code that should get the seed is dataset split function. as the <a href="https://torchtext.readthedocs.io/en/latest/data.html#torchtext.data.Da...
python|pandas|nlp|pytorch|torchtext
0
354,869
68,270,512
Sample from aggregate data in Pandas
<p>Let's say I have a Pandas dataframe with counts of objects in each category:</p> <pre><code>df = pd.DataFrame(data={'color': ['red', 'red', 'green', 'green', 'blue', 'blue'], 'shape': ['round', 'square', 'round', 'square', 'round', 'square'], 'number': [10000, 1, 50, 500, 7, 3000]}) color shape number 0 r...
<p>This seems like an improvement on the brute-force solution:</p> <pre><code>df = pd.DataFrame(data={'color': ['red', 'red', 'green', 'green', 'blue', 'blue'], 'shape': ['round', 'square', 'round', 'square', 'round', 'square'], 'number': [10000, 1, 50, 500, 7, 3000]}) score_dist = {'A': 0.1, 'B': 0.5, 'C': 0.25, 'D': ...
python|pandas|numpy
0
354,870
68,396,041
Replace pandas column special characters
<p>I have a pandas colum which has special characters such as {{,}},[,],,. (commas are separators).</p> <p>I tried using the following to replace the special characters with an underscore ('_'), but it is not working. Can you please let me know what I am doing wrong? Thanks.</p> <pre><code>import pandas as pd data = [[...
<p>From this <code>DataFrame</code> :</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; data = [[&quot;facebook_{{campaign.name}}&quot;], [&quot;google_[email]&quot;]] &gt;&gt;&gt; df = pd.DataFrame(data, columns = ['Marketing']) &gt;&gt;&gt; df Marketing 0 faceboo...
pandas|replace
0
354,871
68,385,453
cython function returns all values in a single cell after groupby apply
<p>I was looking to speed up processing of a groupby operation and while it now processes much faster, the resulting dataframe is not what I want.</p> <p>Make MultiIndexed dataframe with some data:</p> <pre><code>import pandas as pd import numpy as np import cython data = np.round(np.random.randn(4, 3), 1) df = pd.Da...
<p>Since Henry already answered the pandas part of your question, let me address the performance aspect. I don't really see the need for Cython here. As a rule of thumb, try to avoid loops over np.ndarrays whenever possible, i.e. use vectorized operations/functions instead of loops:</p> <pre class="lang-py prettyprint-...
pandas|pandas-groupby|cython
3
354,872
68,046,674
Converting datetime list to an hourly distribution dataframe
<p>I have a list of datetime string values. I wanted to have them in hourly distribution from Hours 00 to 24.</p> <p>For example, a sample list:</p> <pre><code>['2021-06-18 14:39:54', '2021-06-18 08:30:26', '2021-06-18 15:07:12', '2021-06-18 13:13:29', '2021-06-18 11:27:48', '2021-06-19 09:25:26', '2021-06-19 16:14:38'...
<p>With <code>l</code> your list you can convert it do a Series of datetimes using <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_datetime</code></a></p> <pre><code>&gt;&gt;&gt; s = pd.Series(l).transform(pd.to_datetime) &gt;&gt;...
python|pandas|dataframe|datetime
2
354,873
68,300,391
Pandas Groupby and find duplicates in multiple columns
<p>I have a dataframe and I want to groupby the 'Value_pack' column and check if 2 or more 'Value_pack' have the same 'value' and 'discount'. (Duplicates)</p> <p>I want to remove all but the first occurrence of duplicates from the dataframe.</p> <p>Input Dataframe:</p> <pre><code> Value_pack value discount va...
<p>No need to use <code>groupby</code>. Try: <code>df.drop_duplicates(subset=['value', 'discount'])</code>. Check out docs <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop_duplicates.html?highlight=drop_duplicates#pandas.DataFrame.drop_duplicates" rel="nofollow noreferrer">here</a>.</p>
python|pandas|dataframe|pandas-groupby
1
354,874
68,151,915
No matching distribution found for tensorflow_cpu==2.3.1 while building Docker Image
<p>I am trying to build a docker image, but while insstalling the tensorflow, it shows the following error:</p> <blockquote> <p>#9 2.293 ERROR: Could not find a version that satisfies the requirement tensorflow_cpu==2.3.1 (from versions: none) #9 2.293 ERROR: No matching distribution found for tensorflow_cpu==2.3.1</p>...
<p>I think this problem might be originated by some missing library in the alpine image or architecture incompatibility. Try to change the image from <code>alpine</code> to <code>slim</code>. I tested with slim, and it worked.</p> <pre><code>FROM python:3.8.8-slim </code></pre>
python|docker|tensorflow|docker-compose
1
354,875
68,085,572
Sort numpy array by another array
<p>I've got two numpy arrays <code>lst</code> and <code>a</code> and I want to sort the first column of <code>a</code> in the same order it appears in <code>lst</code>, while maintaining each row of <code>a</code> to have the same elements.</p> <pre><code>lst = np.array(['a','b','d','e','c']) a = np.array([['e','b','a'...
<p>I'm assuming all your values in <code>lst</code> are unique, <code>lst</code> and <code>a</code> are the same length, and they contain the same characters that you're sorting by.</p> <pre><code>lst = np.array(['a','b','d','e','c']) a = np.array([['e','b','a','d','c'],[1,2,3,4,5]]).T first_col = a[:, 0] lst_grid, f...
python|numpy
1
354,876
68,221,427
From XML url to Pandas dataframe
<p>I'm new to Python and I'm having some trouble importing a simple XML file from the web and converting it into a pandas DF: <a href="https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/cny.xml" rel="nofollow noreferrer">https://www.ecb.europa.eu/stats/policy_and_exchange_rates...
<p>Aiii!</p> <pre><code>from bs4 import BeautifulSoup import requests import pandas as pd response = requests.get('https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/cny.xml') bs = BeautifulSoup(response.text, ['xml']) obs = bs.find_all(&quot;Obs&quot;) #&lt;Obs OBS_CONF=&qu...
python|python-3.x|pandas|xml|xml-parsing
0
354,877
68,343,073
'Seq2SeqModelOutput' object has no attribute 'logits' BART transformers
<p>I am trying to generate summary of long PDF. So, what I did, first I converted my pdf to text using <code>pdfminer.six</code> library. Next, I used 2 functions which were provided in a discuss <a href="https://github.com/huggingface/transformers/issues/4224#issuecomment-694650789" rel="nofollow noreferrer">here</a>....
<p>The issue here is the <em>BartModel</em> line. Switch this for a <em>BartForConditionalGeneration</em> class and the problem will be solved. In essence the generation utilities assume that it is a model that can be used for language generation, and in this case the BartModel is just the base without the LM head.</p...
nlp|huggingface-transformers
4
354,878
68,246,928
Create a customized tensorflow layer to separate features
<p>To solve the issue that I've posted here : <a href="https://stackoverflow.com/questions/68245361/adjust-the-output-of-a-cnn-as-an-input-for-timedistributed-tensorflow-layer">Adjust the output of a CNN as an input for TimeDistributed tensorflow layer</a> which is about <em>input data format of the Time distributed te...
<p>Thank you @Marco for the help. Exactly like Marco says, I separate the input using index slicing and was done using a <strong>Lambda layer</strong>. This is the code:</p> <pre class="lang-py prettyprint-override"><code>input_layer1=tf.keras.Input(shape=(input_shape)) separate_features1 = tf.keras.layers.Lambda(lamb...
python|tensorflow|keras
0
354,879
68,391,284
Aggregate values into list like string and then cast to true list datatype
<pre><code>df = pd.DataFrame([ [&quot;a&quot;, 1], [&quot;a&quot;, 2], [&quot;b&quot;, 5], [&quot;b&quot;, 11] ]) df.columns=[&quot;c1&quot;,&quot;c2&quot;] grouped = df.groupby([&quot;c1&quot;])[&quot;c2&quot;].apply(list) grouped = grouped.reset_index() grouped[&quot;c3&quot;] = &quot;[11,12]&quot; #a...
<p>The aggregated column &quot;c2&quot; is a series of lists, eval doesn't accept that. If you cast it to str <code>grouped[&quot;true_list_c2&quot;] = grouped[&quot;c2&quot;].apply(str).apply(eval)</code> (just like &quot;c3&quot;) it works just fine.</p>
python|pandas
1
354,880
68,287,588
Python: Can't Filter CSV, ValueError: can only convert an array of size 1 to a Python scalar
<p>I have a CSV like this:</p> <pre><code>| path | artists | item | id | | ------------------------------- | ------- | ---- | ------------------ | | ../gifs/dwight\_harry\_0.gif | dh | 0 | wUIh5rHf5QCyhIk8Ay | | ../gifs/dwight\_beatles\_0.gif | db | 0 | O...
<p>IIUC:</p> <p>try:</p> <pre><code>df=df.apply(lambda x:x.str.strip(),axis=1) out=df.groupby('artists')['id'].agg(lambda x:x.value_counts().idxmax()) </code></pre> <p>output of <code>out</code>:</p> <pre><code>artists db OqBPFGQkA2rmoouv4A dh wUIh5rHf5QCyhIk8Ay mb hgKfGjpxOdfM38b3sk mh ITAra7ShPMXQecbFGZ N...
python|pandas|dataframe
0
354,881
68,340,334
Pandas_DataReader not working with Yahoo Finance API
<p>I started working on a project a month ago to try and predict future stock prices using historical data. The project was going fine and I decided to take a small break to upgrade my PC. Well, I tried checking out my code after finishing the computer but now I'm running into a bunch of errors concerning pulling data ...
<p>I don't know if it helps but yesterday I saw five questions for similar problem in module <code>yfinance</code>.</p> <p>It seems <code>Yahoo</code> changed something on pages and it needs changes in modules.</p> <p>For <code>yfinance</code> helps installing the newest version.</p> <p>Maybe this module needs also new...
python|pandas|api|yahoo-finance|pandas-datareader
1
354,882
68,180,288
How to concatenate vectors to matrix?
<p>I want to create a matrix from 3 vectors:</p> <pre><code>import numpy as np v1 = np.array([10, 0]) v2 = np.array([120, 9]) v3 = np.array([100, 7]) M = np.concatenate((v1, v2, v3)) print(M) </code></pre> <p>Results:</p> <pre><code>[10 0 120 9 100 7] </code></pre> <p>Desired results:</p> <pre><code>10 120 100 ...
<p>You can use <code>np.stack</code> with <code>axis=1</code>:</p> <pre><code>np.stack((v1, v2, v3), axis=1) </code></pre> <p>Output:</p> <pre><code>array([[ 10, 120, 100], [ 0, 9, 7]]) </code></pre>
python|python-3.x|numpy
2
354,883
68,124,402
how to copy and paste values until specific column ends in python dataframe
<p>I am trying to fill nans with previous values so wondering how to copy and paste values until single column ends.</p> <p>Here is the data I've got</p> <pre><code>Time indicator Value 2021-03-01 11:00 602500 1015.31 2021-05-01 8:00 602500 1017.61 2021-05-01 5:00 307001 3485....
<p>You can pass a mapping to <code>groupby()</code> like so:</p> <pre><code>df.groupby(df.index % df.Time.isna().idxmax()).ffill() </code></pre> <p>Note here that <code>df.Time.isna().idxmax()</code> is getting the index of the first <code>NaN</code> value in the <code>Time</code> column so that you know how many value...
python|pandas
1
354,884
68,255,306
Check if number in numpy array is within range specified in another array
<p>Data</p> <pre><code>a = np.array([[0.5,1,50],[0.5,1,30]]) b = np.array([[0.40,0.60],[0.75,2.0],[40,70]]) </code></pre> <p>Expected results:</p> <pre><code>TRUE FALSE </code></pre> <p>If I only had few rows, a stupid way to do it would be:</p> <pre><code>if b[0][0] &lt;= a[0][0] &lt;= b[0][1] and b[1][0] &lt;= a[0][...
<p>IIUC, here's one way:</p> <pre><code>result = np.apply_along_axis(lambda x: all((x &gt; b.T[0]) &amp; (x &lt; b.T[-1])), 1, a) </code></pre> <p>OUTPUT:</p> <pre><code>array([ True, False]) </code></pre>
python|python-3.x|pandas|list|numpy
1
354,885
68,173,284
Remove suffix of the column names and unpivot
<p>I'd like to unpivot the following table with column names &quot;Year&quot;, &quot;Item&quot;, and &quot;$&quot;. My workaround is to separate the table into two dataframes and remove the suffixes, then concatenate the two columns vertically. Are there any other easier ways to approach this?</p> <p>Example Dataframe:...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> for convert columns without separator <code>_</code> to index, then split columns names to <code>MultiIndex</code> :</p> <pre><code>cols = ['$'] #if m...
python|pandas|dataframe|unpivot|suffix
3
354,886
68,296,206
Pandas Period to to_timestamp giving me TypeError
<p>I have a Pandas Dataframe of the format as shown below:</p> <pre class="lang-none prettyprint-override"><code> Month Count 2021-02 100 2021-03 200 </code></pre> <p>Where the &quot;Month&quot; column is obtained from a timestamp using <em>dt.to_period('M')</em>.</p> <p>Now I have to convert this...
<p>If working with a column, it is necessary to add <code>.dt</code>. If omitting it, Pandas tries to convert <code>DatetimeIndex</code> and if it does not exist, it raises an error, because it called <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_timestamp.html" rel="nofollow no...
pandas|datetime|period
3
354,887
68,202,458
How to select specific values in an array/matrix in Numpy for a function?
<p>I have an array such as this:</p> <pre><code>data = np.array([[327, 137, 82], [301, 168, 75]]) </code></pre> <p>I need to be able to manipulate the individual entries in order to solve the question I am working on. For example, I must be able to sum both rows together, but also add the columns together, i.e. <code>d...
<p>I had a hard time trying to figure if you were trying to get a scalar value or a column/row vector from the sums but here is how I would try to get either:</p> <p>To get a row vector from:</p> <p><code>data = np.array([[327, 137, 82], [301, 168, 75]])</code>,</p> <p>you can use <code>np.sum(data, axis=0)</code> whic...
python|arrays|numpy|matrix
0
354,888
68,137,004
Making a pie chart from Pandas with custom categories
<p>First time asker apologies if answered elsewhere and I just can't find it.</p> <p>I have a dataframe that has some percent values in one column, I want to group all the data that's &lt;1%, 1-2%, 2-5%, 5-10%, and &gt;10% and make a pie chart with those values. I have a column in my dataframe that tells me which &quot...
<p>You could use Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html#pie-plot" rel="nofollow noreferrer"><code>plot.pie</code></a> and use <code>labeldistance</code> and <code>rotatelabels</code> to place the categories inside the chart giving the impression that those are the per...
python|pandas
0
354,889
68,086,528
Pytorch with CUDA throws RuntimeError when using pack_padded_sequence
<p>I am trying to train a BiLSTM-CRF on detecting new NER entities with Pytorch. To do so, I am using a snippet of code derivated from the <a href="https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html" rel="nofollow noreferrer">Pytorch Advanced tutorial</a>. <a href="https://github.com/jtlin-sync/batch_bil...
<p>Within <code>PadSequence</code> function (which acts as a <code>collate_fn</code> which gathers samples and makes a batch from them) you are explicitly casting to <code>cuda</code> device, namely:</p> <pre><code>class PadSequence: def __call__(self, batch): device = torch.device('cuda') ...
python|pytorch|named-entity-recognition|custom-training
3
354,890
68,313,118
do numpy 1.19 work with python 3.6 and pandas 1.15 ? If not what version do I have to use?
<p>The error I am facing is:</p> <blockquote> <p>Unable to import module 'lambda_function': Unable to import required dependencies: numpy:</p> <p>IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!</p> <p>Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues...
<p>Just run command : Import numpy numpy --upgrage</p> <p>And you can chek version by : Print (numpy.<strong>version</strong>)</p>
python|pandas|numpy|aws-lambda|python-3.6
-1
354,891
68,436,277
Count occurrences within range
<p>I have a dataset which like:</p> <pre><code>ID Amt TYPE 1 1000 A 2 200 NA 3 1100 S </code></pre> <p>I need to count the occurrences of each type within a specific range for each type:</p> <pre><code>Range A_Count NA_Count S_Count 0-1000 1 1 0 1001-2000 0 0 1 </code></pre> <p...
<h3 id="tabulating-te7c">Tabulating</h3> <p>First <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><strong><code>cut()</code></strong></a> the amounts into ranges and then <a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html" rel="nofol...
python|pandas|numpy|matplotlib
4
354,892
68,387,618
RuntimeError: mat1 and mat2 shapes cannot be multiplied
<p>I'm trying to input a 5D tensor with shape ( 1, 8, 32, 32, 32 ) to a VAE I wrote:</p> <pre><code>self.encoder = nn.Sequential( nn.Conv3d( 8, 16, 4, 2, 1 ), # 32 -&gt; 16 nn.BatchNorm3d( 16 ), nn.LeakyReLU( 0.2 ), nn.Conv3d( 16, 32, 4, 2, 1 ), # 16 -&gt; 8 nn.BatchNor...
<p>This line</p> <pre><code>x = x.view( -1, x.size( 1 )) </code></pre> <p>Means you leave the second dimension(channel) as is and put everything else at the first dimension(batch).</p> <p>And as the output of the <code>self.encoder</code> is <code>(1, 48, 4, 4, 4)</code>, doing that means you'll get <code>(64, 48)</cod...
python|neural-network|pytorch|autoencoder
3
354,893
68,289,298
How do I write a function that removes duplicate customers from a database while adding the customer column sales? Keeping customers unique with sales
<p>I have a customer database, because of confidentiality cannot share it, but here is an example of it:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Sales</th> <th>Email</th> <th>Etc</th> </tr> </thead> <tbody> <tr> <td>01</td> <td>Pablo</td> <td>$1000</td> <td...
<p>I got it:</p> <pre><code>def groupby_sum(df, group_vars, agg_var='Total', sort_var='Total'): ''' Return: a Pandas dataframe object where rows have been gruped by a given group of columns (categorical variables). The resulting dataframe will be sorted descending from highest to lowest amount of deaths and th...
python|pandas|duplicates
0
354,894
68,095,609
Extracting Multiple Parameters from a String using Regex or Pandas
<p>I'm working with the following DataFrame</p> <pre><code>0 NaN 1 {u'bphigh': u'120', u'bplow': u'70', u'weight'... 2 NaN 3 {u'bphigh': 120, u'bplow': 60, u'weight': u'10... 4 ...
<pre><code>from ast import literal_eval </code></pre> <p>try:</p> <pre><code>df['vital']=df['vital'].astype(str).map(lambda x:literal_eval(x) if x!='nan' else float('NaN')) #In the above code we are making the string values to actual dictionary via #map() method we are iterating the values of 'vital' column and conve...
python|regex|pandas
2
354,895
68,425,656
Panda: Get row number by comparing value of different column
<p>I have a dataframe consist of the following, and want to add a new column based on high - open &lt; x number and High.rowNum &gt;= Open.rowNUm</p> <p>basically I just want to get the first Row Num that match the criteria above and store it as different column</p> <div class="s-table-container"> <table class="s-table...
<p>As per my understanding based on your question and comment, you need 'S/N' in the new column which satisfy the criteria .. so simply you can use <code>apply</code> function in dataframe and store result as new column</p> <pre class="lang-py prettyprint-override"><code>df['New'] = df.apply(lambda x: x['S/N'] if x['Hi...
python|pandas|dataframe
0
354,896
68,310,729
No module named 'pycaret
<p>I am getting this error in my VSCODE:</p> <pre><code>No module named 'pycaret </code></pre> <p>my query is this:</p> <pre><code>from pycaret.classification import * </code></pre> <p>I have installed pycaret, may I know how can I solve this error?</p>
<p>Make sure you install pycaret in a clean python environment. Then enable the python environment before trying to run the script.</p>
python|pandas|numpy|visual-studio-code|pycaret
0
354,897
68,394,247
Pandas create a new column after dataframe gets df.style
<p>I'm trying to add a new column after dataframe gets df.style. However, I got an error message:</p> <blockquote> <p>'Styler' object does not support item assignment</p> </blockquote> <p>Below is my code:</p> <pre><code>import pandas as pd df = pd.DataFrame([[10,3,1], [3,7,2], [2,4,4]], columns=list(&quot;ABC&quot;)) ...
<p>You cannot processing styler object by add data processing like add new column, you need add it before:</p> <pre><code>df2['sum'] = None subsets = pd.IndexSlice[:, 'A'] df2 = df.style.applymap(lambda x: 'background-color: yellow', subset = subsets) </code></pre>
python|pandas|dataframe|styles
0
354,898
68,222,241
Setting MacOS target version for Bazel build
<p>I'm trying to build the TensorFlow Lite C library on MacOS 11.4. I need the built library to be able to run on MacOS 10.13 or newer. However, something in the build toolchain sets the target OS to 11.3, so that the full compile commands printed by <code>-s</code> look like this</p> <pre><code>(cd /private/var/tmp/_b...
<p>The way that works is Bazel command line option <code>--macos_minimum_os</code> (or related <code>--macos_minimum_os</code>).</p> <p>It's right there in the documentation if you know what to search for, but apparently not discoverable by Google. I found it by reading Bazel source.</p>
macos|tensorflow|bazel
1
354,899
68,213,932
numpy where search multiple conditions with a precomputed series
<p>I have a list with a multiple series with booleans and pandas DataFrame. The number of series in the list varies.</p> <pre><code>s1 = {Series: (4,)} (0, True) (1, True) (2, True) (3, True) s2 = {Series: (4,)} (0, True) (1, True) (2, True) (3, False) list_with_series = [s1, s2] df = {DataFrame: (4, 8)} </code></pre>...
<p>When you write <code>' &amp; '.join(...)</code> in this case, the expectancy is that you'll pass strings, not series. This is the error.</p> <p>In this case, you could use:</p> <pre><code>import numpy as np np.logical_and.reduce([s.values for s in list_with_series]) </code></pre>
python|pandas|numpy
1