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
11,900
37,247,523
pandas groupby on columns
<p>I am trying following example, where I need to <strong>group on columns</strong>:</p> <pre><code>import pandas as pd import numpy as np y = pd.DataFrame(np.random.randint(0,10, (20,30)).astype(float), columns = pd.MultiIndex.from_tuples( list(zip(np.arange(30), ...
<p>The <code>groupby</code> function is applied column-wise to your dataframe, however, when the dataframe is transposed, rows become columns and vice-versa.</p> <p>This wouldn't be an issue if it weren't for the fact that your rows and columns aren't both multi-index. However, since you're treating your row index as ...
python|pandas|grouping
0
11,901
37,147,592
Multiple inputs multivariate data visualisation
<p>I am trying to visualise multivariate data model by reading them from multiple input files. I am looking for a simple solution to visualise multiple category data read from multiple input csv files. The no. Of rows in inputs range from 1 to 10000s in individual files. The format is same of all the inputs with 4 co...
<p><strong>UPDATE:</strong></p> <p>with different colors:</p> <pre><code>colors = dict(low='DarkBlue', high='red', part='yellow', medium='DarkGreen') fig, ax = plt.subplots() for grp, vals in df.groupby('col4'): color = colors[grp] vals[['col2','col3']].plot.scatter(x='col2', y='col3', ax=ax, ...
python|pandas|data-visualization|multivalue|multivariate-testing
2
11,902
42,024,039
Error with plt.savefig in the loop
<p>At first, I have to say that I'm a true beginner in Python (and in programming itself) so this may be a silly question but I couldn't find a solution. </p> <p>I load data from 3 different .csv files then make some calculations and in the end i want to save 3 heatmaps. My problem is with saving. When i use <code>plt...
<p>You override <code>i</code> here:</p> <pre><code>instrumenty = ['gold','sp500','dax'] for i in instrumenty: i = pd.read_csv(i+'_m.csv', sep=',') </code></pre> <p>Better use <code>name</code>:</p> <pre><code>for name in instrumenty: # use `name` i = pd.read_csv(name +'_m.csv', sep=',') i['Miesiąc']...
python|python-3.x|pandas|matplotlib
3
11,903
37,867,092
Sort and Filter data from a Panda Dataframe according to date range
<p>My dataframe has two columns: (i) a date column in a string format and (ii) an int value. I would like to convert the date string into a date object and then filter and sort the data according to a date range. Converting one string to a date worked fine with: </p> <pre><code>date = dateutil.parser.parse(date_string...
<p>You want to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>pd.to_datetime</code></a>:</p> <pre><code>df['etime'] = pd.to_datetime(df['etime'], format="%H:%M:%S") </code></pre>
python|pandas|filter|dataframe
2
11,904
37,651,648
Applying same calcuation to each element of dataframe in python
<p>I have a dataframe like this.</p> <pre><code> user tag1 tag2 tag3 0 Roshan ghai 0.0 1.0 1.0 1 mank nion 1.0 1.0 2.0 2 pop rajuel 2.0 0.0 1.0 3 random guy 2.0 1.0 1.0 </code></pre> <p>I have to apply a calculation to each row. which is for each element x </p> <pre><code>...
<p>You can try this:</p> <pre><code>import io temp = u""" user tag1 tag2 tag3 0 Roshan-ghai 0.0 1.0 1.0 1 mank-nion 1.0 1.0 2.0 2 pop-rajuel 2.0 0.0 1.0 3 random-guy 2.0 1.0 1.0""" df = pd.read_csv(io.StringIO(temp), delim_whitespace=True) maxtag1 = df.tag1.max() maxtag2 = ...
python|pandas|dataframe|data-analysis|large-data
1
11,905
37,650,913
Convert each cell of a Pandas's column from list to word-count dictionary?
<p>There's a column of a DataFrame, <code>df['Title']</code>, where each row is a book sold at a location, <code>LOCATION_ID</code>. I'd like to group the <code>df</code> by <code>LOCATION_ID</code> and create a new DataFrame that has two columns: <code>LOCATION_ID</code> and a <code>Title-Count</code>dictionary of th...
<p>Use <code>agg</code> instead of <code>apply</code>:</p> <pre><code>import numpy as np import pandas as pd from collections import Counter prng = np.random.RandomState(0) df = pd.DataFrame({'LOCATION_ID': prng.choice([1, 2, 3], 1000), 'TITLE': [''.join(prng.choice(list("abcd"), 3)) for _ in range(1000)]}) df.head() ...
python|dictionary|pandas|counter
3
11,906
37,684,836
groupby and normalize over two arrays
<p>I have a<code>DataFrame</code> where the columns are a <code>MultiIndex</code>. The first <code>level</code> specifies <code>'labels'</code>, the second specifies <code>'values'</code>. A <code>'label'</code> in the <code>(i, j)</code> position of <code>df.labels</code> corresponds to the <code>'value'</code> in th...
<p>To get the normalized values, you could:</p> <pre><code>new_values = pd.DataFrame(data=np.zeros(df['values'].shape)) for v in np.unique(df['labels']): mask = df['values'].where(df['labels'].isin([v])) new_values += mask.div(mask.sum().sum()).fillna(0) df.loc[:, 'values'] = new_values.values </code></pre> <...
python|numpy|pandas|group-by|multi-index
2
11,907
31,519,197
Python + OpenCV = How to crop circle?
<p>The below is the code:</p> <pre><code>self.img = cv2.imread(image,) circle = cv2.HoughCircles(self.img, 3, dp=1.5, minDist=1000, minRadius=100, maxRadius=1000) red = (0,0,255) x = circle[0][0][0] y = circle[0][0][1] r = circle[0][0][2] cv2.circle(self.img, (x, y), r, red, 2) x - X ...
<p>After circles=cv2.HoughCircles(img,...)</p> <pre><code>if len(circles) == 1: x, y, r = circles[0][0] print x, y, r mask = np.zeros((w0,h0),dtype=np.uint8) cv2.circle(mask,(x,y),r,(255,255,255),-1,8,0) #cv2.imwrite(argv[2],mask) out = img*mask white = 255-mask cv2.imwrite(argv[2],out+w...
python|opencv|numpy|crop|geometry
2
11,908
47,850,352
Why does operating on what seems to be a copy of data modify the original data?
<p>Let's quote numpy manual: <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="noreferrer">https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing</a></p> <blockquote> <p>Advanced indexing is triggered when the selection object, obj, is a non-tupl...
<p>While statements</p> <pre><code>a = expr </code></pre> <p>and</p> <pre><code>a[x] = expr </code></pre> <p>look similar, they are actually fundamentally different. The first binds the name 'a' to expr. The second is more or less <a href="https://docs.python.org/3/reference/datamodel.html#emulating-container-types...
python|arrays|numpy|copy
6
11,909
47,543,392
Does the aggregate function in pandas groupby treat builtin functions differently?
<p>Came across this seemingly odd behaviour while discussing <a href="https://stackoverflow.com/a/47543066/9017455">https://stackoverflow.com/a/47543066/9017455</a>.</p> <p>The OP had this dataframe:</p> <pre><code>x = pd.DataFrame.from_dict({ 'cat1':['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'], 'cat2':['X', 'X',...
<p>This behaviour seems to have changed by now. At least here in version 0.23.0, both <code>lambda x: set(x)</code> and <code>set</code> behave identically:</p> <pre><code>In [6]: x.groupby('cat1').agg(set) Out[6]: cat2 cat1 A {Y, X} B {Y} C {Y, Z} In [7]: x.groupby('cat1').agg(lambda x: set(x)...
python|pandas|pandas-groupby
1
11,910
58,631,882
SSH into Docker? or docker on SSH? and I need command
<p>I'm new to DL, and docker and even not familiar with Linux and internet things (SSH and port.. DNS things.. part of them are only existing in my mind). Thus, I'd be so much happy with "specific explanation + command" (or reference sites).</p> <p>My basic questions are:</p> <ol> <li><p>what is superior concept betw...
<p>Your question is extensive and somewhat unclear.</p> <p>It's good practice here (and you'll likely receive useful responses) if you ask specific questions.</p> <p>I encourage you to Google some of these topics ("What is Docker?", "What is SSH?").</p> <p>That said, because you're a noob, I'm going to take a guess ...
linux|docker|ssh|port|pytorch
1
11,911
70,206,678
Scraping dynamic data selenium - Unable to locate element
<p>I am very new to scraping and have a question. I am scraping worldometers covid data. As it is dynamic - I am doing it with selenium.</p> <p>The code is the following:</p> <pre><code>from selenium import webdriver import time URL = &quot;https://www.worldometers.info/coronavirus/&quot; # Start the Driver driver = ...
<p>To scrape table within <a href="https://www.worldometers.info/coronavirus/" rel="nofollow noreferrer">worldometers covid data</a> you need to induce <a href="https://stackoverflow.com/questions/59130200/selenium-wait-until-element-is-present-visible-and-interactable/59130336#59130336">WebDriverWait</a> for the <a hr...
python|pandas|dataframe|selenium|web-scraping
2
11,912
70,249,135
How to add a new column in the dataframe respecting a python rule?
<p>I have the following dataframe:</p> <pre><code> import numpy as np import pandas as pd df = pd.DataFrame({'Name': ['Station', 'Station', 'Sensor', 'Sensor', 'Sensor', 'Sensor', 'Station', 'Station'], 'id': [10, 10, 11, 11, 12, 12, 13, 13]}...
<p>If you want to only use <code>pandas</code> without <code>numpy</code>, you can use <code>loc</code> and <code>fillna</code>:</p> <pre><code>df.loc[df.id.isin(array_id),'class'] = 'class1' df['class'].fillna('class2',inplace=True) </code></pre> <hr /> <pre><code> Name id class 0 Station 10 class1 1 Stati...
python|pandas|dataframe
0
11,913
70,369,770
How to resolved this error: ValueError: could not convert string to float: 'clinical1'?
<p>I am trying to execute the following code:</p> <pre><code>from sklearn.ensemble import RandomForestClassifier import numpy as np from sklearn.model_selection import cross_validate from sklearn.metrics import fbeta_score, make_scorer import keras.backend as K from sklearn.metrics import confusion_matrix from sklearn....
<p>Syntax:</p> <pre><code>numpy.loadtxt(fname, dtype='float', comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0) </code></pre> <p>If your file has text information, such as column headers for example, then when you read the file and it expects information of type float, this...
python|pandas|numpy|tensorflow|scikit-learn
0
11,914
70,341,655
How do you sort column values in pandas to only include certain values?
<p>Essentially my program finds the person with the most yards per carry, but finds the person with only a couple of attempts.</p> <p>I'm trying to filter out the rest of the players so that I only get people with above 200 yards so far in the season.</p> <p>All of the data comes from a CSV file and so it has to be don...
<p>You filter when you did <code>yards_leader = wide_receiver.loc[wide_receiver['ypc'] == wr_ypc]</code>, so now just use that same concept.</p> <pre><code>import pandas as pd sample_dict = {'id': {0: 11706, 1: 11791, 2: 11792, 3: 11793, 4: 11810}, 'name': {0: 'Mark Ingram', 1: 'Rob Gronkowski', 2: 'Marcedes Lewis', 3...
python|pandas
0
11,915
70,256,939
Converting parameter unit
<p>I need to evaluate the following equation:</p> <p><img src="https://i.stack.imgur.com/SQpDu.png" alt="enter image description here" /></p> <p>I have the following parameters values:</p> <pre><code>C_gamma = 8.846E-05 m/GeV3 Gamma = 11741.707101355101 beamEnergy = 6.0E9 #eV I2 = 0.2803660599555248 E0 = (beamEnergy/Ga...
<p>With float arithmetics you should always have the fact of <a href="https://stackoverflow.com/questions/588004/is-floating-point-math-broken">Is floating math broken</a> - which is documented here: <a href="https://docs.python.org/3/tutorial/floatingpoint.html" rel="nofollow noreferrer">python.org &quot;15. Floating ...
python|numpy|math
0
11,916
56,238,204
Multiply each element in one row and append new column in same dataFrame?
<p>Want to multiply each element of a row and then add new result column for every row of the dataFrame.</p> <p>I am able to extract each row from dataFrame. </p> <pre><code>df_temp.values[0,:] array([18, 10, 5, 11, -2], dtype=int64) </code></pre> <p>But am not able to proceed after that. Tried using the <code>mul(...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>df.assign()</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.prod.html" rel="nofollow noreferrer"><code>df.prod()</code></a> on <co...
python|python-3.x|pandas|numpy|dataframe
3
11,917
56,356,111
Getting values from time indexed pandas dataframe for a specific time within the two timestamps
<p>I have the following pandas dataframe df:</p> <pre><code> C1 C2 C3 Date 2000-01-01 00:00:00 2 175 160 2000-01-01 01:00:00 4 192 164 2000-01-01 02:00:00 6 210 189 2000-01-01 03:00:00 8 217 199 2000-01-01 04:00:00 10 176 158 </code></pre> <p>from...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.asof.html" rel="nofollow noreferrer"><code>DataFrame.asof</code></a> method:</p> <pre><code>print(df['C1'].asof(my_specific_time)) 4 </code></pre>
python|pandas|datetime
2
11,918
56,401,313
Keep all cells above given value in pandas DataFrame
<p>I would like to discard all cells that contain a value below a given value. So not only the rows or only the columns that, but for for all cells.</p> <p>Tried code below, where all values in each cell should be at least 3. Doesn't work. </p> <pre><code>df[(df &gt;= 3).any(axis=1)] </code></pre> <p>Example</p> <p...
<p>You can check if the value is >= 3 then drop all rows with NaN value.</p> <pre><code>df[df &gt;= 3 ].dropna() </code></pre> <p>DEMO:</p> <pre><code>import pandas as pd my_dict = {'A':[1,5,6,3],'B':[9,9,1,3],'C':[1,1,3,5]} df = pd.DataFrame(my_dict) df A B C 0 1 9 1 1 5 9 1 2 6 1 3 3 3...
python|pandas
1
11,919
55,977,210
Error in Keras custom loss function - tensotflow
<p>I am fairly new to tensorflow and I was following the answer to the question below in order to build a custom loss function in Keras that considers only the top 20 predictions.</p> <p><a href="https://stackoverflow.com/questions/48096812/how-can-i-sort-the-values-in-a-custom-keras-tensorflow-loss-function">How can ...
<p>Use:</p> <pre><code>y_pred_top_k, y_pred_ind_k = tf.nn.top_k(y_pred[:,0], top) </code></pre> <p><code>y_pred[:,0]</code> gets the predicted values of the full batch as a rank 1 tensor.</p> <p><strong>Another Problem:</strong></p> <p>However, you will still end up with problem with the last batch. Say your batch ...
python|tensorflow|keras
1
11,920
55,965,492
How to solve triadiagonal matrix using Numpy\Python
<p>I'm working on a project and i want to solve a system of tridiagonal matrix with9 equations with 9 unknowns in 20 steps. How do i go about the code using numpy\python.</p> <p>Here is an example <a href="https://i.stack.imgur.com/Rf95s.png" rel="nofollow noreferrer">Tridiagonal Matrix</a></p> <p>I am solving for ...
<p>Step 1: perform the forward sweep to eliminate the sub-diagonal;</p> <p>Step 2: perform back substitution to eliminate the super-diagonal.</p> <p>This is the Thomas algorithm.</p>
python|algorithm|numpy|matrix|diagonal
0
11,921
64,756,128
How to read a large .jl file in python
<p>I'm trying to read the following dataset and turn it into a pandas dataframe: <br> <a href="https://www.kaggle.com/marlesson/meli-data-challenge-2020" rel="nofollow noreferrer">https://www.kaggle.com/marlesson/meli-data-challenge-2020</a></p> <p>It is a file with lines with the following format:<br></p> <pre><code>{...
<p>The file I was trying to read was a JSON file with multiple objects. Pandas <code>read_json()</code> supports a <code>lines</code> argument for data like this: <br></p> <pre><code>%%time df = pd.read_json('/kaggle/input/meli-data-challenge-2020/item_data.jl', lines=True) Output: CPU times: user 14.1 s, sys: 3.31 s...
python|pandas|dataframe
4
11,922
39,628,497
Difference between normed plt.xcorr at 0-lag and np.corrcoef
<p>I am working on a cross correlation between two relatively small time series, but in trying to accomplish I am running into a problem I cannot reconcile myself. To begin, I understand the dependence between <code>plt.xcorr</code> and <code>np.correlate</code>. However, I am having trouble reconciling the difference ...
<p>Calculation of standard "Pearson product-moment correlation coefficient" is using samples, shifted by mean values. Cross-correlation coefficient doesn't use normalized samples. Other than that, computation is similar. But still those coefficients have different formulas and different meaning. They are equal only if ...
python|numpy|correlation|cross-correlation
2
11,923
44,103,188
How can I select one matrix' vectors which in another matrix
<p>I have two matrices:</p> <pre><code>a = [[1,3,4],[2,5,3],[2,4,6],[6,5,3]] b = [[2,4,5],[2,4,6],[1,3,4]] </code></pre> <p>and I want to choose [2,4,6],[1,3,4] in b, which is in a. </p> <p>Since a and b are large, </p> <pre><code>for v in b: if v in a: </code></pre> <p>is expensive.</p> <p>Can anybody t...
<p>What you want is an equivalent of <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow noreferrer">numpy.in1d</a>, for 2-dimensional matrices. I wrote such a function a while ago</p> <pre><code>def in2d(arr1, arr2): """Generalisation of numpy.in1d to 2D arrays""" ass...
python|pandas|numpy
1
11,924
69,437,808
Repeat values in a column n times
<p>I have the following dataframe</p> <pre><code> Code 1 3 4 5 </code></pre> <p>I want to repeat each code value 5 times so that output is:</p> <pre><code> Code 1 1 1 1 1 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 </code></pre> <p>np.repeat does not seem to w...
<p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.repeat.html" rel="nofollow noreferrer"><code>repeat</code></a> the index:</p> <pre><code>df.loc[df.index.repeat(5)] </code></pre>
python|pandas|dataframe|numpy
1
11,925
69,516,225
Increasing num of layers in LSTM increases the input dimensions in Pytorch?
<p>This is my LSTM model and I am finding a peculiar problem while training it.</p> <pre><code>class LSTM1(nn.Module): def __init__(self, num_classes, input_size, hidden_size, num_layers, seq_length,drop_prob=0.0): super(LSTM1, self).__init__() self.num_classes = num_classes #number of classes self.num_laye...
<p>The issue is that you are flattening <code>hn</code>, according to the documentation page, its shape is <code>(D*num_layers, N, Hout)</code>, <em>i.e.</em> it depends on the number of hidden layers. So you will either have to change the fully connected that is following or only take the last hidden state of your LST...
pytorch|lstm
2
11,926
69,615,585
unable to start Airflow webserver with python 3.10
<p>I installed python 3.10, airflow version 2.2.0 but when I tried to run cmd : airflow webserver I got :</p> <pre><code>C:\Users\*\AppData\Local\Programs\Python\Python310\lib\site-packages\airflow\configuration.py:270: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Us...
<p>Please take a look at this link. <a href="http://airflow.apache.org/docs/apache-airflow/stable/installation/prerequisites.html" rel="nofollow noreferrer">http://airflow.apache.org/docs/apache-airflow/stable/installation/prerequisites.html</a></p> <p>Airflow 2.2 is not certified to run on python 3.10</p>
python|numpy|airflow
3
11,927
69,622,884
How to draw a rounded edges for a polygon having its x,y coordinates?
<p>I need to draw polygon from X, Y coordinates but with rounded corners I have the points of X, Y</p> <p>My code is below, however if there is another library, I can use it.</p> <p>Here my output image:</p> <p><img src="https://i.stack.imgur.com/Zsl8r.png" alt="Test image" /></p> <p>and this is the code</p> <pre><code...
<p>You can do it by using the <a href="https://pypi.org/project/Pillow/" rel="nofollow noreferrer">Pillow</a>'s <a href="https://pillow.readthedocs.io/en/latest/reference/ImageDraw.html" rel="nofollow noreferrer"><code>ImageDraw</code></a> module by first using the coordinates to draw a polygon and then outlining it wi...
python|numpy|opencv|drawing|polygon
0
11,928
69,441,834
Check if data pandas.series value contains numeric character
<p>Is there a way to check if a pandas series value contains <em>any</em> numeric characters and replace those who does not contain any with NaN? <code>Series.str.isnumeric</code> only checks whether all characters are numeric.</p> <p>Given the following series:</p> <pre><code>d = {'a': &quot;Python&quot;, 'b': &quot;$...
<p>Use <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow noreferrer"><code>any</code></a> + <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>apply</code></a>:</p> <pre><code>res = ser.apply(lambda x: x if any(c.isnumeric() for c i...
python|pandas
1
11,929
69,573,460
Combine elements within a group and get number of occurences across groups using pandas
<p>The data I'm analyzing has a structure similar to this one:</p> <pre><code>df = pd.DataFrame( { &quot;group&quot;: [&quot;group1&quot;, &quot;group1&quot;, &quot;group2&quot;, &quot;group2&quot;, &quot;group2&quot;, &quot;group3&quot;, &quot;group3&quot;, &quot;group3&quot;, &quot;group4&quot;, &quot;gro...
<p>IIUC you are looking for <code>combinations</code>:</p> <pre><code>from itertools import combinations out = (df.sort_values([&quot;group&quot;, &quot;letter&quot;]) .groupby(&quot;group&quot;)[&quot;letter&quot;] .apply(lambda d: pd.DataFrame(combinations(d, 2), columns=[&quot;letter_x&quot;, &qu...
python|pandas|merge
0
11,930
69,547,964
Making a barplot with elements with different values under different conditions, where values for each element are grouped and colored by element
<p>First of all I would like to say that I've been looking up for a solution for several days, and I've tried several workarounds, but I've not been able to find a proper solution to what I'm trying to do.</p> <p>So, the thing is the following. I have a dataframe with some elements that have a particular value under a ...
<p>I am not too much a fan of these prepackaged plot modules such as seaborn. There may be a way to do this with seaborn more readily. Here however is a matplotlib native approach.</p> <p>The trick is to compute where the centers are of your labels. Then merely iterating through the conditions and keeping track of wher...
python|pandas|matplotlib|seaborn|bar-chart
0
11,931
69,307,455
Seeking Advice on Python Mathematical Loop
<p>I am using python to calculate the forward, central, and backward finite differences of f(x)=cos(x). I can get them to plot when it is running each iteration at a set step size (h). However, my main task is to have the step size be reduced by a factor of two for each iteration of the finite difference methods. Here ...
<p>Assuming that you plotted the figure (used h) <strong>inside the while loop's body</strong>, what you said should work.</p> <p>In more detail:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt f = lambda x: np.cos(x) x=np.linspace(-np.pi, np.pi, num=50) #x should be initialized. this line was mi...
python|numpy|math|python-requests
1
11,932
69,617,156
Check if unordered pair of two columns values is the same and reduce (directional sum) using groupby
<p>I have a dataframe df:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Source</th> <th>Dest</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>B</td> <td>10</td> </tr> <tr> <td>A</td> <td>B</td> <td>7</td> </tr> <tr> <td>B</td> <td>A</td> <td>6</td> </tr> <tr> <td>A</td> <td>...
<p>We need <code>np.sort</code> then can trim the value with the diff</p> <pre><code>df1 = df.copy() l = ['Source','Dest'] df1[l] = np.sort(df1[l].values,axis=1) df1.loc[df1[l].ne(df[l]).all(1),'Value'] *= (-1) df1 = df1.groupby(l)['Value'].sum().reset_index() df1 Out[83]: Source Dest Value 0 A B 11 1 ...
python|pandas
1
11,933
41,097,567
How to avoid shape error when I change Keras' backend from Theano to Tensorflow?
<p>I tried to use Deep Semantic Similarity Model(DSSM): <a href="https://github.com/airalcorn2/Deep-Semantic-Similarity-Model/blob/master/deep_semantic_similarity_keras.py" rel="nofollow noreferrer">https://github.com/airalcorn2/Deep-Semantic-Similarity-Model/blob/master/deep_semantic_similarity_keras.py</a> on Keras u...
<p>(Converted from a comment to an answer at @dga's request)</p> <p>I asked our resident Keras expert, and his response was: Looking at the error message and code, one can infer that the final output prob is a scalar, whereas it should be a 2D array (one scalar probability per batch entry). The problem is likely to be...
python|tensorflow|deep-learning|theano|keras
0
11,934
53,824,342
Replacing a certain value in a dataframe
<p>I have created a dataframe by reading in two different datasets as csv files.</p> <p>At the minute, the data frame prints out something like this:</p> <pre><code> Name Value 1 Value 2 Value 3 Value 4 Value 5 0 A 1 3 4 5 2 1 B 4 ...
<h3><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> + Boolean indexing</h3> <p>You can use <code>loc</code> with Boolean indexing:-</p> <pre><code>df.loc[df['Value 3'].eq(6) &amp; df['Name'].eq('B'), 'Value 3'] = 8 </code></pre>...
python|pandas|dataframe
1
11,935
38,095,546
Is this a bug in Pandas? FloatingPointError on ewm().std()
<p>When I execute the following, I get a FloatingPointError.</p> <pre><code>import traceback import warnings import sys import pandas as pd import numpy as np np.seterr(all='raise') def warn_with_traceback(message, category, filename, lineno, file=None, line=None): traceback.print_stack() log = file if hasattr...
<p><code>np.seterr(all='raise')</code> is causing the issue. </p> <p>Check this out: <a href="https://stackoverflow.com/questions/35657516/pandas-floatingpointerror-with-np-seterrall-raise-and-missing-data">pandas: FloatingPointError with np.seterr(all=&#39;raise&#39;) and missing data</a></p> <p>The output of <code>...
python|numpy|pandas
0
11,936
38,130,221
How to optimize changing a value in a Pandas Data Frame column
<p>I'm trying to find how much a stock will change from a given day to n days in the future. The only problem is that it takes about a minute to run this on 1000 lines of data and I have millions of lines. I think the 'lag' is caused by the line:</p> <p><code>stocks[0][i][string][line[index]] = adjPctChange(line[adj...
<p>You shouldn't loop over a DataFrame; just do everything with array functions.</p> <p>Before:</p> <pre><code>In [30]: df Out[30]: date open close adjClose closeShift1 closeShift2 0 19980102 20.3835 20.4417 NaN NaN 0.984507 1 19980105 20.5097 20.5679 NaN 0.984507 ...
python|pandas
2
11,937
66,156,993
Aggregating and custom function pandas
<p>I have a dataframe like the following:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Label</th> <th>Indicator</th> <th>Value1</th> <th>Value2</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>77</td> <td>50</td> <td>50</td> </tr> <tr> <td>A</td> <td>776</td> <td>60</td> <td>70</td> </tr>...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html?highlight=get%20dummies#pandas.get_dummies" rel="nofollow noreferrer">get_dummies</a> to replace the step where you split your indicator separate columns. Then you can use those bool values to carry out your aggre...
python|python-3.x|pandas
1
11,938
52,782,246
Python - Merge dataframe name contains in list
<p>I have 2 dataframe (for now I am saying 2 but we can have n number of dataframe). And the name of the dataframe is in a list. I want to join all the dataframe whose names are present in the list</p> <pre><code>import pandas as pd data1 = [['Alex',10],['Bob',12],['Clarke',13]] df1 = pd.DataFrame(data1,columns=['Name...
<p>you need to set the name as index then do <code>concat</code> </p> <pre><code>list = [df1,df2] pd.concat([x.set_index('Name') for x in list],axis=1) Out[270]: Age Age Alain NaN 12.0 Alex 10.0 NaN Bob 12.0 NaN Clarke 13.0 NaN David NaN 10.0 Rob NaN 13.0 </code></pre> <p>Or ...
python|pandas
1
11,939
46,283,564
panda dataframe: how to copy some columns in others according to a value in the row
<p>Hello I am dealing with a dataframe like below:</p> <pre><code> yearStart 2014 2015 2016 2017 2018 2019 0 2015 0 150 200 0 0 0 1 2016 0 0 200 140 35 10 2 2017 0 0 0 20 12 12 </code></pre> <p>Typically, it is a...
<pre><code>df=df.replace({0:np.nan}) df=df.loc[:,df.isnull().sum(0).ne(3)] </code></pre> <p>Option 1 :</p> <pre><code>df.apply(lambda x : (x[x.notnull()].values.tolist()+x[x.isnull()].values.tolist()),1).fillna(0) </code></pre> <p>Out[145]: </p> <pre><code> yearStart 2015 2016 2017 2018 2019 0 2015.0 ...
python|pandas|dataframe
1
11,940
46,177,826
Groupby on condition and calculate sum of subgroups
<p>Here is my data:</p> <pre><code>import numpy as np import pandas as pd z = pd.DataFrame({'a':[1,1,1,2,2,3,3],'b':[3,4,5,6,7,8,9], 'c':[10,11,12,13,14,15,16]}) z a b c 0 1 3 10 1 1 4 11 2 1 5 12 3 2 6 13 4 2 7 14 5 3 8 15 6 3 9 16 </code></pre> <h1>Question:</h1> ...
<p>It might just be easiest to change the order of operations, and filter against your criteria first - it does not change after the <code>groupby</code>. </p> <pre><code>z.query('4 &lt; b &lt; 9').groupby('a', as_index=False).c.sum() </code></pre> <p>which yields</p> <pre><code> a c 0 1 12 1 2 27 2 3 15 <...
python|pandas|dataframe|group-by|pandas-groupby
3
11,941
46,564,427
How to not re-initialize the pretrained loaded model in Tensorflow?
<p>I have loaded a pretrained model (<code>Model 1</code>) using the following code: </p> <pre><code>def load_seq2seq_model(sess): with open(os.path.join(seq2seq_config_dir_path, 'config.pkl'), 'rb') as f: saved_args = pickle.load(f) # Initialize the model with saved args model = Model1(saved_ar...
<p>All variables that are restored using a saver don't need to be initialized. Therefore, instead of using <code>tf.initialize_all_variables()</code> you can use <code>tf.variables_initializer(var_list)</code> to only initialize the weights of the second network. </p> <p>To get a list of all the weights of the second ...
python|tensorflow|deep-learning
1
11,942
58,206,686
tf.argsort and np.argsort gave different results
<p>So I want to argmax y0, and I tested it in numpy and tensorflow 2, which results are different. Couldn't figure out why.</p> <pre><code>maxy0 = np.amax(y0) e0 = np.exp(y0 - maxy0) p0 = e0 / np.sum(e0) y0 = np.log(1e-20 + p0) print(y0) [[-46.0517 -46.0517 -46.0517 ... -46.0517 -46.0517 -46.0517]] </code></pre> <pre...
<p>Try changing the stable argument to <strong>True</strong> as by default it is <strong>False</strong> in tf.argsort. Please refer <a href="https://www.tensorflow.org/api_docs/python/tf/argsort" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/argsort</a></p>
python|numpy|tensorflow|tensorflow2.0
0
11,943
69,016,985
finding duplicates with tolerance and assign to a set in pandas
<p>Input</p> <pre><code> Name A B C 0 aa 0.002667 2.5 13.5 1 bb 0.003400 2.5 13.7 2 cc 0.003600 1.0 13.6 3 dd 0.003667 1.0 13.6 4 aa 0.003667 1.0 13.6 5 bb 0.007600 1.0 13.6 6 cc 0.007000 1.0 13.6 7 dd 0.007000 1.0 13.6 </code></pre> <p>Allowed Tolerance:</p> <pre...
<p>Here is a way that is <em>relatively</em> fast, and can be adapted for other proximity query types (for example, finding sets of points that are within Euclidean distance of each other). It treats proximity in a transitive way: if <code>a</code> is within tolerance of <code>b</code>, and <code>b</code> is within tol...
python|pandas|pandas-groupby
5
11,944
44,781,179
integers become floats when concatenating pandas dataframes
<p>I have 2 pandas dataframes:</p> <p>df1 is an empty dataframe: import pandas as pd import numpy as np</p> <pre><code>df1 = pd.DataFrame(columns=['Start','End','Duration']) df1 Out[1]: Empty DataFrame Columns: [Start, End, Duration] Index: [] </code></pre> <p>df2 contains:</p> <pre><code>df2 = pd.DataFrame(np.arr...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow noreferrer">astype</a>:</p> <pre><code>df1[['Start','End']] = df1[['Start','End']].astype(int) </code></pre> <p>output:</p> <pre><code> Start End Duration 0 483 523 0.8 </code></pre>
python|pandas|dataframe
1
11,945
44,768,398
Loading multiple files and saving them as variables
<p>I need to load data from different files and save it as arrays. I have multple files named <code>file.n.project.dat</code> where n is 1-100. So far, it seems that using numpy is the best way to start. Each file is a 5 by 5 array. I need to be able to add/multiply arrays later on in my code.</p> <p>Right now I have ...
<p>Can you try appending each of the values to a list and then try to access the list elements as one by one to get values. <code> import numpy as np l = [] for i in range(1,101): l.append(np.loadtxt('file.' + str(i) + '.project.dat')) print l</code></p> <p>I believe your problem should be solved this way. l will...
python|numpy|data-manipulation
3
11,946
44,639,260
Retrieving an unnamed variable in tensorflow
<p>I've trained up a model and saved it in a checkpoint, but only just realized that I forgot to name one of the variables I'd like to inspect when I restore the model.</p> <p>I know how to retrieve named variables from tensorflow, (<code>g = tf.get_default_graph()</code> and then <code>g.get_tensor_by_name([name])</c...
<p>First of all, following up on my first comment, it makes sense that <a href="https://www.tensorflow.org/api_docs/python/tf/get_collection" rel="nofollow noreferrer"><code>tf.get_collection</code></a> given a name scope is not working. From <a href="https://www.tensorflow.org/api_docs/python/tf/get_collection" rel="n...
tensorflow
7
11,947
61,043,714
create multiple or single csv file from complete txt files folder
<p>I need to convert my txt files to csv files for annotations to prepare my dataset for training. I tried to convert using pandas and it worked for single file by using this code:</p> <pre><code>import pandas as pd read_file = pd.read_csv (r'/Users/shwaitkumar/Downloads/models-master/research/object_detection/images...
<p>If you just want to convert all files to csv, you can use the os module to get a list of all files and loop through them:</p> <pre><code>import pandas as pd import os origin_path = r'/Users/shwaitkumar/Downloads/models-master/research/object_detection/images/annotations' destination_path = r'/Users/shwaitkumar/Do...
python|pandas
0
11,948
71,540,430
Python convert string to numpy array with dtype set
<p>I have a script that saves me a numpy array (<code>numpy.ndarray</code>) in a file which then looks like this:</p> <pre><code>[-1.18229054e-01 1.29475027e-01 1.23235974e-02 -6.50683045e-02 -9.55493823e-02 2.64045410e-02 -2.75938213e-03 -6.67368323e-02 9.00188163e-02 -2.10145377e-02 2.66856700e-01 9.40015819e...
<p>Okay I have found the problem as suggested by <a href="https://stackoverflow.com/users/901925/hpaulj">hpaulj</a> I had to remove the brackets. Which I tried before by using <code>encodingString[1:-1]</code> but as it seems there was another character at the end so I had to use <code>encodingString[1:-2]</code></p>
python|arrays|numpy|type-conversion
0
11,949
42,422,646
Keras train partial model issue (about GAN model)
<p>I came across a strange issue when using keras to implement GAN model.</p> <p>With GAN we need to build up G and D first, and then add a new Sequential model (GAN) and add(G), add(D) sequentially afterwards.</p> <p>Keras seems to backprop back to G (via GAN model) when I do <code>D.train_on_batch</code>, and I got...
<p>After strived for quite a long time, I finally get it that it's the Discriminator's BatchNormalization layer that caused the problem.</p> <p>If you just comment out the <code>model.add(kl.BatchNormalization())</code> in the Discriminator. It'll work fine.</p> <p>However, as @NassimBen shown, the functional API doe...
tensorflow|machine-learning|keras|generative-adversarial-network
1
11,950
69,899,063
KeyError building decision tree in jupyter:
<p>I'm building a scikit-learn decision tree in Python with a Jupyter notebook with this code:</p> <pre><code>from pandas import read_csv from sklearn import tree data = read_csv(&quot;data.csv&quot;) print(data.head()) A;B;C;D;E;F;Class 0 1;1;1;0;0;0;0 1 0;1;1;0;0;1;0 2 1;1;1;0;0;0;0 3 0;0;1;0;0...
<p>The error was that dataset .csv was only a column, because the separation between every data was with a &quot;;&quot; y not witha &quot;,&quot; Resolved with a .xlsx/.csv online converter.</p>
python|pandas|compiler-errors|decision-tree
0
11,951
69,829,293
Cannot slice DatetimeIndex using the datetime object
<p>I create a dataframe indexed by a datetime object and the index becomes a DatetimeIndex.</p> <pre><code>from datetime import datetime from datetime import timedelta from dateutil.parser import parse import pandas as pd datestr=[&quot;2021/2/3&quot;,&quot;2021/01/6&quot;,&quot;2021/2/4&quot;,&quot;2021/2/7&quot;,&q...
<p>The problem is that the index isn't sorted, so you can't properly slice on a date range. It's not a great error message from pandas. See here:</p> <p><a href="https://github.com/pandas-dev/pandas/issues/5821" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/5821</a></p> <p>So, to fix your exam...
python|pandas|datetime|slice
0
11,952
69,808,059
How to predict a certain time span into the future with recurrent neural networks in Keras
<p>I have the following code for time series predictions with RNNs and I would like to know whether for the testing I predict one day in advance:</p> <pre><code># -*- coding: utf-8 -*- &quot;&quot;&quot; Time Series Prediction with RNN &quot;&quot;&quot; import pandas as pd import numpy as np from tensorflow import k...
<p>So if your goal is to predict the next 96 steps given 96 steps in the past, I think you are over-complicating it with your current model. Why not start off with something simple like this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np import tensorflow as tf from sklearn....
python|tensorflow|machine-learning|keras|time-series
1
11,953
72,473,949
Stacking 2D arrays into a 3D array
<p>I have a very simple question but I just can't figure it out. I would like to stack a bunch of 2D numpy arrays into a 3D array one by one along the third dimension (depth).</p> <p>I know that I can use <code>np.stack()</code> like this:</p> <pre><code>d1 = np.arange(9).reshape(3,3) d2 = np.arange(9,18).reshape(3,3) ...
<p>Why don't you add directly d1, d2, d3 in a single stack (<code>np.stack((d1, d2, d3))</code>)? This is generally bad practice to repeatedly concatenate arrays.</p> <p>In any case, you can use:</p> <pre><code>np.stack((*foo, d3)) </code></pre> <p>or:</p> <pre><code>np.vstack((foo, d3[None])) </code></pre> <p>output:...
python|arrays|numpy
1
11,954
72,147,410
Retrieving values based on other values (dataframe) - how to make my code more efficient?
<p>So after much trying I've managed to get something a bit closer to what I intend to do.</p> <p>Scenario is as follows, a dataframe with many columns of which one contains unique values. Lets say this column is called &quot;Customer Name&quot;. This maps with a one to many match on a different column lets call that o...
<p>IIUC, and building on @Leo's answer, would this work?</p> <pre><code>df = pd.DataFrame({'Customer Name': ['Great Customer','Great Customer','Great Customer','Best Customer','Best Customer','Best Customer'], 'Customer Alias': ['Great Customer LDA', 'Great Customer Enterprises', 'Great Customer Japan', 'Best Offices',...
pandas
0
11,955
72,188,381
Checking for specific value change between columns in pandas
<p>I've got 4 columns with numeric values between 1 and 4, and I'm trying to see which rows change from a value of 1 to a value of 4 progressing from column a to column d within those 4 columns. Currently I'm pulling the difference between each of the columns and looking for a value of 3. Is there a better way to do th...
<p>You can just do <code>cummax</code></p> <pre><code>col = ['a','b','c','d'] s = df[col].cummax(1) df['new'] = s[col[:3]].eq(1).any(1) &amp; s[col[-1]].eq(4) Out[523]: 0 True 1 False 2 True 3 True 4 True 5 False 6 True 7 True 8 True dtype: bool </code></pre>
python-3.x|pandas
1
11,956
50,347,159
Keras does not use GPU - how to troubleshoot?
<p>I'm trying to train a Keras model on the GPU, with Tensorflow as backend.</p> <p>I have set everything up according to <a href="https://www.tensorflow.org/install/install_windows" rel="noreferrer">https://www.tensorflow.org/install/install_windows</a>. This is my setup:</p> <ul> <li>I'm working in a Jupyter notebo...
<p>Check<br> <code>nvcc -V</code><br> and </p> <p><code>nvidia-smi</code> </p> <p>and see if it shows our gpu or not.</p> <p>Assuming your cuda cudnn and everything checks out, you may just need to<br> 1. Uninstall keras<br> 2. Uninstall tensorflow<br> 3. uninstall tensorflow-gpu<br> 4. Install only tensorflow-...
python|tensorflow|cuda|keras|gpu
16
11,957
62,733,919
Error 403, Problem with importing image data in s3 to SageMaker Notebook
<p>I am working with SageMaker Notebook and image data in S3 bucket with name s3:///train/ and validate data in other dir. I create an IAM Role and put previous specific bucket, in the notebook I load this bucket with:</p> <pre><code>s3_train = 's3://&lt;BucketName&gt;/train' train_data = sagemaker.session.s3_input(s3_...
<p>You're seeing that error because the <code>fit(...)</code> method was unable to get access to your S3 bucket. You probably need to make changes to your IAM role you used in your notebook to allow access to your bucket.</p> <p>SageMaker uses IAM roles to get access to your resources.</p> <p>There is comprehensive doc...
python|amazon-web-services|tensorflow|amazon-s3|amazon-sagemaker
0
11,958
62,495,476
Product Classification loading image error in python
<p>Recently i was doing a product classification project, i have a pre-classified dataset 'train' with 41 folders corresponding to each category of products, and its csv file listing the image name and its category.</p> <p>Then, i have another 'test' dataset with bunch of unclassified products, the project wished to cl...
<p>Ok i get it it's the format problem of load_image</p> <pre><code>img = image.load_img(r'train/train/' + str(train_df['category'][i]) + '/' + train_df['filename'][i], target_size=(28,28)) </code></pre>
python|pandas|machine-learning|image-processing|google-colaboratory
0
11,959
54,579,287
Efficient upsert of pandas dataframe to MS SQL Server using pyodbc
<p>I'm trying to upsert a pandas dataframe to a MS SQL Server using pyodbc. I've used a similar approach before to do straight inserts, but the solution I've tried this time is incredibly slow. Is there a more streamlined way to accomplish an upsert than what I have?</p> <pre><code>sql_connect = pyodbc.connect('Driver...
<p>Update, July 2022: You can save some typing by using <a href="https://gist.github.com/gordthompson/be1799bd68a12be58c880bb9c92158bc" rel="nofollow noreferrer">this function</a> to build the MERGE statement and perform the upsert for you.</p> <hr> <p>Here is an example of an &quot;upsert&quot; using <a href="https://...
python|sql|sql-server|pandas|pyodbc
6
11,960
54,435,024
Choose r outcomes from n possibilities efficiently in Pandas
<p>I have a 50 years data. I need to choose the combination of 30 years out of it such that the values corresponding to them reach a particular threshold value but the possible number of combination for <code>50C30</code> is coming out to be <code>47129212243960</code>. How to calculate it efficiently?</p> <pre><code>...
<p>You can use numpy's <a href="https://docs.scipy.org/doc/numpy-1.14.1/reference/generated/numpy.random.choice.html" rel="nofollow noreferrer"><code>random.choice</code></a>:</p> <pre><code>In [11]: df.iloc[np.random.choice(np.arange(len(df)), 3)] Out[11]: Prs_100 Yrs 2023 392.193322 2047 337.491898 2026 ...
python|pandas|discrete-mathematics|apriori
1
11,961
54,414,978
Python: add column to dataframe that relates to another column
<p>I have imported a stock's data from yahoo into a dataframe using pandas_datareader. There are 2 columns : date and the adjusted close of the stock.</p> <pre><code>Date Adj Close 2017-08-31 168.851196 2017-09-01 169.867691 2017-09-05 165.333496 2017-09-06 165.233810 2017-09-07 166.001160 2017-0...
<p>Try this:</p> <pre><code>df['Adj Yesterday'] = df['Adj Close'].shift() df['Log Return'] = df['Adj Close'] / df['Adj Yesterday'] - 1. </code></pre> <p>If this is not quite what you wanted, but close, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferr...
python|pandas|dataframe
3
11,962
73,729,351
Why we use validation set (not train or test set) in early stopping function ( DL / CNN )?
<p>This is my first attempt to CNN in Pytorch. I have gone by few tutorials, but still need some clarification.</p> <p>I have theoretical question, I don't understand why in <strong>early stopping function</strong> we base on <strong>validation set</strong>, not train or test set?</p> <p>Has it something common with me...
<p>The number of training epochs is one of the <em>training</em> hyper-parameters. Therefore, you MUST NOT use the test data to determine the value of this hyper-parameter. Additionally, you cannot use the training set itself to determine the value of early stopping. Therefore, you need to use the validation set for de...
machine-learning|pytorch|conv-neural-network
1
11,963
73,743,926
How to read nested dictionary created from pandas?
<p>I am creating a dictionary from a panda table for fast access. However, I am unable to figure out how to access the elements and the key easily.</p> <p>The dictionary is in the below format.</p> <pre><code>{'token': {'NIFTY22SEP2214100PE': '52263_NFO', 'NIFTY22SEP2214050PE': '52249_NFO'}, 'o185': {'NIFTY22SEP221410...
<p>If your dictionary is called &quot;dic&quot;, one thing you can do is :</p> <pre><code>token = [token for token in dic[&quot;token&quot;] if dic[&quot;token&quot;][token] == &quot;52263_NFO&quot;][0] strike = dic[&quot;strike&quot;][token] </code></pre> <p>You can adapt this lines for the 2nd question.</p>
python|pandas|dictionary
1
11,964
73,670,303
Directly grouping rows from pandas.DataFrame through matplotlib plotting
<p>I have a Dataframe saved as a <code>.csv</code> file that is similar to the one produced by the following code:</p> <pre><code> dates = [[&quot;2022-03-31&quot;, &quot;A&quot;,100], [&quot;2022-03-31&quot;, &quot;B&quot;,100], [&quot;2022-03-31&quot;, &quot;C&quot;, 250], [&quot;2022-04-31&quot;, &quot;A&quot;, 500...
<p>Here are two solutions. The first is using pandas only. Pandas makes it easy to plot data and the backend is matplotlib, too. The second solution uses matplotlib.</p> <h2>Data handling</h2> <p>Before I start, I want to comment, that I don't use [<code>pd.groupby()</code>], because in this case <a href="https://panda...
python|pandas|matplotlib
1
11,965
71,136,337
Matplotlib/Seaborn - Plotting datetime objects on the x-axis is giving a very long label
<p>I'm trying to plot time-series data using Seaborn, but the formatting of the x axis tick labels is being very odd, giving me much more detail than I'm interested in. Here is the head of my dataframe, my code, and the output.</p> <p>Head of Dataframe showing year and month column to be combined:</p> <p><img src="http...
<p>In pandas, all datetime objects are stored as <code>datetime64[ns]</code> with precision down to nanoseconds. When you run <code>df['arrival']</code>, the output you're getting is what is being displayed but the actual underlying data underneath is at nanosecond precision (and this is what matplotlib is showing on t...
python|pandas|datetime|matplotlib|seaborn
1
11,966
71,415,810
Iteration with multiple conditions in Pandas
<p>In part of my code, I am searching for subsets of a DataFrame in order to manipulate them later. Part of the code that takes a very long time goes as follow:</p> <pre><code>for record in records.itertuples(): matches_ids = df[((df['column_1'] &lt; record.attribute_1) &amp; (record....
<p>You can perform a cross <code>merge</code> then filter out your dataframe with <code>query</code>:</p> <pre><code>qs = &quot;(column_1 &lt; attribute_1) \ &amp; (attribute_2 &lt; column_2) \ &amp; (column_3 &lt; attribute_3) \ &amp; (attribute_4 == column_4) \ &amp; (column_5 != value...
pandas|performance
1
11,967
71,144,743
Opening a large JSON file and converting it to CSV
<p>I'm trying to convert a large <code>JSON</code> file (4.35 GB) to <code>CSV</code>.</p> <p>My initial approach was importing it, converting it to a data frame (I only need what's in <code>features</code>), doing some data manipulation, and exporting it to <code>CSV</code>.</p> <pre class="lang-py prettyprint-overrid...
<p>For splitting up the data you can use a streaming parser such as <a href="https://github.com/ICRAR/ijson" rel="nofollow noreferrer">ijson</a> e.g.</p> <pre><code>import ijson import itertools import json chunk_size = 10_000 filename = 'Risk_of_Flooding_from_Rivers_and_Sea.json' with open(filename, mode='rb') as f...
python|json|pandas|csv|large-data
2
11,968
52,232,315
How to compare two different Data frames on simile column values and put values to other data frame
<p>I need to automate the validations performed on text file. I have two text files and I need to check if the row in one file having unique combination of two columns is present in other text file having same combination of columns then the new column in text file two needs to be written in text file one.</p> <p>The ...
<pre><code>del df['Vehicle_price'] print(df) dd = pd.merge(df, df1, on=['vehicle_Brought_City', 'Vehicle_Brand']) print(dd) </code></pre> <p><strong>output:</strong></p> <pre><code> fname lname vehicle_Brought_City Vehicle_Brand Vehicle_price 0 aaa xxx pune honda 50000 1 aaa ...
python|pandas|dataframe
1
11,969
60,577,051
Replace column values in large Pandas dataframe
<p>I have a large input file of numerical data (22000) columns and at the moment when I use<br> <code>df = pd.read_csv(path_to_file)</code>, it uses the first line of numbers as the column values. </p> <p>Is there any way to replace the column value with random variables or load the data in a way that the first line i...
<p>Use <code>pd.read_csv("path_to_file", header=0)</code>.</p> <p>If you also want to assign names to the columns you can pass a list in the <code>names</code> parameter of pd.read_csv.</p>
python|python-3.x|pandas|dataframe
0
11,970
60,343,343
Python groupby returning NaN averaged values after creating bins
<p>I have a dataframe that consist in hourly values of alpha (wind shear) for 2014, 2015 and 2016.</p> <pre><code> Year Month Day Hour alpha 0 2014 8 1 0 0.275673 1 2014 8 1 1 0.365437 2 2014 8 1 2 0.431942 3 2014 8 1 3 0.450911 4 2014 8 1 4 0.348400 5 2014 ...
<p>You can create a boolean value to indicate nighttime hours. If this is false, that means day time. Then add 'Night' to your groupby function and unstack it so that the day and night averages are side by side for a given date.</p> <pre><code>&gt;&gt;&gt; result = ( df .assign(Night=df['Hour'].lt(8)...
python|pandas|pandas-groupby
2
11,971
60,639,638
Return custom variables for each dataframe in pandas
<p>I feel like this is a super simple question, I just don't have the vocabulary to articulate it in google. Here goes:</p> <p>I have a dataframe that I want to slice and split into several dataframe. So I created a function and a for loop for this.</p> <p>Sample table</p> <pre><code> col1 col2 col3 col4 col5 ro...
<p>Making a dictionary would be ideal for this case!:</p> <pre><code>df_slicer = {} for i in df.col1: df_slicer[i] = df[df.col1==i] #dfA: df_slicer['A'] </code></pre>
python|pandas|function
1
11,972
59,612,201
How do I merge categories for crosstab in pandas where some categories are common?
<p><a href="https://stackoverflow.com/questions/59431633/how-do-i-merge-categories-for-crosstab-in-pandas/59431990#59431990">A while ago I asked this question</a></p> <p>But that does not cover the case where two merged categories might have a common category</p> <p>In that case I wanted to merge the categories A and...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a> by all unique values and then sum values by selecting by categories in index values:</p> <pre><code>df = pd.crosstab(df.X, df.Y) df.loc['A or B'] = df.loc[...
python|pandas
1
11,973
59,726,916
how to pivot pandas dataframe with multiple aggregate field and multiple index fields to sumIfs in python?
<p>I have a dataframe like his</p> <pre><code>import pandas as pd lst = [['A', '1','1', 25, 5], ['A', '1','0', 3,7], ['A', '0','1', 5, 9], ['A', '0','0', 5, 10], ['B', '1','1', 15, 18], ['B', '1','0', 2, 20], ['B', '0','1', 2, 60], ['B', '0','0', 55, 60]] df1=pd.DataFrame(lst, columns =['id', ...
<p>simple <code>multiplication</code>, <code>concat</code> and <code>groupby.sum</code> would achive your result</p> <pre><code>df_gb1 = df1[['sumfield1', 'sumfield2']].mul(df1.groupby1, axis=0).add_suffix('_groupby1') df_gb2 = df1[['sumfield1', 'sumfield2']].mul(df1.groupby2, axis=0).add_suffix('_groupby2') df_sum =...
python|pandas
2
11,974
59,896,544
Plot a multiple line chart based on date ranges (min and max)
<p>I have a df like the following:</p> <pre><code> DATE_MIN DATE_MAX 214 1994-06-29 2010-07-12 125 1969-10-26 2011-10-10 123 2013-07-02 2015-01-29 74 2006-01-05 2016-06-20 </code></pre> <p>Columns are: DATE_MIN, DATE_MAX</p> <p>I would like to plot a long vertical chart with as many horizontal lines as df ...
<p>If you are happy to make a gantt and use plotly you could use this <a href="https://plot.ly/python/gantt/" rel="nofollow noreferrer">doc</a></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from io import StringIO import plotly.figure_factory as ff txt="""TASK DATE_MIN DATE_MAX 214 1994-06-...
python|pandas|dataframe|matplotlib|charts
0
11,975
32,441,934
How can I make this code more pythonic?
<p>I am reading a bunch of daily files and using glob to concatenate them all together into separate dataframes.I eventually join them together and basically create a single large file which I use to connect to a dashboard. I am not too familiar with Python but I used pandas and sklearn often. </p> <p>As you can see, ...
<p>I didn't change names, but IMHO they should be more verbose eg. pd == panda? Not sure. Here is some more pythonic way to write it:</p> <pre><code>from functools import partial import logging from operator import add, sub import os import datetime as dt import contextlib os.chdir(r'C:\\Users\Documents\FTP\\') locat...
python|pandas
-1
11,976
40,722,963
Average every four rows but preserve timestamp values
<p>What is the fastest way in pandas to average every four rows in a dataframe?</p> <p>My problem is that I have a program recording data every 15 seconds which looks like this:</p> <pre><code>1477892758, 10 1477892773, 20 1477892788, 30 1477892803, 40 1477892818, 15 1477892833, 25 1477892848, 35 1477892863, 45 </cod...
<p>You can use <code>groupby</code> by <code>index</code> floor divided by <code>4</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow noreferrer"><code>aggregate</code></a> for first column <code>first</code> and for second <code>mean</cod...
python|pandas|group-by|aggregate|mean
2
11,977
40,578,349
How to find mean in kmeans in single shot using numpy
<p>I have a function:</p> <pre><code>def update(points, closest, centroids): return np.array([points[closest==k].mean(axis=0) for k in range(centroids.shape[0])]) </code></pre> <p>It basically the update of centroids step in kmeans algorithm. Basically, points is a matrix, closest is an assignment of a point to a...
<p>Here's a vectorized approach based on <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduceat.html" rel="nofollow noreferrer"><code>np.add.reduceat</code></a> -</p> <pre><code>c = np.bincount(closest,minlength=centroids.shape[0]) mask = c != 0 pts_grp = points[closest.argsort()] cut_idx =...
python|numpy|vectorization
1
11,978
61,735,722
Assigning multiple function outputs to separate columns in pandas dataframe in python
<p>I have a function with 3 outputs, and for the sake of efficiency, I would like to apply the function to all rows in my dataframe. Currently I am calling the function 3 times, once for each column/ouput, but I would like to call the function once and save all 3 outputs to 3 separate columns. But currently I cannot fi...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">apply</a> with the <code>result_type='expand'</code>:</p> <pre><code>df2 = df.apply(lambda x: function(x), result_type='expand', axis=1) </code></pre> <p>Example:</p> <pre><code> ...
python|pandas|lambda|assign
1
11,979
62,032,395
Numpy Array missing dates when I get data from an api (yfinance)
<p>I am trying to gather stock data on an Numpy Array in which the dates of the stock prices are in the first column. When I turn the data directly into an array I will get <code>[ 30.99 32.08 32.12 ... 318.66 315.77 323.5 ]</code> here is my code below.</p> <pre><code>import numpy as np import yfinance as yf def p...
<p>I had the same problem, these are weekends and holidays, the markets is closed on those dates. Conversion to numpy array is problematic as dates are either <code>datetime</code> or <code>string</code> while the rest of the data is <code>float</code>. To keep the first column you need to convert it into <code>float</...
python|pandas|numpy|dataframe|yfinance
1
11,980
58,139,893
Python converting data frame to comma separated rows
<p>I have a pandas dataframe, call it df with 2 columns:</p> <pre><code> user_id result --------- --------- 12 0 233 1 189 0 </code></pre> <p>And so forth. Is there an easy way to write this data frame out to a text file (with column headers remov...
<p><code>df.to_csv("path.txt", header = False, sep = ",", index = False)</code></p> <p>This will write it to text file.</p>
python|pandas
2
11,981
57,803,735
Keras image generator keep giving different number of labels
<p>I am trying to make a simple fine turned Resnet50 model using the Market1501 dataset and keras.</p> <p>So the data set contains images (12000 or so) and 751 labels that I want to use (0-750). I can fit the data into a single go so I have to use a image generator for this.</p> <p>So my base model is like this</p> <pr...
<p>change </p> <pre><code>batch_indices = indices[bid * batch_size: (bid + 1) * batch_size] </code></pre> <p>with</p> <pre><code>batch_indices = indices[bid * batch_size: min((bid + 1) * batch_size, number_of_images)] </code></pre>
python|tensorflow|keras|neural-network|generator
1
11,982
57,789,572
Python Basics: Convert np.array to
<p>I have the following np.array: <code>{0: array([[254, 426],...54, 426]])}</code></p> <p>and would like this as desired output: <code>[(444, 703), (623, 543), (691, 177), (581, 26), (482, 42)]</code></p> <p>How can I do this? I need the variable to be set like in the desired output. </p> <p>Thanks a lot. </p>
<p>As it is mentioned in the comments that is not an array but a dictionary. can get list of tuples buy doing this: </p> <pre><code>list(map(tuple, dict[0])) </code></pre> <p>where dict is your dictionary</p>
python|numpy|matrix
1
11,983
58,103,122
Changing a dataframes data types for the express purpose of using that data for data visualization
<p>I have a data frame that has columns within it that are of the types: object, float 64 and int64. I want to change these types to one that I can use for data visualisations. I have tried already by using the astype method but I am getting an error. How do I go about changing these types to one more suited for data ...
<p>The format for the objects are correct, you can try setting the 'Date' column to a datetime type by using:</p> <pre><code>raw_b['Date'] = pd.to_datetime(raw_b['Date']) </code></pre> <p>If that doesn't work, you should pass the format by using:</p> <pre><code>raw_b['Date'] = pd.to_datetime(raw_b['Date'], format= '...
python|pandas|types
0
11,984
58,025,517
How to link two dataframes based on the string similarity of one column
<p>I have two dataframes, both have an ID and a Column <code>Name</code> that contains Strings. They might look like this:</p> <p><strong>Dataframes:</strong></p> <pre><code>DF-1 DF-2 --------------------- --------------------- ID Name ID ...
<p>Using the pandas dedupe package: <a href="https://pypi.org/project/pandas-dedupe/" rel="nofollow noreferrer">https://pypi.org/project/pandas-dedupe/</a></p> <p>You need to train the classifier with human input and then it will use the learned setting to match the whole dataframe. </p> <p>first <code>pip install pa...
python|pandas|dataframe
4
11,985
34,051,205
Accessing filename from file queue in Tensor Flow
<p>I have a directory of images, and a separate file matching image filenames to labels. So the directory of images has files like 'train/001.jpg' and the labeling file looks like:</p> <pre><code>train/001.jpg 1 train/002.jpg 2 ... </code></pre> <p>I can easily load images from the image directory in Tensor Flow by c...
<p>Given that your data is not too large for you to supply the list of filenames as a python array, I'd suggest just doing the preprocessing in Python. Create two lists (same order) of the filenames and the labels, and insert those into either a randomshufflequeue or a queue, and dequeue from that. If you want the "l...
python|tensorflow
13
11,986
37,044,735
Convert String to Variable List
<p>I have a string:</p> <pre><code>str='ABCDEFG' </code></pre> <p>I also have numpy arrays defined:</p> <pre><code>A=numpy.array([1,2,3]) B=numpy.array([2,3,4]) </code></pre> <p>Now I want to be able to covert the string into a numpy array with the rows defined by these variables:</p> <pre><code>str=[[1,2,3],[2,3,...
<p>List comprehension for the win:</p> <pre><code>In[18]: str='ABCDEFG' In[19]: A=[1,2,3] B=[2,3,4] In[20]: [locals().get(x) for x in str if x in locals().keys()] Out[20]: [[1, 2, 3], [2, 3, 4]] </code></pre> <p>You should use <code>locals</code> or <code>globals</code> depending on your scope.</p>
python|numpy
1
11,987
55,047,922
Remove duplicated permuted rows in Pandas
<p>I have one Pandas DF with three columns like below:</p> <pre><code> City1 City2 Totalamount 0 A B 1000 1 A C 2000 2 B A 1000 3 B C 500 4 C A 2000 5 C B 500 </code></pre> <p>I want to delete the duplicated rows where...
<p>If the entire dataframe follows the pattern you show in your sample, where:</p> <ul> <li>All rows are duplicated like (A, B) and (B, A)</li> <li>There are no unpaired entries</li> <li>CityA and CityB are always different (no instances of (A, A)) </li> </ul> <p>then you can simply do</p> <pre><code>df = df[df['Cit...
python-3.x|pandas
1
11,988
54,958,144
Pandas - select lowest value to date
<p>I'm new to Pandas.</p> <p>I've got a dataframe where I want to group by user and then find their lowest score up until that date in the their speed column.</p> <p>So I can't just use <code>df.groupby(['user'])['speed'].transform('min)</code> as this would give the min of all values not just form the current row to...
<p>Without seeing your dataset it's hard to help you directly. The problem does boil down to the following. You need to select the range of data you want to work with (so select rows for the date range and columns for the user/speed). </p> <p>That would look something like <code>x = df.loc[["2-4-2018","2-4-2019"], ['...
python|pandas
0
11,989
54,833,973
pandas Dataframes merge column names with column values
<p>I have 2 dataframes </p> <pre><code>df = pd.DataFrame({'Location': [ 'Hawai', 'Torino', 'Paris'], 'Time': [2000, 2001,2002], 'Value': [1.2, 2.2,3.4] }) df.set_index(['Location','Time'],inplace=True) df2 = pd.DataFrame({'Country': [ 'US', 'IT', 'FR'], ...
<p>Doing with <code>unstack</code> then <code>mul</code> </p> <pre><code>df2.columns=df2.columns.astype(int) s=df.Value.unstack(fill_value=1) df2.mul(s) Out[675]: 2000 2001 2002 Country Unit Location US USD Hawai 799.2 NaN 44.0 IT EUR Torino 888.0 ...
python|pandas|dataframe
2
11,990
54,697,451
Output TFRecord to Google Cloud Storage from Python
<p>I know <code>tf.python_io.TFRecordWriter</code> has a concept of GCS, but it doesn't seem to have permissions to write to it.</p> <p>If I do the following:</p> <pre><code>output_path = 'gs://my-bucket-name/{}/{}.tfrecord'.format(object_name, record_name) writer = tf.python_io.TFRecordWriter(output_path) # write to...
<p>A common strategy to setup credentials on systems is to use Application Default Credentials (ADC). ADC is a strategy to locate Google Cloud Service Account credentials.</p> <p>If the environment variable <code>GOOGLE_APPLICATION_CREDENTIALS</code> is set, ADC will use the filename that the variable points to for se...
python|tensorflow|google-cloud-platform|google-cloud-storage|tfrecord
4
11,991
49,709,035
Separate Spam and Ham for WordCloud Visualization
<p>I am performing spam detection and want to visualize spam and ham keywords separately in Wordcloud. Here's my .csv file.</p> <pre><code>data = pd.read_csv("spam.csv",encoding='latin-1') data = data.rename(columns = {"v1":"label", "v2":"message"}) data = data.replace({"spam":"1","ham":"0"}) </code></pre> <p><a href...
<p>The issue is that the current code replaces <code>"spam"</code> and <code>"ham"</code> with the one-character <em>strings</em> <code>"1"</code> and <code>"0"</code>, but you filter the DataFrame based on comparison with the <em>integer</em> 1. Change the replace line to this:</p> <pre><code>data = data.replace({"sp...
python-3.x|pandas|join|spam-prevention|word-cloud
0
11,992
49,448,787
how to crop image based on white lines
<p>I am trying to cut an image, in a way to remove the white lines. This image has one object in the corner, surround by blank space. I am trying to use the following commands, but its cutting the image in a wrong way. <a href="http://www.image-share.com/ipng-3711-164.html" rel="nofollow noreferrer">image</a></p> <p...
<p>IIUC, you should just need to find the smallest rectangle of non-white pixels. Assuming the channel is the last dimension:</p> <pre><code>color_x, color_y = np.where(np.any(image &lt; 255, axis=2)) x0 = color_x.min() x1 = color_x.max() y0 = color_y.min() y1 = color_y.max() cropped_image = image[x0:x1 + 1, y0:y1 + 1...
python|image|numpy
0
11,993
49,496,403
What's wrong with this gradient descent?
<p>I want to minimize <code>||Ah(Wx)-y||</code> by gradient descent where <code>h</code> us ReLU </p> <pre><code>s = 9 n = 99 m = 999 A = np.random.normal((n,m)) y = np.random.normal((m,1)) W = np.random.normal((n,s)) def obj_fcn(x): return np.linalg.norm(A.dot(np.max(W.dot(x),0))-y) if __name__ == '__main__': ...
<p>I broke down your function to individual operations and printed the inputs and results as soon as computed. This is a very basic debugging technique; you <em>need</em> to learn this skill if you're going to program at any level beyond trivial applications. See this lovely <a href="https://ericlippert.com/2014/03/0...
python|numpy|machine-learning|neural-network
0
11,994
73,287,143
How to get elements from a nested list in python based on key, value pairs?
<p><code>['ISBN: 9789353765170', 'Pages: 64', 'Size: 294 x 219', 'Language: English', 'Book Binding: Paperback', 'Weight: 350 gm.']</code></p> <p>I splitted with l.split(&quot;:&quot;), to get a nested list but that isn't helping</p> <p><code>[['ISBN', ' 9789353765170'], ['Pages', ' 64'], ['Size', ' 294 x 219'], ['Lang...
<p>IIUC use:</p> <pre><code>L = ['ISBN: 9789353765170', 'Pages: 64', 'Size: 294 x 219', 'Language: English', 'Book Binding: Paperback', 'Weight: 350 gm.'] df = pd.DataFrame((x.split(': ') for x in L), columns=['a','b']) print (df) a b 0 ISBN 9789353765170 1 Pages ...
python|pandas|list|dataframe
1
11,995
73,360,270
How to plot on exactly rows of a dataframe
<p>That's not easy to describe with words, so I will reveal a picture for you in order to understand:<br /> <a href="https://i.stack.imgur.com/xIQGo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xIQGo.png" alt="enter image description here" /></a> As the image shows, I want to plot a line on each r...
<p>Here's an example to get you started: it uses <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.table.html" rel="nofollow noreferrer"><code>table</code></a> to plot the dataframe and overplots the stacked lines. The line for each row is shifted by <code>ymax</code>, the maximum value in the datafr...
python|pandas|matplotlib
0
11,996
34,998,392
Pandas DataFrame with MultiIndex: Group by year of DateTime level values
<p>I have and pandas dataframe with a multiindex that looks like this:</p> <pre><code># -*- coding: utf-8 -*- import numpy as np import pandas as pd # multi-indexed dataframe df = pd.DataFrame(np.random.randn(8760 * 3, 3)) df['concept'] = "some_value" df['datetime'] = pd.date_range(start='2016', periods=len(df), freq...
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by second level of <code>multiindex</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.year.html" rel="nofollow"><code>year</code><...
python|pandas
4
11,997
35,087,539
Drop pandas dataframe row based on max value of a column
<p>I have a Dataframe like so:</p> <pre><code> p_rel y_BET sq_resid 1 0.069370 41.184996 0.292942 2 0.116405 43.101090 0.010953 3 0.173409 44.727748 0.036832 4 0.225629 46.681293 0.540616 5 0.250682 46.980616 0.128191 6 0.294650 47.446113 0.132367 7 0.322530 48.078038 0.235047 </code></...
<p>You could just filter the df like so:</p> <pre><code>In [255]: df.loc[df['sq_resid']!=df['sq_resid'].max()] Out[255]: p_rel y_BET sq_resid 1 0.069370 41.184996 0.292942 2 0.116405 43.101090 0.010953 3 0.173409 44.727748 0.036832 5 0.250682 46.980616 0.128191 6 0.294650 47.446113 0.132367...
python|numpy|pandas|dataframe
25
11,998
67,222,042
Alternative to for loop to loop through rows of an np.array
<p>I have two numpy arrays. I would like to use the values inside each row of the array <code>p</code> as indices for the array <code>food</code> in the <code>consume</code> function. Unfortunately, it takes very long with the <code>for</code> loop when <code>p</code> get to the size of <code>2000</code> rows.</p> <p>W...
<p>Read <a href="https://numpy.org/doc/stable/user/basics.indexing.html#indexing-multi-dimensional-arrays" rel="nofollow noreferrer">Indexing Multi-Dimensional Arrays</a></p> <p>Basically if you want to access <code>food[x1, y1, z1]</code>, <code>food[x2, y2, z2]</code> ... <code>food[xn, yn, zn]</code> values from foo...
python|numpy|for-loop|row
1
11,999
67,398,072
What is the 'python version' of array[i]?
<p>I am learning Python and trying to compare the elements of multiple arrays/lists at a time, my arrays are Numpy arrays (I guess?) as I did <a href="https://stackoverflow.com/a/67302172/13061992">the following</a> to create them and the answer mentions the output as a numpy array</p> <p>I have 3 arrays of length 40 i...
<p>This should work for you:</p> <pre><code>for x,y,z in zip(array1,array2,array3): if(x==y and x==z): #Do Something </code></pre>
python|arrays|numpy
1