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 |
|---|---|---|---|---|---|---|
358,200 | 53,103,840 | Modify SQL query to avoid having? | <p>I have a column with SQL queries to a column. These are implemented on a function called <code>Select_analysis</code></p>
<p>Form:</p>
<pre><code>Select_analysis (in_file, out_file, {where_clause})
</code></pre>
<p>It is for simple queries and receives up until where clause. </p>
<p>Example:</p>
<p>A query lik... | <p>The answer to this may depend on your specific SQL implementation, but fundamentally your problem is you're trying to avoid using a 'having' while still processing an aggregate function. A 'having' clause is just like a where clause, but processed after an aggregation step.</p>
<p>So I don't think you're going to ... | python|sql|pandas|arcpy | 0 |
358,201 | 53,223,019 | How do I turn a numpy array into a tensor in "Tensorflow"? | <p>I tried to test some learning networks after I completed training with a tensorflow.</p>
<p>But my test image is [512 512 1] data of channel 1 in 512 horizontal and 512 vertical pixels.</p>
<p>I changed the image data to a numpy array.</p>
<p>The tensor network should be [? 512 512 1] It looks like this.</p>
<p>... | <p>You just have to append one dimension</p>
<pre><code>arr = your_image # [512, 512, 1]
new_arr = np.expand_dims(arr, 0)
tensor = tf.convert_to_tensor(new_arr)
</code></pre>
<p>Now you can use feed dict or something else.</p> | numpy|tensorflow | 3 |
358,202 | 52,983,913 | getting 'True' value instead of real value when trying to append in pandas dataframe | <p>Below is my python script.I am trying to parse an xml file and trying to store values in pandas dataframe so that I can later change it to csv file.</p>
<pre><code>import os
import pandas as pd
import sys
import requests
import xml.etree.ElementTree as ET
from xml.dom import minidom
tree = ET.parse('schedule.xml')... | <p>As Nitin and Martin replied, pasting final code here.</p>
<pre><code>import os
import pandas as pd
import sys
import requests
import xml.etree.ElementTree as ET
from xml.dom import minidom
tree = ET.parse('schedule.xml')
FILENAME = sys.argv[1]
COL_NAMES = ['PODNAME', 'DC', 'Upgrade']
DF = pd.DataFrame(columns = CO... | python|pandas|append | 0 |
358,203 | 53,232,969 | How to monitor validation loss in the training of estimators in TensorFlow? | <p>I want to ask a question about how to monitor validation loss in the training process of estimators in TensorFlow. I have checked a similar question (<a href="https://stackoverflow.com/questions/45417502/validation-during-training-of-estimator">validation during training of Estimator</a>) asked before, but it did no... | <p>You need to create a validation input_fn and either use estimator.train() and estimator.evaluate() alternatively or simpy use tf.estimator.train_and_evaluate()</p>
<pre><code>x = ...
y = ...
...
# For example, if x and y are numpy arrays < 2 GB
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_tra... | python|tensorflow|machine-learning|deep-learning | 3 |
358,204 | 53,096,844 | Using "python --version" command bringing up error message | <p>I have Python 3.7.1 on my Windows 10 PC. I want to install Pandas and firstly need to do some checks to see if I have everything required. I tried typing the following to double check the Python version:</p>
<pre><code>python --version
</code></pre>
<p>but it keeps spitting out the error:</p>
<pre><code>Traceback... | <p>You shouldn't be entering <code>python --version</code> in a Python shell. Enter it in the cmd.exe shell.</p> | python|pandas|shell|version | 2 |
358,205 | 53,306,962 | Pandas rolling mean with update | <p>Consider dataframe:</p>
<pre><code>df = pd.DataFrame({
"a": [None, None, None, None, 1, 2, -1, 0, 1],
"b": [5, 4, 6, 7, None, None, None, None, None]
})
>> a b
0 NaN 5.0
1 NaN 4.0
2 NaN 6.0
3 NaN 7.0
4 1.0 NaN
5 2.0 NaN
6 -1.0 NaN
7 0.0 NaN
8 1.0 NaN
</code></pre>
<p>Fo... | <p>Using for loop here, panda is not row-wise , they can not using the previous calculated value for the future calculation.(vectorized)</p>
<pre><code>l=[]
for x ,y in zip(*df.values.T.tolist()):
if len(l)<4:
l.append(y)
else:
l.append(sum(l[-4:])/4+x)
l
Out[188]: [5.0, 4.0, 6.0, 7.0, 6.5,... | python|pandas|dataframe | 3 |
358,206 | 53,332,235 | Parsing large string values in Pandas | <p>I have a <code>.csv</code> which I've generated a dataframe from. This csv has raw data outputs from a system that follows this format:</p>
<pre><code>{"DataType1":"Value","DataType2":"Value","DataType3":"Value",.....}
</code></pre>
<p>Each row in the dataframe has just this in 1 column. I'm trying to break this... | <p>Dataframes follow this format when converted from a dictionery:</p>
<pre><code>dict = {'column 1':[1,2], 'column 2':[3,4], ...}
</code></pre>
<p>Notice that the length of values in each key is same or </p>
<pre><code>pd.DataFrame(dict)
</code></pre>
<p>will throw an error.</p>
<p>To surpass the error, you can i... | python|pandas|csv|dataframe | 0 |
358,207 | 53,084,967 | Pandas rolling method with data to be offset | <pre><code>df = pd.DataFrame({'Number': [x for x in range(10)]})
df["rolling"] = df["Number"].rolling(3).mean()
print(df)
</code></pre>
<p>With the above code, it will output </p>
<pre><code> Number rolling
0 0 NaN
1 1 NaN
2 2 1.0
3 3 2.0
4 4 3.0
5 5 ... | <p>As noted earlier by viktor, you can combine shift and rolling operator. </p>
<pre><code>df['rolling2'] = df['Number'].shift(1).rolling(3).mean()
Number rolling rolling+shift
0 0 NaN NaN
1 1 NaN NaN
2 2 1.0 NaN
3 3 2.0 1.0
... | python|pandas|dataframe | 2 |
358,208 | 53,014,549 | How to annonate / display y values on plot | <p>How can I display the data(y axis values) on the matlotlib graph?
I found this related <a href="https://stackoverflow.com/questions/6282058/writing-numerical-values-on-the-plot-with-matplotlib">post</a>, I tried suggested solution but it doesn't work here, at least I couldn't figure it out. I'd appreciate if you ca... | <p>Use <code>annotate</code>:</p>
<hr>
<p><strong>Example:</strong></p>
<pre><code>import numpy
from matplotlib import pyplot
x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])
fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
ax.annotate(str(j),xy... | python|pandas|matplotlib | 2 |
358,209 | 53,200,022 | Getting 'ValueError: x and y must be 1D arrays of the same length' when they are in fact 1D arrays of same length | <p>I have this dataframe:</p>
<pre><code> key variable value
0 0.25 -0.2 606623.455859
1 0.27 -0.2 621462.029200
2 0.30 -0.2 640299.078053
3 0.33 -0.2 653686.910706
4 0.35 -0.2 659278.593742
5 0.37 -0.2 665684.466383
6 0.40 -0.2 671975.695814
7 0.25 0 ... | <p>Okay I found a way to make it work. Really not sure why it didn't work the original way because I was feeding tricontourf 1D arrays, but basically I wrarpped my data in a list() function just to double make sure it was 1D arrays. This made it work. Here's the code:</p>
<pre><code>x = df_2020_pivot['key'].values
y =... | python-2.7|pandas|numpy|matplotlib|contourf | 6 |
358,210 | 53,284,048 | system error when creating date_range with pandas | <p>I would like to create a <code>date_range()</code> with using pandas. I am kinda sure it worked before I updated pandas package.</p>
<p>with following line of code, I am trying to create the <code>date_range()</code>:</p>
<pre><code>date_time_index = pd.date_range(start='1/1/2018', periods=8760, freq='H')
</code><... | <p>Pandas version 0.19.1 <code>date_range()</code> does not work with the input I gave. I updated pandas to 0.23.4 now everything is fine.</p>
<p>Meanwhile:</p>
<pre><code>pip3 install --upgrade pandas
</code></pre> | python|pandas|date-range | 0 |
358,211 | 65,837,930 | How to get an ordered count of month names from a datetime index | <p>I have a dataframe called WorkOrders that looks like this</p>
<p><a href="https://i.stack.imgur.com/fyPcF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fyPcF.png" alt="enter image description here" /></a></p>
<p>what I want to do is to convert the format of the timestamp in the index so the inde... | <ul>
<li>The desired format, <code>'2018-Feb-27 10:47:00'</code>, is a <code>str</code> not a <code>datetime64[ns] dtype</code>, which means <code>df.index.month</code> and <code>df[col].dt.month</code> can't be used to extract the month, because those methods don't work on <code>strings</code>.</li>
</ul>
<h2>Option 1... | python|pandas|dataframe|datetime | 0 |
358,212 | 65,726,728 | Update main dataframe based on sub dataframes coming from groupby | <p>I am pretty new to pandas and trying to learn it. So, any advice would be appreciated :)</p>
<p>This is just a small part of my whole dataframe <code>DF2</code>:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;"></th>
<th style="text-align: left;">Chromosome_Name<... | <p>I am new to pandas too so I do not want to give you a wrong insight and advices but have you ever thougth of converting <code>Start</code> and <code>End</code> columns to lists. So that you can use if statement if you are not comfortable with pandas but your task is urgent. However, I am aware that converting datafr... | python|pandas|dataframe|loops|pandas-groupby | 0 |
358,213 | 65,751,030 | duplicates sorted to CSV listing all duplicate references pandas | <p>Given this sample data frame with duplicates, I am trying to organize these duplicates in to separate csv output files so that every law firm that has a duplicate gets a list of those duplicates AND the name of the other firm associated with that duplicate.</p>
<pre><code>Client SSN Law Firm
Jones 1... | <p>Filter by <code>Law Firm</code> and use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>isin</code></a> on resulting <code>SSN</code>:</p>
<pre><code>df[df["SSN"].isin(df[df['Law Firm']=="A"]["SSN"])]
</code></... | pandas|duplicates | 1 |
358,214 | 65,706,743 | How to count ocurrences in a column dataframe Python | <p>I have this dataframe</p>
<pre><code> ORF IDClass genName ORFDesc
0 b186 [1,1,1,0] 'bglS' beta-glucosidase
1 b2202 [1,1,1,0] 'cbhK' carbohydrate kinase
2 b727 [1,1,1,0] 'fucA' L-fuculose phosphate aldolase
... | <p>If your <code>IDClass</code> is string type, you can just do:</p>
<pre><code>df['IDClass'].value_counts()
</code></pre>
<p>If that gives an error, it's likely that your <code>IDClass</code> is list type. Then you can use <code>tuple</code>:</p>
<pre><code>df['IDClass'].apply(tuple).value_counts()
</code></pre> | python|pandas | 1 |
358,215 | 65,874,915 | pandas python get table with the first date of event in every year, each country, alternative groupby | <p>Who can help, I'm trying to group this table here ( <a href="https://i.stack.imgur.com/bG1qG.jpg" rel="nofollow noreferrer">original table</a> ) with tables : (country, year, date of the earthquake) in this form: the first earthquake in every year, each country. I was able to group through groupby, ( <a href="https:... | <p>Once you get your <code>groupby</code> use <code>df = df.reset_index()</code>.
This will bring the columns you used in the groupby to columns and will get you the result you want</p> | python|pandas | 0 |
358,216 | 65,908,341 | How to interpret column matrix to find best model for imbalanced dataset? | <p>I am trying to make binary classification and My dataset is imbalanced with a 1:7 ratio. I have 1000 "1" labels and 6990 "0" labels.</p>
<p>Predicting "1" Labels is more important than "0" but still, It should also detect "0" labels correctly as much as possible.</p>... | <p>One way is to validate your model is using different k-folds. Divide your data into 4 or 5 sets of train-test pairs. Get the results of the different tests and take an average. That should allow you to better understand the performance of the different models.</p> | pandas|scikit-learn|data-science|confusion-matrix|imbalanced-data | 0 |
358,217 | 65,535,790 | Visualizing specific information out of two variables in a data | <p>Suppose I have this csv file named sample.csv:</p>
<pre><code>CODE AGEGROUP SEX CITY HEALTHSTATUS
---- --------- --- ---- ------------
E101 25 to 29 M Denver Recovered
E102 25 to 29 F Chicago Recovered
E105 45 to 49 M Denver Mil... | <p>Just change:</p>
<pre><code>df["SEX"].value_counts().plot(kind="bar", ax=ax0)
</code></pre>
<p>To:</p>
<pre><code>df["SEX"][df['HEALTHSTATUS'] == 'Recovered'].value_counts().plot(kind="bar", ax=ax0)
</code></pre>
<p>Full Code:</p>
<pre><code>import pandas as pd
import matplotl... | python|pandas|csv|matplotlib|visualization | 1 |
358,218 | 65,600,112 | Is there a quick way to subset columns in PANDAS? | <p>I am trying to setup a PANDAS project that I can use to compare and return the differences in excel and csv files over time. Currently I load the excel/csv files into pandas and assign them a version column. I assign them a "Version" column because in my last step, I want the program to create me a file co... | <p>If I've understood well:</p>
<ol>
<li>Store the headers in a list.</li>
<li>Remove the names you don't want by hand.</li>
<li>Inside the subset of <code>drop_duplicates()</code>, place the list.</li>
</ol>
<p>In case that the columns you want to remove are more than those you want to keep, add by hand all the wanted... | pandas|subset|drop-duplicates | 0 |
358,219 | 65,695,028 | Pandas: How to find the low after a high within a rolling window | <p>For a series of numbers, I am trying to find the low after the high within a rolling window. I am able to calculate the high within the window, but not the low after it within the same window. I'm using Pandas and have tried to get the index of the high and use that as some type of reference, but I can't get it to... | <p>Let us do <code>apply</code> with <code>idxmax</code></p>
<pre><code>df['Low_After_High'] = df.Temperature.rolling(5).apply(lambda x : min(x[pd.Series(x).idxmax():]))
2013-01-01 NaN
2013-01-02 NaN
2013-01-03 NaN
2013-01-04 NaN
2013-01-05 2.0
2013-01-06 92.0
2013-01-07 54.0
2013-01-08 98.... | python|pandas|max|min|rolling-computation | 1 |
358,220 | 65,750,508 | Numpy multiply array with specific column | <p>Im not sure, how I would go about doing this (preferably in an efficient manner) -</p>
<pre><code>import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.array([[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0]]
</code></pre>
<... | <p><code>Numpy</code> has very efficient matrix/vector operations.
If you want the dot product between <code>a</code> and the third column of <code>b</code> you can do</p>
<pre><code>a.dot(b[:,2])
# returns 15
</code></pre>
<p>and if you want the element-wise multiplication, you can do</p>
<pre><code>np.multiply(a, b[:... | python-3.x|numpy | 1 |
358,221 | 65,836,235 | In each row of pandas, starting at the first non-NaN a window of X values remains untouched while all other values are NaN | <p>Citizens of StackOverflow,</p>
<p>I am currently running iterations over a dataframe that can be millions of rows long. In each row of my dataframe I have leading NaNs (desired), followed by values. I want to only have X number of values in each row, followed by NaN's after that. <em>Effectively I want a window o... | <p>Try:</p>
<pre><code>df.where(df.notna().cumsum(1)<4)
</code></pre>
<p>Output:</p>
<pre><code> 2018Q3 2018Q4 2019Q1 2019Q2 2019Q3
0 0.0 1.0 2.0 NaN NaN
1 NaN NaN 3.0 4.0 5.0
2 NaN NaN NaN NaN NaN
3 NaN NaN NaN 8.0 9.0
4 NaN ... | python|pandas|nan | 4 |
358,222 | 65,563,874 | Pandas: from crosstab to a count table | <p>I have a table of 0's and 1's generated from <code>pd.crosstab()</code></p>
<p>A row is a recipe and the columns are ingredients. So for example we can have:</p>
<pre><code> banana mushrooms ... chocolate tuna
banana-split 1 0 ... 1 0
</code></pre>
<p>I'd like to transform it to a ... | <p>You can do <a href="https://en.wikipedia.org/wiki/Matrix_multiplication#Definition" rel="nofollow noreferrer">matrix multiplication</a>:</p>
<pre><code>df.T @ df
</code></pre> | python|python-3.x|pandas | 4 |
358,223 | 65,760,532 | pandas - dropna - what if arguments contradict? | <p>Say we have a pandas <code>DataFrame</code> <code>df</code>.</p>
<p><a href="https://i.stack.imgur.com/bAiVv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bAiVv.png" alt="pic003" /></a></p>
<p>And let's say we call <code>df.dropna(how='all', thresh=0)</code> on it.</p>
<p>Isn't this set of argum... | <p>The <a href="https://github.com/pandas-dev/pandas/blob/v1.2.0/pandas/core/frame.py#L5164" rel="nofollow noreferrer">source code of pandas</a> reads:</p>
<pre><code> if thresh is not None:
mask = count >= thresh
elif how == "any":
mask = count == len(agg_obj._get_ax... | python|pandas | 1 |
358,224 | 65,861,179 | How to create separate dataframes with groupby time | <p>I have this <a href="https://www.kaggle.com/anikannal/solar-power-generation-data" rel="nofollow noreferrer">dataset</a> with data collected over 34 days with 15-minute intervals.</p>
<p>How would I fetch all data from the same time of day? I have already loaded and converted the dataset into DateTime format.</p>
<... | <ul>
<li>Use <code>pandas.DataFrame.groupby</code> for <code>.dt.time</code>.
<ul>
<li><code>.dt.hour</code> can be used if you want to group on the hour.</li>
</ul>
</li>
<li>Aggregation functions haven't been specified for the columns, so <code>dfg</code> is a <code>DataFrameGroupBy</code> object.</li>
<li>Using the ... | python|pandas|time | 1 |
358,225 | 65,563,274 | Pandas dataframe covert wide to long multiple columns with name from column Name | <p>Consider I have a Pandas Dataframe with the following format.</p>
<pre><code>Date Product cost|us|2019 cost|us|2020 cost|us|2021 cost|de|2019 cost|de|2020 cost|de|2021
01/01/2020 prodA 10 12 14 12 13 15
</code></pre>
<p>How can w... | <p>Convert non year columns to <code>MultiIndex</code> by <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>, then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.rspl... | python|pandas | 2 |
358,226 | 65,591,624 | Python: writes only one row into SQLite DB despite loading the full file data into pandas framework | <p>I am trying to read the data from "data.txt" and write it to SQLITE database, what I actually get is only first row of the record. I figured out by printing the pandas frame object, it does get all the data from "txt" but failed to iterate throughout, to me the iteration loop looks fine can anybo... | <p>This should work as expected:</p>
<pre class="lang-py prettyprint-override"><code>data = pd.read_csv ("data.txt", delimiter=' ', header=None, names=['object_id', 'object_type'], skipinitialspace=True)
for row in data.itertuples(index=False):
cur.execute(''' INSERT INTO objects (object_id, object_type... | python|pandas|sqlite | 2 |
358,227 | 65,592,179 | Make new dataframe from if condition across 2 dataframes | <p>If I have a monthly "points" dataframe, in which the values are from cumsum():</p>
<pre><code>ID month1 month2 month3 month4
000 0 10 45 55
111 40 60 100 100
</code></pre>
<p>And I have a "buy" dataframe, which is basically whether there'll be a purchase in th... | <p>The easiest would be to merge the two datasets by 'ID':</p>
<pre><code>df = df1.merge(df2, on='ID')
</code></pre>
<p>And then use np.where:</p>
<pre><code>df['month1_x'] = np.where((df['month1_x'] > 40) & (df['month1_y'] == 'YES'), MAX(40, 0.8*df['month1_x']), 0)
</code></pre> | pandas|dataframe | 2 |
358,228 | 65,619,374 | Pixelwise OR two images with numpy | <p>I am using numpy to numerically manipulate image data. I have two black and white images which I would like to perform a logical OR on (i.e. if a pixel is white in either image, the corresponding pixel in the output image is also white). I have an inelegant solution that works, but I'm certain there must be a more e... | <p>Try:</p>
<pre><code>def insert_subimage(img, subimage, x,y):
h,w = subimage.shape[:2]
# one should check if
# y + h >= img.shape[0] or
# x + w >= img.shape[1]
img[y: y+h, x: x+w] = img[y: y+h, x: x+w] | subimage
</code></pre> | python|numpy|image-processing | 1 |
358,229 | 65,634,348 | Series describe function pandas ploting | <p>I have question for you. Which plot is a best to show describe result in series pandas</p>
<pre><code>filter = genderage['Customer_Gender'] == "F"
genderage[filter]
genderage[filter].describe()
Customer_Age
count 54724.000000
mean 36.168993
std 10.910622
min 17.000000
25% 28.000000
50% 35.000000
... | <p>A <code>boxplot</code> will combine nearly all of this information into a single visualization. It won't plot the <code>mean</code> by default but you can add that as a dashed line with <code>meanline</code> and <code>showmeans</code>.</p>
<p>The whiskers extrend from the <code>max</code> to the <code>min</code>. Th... | python|pandas|plot|statistics|dataset | 6 |
358,230 | 65,676,151 | How does torchvision.transforms.Normalize operates? | <p>I don't understand how the normalization in <code>Pytorch</code> works.</p>
<p>I want to set the mean to <code>0</code> and the standard deviation to <code>1</code> across all columns in a tensor <code>x</code> of shape <code>(2, 2, 3)</code>.</p>
<p>A simple example:</p>
<pre><code>>>> x = torch.tensor([[[... | <p>To give an answer to your question, you've now realized that <a href="https://pytorch.org/docs/stable/torchvision/transforms.html#torchvision.transforms.Normalize" rel="nofollow noreferrer"><code>torchvision.transforms.Normalize</code></a> doesn't work as you had anticipated. That's because it's not meant to:</p>
<u... | pytorch|torchvision | 11 |
358,231 | 65,692,714 | How to replace all backslashes in a dataframe column / pandas series | <p>I want to replace a dataframe column's any '\' values with empty.</p>
<p>the dataframe column</p>
<pre><code>name
jack\\\`s ltd
jack & co \
jack\'s kitchen
</code></pre>
<p>I'm able to get the rows with <code>df[df['name'].str.contains('\\\\')]</code> but when I used
<code>df['name'].replace('\\\\', '', inplace=... | <p>You need to:</p>
<ol>
<li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>str.replace</code></a></li>
<li>Use backslashes to escape each backslash (essentially doubling the number of backslashes).</li>
<li>Per comment: <code>rege... | python-3.x|pandas|dataframe | 3 |
358,232 | 65,569,724 | Python Pandas Query for multiple files with missing data | <p>I'm looking for some advice. I have a basic understanding of Pandas and think this should be easy to implement but don't know how to.</p>
<p>I have uploaded two images below.</p>
<p><a href="https://i.stack.imgur.com/VZ3Gn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VZ3Gn.png" alt="file name" ... | <p>Assuming that the files are in your <code>Desktop</code> folder, you can do use <code>glob</code> and <code>concat</code> all of the files (put in whatever folder path you require in my code). and create a new <code>Filename</code> column as you read in the files. Finally, <code>dropna()</code> rows passing the subs... | python|pandas|dataframe|csv | 0 |
358,233 | 65,588,382 | Removing empty words from column of tokenized sentences | <p>I have a dataframe containing lists of words in each row in the same column. I'd like to remove what I guess are spaces. I managed to get rid of some by doing:</p>
<pre><code>for i in processed.text:
for x in i:
if x == '' or x==" ":
i.remove(x)
</code></pre>
<p>But some of them... | <p>You can use split(expand=True) to do that. Note: You dont have to specifically give spilt(' ', expand=True). By default, it takes ' ' as the value. You can replace <code>' '</code> with anything. For ex: if your words separate with <code>,</code> or <code>-</code>, then you can use that separator to split the column... | python|pandas|dataframe | 0 |
358,234 | 65,669,795 | Python - get latest date column | <p>Problem: I have a pandas DataFrame, that has several columns. Some of the columns are strings as dates for example: <code>["A", "2019-12-01 00:00:00", "2020-01-01 00:00:00"]</code></p>
<p>Q:How does one choose the latest date column in this case, keeping in mind that the column location... | <p>Converting column names to dates with <code>pd.to_datetime</code> and <code>errors='coerce'</code> parameter to ignore non-datetime values, and then taking <code>max</code>:</p>
<pre><code>cols = ["A", "2019-12-01 00:00:00", "2020-01-01 00:00:00"]
pd.to_datetime(cols, errors='coerce').m... | python|pandas|list|dataframe|datetime | 2 |
358,235 | 65,817,162 | How to sort the values in dataframe after carrying out logical operations on the data? | <pre><code>import numpy as np
import pandas as pd
data = [["John",1,3],["Jenna",3,5],["Jay",7,10],["Jose",11,16]]
df = pd.DataFrame(data,columns=['Name','LL','UL'])
print(df['LL'])
print(df['LL'].values)
desired = int(input("Enter Desired: "))
i = 0
df['Best'] = 0
fo... | <p>check your parenthesis on this line and correct to:</p>
<pre><code>if( (desired >= int(lowerLim[0][0])) & (desired <= int(upperLim[0][0])) ):
</code></pre>
<p>give that try and see if you get expected results. complete trace:</p>
<pre><code>0 1
1 3
2 7
3 11
Name: LL, dtype: int64
[ 1 3 7 1... | python-3.x|pandas|dataframe|sorting|machine-learning | 0 |
358,236 | 65,742,597 | Pandas Dataframe of series, get series by name | <p>I have a pandas dataframe that consists of multiple series. I want to get one series by name, but for the life of me can't figure out how to do it.</p>
<p>Dataframe:</p>
<pre><code> user_id name
gender
male 1 John
female 2 Abiga... | <p>Simply use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>.loc</code></a>:</p>
<pre><code>df.loc['male','name']
</code></pre> | python|pandas|dataframe|pandas-groupby | 2 |
358,237 | 65,529,206 | numpy - is there a way to cause multiple increments at arr[1, [0, 2, 0, 2, 0]] += 1 | <h1>Background</h1>
<p><code>+1</code> occurs only once for each element although each indexed element is referenced multiple times.</p>
<pre><code>a = np.arange(12).reshape((3, 4))
b = a.copy()
print(a)
---
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
a[1, [0, 2, 0, 2, 0]] += 1 # a[1][0] referenced 3 times and a[1... | <p>What you're looking for is <a href="https://numpy.org/doc/stable/reference/generated/numpy.ufunc.at.html" rel="noreferrer"><code>numpy.ufunc.at</code></a>. Here is how you can use it in your case:</p>
<pre class="lang-python prettyprint-override"><code>np.add.at(a, (1, [0, 2, 0, 2, 0]), 1)
print(a - b)
# [[0 0 0 0]... | numpy | 5 |
358,238 | 65,492,807 | Python Polynomial Regression on 3D Data points | <p>My problem is, that I have about 50.000 non-linear data points (x,y,z) with z depending on the independent variables x and y. From one side, so from a two-dimensional perspective, the data points look like a polynomial of degree 7. Unfortunately I cannot show this data.</p>
<p>My goal is to find a polynomial in 3D t... | <p>As far as fitting a polynomial to a surface, I think your best bet is to try different sets of polynomials and rank them based on fit, as described <a href="https://stackoverflow.com/questions/47442102/how-to-find-the-best-degree-of-polynomials">here</a>.</p>
<p>If you are willing to try different surface fitting me... | python|pandas|scikit-learn|regression|polynomials | 2 |
358,239 | 65,581,268 | Why is batch size allocated in GPU? | <p>Given a Keras model (on Colab) that has input shape (None,256,256,3) and batch_size is 16 then the memory allocated for that input shape is 16*256*256*3*datatype (datatype=2,4,8 depending on float16/32/64). This is how it works. My confusion is that for a given batch_size (=16) 1*256*256*3 could have been allocated ... | <p>In general batch size is what you need to tune-up.</p>
<p>And as for your query batch size is data-dependent, and as you use batches, you are generally running a generator object, which loads data in batches, perform GD and then move on next.</p>
<p>It is preferred to use batch gradient decent as it converges faster... | tensorflow|keras|gpu|google-colaboratory|keras-layer | 1 |
358,240 | 65,501,377 | How to convert all pandas timestamp timezones in a pandas dataframe | <p>Imagine you had a dataframe like this, with multiple datetime columns in UTC. What is the best way to convert them all to a timezone of your choice, such as EST?</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'id': {0: 12394, 1: 12393, 2: 12392, 3: 12391, 4: 12390},
'created_timestamp': {0: pd.Timestamp('2020... | <p>another option: make a boolean mask based on dtype, and use it in <code>loc</code>:</p>
<pre><code>m = df.dtypes == 'datetime64[ns]'
df.loc[:, m] = df.loc[:, m].apply(lambda x: x.dt.tz_localize("UTC").dt.tz_convert("America/New_York"))
df
id ... updated_timestamp
0 12394 ... | python|pandas|dataframe|datetime | 1 |
358,241 | 65,769,654 | python: RecursionError: maximum recursion depth exceeded while calling a Python object passing a dataframe to class method | <p>I am new to Python. I am trying to pass a dataframe to a class. My class has 2 methods. I would like to call them as a chained methods. Both the methods return dataframes and one is the input to other like the code return below.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"A": [1, 2, 3], "B&... | <p>You have multiple errors:</p>
<ol>
<li>Class argument should be empty</li>
<li>In the methods <code>bar</code> and <code>baz</code> you're calling <code>df</code> instead of <code>self.df</code></li>
<li>If you want to apply a method over a method output, it has to be a <code>Foo</code> instance.</li>
</ol>
<p>Here'... | python|python-3.x|pandas|dataframe | 2 |
358,242 | 65,693,152 | Indexing a numpy array with a arrays | <p>I am trying to convert the vanilla python standard deviation function that takes n number of indexes defined by the variable <code>number</code> for calculations into numpy form. However the numpy code is faulty which is saying <code> only integer scalar arrays can be converted to a scalar index</code> is there any ... | <pre><code>In [46]: std= np.array([arr[i:i+number].std() for i in range(0, len(arr)-number)
...: ])
In [47]: std
Out[47]:
array([22.67653383, 10.3940773 , 14.60076482, 13.82801944, 13.68038469,
12.54834004, 13.13574418, 15.24698722, 14.65383773, 11.62092989,
8.57331689, 4.76392583, 9.49404494, 21.... | python|list|function|numpy|indexing | 1 |
358,243 | 65,684,415 | Exporting CSV shows ImportError: cannot import name 'CompressionOptions' from 'pandas._typing' | <p>When attempting to export to CSV the error below arises:</p>
<p>-I've tried updating pandas and then reverting to an older version with no luck.</p>
<pre><code>~\Anaconda4\lib\site-packages\pandas\core\generic.py in to_csv(self, path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encod... | <p>It seems that the problem is with the latest updates of the Pandas package (<a href="https://pypi.org/project/pandas/#history" rel="noreferrer">Release version 1.2.0 and 1.2.1</a>).</p>
<p>To solve the problem, you can <strong>downgrade the version to "1.1.5"</strong> (The latest update on the 1.1 release)... | python|pandas|csv|importerror | 12 |
358,244 | 65,712,349 | Zero diagonal of a PyTorch tensor? | <p>Is there a <strong>simple</strong> way to zero the diagonal of a PyTorch tensor?</p>
<p>For example I have:</p>
<pre><code>tensor([[2.7183, 0.4005, 2.7183, 0.5236],
[0.4005, 2.7183, 0.4004, 1.3469],
[2.7183, 0.4004, 2.7183, 0.5239],
[0.5236, 1.3469, 0.5239, 2.7183]])
</code></pre>
<p>And I wa... | <p>I believe the simplest would be to use <a href="https://pytorch.org/docs/stable/generated/torch.diagonal.html" rel="noreferrer"><code>torch.diagonal</code></a>:</p>
<pre><code>z = torch.randn(4,4)
torch.diagonal(z, 0).zero_()
print(z)
>>> tensor([[ 0.0000, -0.6211, 0.1120, 0.8362],
[-0.1043, ... | python|pytorch|tensor|diagonal | 4 |
358,245 | 65,789,613 | all features must be in [0, 9] or [-10, 0] | <p>I have the following code:</p>
<pre><code>df = load_data()
pd.set_option('display.max_columns', None)
df.dtypes
intBillID object
chBillChargeCode object
chBillNo object
chOriginalBillNo object
sdBillDate datetime64[ns]
sdDueDate ... | <p>In this line, you are selecting 10 features for X, so the shape of X is changed now.</p>
<pre><code># Separate features and labels
X, y = df[['totalDaysToPay', 'paidOnTime','dcTotFeeBilledAmt','dcFinalBillExpAmt','dcTotProgBillAmt', 'dcTotProgBillExpAmt','dcTotProgBillExpAmt','dcReceiveBillAmt','dcTotWipHours','dcTo... | python|python-3.x|pandas|dataframe | 2 |
358,246 | 65,616,374 | pandas pivot table: calculate weighted averages through aggfunc | <p>I've got a pandas dataframe on education and income that looks basically like this.</p>
<pre><code>import pandas as pd
import numpy as np
data = {
'education': ['Low', 'High', 'High', 'Medium', 'Low', 'Low', 'High', 'Low', 'Medium', 'Medium'],
'income': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'weights': [11, 1... | <p>I'm a big fan of <code>pivot_table</code>, so here it goes a solution using it:</p>
<pre><code>pivot = df.pivot_table(values='income',
index='education',
aggfunc=lambda rows: np.average(rows, weights=df.loc[rows.index, 'weights']))
</code></pre>
<p>The resulting datafram... | python|pandas|dataframe|pivot-table|weighted-average | 2 |
358,247 | 65,705,274 | How to extract Email and Phone number from same column and make it two column | <p>I have a dataset where contact column has data like this</p>
<pre><code>| id | contact |
| --- | ------------------------------------------ |
| 1 | 951-719-9170ZoeWellish@superrito.com |
| 2 | PamelaSHill@cuvox.de+1 (217... | <p>For your sample it would be done this way:</p>
<pre><code>df['Phone'] = df['contact'].str.extract(r'([+]?[0-9]+[\s+]?[\(]?[\-]?[0-9]+[\)]?[\s+]?[0-9]+[\s+]?[\-]?[0-9]+)')
df['E-mail'] = df['contact'].str.extract(r'([a-zA-Z][a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]+)')
</code></pre>
<p>Output:</p>
<pre><code>0 951... | python|pandas|dataframe|data-analysis|data-cleaning | 0 |
358,248 | 65,781,799 | Convert DataFrame Column's String to other Columns like a dictionary | <p>I Have a dataframe with like this:</p>
<pre><code> id contact
0 101 {"ref": 201, "name": "Alejandro"}
1 102 {"ref": 202, "name": "Betty"}
2 103 {"ref": 203, "name": "Jose"}
3 104 {"ref": ... | <p>You can give this a try:</p>
<pre class="lang-py prettyprint-override"><code>
import pandas as pd
d = {
'ID': [101, 102, 103, 104, 105],
'contact': [{"ref": 201, "name": "Alejandro"},
{"ref": 202, "name": "Betty"},
... | python|python-3.x|pandas|dataframe|jupyter-notebook | 0 |
358,249 | 65,909,291 | In Pandas how can I map a cell in a filtered DataFrame to the corresponding cell in the original? | <p>In the code below, I need some way to determine the value of <code>row_num_mapped</code> such that the assertion <code>val == val2</code> is always true. In other words, for a row/column in a filtered subset of <code>df</code> I need to map that cell to a row/column in the original <code>df</code>. I can use any of ... | <p>You could add a temporary sequential index to the original dataframe, and then kill it afterwards:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'a': np.random.randint(0,5,15), 'b': np.random.randint(0,5,15)},
index=np.random.randint(0,5,15))
df = df.set_index(pd.Series... | python|pandas | 1 |
358,250 | 65,712,868 | How to select a particular value from a DataFrame? | <p>How can I select a particular value from a DataFrame based on values in some column in Pandas?
I cannot use index as my data has no pandas indices</p>
<p>In SQL, I would use:</p>
<pre><code>SELECT name
FROM contacts
WHERE phone = '234-567-8900'
</code></pre>
<p>I want to return the name of the contact with the pho... | <pre><code>contacts[(contacts['Phone'] == '234-567-8900')]['name'].iloc[x]
</code></pre>
<p>x is any integer - if there's only one element then set x to 0</p>
<p>You first select all rows where contacts is 234-567-8900, and then for those rows, you take the name column</p> | python|sql|pandas|dataframe | 0 |
358,251 | 65,738,596 | Comparing two cell values and extracting the difference | <p><a href="https://i.stack.imgur.com/oNgGT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oNgGT.png" alt="enter image description here" /></a></p>
<p>Trying to compare two cell values. Per topic I need to screen whether the Old countries and New countries list is exactly the same or whether there a... | <p>Here's a working example (for one of your requests). You can alter <code>func</code> to achieve whatever you want. As is, it gets the elements in column 2 that are not in column 1.</p>
<pre><code>import pandas as pd
# some data that is in the same format as your image
df = pd.DataFrame()
df['Col1'] = ['A;E;I;O;U']
... | python|pandas | 2 |
358,252 | 65,737,829 | Drop a value iplace from series derived from data frame pandas? | <p>I just came across this code below and i am wondering why the value is not dropped from the data frame.</p>
<pre><code>import pandas as pd
cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
'Price': [22000,25000,27000,35000]
}
df = pd.DataFrame(cars, columns = ['Brand', 'Pric... | <p>The value at index <code>0</code> of <code>Brand</code> column is getting dropped. Have a look at this:</p>
<pre><code>In [1240]: df.Brand.drop(axis=0,index = 0,inplace=True)
In [1242]: df.Brand
Out[1242]:
1 Toyota Corolla
2 Ford Focus
3 Audi A4
Name: Brand, dtype: object
</code></pre>
<p>But I ... | python|pandas | 0 |
358,253 | 65,574,092 | "NumPy-est" way to generate equilateral grid | <p>I have a rectangular extent [[left, bottom], [right, top]] and an initial point [x, y]. I want to fill the extent with the equilateral point grid (of width w) on which the initial point lies.</p>
<p>So far I've found the top-left point via</p>
<pre><code>h = w * math.sqrt(3.0) / 2.0
start = np.array([right - ((right... | <pre class="lang-py prettyprint-override"><code>x_values = np.arange(start[0],right,w)
y_values = np.arange(start[1],bottom,-h)
points = np.c_[tuple(np.ravel(mesh) for mesh in np.meshgrid(x_values,y_values))]
</code></pre>
<p>Example with dummy data</p>
<pre class="lang-py prettyprint-override"><code>>>> x_val... | python|numpy|geometry|numpy-ndarray | 0 |
358,254 | 65,566,690 | how do i change indexes in an array using numba | <p>I have a function in which I do some operations and want to speed it up with <strong>numba</strong>. In my code changing the values in an array with advanced indexing is not working. I think they do say that in the numba documents. But what is a workaround for like <strong>numpy.put()</strong>?</p>
<p><em><strong>He... | <p>@mandulaj posted the way to go. Here a little different way I went before mandulaj gave his answer.</p>
<p>With this function I get a deprecation warning...so best way to go with @mandulaj and dont forget to transpose the indexList.</p>
<pre><code>@jit
def change_arr(arr,idx,val): # change values in array by np inde... | python|arrays|numpy|indexing|numba | 2 |
358,255 | 65,738,778 | Python: divide array elements that are not None | <p>Please go easy on me I'm not a programmer only a med student. I'm having trouble with doing the following operation.</p>
<p>self.longitude is a list:
self.longitude = [None, None, 1,7,3,4,....]</p>
<pre><code> self.longitude = np.array(self.longitude)
self.longitude = np.where(self.longitude is None, None, self.... | <p>You can do the following</p>
<pre><code>self.longitude[np.where(self.longitude != None)] /= 11930465
</code></pre>
<p>This does in-place division of the not None elements of <code>self.longitude</code> by <code>11930465</code>.</p> | python|numpy | 0 |
358,256 | 65,860,854 | How to save a 30- dimensional numpy array to human readable txt file in python? | <p>I'm new to python and have a question. I have following array and want to save it to a txt file.</p>
<p><code>data_arr = np.array([[str(Drahtnummer).zfill(4), str(Lagenummer).zfill(4), Position_in_Lage, "{0:07.2f}".format(x_mid), "{0:07.2f}".format(y_mid), "{0:07.2f}".format(z_0),"... | <p>You can try this format.</p>
<pre><code>a_file = open("test.txt", "w")
for row in an_array:
np.savetxt(a_file, row)
a_file.close()
</code></pre>
<p>and when you open your file. You can try this</p>
<pre><code>original_array = np.loadtxt("test.txt").reshape(dims)
print(original_arr... | python|arrays|numpy|save | 2 |
358,257 | 65,727,874 | TypeError while doing fuzzy matching | <p>I am getting a TypeError while doing fuzzy matching between 2 columns in 2 different dataframes. I have already taken care of nan's and also converted the datatype to string but it still fails. Also I'm not able to figure out which value is causing this error. I have already tried doing a match one by one by using f... | <h2>Better alternative to your goal</h2>
<p>Complete code for getting best match between 2 lists/series of strings -</p>
<ol>
<li>Use <code>itertools</code> for getting combinations of a and b lists/series.</li>
<li>Use the scorer from `Fuzz directly on each combination.</li>
<li>Use <code>np.argmax</code> to get index... | python|pandas|typeerror|fuzzywuzzy | 1 |
358,258 | 65,520,393 | How to merge 2 pandas data frames and update a column with latest value from 2 matched rows? | <p>I have 2 pandas data frames which have multiple columns.</p>
<p>Some rows have same values in all columns except one column which is <code>updated_at</code>.</p>
<p>I need to merge 2 data frames and consider the latest <code>updated_at</code> value from matched rows. <code>updated_at</code> is a datetime value.</p>
... | <p>Here is an example that will accomplish this task, I'm pretty sure. Instead of using a merge, use a <code>concat</code>, then a <code>groupby</code> with an <code>agg</code>, as follows.</p>
<pre><code>A = pd.DataFrame({'Name':['John','Joe'], 'Val':['1','3']})
Name Val
0 John 1
1 Joe 3
B = pd.DataFrame({... | python|python-3.x|pandas|dataframe|pandas-groupby | 2 |
358,259 | 65,543,423 | AttributeError: 'tuple' object has no attribute 'size' | <p>UPDATE: after looking back on this question, most of the code was unnecessary. In summary, the hidden layer of a Pytorch RNN needs to be a torch tensor. When I posted the question, the hidden layer was a tuple.</p>
<p>Below is my data loader.</p>
<pre><code>from torch.utils.data import TensorDataset, DataLoader
def... | <p>The issue comes from the fact that <code>hidden</code> (in the <code>forward</code> definition) isn't a <code>Torch.Tensor</code>. Therefore, <code>r_output, hidden = self.gru(nn_input, hidden)</code> raises a rather confusing error without specifying exaclty what's wrong in the arguments. Altough you can see it's r... | python|deep-learning|pytorch|recurrent-neural-network|gated-recurrent-unit | 4 |
358,260 | 65,644,735 | Using dataframe index containing the year as x axis | <p>I'm plotting a visualization with two y axes each representing a dataframe column. I used one of the dataframe's (both dataframes have the same index) index as the x-axis, however the xticks labels are not showing correctly. I should have years from 2000 to 2018</p>
<p>I used the following code to create the plot:</... | <p>I couldn't duplicate your issue (mpl.<strong>version</strong> = 3.2.2):</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df1 = pd.DataFrame({'col1':np.random.randint(1,7 , 19)},
index=[str(i) for i in range(2000,2019)])
print(df1.index)
df2 = pd.Series(np.l... | python|pandas|dataframe|matplotlib | 0 |
358,261 | 65,887,358 | Convert the column type from object to date format - python | <p>I have concatenated two dataframes, the column type before concatenation was datetime, but after concatenation the column type changed to object, and when I export to excel it completely changed!</p>
<p>here is the two dataframe:</p>
<p>df_last_month:</p>
<div class="s-table-container">
<table class="s-table">
<thea... | <p>How about converting the Datetime columns to string before concatenating the two dataframes. This way you can have the output you wanted.</p>
<pre><code>from pandas.api.types import is_datetime64_any_dtype
for col in df_current_month.columns:
if is_datetime64_any_dtype(df_current_month[col]):
... | python|excel|pandas|date|object | 1 |
358,262 | 65,711,368 | Python - Pandas writing blank files to file | <p>I have a python script that writes to several file formats via Pandas. It can write to CSV/JSON/HTML/Excel.</p>
<p>However for some reason the script is writing blank files. When I open the file this is what I see:</p>
<p><a href="https://i.stack.imgur.com/HNhbL.png" rel="nofollow noreferrer"><img src="https://i.sta... | <p>You can view the file in Excel by:</p>
<ol>
<li>Opening Excel</li>
<li>Going to the "Data" tab</li>
<li>In the "Get & Transform Data" section, click "From Text/CSV"</li>
</ol> | python|pandas | 1 |
358,263 | 65,534,834 | Fill in NaN in Pandas Dataframe using trend of previous valid values | <p>I am trying to fill in gaps in data by grouping and then using the trend of the previous data points to predict what the missing values are.</p>
<pre><code>df
Group Week Value
B 1 5
B 2 6
B 3 NaN
B 4 NaN
B 5 NaN
B 6 8
B 7 8
B 8 7
B 9 ... | <p>You can create subgroups Series <code>g</code> and pass <code>method="spline"</code> and <code>order=1</code> to <code>interpolate</code>:</p>
<pre><code>g = df['Value'].mask(df['Value'].notnull(), df['Value'].isnull().cumsum()).ffill()
df['Value'] = (df.groupby(['Group', g])['Value']
.ap... | python|pandas|dataframe|interpolation|extrapolation | 0 |
358,264 | 65,820,012 | Unable to convert a list into a dataframe. Keep getting the error "ValueError: Must pass 2-d input. shape=(1, 4, 5)" | <p>I have to 2 dfs:</p>
<p><strong>dfMiss:</strong></p>
<p><a href="https://i.stack.imgur.com/Jj5V4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jj5V4.png" alt="enter image description here" /></a></p>
<p>and</p>
<p><strong>dfSuper:</strong></p>
<p><a href="https://i.stack.imgur.com/vdbuH.png" rel... | <p>separate your code using SOLID. separation of concerns. It is not easy to read</p>
<pre><code> sid=[665544,665544,2121,665544,212121,123456,666666]
mission_end_date=["10/10/2020", "03/03/2021", "02/02/2021", "05/12/2020", "15/07/2021", "03/06/2021", &quo... | python|excel|pandas|dataframe|data-science | 1 |
358,265 | 21,069,572 | Best way to create a dataframe from several lists | <p>I am working through ThinkStats, but decided to learn Pandas along the ways as well. So the code below reads in data from a file, does some checking and then appends the data to a list. I end up with several lists containing the data I need. The code below works (except for scrambling up the columns...)</p>
<p>My q... | <p>I would probably use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_fwf.html" rel="nofollow"><code>read_fwf</code></a>:</p>
<pre><code>>>> df = pd.read_fwf("2002FemPreg.dat",
... colspecs=[(0,13), (274, 276), (276, 277), (277, 279), (422, 440)],
... names=["caseid", "... | python|pandas | 3 |
358,266 | 21,131,707 | Multiple data in scatter matrix | <p>Is it possible to add multiple data to a <code>pandas.tools.plotting.scatter_matrix</code> and assigning a color to each group of data?</p>
<p>I'd like to show the scatter plots with data points for one group of data, let's say, in green and the other group in red in the very same scatter matrix. The same should ap... | <p>The short answer is determine the color of each dot in the scatter plot, role it into an array and pass it as the <code>color</code> argument.</p>
<p>Example:</p>
<pre><code>from pandas.tools.plotting import scatter_matrix
import pandas as pd
from sklearn import datasets
iris = datasets.load_iris()
iris_data = pd... | python|pandas|scatter-plot | 21 |
358,267 | 20,915,800 | Plotting with GroupBy in Pandas/Python | <p>Although it is straight-forward and easy to plot groupby objects in pandas, I am wondering what the most pythonic (pandastic?) way to grab the unique groups from a groupby object is. For example:
I am working with atmospheric data and trying to plot diurnal trends over a period of several days or more. The followi... | <p>Storing the groupby stats (mean/25/75) as columns in a new dataframe and then passing the new dataframe's <code>index</code> as the <code>x</code> parameter of <code>plt.fill_between()</code> works for me (tested with matplotlib 1.3.1). e.g.,</p>
<pre><code>gdf = df.groupby('Time')[col].describe().unstack()
plt.fi... | python|matplotlib|pandas | 5 |
358,268 | 21,010,247 | IPython engines returning different results | <p>Hopefully someone can enlighten me without me having to post a lot of confusing code.</p>
<p>I am using IPython.parallel to process neural networks. In an attempt to find a bug I decided to send the same network out to each client with the same input data. I would expect to have each client return the same answer... | <p>Thought I should show the answer (if it can be called that) here as well...</p>
<p>Please see <a href="https://stackoverflow.com/questions/21268990/debug-ipython-parallel-engines-in-cluster/21271896#21271896">THIS THREAD.</a></p> | python|numpy|ipython|ipython-parallel | 0 |
358,269 | 63,523,512 | Pandas groupby and resample gives unusual result | <p>I have created a DataFrame with following data</p>
<pre><code>Time Source Destination User ID
1/1/20 12:00 1.2.3.4 5.6.7.8 a1
1/1/20 12:01 1.3.4.5 6.7.8.9 a2
1/1/20 12:02 1.3.4.5 7.2.3.4 a2
1/1/20 12:03 1.2.3.4 5.6.7.8 a1
1/1/20 12:04 ... | <p>Python counters start at <code>0</code>. So instead of getting <code>1,2,3</code>, Python gives <code>0,1,2</code>. If that is an issue you can always just add 1 to each counter.</p>
<p><code>1/1/2020 12:05 1.3.4.5 7.2.3.4 a2 0</code> is actually 1.</p> | python-3.x|pandas | 0 |
358,270 | 63,474,342 | Add columns based on indexing in rows | <p>I have a dataframe like</p>
<pre><code>df =
Group lst
0 A [0,0,1,0,1,0,0]
1 B [1,1,0,0,0,0,0,1,0]
2 C [0,0,1,0]
3 D [0,1,0,1,0]
</code></pre>
<p>I want to add a column with a list containing the indices of all 1 items in that row and another column ... | <p>You get the length of lists in a column with <code>pd.Series.str.len</code>. We can use <code>np.where</code> to get the indices, assuming 1 and 0 are the only possible values (Though it's a slow apply over the rows).</p>
<pre><code>import numpy as np
df['one_inds'] = df['lst'].apply(lambda x: np.where(x)[0].tolist... | python|pandas | 3 |
358,271 | 63,695,839 | How to groupby based on multiple columns in pandas? | <p>I want to group by a dataframe based on multiple columns. For example to make this:</p>
<pre><code>Country Type_1 Type_2 Type_3 Type_4 Type_5
China A B C D E
Spain A A R B C
Italy B A B R R
</code></pre>
<p>Into this:</p>
<pre><code>... | <p>Do <code>melt</code> then <code>groupby</code> with <code>size</code></p>
<pre><code>s = df.melt('Country').groupby(['Country','value']).size()
Out[326]:
Country value
China A 1
B 1
C 1
D 1
E 1
Italy A 1
B 2
... | python|pandas|group-by|concat | 1 |
358,272 | 63,715,745 | Merging a dataframe by specific column for python | <p>How do you merge the data so that you always merge to the longest column.</p>
<p>Currently my code is:</p>
<pre><code>csvs = lsit of data frames
df_final = reduce(lambda left,right: pd.merge(left,right,on='LEVELS',how="left"), csvs)
df_final = df_final.fillna('')
</code></pre>
<p>Which produces this:</p>
... | <p>Have you tried if statement according to the length of the rows?
for instance</p>
<pre><code>row1=df1.shape[0]
row2=df2.shape[0]
if row1>row2:
xxxxxxx
else:
xxxx
</code></pre> | python|python-3.x|pandas|dataframe|csv | 0 |
358,273 | 63,431,240 | Unhashable type: 'set' when I draw a network | <p>I would like to understand why I am getting this error: <code>TypeError: unhashable type: 'set'</code>, when I run this code</p>
<pre><code>import matplotlib.pyplot as plt
import networkx as nx
def my_function(file):
file = file.explode('Two')
G = nx.DiGraph()
nx.add_path(G, file['One'])
nx.add_pat... | <p>When you adding the path you can <code>explode</code> the dataframe first</p>
<pre><code>df = df.assign(Two=df.Two.map(list)).explode('Two')
</code></pre> | python|pandas | 0 |
358,274 | 63,422,844 | How to judge whether the sample in a new data set belongs to original data set in PyTorch? | <p>I am new to PyTorch. Now, I have two data sets named A and B (eg: MNIST). I want to mix A and B together to form a new data set. And I want to shuffle this new data set. During the period of training, I need to determine whether the sample in batch is belongs to A. How can I do this?</p>
<p>The two problems are as f... | <p>By defining custom dataset and some flag labels you can achieve that.
Here's sample code:</p>
<pre><code>import torch
from torch.utils.data import DataLoader, Dataset
class to_dataset(Dataset):
def __init__(self , data_A, data_B):
self.lena = data_A.shape[0]
self.len = data_A.shape[0] + d... | dataset|pytorch|shuffle | 0 |
358,275 | 63,733,384 | pandas rolling function with Lamdba | <p>I was working on the older pandas 0.24.0 version where I had code:</p>
<pre><code>df["A"] = df['B'].rolling(window=2).apply(lambda x: x[0] - x[1])
</code></pre>
<p>However the pandas version was upgraded to 1.1.0, which causes this code to not work.
I tried using different variations of rolling function wi... | <p>This is more like <code>shift</code></p>
<pre><code>df['A'] = df['B'] - df['B'].shift()
</code></pre> | pandas|lambda|rolling-computation | 1 |
358,276 | 63,683,000 | Why multiindex dataframe will return all index after selection? | <p>I find one thing is very strange about multiindex dataframe:</p>
<p>For a very simple df:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([{'Name': 'Chris', 'Item Purchased': 'Sponge', 'Cost': 22.50},
{'Name': 'Kevyn', 'Item Purchased': 'Kitty Litter', 'Cost': 2.50},
{'Name': 'Filip', 'Item Purchased': 'Spoo... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.remove_unused_levels.html" rel="nofollow noreferrer"><code>MultiIndex.remove_unused_levels</code></a>:</p>
<pre><code>df4.index = df4.index.remove_unused_levels()
print (df4.index.levels[0])
</code></pre> | python|pandas|multi-index | 0 |
358,277 | 63,454,448 | How do I run a function on all pandas columns that end in _DT | <p>I am trying to run a data cleanup script in Python. I have a base class with a function called cleanData(). Depending on the dataset returned, there are a number of date fields, all of which end in _DT, but could start with anything (such as SCHEDULED_START_DT, SERVICE_DISRUPT_DT, etc). This code will support hun... | <p><code>list(df.columns)</code> wiil return the the column names.</p>
<p>Loop over it and do the thing:</p>
<pre><code>for name in list(df.columns):
if name.endswith('_DT'):
#your logic goes here
</code></pre> | python|pandas | 2 |
358,278 | 63,355,107 | Keras.ImageDataGenerator result display [flow()] | <p>I am trying to display images generated by the Imagedatagenerator.flow() but I am unable to do so.</p>
<p>I am using a single image and passing that to the .flow(img_path) to generate augmented images by until the total matches our requirement:</p>
<pre><code>total = 0
for image in imageGen:
total += 1
if total == 1... | <p>If you want to use the image path you can use <a href="https://keras.io/api/preprocessing/image/#flowfromdirectory-method" rel="noreferrer">flow_from_directory</a>, and pass the image folder containing the single image. To obtain the images from the generator use <code>dir_It.next()</code> and access the first eleme... | python-3.x|tensorflow|keras|tensorflow2.0 | 10 |
358,279 | 63,515,458 | How do I join the values of two columns in a Pandas dataframe only if none are NaN | <p>I'm trying to join two string in a new column within a DataFrame, but have tried several approaches and none work, the closest I have come is with a lambda formula, but still can't understand the problem. Can anyone help?</p>
<p>Data frame:</p>
<pre><code> full_name certificacion company
member_#
... | <p>Since both columns are strings, you can add them together with a <code>+</code> with <code>, </code> between. Then for the rows that have <code>NaN</code> just handle those with <code>np.where()</code> logic to use <code>full_name</code> instead of <code>member_name</code>:</p>
<pre><code>df['member_name'] = df['ful... | python|pandas|dataframe|notnull | 2 |
358,280 | 63,724,741 | AttributeError: module 'pandas.api' has no attribute 'indexers' | <p>I receive the following error: <code>AttributeError: module 'pandas.api' has no attribute 'indexers'</code>
when executing this code, which is directly copied from the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer">documentation</a>:</p>
<... | <p>Upgrade pandas, because need at least pandas 1.1.0 - <a href="https://pandas.pydata.org/pandas-docs/stable/whatsnew/v1.1.0.html?highlight=fixedforwardwindowindexer" rel="nofollow noreferrer">link</a>:</p>
<blockquote>
<p>Added a pandas.api.indexers.FixedForwardWindowIndexer() class to support forward-looking windows... | python|pandas | 3 |
358,281 | 63,568,895 | How to compare dates from two dataframes and update the value in the column | <p>I have two dataframes that refer to weather stations:</p>
<pre><code> import pandas as pd
df_shift = pd.DataFrame({'Date': ['2010-10-05', '2010-10-20', '2011-03-15',
'2012-03-22', '2015-01-17', '2015-01-23',
'2015-01-30'],
'S... | <p>We do <code>merge_asof</code>, take the usage of <code>by</code> and <code>on</code></p>
<pre><code>df_station['Date'] = pd.to_datetime(df_station['Date'])
df_shift['Date'] = pd.to_datetime(df_shift['Date'])
df_shift['DIFF'] = df_shift['Date']
df = pd.merge_asof(df_station, df_shift[['Date', 'Sensor_id', 'DIFF']],
... | python|pandas|for-loop | 2 |
358,282 | 63,651,356 | Tensorflow 1.2.1 :AttributeError: module 'tensorflow' has no attribute 'random' | <p>I have installed tensorflow 1.2.1 and whenever i try to run</p>
<p><code> c=tf.random.normal(shape=(3,4),dtype=tf.float32)</code></p>
<p>I get the error <code>AttributeError: module 'tensorflow' has no attribute 'random'</code></p> | <p>Use</p>
<pre><code>c = tf.random_normal(shape=(3,4),dtype=tf.float32))
</code></pre>
<p>See the full list of available APIs <a href="https://github.com/tensorflow/docs/blob/r1.2/site/en/api_docs/python/index.md" rel="nofollow noreferrer">here</a></p>
<p>See the usage <a href="https://github.com/tensorflow/docs/blob/... | tensorflow|python-3.6 | 0 |
358,283 | 63,582,798 | geopandas sjoin returning empty rows | <p>I have a table of polygons of all UK output areas structured as such:</p>
<pre><code>newpoly
OBJECTID OA11CD LAD11CD Shape__Are Shape__Len TCITY15NM geometry
67519 67520 E00069658 E06000018 3.396296e+04 1006.464423 Nottingham POLYGON ((456069.067 340766.874, 456057.000 34...
67520 675... | <p>You are using different projections. I am sure GeoPandas <code>sjoin</code> actually warns you about that. Create your point layer in the following way:</p>
<pre class="lang-py prettyprint-override"><code>restaurants = pd.read_csv('Restaurants_clean.csv')
restaurants = gpd.GeoDataFrame(
restaurants,
geometr... | python|geopandas | 1 |
358,284 | 63,358,036 | pandas to_sql in django: insert foreign key into DB | <p><strong>Is there a way to insert foreign keys when using pandas to_sql function?</strong></p>
<p>I am processing uploaded <code>Consultation</code>s (n=40k) with pandas in django, before adding them to the database (postgres). I got this working row by row, but that takes 15 to 20 minutes. This is longer than I want... | <p>I had same problem and this is how I solved it. My answer isn't as straight forward but I trust it helps.</p>
<p>Inspect your django project to be sure of two things:</p>
<ol>
<li>Target table name</li>
<li>Table column names</li>
</ol>
<p>In My case, I use <code>class Meta</code> when defining django models to use ... | django-models|foreign-keys|django-database|django-postgresql|pandas-to-sql | 2 |
358,285 | 63,336,125 | Python Pandas: applying a specific function to each row | <p>I'm trying to apply a form of normalization to the data I have. I wish to subtract the <strong>median of each row</strong> from each value in the dataframe. What I have so far:</p>
<pre><code># Generate sample data
data = { "sample_name": ["s1", "s2", "s3", "s4", &qu... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>DataFrame.select_dtypes</code></a> for get numeric columns and subtract by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sub.html" rel="nof... | python|pandas | 3 |
358,286 | 63,430,837 | Difference between giving pandas a python iterable vs a pd.Series for column | <p>What are some of the differences between passing a <code>List</code> vs a <code>pd.Series</code> type to create a new dataFrame column? For example, from trial-and-error I've noticed:</p>
<pre><code># (1d) We can also give it a Series, which is quite similar to giving it a List
df['cost1'] = pd.Series([random.choice... | <p><code>List</code> assign to dataframe here require the same length</p>
<p>For the <code>pd.Series</code> assign , it will use the index as key to match original <code>DataFrame</code> <code>index</code>, then fill the value with the same index in <code>Series</code></p>
<pre><code>df=pd.DataFrame([1,2,3],index=[9,8,... | python|pandas|dataframe|iterable | 3 |
358,287 | 63,730,939 | How to determine if any value in one array, is lower than any value in another array, for a given bin? | <p>I am trying to compare different lines, to know if one is above the other one, and if not, at which <code>x</code> this change happens.</p>
<p>If I had the same <code>x</code> values and same length, that would be very easy and only difference in <code>y</code>s of the lines.</p>
<p>But I have different <code>x</cod... | <h2>Functions</h2>
<ul>
<li><code>def get_new_x</code> uses <a href="https://numpy.org/doc/stable/reference/generated/numpy.digitize.html" rel="nofollow noreferrer"><code>np.digitize</code></a> to re-bin the x-axis values.</li>
<li><code>def get_comparison</code> adds a column of Booleans for each two columns compared
... | python|pandas|numpy|compare|line | 1 |
358,288 | 63,479,262 | TypeError: expected string or bytes-like object when using NLTK word_tokenize | <p>I am trying to import a CSV file and then using NLTK to analyse the text. The CSV file contain several columns but now I only want to analyse one column in this file so far.</p>
<p>The sample of csv file is:
<a href="https://i.stack.imgur.com/vjScL.png" rel="nofollow noreferrer">sample data from csv file</a></p>
<p... | <p>Make sure there are no NaNs in that column</p>
<pre><code>data.SAT_COMMENTS = data.SAT_COMMENTS.fillna('')
</code></pre> | pandas|csv | 0 |
358,289 | 63,470,907 | Why does `is_same` in the C++ PyTorch API fail when comparing with the same tensor that is read from a file? | <p>Why does <code>torch::Tensor::is_same</code> fail the following assertion? A tensor is written to a file using the C++ PyTorch API, then read again into another tensor, and <code>is_same</code> compares both tensors:</p>
<pre><code>torch::Tensor x_sequence = torch::linspace(0, M_PI, 1000);
torch::save(x_sequence... | <p><code>torch::Tensor::is_same(const torch::Tensor& other)</code>is defined <a href="https://github.com/pytorch/pytorch/blob/b2e52186b93b786b1ed812179804fd2496c6efd1/caffe2/core/tensor.h" rel="nofollow noreferrer">here</a>. It is important to notice that a <code>Tensor</code> is actually a pointer on an underlying... | pytorch|libtorch | 2 |
358,290 | 63,582,979 | Merge all tables from SQLite3 database into one single pandas dataframe | <p>I would like to undertake some anaylsis of the tables within my database. But to do this, first I need to merge my sqlite3 tables into one single pandas dataframe.</p>
<p>All the tables are identical in structure.</p>
<p>I would also like the dataframe to have the column headers at the top.</p>
<p>The link below tou... | <p>I have just stumbled across a simple solution to my own question:</p>
<pre><code>conn = sqlite3.connect('name_of.db')
cur = conn.cursor()
cur.execute('INSERT INTO master_table SELECT * FROM table_name1)
cur.execute('INSERT INTO master_table SELECT * FROM table_name2)
cur.execute('INSERT INTO master_table SELECT *... | python|pandas|sqlite|dataframe | 0 |
358,291 | 63,454,811 | Convert sklearn diabetes dataset into pandas DataFrame | <p>How to convert sklearn diabetes dataset into pandas DataFrame?</p>
<p>code:</p>
<pre><code>import pandas as pd
from sklearn.datasets import load_diabetes
data = load_diabetes()
</code></pre> | <p>From the sklearn website. You can pass as_frame to specify a pandas dataframe.
<a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html</a></p>
<p><code>data = load_d... | python|pandas|scikit-learn | 1 |
358,292 | 63,353,841 | KMeans vectorized implementation updating cluster centroids. Numpy pro | <p>I'mn implementing kmeans in python. In a single iteration i have computed the center labels for each 150 points:</p>
<pre><code>label =
array([0, 1, 2, 3, 4, 5, 6, 7, 3, 1, 5, 7, 1, 2, 5, 5, 5, 0, 5, 4, 0, 4,
6, 7, 7, 1, 7, 0, 0, 3, 3, 0, 5, 5, 1, 1, 0, 4, 3, 7, 0, 1, 3, 7,
5, 1, 4, 3, 0, 7, 5, 5, 5, ... | <h2>Update centers</h2>
<p>You can use <a href="https://numpy.org/devdocs/reference/arrays.indexing.html" rel="nofollow noreferrer">boolean array indexing</a> and <a href="https://numpy.org/doc/stable/glossary.html" rel="nofollow noreferrer">computation along an axis</a> to only explicitly iterate over the clusters ins... | python|numpy|vectorization | 2 |
358,293 | 63,556,669 | Numpy array all and any operation with combination in 3d array | <p>I'm very new to numpy. I have an array like this and want to apply some operations on it.
It's easy in 2d array, lots of example are there but won't any such in 3d array.</p>
<pre><code>arr = np.array([[[ True, True, False, True],[False, False, True, False],[False, False, False, False], [False, False, False, False],... | <p>I think the issue comes from confusion in the axis handling.</p>
<p>As a rule of thumb, you can consider that the innermost brackets contain data of the highest dimension.</p>
<p>In your example, if you type <code>arr.shape</code> in your interpreter it will return the following tuple <code>(3, 5, 4)</code> which re... | python|python-3.x|numpy|scipy|numpy-ndarray | 1 |
358,294 | 63,562,627 | EfficientDet Low Accuracy | <p>I use TensorFlow 2.3 and tested all EfficientDet models. It is written on the TensorFlow github <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md" rel="nofollow noreferrer">page</a> that EfficientDet D7 has higher mAP than NasNet as 51.5 > 43 <a href="h... | <p>The first place to check is whether you have done all the input preprocessing steps for respective model incase you are using COCO or PASCAL VOC pretrained model. If you are doing custom training there are many a ways a model can do wrong. Kindly check this out <a href="https://karpathy.github.io/2019/04/25/recipe/"... | tensorflow|tensorflow2.0|object-detection-api|faster-rcnn|efficientnet | 2 |
358,295 | 63,512,562 | Python ConvNet Image Classifier - "ValueError" when fitting a model for a binary image classification | <p>I am very new to deep learning and TensorFlow/Keras, so I'm having trouble understanding why I am throwing an error when trying to fit a model to classify images as either "dogs" or "cats." (image database can be found here: <a href="https://www.microsoft.com/en-us/download/details.aspx?id=54765"... | <p>You should do transformation proccess for numpy array of y, not just X.</p>
<pre class="lang-py prettyprint-override"><code>X = []
y = []
for features,label in training_data:
X.append(features)
y.append(label)
print(X[0].reshape(-1, IMG_SIZE, IMG_SIZE, 1))
X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1... | python|numpy|tensorflow|machine-learning|keras | 4 |
358,296 | 63,581,778 | merge two dataframes by following a specific pattern | <p>I have two df :</p>
<pre><code>date=pd.date_range(start = '8/1/2020 7:00:00', end ='8/1/2020 7:15:00',freq='min')
df1=pd.DataFrame({'date':date})
</code></pre>
<p>and</p>
<pre><code>df2=pd.DataFrame({'date':[dt.datetime(2020,8,1,7,0),dt.datetime(2020,8,1,7,6),dt.datetime(2020,8,1,7,12)],'count':[5,6,1]})
</code></pr... | <pre><code>date=pd.date_range(start = '1/8/2020 7:00:00', end ='1/8/2020 7:15:00',freq='min')
df1=pd.DataFrame({'date':date})
df2=pd.DataFrame({'date':[dt.datetime(2020,1,8,7,0),dt.datetime(2020,1,8,7,6),dt.datetime(2020,1,8,7,12)],'count':[5,6,1]})
#I've corrected your input df2, months<-> days position
df3= ... | python|pandas|datetime|join|merge | 3 |
358,297 | 63,359,502 | How to replace a value in a Pandas Dataframe Index with another given a date range? | <p>Suppose I have a multi-index Pandas Dataframe that has a structure like this</p>
<pre><code>df1
value
Key1 date
A 2010-01-01 1
2010-01-02 2
...
B 2010-01-01 1
2010-01-02 1
</code></pre>
<p>I have another Dataframe that looks like this that maps Key1 to Ke... | <p>You can merge both tables on their key1 and drop the columns that you don't want to have</p>
<pre><code>df = pd.merge(df1, df2, on='Key1')
df.drop('date', axis = 1)
</code></pre>
<p>you can drop as much as you want and if they are not identical in means of dates. You can delete nulls with dropna() function.</p> | python|pandas|dataframe | 0 |
358,298 | 63,611,125 | "Axis -1 does not exist for dimension 0" error when using numpy vectorize | <p>I am trying to map a custom function to each element of a numpy array. The function in question:</p>
<pre><code>def find_closest(value, lookup_array, breed=True):
if breed == True:
return lookup_array[sum(lookup_array <= value) - 1]
else:
return lookup_array[sum(lookup_array >= value) -... | <p>you forgot to tell the program it is not allowed to vectorize over the lookup array. You can fix that easily by using the parameter excluded. This code worked fine for me (note that the parameters now have to be named):</p>
<pre><code>import numpy as np
def find_closest(value, lookup_array, breed=True):
if bree... | python|numpy|vectorization | 1 |
358,299 | 63,673,923 | How to I get summary statistics by rows while using Pandas df.describe() , | <p>I have issues when trying to get summary statistics from my dataframe.</p>
<p>I need the function to calculate all the summary statistics by rows.</p>
<p>for example, mean = adding up all the values in a row and divided by the number of observations in a row</p> | <p>You can turn rows into columns and then use describe:</p>
<pre><code>df.T.describe()
</code></pre> | python|pandas | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.