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
352,400
55,727,936
How to solve the error string indices must be integers
<p>TypeError: string indices must be integers. For example: 20 is applicable but not 3550.</p> <pre><code>i=0 for key in dict1: for keys in dict2: if (dict1[key]['TITLE']==dict2[keys]['TITLE']): if pd.isna(d1.loc[i,'DB']) is True: d1.iloc[i]=dict2[keys] i+=1 </...
<p>"TypeError: string indices must be integers" means that one of <code>dictN</code> or <code>dictN[i]</code> is a string. I would start debugging by investigating the types for each of those.</p> <p>Your sample data isn't making sense to me because if <code>dictN</code> really was a Python dict then <code>dictN[i]</c...
python|pandas|dataframe|dictionary
0
352,401
55,966,945
How to selectively put values into a dataframe columns after flattening the dataframe columns?
<p>I'm new to use pandas data frame and I'm actually stuck with a problem. I have one dataframe, which looks like this: </p> <pre><code>Name SubName ATTR VAL GSKT SW type circular GSKT SW size 2mm GSKT SW shape square GSKT SW tip bend GST ...
<p>Try with:</p> <pre><code>df.ATTR=pd.Categorical(df.ATTR,['type','size','shape','tip'],ordered=True) df.pivot_table(index=['Name','SubName'],columns=['ATTR'],values='VAL', aggfunc='first') </code></pre> <hr> <pre><code>ATTR type size shape tip Name SubName ...
python|pandas|dataframe
1
352,402
55,868,173
Accepting base64-images as input for TensorFlow model
<p>I am trying to export my TensorFlow image-classifying model such that it accepts base64 strings as input. </p> <p>I have tried to implement the solution that is provided on <a href="https://stackoverflow.com/a/47944205/11415897">this question</a>, however I am getting the following error:</p> <blockquote> <p>"In...
<p>As per the Tutorials mentioned in the <a href="https://www.tensorflow.org/api_docs/python/tf/io/decode_jpeg#used-in-the-notebooks_1" rel="nofollow noreferrer">tf.decode_jpeg</a>, we should use <code>image = tf.io.read_file(path)</code> before using <code>image = tf.image.decode_jpeg(image)</code>.</p> <p>Working co...
python|rest|tensorflow-serving
0
352,403
64,803,507
Find occurences where a column from one dataframe equals another, based on condition
<p>I have the following two dataframes, which have different size: df1 (966 rows x 2 cols), df2 (36 rows, 2 cols), where</p> <p>df1:</p> <pre><code> Video_# Selected Joint.1 484 1 Left_shoulder 778 1 Left_shoulder 418 1 Right_shoulder 964 1 Right_shoulder 193 1 Right_shoulde...
<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 <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</c...
python|pandas|dataframe
1
352,404
64,633,850
How can I print all filter matrixes from specific layers in pre-trained model?
<p>I use VGG19 pre-trained model as feature extractor from specific layers. As I written below, I want to get features from the layer that 'block5_conv4' which is the last 5th layer.</p> <pre><code>model = keras.applications.VGG19( include_top=True, weights=&quot;imagenet&quot;, input_tensor=None, input_shape=None, poo...
<p>vgg_feature[:,:,:,0] and vgg_feature[:,:,:,511] gives all filters as 7x7 matrices.</p>
python|tensorflow|keras|feature-extraction|tf.keras
0
352,405
64,651,650
Merging Pandas DataFrames by column
<p>I have two data frames:</p> <pre><code>df1 = pd.DataFrame({'dateRep': ['2020-09-10', '2020-08-10', '2020-07-10', '2020-24-03', '2020-23-03', '2020-22-03'], 'cases': [271, 321, 137, 8, 0, 1], 'countriesAndTerritories...
<p>You can use <code>df.append</code> with <code>df.combine_first()</code>:</p> <pre><code>In [297]: x = df1.append(df2) In [299]: x.date = x.dateRep.combine_first(x.date) In [301]: x.country_refion = x.country_refion.combine_first(x.countriesAndTerritories) In [308]: x = x.sort_values('date').drop(['dateRep', 'countr...
pandas|dataframe|join|merge
1
352,406
64,621,113
Working with panda dataframe column values and pasting in next row
<p>I am very new to Panda dataframe in Python. I am working on a code where the csv file structure looks like below:</p> <pre><code>Id, Title, Body, Tags, Date 1, First question, My first question, robot Python, 2015 2, Second question, My second question, C++ Python, 2015 3, Third question, My third question, Selenium...
<p>You can do it like this:</p> <pre><code>df = df.drop([&quot;Id&quot;], axis=1) df2 = pd.DataFrame(columns=df.columns) for index, row in df.iterrows(): aux = row for tag in row[&quot;Tags&quot;].split(): aux[&quot;Tags&quot;] = tag df2 = df2.append(aux) df2.reset_index(drop=True) </code></pre>...
python|pandas|dataframe
1
352,407
64,922,025
Pandas 'color=[]' only displaying first color value for all bars in chart
<p>I'm using Pandas 1.1.4 trying to graph a dataframe in Jupyter, with the bar colors a certain color depending on the value of a column.</p> <pre><code>col = [] for count in df_count.values: val = [1, 3, 6] colors = ['r', 'g', 'b'] for i in range(len(val)): if count == val[i]: col.appen...
<p>I discovered the answer almost immediately after posting this question, but I will leave it up with a solution in-case anyone comes across this issue.</p> <pre><code>df_count.plot.barh(figsize=(10, 5), color=[col], legend=False) </code></pre>
python|pandas|matplotlib|jupyter
0
352,408
64,830,528
rearranging 2*2 pixel images, each given by 1 by 4 numpy vectors, into a single 8 by 8 matrix without using a for loop
<p>in an assignment for a uni class i am given multiple images in vectors, and i need to display multiple of them by rearranging them into a single matrix.</p> <p>assume the given vectors:</p> <pre><code>[[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13,14,15,16]] </code></pre> <p>where each pair of 4 values within a vect...
<p>Let's use <code>reshape</code>, and <code>swapaxes</code>:</p> <pre><code>arrs = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13,14,15,16]] np.array(arrs).reshape(2,2,2,2).swapaxes(1,2).reshape(4,4) </code></pre> <p>Output:</p> <pre><code>array([[ 1, 2, 5, 6], [ 3, 4, 7, 8], [ 9, 10, 13, 14], ...
python|numpy|matrix|reshape|imshow
1
352,409
64,885,740
PANDAS - I need the program to find some values, if the value is >= 4, then it returns the header of that column
<p>Good evening.</p> <p>I’m having a hard time with pandas. The short explanation is that I need the program to find some values, if the value is &gt;= 4, then it returns the header of that column.</p> <p>With that simple explanation out of the way, I’ll give more details. First of all, I’m still learning python, and I...
<p>Boolean indexing can be very helpful here.</p> <pre><code>v4 = (v2.loc[nome, 6:95]) # Select the person and the columns you want to check check high_values = (v4 &gt;= 4) # Find where response was greater than or equal to 4 v5 = v4.loc[high_values] # Take the subset of questions where condition is True questions_...
pandas|dataframe|header|row|spreadsheet
0
352,410
64,789,336
How to return a list into a dataframe based on matching index of other column
<p>I have a two data frames, one made up with a column of numpy array list, and other with two columns. I am trying to match the elements in the 1st dataframe (df) to get two columns, o1 and o2 from the df2, by matching based on index. I was wondering i can get some inputs.. please note the string 'A1' in column in 'o1...
<p>I believe you can explode <code>df</code> and use that to extract information from <code>df2</code>, then finally join back to <code>df</code></p> <pre><code>s = df['A'].explode() df_output= df.join(df2.loc[s].groupby(s.index).agg(lambda x: list(set(x)))) </code></pre> <p>Output:</p> <pre><code> A ...
pandas|list|numpy|dataframe
1
352,411
64,718,692
Python Previous Row Value
<p>I have a data set with a header row and multiple sub lines that are associated like this.</p> <pre><code>Step status 0 010000000409139 1 00001 2 00002 3 00003 4 00004 5 00007 6 00005 7 00006 8 00008 9 010000000473498 10 00001 11 00002 </code></pre> <p>What I want is just the header line repeate...
<p>You can create a boolean series by checking the <code>len</code> of <code>status</code>, use <code>cumsum</code> to create a group number, and then <code>groupby</code> on it and finally <code>transform</code>:</p> <pre><code>df[&quot;status&quot;] = df.groupby(df[&quot;status&quot;].str.len().eq(15).cumsum())[&quot...
python|pandas|function|rows
1
352,412
65,044,278
Why this model doesn't fit the result
<p>Im trying to execute the code below, but what happend is that this machine doesn't fit the value when I test this specific number 474244.073</p> <pre><code>import tensorFlow as tf import numPy as np from tensorFlow import Keras model=tf.keras.Sequential([keras.layers.Dense(units =1, input_shape=[1])]) model.compi...
<p>Check the shape of xs and ys in your code. I think your xs has 27 values while ys has only 24 values. The shapes of both the arrays must be same to fit the model correctly.</p>
python|tensorflow
0
352,413
64,770,749
replace a string in entire dataframe from excel with value
<p>I have this kind of data from excel</p> <pre><code>dminerals=pd.read_excel(datafile) print(dminerals.head(5)) </code></pre> <p><a href="https://i.stack.imgur.com/7gm1e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7gm1e.png" alt="enter image description here" /></a></p> <p>Then I replace the 'Tr...
<p>You are replacing <code>Tr</code> with 1, however there is a <code>tr</code> that's not being replaced (this is what you <code>ValueError</code> is saying. Remember python is case sensitive. Also, using for loops is extremely inefficient you might want to try using the following lines of code:</p> <pre><code>dminera...
python|pandas|dataframe|valueerror
1
352,414
64,884,534
removing elements from pandas dataframe iterator prior to loading to json (to_json)
<p>I'm trying to remove email and userid from the data_json string as it's extracted out prior and i don't want these fields listed twice, working python script:</p> <pre><code>credentials = service_account.Credentials.from_service_account_file('/keys/json_poc.txt') project_id = 'myproject' bq_conn = bigquery.Client(cr...
<p>Sorted it out, just need to change the following:</p> <pre><code>def myconverter(o): if isinstance(o, datetime.datetime): return o.__str__() bq_sql = (&quot;&quot;&quot;select email , userid, * except (email , userid) from dataset.usertable &quot;&quot;&quot;) df = bq_conn.query(bq_sql).to_dataframe() for i,...
python|json|pandas|dataframe
0
352,415
65,038,044
Accumulated Distribution Line
<p>I'm trying to learn some python and are currently doing a few stock market examples. However, I ran across something called an Accumulated Distribution Line(technical indicator) and tried to follow the mathematical expression for this until I reached the following line:</p> <p><strong>ADL[i] = ADL[i-1] + money flow ...
<p>that just looks like a cumulative sum with an unspecified base case, so I'd just use the built in <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a> functionality.</p> <pre><code>import pandas as pd df = pd.DataFrame(di...
python|pandas
0
352,416
64,694,320
Create a datetime64[ns] variable (or use between_time function?)
<p>I have a dataframe with a time column. First df.dtypes return ‘object’ and the values all look like this:</p> <pre><code>2019-10-18T08:13:26.702000 </code></pre> <p>I use pd.to_datetime and df.dtypes return ‘datetime64[ns]’ and the values all look like this:</p> <pre><code>2019-10-18 08:13:26.702000 </code></pre> <p...
<p>You need <code>DatetimeIndex</code> from column <code>ts</code>, one possible solution is use <code>DatetimeIndex</code> or convert column to index and select <code>.index</code>:</p> <pre><code>df['ts'] = pd.to_datetime(df['ts']) df = df.iloc[pd.DatetimeIndex(df['ts']).indexer_between_time(datetime.time(8,20,0), ...
python|pandas|datetime-format
0
352,417
64,764,937
Creating a pytorch tensor binary mask using specific values
<p>I am given a pytorch 2-D tensor with integers, and 2 integers that always appear in each row of the tensor. I want to create a binary mask that will contain 1 between the <strong>two</strong> appearances of these 2 integers, otherwise 0. For example, if the integers are 4 and 2 and the 1-D array is <code>[1,1,9,4,6,...
<p>Perhaps a bit messy, but it works without iterations. In the following I assume an example tensor <code>m</code> to which I apply the solution, it's easier to explain with that instead of using general notations.</p> <pre><code>import torch vals=[2,8]#let's assume those are the constant values that appear in each r...
python|pytorch|numpy-ndarray|tensor|binary-matrix
4
352,418
64,941,654
read column of a text file using loop
<p>Hii i have a text file that contain 3 columns, in each iteration i want to read one column</p> <pre><code>2 3 4 2 3 4 2 1 3 4 5 6 3 5 2 </code></pre> <p>in first iteration i need to read first column values<code>[2 2 2 4 3]</code> then second column and so on and want to save it in any name</p> <p>i tried script</p...
<p>Hi Your requirement can be fulfilled by a library called pandas.</p> <p>the function is called pandas.read_csv please use the following example</p> <pre><code>data = pd.read_csv('output_list.txt', sep=&quot; &quot;, header=None) data.columns = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;etc.&quot;] </code></...
python|numpy|for-loop
0
352,419
64,979,142
How to obtain the datetime index value at a specific row number
<p>I am working with a dataframe that looks like this:</p> <pre><code>time value 2020-08-02 21:00:00+00:00 4 2020-08-02 21:01:00+00:00 2 2020-08-02 21:02:00+00:00 3 2020-08-02 21:03:00+00:00 2 2020-08-02 21:04:00+00:00 2 2020-08-02 21:05:00+00:00 3...
<pre><code>print('Datetime at position 9 is %s' % df.index[9]) </code></pre> <p>credit to Noah - thanks for your detailed explanation - it got me thinking</p>
python|pandas|datetime|indexing
0
352,420
64,642,574
How to convert a list of dictionary values containing Timesamp objects into datetime objects in Python?
<p>I have a dictionary containing results of a user's social media activity, the values of the dictionary are in a list containing Timestamp objects and I want to convert it to time objects (datetime.time())</p> <p>here is the dictionary</p> <pre><code>{{'Instagram':[Timestamp('2020-08-23 04:16:05.12456'), Timestamp('2...
<p>Use neste dict with list comprehension:</p> <pre><code>d = {k: [x.time() for x in v] for k, v in d.items()} </code></pre> <p>But if processing solution from <a href="https://stackoverflow.com/a/64587779/2901002">this</a> you can create new column filled by times and pass after <code>groupby()</code>:</p> <pre><code>...
python|pandas|datetime
1
352,421
64,846,130
How to use distributed training with a custom loss using Tensorflow?
<p>I have a transformer model I'd like to train distributed across several workers on the Google Cloud AI Platform using Actor-Critic RL for training. I have my data broken up into individual files by date and uploaded to Cloud Storage. Since I'm using Actor-Critic RL, I have a custom loss function that calculates and ...
<p><a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">Tensorflow Model</a> is provided with a practiced solution, defined in <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/model_lib_v2.py" rel="nofollow noreferrer">model_li...
python|tensorflow|keras|distributed-computing
1
352,422
64,956,763
How to implement gradient ascent in a Keras DQN
<p>Have built a Reinforcement Learning DQN with variable length sequences as inputs, and positive and negative rewards calculated for actions. Some problem with my DQN model in Keras means that although the model runs, average rewards over time decrease, over single and multiple cycles of epsilon. This does not change ...
<h1>Writing a custom loss function</h1> <p>Here is the loss function you want</p> <pre><code>@tf.function def positive_mse(y_true, y_pred): return -1 * tf.keras.losses.MSE(y_true, y_pred) </code></pre> <p>And then your compile line becomes</p> <pre><code>model.compile(loss=positive_mse, optimizer=Adam(lr=...
python|tensorflow|keras|deep-learning|dqn
1
352,423
64,814,864
Find specific value in dataframe cells and print row header with matching columns for that value
<p>I am a Python starter using Python 3.7.0 so apologies for the blunders with my code below. I have imported an excel spreadsheet into a dataframe which shows in Jupyter as below.</p> <pre><code> Title Name1 Name2 Name3 Name4 0 A P O P 1 B P O 2 C ...
<p>Convert <code>Title</code> to index, compare 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 create new column with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dot.html"...
python|pandas|dataframe
1
352,424
64,920,746
Create multiple slices given a data frame with start and end index
<p>I have a data frame DF1 that contains a start index and end index. I want to use these indices to create multiple slices of another data frame DF2.</p> <p>I don't want to iterate through the whole dataset, one way I thought was to create an extra column on DF2 that will tell me where each slice starts and ends with ...
<p>Adapted from the great work here: <a href="https://stackoverflow.com/questions/50098025/mapping-ranges-of-values-in-pandas-dataframe">Mapping ranges of values in pandas dataframe</a></p> <p>If you can reconfigure your range inputs, this is relatively straightforward based on the linked article. Otherwise, you'll hav...
python|python-3.x|pandas|dataframe|vectorization
1
352,425
64,994,840
Pandas dataframe only select the columns that have all True
<p>Given a dataframe df, I need to select the columns that have only True values</p> <pre><code>df = A B C D E True False True False True </code></pre> <p>Output should be</p> <pre><code>output = [A, C, E] </code></pre>
<p>Try boolean indexing with <code>all</code> (for <em>only True values</em>):</p> <pre><code>df.columns[df.all()] </code></pre> <p>Output:</p> <pre><code>Index(['A', 'C', 'E'], dtype='object') </code></pre>
python|pandas|dataframe
3
352,426
64,801,774
AttributeError: module 'numexpr' has no attribute '__version__'
<p>Trying to import some modules written below:</p> <pre><code>import numpy as np import os.path import pandas as pd import math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D </code></pre> <p>However I get an AttributeError: module 'numexpr' has no attribute '<strong>version</strong>' which I ...
<p>I experienced the same problem a while back and solved it by doing the following thing in <code>Ananconda</code>:</p> <pre><code>pip uninstall -y numpy pip uninstall -y setuptools pip install setuptools pip install numpy </code></pre> <p>If you are using Anaconda3 try the same thing using <code>pip3</code>.</p>
python|pandas
0
352,427
64,967,770
EasyOCR used under Python / Torch Multiprocessing is defaulting to CPU
<p>I am using EasyOCR for text extraction from images. It uses PyTorch. There are multiple images in different folders and the sequence in which these folders are read isn't consequential.</p> <p>When run in sequence, EasyOCR is by default using GPU and is faster compared to when run on CPU. But when Python / Torch Mul...
<p>If torch.cuda.is_available returns False,</p> <ol> <li>Verify your device has a GPU.</li> <li>Verify that the installed version of CUDA is supported on your GPU.</li> <li>Verify that you have installed torch with CUDA support.</li> </ol> <p>Check this question for additional details: <a href="https://stackoverflow.c...
python|pytorch|gpu|cpu|python-multiprocessing
1
352,428
64,926,574
convert columns to rows in pandas based on condition
<p>I am trying to convert columns into multiple rows using pandas.I have the data in following table in a database. Attached below is the csv format</p> <pre><code>CustomerID,Expiry_Date,ProductA,ProductAType,ProductB,ProductBType,ProductC,ProductCType,ProductD,ProductDType,ProductF,ProductFType,ProductG,ProductGType 1...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with filter <code>YES</code> values with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pop.html" rel="nofollow noreferrer"...
python|sql|pandas
1
352,429
64,799,299
Use TensorBoard to visualize graph from tf_agents
<p>I'm quite new to RL and currently teaching myself how to implement different algorithms and hyper-parameters using tf_agents library.</p> <p>I've been playing around with the code provided from this tutorial <a href="https://colab.research.google.com/github/tensorflow/agents/blob/master/docs/tutorials/1_dqn_tutorial...
<p>Consider that this colab notebook is a very simple version of how TF-Agents actually works. In reality you should use the Driver to sample trajectories instead of you manually calling</p> <pre><code>agent.action(state) env.step(action) </code></pre> <p>at every iteration. The other advantage of the Driver is that it...
tensorflow|tensorboard|reinforcement-learning|dqn
3
352,430
64,967,308
How to return a column by checking multiple column with True and False without if statements
<p>How to get this desired output without using if statements ? and checking row by row</p> <pre><code>import pandas as pd test = pd.DataFrame() test['column1'] = [True, True, False] test['column2']= [False,True,False] index column1 column2 0 True False 1 True True 2 False ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.all.html" rel="nofollow noreferrer"><code>DataFrame.all</code></a> for test if all values are <code>True</code>s:</p> <pre><code>test['column3'] = test.all(axis=1) </code></pre> <p>If need filter columns add subset <code>['column...
pandas|list|dataframe|if-statement|list-comprehension
0
352,431
64,773,690
python: Getting error when importing type requests.models.Response into dataframe
<p>I'm new to python and I'm trying to use the census geocoding services API to geocode addresses then convert the output to a dataframe. I've been able to read in my address file and I can see the output, but I can't seem to figure out how to import it into a dataframe. I provided the code I used below as well as the ...
<p>Nikolaos provided the answer. My final code was</p> <pre><code>import requests import pandas as pd import io import csv url = 'https://geocoding.geo.census.gov/geocoder/geographies/addressbatch' payload = {'benchmark':'Public_AR_Current','vintage':'Current_Current'} files = {'addressFile': ('C:\PYTHON_CLASS\CSV\ADD...
python|pandas|api|dataframe|python-requests
0
352,432
64,842,993
How to compare one column value with multiple column value in pandas
<p>I need to create a new column based on Multiple column value. for example,</p> <p>df:</p> <pre><code> Num A B C D 0 56 65 96 46 325 1 25 96 65 35 24 2 69 23 59 63 22 3 89 46 94 79 259 </code></pre> <p>df_output:</p> <pre><code> Num A B C D E 0 56 65 96 46 325 ...
<p>Admittedly this isn't pretty but gets the job done. If you need something scalable (ie for analyzing more or less columns, this should be further refined. Nonetheless, it answers your example.</p> <pre><code>df = pd.DataFrame( { 'Num' : [56,25,69], 'A': [65...
python|pandas
0
352,433
65,036,332
How to create new columns and insert values from cell values in a pandas dataframe
<p>I have a dataframe that is in the following format:</p> <pre><code> geo_locations feature mau_audience 0 Aabenraa Alcholic Drinks,Android users,Architecture,Art... 3.380211241711606,3.230448921378274,3.0,3.5910... 1 Aalborg Alcholic Drinks,Android...
<p>Assuming that every comma separated value in feature has a corresponding value in mau_audience.</p> <h2>Create DataFrame</h2> <pre><code>data = pd.DataFrame([ ['Aabenraa','Alcholic Drinks,Android users,Architecture', '3.380211241711606,3.230448921378274,3.0'], ['Aalborg','Alcholic Drinks,Android users,Architecture',...
python|pandas
2
352,434
64,733,982
is there any way to skip rows in pandas until csv says "Flight Table"?
<pre><code>N11682,aircraft,C172,,Cessna,C172SP,airplane,airplane_single_engine_land,fixed_tricycle,Piston,false,false,false,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Flights Table,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Date,AircraftID,From,To,Route,TimeOut,Ti...
<p>I would:</p> <ol> <li>Open the CSV file</li> <li>loop through it as an iterator</li> <li>if a line starts with your magic string, pass the remaining lines to <code>pandas.read_csv</code></li> </ol> <pre><code>with open(mycsv, 'r') as fobj: for line in fobj: if line.startswith('Flights Table'): ...
python|pandas|csv
1
352,435
64,843,280
How to convert a string into datetime format
<p>I'm trying to convert strings in a list to datetime format on Python. I am unable to use <code>pd.DateTime</code> at the moment. The imported <code>datetime</code> package doesn't seem to work. I'm new to this.</p> <p>Please help.</p> <p>Cheers.</p> <p><a href="https://i.stack.imgur.com/JM8Cu.png" rel="nofollow nore...
<p>You should consider using official datetime formats</p> <p>Example:</p> <pre><code>from datetime import datetime #datetime(year, month, day) date = datetime(2018, 11, 28) # datetime(year, month, day, hour, minute, second, microsecond) date = datetime(2017, 11, 28, 23, 55, 59, 342380) </code></pre>
python|pandas|list|datetime|typeerror
0
352,436
64,824,193
Fastest way to filter a pandas dataframe many times in a loop
<p>I have a dataframe with 3 millions of rows (df1) and another with 10k rows (df2). What is the fastest method of filtering df1 for each row in df2?</p> <p>Here is exactly what I need to do in the loop:</p> <pre><code>for i in list(range(len(df2))): #For each row x = df1[(df1['column1'].isin([df2['info1'][i]])) \ ...
<pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np def make_filter(x, y, match_dict, uinque=False): filter = None for x_key in x.columns: if x_key in match_dict: y_key = match_dict[x_key] y_col = y[y_key] if uinque: ...
python|pandas|dataframe|for-loop|filter
0
352,437
64,774,519
Python Append dataframe generated in nested loops
<p>My program has two <code>for</code> loops. I generate a df in each looping. I want to append this result. For each iteration of inner loop, 1 row and 24 columns data is generated. For each iteration of outer loop, it generates 8 rows 24 columns data. I am having issues in appending in the right way so the final data...
<p>Try:</p> <ul> <li><p>Change this <code>biglist.append(tem_list)</code> to this: <code>biglist.append(pd.concat(tem_list))</code>.</p> </li> <li><p>Remove this line: <code>biglist1 = [item for sublist in biglist for item in sublist]</code></p> </li> <li><p>Modify this one <code>df = pd.concat(biglist1)</code> to <cod...
python|pandas|list|dataframe|for-loop
1
352,438
65,017,261
How to input a numpy array to a neural network in pytorch?
<p>This is the neural network that I defined</p> <pre><code>class generator(nn.Module): def __init__(self, n_dim, io_dim): super().__init__() self.gen = nn.Sequential( nn.Linear(n_dim,64), nn.LeakyReLU(.01), nn.Linear(64, io_dim), ) def forward(self, x): return self.gen(x) #The ...
<p>To input a NumPy array to a neural network in PyTorch, you need to convert <code>numpy.array</code> to <code>torch.Tensor</code>. To do that you need to type the following code.</p> <pre><code>input_tensor = torch.from_numpy(x) </code></pre> <p>After this, your <code>numpy.array</code> is converted to <code>torch.Te...
python|numpy|pytorch|numpy-ndarray
0
352,439
64,929,719
Trouble obtaining data using genfromtxt
<p>I have the following code:</p> <pre><code>import pandas as pd data = [['Initial height', param[4]], ['Exponential decay constant', param[1]], ['Angular frequency', param[2]], ['Phi offset', param[3]], ['The amplitude', param[0]]] df = pd.DataFrame(data, columns=['Variable', 'Value']) ...
<p>With your write:</p> <pre><code> In [31]: with open('tst1.csv', 'w') as f: ...: f.write( ...: df.to_string(header = False, index = False) ...: ) ...: In [33]: cat tst1.csv Initial height 0.601793 Exponential decay constant 0.612753 Angular frequency 0....
python|pandas|numpy|numpy-ndarray
1
352,440
65,008,711
What is the optimal way to create a new column in Pandas dataframe based on conditions from another row?
<p>I have a Pandas dataframe, <code>week1_plays</code> in the following format:</p> <p><a href="https://i.stack.imgur.com/18A4N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/18A4N.png" alt="enter image description here" /></a></p> <p>What I want to do is add a column <code>week1_plays['distance_fro...
<p>You are looking for a <code>merge</code> or <code>join</code> operation. Try something like this:</p> <pre><code>df = pd.DataFrame({'gameId':[1,1,1,1,1,1],'playId':[1,1,1,1,1,1], 'frameId':[1,1,1,2,2,2], 'position':['A','B','WR','C','WR','D'], 'x':[87,56,45,34,45,67], 'y':[25,36...
python|pandas|dataframe
2
352,441
64,656,350
How to divide the DataFrames based first column?
<pre><code>Id Jan Feb mar apr N1 12 23. 56. 76 65. 08. 04. 67 N2 45. 76. 87. 34 45 76. 76. 65 23. 65. 34. 87 </code></pre> <p>This value from excel sheet I written below code</p> <pre><code>Import pandas as pd df= pd.read_excel('data.xlsx') df.iloc[0:2] </code></pre> <p>This code print two rows I need to ex...
<p>We need to do the <code>ffill</code> NaN</p> <pre><code>d = {x : y for x , y in df.groupby(df.Id.mask(df.Id.eq('')).ffill())} </code></pre>
python|pandas|dataframe|pandas-groupby
1
352,442
65,017,512
KeyError in Flask app with uploaded CSV and CSV in Heroku
<p>I did this web app in Flask with a friend and I had the following form to get X and Y for any kind of plot from an uploaded CSV. The code is below:</p> <pre><code> &lt;form action=&quot;{{url_for('plot')}}&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt; &lt;div class=...
<p>I kept trying to use it in Heroku but it was of no use. I switched to PythonAnywhere and now the error does not pop up.</p>
python|html|pandas|flask|heroku
0
352,443
64,783,294
Pandas lambda function syntax for working with strings
<p>I would like to use a lambda function on a whole dataframe column with a conditional to:</p> <ul> <li>remove the 3rd character</li> <li>replace the 4th &amp; 3rd last characters with a single dash '-'</li> <li>only when a value starts with 'AB'</li> </ul> <p>Such that 'AB123456789' becomes 'AB2345-89'</p> <pre><code...
<p>It only makes sense when all AB strings have length &gt;= 7:</p> <pre><code>df['adj_key'] = df['key'].apply(lambda x: x[:2]+x[3:-4]+'-'+x[-2:] if x.startswith('A') else x) </code></pre> <p>Output:</p> <pre><code> key adj_key 0 123456789 123456789 1 AB123456789 AB2345-89 2 CD123456789 CD123...
python|pandas
1
352,444
64,644,087
Python: Validate if column entries match a desired format
<p>I am currently running sanity checks to validate if an id matches the desired format. I'd like to filter my Dataframe for projects, which are not fulfilling a desired set of standard format. In this case:</p> <ul> <li>The first two have to be letters</li> <li>The total length should be 16 characters</li> </ul> <p>I'...
<p>Use a <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer">boolean indexing</a>, like the following:</p> <pre><code>mask = ~df['project_id'].str.match(&quot;^[a-zA-Z]{2}&quot;) | df['project_id'].str.len().ne(16) print(df[mask]) </code></pre> <p><...
python|python-3.x|pandas|numpy|lambda
2
352,445
64,879,807
Get n users from pandas dataframe by id
<p>This is a mock dataframe.</p> <pre><code>df_test = pd.DataFrame({ 'ID': [8972685, 8972685, 8972685, 8972685, 8972685, 8972685, 9834561, 9834561, 9834561, 9834561, 9834561, 9834561], 'POST': ['texteghteh', 'tethrtxt', 'tetrhrtxt', 'terthtrxt', 'teetrwxt', 'twetrhext', 'tethdxt', 'texthdt', 'texdhtrt', 'texdthdt',...
<p>Depending how you would sample the users and their posts. For example, if you want to get the first 500 users with at least 1000 posts:</p> <pre><code>n_users, min_posts = 500, 1000 groups = df_test.groupby('ID') sizes = groups.size() # get the first n_users with at list min_posts users = sizes[sizes&gt;=min_posts]...
python|pandas|dataframe
1
352,446
65,029,419
TensorFlow lite conversion: error: op operands must be tensor of 8-bit unsigned integer, but got tensor<1x?x?x3x!tf.quint8>
<p>I am trying to convert a model to TensorFlow Lite after adding a few layers to a model. I have successfully run them with test inputs in Python, and they're working fine. The goal is to allow the model to take in RGB images (uint8), resize and shuffle the channels so that preprocessing is entirely consistent between...
<p>My workaround is to just use float32 in the model. This does mean I cast the input before passing it into the model, but this can be done by the TensorFlow lite support library. It looks like this might be a bug in the conversion to TensorFlow Lite.</p> <p><code>TensorBuffer imageBuffer = TensorBuffer.createFrom(ima...
tensorflow|keras|tensorflow-lite
0
352,447
64,671,437
Python pandas - Groupby + Conditional count of cells values
<p>I have a table that contains the list of parcel ids, their departure time, arrival time and type or parcel.</p> <p>A minimum working example is given below to illustrate the table.</p> <p>For each line, i am trying to get the number of parcels of similar type (i.e. TV or PC) which departure time is superior or equal...
<p>This works</p> <pre><code>df['number_of_parcels'] = df.groupby('type').apply(lambda x: x.apply(lambda y:( (x['departure_time'] &gt;= y['departure_time']) &amp; (x['departure_time'] &lt; y['arrival_time']) ).sum(), axis=1)).droplevel(level=0) df </code></pre> <p>Out:</p> <pre><code> Parcel_id departure_time ...
python|conditional-statements|pandas-groupby|counting
2
352,448
64,863,468
Appending data from multiple excel files into a single excel file without overwriting using python pandas
<p>Here is my current code below.</p> <p>I have a specific range of cells (from a specific sheet) that I am pulling out of multiple (~30) excel files. I am trying to pull this information out of all these files to compile into a single new file appending to that file each time. I'm going to manually clean up the destin...
<p>Ideally you want to loop through the files and read the data into a list, then concatenate the individual dataframes, then write the new dataframe. This assumes the data being pulled is the same size/shape and the sheet name is the same. If sheet name is changing, look into zip() function to send filename/sheetname ...
python-3.x|excel|pandas
0
352,449
64,852,675
Want to find Year on Year calculation using Groupby and apply for various years
<p>I have a dataframe as follows:</p> <pre><code> MARKET PRODUCT TIMEPERIOD DATE VALUES 0 USA MARKET APPLE QUARTER 2020-06-01 100 1 USA MARKET APPLE YEARLY 2020-06-01 1000 2 USA MARKET PEAR QUARTER 2020-06-01 200 3 USA MARKET PEAR YEARLY 2020-06-01 5000 4 USA MARKET APPLE QU...
<p>You can use <code>itertools.combinations</code> to get the year-year combination, together with further manipulation inside a function to be applied in the groups, like this:</p> <pre><code>import numpy as np import pandas as pd from itertools import combinations def get_annual_growth(grp): # Get all possible c...
python|pandas|dataframe|group-by
2
352,450
64,940,003
slicing periodically for a numpy array
<p>I have a numpy array <code>a = np.arange(100)</code> including 100 numbers. I wondered to know is there a way to slice it periodically rather than using the conditional statements.</p> <p>for example, if I want to slice the 1st four numbers + 5th four numbers + 9th four numbers and so on and finally have all these i...
<p>Code:</p> <pre><code>import numpy as np a = np.arange(100) grp = 4 grp_no = [1,5,9] lst = np.array([a[range(n*grp-4, n*grp)] for n in grp_no]) print(lst) print(lst.flatten()) #if required </code></pre> <p>Output:</p> <pre><code>[[ 0 1 2 3] [16 17 18 19] [32 33 34 35]] [ 0 1 2 3 16 17 18 19 32 33 34 35] </co...
python|python-3.x|numpy|numpy-slicing
1
352,451
64,649,166
conditional replace in pandas dataframe
<p>I have the following dataframe:</p> <p>df:</p> <pre><code>A B C 121 The price is $4M USA 323 The price is $2.2M USA 454 The price is $62K Japan 654 The price is $91M(-21%) Japan 877 The price is $432M(91%) USA </code></pre> <p>I am trying to replace the column B based on the...
<p>You can use <code>mask</code>:</p> <pre><code>df[&quot;B&quot;] = df[&quot;B&quot;].mask(df[&quot;C&quot;].eq(&quot;Japan&quot;), df[&quot;B&quot;].str.replace(&quot;$&quot;, &quot;Y&quot;)) print (df) A B C 0 121 The price is $4M USA 1 323 The price is $2.2M ...
python|pandas|dataframe
2
352,452
64,959,737
Making a Numpy Operation Vectorised
<p>Long story short, I'm applying a function onto multiple different time intervals and then storing the resulting arrays at different indexs in an ndarray. Presently, I'm doing this by using the a <code>for</code> loop with the numpy equivalent of the <code>enumerate</code> function. As I understand it, this eliminate...
<p>Question is not really reproducible because some of the functions that are being called are missing but here is my vectorised implementation of <code>measurement_operator</code>. This is with the assumption that <code>finished_quantum_state</code> has a shape of <code>(P, )</code> (Not sure if that's the case, becau...
python|arrays|numpy
1
352,453
64,709,250
IndexError: index 4 is out of bounds for axis 0 with size 4
<p>Hey I am having this Index Error where I am trying to composite events but my indices start at 0 and not 1 and while have tried to do a number of things like trying to .append[i+1] I am unable to fix this error I am having.</p> <p>Theres apparently something wrong with this specific line of code : <code>dset_IDX[off...
<p>not much info is provided but what i have understood, the error says that axis 0 has size=4 and you are trying to access index 4 which is not possible with size 4 as it starts with 0 and max index could be 3.</p>
python|numpy|index-error
2
352,454
64,648,237
How to convert this numpy one-liner into Tensorflow backend code?
<p>I have multiple depthmaps which show a car from different angles. I need to calculate how well they match together in my loss function, so I have to reproject them into a different view. The depthmaps live in a cube that is relative to the length of the vehicle. The images have the shape (256,256). I already wrote t...
<p>You can do this by using <code>tf.matmul()</code> the first input will be your pointcloud, from the dimensions i am assuming you are storing for every pixel a 3d vector x,y,z. The second input will be the 3d rotation matrix coresponding to the projection you need, keep in mind this works for every angle you want to ...
numpy|tensorflow|keras|backend|loss
0
352,455
64,874,172
Appending data to new row without changing previous one and index number pandas
<p>So i am scraping stock price data every 10 minutes from a website right now i am recording it using the below code to excel.</p> <pre><code>dataframe.to_excel('pricedata.xlsx',engine='xlsxwriter', header=True, index=True) </code></pre> <p>as price changes every 10 minutes i want to append it to previous excel withou...
<p>This should work:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a': [3], 'b': [4]}) s = df.xs(0).copy() s.name = 0 s['a'] = 5 s['b'] = 6 df = df.append(s) print(df) </code></pre> <pre><code> a b 0 3 4 0 5 6 </code></pre>
python|pandas
1
352,456
64,771,881
Pandas convert UNIX time to multiple different timezones depending on column value
<p>I have a pandas dataframe with UNIX timestamps (these are integers and not time objects). The observations occur in multiple geographic locations, and therefore multiple timezones. <strong>I'd like to convert the UNIX timestamp into local time (in a new column) for each of these timezones, based on the geography of ...
<p>Assuming POSIX timestamps (seconds since 1970-01-01 UTC), you can directly convert to UTC with keyword utc=True.</p> <pre><code>import pandas as pd c1=[1546555701, 1546378818, 1546574677, 1546399159, 1546572278] c2=['America/Detroit','America/Chicago','America/Los_Angeles','America/Los_Angeles','America/Detroit'] ...
python|pandas|datetime|timezone|dst
1
352,457
64,717,281
How can I save unknown data types to the database?
<p>I'm preparing a data analysis program with pandas. Users transfer data from the excel file to the program. Column names taken from the Excel file are constantly changing. Therefore, I do not know the column names and data types that I will record in the database. How can I save unfamiliar types of data in the databa...
<p>Relational database are not well suited for storing data do not adhere to a fixed schema.</p> <p>I see two options:</p> <ul> <li><p>Analyze the data you have and create a new table that fits the data before you insert them into the database.</p> <p>The question is what to do with all these tables in PostgreSQL.</p> ...
python|sql|pandas|postgresql|dataframe
2
352,458
64,680,557
How to get permission for file editing in python(pandas)
<p>I am trying to modify existing excel file on Windows using Python via Pandas, but the program gives me an error.</p> <p>This is a sample of my simple program:</p> <pre><code>df_read = pd.read_excel(&quot;C:\\Users\\77888\\Desktop\\HKR_ОТЧЕТЫ\\Ноябрь 2020\\2020-11-03.xlsx&quot;) df = pd.DataFrame({&quot;Время&quot;:[...
<p>The most common cause of this issue on Windows is that the xlsx file being created is already open in Excel. For example:</p> <pre><code># A simple pandas/xlsxwriter program. C:\jmcnamara&gt;type pandas_simple.py import pandas as pd df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]}) writer = pd.ExcelWriter('...
python|pandas
0
352,459
64,721,602
Why would using the same dataset for training and testing gives different accuracies?
<p>I've been looking into the loss function of the training and the validation dataset, and I keep seeing the validation loss being smaller than the training loss, even when they are the same data set. I'm trying to get some insight as to why this would be the case.</p> <p>I am training a model in tensorflow to predict...
<p>They are different because optimizer updates the parameters at the end of each batch and the <code>val_loss</code> will be computed at the end, but the <code>train_loss</code> will be computed in the process.</p> <p>Even if you just have one sample in a batch and just one batch in each epoch, they will differ from e...
python|tensorflow
0
352,460
39,883,715
How to efficiently write a binary file containing mixed label and image data
<p>The <a href="https://github.com/tensorflow/tensorflow/tree/411f57e291839094108afdaa9c43094f44979eaa/tensorflow/models/image/cifar10" rel="nofollow noreferrer">cifar10 tutorial</a> deals with binary files as input. Each record/example on these CIFAR10 datafiles contain mixed label (first element) and image data infor...
<p>When I write binary files I usually just use the python module <em>struct</em>, which works somehow like this:</p> <pre><code>import struct import numpy as np image = np.zeros([2, 300, 300], dtype=np.uint8) label = np.zeros([2, 1], dtype=np.uint16) with open('data.bin', 'w') as fo: s = image.shape for k i...
python|io|tensorflow
1
352,461
40,059,994
Pandas Get a list of index from dataframe.loc
<p>I have looked through various sites and SO posts.Seems easy but somehow i am stuck with this.I am using</p> <pre><code>print frame.loc[(frame['RR'].str.contains("^[^123]", na=False)), 'RR'].isin(series1.str.slice(1)) </code></pre> <p>to get</p> <pre><code>3 True 4 False 8 False Name: RR, dtype: bool </c...
<p>You are testing two conditions on the same column so these can be combined (and negated):</p> <pre><code>frame[~((frame['RR'].str.contains("^[^123]", na=False)) &amp; (frame['RR'].isin(series1.str.slice(1))))] </code></pre> <p>Here, after <code>~</code> operator, it checks whether a particular row satisfies both c...
python|python-2.7|pandas
1
352,462
40,165,154
Extra lane in heat map (pandas)
<p>Here is my <a href="https://www.dropbox.com/s/0ymrbo7v9vxpjhu/extra_line.csv?dl=0" rel="nofollow">file</a></p> <p>I plot heat map from it using the following code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt new = pd.read_csv(r'path_to_file') full_list=new.columns.values new = new[full_list...
<p>There is nothing wrong. First, this has nothing to do with pandas, so we can leave that out and consider the following example</p> <pre><code>import matplotlib.pyplot as plt import numpy as np a = np.random.randint(0,10,size=(11, 2)) plt.pcolor(a, cmap='Blues') plt.show() </code></pre> <p>We create an array with...
pandas|matplotlib|heatmap
2
352,463
39,886,037
How to search datetime index and place None-values to another variables whenever it is weekend Python
<p>Say that I have a pandas <code>df</code> which contains financial time-series data with datetime index. An example: </p> <pre><code>x = ['10-06-2016', '10-07-2016', '10-10-2016', '10-11-2016', '10-12-2016'] y = [0,1,2,3,4] </code></pre> <p>Note that I don't have time-series values on weekends, which is why '10-0...
<p>You can <code>reindex</code> the data frame which has a <code>datetimeIndex</code> with a wider range of date as follows, missing values will be filled with <code>NaN</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Value': y}, index=pd.to_datetime(x)) # Value #2016-10-06 0 #2016-10-07 1 #2016-...
python|datetime|pandas
0
352,464
39,890,147
Keras uses way too much GPU memory when calling train_on_batch, fit, etc
<p>I've been messing with Keras, and like it so far. There's one big issue I have been having, when working with fairly deep networks: When calling model.train_on_batch, or model.fit etc., Keras allocates significantly more GPU memory than what the model itself should need. This is not caused by trying to train on some...
<p>It is a very common mistake to forget that the activations, gradients and optimizer moment tracking variables also take VRRAM, not just the parameters, increasing memory usage quite a bit. The backprob calculations themselves make it so the training phase takes almost double the VRAM of forward / inference use of th...
memory|tensorflow|keras|theano
21
352,465
39,880,920
Compute the median of dynamic time series
<p>If I have a pandas series [a1,a2,a3,a4,...] with length = T. Each value corresponds to one day. For each day, I would like to compute the historical median. For example, the first day compute the median of [a1]; the second day compute the median of [a1,a2]; the nth day compute the median of [a1,a2,...,an]. Finally I...
<p>For a Series, <code>ser</code>:</p> <pre><code>ser = pd.Series(np.random.randint(0, 100, 10)) </code></pre> <p>If your pandas version is 0.18.0 or above, use:</p> <pre><code>ser.expanding().median() Out: 0 0.0 1 25.0 2 50.0 3 36.5 4 33.0 5 36.0 6 33.0 7 36.0 8 33.0 9 36.0 dtype: fl...
python|pandas
0
352,466
39,932,920
How to sample image tensor in tensorflow
<p>I have one image data tensor with shape of <code>B*H*W*C</code> and one position tensor with shape of <code>B*H*W*2</code>. The values in position tensor are pixel coordinates and I want to sample pixels in image data tensor according to these pixel coordinates. I have tried one way to do that like reshaping the ten...
<p>I would first ask if you are sure the position matrix isn't redundant. If the position matrix entries simply correspond to the pixel locations in the image array, then for a given application however you access the position matrix could be used instead on the image data.</p> <p>Perhaps as a starting point, running<...
tensorflow|tensorboard
0
352,467
40,115,405
Initialize placeholder if value is not provided
<p>Is there an elegant way to specify a default value for a placeholder?</p> <p>If you specify a value in the <code>run(feed_dict=...)</code> then uses that value otherwise it defaults to a given value that you specify at build time.</p>
<p>I just found it myself: </p> <pre><code>tf.placeholder_with_default(input, shape, name=None) </code></pre>
tensorflow
8
352,468
40,098,300
Use a list to conditionally fill a new column based on values in multiple columns
<p>I am trying to populate a new column within a pandas dataframe by using values from several columns. The original columns are either <code>0</code> or '1' with exactly a single <code>1</code> per series. The new column would correspond to df['A','B','C','D'] by populating <code>new_col = [1, 3, 7, 10]</code> as show...
<p>I can think of a few ways, mostly involving <code>argmax</code> or <code>idxmax</code>, to get either an ndarray or a Series which we can use to fill the column.</p> <p>We could drop down to <code>numpy</code>, find the maximum locations (where the 1s are) and use those to index into an array version of new_col:</p...
python|list|python-2.7|pandas
2
352,469
40,095,325
Covariance matrix from np.polyfit() has negative diagonal?
<p><strong>Problem:</strong> the <code>cov=True</code> option of <code>np.polyfit()</code> produces a diagonal with non-sensical negative values.</p> <p><strong>UPDATE:</strong> after playing with this some more, I am <em>really starting to suspect a bug in numpy</em>? Is that possible? Deleting any pair of 13 values ...
<p>It looks like it's related to your x values: they have a total range of about 3, with an offset of about 1.5 billion.</p> <p>In your code</p> <pre><code>np.asarray(x) </code></pre> <p>converts the x values in a ndarray of float64. While this is fine to correctly represent the x values themselves, it might not be ...
python|python-2.7|numpy|statistics|linear-regression
2
352,470
39,922,986
How do I Pandas group-by to get sum?
<p>I am using this dataframe:</p> <pre><code>Fruit Date Name Number Apples 10/6/2016 Bob 7 Apples 10/6/2016 Bob 8 Apples 10/6/2016 Mike 9 Apples 10/7/2016 Steve 10 Apples 10/7/2016 Bob 1 Oranges 10/7/2016 Bob 2 Oranges 10/6/2016 Tom 15 Oranges 10/6/2016 Mike 57 Oranges 10/6/2016 Bob 65 O...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.sum.html" rel="nofollow noreferrer"><code>GroupBy.sum</code></a>:</p> <pre><code>df.groupby(['Fruit','Name']).sum() Out[31]: Number Fruit Name Apples Bob 16 Mike 9 ...
python|pandas|dataframe|group-by|aggregate
402
352,471
40,180,737
How to get data from pickle files into a pandas dataframe
<p>I'm working on a social media sentiment analysis for a class. I have gotten all of the tweets about the Kentucky Derby for a 2 month period saved into pkl files.</p> <p>My question is: how do I get all of these pickle dump files loaded into a dataframe?</p> <p>Here is my code:</p> <pre><code>import sklearn as sk...
<p>You can use </p> <ol> <li><code>pd.read_pickle(filename)</code></li> <li>add it to a list</li> <li>then <code>pd.concat(thelist)</code></li> </ol>
python|pandas|twitter|pickle
10
352,472
40,118,240
get, access and modify element values for an numpy array
<p>I once saw the following code segment</p> <pre><code>import numpy as np nx=3 ny=3 label = np.ones((nx, ny)) mask=np.zeros((nx,ny),dtype=np.bool) label[mask]=0 </code></pre> <p>The <code>mask</code> generated is a bool array</p> <pre><code>[[False False False] [False False False] [False False False]] </code></pr...
<p>Here is a code snippet with some comments that might help you make sense of this. I would suggest you look into the link that @Divakar provided and look into <a href="https://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">boolean-indexing</a>. </p> <pre><code...
python|numpy|scipy
0
352,473
39,966,021
align rows by date in pandas dataframe
<p>An excerpt of the Dateframe could look like this (it's certainly much larger):</p> <pre><code> Date1 Log1 Date2 Log2 Date3 Log3 Index 0 01.01.2000 1000 02.01.2000 2000 01.01.2000 3000 1 02.01.2000 1050 03.01.2000 1950 02.01.2000 3020 2 ...
<p>I am assuming you only want to keep values from ['Date2', 'Log2'] and ['Date3', 'Log3'] when the dates have a match in Date1.</p> <p>You can read the different columns into separate dataframes and use <code>merge</code>. Then filter to only keep rows where the Date1 column is not null.</p> <pre><code>df &gt;&gt;&g...
python|pandas|dataframe
2
352,474
39,890,785
google cloud machine learning hyperparameter tuning avoid Nans
<p>I am running google cloud machine learning beta - and use the hypertune setup with tensorflow.</p> <p>In some of the sub runs of hyperparameter tuning I have losses becoming NaNs - and that crashes the computations - which in turns stop the hyperparameter tuning job. </p> <pre><code>Error reported to Coordinator: ...
<p>You should protect the loss function by checking for NaNs. Any crash or exception thrown by the program is treated by Cloud ML as a failure of the trial, and if enough trials fail the entire job will be failed.</p> <p>If the trial exits cleanly without setting any hyperparameter summaries, the trial will be consid...
python|machine-learning|tensorflow|google-cloud-ml
1
352,475
40,190,402
python - pass 3d array to C code
<p>How to pass 3D python array to C code then get return back? I have researched,</p> <ul> <li><a href="https://stackoverflow.com/questions/22425921/pass-a-2d-numpy-array-to-c-using-ctypes">Pass a 2d numpy array to c using ctypes</a></li> </ul> <p>I have tried for 2D</p> <p>Source : - <a href="http://cboard.cprogra...
<p>Finally, I solved my problem, (Thanks to Evert for suggestion)</p> <p>c_multiply.c</p> <pre><code>#include "c_multiply.h" #include &lt;stdio.h&gt; void ccmultiply4d(double* array, double multiplier, int m, int n, int o, int p) { int i, j,k, l ; for (i = 0; i &lt; m; i++) for (j = 0; j &lt; n; j++...
python|c|numpy|ctypes
-1
352,476
40,100,340
numpy multivariate_normal bug when dimension too high
<p>I am working on a homework assignment and I noticed that when the dimension of mean and covariance is very high, <code>multivariate_normal</code> will occupy all CPU forever, without generating any results. </p> <p>An example code snippet, </p> <pre><code>cov_true = np.eye(p) mean_true = np.zeros(p) beta_true = m...
<p><strong>What takes so much time?</strong></p> <p>To account for relations between variables NumPy <a href="https://github.com/numpy/numpy/blob/v1.11.2/numpy/random/mtrand/mtrand.pyx#L4716" rel="nofollow">computes the singular value decomposition</a> of your covariance matrix and this takes the majority of the time ...
python|numpy
4
352,477
39,757,188
How can I make a python candlestick chart clickable in matplotlib
<p>I am trying to make a OHLC graph plotted with matplotlib interactive upon the user clicking on a valid point. The data is stored as a pandas dataframe of the form </p> <pre><code>index PX_BID PX_ASK PX_LAST PX_OPEN PX_HIGH PX_LOW 2016-07-01 1.1136 1.1137 1.1136 1.1106 1.1169 1.1072 2016-07-04 ...
<p>You need to set <code>set_picker(True)</code> to enable a pick event or give a tolerance in points as a float (see <a href="http://matplotlib.org/api/artist_api.html#matplotlib.artist.Artist.set_picker" rel="nofollow">http://matplotlib.org/api/artist_api.html#matplotlib.artist.Artist.set_picker</a>).</p> <p>So in ...
python|pandas|matplotlib|graph|interactive
1
352,478
39,815,625
Python Pandas - Index' object has no attribute 'hour'
<p>I have a pandas dateframe and the following code works</p> <pre><code>df['hour'] = df.index.hour df['c'] = df['hour'].apply(circadian) </code></pre> <p>but i was trying to reduce the need to make a 'hour' coloumn, using the following code</p> <pre><code>df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=1...
<p><strong>Approach 1:</strong> </p> <p>Convert the <code>DateTimeIndex</code> to <code>Series</code> and use <code>apply</code>.</p> <pre><code>df['c'] = df.index.to_series().apply(lambda x: circadian(x.hour)) </code></pre> <p><strong>Approach 2:</strong></p> <p>Use <code>axis=0</code> which computes along the r...
python|pandas|apply
13
352,479
39,795,138
How to put these outputs into 9 by 9 array using Numpy array
<p>sorry if this is a basic question. I am just starting with python and programming.</p> <p>I want the output from iteration in a 9 by 9 array. For now I just get the output in one column.</p> <pre><code>for q in range(11,20,1): for x in range(11,20,1): if q &lt;= x: V = 3.5*q ‐ 1.5 * x ...
<p>Your problem is exactly what the error says: you are trying to access index 11 in a an array of size 9 (by 9).</p> <p><code>for q in range(11,20):</code> is iterating over <code>q = 11, 12, 13,..., 19</code>. Then <code>V[q][x]</code> is trying to access element with indexes <code>q</code> and <code>x</code> in <c...
python|arrays|numpy|multidimensional-array
1
352,480
39,864,921
Weighted K-means with GPS Data
<p><strong>OBJECTIVE</strong></p> <ul> <li><p>Aggregate store locations GPS information (longitude, latitude) </p></li> <li><p>Aggregate size of population in surrounding store area (e.g 1,000,000 residents) </p></li> <li>Use K-means to determine optimal distribution centers, given store GPS data and local population ...
<p>1) You only want to do k-means in the (longitude, latitude) space. If you add population as a 3rd dimension, you will bias your centroids towards the midpoint between large population centres, which are often far apart.</p> <p>2) The simplest hack to incorporate a weighting in k-means is to repeat a point (longitud...
python|numpy|statistics|k-means
3
352,481
39,562,113
Error on using xarray open_mfdataset function
<p>I am trying to combine multiple netCDF files with the same dimensions, their dimensions are as follows:</p> <pre><code>OrderedDict([(u'lat', &lt;type 'netCDF4._netCDF4.Dimension'&gt;: name = 'lat', size = 720 ), (u'lon', &lt;type 'netCDF4._netCDF4.Dimension'&gt;: name = 'lon', size = 1440 ), (u'time', &lt;type 'net...
<p>This error message is probably arising because you have two files with the same variables and coordinate values, and xarray doesn't know whether it should stack them together along a new dimension or simply check to make sure none of the values conflict.</p> <p>It would be nice if explicitly calling <code>open_mfda...
python|numpy|netcdf|python-xarray|netcdf4
3
352,482
39,858,543
How to handle NA values when tokenizing the contents of a data frame?
<p>I have a pandas dataframe and I am trying to tokenize the contents of each row. </p> <pre><code>import pandas as pd import nltk as nk from nltk import word_tokenize TextData = pd.read_csv('TextData.csv') TextData['tokenized_summary'] = TextData.apply(lambda row: nk.word_tokenize(row['Summary']), axis=1) </code></p...
<p>You can use <code>fillna()</code> to replace NaN with a specified value:</p> <pre><code>import pandas as pd import nltk as nk from nltk import word_tokenize TextData = pd.read_csv('TextData.csv') TextData.fillna('some value') # or just: TextData['Summary'].fillna('some value') TextData['tokenized_summary'] = TextDa...
python|pandas|nltk
2
352,483
39,840,890
How to Use Lagged Time-Series Variables in a Python Pandas Regression Model?
<p>I'm creating time-series econometric regression models. The data is stored in a Pandas data frame.</p> <p><strong>How can I do lagged time-series econometric analysis using Python</strong>? I have used Eviews in the past (which is a standalone econometric program i.e. not a Python package). To estimate an OLS equat...
<p>pandas allows you to shift your data without moving the index such has</p> <pre><code>df.shift(-1) </code></pre> <p>will create a 1 index lag behing</p> <p>or</p> <pre><code>df.shift(1) </code></pre> <p>will create a forward lag of 1 index</p> <p>so if you have a daily time series, you could use df.shift(1) to...
python|pandas|time-series|regression
26
352,484
39,818,381
How to reindex a python array to move polyline starting point?
<p>I have a python array defining the points for a polyline P(x,y,z). I need to align the points with points on another polyline - to be precise, the point with index 0 on polyline 1 should be close to the point with index 0 of the second polyline. </p> <p>Think of a polyline circle. How can I move the "index number" ...
<p>To shift to left by x points(assuming x is less than the length of array):</p> <pre><code>newPolyline = polyline[x:] + polyline[:x] </code></pre> <p>To shift right:</p> <pre><code>newPolyline = polyline[len(polyline) - x:] + polyline[:len(polyline) - x] </code></pre>
python|arrays|numpy
0
352,485
39,604,094
Pandas delete all rows that are not a 'datetime' type
<p>I've got a large file with login information for a list of users. The problem is that the file includes other information in the <code>Date</code> column. I would like to remove all rows that are not of type <code>datetime</code> in the <code>Date</code> column. My data resembles</p> <p><code>df</code>:</p> <div cla...
<p>Use <code>pd.to_datetime</code> with parameter <code>errors='coerce'</code> to make non-dates into <code>NaT</code> null values. Then you can drop those rows</p> <pre><code>df['Date'] = pd.to_datetime(df['Date'], errors='coerce') df = df.dropna(subset=['Date']) df </code></pre> <p><a href="https://i.stack.imgur....
python|pandas|dataframe
45
352,486
39,421,433
Efficient way to find null values in a dataframe
<pre><code>import pandas as pd import numpy as np df = pd.read_csv ('file',low_memory=False) df_null = df.isnull() mask = (df_null == True) i, j = np.where(mask) print (list(zip(df_null.columns[j], df['Column1'][i]))) </code></pre> <p>This is what I currently have. Essentially, I've created two dataframes and from t...
<p>A routine that I normally use in pandas to identify null counts by columns is the following:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv("test.csv") null_counts = df.isnull().sum() null_counts[null_counts &gt; 0].sort_values(ascending=False) </code></pre> <p>This will...
python|pandas|numpy
3
352,487
39,613,228
Pandas: concatenate dataframes
<p>I have 2 dataframe</p> <pre><code>category count_sec_target 3D-шутеры 0.09375 Cериалы 201.90625 GPS и ГЛОНАСС 0.015625 Hi-Tech 187.1484375 Абитуриентам 0.8125 Авиакомпании 8.40625 </code></pre> <p>and </p> <pre><code>category count_sec_random 3D-шутеры 0.369565217 Hi-Tech 70.42391304...
<pre><code>df3 = pd.concat([d.set_index('category') for d in frames], axis=1).fillna(0) df3['ratio'] = df3.count_sec_random / df3.count_sec_target df3 </code></pre> <p><a href="https://i.stack.imgur.com/Xp8Dg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xp8Dg.png" alt="enter image description her...
python|pandas|dataframe
5
352,488
39,581,893
pandas: find percentile stats of a given column
<p>I have a pandas data frame my_df, where I can find the mean(), median(), mode() of a given column:</p> <pre><code>my_df['field_A'].mean() my_df['field_A'].median() my_df['field_A'].mode() </code></pre> <p>I am wondering is it possible to find more detailed stats such as 90 percentile? Thanks!</p>
<p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.quantile.html" rel="noreferrer">pandas.DataFrame.quantile()</a> function, as shown below. </p> <pre><code>import pandas as pd import random A = [ random.randint(0,100) for i in range(10) ] B = [ random.randint(0,100) fo...
python|python-2.7|pandas|statistics
142
352,489
39,518,414
textsum beam search decoder gives all <UNK> results
<p>I have been testing textsum with both the binary data and gigaword data, trained models and tested. The beam search decoder gives me all 'UNK' results with both set of data and models. I was using the default parameter settings. </p> <p>I first changed the data interface in data.py and batch_reader.py to read and p...
<p>I think I found why it is happening with at least the given toy data set. In my case, I trained and tested with the same toy set given (the data &amp; vocab files). The reason why I'm getting [UNK]s in decoder result is the vocab file doesn't contain any words that appear in the summaries of toy data set. Due to th...
tensorflow|textsum
2
352,490
39,714,724
pandas .plot() x-axis tick frequency -- how can I show more ticks?
<p>I am plotting time series using pandas .plot() and want to see every month shown as an x-tick. </p> <p>Here is the dataset structure <a href="https://i.stack.imgur.com/8OOw4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8OOw4.png" alt="data set"></a></p> <p>Here is the result of the .plot()</p> <p><a ...
<p>No need to pass any args to <code>MonthLocator</code>. Make sure to use <code>x_compat</code> in the <code>df.plot()</code> call per @Rotkiv's answer.</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pylab as plt import matplotlib.dates as mdates df = pd.DataFrame(np.random.rand(100,2), index...
pandas|datetime|matplotlib|time-series
27
352,491
39,860,269
Modifying a pandas dataframe that may be a view
<p>I have a pandas <code>DataFrame</code> <code>df</code> that is returned from a function and I generally don't know whether it is an independent object or a view on another <code>DataFrame</code>. I want to add new columns to it but don't want to copy it unnecessarily.</p> <pre><code>df['new_column'] = 0 </code></pr...
<p>you should use an indexer to create your s1 such has:</p> <pre><code>import pandas as pd s = pd.DataFrame({'a':[1,2], 'b':[2,3]}) indexer = s[s.a &gt; 1].index s1 = s.loc[indexer, :] s1['c'] = 0 </code></pre> <p>should remove the warning.</p>
python|pandas
0
352,492
39,597,671
Dropout on test somehow causes LSTM performance failure
<p>I have a problem with TensorFlow where the performance of my LSTM drops dramatically (from 70% to &lt;10%) when I use input dropout. </p> <p>As I understand it I should set the input_keep_probability to (e.g.) 0.5 during training and then to 1 during testing. This makes perfect sense, but I cant get it to work as i...
<p>Try input_keep_prob = output_keep_prob = 0.7 for training and 1.0 keep prob for testing</p> <p>0.5 keep prob doesn't work well om my LSTM either</p>
tensorflow
0
352,493
39,554,292
why it is saying at i have declare kernel
<pre><code> import numpy as np from numpy.fft import fft2, ifft2 import cv2 from PIL import Image def wiener_filter(img,kernel,K = 10): kernel=([3,1],[2,1]) dummy = np.copy(img) kernel = np.pad(kernel, [(0, dummy.shape[0] - kernel.shape[0]), (0, dummy.shape[1] - kernel.shape[1...
<p>There : </p> <pre><code>def wiener_filter(img,kernel,K = 10): kernel=([3,1],[2,1]) </code></pre> <p>You define a function that takes <code>kernel</code> as a parameter and you overwrite it directly.</p> <p>Then you try to use <code>kernel.shape</code> which obviously doesn't exist in <code>([3,1],[2,1])</code...
python|numpy
2
352,494
39,419,178
How can I manage units in pandas data?
<p>I'm trying to figure out if there is a good way to manage <em>units</em> in my pandas data. For example, I have a <code>DataFrame</code> that looks like this:</p> <pre><code> length (m) width (m) thickness (cm) 0 1.2 3.4 5.6 1 7.8 9.0 1.2 2 3.4 ...
<p>There isn't any great way to do this right now, see github issue <a href="https://github.com/pydata/pandas/issues/10349" rel="noreferrer">here</a> for some discussion.</p> <p>As a quick hack, could do something like this, maintaining a separate dict with the units.</p> <pre><code>In [3]: units = {} In [5]: newcol...
python|pandas|units-of-measurement|custom-formatting
16
352,495
39,578,611
geopandas AttributeError: 'MultiPolygon' object has no attribute 'exterior'
<p>I have two GeoDataFrame. One is of the state of Iowa, while the other is of foretasted rain over the next 72 hours for North America. I want to create a GeoDataFrame of the rain forecast where it overlies the state of Iowa. But I get an error.</p> <pre><code>state_rain = gpd.overlay(NA_rain,iowa,how='intersection...
<p>I agree with @jdmcbr. I suspect that at least one of the features in <code>NA_rain</code> is a MultiPolygon which did not get detected since the condition you showed is misspelled (<code>MulitPolygon</code> instead of <code>MultiPolygon</code>).</p> <p>If your dataframe has MultiPolygons, you can convert all of them...
python|pandas|polygon|shapely|geopandas
0
352,496
39,816,610
pandas has no attribute read_html raspberry pi
<pre><code>import pandas as pd f_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states') </code></pre> <p>So above script works fine when calling it directly in the python shell:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; f_states = pd.read_html('https://simple.wikipedia.org...
<p>You need to update pandas, use:</p> <pre><code>pip install pandas==1.3 </code></pre>
python-2.7|pandas|raspberry-pi
-2
352,497
39,822,276
numpy multidimensional (3d) matrix multiplication
<p>I get two 3d matrix A (32x3x3) and B(32x3x3), and I want to get matrix C with dimension 32x3x3. The calculation can be done using loop like:</p> <pre><code>a = numpy.random.rand(32, 3, 3) b = numpy.random.rand(32, 3, 3) c = numpy.random.rand(32, 3, 3) for i in range(32): c[i] = numpy.dot(a[i], b[i]) </code></p...
<p>You could do this using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>:</p> <pre><code>In [142]: old = orig(a,b) In [143]: new = np.einsum('ijk,ikl-&gt;ijl', a, b) In [144]: np.allclose(old, new) Out[144]: True </code></pre> <p>One advant...
python|numpy|matrix|multidimensional-array|matrix-multiplication
4
352,498
39,435,218
python pandas elegant dataframe access rows 2:end
<p>I have a dataframe, <code>dF = pd.DataFrame(X)</code> where X is a numpy array of doubles. I want to remove the last row from the dataframe. I know for the first row I can do something like this <code>dF.ix[1:]</code>. I want to do something similar for the last row. I know in matlab you could do something like this...
<p>you can do it this way:</p> <pre><code>In [129]: df1 Out[129]: c1 c2 c3 0 1 2 3 1 4 5 6 2 7 8 9 In [130]: df2 Out[130]: c1 c2 c3 0 a b c 1 d e f 2 g h i In [131]: df1.iloc[1:].reset_index(drop=1).join(df2.iloc[:-1].reset_index(drop=1), rsuffix='_2') Out[131]: c1 c2 c3 c1_2 c...
python|matlab|pandas|numpy
0
352,499
39,593,821
Convert a dict to a pandas DataFrame
<p>My data look like this : </p> <pre><code>{u'"57e01311817bc367c030b390"': u'{"ad_since": 2016, "indoor_swimming_pool": "No", "seaside": "No", "handicapped_access": "Yes"}', u'"57e01311817bc367c030b3a8"': u'{"ad_since": 2012, "indoor_swimming_pool": "No", "seaside": "No", "handicapped_access": "Yes"}'} </code></pre> ...
<p>You need convert column of <code>type</code> <code>str</code> to <code>dict</code> by <code>.apply(literal_eval)</code> or <code>.apply(json.loads)</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html" rel="nofollow"><code>DataFrame.from_records</code>...
python|json|pandas
2