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
353,400
60,523,562
Convert a column which contains pandas Series to features
<p>My data frame is like below:</p> <pre><code> a 0 [8, 10] 1 [12, 7, 9] </code></pre> <p>As you can see column a contains a list. Number inside that list has meaning in our domain and i want to use them as feature. My expected output is like below:</p> <pre><code> Tag_7 Tag_8 Tag_9 Tag_10 Tag_...
<p>Give <code>scikit-learn</code> a try to see if it helps</p> <pre><code>from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() cols = np.unique(np.concatenate(df.a)) df_final = pd.DataFrame(mlb.fit_transform(df.a), columns=cols).add_prefix('T_') Out[213]: T_7 T_8 T_9 T_10 T_12 0 ...
python|pandas|dataframe|series
2
353,401
60,354,986
Using python (via requests or otherwise) to retrieve an html table selected by drop down
<p>I'm trying to pull historical weather data from the following site: <a href="https://www.timeanddate.com/weather/usa/boston/historic" rel="nofollow noreferrer">https://www.timeanddate.com/weather/usa/boston/historic</a></p> <p>There are two dropdown menus that I need to select in order to load the table for any par...
<p>Data of this page load through <code>JSON</code> dynamically. You can find this <code>AJAX</code> request in network tab when you change date. But the problem with <code>JSON</code> is that it is not into the proper format so when you use <code>response.json()</code> it gives you an error. So you have to convert you...
python|pandas|python-requests
1
353,402
60,649,975
how to prevent automatic shift in decimal numbers in numpy
<p>Here is my code:</p> <pre><code>y = np.array([-3.44 , 1.16 , -0.81]) y = np.exp(y) print(y) </code></pre> <p>for this block, I got the below result</p> <pre><code>[0.03206469 3.18993328 0.44485807] </code></pre> <p><strong>However, when I add <code>3.91</code> to the list, the result changed</strong></p> <pre>...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html" rel="nofollow noreferrer"><code>np.set_printoptions</code></a>:</p> <pre><code>&gt;&gt;&gt; x = np.array([-3.44 , 1.16 , -0.81 , 3.91]) &gt;&gt;&gt; x = np.exp(x) &gt;&gt;&gt; print(x) [3.20646853e-02 3.18993328e+...
python|numpy|scientific-notation
2
353,403
60,652,062
How to remove right most None from pandas.tolist()?
<p>Suppose I import <code>xlsx</code> file to list:</p> <p><a href="https://i.stack.imgur.com/pAhfr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pAhfr.png" alt="enter image description here"></a></p> <pre><code>pd.read_excel(open('1.xlsx','rb'), index_col=None, header=None).values.tolist() [[na...
<h3>NumPy based solution</h3> <pre><code># reverse the columns a_rev = a[:,::-1] # indices of all values after first nan to True m = np.cumsum(~np.isnan(a_rev), 1) &gt;= 1 # indices where to split s = np.cumsum(m.sum(1)) # reverse again ix = m[:,::-1] # split to obtain n arrays res = np.split(a[ix], s)[:-1] print(re...
python|pandas|list|numpy
1
353,404
60,358,808
Merging images into z-stack and making max-projection / in Python
<p>It would be great if someone could me help me to write code in Python (which I am gradually learning) to solve the problem I am facing. </p> <p>We are using high-throughput microscope, and I am imaging 96 well plates - a z-stacks of various locations in multiple wells. When I extract images, their name encodes row ...
<p>I am not sure I fully understand your question.</p> <p><a href="https://stackoverflow.com/questions/47248065/creating-a-tiff-stack-from-individual-tiffs-in-python">This answer</a> explains how to merge single TIFF files into stacks.</p> <p>Once you have your stack, maybe the Python module <a href="https://pypi.org/p...
python|pandas|image|numpy|tiff
0
353,405
60,425,609
how visualize multi channel of feature from PyTorch?
<p>I'm almost newbie at PyTorch</p> <p>One of my output size from conv is [1, 25, 8, 32] (25=channel, 8=height, 32=width)</p> <p>I can use squeeze and make it to [25, 8, 32].</p> <p>But I'm confused with 25 channel.</p> <p>When I want to visualize sum of 25 channel and make to one GRAYorRGB image(1or3x8x32),How can...
<p>It is difficult to visualize images with more than 3 channels and it is unclear what a feature vector in 25 dimensional space actually looks like.</p> <p>The most straight forward approach would be to visualize the 8x32 feature maps you have as <em>separate</em> 25 gray scale images of size 8x32. Each image will sh...
pytorch|visualize
2
353,406
60,473,458
Combining sets of columns using pandas
<p>I have the following data frame structure:</p> <pre><code> SC0 Shape S1 S2 S3 C1 C2 C3 D1 D2 D3 2 1 Circle NaN NaN NaN 1 1 1 NaN NaN NaN 3 13 Square 2 1 2 NaN NaN NaN NaN NaN NaN 4 13 Diamond NaN NaN NaN NaN NaN NaN 2 1 2 5 16 Diamond NaN NaN NaN NaN NaN NaN 2 2 2 6 ...
<p>IIUC you have an equal amount of columns for each category, and you want to compress this into numeric columns which are shape agnostic. If so this will work:</p> <pre><code>dfs = [] for var in ['S', 'D', 'C']: # filter columns with a regex res = df[df.iloc[:, 2:].filter(regex= var + '\d{1,2}').col...
python|pandas
1
353,407
60,406,856
merge same name columns during json conversion in pandas
<p>I have dataframe like this:</p> <pre><code> question option option 1 &quot;1+2 ?&quot; 1 3 </code></pre> <p>And I want to convert it to json</p> <pre class="lang-json prettyprint-override"><code>{&quot;question&quot;:&quot;1+3 ?&quot;, &quot;option&quot;: [1,3]} </code></pre> <p>I know data can be conv...
<p>Create a new column with the the values in your <code>option</code> columns and export using <code>to_dict</code> with <code>orient="records"</code>:</p> <pre><code>print (df.assign(opt=df.filter(like="option").values.tolist()) .loc[:, ["question","opt"]].to_dict(orient="records")) # [{'question': '"1+2 ?...
python|pandas
1
353,408
60,417,284
Pandas read_csv() parse multiple datetime formats
<p>I would like to read multiple data files that have different DateTime formats. But How can I parse these formats together in one go?</p> <pre><code>dateparse_1 = lambda x: pd.datetime.strptime(x, "%d/%m/%Y %H:%M:%S.%f") dateparse_2 = lambda x: pd.datetime.strptime(x, "%Y-%m-%d %H:%M:%S.%f") dateparse_3 = lambda x:...
<p>You can combine <code>dateparse_{1,2,3}</code> by trying them until one succeeds. For example,</p> <pre class="lang-py prettyprint-override"><code>def combine_date_parsers(date_parsers): def combined_date_parser(value): for date_parser in date_parsers: try: return date_parse...
python|pandas|datetime|parsing
2
353,409
60,413,243
fill missing values in dataframe only when they are between two same values
<p>I have a patient dataset with missing values. These missing values occur between two important events. The dataset is as below</p> <p>I only need to fill up the missing rows if the upper event and the lower event matches. if the upper event is "No response" and the lower event is "No response", I need to fill up th...
<p>Hard to tell without dataset, but I think this can help you -- </p> <pre><code>df.replace([np.inf, -np.inf], np.nan).dropna(subset=["col1", "col2"], how="all") #This will replace values in first arg with values in second arg, and can be lists .. #can also be ran on individual columns either with this or just call...
python|pandas
0
353,410
60,721,581
Internal sorting with values correction in Python & PANDAS
<p>I have below DF:</p> <p>DF is sorted by VEHICLE_ID_FW and secondly by TRANSACTION_DATE_FW (ascending=False).</p> <p>Task:</p> <p>I need correct values in ODOMETER_FW column. (There are mileages of vehicles). For <strong>single VEHICLE_ID_FW</strong> I need check:</p> <ol> <li><p>If some values in ODOMETER_FW <st...
<p>Data: Current DF:</p> <pre><code>VEHICLE_ID_FW ODOMETER_FW TRANSACTION_DATE_FW DC19YTZ 11833 2020-02-08 DC19YTZ 0 2020-02-05 DC19YUA 14878 2020-02-06 DC19YUA 144754 2020-02-04 DC19YUB 10952 2020-02-07 DC19YUB 1007 2020-02-05 D...
python|pandas
0
353,411
60,384,288
pyinstaller ModuleNotFoundError
<p>I have built a python script using tensorflow and I am now trying to convert it to an .exe file, but have ran into a problem. After using pyinstaller and running the program from the command prompt I get the following error: </p> <pre><code>File "site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 25, ...
<p>EDIT: The latest versions of PyInstaller (4.0+) now include support for <code>tensorflow</code> out of the box.</p> <p>Create a directory structure like this:</p> <pre><code>- main.py # Your code goes here - don't bother actually naming you file this - hooks - hook-tensorflow.py </code></pre> <p>Copy the followin...
python|tensorflow|pyinstaller
18
353,412
60,525,627
Getting the means and sum of columns of a dataframe on the basis of randomly selected bins
<p>I have a dataframe like below.</p> <p>data</p> <pre><code>Index ID AA BB CC BIN 0 Z1 10 11 12 1 1 Z1 0 12 13 1 2 Z1 20 13 14 2 3 Z1 34 14 15 3 4 Z1 54 52 16 3 5 Z1 67 53 17 3 6 Z7 45 54 18 1 7 Z7 34 55 19 2 8 Z7 45 56 5...
<p>So here's your pandas dataframe: </p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame( ... [ ... ['Z1', 10, 11, 12, 1], ... ['Z1', 0, 12, 13, 1], ... ['Z1', 20, 13, 14, 2], ... ['Z1', 34, 14, 15, 3], ... ['Z1', 54, 52, 16, 3], ... ['Z1', 67, 53,...
python|pandas|dataframe
1
353,413
60,397,616
Year wrongly read is System---YYYY is getting read as YY
<p>I have a txt file which is tab separated. Few of the columns have date data in the format of</p> <blockquote> <p>"Dec-2011", "Jan-1994"</p> </blockquote> <p>etc the date ranges from "Jan-1944 to Dec-2015"</p> <p>Problem is the in original data the date format is "Jan-1994" or the year is in YYYY format but when...
<p>Are you sure that the data is being read incorrectly? You can check it by writing the df to new file checking the new file.</p> <pre><code>import pandas as pd Raw_Data=pd.read_csv("XYZCorp_LendingData.txt", encoding="Latin-1", sep ='\t', low_memory=False) Raw_Data.to_csv('Date_check.csv') </code></pre> <p>My gues...
python-3.x|pandas|python-datetime
0
353,414
60,558,960
How to calculate Cosine similarity and Euclidean distance between two tensors in TF2.0?
<p>I have two tensors (OQ, OA) with shapes as below at the end of last layers in my model.</p> <p>OQ shape: (1, 600)</p> <p>OA shape: (1, 600)</p> <p>These tensors are of type 'tensorflow.python.framework.ops.Tensor'</p> <ol> <li>How can we calculate cosine similarity and Euclidean distance for these tensors in Ten...
<p>You can calculate Euclidean distance and cosine similarity in tensorflow 2.X as below. The returned output will also be a tensor.</p> <pre><code>import tensorflow as tf # It should be tf 2.0 or greater print("Tensorflow Version:",tf.__version__) #Create Tensors x1 = tf.constant([1.0, 112332.0, 89889.0], shape=(1,...
python|tensorflow|euclidean-distance|cosine-similarity
4
353,415
60,426,599
How to read and print rows with common data in CSV using pandas
<p>I am using below code to read the particular rows from csv using python and pandas. But I am stuck while I want to print common data, text rows. I want to print the row containing order code as and 00157B. PFA Screenshot of scenario and attached code I am using.</p> <pre><code>rows = pd.read_csv('SampData.csv', s...
<p>You could try one of these -</p> <p>In case you want to do a compare by the whole term in the <code>OrderCode</code> column ( for e.g. 00157B ) :</p> <pre><code> filtered = rows[rows['OrderCode'] == '00157B'].reset_index(drop=True) filtered.to_csv('output.csv', index=False) </code></pre> <p>In case you want to d...
python|pandas|csv|data-science|rows
0
353,416
60,655,401
How Groupby value counts pandas dataframe?
<p>this is my dataframe</p> <pre><code>df = pd.DataFrame([ ('a', 0, 0), ('b', 1, 1), ('c', 1, 0), ('d', 2, 1), ('e', 2, 1) ], columns=['name', 'cluster', 'is_selected']) </code></pre> <p>i want to count each letter selected in each cluster and group by cluster. i tried this : <code>df.groupby('clu...
<p>Based on your explanation you want to count the letters that are selected (value of 1 in <code>is_selected</code>) grouped by clusters.</p> <p>if that's what you're looking for then this should help:</p> <pre><code>df[df.is_selected == 1].groupby(['cluster'])['name'].count().reset_index(name='count_selected') </co...
python|pandas|dataframe
1
353,417
60,646,502
Replacing values inplace in a pandas dataframe work not working with .replace()
<p>I have a dataset with various gridstations and their connections with other grid stations and I need to map out transmission lines from this data. It looks something like this (there are about a 100 or so lines in the original dataframe):</p> <pre><code>&gt;df Name Latitude Longitude Link 1 Link 2 Li...
<p>Here is one solution. </p> <p><strong>Step 1 -</strong> First step is to sort the values of 'Name' and 'Link 1' along the column axis.</p> <pre><code>datax[['Name', 'Link 1']].apply(sorted, axis=1) </code></pre> <p>This gives you a list like this</p> <pre><code>0 [A, B] 1 [A, B] 2 [B, C] </code></pre> ...
python|python-3.x|pandas|dataframe
2
353,418
60,416,577
Creating 3D Array in Python
<p>I am trying to form a 3D array in Python by populating it with 2D arrays. N is a number than varies depending on the file being read. The matrix is forming as 3D but only appears to have 1 'layer' to it when I am expecting it to have N layers. It appears that the N number of 'layers' is not being passed into the for...
<p>You don't say exactly what shape you are expecting. The code below will return a 3D array of shape <code>(3, 3, N)</code></p> <pre><code>ones_vec = np.array([1] * N) arr = np.array([[a, b, ones_vec], [d, e, ones_vec], [g, h, h]]) print(arr.shape) # (3, 3, N) </code></pre>
python|arrays|numpy|matrix
-1
353,419
60,746,034
"Data source name too long" error with mssql+pyodbc in SQLAlchemy
<p>I am trying to upload a dataframe to a database on Azure SQL Server Database using SQLAlchemy and pyobdc. I have established connection but when uploading I get an error that says</p> <p><strong>(pyodbc.Error) ('IM010', '[IM010] [Microsoft][ODBC Driver Manager] Data source name too long (0) (SQLDriverConnect)')</st...
<p>Three issues here:</p> <ol> <li>If a username or password might contain an <code>@</code> character then it needs to be escaped in the connection URL.</li> <li>For the <code>mssql+pyodbc</code> dialect, the database name must be included in the URL in order for SQLAlchemy to recognize a &quot;hostname&quot; connecti...
pandas|sqlalchemy|azure-sql-database|etl|pyodbc
4
353,420
60,642,412
Do I have to cut y (prediction) column from Pandas dataframe with Scikit-learn?
<p>I've split my Pandas DataFrame into <code>train_X</code> and <code>train_y</code> parts, where <code>train_X</code> has all N columns, and <code>train_y</code> has only N-th column, depicting the variable that I want to predict. Currently I'm doing:</p> <pre><code>train_X.drop("N-th column name", axis=1, inplace=Tr...
<p>You must declare <code>X</code> and <code>y</code> explicitly when calling <code>fit</code> on a <code>sklearn</code> estimator. Generally by the time you're ready to split your data into training and testing sets, <code>X</code> should include model features only, so should not include your target <code>y</code>.<b...
python|pandas|scikit-learn
3
353,421
60,704,061
How can I convert an excel function that is shown below into a python pandas code?
<p>I have a function in excel like this</p> <pre><code>=IF(B17="","",MIN(MAX(CEILING((B17-MIN(B$17:B$46))/((MAX(B$17:B$46)-MIN(B$17:B$46))/10),1),1),10)) </code></pre> <p>input:</p> <pre><code>Column1 output 512.96 10 307.41 3 413.76 7 323.65 4 376.84 5 368.79 5 367.77 5 345.65 4 </code></pre> <p>It can be ...
<p>Consider passing in a Pandas Series as parameter in order to return a same length Series as the Excel formula runs by individual cells to return results of same length results. Then either call the Python function for single column assignment or with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/ap...
python|excel|pandas|numpy
1
353,422
60,646,050
OpenCV: find small dark(black) dots inside a circle
<p>I am trying to detect the circles that are black dots or have black dots in them(the ones that I pointed with arrow in the following image). <a href="https://i.stack.imgur.com/rMDzj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rMDzj.png" alt="enter image description here"></a></p> <p>My curre...
<p>This is the approach I took and can be used for inspiration. I'm not sure it catches all the cases of "black dots" but you can be the judge on that. I just added a threshold to the loaded image and then reused the code you provided.</p> <pre><code>import cv2 import numpy as np img = cv2.imread('blackdots.jpg') gra...
python|algorithm|numpy|opencv|image-processing
1
353,423
60,608,134
How to plot a fitted curve over a categorical boxplot in PyPlot? Why does the result differ from the same plot in Google Sheets?
<p>I have the following csv data:</p> <pre><code>Dataset Size,MAPE,MAE,STD MAPE,STD MAE 35000,0.0715392337,23.38300578,0.9078698348,2.80407539 26250,0.06893431034,22.34732326,0.9833948236,1.926517044 17500,0.0756695622,26.0900766,0.6055443674,8.842862631 8750,0.07176532526,23.02646184,0.8284005282,2.190506033 4200,0.0...
<p>Played around with some functions, and I think I can say with some degree of certainty that the Google Sheets exponential function has a form close to this:</p> <pre><code>def sheetey_exponential_function(x, a, b, c): return a * b ** (x + c) </code></pre> <p><a href="https://i.stack.imgur.com/0KR5M.png" rel="n...
python|pandas|matplotlib|google-sheets
1
353,424
60,338,228
How can I improve the performance of my script?
<p>I have a "seed" GeoDataFrame (GDF)(RED) which contains a 0.5 arc minutes global grid ((180*2)*(360*2) = 259200). Each cell contains an absolute population estimate. In addition, I have a "leech" GDF (GREEN) with roughly 8250 adjoining non-regular shapes of various sizes (watersheds).</p> <p>I wrote a script to allo...
<h3>Introduction</h3> <p>It might be worthy to profile your code in details to get precise insights of what is your bottleneck. </p> <p>Bellow some advises to already improve your script performance:</p> <ul> <li>Avoid <code>list.append(1)</code> to count occurrences, use <a href="https://docs.python.org/3.7/library...
python|pandas|performance|geopandas
6
353,425
72,562,173
Find most recent date from different dataframe
<p>I have a data frame (df1) and want to get a previous most recent survey_date for the ID and associated score from another data frame (df2)</p> <pre><code> df1 = pd.DataFrame({'ID' : [1,2], 'start_date':['2018-08-04','2018-08-09']}) df1 df2 = pd.DataFrame({'ID' : [1,1,2,2], 'su...
<p>You can try <code>merge_asof</code></p> <pre><code>#df1.start_date = pd.to_datetime(df1.start_date) #df2.survey_date = pd.to_datetime(df2.survey_date) out = pd.merge_asof(df1, df2, by = 'ID', left_on = 'start_date', right_on = 'survey_date') Out[366]: ID start_date survey_date score 0 1 2018-08-04 2018-08-...
pandas|date
2
353,426
72,555,014
How to sume datetime.time values in pandas dataframe?
<p>I have dataframe like this:</p> <pre><code>A B x 00:11:12 y 00:10:10 z 00:00:15 g 00:01:32 </code></pre> <p>I would like to be able to simply <code>sum</code> column <code>B</code>. However <code>df['B'].sum()</code> yields the following error:</p> <pre><code>TypeError: unsupported operand type(s) ...
<p>You are close, need casting times to strings:</p> <pre><code>out = pd.to_timedelta(df[&quot;B&quot;].astype(str)).sum() print (out) 0 days 00:23:09 </code></pre> <p>If need extract times (days are not important):</p> <pre><code>time = (datetime.datetime.min + out).time() print (time) 00:23:09 </code></pre> <hr /> <p...
python|pandas
1
353,427
72,690,249
Pandas DateTime - System DownTime
<p>May I know any better way to get the system downtime period.</p> <p>The system will detect a value and transmit its reading for every 20 minutes.</p> <p>This code is used to identify the similar data of 0.00 that measured no data. However, I would like to find out how long its had lost data in this consecutive times...
<p>If your data are truly this small, why not just iterate over the rows while recording appropriate values?</p> <pre><code>down_flag = False down_start = None down_stop = None for i, row in df.iterrows(): if row['Water Quality Sensor'] == 0 and down_flag == False: down_flag = True down_start = row...
python|pandas|dataframe|datetime
0
353,428
72,651,052
How do I convert a column to Pandas Timestamps?
<p>I have a column in my DataFrame with values like <code>'2022-06-03T00:00:00.000Z'</code> and I want to convert these (in place) to <code>pd.Timestamp</code>. I see many answers he on how to convert to <code>np.datetime64</code> and on how do convert arbitrary columns of DataFrames, but can't figure out how to apply ...
<p>Use from pd.to_datetime method I think this solve your problem Just you need to active utc argument in your method</p> <pre class="lang-py prettyprint-override"><code> import pandas as pd lst = {'a':['Geeks', 'For'],'b':['2022-06-03T00:00:00.000Z','2024-03-03T00:00:00.000Z']} df = pd.DataFrame(lst) df['b']=pd.t...
pandas|dataframe|timestamp|type-conversion
1
353,429
72,730,906
How to unify multiple columns in pandas dataframe into a multiindex?
<p>I have a dataframe like this:</p> <pre><code>pd.DataFrame(data={&quot;a&quot;: [1,2], &quot;b&quot;: [3,4], &quot;c&quot;: [5,6]}, index=[0,1]) </code></pre> <p>In tabular form:</p> <pre><code> a b c 0 1 3 5 1 2 4 6 </code></pre> <p>I want to transform it to a dataframe like this:</p> <pre><code>pd.DataFra...
<p>First create a new multiindex</p> <pre><code>df.columns = pd.MultiIndex.from_product([df.columns.tolist(), ['foo']]) print(df) a b c foo foo foo 0 1 3 5 1 2 4 6 </code></pre> <p>then use <code>.stack</code> with <code>.swaplevel()</code></p> <pre><code>df.stack(0).swaplevel(0,1) </code></pre>...
python|pandas|dataframe|multi-index
2
353,430
72,681,779
How to replace pandas DataFrame with the values of another DataFrame?
<p>I have 2 DataFrames (<code>signal_df</code>, and <code>price_df</code>) that can be generated using the following code.</p> <pre><code>import pandas as pd import numpy as np signal_df = pd.DataFrame({ 'long':[ True ,True, np.nan, True, np.nan ], 'short':[ np.nan, np.nan, True, np.nan, Tr...
<p>You can try <code>mask</code> the True value in <code>long</code> column of <code>signal_df</code></p> <pre class="lang-py prettyprint-override"><code>out = (signal_df['long'].mask(signal_df['long'].eq(True), price_df.loc[signal_df.index, 'close_price']) .to_frame()) </code></pre...
python|pandas|dataframe
0
353,431
72,715,393
Converting and manipulation tf data image dataset straight from a folder
<p>I am trying to load a dataset from a local folder and use it as a tf data dataset. The folder structure is :</p> <pre><code> ../dataset/ class_0/ class_1/ </code></pre> <p>where class 0 sub-fodler contains all images with class 0 and class 1 all with class 1.<br /> To achieve this my code is :</p> <pre...
<p>The problem seems to be with floating point numbers for Pillow</p> <p>In your converting function, you have <code>img = Image.fromarray(img, 'RGB')</code>.</p> <p>Changing this to <code>img = Image.fromarray(img.astype('uint8'), 'RGB')</code> should solve this issue.</p>
image|tensorflow|tensorflow2.0|tensorflow-datasets
0
353,432
72,780,437
Difference between mean mode imputation and bfill and ffill imputation
<p>My dataset has 5% missing value. It is a categorical dataset , only two attributes are numerical. If I impute missing value with mean and mode method I got accuracy 0.781, recall 0.500 and AUROC 0.756 whereas if I impute missing value with bfill and ffill I got accuracy 0. 785, recall 0.586, AUROC 0.780.</p> <p>I ca...
<p><em>Global</em> imputation methods like mean/mode don't take order (like backward/forward fill) in rows or similarity between rows (like nearest neighbor based imputation) into account. Depending on your data these <em>local</em> methods can be better by quite a bit.</p>
pandas|dataframe|weka|missing-data|categorical-data
0
353,433
72,547,834
why do I receive these errors "WARNING: Ignoring invalid distribution -yproj " while installing any python module in cmd
<p>WARNING: Ignoring invalid distribution -yproj (c:\users\space_junk\appdata\local\programs\python\python310\lib\site-packages) WARNING: Ignoring invalid distribution -yproj (c:\users\space_junk\appdata\local\programs\python\python310\lib\site-packages) WARNING: Ignoring invalid distribution -yproj (c:\users\space_jun...
<p>I was getting a similar message that turned out be caused by a previous failed pip upgrade. I had attempted to upgrade pip from a user account that didn't have the proper rights. There was a temp directory left behind in site-packages that began with ~ip which was causing pip to complain every time it ran. I remo...
python|geopandas|torch|fiona|osgeo
2
353,434
72,547,603
I need to loop over a big JSON - Pandas/Python
<p>I have a JSON file that looks like this:</p> <pre><code>[ { &quot;id&quot;: 121, &quot;name&quot;: &quot;Lebanon&quot;, &quot;iso3&quot;: &quot;LBN&quot;, &quot;iso2&quot;: &quot;LB&quot;, &quot;numeric_code&quot;: &quot;422&quot;, &quot;phon...
<p>Use:</p> <pre><code>yourJsonObj = json.loads(&quot;your json string&quot;) for key, val in yourJsonObj Access/Manipulate data </code></pre> <p>Here are more examples: <a href="https://www.programiz.com/python-programming/json" rel="nofollow noreferrer">JSON Read, write, parse</a> Good luck!</p>
python|json|python-3.x|pandas|dataframe
0
353,435
72,768,404
Problem loading Pytorch Tacotron2 model with only the pth file
<p>I've trained a Tacotron2 model, using Mozilla TTS, on a custom dataset. The trainer outputs a pth file and a config.json file. I have difficulty loading the trained model into PyTorch.</p> <pre><code>from torchaudio.models.tacotron2 import Tacotron2 tacotron2 =Tacotron2() tacotron2.load_state_dict(torch.load('models...
<p>According to the error message, what the <code>load_state_dict()</code> command was expecting was apparently a dictionary with keys being named network parameters like <em>&quot;decoder.attention_rnn.bias_hh&quot;</em> etc, i.e. the trained parameters and a way to identify them. It seems however that the <code>pth</...
python|deep-learning|pytorch|text-to-speech
0
353,436
72,794,398
np.random.choice conflict with multiprocessing? multiprocessing inside for loop?
<p>I want to use <strong>np.random.choice</strong> inside a <strong>multiprocessing pool</strong>, but I get the <strong>IndexError: list index out of range</strong>. I don't get any error when I use the choice function inside a for loop (in series then, not parallel). Any ideas on how to overcome this? This is just a ...
<p>Child processes do not share the memory space of parent processes. Since you populate <code>X</code> inside the <code>if __name__ ...</code> clause, the child processes only have access to the X defined at the top module, i.e <code>X = []</code></p> <p>A quick solution would be to shift the line <code>X = np.arange(...
python-3.x|multiprocessing|numpy-random
1
353,437
72,708,481
Python: Divide row in one DataFrame by all rows in another DataFrame
<p>I have two DataFrames as follows:</p> <pre><code>df1: A B C D index 0 10000 20000 30000 40000 df2: time type A B C D index 0 5/2020 unit 1000 4000 900 200 1 6/2020 unit 7000 2000 600 4000 </code></pre> <p>I want to divide <code>df1.iloc[0]...
<p>Let us do</p> <pre><code>df2.update(df2.loc[:,df1.columns].rdiv(df1.iloc[0])) df2 Out[861]: time type A B C D 0 5/2020 unit 10.000000 5.0 33.333333 200.0 1 6/2020 unit 1.428571 10.0 50.000000 10.0 </code></pre>
python|pandas|dataframe|division
1
353,438
72,743,981
ValueError: y contains previously unseen labels: 'some label'
<p>Whenever i am trying to execute the following code it is showing ValueError: y contains previously unseen labels: 'some_label'</p> <pre><code>X_test['Gender'] = le.transform(X_test['Gender']) X_test['Age'] = le.transform(X_test['Age']) X_test['City_Category'] = le.transform(X_test['City_Category']) X_test['Stay_In_C...
<p>I am not really sure what is your whole code is but I think the problem is your train data is different from your test data, meaning when you are using &quot;transform&quot; there is some data point in test that was not available while you fit your transformer on &quot;Train&quot; data.</p> <p>Lets see it with an ex...
python|pandas|encoding|data-analysis|label-encoding
1
353,439
72,691,914
Group by the data based on the two column (id and date) and then build the rows with the values in data frame
<p>I have a data frame with multiple id in column id. For each day, I have 5 time steps. (6:00, 6:15, 6:30, 6:45, 7:00) However, some days does not have 5. And I want to fill the missing value as Nan.. Let see the following example,</p> <pre><code>import pandas as pd df = pd.DataFrame() df['id'] = [1, 1, 1, 1, 1, 2, ...
<p>create columns based on the time, I just added one line and changed the pivot to include time, in your code.</p> <p>you were grouping by 'date', that has both date and time and hence you end up with 7 columns.</p> <pre><code>df[&quot;dates&quot;] = pd.to_datetime(df[&quot;date&quot;]).dt.date df['time'] = pd.to_date...
python|pandas|dataframe
1
353,440
72,673,100
How to get position for records grouped by one column sorted and sorted by another pandas DataFrame
<p>I have a very large DataFrame with ~100M rows that looks like this:</p> <pre><code> query score1 score2 key 0 query0 97.149704 1.317513 key1 1 query1 86.344880 1.337784 key2 2 query2 85.192480 1.312714 key3 3 query1 86.240326 1.317513 key4 4 query2 85.192480 1.312714 key5 ... </code><...
<p>Use <code>groupby</code> and <code>rank</code>:</p> <pre><code>df[['pos1', 'pos2']] = (df.groupby('query')[['score1', 'score2']] .rank(method='max', ascending=False) .sub(1).astype(int)) print(df) # Output query score1 score2 key pos1 pos2 0 query0...
python|python-3.x|pandas|dataframe|parallel-processing
0
353,441
72,830,231
How to merge cell in the data frame?
<p>Currently I have below dataframe: <a href="https://i.stack.imgur.com/9Jl1g.png" rel="nofollow noreferrer">enter image description here</a></p> <p>And need to convert to below: <a href="https://i.stack.imgur.com/1PVxX.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>If both columns are strings (if it's integers you have to first convert it to string using df[&quot;A&quot;].astype(str) and df[&quot;B&quot;].astype(str)), you can concatenate them directly:</p> <p><code>df[&quot;A&quot;] = df[&quot;A&quot;] + df[&quot;B&quot;]</code></p>
python|pandas
1
353,442
72,673,046
Remove 0 from a pandas series containing lists
<p>I have a pandas DataFrame with a series that stores data as lists.</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'id': [0, 1], 'vl': [ [1, 0, 2], [0, 1, 5] ] }) </code></pre> <p>For lists containing <code>0</code>, I'd like to remove <code>0</code>s fr...
<p>Explode your column then filter your values:</p> <pre><code>df['vl'] = df['vl'].explode().loc[lambda x: x != 0].groupby(level=0).agg(list) print(df) # Output id vl 0 0 [1, 2] 1 1 [1, 5] </code></pre> <p>Alternative:</p> <pre><code>df['vl'] = df['vl'].apply(lambda x: [i for i in x if i != 0]) print(df)...
python|pandas
3
353,443
72,575,324
I need to groubpy/aggregate with adding a comma
<p>I want to aggregate in this data frame columns.</p> <pre><code>data = {'one':['one', 'five', 'one', 'one'], 'two':['one', 'five', 'one', 'one']} df = pd.DataFrame(data) df </code></pre> <p>Using the following code:</p> <pre><code>new_df = df.groupby('one').agg(names = ('two', 'sum')) </code></pre> <p>The out...
<p>You just need to add <code>','.join</code> instead of <code>sum</code>.</p> <pre><code> new_df = df.groupby('one').agg(names = ('two', ', '.join)) </code></pre> <p>Output:</p> <pre><code> names one five five one one, one, one </code></pre>
python|python-3.x|pandas|dataframe
0
353,444
72,757,789
Create Column with Lap Times Given Total Time Elapsed
<p>I have four different people, each run laps and I need to calculate lap time for each lap for each person. I am given the total elapsed time starting from the very beginning at the end of each lap. What kind of PySpark/SQL/Pandas syntax could I use to calculate lap times efficiently?</p> <p>Example:</p> <p>Each row ...
<p>Window functions could do it.</p> <ul> <li><p>PySpark:</p> <pre class="lang-py prettyprint-override"><code>from pyspark.sql import functions as F, Window as W df = spark.createDataFrame( [(1, 200), (1, 300), (1, 550), (2, 100), (2, 150), (2, 250), (3, 150), (3, 500), (4, 100), (4, 300), (4, 350), (4, 460)],...
sql|pandas|pyspark|group-by|apache-spark-sql
0
353,445
72,825,903
Getting start date of week from week number
<p>I have a list like this <code>lst = [25,26,27]</code></p> <p>numbers: <code>25</code>, <code>26</code>, <code>27</code> are the week number.</p> <p>For each number from list I would like to have a start date, e.x. for week <code>25</code> the start date is <code>2022-06-21</code> (week starts on Monday).</p> <p>Plea...
<p>IIUC, you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>:</p> <pre><code>lst = [25,26,27] year = 2021 out = pd.to_datetime(pd.Series(lst).astype(str)+str(year)+'Mon', format='%W%Y%a') </code></pre> <p>output:</p> <pre><co...
pandas|timedelta
0
353,446
72,800,548
Remove string from array using numpy
<p>I have this csv with a column containing a mix of string and integer types. (ie, 6 Years and 12 Months). I am trying to find a way to convert the 'years' and 'months' into a new array containing just the months.</p> <pre><code>YrsAndMonths=np.array(['6 Years and 12 Months','7 Years and 8 Months','2 Years']) </code><...
<p>There is a specific approach that should work with the pattern of your sentences:</p> <pre><code>sentences = ['6 Years and 12 Months','7 Years and 8 Months','2 Years'] res = [] for x in [sentence.lower() for sentence in sentences]: local_res = 0 if &quot;year&quot; in x: year = x.split(&quot;year&qu...
python|numpy
1
353,447
72,730,300
could not broadcast input array from shape (512,512) into shape (512,512,2)
<pre><code>class DataGenerator(Sequence): def __getitem__(self, index): indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size] list_IDs_temp = [self.list_IDs[k] for k in indexes] X,y= self.__data_generation(list_IDs_temp) return X, y def on_epoch_en...
<p><code>Pydicom.read_file(path).pixel_array</code> returns an array of size <code>image heigt x image width</code>, it does not include any channels. An array with the same shape is returned by <code>self.load_dicom_xray</code>. When trying to put this array into array <code>X</code>, which shape includes channels, t...
python|tensorflow|keras
1
353,448
72,505,979
TypeError: 'DataFrame' object is not callable while creating new dataframe
<p>i am trying to create new dataframe from my existing data and i am getting this error . i have checked all the grammatical and syntatical erros .how to fix this error</p> <pre><code>teams = data['toss_winner'].unique() decision_making = pd.DataFrame([],columns=['Toss Winner','Decision','Times']) for id,element in e...
<p>Seems like you missed some syntax error. You used parenthesis after <code>data[data</code>.</p> <pre><code>for id,element in enumerate(teams): temp_data = data[(data['toss winner']==element) &amp; (data['toss_decision']=='bat')] temp_data = data[(data['toss winner']==element) &amp; (data['toss_decision']=='...
python|pandas|dataframe|data-visualization
0
353,449
72,577,675
Iteratively Output Individual Dataframes from a Dictionary of Dataframes (Python)
<p>First, I have a dictionary of dataframes named (dfs). There are five dataframes in the dictionary.</p> <p>Second, using the the dictionary of dataframes (dfs), I run the code below to classify items in the dataframes, dfs, and save them to a new dictionary of dataframes (out_dfs), see sample output below.</p> <pre><...
<p>I am not sure i completely understood your desired output, but here is my interpretation. Below uses <a href="https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/" rel="nofollow noreferrer">f strings</a> and <a href="https://www.geeksforgeeks.org/exec-in-python/" rel="nofollow noreferrer">exec()...
python|pandas|dataframe|dictionary
0
353,450
72,509,167
Renaming columns according to a string in the rows of a dataframe
<p>I have a dataframe with hundreds of columns like the example below:</p> <pre><code> 1 12 13 14 15 id=10 formatted_value=U$ 20.000 weighted_value=U$ 20000 person_name=Natys Person query={'id':0,'name':'Ro...
<pre><code>pd.DataFrame(df.apply(lambda x:dict(list(x.str.split('='))),axis=1).to_list()) id formatted_value weighted_value person_name 0 10 U$ 20.000 U$ 20000 Natys Person 1 11 U$ 10.000 U$ 10000 Mike Tyson </code></pre> <p>with the dictionaries:</p> <pre><code>pd.DataFrame(df.apply...
pandas
2
353,451
72,805,494
Openpyxl: While value in first column is the same append all row data to right of value to new workbook
<p>I have the table below. While the value in the Boat ID column is the same, I would like to copy all data to the right, open up an existing WB on my PC with the same column headers and paste the data starting at cell A2. This process would be repeated for all unique values in the Boat ID column</p> <div class="s-tabl...
<p>Based on what was mentioned and the code, this is what I believe you are looking for...</p> <ol> <li>There is an existing file &quot;boats_ans.xlsx&quot; and you want to append data to that file</li> <li>You have no issues creating the data, but you want to create multiple sheets with name &quot;Boat id N&quot; in t...
python|excel|pandas|loops|openpyxl
0
353,452
72,732,177
IsADirectoryError when loading my pytorch model with load_from_checkpoint
<p>Could someone please explain to me why this function:</p> <pre><code>def train_graph_classifier(model_name, **model_kwargs): pl.seed_everything(42) # Create a PyTorch Lightning trainer with the generation callback root_dir = os.path.join('/home/predictor2', &quot;GraphLevel&quot; + model_name) os.makedirs(r...
<p>This:</p> <pre class="lang-py prettyprint-override"><code>model=GraphLevelGNN.load_from_checkpoint(trainer.checkpoint_callback.best_model_path) </code></pre> <p>is failing because you are trying to open a directory and not a file. Check that <code>trainer.checkpoint_callback.best_model_path</code> actually is the pa...
python|pytorch
1
353,453
72,582,273
I need to set a really specific regex pattern
<p>I have a pandas dataframe with values on each cell like this:</p> <pre><code>GRI 101: Foundation: • Clause 1.1 (Stakeholder Inclusiveness principle) • Clause 1.3 (Materiality principle) • Clause 2.1 (Applying the Reporting Principles) GRI 102: General Disclosures: Disclosures 102-40, 102-42, 102-43, and 102-44 <...
<p>See if this work:</p> <pre><code>Disclosures = df['0'].str.findall(r'\d+-\d+').str.join('\n')[0] top_number = str(df['0'].str.findall(r'GRI \d+').str.join('')).split('GRI')[1].strip() clauses = str(df['0'].str.findall(r'[\d+][.][\d+]').str.join(' ')[0]).split(' ') for c in clauses: print(top_number, '-', c, sep=...
python|regex|pandas|mapping
1
353,454
72,715,012
How to remove all data from TFRecordDataset except the first record
<p>The following code created a <code>TFRecordDataset</code> from <code>test_filenames</code>, and it contains 10000 records:</p> <pre><code>test_dataset = tf.data.TFRecordDataset([test_filenames]) </code></pre> <p>I want to keep the first record in the test_dataset and remove all other records for testing.</p> <p>Here...
<p>You need to create <code>Dataset</code> first. for creating the dataset you need to change your <code>test_function</code> like below then use <code>.map()</code> and at the end use <code>batch(1).take(1)</code> like below:</p> <pre><code>def test_function(record): keys_to_features = { &quot;test1&quot;:...
python|tensorflow|keras
0
353,455
72,817,366
how can i make 4 rows into 1 row in pandas dataframe?
<p>I'm using python3 and jupyter notebook in intel-cpu mac</p> <p>I want to make 15 column and 25600 rows csv file into</p> <p>60 column and 6400 rows</p> <p>just making</p> <p>new 0th row = 0th row, 1st row, 2nd row, 3rd row</p> <p>new 1th row = 4th row, 5th row, 6th row, 7th row</p> <p>and so on</p> <p>what can i do?...
<p>You can do:</p> <pre><code>df2 = pd.concat( [pd.DataFrame(df.iloc[i:i+4].stack().tolist()).T for i in range(0, len(df), 4)] ).reset_index(drop=True) df2.columns = np.ravel([df.columns]*4) </code></pre> <p>Basically get 4 rows stack them and form a list and concatenate them into a dataframe.</p> <p>Example:</p> <...
python|pandas|dataframe
0
353,456
72,709,536
Convert a list of nested dictionary WITH STRING OBJECT into pandas Dataframe
<p>I have a real-time url &quot;linktoAPI&quot; containing a list of nested dictionary. I have tried many solutions from the links below, but none of them helps me achieve what I want. Apparently, it is because the value of the nested dictionary (key: &quot;history_value&quot;) is ununiform and contain long string obje...
<p>If I get it right, this should work:</p> <pre class="lang-py prettyprint-override"><code>import json import requests import pandas as pd req = requests.get('https://office.ieltsvietop.vn/api/get_data/history') req_json = req.json() df = pd.DataFrame(json.loads(r['history_value']) for r in req_json) </code></pre> <...
python|pandas|dictionary
1
353,457
72,796,541
Convert multiple time format object as datetime format
<p>I have a dataframe with a list of time value as object and needed to convert them to <code>datetime</code>, the issue is, they are not on the same format so when I try:</p> <pre><code>df['Total call time'] = pd.to_datetime(df['Total call time'], format='%H:%M:%S') </code></pre> <p>it gives me an error</p> <pre class...
<pre><code>times = &quot;&quot;&quot;\ 2:04:07 3:22:41 2:30:41 2:19:06 1:45:55 1:30:08 1:32:15 1:43:28 45:48 1:41:40 5:08:37 3:22 4:29:05 2:47:25 2:39:29 2:29:32 2:09:52 3:31:57 2:27:58 2:34:28 3:14:10 2:12:10 2:46:58&quot;&quot;&quot;.split() import pandas as pd df = pd.DataFrame(times, columns=['elapsed']) def pad(s...
python|pandas|dataframe|datetime|timedelta
0
353,458
72,779,228
pytorch gives me an error when I don't run it in ~/ directory
<p>When I run the following python script in an subdirectory, for example ~/test_dir, python results in an error :</p> <pre><code>import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 out...
<p>It seems that you named your working directory and a script <code>torch</code>. It causes a conflict with the installed Pytorch library, therefore you're calling <em>your</em> <code>torch</code>, not the installed one.</p> <p>Try it after changing the names of your directory and script.</p>
python-3.x|pytorch|pythonpath
2
353,459
72,492,674
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (3,)
<p>I have an <code>np.ndarray</code> of shape <code>(5, 5, 2, 2, 2, 10, 8)</code> named <code>table</code>. I can succesfully slice it like this:</p> <pre><code>table[4, [0, 1], 1, 1, 1, slice(0, 10, None), slice(0, 8, None)] </code></pre> <pre><code>table[4, [0, 1], 1, 1, 1, [0, 2], slice(0, 8, None)] </code></pre> <p...
<pre><code>In [219]: table = np.zeros((5, 5, 2, 2, 2, 10, 8),int) In [220]: table.shape Out[220]: (5, 5, 2, 2, 2, 10, 8) </code></pre> <p>The fact that you use <code>slice</code> instead of <code>:</code> doesn't matter; same for the fact that the trailing slices don't have to be specified.</p> <pre><code>In [221]:...
python|arrays|numpy|numpy-ndarray|numpy-indexing
3
353,460
72,608,485
Modify multiple columns - None of [Index] are in the [columns]
<p>Hello stackoverflow community,</p> <p>i've build following code to merge a column from two csv files and it works perfectly for one file</p> <pre><code>df1 = pd.read_csv(r'path') df2 = pd.read_csv(r'path') df2 = df2.fillna(0) df3 = pd.merge(df1,df2[['status','stati']].astype(object),on='status', how='left').drop(c...
<p>Since running your example code with those two dataframes yields me</p> <pre><code> status 0 aktiv 1 beantragt 2 storniert 3 DV </code></pre> <p>I think you're trying to <a href="https://en.wikipedia.org/wiki/Data_mapping" rel="nofollow noreferrer">map</a> status codes in one dataframe to status ...
python|pandas|csv|merge
1
353,461
72,529,063
How to adjust the density of global divergent wind vector using quiver
<p>I plotted the divergent wind vector globally using <code>cartopy</code> and <code>quiver</code> in <code>PlateCarree(central_longitude=180)</code> projection.</p> <pre><code>lat=lats.to_numpy() lon=lons.to_numpy() uchi_1=uchi1.to_numpy() vchi_1=vchi1.to_numpy() ax2 = plt.axes(projection=ccrs.PlateCarree(central_lon...
<p>Looks like you figured out how to get this up and running by downsampling the 2D arrays in comments! I just wanted to offer an xarray-native way of approaching this, as it provides a pretty powerful and friendly way of interacting with large labeled datasets like this.</p> <p>As of v0.17.0 (Feb 2021), xarray has a <...
python|numpy|matplotlib|python-xarray
0
353,462
72,595,789
Pandas grouping and inverting df manipulating of hist.price data
<p>For the following code the output returned is such:</p> <p><a href="https://i.stack.imgur.com/cMmPi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cMmPi.png" alt="enter image description here" /></a></p> <p>The desired arrangement is however with the tickers raised and grouped/aggregated like:</p...
<p>Here is the pivoted df:</p> <pre><code>df = pd.DataFrame({ 'datetime': ['2022-06-08', '2022-06-09', '2022-06-10', '2022-06-08', '2022-06-09', '2022-06-10', '2022-06-08', '2022-06-09', '2022-06-10', '2022-06-08', '2022-06-09', '2022-06-10', '2022-06-08', '2022-06-09', '2022-06-10'], 'value': [0, 1, 2, 3, 4, ...
python|pandas|dataframe|stockquotes
0
353,463
72,563,553
Checking if points fall into shapefile (polygons and points are in different unit)
<p>I'm trying to create a mask following <a href="https://stackoverflow.com/questions/72534885/mask-area-outside-of-a-shape-file-with-cartopy-and-geopandas">this question's answer</a>, so that I can color areas inside my shape file only. I will post the code example here (which is pretty much the same with the code in ...
<p>Here's another MRE. Keeping things very simple - I'm just using the bbox and vector of (x, y) values rather than the mesh you have. But it should be enough to illustrate the issue you're dealing with.</p> <pre class="lang-py prettyprint-override"><code>import cartopy.crs as ccrs import shapely.geometry import shapel...
python|mask|geopandas|shapefile|cartopy
2
353,464
72,661,086
Python: count headers in a csv file
<p>I want to now the numbers of headers my csv file contains (between 0 and ~50). The file itself is huge (so not reading the complete file for this is mandatory) and contains numerical data. I know that csv.Sniffer has a has_header() function, but that can only detect 1 header. One idea I had is to recursivly call the...
<p>Here's a sketch for finding the first line which matches a particular criterion. For demo purposes, I use the criterion &quot;there are empty fields&quot;:</p> <pre><code>import csv with open(filename, &quot;r&quot;, encoding=&quot;utf-8&quot;) as handle: for lineno, fields in enumerate(csv.reader(handle), 1): ...
python|pandas|csv
1
353,465
72,766,206
too many indices for array with matplotlib subplots
<p>I'm trying to plot 2 different data sets but I don't know how to fix the subplot (if i put 2,2 it works but if i try anything else it gives me an error)</p> <pre><code>fig, axs = plt.subplots(nrows=2, ncols=1) axs[0,1].plot(adj_close['SOL-USD']) axs[2,1].set_title('SOL') plt.show() </code></pre> <p>error:</p> <pre...
<p>what is going on here is that <code>matplotlib.pyplot.subplots()</code> creates an array of one dimension for axes in fig if nrows or ncols is equal to 1. You can see this by displaying the variable in your current workspace.</p> <p><code>&gt;&gt;&gt; fig, axes = plt.subplots(nrows=2, ncols=1)</code></p> <p><code>&g...
python|pandas
2
353,466
72,641,009
How to extract text and save as excel file using python or JavaScript
<p>How do I extract text from this PDF files where some data is in the form of table while some are key value based data</p> <p>eg: <a href="https://drive.internxt.com/s/file/78f2d73478b832b2ab55/3edb275967deeca6ad33e7d53f2337c50d5dfb50e0aa525bb7f10d49dff1e2b4" rel="nofollow noreferrer">https://drive.internxt.com/s/fi...
<p>This pdf does not have well defined tables, hence cannot use any tool to extract the entire data in one table format. What we can do is read the entire pdf as text. And process each data fields line by line by using regex to extract the data.</p> <p>Before you move ahead, please install the pdfplumber package for py...
python|json|pandas
1
353,467
59,599,787
DeepAR Building Product Categories
<p>I have a problem with the understanding of the DeepAR Algorithm. </p> <p>I tried to forecast the sales of single products with the Algorithm. First I tried it for one SKU on a daily frequence but I got the following error message: </p> <pre><code>ParamValidationError: Parameter validation failed: Invalid type for...
<p>It looks like the error is thrown by boto (<code>ParamValidationError</code>). I suspect that you are not using the correct json-format to send the requests. See an example <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/deepar-in-formats.html" rel="nofollow noreferrer">here</a>.</p> <blockquote> <p>I th...
pandas|amazon-sagemaker
1
353,468
59,699,616
Pandas Date Time subraction - assigning nan values
<p>If I have code as below, </p> <pre><code>df['variance'] = (pd.to_datetime(df.last_date) - pd.to_datetime(df.first_date)) / np.timedelta64(1, 'M') </code></pre> <p>This gives me number of months, but if one of the columns does not have a date and the result for this code for that value is NaN, is there a way where ...
<p>This should do it:</p> <pre><code>df = df.fillna(value='Void') </code></pre>
python|python-3.x|pandas
2
353,469
59,799,888
How to extract XML node values with Elementtree
<p>I have the following data structure (the entire file is about 2.5gb, with many more persons, which is why I rely on parsing): </p> <pre><code>&lt;!-- ====================================================================== --&gt; &lt;person id="10004136"&gt; &lt;attributes&gt; &lt;attribute ...
<p>Your code contains such a flaw that although you defined <em>age</em> as <em>defaultdict(list)</em> but then you make absolutely no use of it. So how do you expect that <em>age</em> dictionary contains any data to create your DataFrame?</p> <p>The solution is that after you parse the source file (you have set <em>t...
python|pandas|parsing|elementtree
1
353,470
59,855,938
While implementing OLS in a a multiple regression with on dependnt variable and three independent variables Patsy error of numpy is there
<p>While implementing OLS in a a multiple regression with on dependent variable and three independent variables the following code is being faced</p> <blockquote> <p>PatsyError: Error evaluating factor: IndexError: only integers, slices (<code>:</code>), ellipsis (<code>...</code>), numpy.newaxis (<code>None</code...
<p>learners problems i guess </p> <p>in</p> <p>regressor_OLS = sm.ols(formula = 'y ~ X1', data = X1)</p> <p>i should have used fwg </p> <p>regressor_OLS = sm.ols(formula = 'y ~ X1', data = datset)</p> <p>sorry for bothering. regards all</p>
python-3.x|numpy
0
353,471
59,728,088
Loading ResNet50 on RTX2070 - Out of Memory
<p>I'm trying to load ResNext50, and on top of it CenterNet, I'm able to do it with Google Colab or Kaggle's GPU. But,</p> <ol> <li><p>Would love to know how much GPU Memory (VRAM) does this network need?</p></li> <li><p>When using RTX 2070 with free 5.5GB VRAM left on it (out of 8GB), I'm not able to load it.</p></li...
<h2>Using third party dependency</h2> <p>You could get size of <code>model</code> in bytes using third party library <a href="https://szymonmaszke.github.io/torchfunc/packages/torchfunc.html#torchfunc.sizeof" rel="nofollow noreferrer"><code>torchfunc</code></a> (disclaimer I'm the author).</p> <pre><code>import torch...
deep-learning|gpu|pytorch|resnet
2
353,472
59,491,694
Pandas: Two equal columns and short second column according to the first
<p>I would like to sort the second, the second column is equal to the first but is missing some values.</p> <p>Data before:</p> <pre><code> Cat1 Cat2 1 fish dog 2 dog ant 3 cat fox 4 ant NaN 5 fox NaN </code></pre> <p>Data after:</p> <pre><code> Cat1 Cat2 1 fish NaN 2 dog ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> with left join by filter each column separately to one column <code>DataFrame</code>s:</p> <pre><code>df = df[['Cat1']].merge(df[['Cat2']], left_on='Cat1', r...
python|pandas
3
353,473
59,538,741
Should I stack, pivot, or groupby?
<p>I'm still learning how to play with dataframe and still can't make this... I got a dataframe like this:</p> <pre><code>A B C D1 D2 D3 1 2 3 5 6 7 </code></pre> <p>I need it to look like:</p> <pre><code>A B C DA D 1 2 3 D1 5 1 2 3 D2 6 1 2 3 D3 7 </code></pre> <p>I know I should use somet...
<p>This is <code>wide_to_long</code> </p> <pre><code>ydf=pd.wide_to_long(df,'D',i=['A','B','C'],j='DA').reset_index() ydf A B C DA D 0 1 2 3 1 5 1 1 2 3 2 6 2 1 2 3 3 7 </code></pre>
python-3.x|pandas|pandas-groupby|pandas-datareader
6
353,474
59,772,870
Python combine monthly and minutes dataframes with TZ-aware datetime index
<p>I have two time-series below. Datetime indices are TZ-aware. </p> <p><strong>df1</strong>: Five minutes interval </p> <pre><code> value_1 Timestamp 2009-04-01 10:50:00+09:30 50 2009-04-05 11:55:00+09:30 55 2009-04-23 16:00:00+09:30 0 2009-05-03 10:50:00+09:30 50 2009-...
<p>Try this, using <code>strftime</code> to create a temporary merge key for both dataframes:</p> <pre><code>df1.reset_index()\ .assign(yearmonth=df1.index.strftime('%Y%m'))\ .merge(df2.assign(yearmonth=df2.index.strftime('%Y%m')))\ .set_index('Timestamp')\ .drop('yearmonth', axis=1) </code></pre> <p>Outp...
python|pandas|merge|timestamp|concat
2
353,475
59,850,703
Pandas grouping logic
<p>In <strong>A</strong> we have column named #type that contain objects like item1, item2 etc. each needs to become new column.</p> <p>item1 have id, you can use it to find item2 with the same id, same goes for item3 and item4 (some may have missing data and have no entries for them but thats is rare, 0 can be put th...
<p>I believe this should do the trick:</p> <pre><code>import pandas as pd from functools import reduce df.set_index('ID', inplace=True) # create a df based on all items 1, and keep date; note, this will make the date of item1 leading df_base = df[df.type=='Item1'].loc[:, 'Date'].to_frame() # pivot the df to get a c...
python|python-3.x|pandas|pandas-groupby
1
353,476
59,504,791
torch tensor changes to numpy array in for/while loop?
<pre><code>print('\nCollecting experience') for ep in range(400): state = env.reset() #print(state.shape) #state = np.array(state) state = state.transpose((2, 0, 1)) #state = torch.from_numpy(state) state = Variable(torch.from_numpy(state)) state = state.unsqueeze(0) print("AA", state.shape) episode_r...
<p>solved it, turns out the problem was later in the loop, the next input wasn't the same, so made the processing into numpy and things into a function, and it worked</p>
python|numpy|machine-learning|pytorch
0
353,477
59,535,073
training apriori dataset with pandas not displaying results
<p>I have created dataframe and list according to the apriori algorithms, I have created rules as well. but the results are not coming out and it's also not showing any error.</p> <p>below is the code:</p> <pre><code>df = pd.read_csv('itemlist.csv', header = None) togetheritems = [] for i in range(0, 2071): to...
<p>You haven't asked Python to visualise the results you've just assigned them to a variable. Try <code>print(results)</code></p>
python|pandas
1
353,478
59,707,289
How to wrap tensorflow graph with placeholder in keras
<p>I have a tensorflow graph (stored in a protobuffer file) with placeholder operations as inputs. I want to wrap this graph as a keras layer or model.</p> <p>Here is an example:</p> <pre><code>with tf.Graph().as_default() as gf: x = tf.placeholder(tf.float32, shape=(None, 123), name='x') c = tf.constant(100,...
<p>I figured out the way. We need to use <code>InputLayer</code> instead of <code>Input</code>.</p> <p>First the codes that create the demo tensorflow graph PB:</p> <pre><code>def dump_model(): # just to hide all vars during creation demo import numpy as np import sys import tensorflow as tf with tf.G...
tensorflow|keras|tf.keras
1
353,479
59,502,712
How to use multiple filter in pandas
<p>i want to filetr my csv file using multiple value. For example </p> <pre><code> NEID VPNID DSCP COS 0 2645 1 18 1 1 2645 1 48 6 2 2645 2 34 2 3 2645 2 46 6 4 2645 3 46 6 </code></pre> <p>I want to filter row whose value in DSCP column must match 18 a...
<p>You don't need to use <code>query</code> to acquire that slice:</p> <pre class="lang-py prettyprint-override"><code>print(df[(df['DSCP'] == dscp1) &amp; (df['DSCP'] == dscp2)]) </code></pre> <p>It is worth pointing out, though, that the slicing used above will never return anything - it is impossible to have two d...
python-3.x|pandas|csv
1
353,480
59,636,849
Pandas groupby inherits groups from parent dataframe?
<p>I am trying to group by a categorical variable <code>installation_id</code>. For some reason groupby seems to include groups that aren't in the dataframe itself. For example:</p> <pre><code>df.groupby('installation_id').size() # Length of each group installation_id 0001e90f 0 000447c4 0 0006a69f 16 0006...
<p>This is a <em>FEATURE</em> of grouping by Categorical data.</p> <p>Instead use:</p> <pre><code>df.groupby(df['installation_id'].to_numpy()).size() </code></pre> <p>OR MUCH MORE SIMPLY from ALollz (will delete if ALollz posts answer)</p> <pre><code>df.groupby('installation_id', observed=True).size() </code></pre>
python|pandas|pandas-groupby
4
353,481
59,775,132
Aligning a Three Column DataFrame by the Order of Another List
<p>I have a pandas data frame of a list of names with their coordinates as such:</p> <pre><code>name1 3 100 name2 5 4 name3 7 5 ... name88 100 300 name21 30 40 </code></pre> <p>I have another list that is a single column series with only the names in a specific order</p> <pre><code>name3 name10 name2 name6 ... name3...
<p>Let's say the names column in your dataframe is called <code>Name</code> and your other series is called <code>names</code>. Then this should do:</p> <pre><code> df = df.set_index('Name').reindex(index=names).reset_index() </code></pre>
python|pandas
2
353,482
59,760,569
keras model prediction is nan after saving and loading
<p>I trained a neural network with google colab.<br> I saved the neural network using <code>joblib.dump()</code></p> <p>I then loaded the model on my PC using <code>joblib.load()</code></p> <p>I made a prediction on the exact same sample, using the same model, on both colab and my PC. On colab, it has an output of <...
<p>As far as I know keras has its own function to save the model such as <code>model.save('file.h5')</code>, and the <code>joblib</code> library is used to save sklearn models.</p>
python|tensorflow|keras|google-colaboratory
0
353,483
59,549,785
Creating a Text Classifier with Other data features in Tensorflow 2.0/Keras
<p><strong>Main question:</strong> How do I create a neural network that can classify text data along with numerical features?</p> <p>It sounds simple, but I must not be understanding something correctly.</p> <h1>Background</h1> <p>I'm trying to build a text classifier (for the first time) using TensorFlow 2/Keras t...
<p>There’s another option for adding in non-text data to text models: make the data textual. The exact way you do this depends on the tokenizer you are using, and how your model handles words it hasn’t seen before (OOV words). But, similar to how you might see special tokens like <code>__EOS__</code> to tell the model ...
python|tensorflow|machine-learning|keras|nlp
1
353,484
59,751,314
pyspark MinHashLSH Jaccard distance : not calculating the distance for some pairs
<p>I'm trying to calculate Jaccard distance between some products using MinHashLSH pyspark.</p> <p>The toy data i use is </p> <pre><code>sdf = spark.read.csv('dt.csv',header=True, sep=',', inferSchema=True) sdf = sdf.withColumn("ticket", sdf["ticket"].cast(StringType())) sdf.show(60) ticket| Brand|value| +------+-...
<p>Sorry,It was me that shows only the first 20, when i collect all i get the result, i will lift this toy example here since there was not </p>
pandas|apache-spark|pyspark|distance|similarity
-1
353,485
59,826,689
iterate over pandas series, if and isin for different actions
<p>checked:</p> <p><a href="https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o">Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()</a></p> <p><a href="https://stackoverflow.com/questions/50267185/iterate-over-panda...
<p>Here's how I would do it:</p> <pre><code>for index, value in s.items(): if value in check_1: print('checked_1') elif value in check_2: print('checked_2') else: print ('nothing') </code></pre>
python|pandas
2
353,486
59,809,540
Tensorflow Datasets, padded_batch, why allow different output_shapes, and is there a better way?
<p>I'm trying to write Tensorflow 2.0 code which is good enough to share with other people. I have run into a problem with tf.data.Dataset. I have solved it, but I dislike my solutions.</p> <p>Here is working Python code which generates padded batches from irregular data, two different ways. In one case, I re-use a...
<p>Answering my own question. <a href="https://www.reddit.com/r/tensorflow/comments/er2ddo/datasetpadded_batch_why_allow_different_output/" rel="nofollow noreferrer">I asked this same question on Reddit</a>. A Tensorflow contributor replied that <a href="https://github.com/tensorflow/tensorflow/commit/b7e9c784141eed0...
python|tensorflow|tensorflow-datasets
1
353,487
59,657,166
Convert frozen model(.pb) to savedmodel
<p>Recently I tried to convert the model (tf1.x) to the saved_model, and followed the official <a href="https://www.tensorflow.org/guide/migrate" rel="noreferrer">migrate document</a>. However in my use case, most of model in my hand or tensorflow model zoo usually is pb file, and according to the <a href="https://www....
<p>in TF1 mode:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import tag_constants def convert_pb_to_server_model(pb_model_path, export_dir, input_name='input:0', output_name='output:0'): ...
tensorflow
3
353,488
59,802,653
Pandas - problem with converting column to int after reading csv
<p>I am importing csv file that I previously scraped from internet site. These are sample lines from this file:</p> <blockquote> <p>year,elections,teryt_code,powiat,gmina,political_party,n_votes,percentage 2011,sejm,020101,bolesławiecki,Miasto Bolesławiec,Lista nr 1 - Komitet Wyborczy Prawo i Sprawiedliwość - Zar...
<p>Actually, you try to convert '3 496' to 3496 which cannot be achieved without processing the no-break space, that is '\xa0'. You can firstly strip the space from that column, such as:</p> <pre><code>df['n_votes'] = df['n_votes'].str.strip() </code></pre> <p>After that you may be able to perform integer converting<...
python|pandas|encoding|utf-8
0
353,489
59,529,227
Error Selecting a Column in Python Dataframe
<p>I have a python dataframe (called df) that looks like this when printed in console:</p> <pre><code> date 2019-09-03 00:00:00 ... OverallAtt students ... 5c48943cbe8e95292564e163 0.0 ... 78.321678 5c48943dbe8e952...
<p>It looks like that <code>students</code> is your index name. In order to get it, you can reset your index:</p> <pre class="lang-py prettyprint-override"><code>Names = df.reset_index(drop=False)['students'] </code></pre>
python|pandas
1
353,490
59,802,608
TypeError: '>' not supported between instances of 'NoneType' and 'float'
<p>I have this code and it raise an error in python 3 and such a comparison can work on python 2 how can I change it?</p> <pre><code>import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')&gt;0.95): ...
<h1>Tensorflow 2.0</h1> <pre><code>DESIRED_ACCURACY = 0.979 class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epochs, logs={}) : if(logs.get('acc') is not None and logs.get('acc') &gt;= DESIRED_ACCURACY) : print('\nReached 99.9% accuracy so cancelling training!') ...
python|tensorflow|machine-learning|keras|typeerror
20
353,491
59,788,925
Divide amount over rows
<p>I'd like to divide a certain number of items over multiple rows. Every row should get at least 1, but the rest according to their required share, until all items have been distributed. Lets say we have 6 available, I'd like to get the result as follows.</p> <p>Using <code>max(1, factor * available)</code> doesn't n...
<p>This is how I would approach the issue if I am understanding it correctly:</p> <pre><code>import numpy as np import pandas as pd data = {'c1':['A','B','C','D','E'],'factor':[0.001,0.2,0.2,0.2,0.3]} df = pd.DataFrame(data) df['factor_rescaled'] = df['factor'] / df['factor'].sum() available = int(input('Available =...
python|pandas|numpy|pyspark
1
353,492
59,752,154
pandas.where with different shapes
<p>I was reading about the pandas dataframe <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>where</code></a> function.</p> <p>But I want to compare two dataframes with different shapes, e.g:</p> <pre><code>&gt;&gt;&gt;print(df1.shape) (1...
<p>I'm not sure if this is the same as what you are doing, but I recently had to do a comparison of disparately shaped dataframes as so:</p> <pre><code>df1['col2'].mask(df1['col1] == df2.loc[0, 'col1']) </code></pre> <p>In my example df1 and df2 have different numbers of rows. This returns back a population from df1...
python|pandas|dataframe
0
353,493
59,868,377
python ValueError: non-broadcastable output operand with shape (389,1) doesn't match the broadcast shape (389,7)
<p>I am new to python programming language I am using Pytorch neural network LSTM to predict the feature price of the stock i know it's a common question but I am not being able to fix the issue</p> <p><strong>ValueError: non-broadcastable output operand with shape (389,1) doesn't match the broadcast shape (389,7)</st...
<p>I can reproduce the error with:</p> <pre><code>In [75]: x = np.ones((4,1)) In [76]: x *= np.ones((4,2)) -------------------------------------------------------------------------...
python|pandas|numpy|pytorch|lstm
0
353,494
59,772,300
Merge data frames keeping a multi-index
<p>I have two data frames, <code>df1</code> and <code>df2</code>. One has a multi-index, say <code>['A', 'B']</code> and the other has a single index <code>['B']</code>. I would like to merge data from <code>df2</code> into <code>df1</code> via the index <code>'B'</code> while preserving my multi-index <code>['A', 'B']...
<p>In this example, I might do it this way:</p> <pre><code>df_state_year['capital'] = df_state_year.index.get_level_values(0).map(df_state.squeeze()) </code></pre> <p>Output:</p> <pre><code> population capital state year California 2000 33871648 Sacramento ...
python|pandas
1
353,495
59,603,959
Not able to comprehend the array statement of last line
<pre><code>import numpy as np arr = np.arange(9, dtype = "float").reshape(3,3) ind1 = np.array([[1,2],[0,1]]) ind2 = np.array([[0,2],[1,2]]) print(arr[ind1, ind2].sum()) </code></pre> <p>Output for the given code coming out to be 17.0 but i am not able to understand how is the arr[ind1,ind2] working.Kindly help!</p>
<p>firstly, solve this thing arr[ind1,ind2] as ind1 and ind2 both are matrices of 2*2. Now we have to pair the corresponding positions of both the matrices. which results in 4 pairs : (1,0) ; (0,1) ; (2,2) ; (1,2) .</p> <p>Now find the values from arr which are at these positions. and values comes out to be 3;1;8;5 r...
python|arrays|multidimensional-array|numpy-ndarray
0
353,496
59,730,501
Tensorboard pointing wrong data loction
<p>I am working on the jupyter notebook environment and made a hyperparameter tuning process using HParams. I planned to use tensorboard to inspect patterns in hyperparameter values but tensorboard kept opening old files(logs/Twitter_sentiment_analysis) and threw the shown error in the image. </p> <p>When I enter othe...
<p>The notebook actually tells you what to do. There is already one TensorBoard instance running on port 6006. You need to kill it first and then start a new TensorBoard.</p>
python|tensorflow|tensorboard
0
353,497
59,777,504
How to efficiently write raw bytes to numpy array data in python 3
<p>While migrating some old python 2 code to python 3, I ran into some problems populating structured numpy arrays from bytes objects. </p> <p>I have a parser that defines a specific dtype for each type of data structure I might encounter. Since, in general, a given data structure may have variable-length or variable-...
<p>Per the suggestion of @nawsleahcimnoraa, I found out that in python 3.3+ (so not in python 2.7), the <code>memoryview</code> object, which is returned by <code>arr.data</code> in my python 3 environment, has a <code>cast()</code> method. Thus, I can do</p> <pre class="lang-py prettyprint-override"><code>arr.data.ca...
python-3.x|python-2.7|numpy|memoryview|structured-array
1
353,498
59,724,872
rename a files within a folder of a folder to its parent folder?
<p>I have a batch of folders that have a name based on the date. Each folder has a folder where they have file names which are all the same. </p> <p>Is there a way rename the files so they become unique based on the directory structure (which appears is the parent folder (the first folder) which is based on the date) ...
<p>Here is one-way using pathlib from python 3.4+ and f-strings from python 3.6+</p> <p>first you need to set your path at the top-level directory, so we can recursively find all the csv files and rename with a simple for loop.</p> <pre><code>from pathlib import Path files = Path(r'C:\Users\datanovice\Documents\Excels...
python|pandas|macos|directory|directory-structure
3
353,499
59,729,239
ConvLSTMCell in tensorflow 2
<p>After upgrade to tensorflow version 2 from 1, all modules from tf.contrib were depreciated.</p> <p>In order to apply <a href="https://github.com/thushv89/attention_keras/blob/master/layers/attention.py" rel="nofollow noreferrer">attention method</a>, I need every cell's state.</p> <p>Initially, what I did in tf ve...
<p>I think that what you are looking for is here: <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/ConvLSTM2D?version=stable" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/layers/ConvLSTM2D?version=stable</a></p> <p>You can import it in your code like: </p> <pre><cod...
python|tensorflow|tensorflow2.0|tf.keras
0