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 |
|---|---|---|---|---|---|---|
370,900 | 48,998,843 | Appending to a new column the differences of current row and previous row, for multiple columns | <p>For each of the columns in my df, I want to subtract the current row from the previous row (row[n+1]-row[n]), but I am having difficulty.</p>
<p>My code is as follows:</p>
<pre><code>#!/usr/bin/python3
from pandas_datareader import data
import pandas as pd
import fix_yahoo_finance as yf
yf.pdr_override()
import os... | <p>Here is an easy and quick way to do what you want:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(25).reshape(5, 5),
columns=['A', 'B', 'C', 'D', 'E'])
print(df)
</code></pre>
<p>result:</p>
<pre><code> A B C D E
0 0 1 2 3 4
1 5 6 7... | python|pandas|numpy|dataframe | 1 |
370,901 | 48,998,583 | Dynamic Count of Boolean Operations in Python | <p>I want to be able to change the number of boolean operations based on an input integer.
Is this possible? </p>
<p>Ex: </p>
<ul>
<li>Input 2: <code>a = df[0] & df[1]</code></li>
<li>Input 3: <code>a = df[0] & df[1] & df[2]</code></li>
</ul> | <p>For your particular example:</p>
<pre><code>n = <Desired number>
a = df[0]
for i in range(1, n):
a &= df[i]
</code></pre> | python|python-3.x|pandas|numpy|boolean | 1 |
370,902 | 49,202,052 | how to join 2 dataframes when the key in DF1 is a substring of the key in DF2 | <p>hi I need to join 2 dataframes but they dont have a common column.</p>
<p>instead, I need to do it based on partial/substring match, i.e. I want rows to be associated if the key in DF1 is a substring of the key in DF2.</p>
<p>thanks in advance!</p>
<p>EDIT:</p>
<p>it'd be the pandas variant to this question</p>
... | <p>Just re-create a substring with the partial match on DF2 </p>
<p>i.e.</p>
<pre><code>DF2['subkey'] = DF2['key'].str[:5] # equivalent to left 6 characters
</code></pre>
<p>Or, if it is located in various parts of the string itself:</p>
<pre><code>DF2['subkey'] = DF2['key'].apply(lambda x: [item for item in x if i... | python|pandas|dataframe | 0 |
370,903 | 49,089,471 | Summing and plotting by month and arbitrary attribute in Pandas | <p>I'm currently getting into data analysis and am building a little accounting app to keep track of my expenses.</p>
<p>My goal is to track my expenses in a Django app, make some analyses with Pandas on it and visualize it with Matplotlib.</p>
<p>My data basis comes from a Django ORM query like this:</p>
<pre><code>qs... | <p>Consider pivoting your groupby result where each category becomes their own column to be individual lines. Below demonstrates with random data (seeded for reproducibility):</p>
<p><strong>Data</strong> </p>
<pre><code>import numpy as np
import pandas as pd
import datetime as dt
import time
import matplotlib.py... | python|pandas|matplotlib | 4 |
370,904 | 49,308,247 | dataframe datetimeindex changes | <p>I have a dataframe with a date column. I want to turn this date column into my index. When I change the date column into <code>pd.to_datetime(df['Date'], errors='raise', dayfirst=True)</code> I get:</p>
<pre><code>df1.head()
Out[60]:
Date Open High Low Close Volume Market Cap
0 20... | <p>According to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer">the docs</a>:</p>
<blockquote>
<p>dayfirst : boolean, default False</p>
<p>Specify a date parse order if arg is str or its list-likes. If True,
parses dates with the day first, eg... | python|pandas|datetime|indexing | 1 |
370,905 | 49,157,077 | Pandas. How to read Excel file from ZIP archive | <p>I have .zip archive with filename.xlsx inside it and I want to parse Excel sheet line by line.</p>
<p>How to proper pass filename into pandas.read_excel in this case?</p>
<p>I tried:</p>
<pre><code>import zipfile
import pandas
myzip=zipfile.ZipFile(filename.zip)
for fname in myzip.namelist():
with myzip.open(... | <p>You can extract your zip-file into a variable in memory and parse it using <code>io.BytesIO</code>:</p>
<pre><code>import io
from zipfile import ZipFile
import pandas as pd
def read_zip(zip_fn, extract_fn=None):
zf = ZipFile(zip_fn)
if extract_fn:
return zf.read(extract_fn)
else:
retur... | python|pandas|zip | 14 |
370,906 | 48,973,801 | numpy broadcasting to all dimensions | <p>I have a 3d numpy array build like this:</p>
<pre><code>a = np.ones((3,3,3))
</code></pre>
<p>And I would like to broadcast values on all dimensions starting from a certain point with given coordinates, but the number of dimensions may vary.</p>
<p>For example if i'm given the coordinates <code>(1,1,1)</code> I c... | <p>What you want to do can be done programmatically using a <code>slice</code> object that is instantiated using the <code>slice</code> function — e.g., see <a href="https://docs.scipy.org/doc/numpy/user/basics.indexing.html#dealing-with-variable-numbers-of-indices-within-programs" rel="nofollow noreferrer">" Dealing w... | python|numpy | 2 |
370,907 | 48,953,373 | Cant seem to flatten numpy array | <p>I have a numpy array which when <code>print</code>-ed looks like this:</p>
<pre><code>print(a.shape)
(21,)
print(a)
[array([8.55570588e+03, 4.23078573e+05, 2.81254715e+07, 2.10356201e+09,
4.24558286e+05, 2.10032147e+07, 1.39638949e+09, 1.04453957e+11,
2.81593475e+07, 1.39354786e+09, 9.26480296e+10, 6.... | <p>One simple way is to use <code>np.hstack</code> in order to flatten list of array and float. Example usage is as follows:</p>
<pre><code>import numpy as np
a = [np.array([1, 2, 3]), np.array([4, 5, 6]), 7, 8, 9]
np.hstack(a)
>> array([1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre> | python|numpy | 2 |
370,908 | 49,280,161 | Avoiding parsing errors due to space character as delimiter + text in Python text files | <p>If a textfile contains a character, say space, as both a delimiter and part of text, how should we read the file using pandas read_csv, read_table or file read?</p> | <p>You can use these array keys to gather elements dynamically, so the first 6 elements will be captured as you expect (Note that the <code>line</code> variable should be in some loop that iterates over every line in the file, assigning the line the to a variable named 'line'):</p>
<pre><code> elements = line.split(" ... | python|pandas|csv|text-files|delimiter | 0 |
370,909 | 58,775,178 | Filtering outliers within each category of categorical data in pandas | <p>I'm new to pandas/seaborn/etc and attempting to graph a subset of my data in a different style (using seaborn), using something like the example here <a href="https://seaborn.pydata.org/generated/seaborn.stripplot.html" rel="nofollow noreferrer">https://seaborn.pydata.org/generated/seaborn.stripplot.html</a> :</p>
... | <p>Here is a small example I created to guide you. I hope it is helpful.</p>
<p>Code</p>
<pre><code>import numpy as np
import pandas as pd
import seaborn as sns
#create a sample data frame
n = 1000
prng = np.random.RandomState(123)
x = prng.uniform(low=1, high=5, size=(n,)).astype('int')
#print(x[:10])
#[3 2 1 3 3 ... | python|pandas|numpy|seaborn | 1 |
370,910 | 58,906,532 | Difference between .find() and 'in' operator in python | <p>I'm working on Dataframe with pandas called <em>filteredDS</em></p>
<p><strong><em>The aim:</em></strong></p>
<blockquote>
<p>Searching for all data, whose <em>question</em> column contains <em>'King'</em> word.</p>
</blockquote>
<p>When I add the column <em>king_quest</em> via <em>in</em> operator like this:</... | <p>There might be multiple issues here.</p>
<ol>
<li><p>Your find is looking for different values in the statements. ' King ' (spaces, initial letter cap in one) and just 'king' in the other.</p>
</li>
<li><p>x.find('king') returns the index of the first matching and -1 otherwise. If you want to use this to check, you ... | python|pandas|find|in-operator | 2 |
370,911 | 58,614,010 | Reliably dealing with nans in pandas | <p>What's the best and hopefully easiest way to write over NaNs, also noting different cases?</p>
<p>In this example <code>df</code>, I want to replace the NaNs in <code>Routed (Expected) Site</code> according to business logic:</p>
<pre><code> DBN DBN - Exam Routed (Expected) Site
00000A 00000A - Scie ... | <h3><code>fillna</code> and <code>map</code></h3>
<p>I make an assumption that I don't know all that your business logic will entail. So I kept it fairly generalized.</p>
<pre><code>def routed_site_exceptions(DBN):
DBN = str(DBN)
if DBN.startswith("84"):
return '84 (Charter)'
if DBN.startswith('7... | python|pandas | 4 |
370,912 | 59,022,199 | Getting a number of items created in a particular year in Pandas | <p>I am writing a function that returns a number of items created in a particular year in a pandas data frame where the search is made in a column ['çreation'] that has a format 2015-05-11 :</p>
<pre class="lang-py prettyprint-override"><code>def do_get_citations_per_year(data, year):
result = tuple()
citation... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>def do_get_citations_per_year(data, year):
result = tuple()
citations = list()
my_ocan['creation'] = pd.DatetimeIndex(my_ocan['creation']).year
for index, row in my_ocan.iterrows():
#print(my_ocan['creation'])
if row['creation... | python|python-3.x|pandas | 0 |
370,913 | 58,752,540 | How to access the contents of an excel file stored in my model - django | <p>I am developing an app in Django.
I have a file model (let's say <code>my_file_model</code>) like this:</p>
<pre><code>class my_file_model(models.Model):
file = models.FileField(upload_to='myDirectory/', blank=False, null=False)
</code></pre>
<p>in which are stored excel sheets like this:</p>
<p><a href="http... | <p>SOLVED:</p>
<pre><code>def pour_entire__my_file_model():
import pandas as pd
from .models import my_file_model, output_model
all_files = my_file_model.objects.all()
for file_element in all_files:
excel_sheet = pd.read_excel(file_element.My_file_model)
var_col_A = excel_sheet.Colu... | python|django|excel|pandas|file | 0 |
370,914 | 58,970,159 | How to split data by using train_test_split in Python Numpy into train, test and validation data set? The split should not random | <p>I want to split data category wise into train, test and validation set. For example: if we have 3 categories positive, negative and neutral in the dataset. The positive category split into train, test, and validation. And the same with the other two categories. The splitting ratio is 80% of the data is for training ... | <p>You can use the <code>stratify</code> parameter to do this:</p>
<p>For example:
If you were to use Iris dataset to do this.</p>
<pre><code>from sklearn import cross_validation, datasets
X = iris.data[:,:2]
y = iris.target
cross_validation.train_test_split(X,y,stratify=y)
</code></pre>
<p>You can read more here... | python|numpy|train-test-split | 0 |
370,915 | 58,892,870 | concatenate in place in sub function with pandas concat function? | <p>I'm trying to write a function that take a pandas Dataframe as argument and at some concatenate this datagframe with another.</p>
<p>for exemple:</p>
<pre><code>def concat(df):
df = pd.concat((df, pd.DataFrame({'E': [1, 1, 1]})), axis=1)
</code></pre>
<p>I would like this function to modify in place the input... | <p>This will edit the original DataFrame inplace and give the desired output as long as the new data contains the same number of rows as the original, and there are no conflicting column names.</p>
<p>It's the same idea as your <code>df['E'] = [1, 1, 1]</code> suggestion, except it will work for an arbitrary number of... | python|pandas | 1 |
370,916 | 58,841,401 | Tensorflow 2.0: Packing numerical features of a dataset together in a functional way | <p>I am trying to reproduce Tensorflow tutorial code from <a href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/load_data/csv.ipynb" rel="nofollow noreferrer">here</a> which is supposed to download <code>CSV</code> file and preprocess data (up to combining numerical data together).</p>
<p>The repro... | <p>After some research and trial the answer to the second question seems to be:</p>
<pre><code>def pack_func(features, labels, num_columns=num_columns):
num_features = [features.pop(name) for name in num_columns]
num_features = [tf.cast(feat, tf.float32) for feat in num_features]
num_features = tf.stack(nu... | python|csv|tensorflow|tensorflow2.0 | 0 |
370,917 | 58,625,890 | How to drop the unwanted columns after resampling a dataframe | <p>I have created a dataframe with the following code:</p>
<pre><code>import pandas as pd
import numpy as np
Timestamp = pd.date_range('21/1/2019', periods=2500, freq='10S')
df = pd.DataFrame(dtype=float)
df['Timestamp'] = Timestamp
LTP = np.arange(100,2600,1)
lowest_sell = np.arange(121,1371,0.5)
highest_buy = np.ara... | <p>You could do:</p>
<pre><code>close_columns = [column for column in resamp.columns if column[1] == 'close']
result = resamp[close_columns]
print(result)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> a-LTP b-Lowest_Sell c-Highest_Buy
close close clo... | pandas|dataframe|resampling | 3 |
370,918 | 59,007,569 | Why Pandas refuse to read a date 9 centuries into the future? | <p>Consider this example df.</p>
<pre><code>
import pandas as pd
from io import StringIO
mycsv = StringIO("id,date\n1,11/07/2018\n2,11/07/<b>2918</b>\n3,02/01/2019")
df = pd.read_csv(mycsv)
df
</code></pre>
<pre><code> id date
0 1 11/07/2018
1 2 11/07/2918
2 3 02/01/2019
</code></pre>
<p>Clearly ther... | <p>From the docs:</p>
<pre><code>Since pandas represents timestamps in nanosecond resolution, the time span that can
be represented using a 64-bit integer is limited to approximately 584 years:
In [92]: pd.Timestamp.min
Out[92]: Timestamp('1677-09-21 00:12:43.145225')
In [93]: pd.Timestamp.max
Out[93]: Timestamp('2... | python|python-3.x|pandas|python-datetime | 2 |
370,919 | 58,644,199 | How to drop row in pandas dataframe according to a condition on the index of the row | <p>I have a dataframe called Prod with this shape:</p>
<pre><code>carriers electricity
techs
ETH_imp 0.000000e+00
T:Arusha 1.786273e+06
T:Dar_es_Salaam 0.000000e+00
T:Dodoma 3.348339e+08
T:Geita 0.000000e+00
ccgt 3.412390e+08
</code></pre>
<p>So my <code>Prod.... | <p>You can change logic - get all rows if not index values contains or starting by <code>T:</code></p>
<p>So filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <code>~</code> for invert mask with <a ... | python|pandas|dataframe | 2 |
370,920 | 58,677,535 | Count and Group By - Pandas Dataframe | <p>I have a dataframe, <code>csv_table</code> that looks like this:</p>
<pre><code>| time | ID | range | text |
|:-----:|:----------------:|:-----:|:--------------------------------------------------:|
| 90000 | B0A0F80A06A3AB6C | 0 | In what year did ba... | <p>I'm assuming you just want 1 final number right? If so then it's just:</p>
<pre><code>val['text'].mean()
</code></pre> | python|pandas | 2 |
370,921 | 58,705,494 | add two pandas dataframe columns which differs by only suffix parameter for e.g., "A_x", "A_y" and rename these two columns addition with "A" | <p>How to add two pandas dataframe columns which differs by only suffix parameter for e.g., "A_x", "A_y" and rename these two columns addition with "A".</p>
<p>For e.g., I have a data like this
<a href="https://i.stack.imgur.com/vWs37.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>The columns ... | <p>Use:</p>
<pre><code>df = pd.DataFrame([np.arange(6)], columns=['a','s','CT_1_x','CT_1_y','CT_2_x','CT_2_y'])
print (df)
a s CT_1_x CT_1_y CT_2_x CT_2_y
0 0 1 2 3 4 5
df = df.set_index(['a','s']).groupby(lambda x: x.rsplit('_', 1)[0], axis=1).sum().reset_index()
print (df)
a s ... | python|pandas | 1 |
370,922 | 58,798,996 | Pandas - Find longest streak of string values in column together with row id | <p>I am trying to find the longest streak of string values and also where it is.
The data I have is formatted like this:</p>
<pre class="lang-py prettyprint-override"><code>ID Datetime Name
0 Date1, Harald
1 Date2, Harald
2 Date3, Esther
3 Date4, Steve
4 Date5, Esther
5 Date6, Esther
6 Date7, Est... | <p>We can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>Series.cumsum</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>Series.shift</code></a>
t... | python|pandas | 4 |
370,923 | 58,692,476 | What is Adaptive average pooling and How does it work? | <p>I recently came across a method in Pytorch when I try to implement AlexNet.
I don't understand how it works. Please explain the idea behind it with some examples. And how it is different from Maxpooling or Average poling in terms of Neural Network functionality</p>
<blockquote>
<p>nn.AdaptiveAvgPool2d((6, 6))</p... | <p>In average-pooling or max-pooling, you essentially set the stride and kernel-size by your own, setting them as hyper-parameters. You will have to re-configure them if you happen to change your input size. </p>
<p>In Adaptive Pooling on the other hand, we specify the output size instead. And the stride and kernel-si... | python|math|neural-network|deep-learning|pytorch | 69 |
370,924 | 58,723,585 | Translating conditional RANK Window-Function from SQL to Pandas | <p>I’m trying to translate a window-function from SQL to Pandas, which is only applied under the condition, that a match is possible – otherwise a NULL (None) value is inserted.</p>
<p><strong>SQL-Code</strong> (example)</p>
<pre><code>SELECT
[ID_customer]
[cTimestamp]
[TMP_Latest_request].[ID_req] AS [I... | <p>Instead of using <code>RANK()</code> function, you can simply using the below, and it is easy to convert.</p>
<pre><code>SELECT A.ID_Customer,A.cTimeStamp,B.ID_req
FROM Customer A
LEFT JOIN (
SELECT ID_Customer,MAX(ID_req)ID_req
FROM Customer_request
GROUP BY ID_Customer
)B
ON A.ID_Customer = B.ID_C... | python|sql|sql-server|pandas | 0 |
370,925 | 58,906,812 | How to make a for loop in python for ttest_ind | <p>When I try to make the for loop to get ttest results I get TypeError: unsupported operand type(s) for /: 'str' and 'int'</p>
<p>But I have no idea what could be wrong with it. When I replace col with a specific column name it works and give me the same results over and over but it wont let me use col in brackets</p... | <p>actually, with a bit more playing around I realized what I had done wrong.</p>
<p>Here was my quick fix.</p>
<pre><code>for col in df_columns:
if col == 'party':
print("Skipped")
else:
print(str(col))
print(ttest_ind(rep[col], dem[col], nan_policy='omit'))
</code></pre> | python|pandas|for-loop | 0 |
370,926 | 58,651,959 | Counting duplicated elements in pandas dataframe | <p>I want to count the number of duplicated elements in a pandas dataframe "data", specifically here in the roi column, and input this number into each corresponding row of the count column.</p>
<p>For instance, roi 35 appears twice, hence each of the rows in the count column should have a "2".</p>
<p>Right now I tri... | <p>try using this line:</p>
<pre><code>data['count'] = data.groupby(['roi']).size().reset_index(name='count')
</code></pre>
<p>the reset_index() function in the last is to display the count of the repeating number. You can skip it, if you want.</p> | python|pandas | 2 |
370,927 | 58,882,929 | Fine-Tune Universal Sentence Encoder Large with TF2 | <p>Below is my code for fine-tuning the Universal Sentence Encoder Multilingual Large 2. I am not able to resolve the resulting error. I tried adding a tf.keras.layers.Input layer which results in the same error. Any suggestion on how to successfully build a fine-tuning sequential model for USEM2 will be much apprec... | <p>As much as I known, <code>Universal Sentence Encoder Multilingual</code> in tf.hub does not support <code>trainable=True</code> so far.</p>
<p>However, these code snippets can make the model do inference:</p>
<p><strong>Using V2</strong></p>
<pre><code>module_url = "https://tfhub.dev/google/universal-sentence-enc... | tensorflow2.0 | 2 |
370,928 | 58,910,413 | How to load unlabelled data for sentiment classification after training SVM model? | <p>I am trying to do sentiment classification and I used sklearn SVM model. I used the labeled data to train the model and got 89% accuracy. Now I want to use the model to predict the sentiment of unlabeled data. How can I do that? and after classification of unlabeled data, how to see whether it is classified as posit... | <blockquote>
<p>What is the meaning of ConvergenceWarning?</p>
</blockquote>
<p>As Pavel already mention, ConvergenceWArning means that the <code>max_iter</code>is hitted, you can supress the warning here: <a href="https://stackoverflow.com/questions/53784971/how-to-disable-convergencewarning-using-sklearn">How to d... | machine-learning|svm|python-3.7|sentiment-analysis|sklearn-pandas | 1 |
370,929 | 58,742,766 | How to get log probabilities in TensorFlow? | <p>I am trying to convert a pytorch script to tensorflow and I need to get log probabilities from a categorical distribution. But the tensorflow calculated log probabilities is different from pytorch's log prob even after using same seed. This is what I have done so far</p>
<pre><code>import torch
from torch.distribu... | <pre><code>tfp.distributions.Categorical(probs)
</code></pre>
<p>takes logs as the default argument. They are being normalized and resulting probabilities of built distribution are [.45, .55].</p>
<p>You need to build tfp distribution as:</p>
<pre><code> tfp.distributions.Categorical(probs=probs)
</code></pre> | python|tensorflow|pytorch|tensorflow2.0|tensorflow-probability | 3 |
370,930 | 58,992,389 | Get the minimum value of a dataframe column with condition on another dataframe | <p>Let's say I have these two dataframes : </p>
<pre><code>dfX = pd.DataFrame({'Points':["A","B","C","D"],'Group':[1,2,1,3]})
dfX
Points Group
0 A 1
1 B 2
2 C 1
3 D 3
dfY = pd.DataFrame({'Points':["A","B","C","D"],'Score':[2,3,4,5]})
dfY
Points Score
0 A 2
1 B 3
2 C ... | <p>First you need to merge the dataframes on the key <code>Points</code>, then get the group of point C, and finally take the mean of the scores within that group:</p>
<pre class="lang-py prettyprint-override"><code>merged = pd.merge(dfX, dfY, on='Points')
group = merged.loc[merged.Points == 'C', 'Group']
val = merged... | python|pandas | 1 |
370,931 | 59,031,275 | Map a pandas dataframe to a dictionary with a composite key | <p>I am working on some code where I need to map a pandas dataframe into a dictionary composed of a composite key and some value.
Below is a starting example, the <code>key</code> is composed of the <code>(PostalCode, Sex)(Name, Age)</code> and the <code>value</code> is the <code>sum</code> of all the <code>salary</cod... | <p>First aggregate <code>sum</code> and then change format of values in <code>MultiIndex</code> in dictionary comprehension with unpacking keys to variables <code>a,b,c,d</code>:</p>
<pre><code>s = people.groupby(["PostalCode", "Sex","Name", "Age"])["Salary"].sum()
print (s)
PostalCode Sex Name Age
ab 11 M ... | python|pandas|dataframe | 2 |
370,932 | 58,800,078 | Annotate matplotlib subplot with values | <p>I would like to annotate each barplot with the value on top each bar. I have found this excellent answer to a single plot <a href="https://stackoverflow.com/questions/28931224/adding-value-labels-on-a-matplotlib-bar-chart">Adding value labels on a matplotlib bar chart</a> , however I can not figure it out with subpl... | <p>It's actually similar, but here in your case it's <code>axes[i]</code> instead of <code>ax</code> in the original answer.</p>
<pre><code>fig, axes = plt.subplots(nrows=3, ncols=1)
for i, c in enumerate(df.columns):
df[c].plot(kind='bar', ax=axes[i], figsize=(12, 12), title=c)
# here it's almost the same wi... | python|pandas|matplotlib|text|subplot | 1 |
370,933 | 58,635,330 | A way to find mode values within range | <p>I have an numpy array of dimension values in this structure:</p>
<pre><code>arr = array([[3067, 78, 3172, 134],
[3237, 89, 3394, 128],
[3475, 87, 3743, 141],
[3763, 86, 3922, 131],
[3238, 147, 3259, 154]])
</code></pre>
<p>which basically stores the... | <p>You can convert your numpy array column to a pandas series and use <code>.value_counts()</code></p>
<pre><code>import pandas as pd
x_left = pd.Series(arr[:,0])
x_left.value_counts()
#3475 1
#3237 1
#3067 1
#3763 1
#3238 1
#dtype: int64
</code></pre>
<p>You could also round the values to, for example... | python|numpy|scipy | 1 |
370,934 | 58,925,655 | When using a Tensorflow Dataset from_tensor_slices(), is it possible to NOT load a new batch every train step? | <p>I would like to train for a few steps on the same batch since I want to give the CPU time to load the next batch. I am using reinitializable iterators and <code>tf.data.Dataset.from_tensor_slices((tf.range(n_train)))</code> and then using .map() to get my dataset by index. I want to run at least as many train steps ... | <p>So you want to repeat each datapoint <code>n</code> times right? The following should achieve that.</p>
<pre><code>n_train = 10
n_repeat = 5
ds = tf.data.Dataset.from_tensor_slices((tf.range(n_train))).interleave(lambda x: tf.data.Dataset.from_tensors(x).repeat(n_repeat), block_length=n_repeat)
diter = ds.make_one... | python|tensorflow|tensorflow-datasets | 0 |
370,935 | 58,787,376 | pythonic way to detect specific pandas column type | <p>what is the most pythonic way to select columns based on there dtype? (only needing the columns and not the entire df as with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html?highlight=select_dtypes" rel="nofollow noreferrer">select_dtypes</a> ) .<br>
assuming ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.api.types.is_datetime64_dtype.html" rel="nofollow noreferrer"><code>pandas.api.types.is_datetime64_dtype</code></a>, for list of all possible functions check <a href="https://pandas.pydata.org/pandas-docs/stable/reference/general_utility_... | pandas | 3 |
370,936 | 58,674,843 | Making a Postman request to Tensorflow Serving predict REST API | <p>Windows 10 and Docker tensorflow/serving. Having problem structuring JSON to request prediction and hoping that someone could help me out.</p>
<p>I have tried different formats of json, none of them successful.</p>
<p>Information about the model served by Tensorflow Serving:</p>
<p><a href="http://localhost:8501/... | <p>I now get the expected prediction</p>
<p>Either of the two changes made the trick, probably the first one.</p>
<ol>
<li>Added an extra [] surrounding the 50 elements in lstm_input</li>
</ol>
<pre><code>{
"inputs":{
"lstm_input":[
[
[
0.178988,
0.172... | json|api|request|postman|tensorflow-serving | 0 |
370,937 | 58,745,432 | Progressbar on Pandas-datareader? | <p>Is it possible to wrap <code>df = web.get_data_yahoo(tickers, start, end)</code> inside a progressbar? It takes about 20 mins but it would it be possible to see the progress?</p> | <p>You can accomplish this with <code>tqdm</code>. Here is a link <a href="https://pypi.org/project/tqdm/" rel="nofollow noreferrer">Click here</a></p>
<p>This would work on tickers to see how many variables have been completed.</p> | progress-bar|pandas-datareader | 0 |
370,938 | 58,810,517 | pd.merge_asof with multiple matches per time period? | <p>I'm trying to merge two dataframes by time with multiple matches. I'm looking for all the instances of df2 whose <code>timestamp</code> falls 7 days or less before <code>endofweek</code> in df1. There may be more than one record that fits the case, and I want all of the matches, not just the first or last (which pd... | <p><code>pd.merge_asof</code> only does a left join. After a lot of frustration trying to speed up the <code>groupby</code>/<code>merge_ordered</code> example, it's more intuitive and faster to do <code>pd.merge_asof</code> on both data sources in different directions, and then do an outer join to combine them.</p>
<p... | python|pandas|dataframe | 1 |
370,939 | 58,896,942 | tensorflow 2 guide Consuming sets of files throws slice index out of bounds | <p>trying the code (please see below) from <a href="https://www.tensorflow.org/guide/data#consuming_sets_of_files" rel="nofollow noreferrer">consuming sets of files</a> throws a slice index -1 of dimension 0 out of bounds (please see output below).</p>
<p>has anyone gotten this code to work?</p>
<pre><code>from __fut... | <p>I think this is because you are running on Windows. Try switch the following line </p>
<pre><code>label = tf.strings.split(file_path, '/')[-2]
</code></pre>
<p>to</p>
<pre><code>label = tf.strings.split(file_path, '\\')[-2]
</code></pre> | python-3.x|tensorflow-datasets|tensorflow2.0 | 0 |
370,940 | 58,941,886 | Training Model with Keras Backend: Invalid argument: You must feed a value for placeholder tensor | <p>I want to train a deep learning model (variational autoencoder, VAE) using keras backend,
and have followed the guideline to do available at <a href="https://towardsdatascience.com/keras-custom-training-loop-59ce779d60fb" rel="nofollow noreferrer">https://towardsdatascience.com/keras-custom-training-loop-59ce779d60... | <p>Not sure but I think culprit is here:</p>
<p><code>vae_input = Input(shape=(data_set.shape[1:]))</code></p>
<p>which means you pass input shape as tuple where first item is list of shape and correct way is to just pass tuple (or list) of values:</p>
<p><code>vae_input = Input(shape=data_set.shape[1:])</code></p>
... | python|tensorflow|keras|deep-learning | 0 |
370,941 | 58,946,512 | Numerical decimal rounding not working correctly in Pandas | <p>I want keep only 3 decimals of the value which I have in a column. But its not working properly.</p>
<p><strong>Input Data</strong></p>
<pre><code>td['latitude']
2.999852
2.999852
2.714852
4.998789
4.999789
</code></pre>
<p>My code</p>
<pre><code>dd = round(td['latitude'], 3)
</code></pre... | <p><em>What is wrong in my code</em>: <code>round</code> is round, i.e. returns the closest integer/precision <code>round(1.66, 1) = 1.7</code>.</p>
<p><em>How to fix this</em>: I remembered some question/answer with truncate, but can't find them with a simple search. So here's a quick solution:</p>
<pre><code>td['la... | python|pandas|numpy|dataframe | 0 |
370,942 | 58,710,518 | Return DataFrame rows for max date of every month and only if it falls in the last 2 weeks of that month | <p>I'm want to <strong>return rows by checking for the maximum date of the month and then rechecking if the date falls in the last 2 weeks of that particular month</strong>. Below is the DataFrame that I'm using:</p>
<p><code>finalPrize date high low</code> </p>
<p><code>1777.44 2018-07-31 18... | <pre><code>import calendar
df.index = pd.to_datetime(df.index)
df['day'] = pd.to_numeric(df.index.day)
df['days_in_month'] = df.apply(lambda row : calendar.monthrange(row.name.year,row.name.month)[1], axis = 1)
df['first_day'] = df.apply(lambda row : calendar.monthrange(row.name.year,row.name.month)[0], axis = 1)
df['... | python|python-3.x|pandas|date|dataframe | 1 |
370,943 | 58,985,428 | Python Pandas - Cleaning data column depending on multiple criteria | <p>I have the following code to create a column with cleaned up zip codes for the USA and Canada</p>
<pre><code>df = pd.read_csv(file1)
usa = df['Region'] == 'USA'
canada = df['Region'] == 'Canada'
df.loc[usa, 'ZipCleaned'] = df.loc[usa, 'Zip'].str.slice(stop=5)
df.loc[canada, 'ZipCleaned'] = df.loc[canada, 'Zip'].str... | <p>The following code solves this question </p>
<pre><code>df.loc[~df['Ship To Customer Zip'].str.contains('[A-Za-z]'), 'ZipCleaned'] = df['Ship To Customer Zip'].str.slice(stop=5)
df.loc[df['Ship To Customer Zip'].str.contains('[A-Za-z]'), 'ZipCleaned'] = df['Ship To Customer Zip'].str.replace(' |-','')
</code></pre> | python|pandas|conditional-statements|data-cleaning | 0 |
370,944 | 58,682,588 | numpy angle computation using coordinates | <p>I have to calculate the angle between two points say A (x1, y1) and B (x2, y2). And the current code that I am using is as follows-</p>
<pre><code>import math
direction = math.degrees(math.atan((y2 - y1) / (x2 - x1)))
</code></pre>
<p>I tried performing the same code by using the following numpy code-</p>
<pre><c... | <p>Seems to me that it works fine. Due to the fact that I dont see the character of you numpy/pandas coordinates array I cant give you exact solution</p>
<p>3 versions:</p>
<p>arctan</p>
<pre><code>>>> direction = np.rad2deg(np.arctan((2-1)/(2-1)))
>>> direction
45.0
</code></pre>
<p>math</p>
<pr... | python|numpy | 1 |
370,945 | 58,826,650 | missing 2 required positional arguments in optimization problem in python | <p>I'm trying to solve an optimization problem using scipy. There's a huge database that I re-arranged in order to use some of the rows as parameters in the optimization problem. Then I take the sum of each entry and multiply by x variables in order to create constraints that must be greater than "arb" (which is just a... | <p>It seems that the constraint function must accept a single argument x and have an output which is the distance from the constraint. For an inequality constraint the minimizer will attempt to keep the returned values in the non-negative range and for an equality it will try to bring it to 0. Your functions however re... | python|pandas|scipy|scipy-optimize | 0 |
370,946 | 59,010,585 | How to identify all x co-ordinate values for a certain y value from the mathplot in python | <p>I have plotted a frequency vs time graph of a audio wav extracted from a video using matplotlib and scipy.</p>
<p>Now I want to identify all the values of time(x-coordinate) for a certain value(like zero, peak positive frequency,..,etc,.) of frequency(y-coordinate).
Here is my code for plotting :</p>
<pre><code>sr... | <p>Thanks <a href="https://stackoverflow.com/users/11301900/alexander-c%C3%A9cile">@Alexander Cécile</a>.Yes, I was very late figuring that out. I have managed to get the values I desired through the index's of <code>y</code> and <code>t</code> lists. I was just making an operation of basic list iteration complicated w... | python|numpy|matplotlib|audio|scipy | 0 |
370,947 | 58,827,663 | pandas merge and update efficiently | <p>Iam getting df1 from the database.
Df2 needs to be merged with df1. Df1 contains additional columns not present in df2. df2 contains indexes that are already present in df1 and which rows need to be updated. the dataframe are multi indexed.</p>
<p>What i want:
-keep rows in df1 that are not in df2
-update df1's val... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">Merge</a> the dataframes, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.update.html" rel="nofollow noreferrer"><code>update</code></a> the column <code>one</c... | python|pandas|dataframe|merge | 3 |
370,948 | 58,778,822 | How to group consecutive values in reguarly time spaced series? | <p>I need to separately analyse the records between holes contained in a regularly spaced time series.</p>
<p>As example in the follwing time series regularly spaced every 6 seconds there is a gap between 00:24 and 00:54:</p>
<pre><code>2018-01-01 00:00:00 4.2
2018-01-01 00:00:06 4.1
2018-01-01 00:00:12 4... | <p>create separate dataframe using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a></p>
<pre><code>groups=( df.index.to_series().diff()>=pd.Timedelta(seconds=6) ).cumsum()+1
for i , group in df.groupby(gro... | python|pandas|time-series|pandas-groupby | 2 |
370,949 | 58,740,027 | TypeError method object is not subscriptable | <p>I'm trying to set the trimester of this <a href="https://www.dropbox.com/s/c9ajy7szesji6wp/accidentalidad2017.csv?dl=0" rel="nofollow noreferrer">data</a> with pandas to start working. I already tried the date_range and others with dates but it doesn't work because there are many (many) rows with the same index. So ... | <p><code>TypeError method object is not subscriptable</code> means that you tried to call a function using <code>[]</code> instead of <code>()</code></p>
<p>There is a difference between <code>print("banana")</code> and <code>print["banana"]</code></p> | python|pandas | 0 |
370,950 | 58,796,369 | Jupyter Notebook: how to use ipython widget variable outside the function | <p>I am using the interact function of ipython widget and I want to use the selection as a variable outside the function. For e.g.</p>
<pre><code>import ipywidgets as widgets
from ipywidgets import interact, interactive
list1 = ['ABC','DEF','GHI']
@interact
def uni_systems(items = list1):
choice = items
</code></... | <p>IIUC, insert <code>global choice</code> statement before assigning a value in it within the function. Basically, creating it as a global variable so you can use it outside the function</p> | python|pandas|jupyter-notebook|widget|ipython | 0 |
370,951 | 58,619,225 | How to convert a date to Epoch time in python | <p>I want to convert the date to epoch ms and attach back to the dataframe how this be done.</p>
<pre><code> Date
30/10/2019
31/10/2019
04/10/2019
15/10/2019
13/11/2019
3/11/2019
</code></pre>
<p>Expected Output:</p>
<pre><code> Date Epoch ms
... | <p>start with </p>
<pre><code>import datetime
</code></pre>
<p>and end with the following. You might need to do some formatting-fu to get different parts of those strings into the function, but I'm confident you can do that if they are delimited the same way.</p>
<pre><code>datetime.datetime(2019,04,01,0,0).strftime... | python|pandas|datetime|epoch | 1 |
370,952 | 59,021,819 | How can I print specific rows in Pandas Data Frame? No solutions worked :( | <p>I am trying to print the rows of my pandas data frame which include key words (dog, cat or bird). I tried all the solutions mentioned on Stack Overflow, but my code only printed 2 rows and I could not figure out the reason. Here are the codes I tried:</p>
<pre><code>dodo_data[dodo_data['title'].str.contains("dog")]... | <p>What you can do is just set <code>title</code> as the index and then use <code>df.loc[the required keyword</code> to get the row containing the value.</p>
<pre class="lang-py prettyprint-override"><code>df.set_index("title", inplace=True)
print(df.loc[['cat','dog']])
</code></pre>
<p>This will print out all the ro... | python|regex|pandas | 0 |
370,953 | 58,785,030 | Nested list elements to data frame in Python | <p>Fair warning this question does require a non standard Python package, <code>nba_api</code>. I have a list with 3 elements with each element in the list containing another list with 2 elements: a <code>player</code> data frame and a <code>team</code> data frame. What is recommended way to achieve the following des... | <p>After a bit more reading (and clarity) I was able to combine the manual parts of my code in for loops that generate one list with player data and one list with team data. Then, using this post: <a href="https://stackoverflow.com/questions/32444138/concatenate-a-list-of-pandas-dataframes-together">Concatenate a list... | python|pandas|list | 1 |
370,954 | 59,019,303 | Generate an N-dimensional matrix using Numpy | <p>For a certain assignment, I have to create a multivariate discrete probability mass function over <code>N</code> random variables. I want to do this by creating an array <code>A</code> filled with random numbers where each element denotes the joint probability over the random variables. In case of 2 random variables... | <p>If <code>l</code> is your list of dimensions, you could let</p>
<pre><code>a = np.random.random(size=l)
a = a/a.sum()
</code></pre> | python|numpy|multidimensional-array|random|probability | 2 |
370,955 | 58,973,414 | Delete a variable in a newly inserted row | <p>my project is about calculating the working time of employees.</p>
<p><strong>df:</strong></p>
<pre><code> Door Name Time Last Name First Name
0 RDC_IN-1 2019-08-05 15:00:00 STARK ARYA
1 RDC_OUT-1 2019-08-05 12:55:00 STARK ARYA
2 RDC_OUT-1 2019-08-05 11:11:00 STARK ... | <p>just use the answer I gave you yesterday and add </p>
<pre><code>df['diff'] = df['Time'].diff()
df.loc[df.door == 'RDC_IN-1','diff'] = np.nan
# calculate cumsum
df.loc[df.door == 'RDC_OUT-1','diff'] = df.loc[df.door == 'RDC_OUT-1','diff'].cumsum()
</code></pre>
<p>at the end.</p>
<p>Also don`t forget to provid... | python-3.x|pandas|row | 1 |
370,956 | 58,689,570 | How to display percentage along with bar chart | <p>I already plot a bar chart for the data below</p>
<pre><code> Total Monthly Actual Hours Total Monthly Work Hours
Activity Month
Apr-19 35381.25 42592
May-19 31722.50 44528
Jun-19 27708.50 38720
Jul-19 34283... | <p>For annotating the bar chart you can refer to the example from matplotlib documentation here. </p>
<p><a href="https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py" rel="nofollow noreferrer">https://matplotlib.org/3.1.1/gallery/lines_bars_and_... | python|pandas|matplotlib|percentage | 3 |
370,957 | 58,801,915 | Removing rows from a dataframe, if the observation for a specific variable is numeric | <p><a href="https://i.stack.imgur.com/REbmz.png" rel="nofollow noreferrer">data example </a>I have a large data frame with over 20000 observations, I have a variable called “station” and I need to remove all rows that only have numbers as the s station name.
The only code that has worked so far is :
Df[‘station’][~df[‘... | <p>You can use an extre column with <code>.str.isnumeric()</code> to be used later on as a filter:</p>
<pre><code>df['filter'] = df['station'].str.isnumeric()
df_filtered = df[df['filter'] != False]#.drop(columns=['filter']
</code></pre>
<p>This should return all rows that are not only numbers for the column <code>s... | python|python-3.x|pandas|python-2.7|numpy | 0 |
370,958 | 58,668,017 | Pandas Dataframe: Removing numbers after (.) and adding % to it and renaming column in certain format | <pre><code>('Total Answered Calls', 'sum') ('Calls Received', 'mean')
329 99.83249581
197 98.02631579
162 99.24242424
57 100
73 97.82608696
</code><... | <p>If that's what you are looking for this may solve the problem:</p>
<pre><code>data.columns = ['Total Answered Calls','Calls Received']
data['Calls Received'] = data['Calls Received'].astype(int).astype(str)+'%'
</code></pre> | python|regex|pandas|dataframe | 1 |
370,959 | 58,981,056 | Cutting Python List with Mass | <p>I have a list like, </p>
<pre><code>defaultdict(list,
{37.0: ['C22H27O7',
'C21H23O8',
'C25H35O7',
'C24H31O8',
'C23H27O9',
'C22H23O10',
'C21H19O11',
'C20H15O12',
'C19H11O13'],
111.... | <p>Assuming that you only want the output (and not another data structure with the split lists), you could iterate over the lists of formulas, comparing each value <code>calculateMass(myList[index][i])</code> with the previous one <code>calculateMass(myList[index][i-1])</code> like this:</p>
<pre><code>for index in my... | python|pandas|dataframe|dictionary | 1 |
370,960 | 58,965,717 | How to create upper triangular matrix in Pytorch? | <p>Simple question, but is there a native way to create an upper triangular matrix from an existing matrix in Pytorch? I was thinking of using a mask, but even that requires creating the upper triangular matrix. </p> | <pre class="lang-py prettyprint-override"><code>import torch
upper_tri = torch.ones(rol, col).triu()
</code></pre>
<p>Eg:</p>
<pre><code>>> mat = torch.ones(3, 3).triu()
>> print(mat)
tensor([[1., 1., 1.],
[0., 1., 1.],
[0., 0., 1.]])
</code></pre> | python|matrix|pytorch | 3 |
370,961 | 58,819,234 | Cannot fill in blank values in Pandas | <p>I have a dataframe </p>
<pre><code>Gender
</code></pre>
<p>0 Female<br>
1 Female<br>
2<br>
3 Female<br>
4 Female</p>
<p>with gender column which has some na values, and the split between genders is:</p>
<pre><code>Male 5453
Female 4543
Name: Gender, dtype: int64
</code></pre>
<p>When trying to f... | <p>As already said by Tserenjamts, most likely that happens because the value you want to fill is not an NaN rather it is an empty string. Also there is an error in your code, so that your code wouldn't fill the NaN's with the most frequent value, but the idmax object.</p>
<p>Try this to fix your error:</p>
<pre><cod... | pandas|fillna | 0 |
370,962 | 58,824,625 | Torch Network load does not processed properly | <p>I am trying to make a network using 3x64x64 image at pytorch environment, and it seems that I succeeded in training my network and save it. The network looks like : </p>
<pre><code>class LC_small(nn.Module):
def __init__(self,c_in,c_out = 256):
super(LC_small,self).__init__()
self.conv1 = conv(c_in,... | <p>So your first error message is because torch.from_numpy(i1r) has the wrong shape. You need to do </p>
<pre><code>np.expand_dims(i1r.transpose(2,0,1), axis=0)
</code></pre>
<p>Then it'll get processed correctly. This is because it expects a batch dimension and you aren't providing one along with the channels bei... | python|pytorch | 0 |
370,963 | 59,021,031 | How to plot an array as if the indices i,j were the x,y coordinates? | <p>Hi guys first question here, looked for an answer but could not find anything, I will try to give it my best.</p>
<p>I am currently working on a problem in the field of Computational Physics and I am solving the Navier-Stokes equations numerically using the Finite Difference Method. It`s my first time working with ... | <p>You can use numpy's ndindex function to get the indices based on shape and then unzip the result.</p>
<pre><code>x,y=list(zip(*np.ndindex((N,N))))
</code></pre>
<p>The data is row by column and can be obtained with meshgrid. If you're interested in the same manipulation. You can make the data with meshgrid as</p>
... | python|numpy|matplotlib|numpy-ndarray | 1 |
370,964 | 58,808,842 | Name group of columns and rows in Pandas DataFrame | <p>I would like to give a name to groups of columns and rows in my Pandas DataFrame to achieve the same result as a merged Excel table:</p>
<p><a href="https://i.stack.imgur.com/q0fTR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q0fTR.png" alt="enter image description here"></a></p>
<p>However, ... | <p>You can set hierarchical indices for both the rows and columns.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame([[3,1,0,3,1,0],[0,3,0,0,3,0],[2,1,3,2,1,3]])
col_ix = pd.MultiIndex.from_product([['Predicted: Set 1', 'Predicted: Set 2'], list('abc')])
row_ix = pd.MultiInde... | python|pandas|dataframe | 3 |
370,965 | 58,691,293 | numpy broadcasting and conditionals | <p>I'm shure the question is already asked somewhere, but i dont have the right keywords to find a solution... </p>
<p>my problem is to ameliorate the following code : </p>
<pre><code>I = np.array([True,False])
x = np.array([1,2])
result = f(x) * (1 - I) + g(x) * I
</code></pre>
<p>Where in fact, <code>I</code> is u... | <p><code>np.piecewise</code> is probably what you want. For example:</p>
<pre><code>I = np.array([True,False])
x = np.array([1,2])
f,g = np.square,np.negative
np.piecewise(x, I, [g,f])
# array([-1, 4])
</code></pre>
<p>One potential gotcha: The output of <code>np.piecewise</code> has the same type as <code>x</code>;... | python|numpy|conditional-statements|broadcast | 2 |
370,966 | 58,792,336 | how to list all the data after group by and sum by making a sepreate column for each | <p>I have a data set called fy2019 that contains the columns</p>
<p><a href="https://i.stack.imgur.com/zfwjR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zfwjR.png" alt="enter image description here"></a></p>
<p>I want to group by Name and add up the expenses based on the name. I did this. It w... | <p>Do you mean something like this:</p>
<pre><code>data = [['Jack', 100], ['Jack', 200], ['Jum', 35],['Brad', 60], ['Brad', 50], ['Anil', 70],['Anil', 90]]
test = pd.DataFrame(data, columns = ['Name', 'Expenses'])
test.groupby(df.Name).sum()
test
Out[449]:
Expenses
Name
Anil 160
Brad ... | python|pandas | 0 |
370,967 | 58,888,448 | How to remove duplicates of column by giving appropriate value to its label in the row? | <p>I have an excel table as follows (contains more data than displayed):</p>
<p><a href="https://i.stack.imgur.com/FJrhI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FJrhI.png" alt="enter image description here"></a></p>
<p>First column contains <code>ids</code>, second column contains <code>lab... | <p>You can use <code>groupby</code> and <code>pivot</code> in python pandas package</p> | python|pandas | 0 |
370,968 | 58,781,581 | Drop Rows with Non-Numeric Entries in a Column (Python) | <p>I am trying to download data from a website. When I do this, there are some rows that are not part of the data included, which is obvious because their first column is not a number. </p>
<p>So I'm getting something like</p>
<pre><code>GM_Num Date Tm
1 Monday, Apr 3 LAA
2 Tu... | <p>Let's cast your 'Gm#' column and drop records in a couple of steps:</p>
<pre><code>df['Gm#'] = pd.to_numeric(df['Gm#'], errors='coerce')
df = df.dropna(subset=['Gm#'])
df
</code></pre>
<p>Output:</p>
<pre><code> Gm# Date Unnamed: 2 Tm Unnamed: 4 Opp W/L R RA \
0 1.0 Monday, A... | python|pandas|dataframe | 0 |
370,969 | 58,964,953 | drop duplicates dataframe pandas | <p>I have a dataframe where I want to sum up all "Hours" (column header) into "total sum" for each "Name" (column header) under 1 "Manager" (column header). I then want to drop all duplicates before sorting the the dataframe based on the total hours sum and print out row by row. However I keep getting duplicates of the... | <p>Do you want to try this</p>
<p><code>df.groupby('Manager').agg({'Hours':['sum','count']}).sort_values(('Hours','sum'), ascending=False)</code></p> | python|pandas|duplicates | 1 |
370,970 | 58,800,557 | Catch python exception thrown from TensorFlow | <p>I’m running a python (v 3.6.5) code that is using TensorFlow (v 1.13.2) to perform inference using a trained model (on Windows 8.1).</p>
<p><strong>I want to catch (and log) exceptions/errors that are thrown from inside TensorFlow library.</strong></p>
<p>For example when the batch size (during a session.run()) is... | <p>This should be caused by catching incorrect exceptions. Tensorflow defines its own <a href="https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/errors" rel="nofollow noreferrer">exceptions</a> which are subclasses of Exception (<a href="https://github.com/tensorflow/tensorflow/blob/r1.15/tensorflow/python/f... | python|python-3.x|tensorflow|exception | 0 |
370,971 | 59,007,923 | `.iloc()` returns strange results when used with dask dataframe groupby | <p>I have a large dataset with 3 columns:</p>
<pre><code> sku center units
0 103896 1 2.0
1 103896 1 0.0
2 103896 1 5.0
3 103896 1 0.0
4 103896 1 7.0
5 103896 1 0
</code></pre>
<p>And I need to use a <code>groupby-apply</code>.</p>
<pre><code>def function_a(x):
return np.sum((x ... | <h2>Assumptions</h2>
<p>Your index (in the above example (0, 1, 2, 3, 4, 5)) corresponds to the correct sorting that you want. E.g. by the data being CSVs of the form </p>
<pre><code>0,103896,1,2.0
1,103896,1,0.0
2,103896,1,5.0
</code></pre>
<p>where the first columns corresponds the sample number. When you then rea... | python|pandas|pandas-groupby|dask | 1 |
370,972 | 58,848,474 | Value_counts() AttributeError: 'str' object has no attribute 'value_counts' | <p>I'm running the code below the meet the outlined object but am getting an error I'm not sure how to fix. </p>
<pre><code>class variableTreatment():
def drop_zero_car_col(self, df):
numerical = list(df._get_numeric_data().columns)
categorical = list(set(df.columns).difference(set(num... | <p>To drop non-numerical columns with same values in dataframe you can change your function like below:</p>
<pre><code>class variableTreatment():
def drop_zero_car_col(self, df):
# selecting numerical columns without accessing private method
numerical = list(df.select_dtypes([np.number... | python|python-3.x|pandas|dataframe | 1 |
370,973 | 58,698,265 | How to calculate geometric mean and stddev over 2D DataFrame bin wise for column ranges defined via IntervalIndex? | <p>I've a 2D DataFrame like follows</p>
<pre><code> 0.0 0.1 0.2 0.3 0.4 ...
0 0 1 NaN 1 9
1 NaN NaN NaN NaN 9
...
</code></pre>
<p>. For every row I'd like to calculate the <a href="https://en.wikipedia.org/wiki/Geometric_mean" rel="nofollow noreferrer">geometric mean</a> and the <a href="https://... | <p>Hope, somebody will improve the answer later.
For now I know that for <strong>geometric mean</strong> you can try QuantStats package:</p>
<pre><code>import quantstats as qs
qs.extend_pandas()
pandas_df.geometric_mean()
</code></pre>
<p>Hope this can help a bit</p> | pandas|dataframe | 0 |
370,974 | 58,957,539 | Removing empty strings with a space in it (" ") in a array column of a Dataframe Series | <p>Example:</p>
<pre><code>Column 1
[1, 3, " "]
[2, " ", 3]
etc.
</code></pre>
<p>Is there a quick list compehension where I can keep just the integers?</p> | <p>You are probably looking for something like so:</p>
<pre><code>a = [1, 3, " "]
b = [i for i in a if i != " "]
print(b) #> [1, 3]
</code></pre>
<p>If you want to include other spaces to remove:</p>
<pre><code>a = [1, 3, " ", ""]
b = [i for i in a if i not in (" ", "")]
</code></pre>
<p>If you want to only add... | python|pandas|dataframe|list-comprehension | 0 |
370,975 | 58,617,533 | Python Pandas to_csv, can you use .replace() to pre-emptively deal with double-quote escape issues | <p>I am trying to get a process going in python to write data into a .csv which can then be BCP'd into a MSSQL database.</p>
<p>The basic to_csv command I am using is:</p>
<pre><code>df.to_csv(csv_path, sep = "«", header = False, index = False, line_terminator="[~~]")
</code></pre>
<p>The one issue I have been seein... | <p>use</p>
<pre><code>import csv
...
df.to_csv(..., quoting=csv.QUOTE_NONE)
</code></pre> | python|pandas|csv|double-quotes | 1 |
370,976 | 58,735,191 | Removing words from the list of sentences | <p>I have a list of channel names and I want to remove words from these names.
I tried methods in this (<a href="https://stackoverflow.com/questions/51317357/removing-words-from-list-in-python">Removing words from list in python</a>) discussion, but did not work for me.
I have these:</p>
<pre><code>'Housekeeping.XTX_... | <p>lets say something like this:</p>
<pre><code>import re
abc=['Housekeeping.XTX_heater-0_Switch_Status',
'Housekeeping.PDM_1__SW11_Status',
'Housekeeping.Slim6_Imager-1_Switch_Status',
'Power.BCM1_Battery_Cell_Temperature_degC']
stop=['Housekeeping.', 'Power.', 'Thermal.', 'LIN.\s+']
print([(lambda x: re.sub(r'|'.... | python|pandas | 0 |
370,977 | 58,919,122 | How to find missing date rows in a sequence using pandas? | <p>I have a dataframe with more than <code>4 million rows and 30 columns</code>. I am just providing a sample of my patient dataframe</p>
<pre><code>df = pd.DataFrame({
'subject_ID':[1,1,1,1,1,2,2,2,2,2,3,3,3],
'date_visit':['1/1/2020 12:35:21','1/1/2020 14:35:32','1/1/2020 16:21:20','01/02/2020 15:12:37','01/... | <p>You can get the first part with:</p>
<pre><code>In [14]: df.groupby("subject_ID")['item_name'].value_counts().unstack(fill_value=0)
Out[14]:
item_name Fio2 PEEP
subject_ID
1 2 3
2 0 5
3 3 0
</code></pre>
<p>EDIT:</p>
<p>I think you've still got your date forma... | python|python-3.x|pandas|dataframe|pandas-groupby | 2 |
370,978 | 58,631,329 | How do I resize Images using python code? | <p>I am working to resize a bundle of images using python code i.e. "Resize.py". But I am getting the following error:</p>
<pre><code>File "C:\Users\NAJEEB\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\Image.py", line 2205, in thumbnail
if x > size[0]:
TypeError: 'int' object is not subscripta... | <p>You declared <code>size = 300*300</code></p>
<p>The pil thumbnail api requires size to be 2 element <strong>tuple</strong> so use</p>
<pre><code>size = (300, 300)
</code></pre> | python|tensorflow | 2 |
370,979 | 58,969,553 | Python result changes during cv2.Rodrigues computation | <p>If I run:</p>
<pre><code>import numpy as np
import cv2
def changes():
rmat=np.eye(4)
tvec=np.zeros(3)
(rvec, jacobian)=cv2.Rodrigues(rmat)
print rvec
for i in range(2):
changes()
</code></pre>
<p>I get:</p>
<pre><code>[[6.92798859e-310]
[2.19380404e-316]
[1.58101007e-322]]
[[0.]
[0.]
[0.... | <p>This is very likely an uninitialized array such as returned by <code>np.empty</code>. This together with memory recycling can lead to the kind of effect you are seeing. A minimal example would be:</p>
<pre><code>for a in range(5):
y = np.empty(3,int)
x = (np.arange(3)+a)**3
print(x,y)
del x
# [0 1 ... | python|numpy|opencv|debugging|opencv3.0 | 8 |
370,980 | 58,795,222 | Extracting regions from image | <p>Hi I am trying to retrieve regions from a set of images. I have used bitwise_and operation on the image and masks to get the regions but doing so is resulting in change of brightness in the resulting image. So, I want to retrieve these regions from the image pixel by pixel and put them together in another blank imag... | <p>First step would be separate out the gray and white masks independently using either <code>cv2.threshold</code> or <code>cv2.inRange()</code> methods, then we can simply use <code>cv2.min()</code> method to take the imprint of the original image at the gray and white areas respectively as:</p>
<pre><code>import cv2... | python|numpy|opencv|image-processing | 0 |
370,981 | 58,878,421 | Unexpected keyword argument 'ragged' in Keras | <p>Trying to run a trained keras model with the following python code:</p>
<pre class="lang-py prettyprint-override"><code>from keras.preprocessing.image import img_to_array
from keras.models import load_model
from imutils.video import VideoStream
from threading import Thread
import numpy as np
import imutils
import ... | <p>So I tried link above which you have mentioned <a href="https://teachablemachine.withgoogle.com/" rel="noreferrer">teachable machine</a><br>
As it turns out model you have exported is from <code>tensorflow.keras</code> and not directly from <code>keras</code> API. These two are different. So while loading it might b... | python|tensorflow|keras | 67 |
370,982 | 70,371,176 | pandas DataFrame: sequentially compare cells to a numeric value, and then update the value once a condition is met | <p>I’ve got this dataframe:</p>
<pre><code> Time Price
0 2021-11-01T13:30:00.001643Z 460.30
1 2021-11-01T13:30:00.00169Z 460.30
2 2021-11-01T13:30:00.001907Z 460.30
3 2021-11-01T13:30:00.002802497Z 460.31
4 2021-11-01T13:30:00.0034985... | <p>I would do something similar to the following.</p>
<ol>
<li>Set the price in a variable</li>
</ol>
<pre><code>PRICE = df["Price"].loc[0]
</code></pre>
<ol start="2">
<li>Set True/False to df["Range"] using a list comprehension.</li>
</ol>
<pre><code>df["Range"] = [True if PRICE-0.1 <... | python|pandas | 0 |
370,983 | 70,034,135 | Removing duplicates based on a condition pandas | <p>When removing duplicates, can I keep those rows that match a condition? Instead of doing:</p>
<pre><code>df.remove_duplicates(subset=['x','y'], keep='first']
</code></pre>
<p>do:</p>
<pre><code>df.remove_duplicates(subset=['x','y'], keep=df.loc[df[column]=='String'])
</code></pre>
<p>Suppose I have a df like:</p>
<p... | <p>Use <a href="http://andas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>DataFrame.duplicated</code></a> with invert mask and chain by <code>&</code> for bitwise <code>AND</code> by condition:</p>
<pre><code>df['mask'] = ~df.duplicated(subset=['A','B... | python|pandas | 1 |
370,984 | 70,142,798 | Using a keyword need to return the entire sentence that contains and remove that from dataset using python pandas | <p>I have one dataset I need to find some certain keywords from the Review column and it needs to return the entire review from it.</p>
<p>For example, the sentence is like this: very nice product delivered.</p>
<p>The keyword I need to find is <strong>nice</strong> and also I need to return the entire sentence that c... | <p>You can use regex to do that.</p>
<pre><code>pattern_to_remove = "(nice)|(good)|(great)|(best)"
row_filter = data['Sentence'].str.contains(patternDel) # a filter to determine if the row matches the pattern
data = data[~row_filter] # drop the rows
</code></pre> | python|pandas | 0 |
370,985 | 70,248,903 | Plotting Pandas GroupBy data | <p>I read a dataset into <code>Pandas</code> and filtered the data using <code>df_new=df.query("parent=='pr1'")</code> to create a new <code>DataFrame</code> which looks like this:</p>
<pre><code> child parent date pres
101 ch05 pr1 2004-06-01 2760.35
102 ch05 pr1 2004-07... | <p>You just need to reset the index</p>
<pre><code>pobs = df.groupby('date')['pres'].mean().reset_index()
</code></pre>
<p>output:</p>
<pre><code> date pres
0 2004-06-01 2760.35
1 2004-07-08 2758.83
2 2004-08-04 2759.13
</code></pre>
<p>In this way, prob is now a dataframe and can be plotted as such, for... | python|pandas | 0 |
370,986 | 70,300,518 | DataFrame Logic To Remove Rows Not Working | <p><strong>Background</strong> - I have a pandas DataFrame, which I have performed some math on, in order to calculate values to populate the <code>Entity ID</code> and <code>% Ownership</code> column with -</p>
<p><code>df['Entity ID %'] = df.groupby('Entity ID')['% Ownership'].transform(sum)</code><br>
<code>df['Acco... | <p>After having a close look at your code, I can see that you are initializing</p>
<pre><code> df['Entity ID %'] = '-'
df['Account # %'] = '-'
</code></pre>
<p>which makes them datatype <strong>object</strong>. You can not compare object with integers.</p>
<p>Make the following change in your ownership_qc():</p>
<pre>... | python|pandas|dataframe|rounding | 0 |
370,987 | 70,346,665 | Conver a list of features into a binary vector | <p>I have several lists of features:</p>
<pre><code>feat_lists = [
['f1','f2','f3'],
['f2','f3'],
['f2','f4']
]
</code></pre>
<p>And I'd like to arrange them in a way that each row represents a list (observation), and each column a feature. So the values are 1/0 or True/False, depending on the presence of the val... | <p>Use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html" rel="nofollow noreferrer"><code>MultiLabelBinarizer</code></a> with casting to boolean by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html" rel="nofollow norefe... | pandas | 1 |
370,988 | 70,274,671 | pandas cut preserving nans when the binning boundaries are not found in the group by function | <p>I am getting strange behaviour in pandas cut function.
Suppose I have this dataframe:</p>
<pre><code>df = pd.DataFrame([1, 4, 8, 9], columns=['A'])
</code></pre>
<p>and I want to do binning based on this values.</p>
<pre><code>bins = list(range(0, 10))
</code></pre>
<p>As Normally, I would expect like this:</p>
<pre... | <p>You need to set <code>observed=True</code>, because your 'Binned' column contains categorical values. In categorical data, all categories are preserved.</p>
<pre><code>df.groupby('binned', as_index=False, observed=True).max()
</code></pre>
<p>As you can see when you check <code>df['binned'].dtype</code>, the type is... | python|pandas | 1 |
370,989 | 70,139,646 | How to find the mean of subseries in DataFrames? | <p>My personnel side project right now is to analyze GDP growth rates per capita. More specifically, I want to find the average growth rate for each decade since 1960, and then analyze it.</p>
<p>I pulled data from the World Bank API("wbgapi")as a DataFrame:</p>
<pre><code>import pandas as pd
import wbgapi as... | <p>Consider to use <code>groupby</code>:</p>
<p>The aggregation will be based on columns you insert inside a List of columns in <code>groupby</code> functions.</p>
<p>In sample below I get the mean for 'County' and 'Region'.</p>
<pre><code>metadata = metadata.groupby(['County','Region']).agg('MeanGDP':'mean').reset_ind... | python|pandas|dataframe | 0 |
370,990 | 70,198,664 | Keep strings present in a list from a column in pandas | <p>I have a problem similar to <a href="https://stackoverflow.com/questions/51666374/how-to-remove-strings-present-in-a-list-from-a-column-in-pandas">this question</a> but an opposite challenge. Instead of having a removal list, I have a keep list - a list of strings I'd like to keep. My question is how to use a keep l... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.findall.html" rel="nofollow noreferrer"><code>Series.str.findall</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.join.html" rel="nofollow noreferrer"><code>Series.str.join</co... | python|pandas | 2 |
370,991 | 70,149,999 | Using a for-loop, in another for-loop, to iterate through a list of lists | <p>I'd like to write a set of for-loops that iterate through a list of lists as shown below.</p>
<pre><code>pathways = ['pathway_1','pathway_2']
pathway_1 = ['gene_A', 'gene_B']
pathway_2 = ['gene_C', 'gene_D']
for i in pathways:
for ii in i:
print(ii)
</code></pre>
<p>I'd like the output to look like t... | <p>In the outside loop you are looping over a string and not a list, change the code like this:</p>
<pre><code>pathway_1 = ['gene_A', 'gene_B']
pathway_2 = ['gene_C', 'gene_D']
pathways = [pathway_1, pathway_2]
for i in pathways:
for ii in i:
print(ii)
</code></pre> | python|pandas|for-loop | 0 |
370,992 | 70,106,192 | How to compute the number of 'True' valued matrices in a tensor? | <p>In the below tensor of dimension (5,1,5,5), I want to calculate the number of 5*5(innermost) Boolean matrices where all the values are 'True'.
For example,</p>
<pre><code>tf.constant([
[[[ True, True, True, True, True],
[False, True, False, True, True],
[False, True, False, True, True],
[ True, ... | <p>I think that you need <strong>tf.reduce_all</strong> .</p>
<pre><code>import tensorflow as tf
temp_tesnor = tf.constant([
[[[ True, True, True, True, True],
[False, True, False, True, True],
[False, True, False, True, True],
[ True, True, True, True, True],
[ True, True, True, True, Tr... | python|matrix|tensorflow2.0|tensor | 0 |
370,993 | 70,346,336 | Align the rows and columns of DataFrames between two Dictionaries | <p>I try to figure out how to align the rows and columns of many <code>DataFrames</code> stored in two separate <code>dictionaries</code>.</p>
<p>To illustrate it, I created four <code>DataFrames</code> <code>df1</code>, <code>df2</code>, <code>df3</code>, and <code>df4</code> which I stored in <code>dictionaries</code... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.align.html" rel="nofollow noreferrer"><code>DataFrame.align</code></a> with create <code>DatetmeIndex</code> in both <code>DataFrame</code>s:</p>
<pre><code>dic1['df1'], dic2['df2'] = (dic1['df1'].set_index('Dates')
... | python|pandas|dictionary | 2 |
370,994 | 70,183,627 | Unpivot a pandas groupby dataframe | <p>I have a dataset of weekly sales of a few stores, which looks something similar to :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>store_id</th>
<th>item_id</th>
<th>week</th>
<th>sales</th>
</tr>
</thead>
<tbody>
<tr>
<td>store1</td>
<td>item1</td>
<td>2021-01</td>
<td>3</td>
</tr>
<t... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html#pandas.DataFrame.melt" rel="nofollow noreferrer"><code>df.melt</code></a>. Using the below dataframe:</p>
<pre><code>df = pd.DataFrame({'store_id' : ['store1', 'store1', 'store1', 'store2', 'store2'],
... | python|pandas|dataframe | 1 |
370,995 | 70,072,326 | TypeError: cannot assign 'torch.cuda.FloatTensor' as parameter 'weight_hh_l0' (torch.nn.Parameter or None expected) | <p>I am trying to train the model implemented in this repo <a href="https://bitbucket.org/VioletPeng/language-model/src/master/" rel="nofollow noreferrer">https://bitbucket.org/VioletPeng/language-model/src/master/</a> (the second model: title to title-storyline to story model)</p>
<p>The training would go fine for the... | <p>I downgraded my python to 3.6 and reinstalled all the requirements and it worked.</p>
<p>So probably the issue was an incompatible torch version.</p> | pytorch | 0 |
370,996 | 70,173,261 | Merging Date and Hour in Pandas | <p>I have two columns in Pandas DataFrame, one containing a date as a string and one containing the hour of the day as an int.</p>
<p>I want to convert this into a datetime stamp.</p>
<p>I have managed this but feel it is slow.</p>
<p>The data is:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'... | <p>I'd do:</p>
<pre><code># is your data day-first or month-first?
df['datetime'] = pd.to_datetime(df['Date'], dayfirst=True) + pd.to_timedelta(df['Hour'], unit='H')
df = df.drop(['Date','Hour'], axis=1)
</code></pre> | python|python-3.x|pandas|datetime | 2 |
370,997 | 70,160,995 | Trying to get subtotals from a pandas dataframe | <p>I'm doing cross-tabulation between two columns in the dataframe. Here's a sample from the columns:</p>
<pre><code> column_1 column_2
A -8
B 95
A -93
D 11
C -62
D -14
A -55
C 66
B 76
D -49
... | <p>If you'd simply like the totals by the individual categories in <code>column_1</code> (A, B, C, D), maybe a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby</a> and summation could be helpful! You would call the <code>groupby</code> ... | pandas|crosstab|subtotal | 1 |
370,998 | 70,347,536 | Cannot find index of corresponding date in pandas DataFrame | <p>I have the following DataFrame with a <code>Date</code> column,</p>
<pre><code>0 2021-12-13
1 2021-12-10
2 2021-12-09
3 2021-12-08
4 2021-12-07
...
7990 1990-01-08
7991 1990-01-05
7992 1990-01-04
7993 1990-01-03
7994 1990-01-02
</code></pre>
<p>I am trying to find the... | <p>I have reproduced your <code>Dataframe</code> with minimal samples. By changing the way that you can compare the <code>date</code> will work like this below.</p>
<pre><code>import pandas as pd
import datetime as dt
df = pd.DataFrame({'Date':['2021-12-13','2021-12-10','2021-12-09','2021-12-08']})
df['Date'] = pd.to_d... | python|pandas|dataframe | 0 |
370,999 | 70,301,548 | convert string as 'hours' and 'mins' into minutes | <p>I have a column in my dataframe df:</p>
<pre><code>Time
2 hours 3 mins
5 hours 10 mins
1 hours 40 mins
10 mins
4 hours
6 hours 0 mins
</code></pre>
<p>I want to create a new column in df 'Minutes' that converts this column over to minutes</p>
<pre><code>Minutes
123
310
100
10
240
360
</code></pre>
<p>Is there a pyth... | <p>Here is ugly bug <code>pd.eval</code> processing only less like 100 rows, so after stripping <code>+</code> is called <code>pd.eval</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a> for prevent it:</p>
<pre><... | python-3.x|pandas|dataframe | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.