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
360,400
60,995,066
Adding and averaging a set of columns depending on the value of a secondary column in python
<p>I have a dataset which has the following values:</p> <pre><code>LabelA PositiveA NegativeA LabelB PositiveB NegativeB LabelC PositiveC NegativeC Final_Label 1 .60 .40 0 .30 .70 1 .9 .1 1 0 .1 ...
<p>Here's my approach with <code>where</code> and <code>mask</code>:</p> <pre><code># filter the labels, positives, negatives: labels = df.filter(regex='Label\w').eq(1).values positives = df.filter(regex='Positive\w') negatives = df.filter(regex='Negative\w') # output df['Polarity'] = np.where(df['Final_Label'], ...
python|pandas|numpy|dataframe|sentiment-analysis
2
360,401
61,070,082
Difference between using import keras and import tensorflow.keras?
<p>I've been using tensorflow for cpu on my laptop and due to it been so slow I decided to move to my desktop pc and use tensorflow for gpu.</p> <p>The problem is that in my desktop computer I can't import like this, which I'm able to do on my laptop:</p> <pre><code>from tensorflow.keras.preprocessing.image import Im...
<p><code>tensorflow.keras</code> imports use <a href="https://github.com/tensorflow/tensorflow/tree/r2.0" rel="noreferrer">TensorFlow</a> repository code, whereas <code>keras</code> imports use <a href="https://github.com/keras-team/keras" rel="noreferrer">Keras</a> repository code. The two use independent method/class...
python|tensorflow|keras
5
360,402
60,791,810
How two combine two columns of different dataframes such that they have unique values?
<p>I have two different dataframes and I want to get the sorted values of two columns.</p> <p><strong>Setup</strong></p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df1 = pd.DataFrame({ 'id': range(7), 'c': list('EDBBCCC') }) df2 = pd.DataFrame({ 'id': rang...
<p>Here one possible way to achive it:</p> <pre><code>t1 = df1.c.drop_duplicates() t2 = df2.c.drop_duplicates() tmp1 = pd.DataFrame({'id':t1, 'c_first':t1}) tmp2 = pd.DataFrame({'id':t2, 'c_second':t2}) result = pd.merge(tmp1,tmp2, how='outer').sort_values('id').drop('id', axis=1) result c_first c_second 4 Na...
python|pandas
2
360,403
60,878,242
File not found error. Cannot get the correct path
<p>I try to open up a file to create a pandas dataframe with the following command:</p> <pre><code>foot_ds=pd.read_excel("C:/Users/xatzo/LocalDisk/Data/S1-speed 3 km_h-trialno 1 - Right Leg - shoe.xlsx") </code></pre> <p>but i get</p> <pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/xatzo...
<p>SOLVED IT, file was not xlsx, was csv</p>
python|excel|pandas
0
360,404
60,944,633
What is the difference between the following matrix?
<p>I have a piece of code like the following. I have to implement image2vector() that takes an input of shape (length, height, 3) and returns a vector of shape (length*height*3). It doesn't give me a result of what I expect. Actually, I don't understand the difference between the result which I got and the expected one...
<p>Your image does not have the shape (length, height, 3) </p> <pre><code>In [1]: image = np.array([[[ 0.67826139, 0.29380381], ...: [ 0.90714982, 0.52835647], ...: [ 0.4215251 , 0.45017551]], ...: ...: [[ 0.92814219, 0.96677647], ...: [ 0.85304703, 0.52351845],...
numpy|math|matrix
1
360,405
60,876,340
How can I save a trained TensorFlow Federated model as a .h5 model?
<p>I want to save a TensorFlow federated model which was trained with the FedAvg Algorithm as a Keras/.h5 model. I couldn't find the documents on this and would like to know how it may be done. Also if possible, I'd like to have access to both the aggregated server model and the models of the clients.</p> <p>The code ...
<p>Roughly, we will be using save_checkpoint/load_checkpoint methods. In particular, you can instantiate a FileCheckpointManager, and ask it to save state (almost) directly.</p> <p>state in your example is an instance of tff.python.common_libs.anonymous_tuple.AnonymousTuple (IIRC), which is not compatible with tf.conv...
tensorflow-federated
3
360,406
61,084,508
How to use pd.grouper along with groupby in pandas
<p>This is my dataframe</p> <pre><code> S2PName-Category S2BillDate totSale 0 Food 2019-05-18 2150.0 1 Beverages 2019-05-19 403.0 2 Food 2019-05-19 7254.0 3 Others 2019-05-19 200.0 4 Juice 2019-05-19 125.0 5 Snacks 2...
<pre><code>basic_df_2 = basic_df.groupby(['S2PName-Category',basic_df['S2BillDate'].dt.to_period('M')], sort=False)['S2PGTotal'].agg([('totSale','sum')]).reset_index() </code></pre> <p>dt.to_period will help in taking up arguments related to frequency ! </p>
python|pandas
0
360,407
60,767,413
How to add major and minor grid lines using pcolor?
<p>My goal is to add a thick set of grid marks over the existing ones I have created using pcolor (see code below). There would be one thick grid line for every N (5 for instance) thinner grid lines. The grid lines I want to add could be analogous to major tick marks while the existing grid lines could be analogous to ...
<p>I was able to resolve my issue by digging around in the <a href="https://matplotlib.org/3.2.0/api/_as_gen/matplotlib.pyplot.grid.html" rel="nofollow noreferrer">matplotlib.pyplot.grid documentation</a>.</p> <p>Here is my updated code:</p> <pre><code>Z = np.random.rand(25, 25) fig=plt.figure(figsize=(18, 16), dpi=...
python|python-3.x|numpy|matplotlib
1
360,408
60,850,695
better method to filter out M-F in the hours of 7AM - 5PM from dataset?
<p>I am experimenting with <code>concat</code> and pandas attempting to filter out weekdays Monday thru Friday in the hours of 7AM to 5PM from a data set. So basically the only data left would be <strong><em>weekends all hours</em></strong> and <strong><em>weekday night time hours of 6PM to 6AM</em></strong>.</p> <h1>...
<p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.between_time.html" rel="nofollow noreferrer"><code>DataFrame.between_time</code></a> to keep only rows between two certain hours and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIn...
python|pandas
1
360,409
60,886,823
Applying calculations to a dataframe where conditions are met
<p>I have a pandas dataframe which looks like this:</p> <p><strong>df</strong></p> <pre><code> date name product items 0 2020-01-01 google one 224.0 2 2020-01-01 amazon two 4.0 3 2020-01-01 amazon thre...
<p>For one condition is possible change your solution with select mask both sides and multiple:</p> <pre><code>m = (df['name']=='google') &amp; (df['product'] == 'one') df.loc[m, 'price'] = df.loc[m, 'items'] * 100 print (df) date name product items price 0 2020-01-01 google one 224.0 22400...
python|pandas|dataframe
2
360,410
60,839,106
re-arranging two or more pandas dataframes for a seaborn graph
<p>Two Laboratories have carried out a series of measurements:</p> <ol> <li>In three experimental conditions where the instruments are known to show a different response (<code>test_1</code>, <code>test_2</code>, <code>test_3</code>)</li> <li>Using two different makes and models of instruments (foo, bar)</li> <li>Repe...
<h3>A not very elegant solution</h3> <p>suppose the original dataframe, complete with all info, is:</p> <pre><code>df = pd.DataFrame({'test': ['test_1', 'test_2' ,'test_3'], 'foo_110': [1.1, 1.18, 1.19], 'foo_112': [1.15, 1.25, 1.25], 'bar_888': [1.11, 1.15, 1.16...
python|pandas|seaborn
0
360,411
61,041,024
TSFRESH - features extracted by a symmetric sliding window
<p>As raw data we have measurements <code>m_{i,j}</code>, measured every 30 seconds (<code>i=0, 30, 60, 90,...720,..</code>) for every subject <code>j</code> in the dataset.</p> <p>I wish use <strong>TSFRESH</strong> (package) to extract time-series features, such that for a point of interest at time <code>i</code>, f...
<p>If I understand your idea correctly, it is even possible to do this with only one-sided rolling. Let's try with one example:</p> <p>You want to predict for the time 8:00 - and you need for this the data from 5:00 until 11:00. If you roll through the data with a size of 6h and positive rolling direction, you will e...
python|pandas|time-series|feature-extraction|tsfresh
1
360,412
60,885,322
Using a series as input, how can I find rows with matching values in a pandas dataframe? e.g. df.loc[series]?
<p>I have a DataFrame <code>df</code> and a series <code>s</code> matching the columns in <code>df</code>. I would like to find all rows in <code>df</code> that have the same values as <code>s</code>. I should probably mention that the columns can change, but <code>s</code> will always be a row within <code>df</code>.<...
<p>Compare rows by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a> and then test if all <code>True</code>s per rows by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.all.html" rel="n...
python|pandas|dataframe
1
360,413
60,847,083
AttributeError: 'torch.return_types.max' object has no attribute 'dim' - Maxpooling Channel
<p>I'm trying to do maxpooling over channel dimension:</p> <pre><code>class ChannelPool(nn.Module): def forward(self, input): return torch.max(input, dim=1) </code></pre> <p>but I get the error</p> <pre><code>AttributeError: 'torch.return_types.max' object has no attribute 'dim' </code></pre>
<p>The <a href="https://pytorch.org/docs/stable/generated/torch.max.html#torch.max" rel="noreferrer"><code>torch.max</code></a> function called with <code>dim</code> returns a tuple so:</p> <pre><code>class ChannelPool(nn.Module): def forward(self, input): input_max, max_indices = torch.max(input, dim=1) ...
python|computer-vision|pytorch
22
360,414
61,165,106
How to apply a formula to all columns in a Dataframe pandas
<p>I have the following Dataframe:</p> <pre><code>import pandas as pd data = {'MA1': [ float("nan"), float("nan"), -1, 1], 'MA2': [ float("nan"), -1, 0, 0], 'MA3': [ 0, 0, 1, -1]} df_input = pd.DataFrame(data, columns=['MA1', 'MA2', 'MA3']) </cod...
<p>You can loop over the columns and use <code>DataFrame.loc</code> to assign the 0 when the first valid value is <code>-1</code>:</p> <pre><code>dft = df_input.replace(0, np.NaN) for col in df_input.columns: idxmin = dft[col].idxmin() if df_input.loc[idxmin, col] == -1: df_input.loc[idxmin, col] = 0 ...
python|pandas
3
360,415
61,071,085
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. (error running Spleeter using Python)
<p>I'm trying to utilize an open-source AI called Spleeter to separate and acquire song stems, but after following the instructions in this tutorial (<a href="https://www.youtube.com/watch?v=WmThLASBpMI" rel="nofollow noreferrer">https://www.youtube.com/watch?v=WmThLASBpMI</a>) and verifying that everything installed c...
<p>I got the same problem, then came up against a catch-22 solution: pip install tensorflow==2.0</p> <p>This supposedly takes care of the missing dll but while tensorflow was installing I got an error that spleeter needs tensorflow 1.15.2 and is incompatible with 2.0. I tried installing 1.15.2 again but got the same d...
python|tensorflow
1
360,416
60,890,739
Tensorflow Custom layer weights not training but bias is
<p>I've been writing some custom layers and I have realized my bias values will train but my weights are not training. I'm going to use a very simplified code here to illustrate the issue.</p> <pre><code>class myWeights(Layer): def __init__(self, units, **kwargs): self.units = units super(myWeigh...
<p>What your trying is <strong>Multilayer Perceptron (MLP)</strong>, <strong>MLP</strong> is usually composed of one(passthrough) input layer, one or more layers of TLUs, called hidden layers, and one final layer of TLUs called the output layer. </p> <p>Here the signal flows only in one direction (from the inputs to ...
python|keras|tensorflow2.0
-1
360,417
60,984,907
How to normalize nested JSON with strings consisting dictionary?
<p>I want to normalize and create dataframe from nested JSON with strings that consists another dict. I already tried</p> <pre><code>with open('/content/drive/My Drive/conversation_data.json', 'r') as f: data = json.load(f) table = pd.json_normalize(data, 'conversations') table </code></pre> <p>but it returns all ...
<p>The string appears to be itself a JSON fragment. It doesn't actually contain those backslashes (those are part of how the string is represented for printing), so all you need to do is feed it back to the JSON parser.</p> <p><code>json.load</code> and <code>json.dump</code> are used with files; the corresponding fun...
python|json|pandas|dataframe|nested
0
360,418
60,764,362
Python Pandas CSV Converting Int64 to the Object and call the right row via input
<p>I am new in Python Pandas and I am trying to figure it out the problem.</p> <p>I am fighting with the problem of converting dtype value in my csv.</p> <p>I wrote a simple example to understand what is the problem but I cannot see there anything and I am not able to find why it is not working .. Please see below.</...
<p>The reason for the observed behavior is that column 'C' is your index. I do not know why, because it is not in your code. My solution:</p> <pre><code>import pandas as pd # build test data data_Cisla = [[1, 10, 'text_1'], [2, 20, 'text_2'],] data_Cisla = pd.DataFrame.from_records(data=data_Cisla, col...
python|pandas|csv|input|type-conversion
0
360,419
60,933,498
Searching for information within grouped data and propogating it to the group
<p>I have a conundrum.</p> <p>My data has an ID, a grouping key, a label, and second label. It looks kinda like this</p> <pre><code>|----|----------|-------|------| |id |group_col |label1 |label2| |--- |----------|-------|------| |1 | 1 | abcd | 123 | |2 | 1 | nfrv | 123 | |3 | 2 | dfg...
<p>I actually had a bit of a brainwave earlier, and came up with a possible solution. havent tested it on the large data jet, and it is not cleaned up (will do that later). But if anyone has a better way I would love to hear it.</p> <pre><code>df = pd.DataFrame(np.array([[1,1,'abcd',123], [2,1,'nfrv'...
python|pandas
0
360,420
61,091,450
No module named "tensorflow"
<p>I want to build tensorflow with python libraries. Currently I have tensorflow installed but I do not see python packages in <code>/usr/local/lib/python3.6/dist-packages</code> so when I try to import tensorflow module in python terminal, it fails. However, there is library in <code>/usr/lib</code> and C++ programs w...
<p>You can get TensorFlow in python package by:</p> <ol> <li>Directly doing pip install tensorflow: It will install the precompiled version by directly downloading a wheel file.</li> <li>Build from source code in GitHub using bazel build.</li> </ol> <p>For the second approach, the following steps are needed:</p> <ol...
tensorflow|bazel
0
360,421
60,982,040
Vanishing rows in pandas dataframe
<p>I am losing rows somehow and I am uncertain on how to move forward or even debug this one. I read a record of about 500,000 rows into a pandas data frame. There doesn't appear to be any nulls. I normalize the data and viola, three rows have vanished. As to which or how, I have no idea. Here is what I am doing. ...
<p>You are normalising with <code>train_stats</code> values rather than <code>train_labels</code> mean and sd.</p>
python|pandas|dataframe
0
360,422
60,878,336
Numpy install wants to create tmp file in lib folder where I do not have write access
<p>I want to install numpy for python3 on a local file system with a Hadoop cluster so that I can use the library in pyspark. The problem is that I cannot install numpy without it failing at a step where it attempts to make a tmp file in the python3 subfolder, except it's trying to create said tmp file to the write-res...
<p>There are couple of options:- ( I would select the virtual environment one because it's the cleanest solution that worked for me easily without tampering anything else.)</p> <ol> <li><p>One being using <code>sudo</code> to get the root access and install it there. </p></li> <li><p>Other options are - install it in ...
python|bash|numpy|filesystems|setuptools
2
360,423
60,870,186
Using resample on dataframe containing multiple Time Series
<p>say I have a dataframe containing multiple time series like here:</p> <pre><code>Time Stamp Name Load 03/01/2017 00:00:00 CAPITL 1040.80 03/01/2017 00:00:00 EST CENTRL 1468.30 03/01/2017 00:00:00 EST DUNWOD 516.90 03/01/2017 00:05:00 CAPITL 1542.80 03/01/2017 00:05:00 EST CENTRL...
<p>You should first groupby Name and then resample:</p> <pre><code>df.groupby('Name').resample('60T', on='Time Stamp').mean() </code></pre>
python|pandas|dataframe|time-series
2
360,424
60,928,959
List almost in list of lists Python
<p>I have a list of lists in python, where in my case the lists are coordinates. I want to append new coordinates to this list, but only if the coordinate does not exist yet. This is easily doable in the following manner.</p> <pre><code>List = [coord1,coord2,...,coordn] coord = [x,y,z] if not coord in List: List.appen...
<p>this is a common problem, which can be solved by rounding the float value:</p> <pre><code>coord = [0.99999999999,0.000000000001] rounded_coord = [ '%.2f' % elem for elem in coord ] </code></pre> <p>this should return the list with the rounded float values, but they will be of type String. to work with the data, it...
python|list|numpy|python-3.6
0
360,425
61,017,461
Initializing values for the first and last row following a resample operation?
<p>Given for instance a DataFrame with 1h <code>Period</code>, I would like to set 0 &amp; 1 values in a new column whenever a new 5h <code>Period</code> starts and finishes respectively.</p> <p>Let's consider this input data for instance:</p> <pre><code>import pandas as pd from random import seed, randint from colle...
<p>Ok, I finally setup to use following approach which is rather fast (no loop)</p> <pre><code> super_pi = pd.period_range(start='2020-01-01 00:00', end='2020-06-01 00:00', freq='5h', name='p5h') super_df = pd.DataFrame({'End' : 1, 'Start' : 0}, index=super_pi).resample('1h').first() # We know last row is a 1 (end o...
python|pandas|period
1
360,426
60,868,404
find specific string in spark sql--pyspark
<p>Im trying to find an exact string match in a dataframe column from employee dataframe</p> <pre><code>Employee days_present Alex 1,2,11,23, John 21,23,25,28 </code></pre> <p>Need to find which employees are present on 2nd based on days_present column expected output: Alex</p> <p>below is what i have tri...
<p>We can use <strong><code>array_intersect</code></strong> function starting from Spark-2.4+ and then check the array size if <strong><code>size &gt;=2</code></strong></p> <p><strong><code>Example:</code></strong></p> <pre><code>df.show() +--------+------------+ |Employee|days_present| +--------+------------+ | A...
pandas|apache-spark|pyspark-sql
2
360,427
61,052,312
Create a new Column in Pandas DataFrame and populate the values from other columns
<p>In Python, I have the following dataframe:</p> <pre><code>df_dict = {'time':[1,2,3],'a':['a1','a2','a3'],'b':['b1','b2','b3'], 'c':['c1','c2','c3']} df = pd.DataFrame(df_dict) df time a b c 0 1 a1 b1 c1 1 2 a2 b2 c2 2 3 a3 b3 c3 </code></pre> <p>I need to add a new column which takes va...
<p>Use <code>df.melt</code></p> <pre><code>In [3]: df.melt(id_vars='time', value_vars=['a', 'b', 'c']) Out[3]: time variable value 0 1 a a1 1 2 a a2 2 3 a a3 3 1 b b1 4 2 b b2 5 3...
python|pandas|dataframe
2
360,428
61,105,982
how to check the specific files is present in folder or not in automated way in python
<p>I have 1000 of the folders in each of their different pdf files available. I have go into each folder and check whether their specific file( for example folder is named as school0001 and files is named as following it schoool_1m.pdf, schoool_2m.pdf.. schoool_10m.pdf) now I have go into the first folder and check all...
<pre><code>import glob import os import pandas as pd # the path to your folder folder_path = r'some\path\to\your\folder' # list the directories in the folder path folders = os.listdir(folder_path) # create an empty list to append to dfs = [] # iterate through all the folders in your path for folder in folders: #...
python|pandas|loops|if-statement
0
360,429
61,178,653
Visualization of missing records in DataFrame
<p>Visualization of missing records in DataFrame</p> <p>I have a lot of missing dataframe records.</p> <pre><code>df.isnull().sum() </code></pre> <p>The problem is that these deficiencies are connected and I don't know how to see them. Because I do not want to mess up so as to spoil data. What are your ways to see t...
<p>You ca use such plot of concentration</p> <pre><code>import seaborn as sns sns.heatmap(df.isnull(),yticklabels=False,cbar=False,cmap='viridis') </code></pre> <p><a href="https://i.stack.imgur.com/IqqQT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IqqQT.png" alt="enter image description here"...
pandas
1
360,430
61,045,787
How to apply functions to a Dataframe with arrays within it, in Python?
<p>I hope to be clear on the questions, but let me explain me better, I have this dataframe:</p> <pre><code>import pandas as pd m = pd.DataFrame({'A': (1, 2, 3), 'B': ([0, 1, 2], [3, 4, 5], [6, 7, 8])}) </code></pre> <p>My objective is to obtain the column z which is each y-array squared plus t...
<p>In <code>pandas</code> , and since you have object in your column, which will make most of the method from pandas not work, we use for loop here. This method should be fast enough ~ </p> <pre><code>m['C']=[(x + np.array(y)**2).tolist() for x , y in zip(m.A,m.B)] </code></pre>
python|pandas|numpy
2
360,431
61,130,853
Create List of Dict: python / pandas
<p>I got an import from a Excel which I read with Pandas. In each row is a different person, the columns give values like people_id etc.</p> <p>Now I actually want to put each person into a dict and later each dict to a list. But unfortunantely my loop returns always the same person, but 19 times in the list. Where is...
<p>If I understood correctly the question, you have to append to <code>list_people</code> in the first loop, after you have completed the dict entry for a person. Here in the first loop you read the first line, store all the info regarding the person in this row and then you pass to the next row, overwriting the conten...
pandas|list|loops|dictionary
0
360,432
61,123,645
How to get the last line number of Pandas Dataframe?
<p>I'm trying to get the last row elements from a CSV file.</p> <p>My code so far -</p> <pre><code>from google.cloud import storage import pandas as pd temp = pd.read_csv('gs://my-bucket/my_file.csv',header=None) print(temp[0][6]) -&gt; Key 0 is obvious as the first element in last row but how to get no. 6 dynamical...
<p>You can get the last row of a Dataframe by using the -1 index.</p> <p>In your example <code>temp.iloc[-1]</code>, or <code>temp.iloc[-1].values</code> if you want to get the values from the last dataframe row as an array.</p>
python|pandas
0
360,433
60,914,074
How to get rows (by id) of ids that appears in the dataframe in time period of 2 months?
<p>Does anybody know how I do the following (in Python)? </p> <p>I have a pandas DataFrame in which I have the following values: date (dd/mm/yy), id (int), label (values 0 or 1). </p> <p>I want to identify (and keep it in a new dataframe), for each id, if it appears again in the dataframe, in the time period of 2 m...
<p>As the task involves date calculations, I converted <em>date</em> column to <em>datetime</em>, so they are printed in <em>yyyy-mm-dd</em> format.</p> <p>Define the following function, generating "second level" group numbers, for each "first level" group (grouped by <em>id</em>):</p> <pre><code>def grNo(dat): g...
python-3.x|pandas|datetime
2
360,434
61,003,237
Count Boolean Variable By Date
<p>I've been posting a lot lately as I'm new to Python/Pandas. I have a pandas DF called NOTES_TAT_v1. It looks like this:</p> <pre><code>PT_FIN Date Interpreter Needed Interpreter Used 1 27 January, 2020 1 1 2 27 January, 2020 1 ...
<pre><code>import pandas as pd df = pd.read_csv('df.txt', sep=r"[ ]{2,}") print(df) PT_FIN Date Interpreter Needed Interpreter Used 0 1 27 January, 2020 1 1 1 2 27 January, 2020 1 0 2 3 27 January, 2020 0 0 3 4 28 January, 2020 0 0 4 5 28 January, 2020 1 1 5 6 29 ...
python|pandas
1
360,435
60,909,479
how to speed up writing a large string into a file in python
<p>So I have a 1 Gb input txt file (1 million lines * 10 columns) and I am using python to process this input to get some calculated information and add each information (out of 1 M lines) into a string, and eventually save it. I tried to run my script, but realized the process got slower and slower as the string got b...
<p>Hard to tell what your goal is here, but a few things might help. Here is an example df.</p> <pre><code>new_df = pd.DataFrame({0:np.random.choice(list(string.ascii_lowercase), size=(10)), 1:np.random.choice(list(string.ascii_lowercase), size=(10)), 2:np.random.choice(li...
python|pandas
0
360,436
60,904,986
How to solve error: InvalidIndexError: Reindexing only valid with uniquely valued Index objects when mapping a dataframe to another one
<p>I have a <code>Pandas DataFrame</code>. I am trying to map the <code>ProductID</code> from one <code>dataframe</code> to another <code>dataframe</code>.</p> <p>Here is my attempt:</p> <pre class="lang-py prettyprint-override"><code>Product_id_mapper = dict(df1[['ProductID', 'Cost']].drop_duplicates().values) df2[...
<p>If I have understood correctly you want to merge based on a <code>Key</code> two dataframes. Then this is my suggestion:</p> <p>Suppose <code>a.csv</code>:</p> <pre><code>carrier,type,count DTH,a,123 DTH,b,3123 DTH,c,41341 DTH,d,13411 BLUEDART,a,12123 BLUEDART,b,31231 BLUEDART,c,411 BLUEDART,d,11 </code></pre> <p...
python|pandas|numpy|dataframe|data-manipulation
0
360,437
61,104,018
Star schema in Python Pandas
<p>I currently have a project where I extract the data from a Firebird database and do the ETL process with Knime, then the CSV files are imported into PowerBI, where I create table relationships and develop the measures. With Knime I summarize several tables, denormalizing. I would like to migrate to Python completely...
<p>I think I can answer your question now that I have a better understanding of what you're trying to do in Python. My stack for reporting also involves Python for ETL operations and Power BI for the front end, so this is how I approach it even if there may be other ways that I'm not aware of.</p> <p>While I create ac...
python|pandas|powerbi|knime
1
360,438
61,045,331
How to do row level operation and append to existing DataFrame in Pandas?
<p>I have a dataframe like:</p> <pre><code> a b c d 0 1 2 3 4 1 4 7 2 8 2 5 7 6 9 </code></pre> <p>I want to make a new dataframe like </p> <pre><code> a b c d sum multiply 0 1 2 3 4 10 24 1 4 7 2 8 ...
<pre><code>df['sum'] = df['a']+df['b']+df['c']+df['d'] df['multiply'] = df['a']*df['b']*df['c']*df['d'] </code></pre>
python|pandas|dataframe
0
360,439
60,961,263
I cannot understand the np.where result function
<p>I have this code:</p> <pre><code>tt = np.asarray([[1,4,5],[3,1,5],[1,4,5],[3,1,5]]) np.where(tt &lt; [2]) </code></pre> <p>but I have this output :</p> <pre><code>(array([0, 1, 2, 3]), array([0, 1, 0, 1])) </code></pre> <p>I don't understand why I have this output, the content of those two arrays indicats what e...
<p>Thank you for the answer. My problem was that I was expecting a table with all the values that are smaller than two. I just understood the output now, the first table shows the row indexes and the second one shows the column indexes. And this indicates that the [Ri,Ci] element (the ith row and the ith column) is les...
python|numpy
0
360,440
60,804,005
Violin plot using sequential rows as the Y-axis
<p>I am trying to build a violin plot of the following data(CSV):</p> <pre><code>,Exp No.,Sensory accuracy(mm),Volume of Data points,Exp 1,Exp 2,Exp 3,Exp 4,Exp 5,Exp 6,Exp 7,Exp 8,Exp 9,Exp 10,Coefficient ,PPIP 0,1,10,3,9948,9998,9961,10042,10049,10029,9975,10020,9986,10002,34.07508050043479,0.4231902824036948 1,2,10...
<p>The question is ambiguous. I will try my best;</p> <p>Data</p> <p><a href="https://i.stack.imgur.com/rJwTl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rJwTl.png" alt="enter image description here"></a></p> <p>Apply <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.m...
python|pandas|matplotlib|plotly|violin-plot
0
360,441
61,052,369
Keeping the data based on date in dataframe python
<p>Input DataFrame</p> <pre><code>ID Data Date 1 A 01-04-2020 23:50 B 02-04-2020 6:15 2 C 30-03-2020 22:10 D 28-03-2020 8:15 3 E 26-03-2020 7:20 </code></pre> <p>Output I want</...
<p>IIUC, you want to keep the first date:</p> <pre><code> df.sort_values('Date').groupby('ID').first() </code></pre> <p>Output:</p> <pre><code> Data Date ID 1 A 2020-01-04 23:50:00 2 D 2020-03-28 08:15:00 3 E 2020-03-26 07:20:00 </code></pre>
python|pandas|dataframe
2
360,442
60,841,161
Why can't I append a PyTorch tensor with torch.cat?
<p>I have:</p> <pre><code>import torch input_sliced = torch.rand(180, 161) output_sliced = torch.rand(180,) batched_inputs = torch.Tensor() batched_outputs = torch.Tensor() print('input_sliced.size', input_sliced.size()) print('output_sliced.size', output_sliced.size()) batched_inputs = torch.cat((batched_inputs, ...
<p>Assuming you're doing it in a loop, I'd say it is better to do like this:</p> <pre class="lang-py prettyprint-override"><code>import torch batch_input, batch_output = [], [] for i in range(10): # assuming batch_size=10 batch_input.append(torch.rand(180, 161)) batch_output.append(torch.rand(180,)) batch_i...
python|pytorch
3
360,443
60,885,005
How does pyplot know what was plotted by the output of pandas.DataFrame(...).cumprod().plot()
<p>I am coming from a background of C# programming to learn python, and trying to wrap my head around how things work. There seems to be a lot of "magic" in getting the result you want in python.</p> <p>For example, take the following code:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplo...
<p>When you run for example plt.legend() it uses the function plt.gca() (get current axis) and since the pandas plot was the last axis plotted it knows where to put the legend. If you do, for example:</p> <pre><code>pd.DataFrame({'x': [1,2], 'y': [2,3]}).plot.line() pd.DataFrame({'x': [1,2], 'y': [2,43]}).plot.line()...
python|pandas
1
360,444
61,063,784
Fast and precise nearest step floating point ceiling/flooring without Decimal.quantize
<p>The following function is supposed to ceil the given number to the nearest step:</p> <pre><code>def ceil_step(x, step): return math.ceil(x / step) * step </code></pre> <p>This works well... until it does not:</p> <pre><code>print(ceil_step(1000.365, 0.01)) # 1000.37 print(ceil_step(1000.369, 0.01)) # 1000.37 ...
<p>For now, I have settled with the following function:</p> <pre class="lang-py prettyprint-override"><code>def round_step(x, step, method=-1): eps = np.finfo(np.float64).eps digits = math.ceil(-np.log10(step)) return round(math.ceil(x * (1 - eps) / step) * step, digits) </code></pre> <p>The multiplicatio...
python|numpy|floating-point|ieee-754|numba
1
360,445
71,581,585
Removing alphabets from column
<pre><code>col A 28 45 67 A 67 C D 78 89 </code></pre> <p>I want to remove row containing characters(i.e) A, B, C...(can be any from A-Z) I was able to remove A,B,C using the below code</p> <pre><code>new_df = df[(df['colA'] != 'A') &amp; (df['colA'] != 'B') &amp; (df['colA'] != 'C')] </code></pre> <p>I feel this is h...
<p>Try with <code>isalpha</code> for no numeric it will return <code>True</code> then we get the <code>~</code></p> <pre><code>df = df[~df.colA.str.isalpha()] Out[953]: colA 0 28 1 45 2 67 4 67 7 78 8 89 </code></pre> <p>Update method 2</p> <pre><code>df = df[pd.to_numeric(df['col A'],errors='coerce').no...
python-3.x|pandas|dataframe|data-science
1
360,446
71,694,146
Pandas: Detect change in a group and change all other entries
<p>I have a couple of datasets with names and ids. One person can be present in a dataset more then one time then this person has the same id in the dataset. The name of person can differ within the dataset and over all datasets. I need to assign UID to each person across all datasets.</p> <p>This is a example dataset,...
<p>Try:</p> <ol> <li>Create a series of &quot;uid&quot; based on the &quot;id&quot;</li> <li>Create &quot;temp_id&quot; mapping each name (lower case) to an &quot;id&quot;</li> <li>Re-map each name to get the same ids for matching id or name and get the &quot;uid&quot;.</li> </ol> <pre><code>uid = &quot;u&quot;+df.grou...
python|pandas|dataframe
2
360,447
71,586,423
comparing two series object of different length
<p>i want to create a new column in df, built on compare of two series objects, when i am trying to compare this two series i am getting</p> <p><code>ValueError: can only compare identically-labeled Series objects</code></p> <p>i am trying:</p> <pre><code>df = ((data1['price'] &gt;= data2['amount_min']) &amp; (data1['...
<p>You can use <code>df2['a'][0]</code> as scalar value instead of Pandas Series:</p> <pre><code>df1 = pd.DataFrame(np.array([1, 2, 3]), columns=['a']) df2 = pd.DataFrame(np.array([1]), columns=['a']) df1['a'] &gt; df2['a'][0] # output 0 False 1 True 2 True Name: a, d...
python|pandas
0
360,448
71,576,208
Replace substrings from a Dataframe column which correspond to values of another dataframe column with values of a third column
<p>I have this huge dataset in which I have to replace each country's name with the corresponding ISO code. I have stored the ISO code of each country into another df. e.g.</p> <p><code>df1</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>TERRITORY</th> </tr> </thead> <tbody> <tr> <t...
<p>You can use a combination of <code>.str.split</code> + <code>.explode</code>, then <code>.replace</code> + <code>.set_index</code>, and finally <code>.groupby(level=0)</code> + <code>agg(list)</code> + <code>.str.join</code>:</p> <pre><code>df1['TERRITORY'] = df1['TERRITORY'].str.split(', ').explode().replace(df2.se...
python|pandas|dataframe|replace|substring
0
360,449
71,632,204
Finding combinatorial occurrences along combination of rows between 2 numpy array
<p>I am trying to find a fast <strong>vectorized</strong> (at least partially) solution finding combinatorial occurrence between two 2D numpy array to identified Single Point Polymorphism linkage. The shape of each array is <strong>(factors, samples)</strong> an example for matrix 1 is as follows:</p> <pre><code>array(...
<p>With example data</p> <pre class="lang-py prettyprint-override"><code>import numpy as np array1 = np.array([ [0., 1., 1.], [1., 0., 1.]]) array2 = np.array([ [1., 1., 0.], [0., 0., 0.]]) </code></pre> <p>We can count the desired combinations with <a href="https://numpy.org/doc/stable...
python|arrays|numpy|vectorization|bioinformatics
2
360,450
71,618,978
LSTM training difficulties
<p>I wanted to train LSTM model for tabular time series data. My data shape is</p> <pre><code>((7342689, 50, 5), (7342689,)) </code></pre> <p>I was having a hard time to handle the training loss. Initially I tried with default learning rate , but it didn't help. My class label is severely skewed. I have added focal los...
<p>The loss of the model first decreased and then increased, which may be because the optimization process got stuck in a local optimal solution. Maybe you can try reducing the learning rate and increasing the epoch.</p>
tensorflow|keras|deep-learning|lstm|tf.keras
0
360,451
71,650,951
Difference in the order of applying linear decoder and average pooling for sequence models
<p>I am working with sequence modelling in pytorch and trying to determine if the order of the pooling and linear decoding layer matters. Given that I have a sequence with the shape <code>(Batch, Seqlen, dim_model)</code> and I want to transform it into <code>(Batch, dim_output)</code> I will need a pooling layer for r...
<p>A linear layer does x -&gt; Ax+b for some matrix A and vector b. If you have a bunch of x (x1, x2, x3, ..., xn) then A[(x1+...+xn)/n] = (Ax1 +... +Axn)/n, so for mean pooling, applying pooling first and then doing the linear layer results (up to floating point errors) in the same value as applying the linear layer f...
pytorch|torch
1
360,452
71,481,253
Count values in column with ranges given a specific condition
<p>I have this code</p> <pre><code>df = pd.DataFrame({'R': {0: '1', 1: '2', 2: '3', 3: '4', 4: '5', 5: '6', 6: '7'}, 'an': {0: 'f', 1: 'i', 2: '-', 3: '-', 4: 'f', 5: 'c,f,i,j', 6: 'c,d,e,j'}, 'nv1': {0: [-1.0], 1: [-1.0], 2: [], 3: [], 4: [-2.0], 5: [-2.0, -1.0, -3.0, -1.0], 6: [-2.0, -1.0, -2.0, -1.0]}}) </code></pre...
<p>You need to loop here.</p> <p>Either using <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a> with a lambda function and <code>sum</code>:</p> <pre><code>df['ct'] = df['nv1'].apply(lambda s: sum(e&lt;-1 for e in s)) </code></pre> <p...
pandas|count|range
1
360,453
71,788,699
How to use groupBy in Pandas to sum total revenue of a customer
<p>I'm working with a database but I'm having a problem with only one thing</p> <p>The part I want to show is in the image below:</p> <p><a href="https://i.stack.imgur.com/TqCGN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TqCGN.png" alt="enter image description here" /></a></p> <p>This database i...
<p>You can aggregate the results by using <code>groupby</code> function.</p> <pre><code>df.groupby('id').agg({'revenue':'sum'}) </code></pre>
python|python-3.x|pandas|dataframe|group-by
2
360,454
71,460,793
tf.reshape(self.normalized_price(prce), (-1, 1)), ValueError: Shape must be rank 1 but is rank 2
<p>I am getting the following error when I am calling the subclass of the model. My guess is that I am not passing the two parameters correctly or the reshape is not outputting the correct value.</p> <pre><code>ValueError: Shape must be rank 1 but is rank 2 for '{{node base_stock_model/concat}} = ConcatV2[N=3, T=DT_FLO...
<p>First I analyzed all the ranks of input tensor. If they were not the same rank model wants then we have to use tf.reshape() command or adjust the input to match model's demand. Note that, tf.shape() gives you the shape while running the model.</p> <p>Here is documentation on it.</p> <p><a href="https://www.tensorfl...
tensorflow|keras|tensorflow2.0|tf.keras
0
360,455
71,634,158
Plotting multiple subplots with different shapefiles in background
<p>I am trying to plot side by side GeoPandas shapefiles using matplotlib but the titles, xlabel and ylabel are not plotting correctly.</p> <pre><code>fig, axes = plt.subplots(1,2, figsize=(10,3), sharex=True, sharey=True) base = subs.boundary.plot(color='black', linewidth=0.1, ax=axes[0]) cluster.plot(ax=base, column...
<p>You have a mixture of object-oriented and pyplot-style <code>matplotlib</code> interactions. The <code>plt.</code>* calls are following a logic of the current axis to act upon. More detail from the <code>matplotlib</code> docs here: <a href="https://matplotlib.org/matplotblog/posts/pyplot-vs-object-oriented-interfac...
python|matplotlib|plot|geopandas
1
360,456
71,549,279
How to generate a series containing each date for the following month relative to a given date in pandas
<p>My start point is the variable <code>data_published_date</code></p> <pre><code>data_published_date Out[47]: &quot;DatetimeIndex(['2022-03-18'], dtype='datetime64[ns]', freq=None)&quot; </code></pre> <p>as it's a date in March, I wish to generate EACH day for the NEXT month as timestamp, like</p> <pre><code>['2022-04...
<p>I think the problem is <code>data_published_date</code> is Index object, but <code>date_range</code> is expecting a singleton. Since it contains only a single element, we could index it and use that instead:</p> <pre><code>out = pd.date_range(data_published_date[0] + pd.offsets.MonthBegin(n=1), ...
python|python-3.x|pandas|time-series|timestamp
1
360,457
71,694,680
Filtering a dataframe column with another column in a separate dataframe
<p>I have a dataframe table (table_1) that contains 3 cloumns:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Iteam ID</th> <th>Date / time</th> <th>Date / time</th> </tr> </thead> <tbody> <tr> <td>12</td> <td>2022-03-21 - 00:27:00</td> <td>2022-03-21 - 00:28:00</td> </tr> <tr> <td>99</td>...
<p>You should use the correct column instead of the whole dataframe:</p> <pre><code>new_df = table_1[table_1['Iteam ID'].isin(table_2['Iteam ID'].values)] </code></pre>
python|pandas|dataframe
0
360,458
71,632,105
Web scraping with python - table with mutliple tbody elements
<p>I'm trying to scrape the data from <a href="https://www.eliteprospects.com/league/nhl/stats/2021-2022?sort=tp" rel="nofollow noreferrer">the top table on this page</a> (&quot;2021-2022 Regular Season Player Stats&quot;) using Python and BeautifulSoup. The page shows stats for 100 NHL players, 1 player per row. The c...
<p>To load all player stats into a dataframe and save it to csv you can use next example:</p> <pre class="lang-py prettyprint-override"><code>import requests import pandas as pd from bs4 import BeautifulSoup dfs = [] for page in range(1, 11): url = f&quot;https://www.eliteprospects.com/league/nhl/stats/2021-2022?...
python|pandas|web-scraping|beautifulsoup
0
360,459
71,718,776
simple mapping of pandas series to 0 and 1s given threshold
<p>I am sorry for asking such a simple question (yes I googled). Do I really require 2 steps to map a simple pandas series of float between 0 and 1s to 0 and 1s given a threshold. This is the reproducible example:</p> <pre><code>series = pd.Series([0.0, 0.3, 0.6, 1.0]) threshold = 0.5 print(series) series[series &gt; ...
<p>You can use the <code>&gt;</code> operator.</p> <pre><code>series = (series &gt; threshold).astype(int) print(series) </code></pre> <p>Output:</p> <pre><code>0 0 1 0 2 1 3 1 dtype: int32 </code></pre>
python|pandas
5
360,460
71,753,506
Reading a folder with multiple excel files which contain more than 15 sheets each into a loop to be processed for feature extraction
<p>community. I hope you can offer some guidance as I am new to python programming</p> <p>I am trying to read a folder that contains 15 excel files and each excel file has 30 worksheets. I am trying to read each excel worksheet separately because I need to extract the features from the 30 sheets. I need to read the exc...
<p>The line <code>df = pd.read_excel(files,sheet_name=None)</code> creates a dictionary, with the dictionary keys being the string name of each sheet and the dictionary values being the data found in each sheet in a pandas data frame.</p> <p>You can loop through like so:</p> <pre><code>df_dict = pd.read_excel(files,she...
python|excel|pandas|loops|batch-processing
0
360,461
71,699,740
Can you perform an identical operation on each Pandas dataframe in a list?
<p>I have a list of dataframes corresponding to different countries, each formatted the same way.</p> <p>Here's <code>AUH</code> for example, the dataframe for Austria-Hungary:</p> <pre><code> stateabb ccode year milex milper irst pec tpop upop cinc version eu_gp_cinc eu_gp_irst eu_cinc 144 ...
<p>Yes, it's possible. I don't understand why your previous attempt didn't work; it was probably a typo.</p> <p>This creates a new column in each dataframe:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd # Create some dataframes from dictionaries d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [5...
python|pandas
0
360,462
71,478,271
Add model predictions as a column in pandas but keep NaN as prediction if null values present in the row
<p>I have a pandas dataframe which has some null values and want to add a new column <code>model_prediction</code> which is model's predictions on the data. The model I have does not take null values and I want the <code>model_prediction</code> value to be NaN for those rows. The problem is the dataframe is very large ...
<p>Assuming your dataframe is <code>df</code> and model is <code>model</code>, please try this:</p> <pre><code>import numpy as np df = df.reset_index(drop=True) df_na = df[df.isna().any(axis=1)] df_na.loc[:,'model_prediction'] = np.nan df_model = df.dropna() df_model.loc[:,'model_prediction'] = model.predict(df_model.v...
pandas
1
360,463
71,565,502
Calculating the time since binary output=1
<p>I have a df with 2 columns: a <code>Binary Output</code> column and a column with the corresponding time. I would like to make a third column where I calculate the time since the binary output was equal to <code>1</code>. I gave a simplified example of the kind of data I'm looking at the my desired output.</p> <p>I'...
<p>You can use <code>cumsum</code> on <code>BinaryOutput</code> to make a group for each group of zeros starting with a one, and then use <code>transform('first')</code> to get the first value for each group, and then subtract the <code>Time</code> column from the result:</p> <pre><code>df['time since output=1'] = df['...
python|pandas|dataframe|numpy|binary-data
0
360,464
71,531,108
A more pythonic way to handle comparing value to previous value in a list
<p>I have the following code which I feel is not very pythonic:</p> <pre><code>old_hostname = None for i, row in dupes.iterrows(): if i == 0: old_hostname = row['Hostname'] else: if row['Hostname'] != old_hostname: print('-----') print(f&quot;{row['Name']:&lt;32} {row['MAC']:&lt;...
<p>I'm not sure if this really answers your question but... If you have a plain list where you want to compare adjacent elements then <em>zip()</em> is your friend. For example:</p> <pre><code>myList = [1, 2, 3, 4, 5] for x, y in zip(myList, myList[1:]): if x &lt; y: # or whatever pass # do something </code></pr...
python|pandas
1
360,465
71,741,398
Pandas groupby count values above threshold
<p>I have a groupby question that I can't solve. It is probably simple, but I can't get it to work nicely. I am trying to compute some statistics on a variable with pandas groupby chained with the very handy agg function. I would like add to the list below a calculation of the number of values above a given threshold.<...
<p>Your answer works. Else you could add it to the one line, not needing to create a separate function by using <code>lambda x:</code> instead.</p> <pre><code>df = df.groupby([&quot;scenario&quot;, &quot;Name&quot;, &quot;year&quot;, &quot;month&quot;])[&quot;Value&quot;].agg([np.min, np.max, np.mean, np.std, lambda x...
python|pandas
1
360,466
71,598,878
create dataframe with increasing numbers in python
<p>I want to create the following dataframe: n is the number of rows, and m is the columns. In R, this would be generated by:</p> <pre><code>ia=array((1:m),c(m,n)) </code></pre> <p>But I do not know how i can achieve the same in python.</p> <p><a href="https://i.stack.imgur.com/mon6j.png" rel="nofollow noreferrer"><img...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.broadcast_to.html" rel="nofollow noreferrer"><code>numpy.broadcast_to</code></a> with <code>DataFrame</code> constructor:</p> <pre><code>m = 24 n = 13 df = pd.DataFrame(np.broadcast_to(np.arange(1, m + 1)[:, None], (m, n))) print (df) 0 1 2 ...
python|pandas|dataframe|matrix
2
360,467
71,505,289
columns.values is not returning the strings
<p>I have a dataframe with column name <code>msg</code> that has string values.</p> <p>I am trying to get this values using:</p> <pre><code>df['msg'].values </code></pre> <p>But I am getting integers(problaby the index of the dataframe) and not the texts.</p> <p>What am I doing wrong?</p>
<p><em>Say you have a pandas dataframe with column 'msg':</em></p> <pre><code> df['msg'] = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] </code></pre> <p><em>You can print just the string values with just:</em></p> <pre><code> df['msg'].values** --&gt; **['red', 'orange', 'yellow', 'green', 'blue', 'purple'] <...
pandas|dataframe
0
360,468
71,463,422
Elements of list in terms of array indices using Python
<p>How do I write elements of list <code>B</code> in terms of array indices of <code>A</code>? The desired output is attached.</p> <pre><code>import numpy as np A = np.array([[1,2,3],[4,5,6],[7,8,9]]) B = [1,5,6] </code></pre> <p>The desired output is</p> <pre><code>B=[A[0,0], A[1,1], A[1,2]] </code></pre>
<p>You could use <code>numpy.isin</code> to see if the elements in <code>B</code> exist in <code>A</code>; then use <code>numpy.where</code> to find the indexes of the elements that exist. Since the indexes are separated by axes, you could finally, you could unpack and <code>zip</code> them to get the desired outcome:<...
python|arrays|list|numpy
0
360,469
71,629,348
How to one hot encode the products of an unorganised market basket dataframe
<p>The dataframe I am talking about <a href="https://drive.google.com/file/d/1nhPeeakWGbcMHo6mT95AdEBANaYtTaLo/view?usp=sharing" rel="nofollow noreferrer">is this</a></p> <p>I am interested in only a subset of the products and I want to transform the data so instead of having &quot;item&quot; columns I have columns wit...
<p>Use:</p> <pre><code>df = pd.DataFrame([['ab', 'bv', 'cc'], ['cc'], ['dv', 'ab', 'ac', 'ff']], columns = ['i1', 'i2', 'i3', 'i4']) corpus = df.apply(lambda x: ' '.join(x.to_numpy().astype(str)), axis=1).values from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(min_df=0, use_idf ...
python|pandas
1
360,470
71,740,369
Drop pandas column with constant alphanumeric values
<p>I have a dataframe <code>df</code> that contains around 2 million records. Some of the columns contain only alphanumeric values (e.g. &quot;wer345&quot;, &quot;gfer34&quot;, &quot;123fdst&quot;).</p> <p>Is there a pythonic way to drop those columns (e.g. using <code>isalnum()</code>)?</p>
<p>Apply <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.isalnum.html" rel="nofollow noreferrer"><code>Series.str.isalnum</code></a> column-wise to mask all the alphanumeric values of the DataFrame. Then use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.all.html" rel="no...
pandas|alphanumeric|drop
3
360,471
71,484,131
Extract sub-array from 2D array using logical indexing - python
<p>I am trying to extract a sub-array using logical indexes as,</p> <pre><code>a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) a Out[45]: array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) b = np.array([False, True, False, True]) a[b, b] O...
<p>Numpy supports logical indexing, though it is a little different than what you are familiar in MATLAB. To get the results you want you can do the following:</p> <pre><code>a[b][:,b] # first brackets isolates the rows, second brackets isolate the columns Out[27]: array([[ 6, 8], [14, 16]]) </code></pre> <p>...
python|arrays|numpy|indexing|numpy-ndarray
3
360,472
71,686,478
Filtering each X in DataFrame with values from other Series/DataFrame (area under curve)
<p>I'm filtering over a DataFrame to get the area under a curve. I've managed to get the border of the curve, such that we only want rows under that curve.</p> <p>The way I've gone about this is by getting the <code>data_y_border</code> <strong>(red curve in diagram)</strong> with (1) in the code below (this works fine...
<p>From your comment:</p> <blockquote> <p>The curve is based on values from another column. It's basically rows where values for another column are greater than a certain value, find the lowest Y for each X. That becomes our curve boundary. Using that curve we want to find the rows in the area beneath the curve.</p> </...
python|pandas|dataframe|lambda|pandas-groupby
2
360,473
71,660,005
Optimizing torch mean over a dimension in a random batch
<p>I am looking for a way to optimize the following code in pytorch.</p> <p>I have a function <code>f</code> defined over space <code>x,y</code> and time <code>t</code>.<br /> In a random batch, I need to compute the average over all the same timestamps. I was able to achieve this with the following inefficient for-lo...
<p>I think you are looking for <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.index_add_.html#torch.Tensor.index_add_" rel="nofollow noreferrer"><code>index_add_</code></a>:</p> <pre class="lang-py prettyprint-override"><code>avg_size = int(t.max().item()) + 1 # number of rows in output tensor z = tor...
python|for-loop|optimization|pytorch|torch
0
360,474
71,641,224
How to get first occurrence of an item in python
<p>I have a table with all those infos:</p> <p><a href="https://i.stack.imgur.com/x9Dcb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x9Dcb.png" alt="enter image description here" /></a></p> <p>I exported this data and I am using panda to create a dataframe. I want to make a new table with only the...
<p>You can make a copy of your original <em>Recip_State</em> and <em>FIPS</em> columns to a new dataframe. First <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer">pandas.DataFrame.drop_duplicates()</a> on <em>Recip_State</em> column. Then slice the <e...
python|pandas|dataframe
1
360,475
71,525,034
Append column value if string is contained in another string
<p>I want to add a new column a3 to my dataframe df: If the strings of &quot;b&quot; contain strings of &quot;b2&quot; from dataframe df2, the new column a3 should append values from a2 of df2.</p> <p>first dataframe df:</p> <pre class="lang-py prettyprint-override"><code> d = {'a': [100, 300], 'b': [&quot;abc&quot;, &...
<p>You need to test all combinations. You could still take advantage of pandas vector <code>str.contains</code>:</p> <pre><code>common = (pd.DataFrame({x: df['b'].str.contains(x) for x in df2['b2']}) .replace({False: pd.NA}) .stack() .reset_index(level=1, name='b2')['level_1'].rename('b2') ) # 1 bc # 2 f...
python|pandas|dataframe
2
360,476
71,497,699
setting up tensorflow_io with tensorflow 2.6.0 on anaconda
<p>I'm new to TensorFlow, I m trying to set up my ML platform on my local machine and I need to feed some audio files as data to my neural network. for this I need TensorFlow-io.</p> <p>but when I setup TensorFlow with anaconda navigator (2.1.2) I keep running into the following error.</p> <pre><code>------------------...
<p>Following worked for me,</p> <p>make conda env with python 3.9.7</p> <p>install tf-gpu</p> <p><code>conda install tensorflow-gpu</code></p> <p>this will install tensorflow 2.6.0 with gpu</p> <p>install tensorflow_io with pip</p> <p><code>pip install tensorflow_io==0.20.0</code></p> <p>upgrade tensorflow gpu to versi...
tensorflow|anaconda
0
360,477
71,488,125
How to plot multiple daily time series, aligned at specified trigger times?
<p><strong>The Problem:</strong></p> <p>I have a dataframe <code>df</code> that looks like this:</p> <pre><code> value msg_type date 2022-03-15 08:15:10+00:00 122 None 2022-03-15 08:25:10+00:00 125 None 2022-03-15 08:30:10+00:00 126 None 2022-03...
<p>Assuming the index has already been converted <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>, create an <a href="https://pandas.pydata.org/docs/reference/api/pandas.arrays.IntervalArray.html" rel="nofollow noreferrer"><code>Interv...
python|pandas|datetime|matplotlib|seaborn
1
360,478
71,548,944
Use a plotly dropdown to select 'Time Column' and plot 'Column 2' vs 'Column 1' respecting the selected Time
<p>Good evening,</p> <p>I need to know if it is possible to use a dropdown button with plotly library and do what i mentioned in the title.</p> <p>I generated these data in order to show you how my dataframe is :</p> <pre><code>+----------+----------+-----------+ | Time | Column1 | Column2 | +----------+--------...
<p>You can try this:</p> <pre><code>from plotly import graph_objs as go import pandas as pd data = {'Time':['06:48:37', '06:48:37', '06:48:37', '06:59:37', '06:59:37', '06:59:37', '07:14:37', '07:14:37', '07:14:37'], 'Column1':[1, 2, 3, 4, 5, 6,7,8, 9], 'Column2':[1, 2,...
python|pandas|dataframe|plotly
1
360,479
71,788,354
Pandas: Rolling Mean and ignore NaN
<p>How does you tell pandas to ignore <code>NaN</code> values when calculating a mean? With min periods, pandas will return <code>NaN</code> for a number of <code>min_periods</code> when it encounters a single <code>NaN</code>.</p> <p>Example:</p> <pre><code>pd.DataFrame({ 'x': [np.nan, 0, 1, 2, 3, np.nan, 5, 6, 7, 8, ...
<p>You want to drop the <code>np.nan</code> first then rolling mean. Afterwards, reindex with the original index and forward fill values to fill the <code>np.nan</code>.</p> <pre><code>df.x.dropna().rolling(3).mean().reindex(df.index, method='pad') 0 NaN 1 NaN 2 NaN 3 1.000000 4 2.0...
python|pandas|python-polars
1
360,480
71,620,622
Is there a way to identify and create a list of all acronyms in a dataframe?
<p>I have a dataframe with a column that has many acronyms in it.</p> <p>I would like to simply (a) identify all acronyms in each cell on the next column and (b) produce a list of all unique acronyms found (not duplicates).</p> <p>I would like to simply use pyspellchecker to find any word that is misspelled and treat i...
<p>Not sure if this is exactly what you want, but maybe it helps. I suppose you have a dataframe like this (not a series):</p> <pre><code>df = Column 1 0 I worked for the NBA 1 I worked at the CIA 2 I am seeing a pt ...
python|pandas|dataframe|pyspellchecker
1
360,481
71,766,739
How to Transpose a table with different columns using python
<p>Here is the initial table as shown below.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Cust ID</th> <th>Jan Transaction Fee</th> <th>Jan Transaction Fee</th> <th>Jan Product Fee</th> <th>Jan Product Fee</th> <th>Feb Transaction Fee</th> <th>Feb Transaction Fee</th> <th>Feb Product Fee...
<p>This is a complex reshape.</p> <p><em>NB. I ignored the '.1', removed using <code>test.columns = test.columns.map(lambda s: s.strip('.1'))</code>.</em></p> <pre><code>df = (test .T.set_index(0, append=True).T .set_index([('Cust ID', '')]) .stack() .rename_axis(index=['Cust ID', 'FX'], columns='Type') .stack() ...
python|pandas
2
360,482
71,446,623
Why tanh function return different in tensorflow and pytorch?
<p>I find that <code>tensorflow</code> and <code>pytorch</code> <code>tanh</code> result is different, I want to know why did this happen? I know that the difference is very small, so is this acceptable?</p> <pre><code>import numpy as np import tensorflow as tf import torch np.random.seed(123) tf.random.set_seed(123) ...
<p>Running your code with the following line at the end:</p> <pre><code>print(np.allclose(tf_out.numpy(), pt_out.numpy())) # Returns True </code></pre> <p>You will receive <code>True</code>. I do not know exactly how tensorflow and pytorch compute the tanh oppeartion, but when working with floating points, you rarely ...
tensorflow|pytorch|activation-function
1
360,483
71,727,232
numpy.linalg.solve for Decimal in Python
<p>Is there any way how to solve equations when a matrix <strong>A</strong> and a vector <strong>b</strong> is composed of decimal.Decimals?</p> <p>My <strong>A</strong>:</p> <pre><code>array([[Decimal('-5266125828.168885444558615257'), Decimal('11312418445.69612428831109944'), Decimal('-8191751288.2627...
<p>I don't see a reason why you couldn't use the code in from <a href="https://integratedmlai.com/system-of-equations-solution/" rel="nofollow noreferrer">here</a>. You said some lines don't work with decimals, but with some small adjustment it seems to work just fine.</p> <pre><code>b = b.reshape(-1, 1) n = len(A) A_...
python|numpy|precision|equation-solving
0
360,484
71,548,657
How do you concatenate tensorflow tensors along axis 0 while preserving the shape of the other n>0 dimensions
<p>My goal is to take a list of tensors of <code>shape(1, 2, ...n)</code> and concatenate them into a tensor of <code>shape(len(list), 1, 2, ..., n)</code>.</p> <p><code>tf.concat(list, -1)</code> does not work. It returns <code>shape(1, 2, ..., n-1*n)</code>, which is understandable.</p> <p><code>tf.concat(list, 0)</c...
<p>Seems hacky, but this works</p> <pre><code> if time_features is not None: s = [len(time_features)] for i in time_features[0].shape[:]: s.append(i) f = tf.concat(time_features, 0) features = tf.reshape(f, s) </code></pre>
python|list|tensorflow|reshape|tensor
0
360,485
71,517,663
Matching columns using if statements
<p>I am trying to clean up typos in this dataset.</p> <p>Database of employee names</p> <pre><code>First Last Location John Smith Calgary John Smith Toronto Joh Smith Toronto Steph Sax Vancouver Steph Sa Vancouver Victor Jones Toronto Stacy Lee Markham ...
<p>Code works,</p> <p>I just had typos...</p> <pre><code>m1 = df10.groupby('ID1')['ID2'].transform('nunique').gt(1) m2 = df10.groupby('ID2')['ID1'].transform('nunique').gt(1) out = df10[m1|m2] </code></pre>
python|python-3.x|pandas|lambda|pandas-groupby
0
360,486
42,153,339
Recognizing specified objects via Android camera using TensorFlow
<p>I stuck with the next problem: is it possible to train TensorFlow model to "remember" any new object that is visible from Android device camera and recognize it next time it will be in the camera focus? I've tried to find tutorial and I've read many of them, but they only describe how to recognize object category wi...
<p>TensorFlow does not support on-device training at this point, only inference. So you can't easily update the model in real time.</p> <p>However, you might try treating the penultimate layer as a embedding space vector and, and then compute distance between frames to see how related they are. </p> <p>Alternatively ...
android|tensorflow
2
360,487
42,391,671
Pandas HDFStore: difference between using the select function and direct access
<p>Given a pandas HDFStore containing a <code>DataFrame</code>:</p> <pre><code>import pandas as pd import numpy.random as rd df = pd.DataFrame(rd.randn(int(1000)).reshape(500, 2), columns=list('ab')) store = pd.HDFStore('store.h5') store.append('df', df, data_columns=['a', 'b']) </code></pre> <p>I can use the <code>...
<p>If you run some benchmark, you'll find the following</p> <pre><code>%timeit store.select('df', ['a &gt; 0', 'b &gt; 0']) 100 loops, best of 3: 2.63 ms per loop %timeit store.df[(store.df.a &gt; 0) &amp; (store.df.b &gt; 0)] 100 loops, best of 3: 6.01 ms per loop </code></pre> <p>This suggest that the first <strong...
python|python-2.7|pandas|hdfstore
1
360,488
42,182,233
The gradient of an output w.r.t network weights that holds another output constant
<p>Let's assume I have a simple MLP</p> <p><a href="https://i.stack.imgur.com/DxKhw.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/DxKhw.jpg" alt="enter image description here"></a></p> <p>And I have a gradient of some loss function with respect to the output layer to get G = [0, -1] (that is, increasing t...
<p>Update: I misunderstood the question. This is the new answer.</p> <p>For this purpose, you need to update connections between the hidden layer and the second output unit only, while keep those between the hidden layer and the first output unit intact. </p> <p><strong>The first approach is to introduce two sets of ...
tensorflow|neural-network|gradient-descent
1
360,489
42,311,773
Select subset of tensor using boolean tensor in tensorflow
<p>I have two rank-2 tensors <code>arr1</code> and <code>arr2</code> of shape <code>m</code> by <code>n</code>. The tensor <code>arr2</code> is boolean; precisely one entry in each of its rows is <code>True</code>. I want to extract a new rank-1 tensor <code>arr3</code> of length <code>m</code>, where the <code>i</code...
<p>You could maybe use <code>tf.boolean_mask</code>?</p> <pre><code>from __future__ import print_function import tensorflow as tf with tf.Session() as sess: arr1 = tf.constant([[1,2], [3,4]]) arr2 = tf.constant([[False, True], [True, False]]) print(sess.run...
python|python-3.x|tensorflow
2
360,490
42,367,757
Graph using tensorboard
<p>How can see the graph, generated by TensorFlow using Tensorboard? Can anyone provide a simple example? I am very new to tensorflow. I am using python as well.</p> <p>Thanks in advance!!</p>
<p>You need to create a <a href="https://www.tensorflow.org/api_docs/python/tf/summary/FileWriter" rel="nofollow noreferrer"><code>tf.summary.FileWriter</code></a> that writes your graph to a TensorBoard log. For instance:</p> <pre><code>summary_writer = tf.summary.FileWriter('logs', graph=tf.get_default_graph()) summ...
tensorflow|tensorboard
2
360,491
42,436,833
Using scipy.ndimage.interpolation.shift(), IndexError: only integers, slices (`:`)
<p>My problem is that when I run the code below I get the following puzzling Error</p> <pre><code> IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices </code></pre> <p>which appears due to the function: scipy.ndimage.interpolation.shift(inp...
<p>So I figured out the problem. The 'data' parameter ´does not function like a typical counter in a for loop but rather is a string containing the file name. Adding a counter inside the for loop and changing the 'data' to that counter in the function will fix the problem.</p> <pre><code>for data in glob.glob(ImageFol...
python|numpy|python-3.4|shift|index-error
0
360,492
42,537,480
Python Pandas Create Cooccurence Matrix from two rows
<p>I have a Dataframe which looks like this (The columns are filled with ids for a movie and ids for an actor:</p> <pre><code> movie actor clusterid 0 0 1 2 1 0 2 2 2 1 1 2 3 1 3 2 4 2 2 1 </code></pre> <p>and i want to create a binary co-occurence matr...
<p>You can create an extra auxiliary column to indicate if the value exists and then do <code>pivot_table</code>:</p> <pre><code>(df.assign(actor = "actor" + df.actor.astype(str), indicator = 1) .pivot_table('indicator', ['clusterid', 'movie'], 'actor', fill_value = 0)) </code></pre> <p><a href="https://i.stack.imgu...
python|pandas|dataframe
1
360,493
42,141,867
Multiple plots on one graph from DataFrame
<p>I have the following Dataframe:</p> <pre><code> Food Men Women Year 0 Apples as fruit 89.18 90.42 1994 1 Berries 84.21 81.73 1994 2 Grapes 88.79 88.13 1994 3 Melons 80.74 84.96 1994 4 Oranges, Total 85.66 89.77 1994...
<p>You would need to create the figure outside the loop. It is then best to supply a matplotlib axes to the Dataframe plot using <code>ax</code> keyword argument.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt year=[1994,1994,1994,2000,2000,2000,2006,2006,2006] fr = ["Apple", "Banana", "Cherry"]*3...
python-3.x|pandas|numpy|matplotlib
2
360,494
42,529,454
Using map() for columns in a pandas dataframe
<p>I have some columns in my dataframe for which I just want to keep the date part and remove the time part. I have made a list of these columns:</p> <pre><code>list_of_cols_to_change = ['col1','col2','col3','col4'] </code></pre> <p>I have written a function for doing this. It takes a list of columns and applies dt....
<p>The simpliest is use <code>lambda</code> function with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="noreferrer"><code>apply</code></a>:</p> <pre><code>df = pd.DataFrame({'col1':pd.date_range('2015-01-02 15:00:07', periods=3), 'col2':pd.date_rang...
python|list|pandas
34
360,495
42,546,365
How to restore variables of a particular scope from a saved checkpoint in tensorflow?
<pre><code>import tensorflow as tf saver = tf.train.Saver() saver.restore(...) </code></pre> <p>But saver.restore only has options to restore the entire graph. I would like to restore only those variables that are in a specific scope. </p> <p>Thanks in advance!</p>
<p>Assume you have Google's model of InceptionNet in scope <code>InceptionV1</code> and you want to load it except for the last layer in scope <code>InceptionRetrained</code> you want to retrain.</p> <p>Assuming you already started retraining the last layer and you created <em>last_layer.ckpt</em> file by <code>saver2...
tensorflow|neural-network|deep-learning
4
360,496
42,386,463
Keras jupyter notebook outputs blocks during training
<p>When using Keras in a Jupyter Notebook environment, during training my Notebook crashes. While running the fit function, apart from the normal training progress, a lot of squares appear. In fact, there are so many squares the browser crashes...</p> <p>When running the same code in a normal terminal these squares do ...
<p>see this <a href="https://github.com/fchollet/keras/issues/4676" rel="noreferrer">issue on github</a></p> <p>in short 4 options :</p> <ul> <li>Use command lines instead of ipython notebooks</li> <li>Use <code>verbose=0</code> or <code>verbose=2</code> in <code>fit()</code>, the first will not output anything, the ...
python|tensorflow|keras|jupyter-notebook
8
360,497
42,398,672
PyCharm remote interpreter and Tensorflow -> can not import Cudart.so
<p>I'm using PyCharm for remote debugging, client Win10, server Ubuntu 16. On the Ubuntu machine I have Cuda 8.0 correctly installed, along with python 2.7 and tensorflow 1.0.0. Tensorflow works perfectly from the server (ssh + invoking python, import tensorflow etc..).</p> <p>In PyCharm I set up a remote debugger to ...
<p>Solution is to add the correct path to the Pycharm environment panel:</p> <pre><code>LD_LIBRARY_PATH='/usr/local/cuda/lib64' </code></pre> <p>or the one that suits your configuration.</p>
python|tensorflow|pycharm|remote-debugging
6
360,498
42,175,232
Cost at all epochs are zero, even before training
<p>I wrote simple multi-layer perceptron program using TensorFlow. This program was made to predict following number after 5 sequence. (e.g. 1 4 9 14 19 [24]) Yes, it is very simple.</p> <p>But I wander to death during at least 4 hours. Because cost at all epochs are zero, even if what I do. Surprisingly, I ensured th...
<p>The problem is you are using loss function for classification (softmax is generally used for classification) while your network could produce an arbitrary single real number, so it's regression, not classification. Use proper cost (say, mean squared error) and your network will start to converge. </p> <p>In this pa...
tensorflow|neural-network|deep-learning
5
360,499
42,138,966
Pandas read csv ignore commas, one column per line
<p>I have a txt file that has the following format</p> <pre><code>a 1 blah b 2 blah,inc c 3 foo,inc </code></pre> <p>i want to read it into a <code>df</code> using <code>read_csv()</code> but the commas are giving me an error and I don't want to skip with <code>error_bad_lines=False</code>.</p> <p>How do I read it i...
<p>I think you need change default separator <code>,</code> to <code>s\+</code> for white-space sep:</p> <pre><code>import pandas as pd from pandas.compat import StringIO temp=u""" a 1 blah b 2 blah,inc c 3 foo,inc""" #after testing replace 'StringIO(temp)' to 'filename.csv' df = pd.read_csv(StringIO(temp), sep='\s+'...
python|csv|pandas
3