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
359,400
51,166,473
Pandas - Create df from list of dicts
<p>I have data in the following format (list of dicts that each contain a list of 3 lists):</p> <pre><code>[{40258: [['2018-07-03T14:13:41'], ['Open'], ['Closed']]}, {40257: [['2018-07-03T13:47:55', '2018-07-03T14:21:52', '2018-07-04T11:56:44'], ['Open', 'In Progress', 'Waiting on 3rd Party'], ['In Prog...
<pre><code>data=[{40258: [['2018-07-03T14:13:41'], ['Open'], ['Closed']]}, {40257: [['2018-07-03T13:47:55', '2018-07-03T14:21:52', '2018-07-04T11:56:44'], ['Open', 'In Progress', 'Waiting on 3rd Party'], ['In Progress', 'Waiting on 3rd Party', 'In Progress']]}, {40255: [['2018-07-03T13:12:58'], ['O...
python|pandas|dictionary
4
359,401
51,250,669
Reading csv file from S3 and converting it to xlsx using Python
<p>I have a big csv file in S3 and i cam concatenating it with another csv file in S3. I am using pandas dataframe in python to do this in AWS lambda. I also have to save the concatenated data frame to xlsx format in S3 using the same lambda. Is there a way to do this?</p> <pre><code>import pandas as pd import os impo...
<p>You can do this by following code :</p> <pre><code>writer = pd.ExcelWriter('test.xlsx') df_new.to_excel(writer) </code></pre>
python|pandas|amazon-s3|aws-lambda|xlsx
1
359,402
51,200,369
Shift rows of a numpy array independently
<p>This is an extension of the question posed <a href="https://stackoverflow.com/questions/20360675/roll-rows-of-a-matrix-independently">here</a> (quoted below)</p> <blockquote> <p>I have a matrix (2d numpy ndarray, to be precise):</p> <pre><code>A = np.array([[4, 0, 0], [1, 2, 3], [0, 0...
<p>Inspired by <a href="https://stackoverflow.com/a/51613442/">Roll rows of a matrix independently's solution</a>, here's a vectorized one based on <a href="http://www.scipy-lectures.org/advanced/advanced_numpy/#indexing-scheme-strides" rel="nofollow noreferrer"><code>np.lib.stride_tricks.as_strided</code></a> -</p> <...
python|arrays|numpy
7
359,403
51,356,116
Pandas replace not working
<p>I have a dataframe res and the following code is not working for a big dataset. But is working for small data. What has to be done to make working?</p> <pre><code>res['Em'].replace(0,"Zero") res = res.replace(True, pd.Series(res.columns, res.columns)) res = res.replace(False, "F") </code></pre> <p>Data Looks like ...
<p>I myself found the issue. I replaced </p> <pre><code>res['Em'].replace(0,"Zero") res = res.replace(True, pd.Series(res.columns, res.columns)) res = res.replace(False, "F") </code></pre> <p>with</p> <pre><code>res['Em'] = res['Em'].replace('0',"Zero") res = res.replace('True', pd.Series(res.columns, res.columns)) ...
python|pandas|dataframe
0
359,404
51,506,897
How do I dynamically create a new dataframe from iterating over multiple values?
<p>New to python.</p> <p>I have this data: </p> <pre><code>sample = pd.DataFrame({'CustomerID': ['1', '2', '3', '4', '5', '6'], 'Date': np.random.choice(pd.Series(pd.date_range('2018-01-01', freq='D', periods=180)), 6), 'Period': np.random.uniform(50, 200, 6), }, columns=['CustomerID', 'D...
<p>For <code>sample</code> as below:</p> <pre><code> CustomerID Date Period 0 1 2018-01-16 152 1 2 2018-06-28 109 2 3 2018-03-07 59 3 4 2018-03-30 172 4 5 2018-01-07 92 5 6 2018-05-22 164 </code></pre> <p>First, let's specify an e...
python|pandas|numpy|datetime|for-loop
1
359,405
51,349,829
How to pass user defined function inside TfidfVectorizer.fit_transform()
<p>I have function for text preprocessing which is simply removing stopwords as:</p> <pre><code>def text_preprocessing(): df['text'] = df['text'].apply(word_tokenize) df['text']=df['text'].apply(lambda x: [item for item in x if item not in stopwords]) new_array=[] for keywords in df['text']: #converts ...
<p>Rather than building additional functions for stop-word removal you can simply pass a custom list of stop-words to TfidfVectorizer. As you can see in the example below "test" is successfully excluded from the Tfidf vocabulary. </p> <pre><code>import numpy as np import pandas as pd from sklearn.feature_extraction.te...
python-3.x|pandas|user-defined-functions|tfidfvectorizer|natural-language-processing
0
359,406
51,139,234
OpenCv and TensorFlow AttributeError: module 'cv2.dnn' has no attribute 'readNetFromTensorFlow'
<p>When I execute this line of code</p> <pre><code>net = cv2.dnn.readNetFromTensorFlow(args["model"]) </code></pre> <p>python3.6 x86 says AttributeError: module 'cv2.dnn' has no attribute 'readNetFromTensorFlow'</p>
<p>I also encountered the same problem, and I found it is caused by a typo. It should be</p> <p><code>net = cv2.dnn.readNetFromTensorflow(args["model"])</code></p> <p>the "f" of Tensorflow should be lower case.</p> <p>Check out the document <a href="https://docs.opencv.org/trunk/d6/d0f/group__dnn.html#gad820b280978d...
python|opencv|tensorflow
0
359,407
51,163,175
How to take mean of one column while filtering by another column's criteria in python
<p>I am working in Python (normally an R guy) and I am trying to create this function for a specific application. Basically, I am trying to take the mean of the column "CallsPresented" for each month in the "Month_of_Year" column. I know I am making this more complex than I need to. How should I accomplish this?</p>...
<p>Why not just <code>groupBy</code> the month column and calculate the <code>mean</code> for each group?</p> <p>Something like </p> <pre><code>def get_monthly_mean(df): df_grouped = df.groupby('Month_of_Year')['CallsPresented'].mean() #Then you can pass the column to a list or just return the grouped df, ...
python|python-3.x|pandas|numpy|anaconda
1
359,408
51,138,775
If statement with two conditions
<p>I have a large pandas sheet where I want to manipulate the wind direction based on the components of the wind speed. Currently I have this:</p> <pre><code>u=new2_df["U component of wind at 850 Mb over the landfall grid point"].values v=new2_df["v component of wind at 850 Mb over the landfall grid point"].values win...
<blockquote> <p>I want to essentially make my code so that it will change individual elements based on the logic tests I have provided.</p> </blockquote> <p>If I understand correctly, you can use a Boolean array with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow nore...
python|arrays|numpy
2
359,409
48,056,568
Add Time column by adding timedelata in pandas
<p>i have a pandas dataframe df:</p> <pre><code>id value mins 1 a 12.4 2 u 14.2 3 i 16.2 3 g 17.0 </code></pre> <p>i have a datetime.datetime variable:</p> <pre><code>current_time = datetime.datetime(2018, 1, 2, 14, 0, 34, 628481) </code></pre> <p>i want to...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>to_timedelta</code></a> with <code>T</code> for minutes:</p> <pre><code>df['total_time'] = current_time + pd.to_timedelta(df['mins'], unit='T') print (df) id value mins ...
pandas
1
359,410
48,189,818
undefined symbol: _ZTIN10tensorflow8OpKernelE
<p>I just updated tensorflow with pip3 (now to version 1.4.1). After it I am having problems:</p> <p>I have a custom op library that I compile with -D _GLIBCXX_USE_CXX11_ABI=0. The library compiles and links fine. Importing it into tensorflow gives:</p> <pre><code>Traceback (most recent call last): ... File "../x...
<p>I was compiling and linking in two different steps in my make file, and just using the proper link flags when linking wasn't enough. I also had to pass the argument <code>-Wl,--no-as-needed</code> to the linker, because for some reason gcc was discarding the library in the final module (as shown by ldd).</p> <p>So ...
tensorflow|undefined|symbols
2
359,411
47,998,782
using .to_period() to get end of business month in python
<p>I say a post that allowed me to get month end in an dataframe index but it only provided Calendar month end and I wanted BUSINESS month end</p> <pre><code>df_mth_return.index = df_mth_return.index.to_period('M').to_timestamp('M') df_mth_return </code></pre> <p>this is a snipit of my resulting data frame. So you c...
<p>Can use <code>BMonthEnd</code> with <code>date_range</code></p> <pre><code>In [28]: pd.date_range('19920101', '19920630', freq=dt.BMonthEnd()) Out[28]: DatetimeIndex(['1992-01-31', '1992-02-28', '1992-03-31', '1992-04-30', '1992-05-29', '1992-06-30'], dtype='datetime64[ns]', freq='BM', ...
python|pandas
1
359,412
48,405,896
Find multiple strings in a given column
<p>I'm not sure whether it is possible to do easily. </p> <p>I have 2 dataframes. In the first one (df1) there is a column with texts ('Texts') and in the second one there are 2 columns, one with some sort texts ('subString') and the second with a score ('Score').</p> <p>What I want is to sum up all the scores associ...
<p><strong>Option 1</strong></p> <pre><code>In [691]: np.array([np.where(df1.Texts.str.contains(x.SubString), x.Score, 0) for _, x in df2.iterrows()] ).sum(axis=0) Out[691]: array([ 0.75, 0. , -0.3 , 0.2 , 0.45, 0.2 ]) </code></pre> <p><strong>Option 2</strong></p> <pre><...
pandas
1
359,413
48,286,179
Difference in the way of representation of timestamp in the provided dataset and the one generated by pandas.datetime
<p>I was having trouble manipulating a time-series data provided to me for a project. The data contains the number of flight bookings made on a website per second in a duration of 30 minutes. Here is a part of the column containing the timestamp</p> <pre><code>&gt;&gt;&gt; df['Date_time'] 0 7/14/2017 2:14:14 PM ...
<p>Can you check the dtype of the 'Date_time' column and confirm for me that it is string (object) ?</p> <pre><code>df.dtypes </code></pre> <p>If so, you should be able to cast the values to pd.Timestamp by using the following.</p> <pre><code>df['timestamp'] = df['Date_time'].apply(pd.Timestamp) </code></pre> <p>Wh...
python|pandas|datetime|timestamp
1
359,414
48,111,790
Read ".db" dictionary type file into pandas DataFrame
<p>How can I import a file with data as below, into a pandas DataFrame? Its saved as "data.db", a format unfamiliar to me.</p> <pre><code>{"hostname":"136.243.73.66","ip":"136.243.73.66","port":16600,"TCPPort":15600,"UDPPort":14600,"seen":1,"connected":0,"tried":0,"weight":1,"dateTried":null,"dateLastConnected":null,"...
<p><code>.db</code> is not a specific file type, although it's often used for sqlite files. This however appears to just be a series of JSON documents, one per line. </p> <pre><code>with open(file_path) as f: return [json.loads(x) for x in f] </code></pre>
python|pandas|dataframe|import
1
359,415
48,083,093
Pandas: per individual, find number of records that are near the current observation. Apply vs transform
<p>Suppose I have several records for each person, each with a certain date. I want to construct a column that indicates, <strong><em>per person</em></strong>, the number of other records that are less than 2 months old. That is, I focus just on the records of, say, individual 'A', and I loop over his/her records to se...
<h3>Edited to count recent records <em>per person</em></h3> <p>Here's one way to count all records strictly newer than 2 months <strong><em>for each person</em></strong> using a lookback window of exactly two calendar months minus 1 day (as opposed to an approximate 2-month window of 60 days or something).</p> <pre><...
python|pandas|apply|pandas-groupby
1
359,416
48,396,688
how to encode data column python pandas
<p>I have a data set with following column:</p> <p><a href="https://i.stack.imgur.com/uIVMs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uIVMs.jpg" alt="Data preview"></a></p> <p>As shown in the image, the Level 1 is univariate while level 2 bivariate and level 3 is multivariate. There level 3 m...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow noreferrer"><code>factorize</code></a> with joined all columns together:</p> <pre><code>df['new'] = pd.factorize(df['Level 1'] + df['Level 2'] + df['Level 3'])[0] </code></pre>
python|pandas|numpy|statistics
0
359,417
48,298,991
Which boolean operator is applied when using Pandas.merge() on multiple keys
<p>Let's say we have 2 dataframes</p> <pre><code>left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'], 'key2': ['K0', 'K1', 'K0', 'K1'], 'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3']}) right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'], ...
<p>From the documentation of <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer">pd.merge</a>, it's an intersection, so an AND as you described:</p> <blockquote> <p>how : {‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘inner’</p> <p>left: use only keys fr...
python|pandas
1
359,418
48,134,598
x.shape[0] vs x[0].shape in NumPy
<p>Let say, I have an array with </p> <p><code>x.shape = (10,1024)</code></p> <p>when I try to print x[0].shape</p> <pre><code>x[0].shape </code></pre> <p>it prints 1024</p> <p>and when I print x.shape[0] </p> <pre><code>x.shape[0] </code></pre> <p>it prints 10</p> <p>I know it's a silly question, and maybe the...
<p><code>x</code> is a 2D array, which can also be looked upon as an array of 1D arrays, having 10 rows and 1024 columns. <code>x[0]</code> is the first 1D sub-array which has 1024 elements (there are 10 such 1D sub-arrays in <code>x</code>), and <code>x[0].shape</code> gives the shape of that sub-array, which happens ...
python|arrays|numpy
19
359,419
48,187,664
Pandas .copy() Space/Time Complexity
<p>I've recently adopted a new programming style in Pandas, where I have single-responsibility functions that return a Series. </p> <p>I have found the benefits to this are that with large dataframes (100+ columns), I can take a slice of only the data I need to perform the calculation. It feels like this is more effic...
<p>Doing it your way is slower. </p> <p>I used the following dataframe </p> <pre><code>import string df = pd.DataFrame({key:range(0, 10000) for key in string.ascii_lowercase}) </code></pre> <p>Then in Jupyter notebook I used the %%timeit cell magic to test how much time it takes to run the following pieces of code:...
python|pandas
0
359,420
48,377,703
Tensorflow: Canonical method of diagnosing "No gradients provided for any variable..." errors
<p>I have a high level question about how to diagnose Tensorflow errors of the form:</p> <blockquote> <p><code>No gradients provided for any variable, check your graph for ops that do not support gradients, between variables</code></p> </blockquote> <p>Of course I am interested in solving this for my specific probl...
<p>I am not aware of any tool helping with this error.</p> <p>It is a typical error when you try to compute a gradient based on the output of some part of the graph w.r.t variables disconnected from the subgraph.</p> <p>There is not doubt that this is a graph-architecture issue, there is a missing link between your g...
python|tensorflow|tensorboard
1
359,421
48,115,308
Converting pandas dataframe to json is slow
<p>Converting a csv (of 50k rows) to json for eventual consumption by a Django template is quite slow. I was wondering if I was converting it correctly or if there's a better way to do this.</p> <p>First few rows of the csv are:</p> <pre><code>tdate,lat,long,entity 3/6/2017,34.152568,-118.347831,x1 6/3/2015,34.069787...
<p>The fastest way to do something is usually to avoid doing it, so maybe you could just save the generated json to a <code>data.json</code> file in your app/static directory, moving your current code to a custom management command that you execute as part of your deployment process. </p> <p>Custom management commands...
python|json|django|pandas
2
359,422
48,197,097
Correlation between array and sparse matrix
<p>I have a sparse matrix (x) and an array (y). I would like to compute the correlation between each column in the matrix and the array. Shown below is a very simple approach which is slow. I was hoping somebody would have a faster/better approach.</p> <pre><code>import numpy as np from scipy.sparse import rand as ...
<p>Using sparsity you can easily gain a speedup of >50x:</p> <pre><code>import numpy as np from scipy.sparse import rand as r1 from numpy.random import rand as r2 from time import time np.random.seed(1000) nrow,ncol = 5000,4000 x = r1(nrow, ncol, format='csc', density=.05) y = (r2(nrow)&lt;=.6).astype(int) t = [] t...
python|numpy|scipy|sparse-matrix
6
359,423
48,189,698
dataframe reshaping with new added columns
<pre><code>columns = ['a', "b","cin",'cout', 'din', 'dout'] rows = [[1 , 1, 3, 4, 2, 3], [2,3,3,1, 8 , 4], [3,1,3,1, 2, 1]] dff1 = pd.DataFrame(rows, columns=columns) </code></pre> <p><strong>result</strong></p> <p><a href="https://i.stack.imgur.com/hivgs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur...
<p>You can use <code>lreshape</code>:</p> <pre><code>df = pd.lreshape(dff, {'c':['c1','c2'], 'd':['d1','d2']}) print (df) a b c d 0 1 1 3 2 1 2 3 3 8 2 3 1 3 2 3 1 1 4 3 4 2 3 1 4 5 3 1 1 1 </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.wide_to_...
python|pandas
2
359,424
48,325,733
Training custom dataset in TensorFlow gives error
<p>I want to perform image classification on my custom dataset with TensorFlow. I have imported my own dataset but stuck at the training step (not sure if it imports the complete dataset or a single batch of 50 images although list contains all file names).</p> <p>Dataset Info: image resolution = 88*128 (single channe...
<p>It looks like you are using an unnecessary second call of <code>tf.train.batch</code>. </p> <p>Generally you would do something like:</p> <pre><code>... images, labels = tf.train.batch([images, labels], batch_size=50) with tf.Session() as sess: sess.run(init) for i in range(steps): sess.run(t...
python-3.x|tensorflow|machine-learning|classification
1
359,425
48,332,759
Pandas remove duplicate with special condition
<p>Suppose I have this df:</p> <pre><code>Day Id Value 7 111 a 6 111 a 5 111 a 4 111 b 3 111 b 2 111 a 1 111 a 6 222 a 5 222 a 4 222 b 3 222 b 2 222 b 1 222 b </code></pre> <p>I want to remove duplicates to get the result like this: (only keep the row everytime the value swi...
<pre><code>columns = ['Id','Value'] df[np.any(df[columns].shift(-1) != df[columns], axis=1)] # Day Id Value #2 5 111 a #4 3 111 b #6 1 111 a #8 5 222 a #12 1 222 b </code></pre>
python|pandas|duplicates
1
359,426
48,115,671
How to use numpy array inputs in tensorflow RNN
<p>I just curious on how how to generate a sequence, batches and or epochs to feed into a tensor flow model, a multi_layer RNN graph from a numpy array. Originally numpy array was generated from pandas dataset and a Sklearn split below.</p> <p>From Numpy to Pandas</p> <pre><code>#define features and labels using X, Y...
<p>I think the problem is here in this part of your code.</p> <pre><code> val = tf.transpose(val, [1, 0, 2]) last = tf.gather(val, int(val.get_shape()[0]) - 1) </code></pre> <p>The output of the RNN is (timestep, batch_index, data) and you are transposing to (batch_index, timestep, data). Then you do gather with in...
python|numpy|tensorflow|batch-processing|sklearn-pandas
2
359,427
48,025,120
python pandas multi-level indexing - adding new columns
<p>I have been using panels in place of dataframes with multi-level indexing because they seem to be faster for large datasets. But I'm now transitioning to the Midx framework. With panel, I can do this easily:</p> <pre><code>import pandas as pd pan = pd.Panel(np.random.randn(3,5,2),items=['p1','p2','p3'],minor_axis=[...
<p>You can use <code>concat</code> since you are trying to assign a dataframe and you have multi level columns i.e </p> <p><strong>Step 1</strong>: Make the dataframe a multi level column dataframe </p> <pre><code>samp = pd.DataFrame(pd.np.random.randn(10,2),columns=['a','b']) p4 = pd.concat([samp], keys=['p4'],axis=...
python|pandas|dataframe|multi-index
1
359,428
48,330,303
Pandas: Removing invalid literals in a column while converting object to int
<p>I am trying to convert a column with postal codes of 'object' type to 'int'</p> <p><code>df['ZIP'] = df['ZIP'].astype(str).astype(int)</code></p> <p>My data is more than 100000 records, and it keeps throwing message with different literals that are invalid in that column. I understand the type of data does not mat...
<p>First, convert to numeric with parameter <code>errors='coerce'</code> so that the ones cannot be converted will be NaN. Then, drop them and cast the Series as integer.</p> <pre><code>df['ZIP'] = pd.to_numeric(df['ZIP'], errors='coerce') df = df.dropna(subset=['ZIP']) df['ZIP'] = df['ZIP'].astype('int') </code></pre...
python|pandas
9
359,429
48,048,736
Install older versions of tensorflow
<p>I am trying to install tensorflow 1.3.0 with the following setup:</p> <pre><code>python 3.6.3 pip 9.0.1 Windows 10 on x64 </code></pre> <p>I have tried running </p> <pre><code>pip install https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow_jni-cpu-windows-x86_64-1.3.0-rc2.zip </code></pre> <p...
<p>Please Use the following command</p> <pre><code>pip install tensorflow==&lt;version&gt; </code></pre> <p>In your case for getting tensorflow 1.3.0, use it likewise</p> <pre><code>pip install tensorflow==1.3.0 </code></pre>
tensorflow
14
359,430
48,270,534
How to have matplotlib's imshow generate an image without being plotted
<p>Matplotlib's <code>imshow</code> does a nice job of plotting a numpy array. This is best illustrated by this code:</p> <pre><code>from PIL import Image import matplotlib.pyplot as plt import numpy as np rows, cols = 200, 200 mat = np.zeros ((rows, cols)) for r in range(rows): for c in range(cols): mat[r...
<p>This simple case can probably best be handled by <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imsave.html" rel="noreferrer"><code>plt.imsave</code></a>.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np rows, cols = 200, 200 r,c = np.meshgrid(np.arange(rows), np.arange(cols)) mat =...
python|numpy|matplotlib|pillow
6
359,431
48,064,043
python correlation coefficent
<pre><code>import pandas as pd import numpy as np import seaborn import scipy import matplotlib.pyplot as plt da=[] outputFile = open ("core.txt","w") f = open ('17059output.txt', "r") lines = f.readlines() for i in range (0,28): x = lines [6+(24*i):73+(24*i)] da.append(np.loadtxt('17059-2016-' + str(i+1) + '-'...
<p>The variable <code>da</code> is initialized as an array and the following line is appending an item to it: </p> <pre><code>da.append(np.loadtxt('17059-2016-' + str(i+1) + '-' + str(i+4) + '.txt', delimiter=",",usecols=2)) </code></pre> <p>So <code>da</code> is a list containing one item - an <code>array</code>. O...
python|numpy|correlation
0
359,432
48,324,072
How to save iterative models and best model in tensorflow?
<p>I'm trying to save iterative checkpoints of my models, but also the model that achieved the best score on an independent validation dataset. My checkpoints however, overwrite my best model. Effectively, I'm using something like:</p> <pre><code>saver = tf.train.Saver() with tf.Session() as sess: for epoch in ra...
<p>The reason is that you're using the same <a href="https://www.tensorflow.org/api_docs/python/tf/train/Saver" rel="nofollow noreferrer"><code>tf.train.Saver</code></a> for both, so it remembers last <code>max_to_keep=5</code> checkpoint files, no matter how you name them.</p> <p>The simplest solution is to set <code...
python|tensorflow|machine-learning|cross-validation
3
359,433
48,080,567
Map dataframe column value by another column's value
<p>My dataframe has a month column with values that repeat as <code>Apr</code>, <code>Apr.1</code>, <code>Apr.2</code> etc. because there is no year column. I added a year column based on the month value using a for loop as shown below, but I'd like to find a more efficient way to do this:</p> <pre><code>Products['Yea...
<p>You can use <code>.str</code> and treat the whole columns like string to split at the dot. Now, apply a function that takes the number string and turns into a new year value if possible.</p> <p>Starting dataframe:</p> <pre><code> Month 0 Apr 1 Apr.1 2 Apr.2 </code></pre> <p>Solution:</p> <pre><code>def ge...
python|performance|pandas
0
359,434
48,329,751
How to transform the nested list in one column of dataframe to one dimension list?
<pre><code> videoID long lat viewerCount 0 225 -10 1.8 [1,[3,4]] 1 228 12 23.0 [5,5] 2 123 10 20.0 [1,[2, [3]]] </code></pre> <p>I have dataframes like shown above. What I'm trying to do is to convert the values of viewerCount to single Dimension array. The expected outpu...
<p>convert it to string, remove all square brackets and spaces and finally split it by <code>','</code>:</p> <pre><code>In [28]: df['viewerCount'] = \ df['viewerCount'].astype(str).str.replace(r'[\[\s\]]', '').str.split(',') In [29]: df Out[29]: videoID long lat viewerCount 0 225 -10 1.8 ...
python|list|pandas|dataframe
1
359,435
48,306,253
How can I use a line in the header of a CSV file as the index in a dataframe?
<p>I have a .csv file with 4 lines in the header. One of them is the column names, and I've gotten that imported correctly, along with the rest of the data. </p> <p>One of the lines in the header tells me the index values with a start value, a stop value and a step size. I can't figure out how to read that information...
<p>You could read the file to get the index values, then use the <code>header</code> argument in <code>pd.DataFrame.from_csv()</code> to skip the first few lines. Finally create a new index with a few commands. </p> <p>Here's an example.</p> <p>Suppose the file was:</p> <pre class="lang-none prettyprint-override"><c...
python|pandas|csv
0
359,436
48,326,979
Indexing numpy indices like array with list of 2D points
<p>I am using python 2.7</p> <p>I have an array of indices created by </p> <pre><code>ids=np.indices((20,20)) </code></pre> <p>ids[0] is filled with all the vertical coordinates and ids<a href="https://i.stack.imgur.com/cjuTD.png" rel="nofollow noreferrer">1</a> is filled with all the horizontal coordinates ids has...
<p>A few tips: You can get <code>mid</code> directly from mask using <code>np.argwhere(mask)</code>. Probably more convenient for your purpose is <code>np.where</code> which you can use like <code>mi, mj = np.where(mask)</code> and then <code>anotherarray[mi, mj]</code>.</p>
python|numpy|indexing|image-registration
1
359,437
48,006,003
Reverb effect with scipy
<p>I'm using numpy and scipy, I want to add reverb effect to signal.</p> <p>It is possible to make reverb with these libaries?</p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p>
<p>It is certainly possible to do signal processing in <strong>scipy</strong>, specifically using <strong>scipy.signal</strong>. Check out <a href="https://docs.scipy.org/doc/scipy/reference/signal.html" rel="nofollow noreferrer">their documentation</a> for a list of useful signal processing functions. You can create a...
python|numpy|scipy|signals|signal-processing
1
359,438
48,281,388
Creating new pandas dataframe by extracting columns from other dataframes - ValueError
<p>I have to extract columns from different pandas dataframes and merge them into a single new dataframe. This is what I am doing:</p> <pre><code>newdf=pd.DataFrame() newdf['col1']=sorted(df1.columndf1.unique()) newdf['col2']=df2.columndf2.unique(), newdf['col3']=df3.columndf3.unique() newdf </code></pre> <p>I am sur...
<p>It seems there is problem length of unique values is different.</p> <p>One possible solution is concat all data together and apply <code>unique</code>.<br> If unique data not same sizes, get <code>NaN</code>s in last values of columns.</p> <pre><code>newdf = pd.concat([df1.columndf1, df2.columndf2, df3.columndf3],...
python|python-2.7|pandas|dataframe
2
359,439
48,035,105
Pandas / Datetime, year form variable
<p>I am using pandas to automatically clean a number of CSV files. The data looks like this</p> <pre><code> date value 1 13 Sep 9 2 5 Oct 8 3 10 Oct 99 </code></pre> <p>I use the following code to convert the string to datetime</p> <pre><code>pd.to_datetime(new_df[0].str.replace(' ',...
<p>You need to update the date format to include the year <code>%d%b%Y</code>:</p> <pre><code>pd.to_datetime(df['date'].str.replace(' ', '') + '2016', format='%d%b%Y') 1 2016-09-13 2 2016-10-05 3 2016-10-10 Name: date, dtype: datetime64[ns] </code></pre>
python|pandas|datetime
3
359,440
48,273,462
Multiplying by zero causes inf or nan during training
<p>I am trying to build a neural network with skip connections. Some times however I want to turn them off i.e. they should still be there (for shape reasons), but I don't want any signal to be conveyed.</p> <p>E.g. I want something like this:</p> <pre><code>for i, num_layers in reversed(list(enumerate(layers))): ...
<p>In this case the problem can be solved by simply assigning <code>skip_connection</code> to the zero vector. This might be useful for others as well, but this solution is very clumsy, so I will leave the question unanswered for now.</p> <pre><code>for i, num_layers in reversed(list(enumerate(layers))): ... i...
tensorflow|deep-learning
0
359,441
48,213,729
How to split a 3D matrix into 3D matrices lined up in a list?
<p>I have a NumPy array with the following shape:</p> <pre><code>(1532, 2036, 5) </code></pre> <p>I would like to generate a list of arrays where each one has the following shape:</p> <pre><code>(1532, 2036) </code></pre>
<p>You can use <a href="https://docs.python.org/3/library/constants.html#Ellipsis" rel="nofollow noreferrer"><code>Ellipsis</code></a> to signify all dimensions up to the last. For example:</p> <pre><code>arr = np.random.rand(4, 3, 2) arr array([[[ 0.35235813, 0.57984153], [ 0.53743048, 0.46753367], ...
python|numpy|scipy
3
359,442
48,179,297
Reindexing a specific level of a MultiIndex dataframe
<p>I have a DataFrame with two indices and would like to reindex it by one of the indices.</p> <pre><code>from pandas_datareader import data import matplotlib.pyplot as plt import pandas as pd # Instruments to download tickers = ['AAPL'] # Online source one should use data_source = 'yahoo' # Data range start_date =...
<p>If you're looking to reindex on a certain <em>level</em>, then <code>reindex</code> accepts a <code>level</code> argument you can pass - </p> <pre><code>adj_close.reindex(all_weekdays, level=0) </code></pre> <p>When passing a <code>level</code> argument, you cannot pass a <code>method</code> argument at the same t...
python|pandas|dataframe|multi-index|reindex
16
359,443
48,105,937
Unable to fillna a column in dataframe with values from a series
<p>I am trying to fillna in a specific column of the dataframe with the mean of not-null values of the same type (based on the value from another column in the dataframe). Here is the code to reproduce my issue:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame() #Create the DateFrame with a col...
<p><code>fillna</code> is base on index, so , you need same index for your target dataframe and process dataframe</p> <pre><code>df.set_index('col1')['col0'].fillna(w_frame.set_index('col1').col0).reset_index() # I only show the first 11 row Out[74]: col1 col0 0 b 0.363899 1 a 0.729004 2 d 0.2...
python|pandas|dataframe
0
359,444
48,276,812
How to calculate running total and reset when value change with Python?
<p>I want to calculate running total of Promo, and reset running total when Promo changes. How can I achieve this with Python and Pandas? Thanks very much!</p> <pre><code> Id Date Promo Running_Total 0 19 2015-07-09 0 0 1 18 2015-07-10 0 0 2 17 2015-07-11 ...
<p>Completely changed solution(s):</p> <p>Values of column <code>Promo</code> was changed with <code>2</code> and <code>3</code>.</p> <p>For count consecutives all values use compare by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.ne.html" rel="nofollow noreferrer"><code>ne</code></a> ...
python|pandas
2
359,445
48,171,887
Only show round numbers on x-axis in point plot
<p>If I use the following code I end up with an overcrowded x-axis. I would like to show only every 10th number on the x axis. Meaning [0,10,...]. Any idea how to do this?</p> <pre><code>import pandas as pd import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt a = pd.DataFr...
<p>You may decide not to use a pointplot at all. A usual lineplot seems to suffice.</p> <pre><code>import pandas as pd import numpy as np from matplotlib import pyplot as plt a = pd.DataFrame({'y':np.random.randn(100)}) plt.plot(a.index, a.y) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/eMHlG.png...
python|pandas|matplotlib|plot|seaborn
3
359,446
48,145,670
Numpy array not behaving as expected
<p>So I wrote this python program in which a part of it is it behaving as i would like to. Where am I going wrong? Any rectification suggested will be most obliged.</p> <pre><code>print(grad2) print(xorTrainingWeights[1:3] - learningRate * grad2[1:3]) xorTrainingWeights[1:3] = xorTrainingWeights[1:3] - learningRate * ...
<p>Your problem is that <code>xorTrainingWeights</code> has <code>dtype=int</code>, so your values are floored when you reassign.</p> <p>Check this:</p> <pre><code>test = np.array([1,2,3]) print(test) test[1:3] = test[1:3] - 0.001 print(test) test = np.array([1.,2.,3.]) # or test = np.array([1,2,3], dtype=float) # o...
python|python-2.7|numpy
3
359,447
48,377,399
How to split an string type array by value
<p>Say I got an array of <code>str</code>:</p> <pre><code>['12.5', '7', '45', '\n', '13.7', '52', '34.3', '\n'] </code></pre> <p>And I want to split it by value, in this case by <code>'\n'</code>, so it becomes:</p> <pre><code>[['12.5', '7', '45'], ['13.7', '52', '34.3']] </code></pre> <p>I don't want to enumerat...
<p>You can use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow noreferrer"><code>itertools.groupby</code></a> which, of course, does iterate the list, but is highly optimized:</p> <pre><code>from itertools import groupby l = ['12.5', '7', '45', '\n', '13.7', '52', '34.3', '\...
python|arrays|numpy
2
359,448
48,203,528
networkx: add edges from list of relationships
<p>I have a dataset (pandas frame) composed of "users" and "interactions between users", like:</p> <pre><code>user, interactions 1, 2 7 9 4 2, 7 1 5 7 8 3 4, 9 5 3 </code></pre> <p>Each number correspond to the ID of an user. Each user can have N interactions, where N >= 0.</p> <p>The values after the commas are the...
<p>Networkx has a function to add edges from a list of edges (<code>.add_edges_from()</code>).</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt user = [1,2,4] interactions = [ [2, 7, 9, 4], [7, 1, 5, 7, 8, 3], [9, 5, 3] ] # create the edge list elist = [] for v1,v2 in zip(user,interactions): ...
python|pandas|networkx
1
359,449
48,170,811
Pandas: Parsing with two conditions issue
<p>I have a dataframe called <code>transcripts</code> and a numpy array called <code>genes</code>. <code>genes</code> is simply the unique values of the <code>geneID</code> column of <code>transcripts</code>. For each value of <code>genes</code> I would like to find the longest transcript (column <code>transcriptLength...
<p>You need <code>z=df.loc[(df['geneID'] != 'g2') | (df['transcriptLength'] == y)].copy()</code>, i.e. you want 'or' instead of 'and'. So anything outside of g2, you keep, and if it's in g2, you want it not to have transcriptLength y. As currently written, you reject anything unless it is both not in g2 and does not ha...
python|pandas|conditional
2
359,450
48,034,789
Find all "neighbors" for element in multidimensional array, wrapping around the boundaries
<p>Lets say I use an 2D/3D numpy array to model a box consisting of cells. The cells are labeled by increasing numbers starting from 0. Until here, this could be done by</p> <pre><code>box = np.arange(np.prod(n_cells)) box = box.reshape(n_cells) </code></pre> <p>where <code>n_cells</code> is a np.array which stores t...
<p>This can be done with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html#numpy.roll" rel="nofollow noreferrer">numpy.roll</a> which "rolls" the array along given axes, with exactly the kind of wrap-around that you want. For example, rolling by (-1, -1) shifts everything to the left and up,...
python|numpy|multidimensional-array|boundary
4
359,451
48,173,695
Issue With Updating Pandas Dataframe Column Based on Reference Table Targeting Another Column
<p>I have a dataframe that I'm trying to update based on information that I have in an external reference table (that is currently a small ~20 entry csv), and I'm having some difficulty figuring out how to get it to work.</p> <p>The dataframe looks like this:</p> <pre><code>id company value1 value2 1 foo...
<p><code>map</code> is by far the fastest way to do what you're doing. But here are a couple of alternatives, along with their performance. </p> <p><strong>Setup</strong></p> <p>First, <code>df</code> - </p> <pre><code>df id company value1 value2 0 1 foo 10.0 0.0 1 2 bar 10.0 0.0 2 ...
python|pandas|csv|dictionary|dataframe
2
359,452
48,370,318
How to display values of 1 column with respect to particular values present in some other column in Excel sheet in Python?
<p>This is a sample document from my Excel sheet (I couldn't upload the screenshot of the Excel sheet, so I tried to make a similar table form with 4 attributes/columns). I want to write code in Python so that I can count how many times any movie name from column 1 is present for a particular value in column 4.</p> <h3...
<p>Noting that your code attempt, imported pandas, I will show how to do that using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow noreferrer">pandas</a>, since it makes this quite straight forward.</p> <h3>Code:</h3> <pre><code>df = pd.read_excel('test.xlsx') pr...
python|python-3.x|pandas
1
359,453
48,091,050
How shall I resolve this "Memory Error" in numpy?
<p>I am using numpy for making a zeroes matrix using np.zeros((x,y))</p> <p>But my notebook says memory error on this.<br> <strong>Note: my x is 92106 and y is 241071</strong>.</p> <p>I guess it's because of these large values that I'm getting an error. Is there any way I can resolve this error? Or basically handle t...
<p>As updated by Alex in comment, your RAM doesn't have enough memory to handle such big array and Numpy is not the optimal choice. You can use sparse matrix to create such array. Here is one way to do that,</p> <pre><code>from scipy.sparse import dia_matrix import numpy as np d = dia_matrix((92106 , 241071), dtype=np...
numpy
1
359,454
48,339,641
Summing and getting distinct count Python Pandas
<p>I have a dataframe which looks like this :</p> <pre><code>ID | Value 1 100 1 300 2 200 3 300 4 400 </code></pre> <p>basically i am trying to achieve this :</p> <pre><code>ID Distinct Count | Total Value 4 1300 </code></pre> <p>so u see the total distinct count of ID is 4 and ...
<p>You're on an older version of pandas, because <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.aggregate.html" rel="nofollow noreferrer"><code>df.agg</code>/<code>aggregate</code></a> are introduced as first class functions from <code>v0.20</code>. Upgrade with <code>pip install --upg...
python|pandas
1
359,455
48,067,318
Python - to_csv
<p>I am currently trying to write a dataframe to a csv using to_csv. The input and output for the data is below. How do I write the to_csv to ensure that the fields with commas still get double quoted but the row with Katie doesn't get additional double quotes?</p> <p>Input: </p> <pre><code>Title Johnny,Appleseed ...
<p>Escaping quotes with double quotes is part of <a href="https://www.rfc-editor.org/rfc/rfc4180" rel="nofollow noreferrer">the CSV standard:</a></p> <blockquote> <p>&quot;7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double qu...
python|pandas|amazon-redshift
1
359,456
48,300,891
Efficiently adding rows to pandas DataFrame
<p>I'm trying to create a simple backtester on python which allows me to assess the performance of a trading strategy. As part of the backtester, I need to record the transactions which occur. E.g., </p> <pre><code>Day Stock Action Quantity 1 AAPL BUY 20 2 CSCO SELL 30 2 ...
<p><code>list.append</code> operations are <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow noreferrer">amortised constant time</a> operations, because it just involves shifting pointers around.</p> <p>OTOH, <code>numpy.ndarray</code> and <code>pd.DataFrame</code> objects are internally represented ...
python|pandas|list|performance
3
359,457
48,827,495
How to Delete Redundant Indexes from Filtered Dataframe
<p>So I have a filtered MultiIndexed pandas dataframe, <code>df</code>, and I want to get rid of the indexes which have been filtered out. How can I do this? </p> <p>The code I used to filter is <code>df.groupby(level=0).filter(lambda x : len(x) == 2)</code>.</p> <p>Thanks,</p> <p>Jack</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.remove_unused_levels.html" rel="nofollow noreferrer"><code>MultiIndex.remove_unused_levels</code></a>: </p> <pre><code>df1 = df.groupby(level=0).filter(lambda x : len(x) == 2) df1.index = df1.index.remove_unused_levels() </code></p...
python|pandas
1
359,458
48,743,556
python pandas percent change with columns of dataframe
<p>I just started studying pandas and have questions. Firstly, I'd like to ask this.</p> <p>I have dataframe and it's like below.</p> <pre><code> Date Open High Low Close 2015-11-02 711.059998 721.619995 705.849976 721.109985 2015-11-03 718.859985 724.650024 714.719971 722....
<p>Also you can use standard operands to achieve what you wanted:</p> <pre><code>df['CloseToOpen'] = (df['Open'] / df['Close'].shift(1) - 1).fillna(0) </code></pre>
python|pandas|dataframe
7
359,459
48,544,798
Pandas giving forward day range and not backward and in certain pattern
<p>I am trying to get the 3 days back date in list format. What I did till now is: </p> <pre><code> datelist = pd.date_range(pd.datetime.today(), periods=3).tolist() &gt;&gt;&gt; datelist [Timestamp('2018-01-31 20:03:51.068944', freq='D'), Timestamp('2018-02-01 20:03:51.068944', freq='D'), Timestamp('2...
<p>For generate from today by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="nofollow noreferrer"><code>date_range</code></a> first substract for first day in past and add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.sort_values.html" rel="nofo...
python|python-2.7|pandas|datetime
2
359,460
48,852,522
How to web scrab from txt file
<p>Let's say I use online tool like HTML Source Code Viewer<br> then I input a link then they generate the HTML Source Code.<br> Then select only the <code>&lt;li&gt;</code> tags that I want, something like this </p> <pre><code>&lt;li class='item'&gt;&lt;a class='list-link' href='https://foo1.com'&gt;&lt;img src='htt...
<p>Just read the file as you normally would. No need to use NumPy.</p> <pre><code>with open("urlcontainer.txt") as f: page = f.read() soup = BeautifulSoup(page, "html.parser") </code></pre> <p>Then, carry on with your parsing activities.</p>
python|numpy|beautifulsoup
1
359,461
48,626,841
Constraining groupby operations
<p>I have the three dataframes show below:</p> <ol> <li><em>primarydf</em> is a dataframe showing a book <em>TitleCode</em>, <em>Type</em> (digital/physical), <em>WeekEnding</em> (meaning that the unit data is for the week ending in this date), and <em>TotalUnits</em> (how many units were sold). </li> <li><em>attachdf...
<p>Consider calculating columns with <code>groupby</code> and <code>transform</code> and join or merge helper dataframes, <em>week1df</em> and <em>week4df</em>:</p> <pre><code># ADD NEW COLUMNS TO ATTACH DF attachdf['WeekNo'] = attachdf.groupby(['TitleCode', 'Type']).cumcount()+1 attachdf['Week4A'] = attachdf[attachdf...
python|pandas
1
359,462
48,703,171
Avoid extra dimension added by numpy.vsplit
<p>We can join several 1d arrays with <code>vstack</code> (or <code>hstack</code>), e.g. <code>D = np.vstack([a,b,c])</code>.<br> The reverse operation is <code>[a2,b2,c2] = np.vsplit(D, 3)</code>. But the dimensionality changes in the round-trip:</p> <pre><code>import numpy as np a = np.random.rand(10,) b = np.rando...
<pre><code>In [98]: D = np.arange(12).reshape(4,3) In [99]: np.vsplit(D, 4) Out[99]: [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]]), array([[ 9, 10, 11]])] </code></pre> <p><code>split</code> is using a slice to select rows, thus preserving that dimension</p> <pre><code>[D[i:i+1,:] for i in range(4)]...
python|numpy
1
359,463
48,758,964
How to use histogram as features when creating an image classifier using Tensor Flow?
<p>I'm still a student and I'm working on how to use histogram as features when creating an image classifier using Tensor Flow (I already used tensor flow for poets, but its inputs are raw images, now I want to use histograms as input). I watched its tutorial on how to do this using apples and oranges as features, but ...
<p>One way of representing an RGB histogram in a feature vector is to extract the relevant values from it.</p> <p>So the histogram would be stored as: <em>redMean, greenMean, blueMean, redStdDev, greenStdDev, blueStdDev</em></p> <p>I've used this approach to represent color profiles of butterflies.</p>
python|image-processing|tensorflow|histogram
0
359,464
48,710,783
Pandas - Find and index rows that match row sequence pattern
<p>I would like to find a pattern in a dataframe in a categorical variable going down rows. I can see how to use Series.shift() to look up / down and using boolean logic to find the pattern, however, I want to do this with a grouping variable and also label all rows that are part of the pattern, not just the starti...
<p>I think you have 2 ways - simplier and slowier solution or faster complicated.</p> <ul> <li>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.window.Rolling.apply.html" rel="noreferrer"><code>Rolling.apply</code></a> and test pattern</li> <li>replace <code>0</code>s to <code>NaN</code>s...
pandas|indexing|row
16
359,465
48,508,152
Python Pandas Dataframe: change a NaN cell value with a different column from previous row
<pre><code>import pandas as pd import numpy as np data = np.array([['', 'Col1', 'Col2', 'Col3'], ['Row1', 1, 2, 3], ['Row2', np.nan, 5, 6], ['Row3', 7, 8, 9] ]) df = pd.DataFrame(data=data[1:, 1:], index=data[1:,0], ...
<p>One way you can do this is to use <code>stack</code>, <code>ffill</code>, and <code>unstack</code>:</p> <pre><code>df.stack(dropna=False).ffill().unstack() </code></pre> <p>Output:</p> <pre><code> Col1 Col2 Col3 Row1 1 2 3 Row2 3 5 6 Row3 7 8 9 </code></pre>
python|python-3.x|pandas|numpy
2
359,466
48,662,237
Pivot Table of countifs() on Pandas
<p>I have a dataset that's an identifier ID and some flags for characteristics in that data, for example:</p> <pre><code>In [86]: frame = pd.DataFrame({"key": [1,2,3,4,5,6,7,8,9], "flag1": [0,1,0,1,0,1,0,1,1], "flag2": [0,0,1,1,0,0,1,1,0], "flag3": [0,0,0,0,1,1,1,1,1]}, columns=['key','flag1','flag2','flag3']) In [87...
<p>Let's remove <code>key</code>, we don't need it. After that, the solution is pretty much a matrix <code>dot</code> product:</p> <pre><code>v = frame.drop('key', 1) v.T.dot(v) flag1 flag2 flag3 flag1 5 2 3 flag2 2 4 2 flag3 3 2 5 </code></pre> <p>Or, more effic...
python|excel|pandas
3
359,467
48,752,239
Python Pandas Multiindex Slicing/Indexing to obtain duplicate data
<p>I'm new to python and I'm working with pandas dataframes with multiple indices. I want to take one dataframe and slice/combine/index it with another dataframe. The first looks like this:</p> <pre><code> a Out[123]: col1 col2 col3 col4 lion tiger bear ohmy row1 1 5 1 2 row2 2 6 ...
<p>You can try </p> <pre><code>s=df2.groupby('col').count() s1=df.loc[:,s.index.tolist()] Out=df2.merge(s1.T.reset_index(),left_on='col',right_on='level_0').drop(['level_0','level_1'],1).set_index(['col','group']).T Out Out[404]: col col2 col3 col4 group A B C D A row1 5 1 1 2 2 row...
pandas|indexing|duplicates|slice|multi-index
0
359,468
48,652,453
Pandas DateTimeIndex multiple groupby or resample aggregation
<p>I have a years worth of data in a pandas dataframe with a DateTimeIndex where I have a record measured every 30 minutes. I want to get 30 minute averages per month. Said another way, for each month I want the average value for every 30 minutes (00:00, 00:30, ..., 23:30) aggregated over each month.</p> <p>Example ...
<p>Not familiar with <code>resample()</code>. So I made a couple changes.</p> <p>I created the index as a column, and used <code>groupby()</code> to get the mean</p> <pre><code>df = pd.DataFrame({'Z': pd.Series(data),'ts': pd.Series(datetime_idx)}) df.groupby([df.ts.dt.month,df.ts.dt.hour,df.ts.dt.minute])['Z'].mean(...
python|pandas|time-series
0
359,469
48,487,570
Low accuracy in neural network with Tensorflow
<p>I was following a <a href="https://codelabs.developers.google.com/codelabs/cloud-tensorflow-mnist/#0" rel="nofollow noreferrer">Google code lab</a> on neural networks and I decided to use the <a href="https://www.cs.toronto.edu/~kriz/cifar.html" rel="nofollow noreferrer">Cifar10</a> dataset instead of the MNIST data...
<p>If I’m not mistaken, that looks like a non-convolutional network. You need to look for a convolutional network architecture. So look for some tutorial using conv2d.</p> <p>Reason: MNIST is single channel, binary data. CIFAR is 3 channels (RGB) with 8 bit colour. It’s not enough to just up the size of the input plac...
python|python-3.x|tensorflow|neural-network|classification
0
359,470
48,819,828
Numpy.NumpyArray has no attribute Read
<p>I am trying to test a Convolution Neural Network with images that are stored in a folder within the root project directory. I have some code that is giving me an error and I am not sure why or where exactly the error is coming from. I will have the code and the full trace back of the error:</p> <p>the code(there ar...
<p>In this line: </p> <pre><code>dog_breed = Resnet_Predict_Breed(pred_image) </code></pre> <p>Use <code>image_path</code> instead, and no need to use <code>cv2.imread</code>.</p>
python|tensorflow|neural-network|keras
0
359,471
48,867,518
Pandas: checking if a value exists in each cell of a Dataframe
<p>I'm using python 2.7 and want to create a column depending on the existence of each value of a list in every cell.</p> <p>Here's an example of data:</p> <pre><code>| query | ----------------- | handbag woman | | shoe man | | t-shirt baby | | watch unisex | | dress | </code></pre> <p>I have ...
<p>First in pandas the best is not used loops, because slow (apply are loops under the hood) and rather use vectorized solutions.</p> <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>extract</code></a> and <a href="http://pandas.pydat...
python|pandas|dataframe|apply
1
359,472
48,856,082
How to avoid creating an intermediate data frame?
<p>I am working with a dataset where I need to identify the max date difference between multiple duplicate rows. The code I have below works to satisfy my requirements (minus the "A value is trying to be set on a copy of a slice from a DataFrame" warning I get), but I am curious about how to perform the same task witho...
<p>I believe you want working only with rows filtered by boolean mask <code>m</code>:</p> <pre><code>m = df.duplicated(subset=['Key', 'Num1','Num2','Date1'],keep=False) d1 = pd.to_datetime(df.loc[m, 'Date2'], format='%Y%m%d') d2 = pd.to_datetime(df.loc[m, 'Date1'], format='%Y%m%d') df['DateDiff'] = (d1 - d2).dt.days ...
python|pandas|dataframe|concat
2
359,473
48,832,687
Merge two values into one cell in dataframe
<p>Say I have a dataframe like this:</p> <pre><code> minute values 0 1 3 1 2 4 2 1 1 3 4 6 </code></pre> <p>And another one with a percentage set of values:</p> <pre><code> minute values 0 1 .30 1 2 .40 2 1 .10 3 4 .60 </code></pre> <p>...
<p>Use <code>pd.concat</code> with the <code>keys</code> argument to combine:</p> <pre><code>df = pd.concat([df1, df2], axis=1, keys=['Count', 'Percentage']) df Count Percentage minute values minute values 0 1 3 1 0.3 1 2 4 2 0.4 2 1 1 ...
python|python-3.x|pandas|dataframe
4
359,474
48,501,768
reading quarterly data in pandas
<p>I have a dataset with quarterly observations indicated as 200101 (quarter 1 of 2001) to 201504 (quarter 4 of 2015). I would like to transform these into proper pandas dates indices.</p> <pre><code>200101 -&gt; 2001-03-31 ... 201504 -&gt; 2015-12-31 </code></pre> <p>for year/months I often use</p> <pre>...
<p>you can convert those strings into <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.PeriodIndex.html" rel="nofollow noreferrer"><code>PeriodIndex(freq='Q')</code></a> and then (if needed) into <code>timestamp(freq='M')</code></p> <p>Demo:</p> <pre><code>In [272]: df Out[272]: qt 0 200...
python|pandas|python-datetime
1
359,475
48,830,026
pandas dataFrame joining error
<p>I have the below dataFrame:</p> <pre><code>columnName | columnText | columnTextContents ---------------------------------------------------------------------------- Linda | [{age:45, category:technical}, | [{city:Mexico,type:member}] | {age:55, category:nontechnic...
<p>You lose track of the original index when you create and modify your <code>tempDF</code>. Then the join will fail, because it doesn't properly match the indices.</p> <p>One way around this, is to manually keep track of the indices, and assign it to the final <code>tempDF</code>. The index can be found as <code>k[0]...
python-3.x|pandas|dataframe|concatenation
0
359,476
48,681,012
numpy - multiplay only if
<p>I have a big issue here, i'm working with numpy and trying to understand it better, but i hit small issues on the road to my goal.</p> <p>here is my code.</p> <pre><code>product_test = [] product_test.append({ 'min-dkk' : 149.9, 'min-procent' : 100.0, 'max-dkk' : 249.9, 'max-procent' : 0.0, 'co...
<p>The equivalent in numpy would be:</p> <pre><code>list_product[:,0] += (list_product[:,0] != 0) * list_product[:,4] </code></pre> <p>The condition is now evaluated to an array of type boolean, cast to the type of list_product (1 for true, 0 for false) then multiplied with the array you might want to add.</p>
python|arrays|numpy
1
359,477
48,531,236
How can I do column wise counts and change value when the frequency is less than 3?
<p>I have a dateframe with a lot of rows with some low frequency values. I need to do column wise counts and then change the value for when the frequency is less than 3.</p> <p>DF-Input</p> <pre><code>Col1 Col2 Col3 Col4 1 apple tomato apple 1 apple potato nan 1 ap...
<p>You use <code>where</code> with <code>value_counts</code>:</p> <pre><code>df.where(df.apply(lambda x: x.groupby(x).transform('count')&gt;2), 'Other') </code></pre> <p>Output:</p> <pre><code> Col2 Col3 Col4 Col1 1 apple tomato Other 1 apple Other banana 1 apple ...
python|pandas|replace
5
359,478
48,547,709
Tensorflow 1.5 build failing - missing path?
<p>I have been following a tutorial to install and build Tensorflow on macOS. When I attempt to build it, I use the following command:</p> <pre><code>bazel build --config=cuda --config=opt --copt=-msse4.2 --copt=-mpopcnt --copt=-maes --copt=-mcx16 --verbose_failures --action_env PATH --action_env LD_LIBRARY_PATH --act...
<p>I was able to get past this error by adding the following to the bazel command: </p> <pre><code>--action_env PYTHON_BIN_PATH=/usr/bin/python </code></pre>
python|numpy|tensorflow
9
359,479
48,613,481
Python: Groupby First Non NaN Value
<p>I have the following dataframe:</p> <pre><code>id number 1 13 1 13 1 NaN 1 NaN 2 11 2 11 2 11 2 NaN </code></pre> <p>I want to find the first non-NaN value per id and mark it with a 1. The result should look like this:</p> <pre><code>id number code 1 13...
<p>Assuming you mean <code>last_valid_index</code>, you can <code>apply</code> the <code>last_valid_index</code> function and <code>loc</code> to assign - </p> <pre><code>df.loc[df.groupby('id').number.apply(pd.Series.last_valid_index), 'code'] = 1 df id number code 0 1 13.0 NaN 1 1 13.0 1.0 2 1 ...
python|pandas
5
359,480
48,499,815
sequential pandas rolling data processing
<p>I´m working with pandas rolling-function to generate sequential data. My main window size is 51 and I need to calculate various measures from this initial window with different windows,e.g.: dummy data:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,800,size=(1000, 3)), columns=list('ABC')) </code></pre> <p>...
<p>This might be a solution you are looking for:</p> <pre><code>import pandas as pd import numpy as np # Create dummy data df = pd.DataFrame(np.random.randint(0,800,size=(1000, 3)), columns=list('ABC')) # To include this data into the dataframe with rolling means, start by creating a copy df_complete = df.copy() # ...
pandas|python-3.6|sequential
0
359,481
48,489,978
the arrays with numpy
<p>Hello I would like to have an array like this (1) :</p> <pre><code>import numpy as np A = np.array([ (1, 2, 9.799, 4.7, 4.77, 148929.0, 450030016.0), (11, 21, 91.799, 41.7, 41.77, 1489129.0, 4500130016.0), (41, 25, 93.799, 74.7, 94.77, 1487929.0, 4500340016.0)], dtype = [('a', '&lt;i4'), ('z', '&lt;f4'), ('e', '&lt...
<p>Use this:</p> <pre><code>l = [] l.append((1, 2, 9.799, 4.7, 4.77, 148929.0, 450030016.0)) l.append((11, 21, 91.799, 41.7, 41.77, 1489129.0, 4500130016.0)) l.append((41, 25, 93.799, 74.7, 94.77, 1487929.0, 4500340016.0)) A = np.array(l, dtype=[('a', '&lt;i4'), ('z', '&lt;f4'), ('e', '&lt;f4'), ('r', '&lt;f4'), ('t',...
python|numpy
0
359,482
48,560,775
How to substitute a column in a pandas dataframe whit a series?
<p>Let's have a dataframe <em>df</em> and a series <em>s1</em> in pandas</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.randn(10000,1000)) s1 = pd.Series(range(0,10000)) </code></pre> <p>How can I modify <em>df</em> so that the column 42 become equal to <em>s1</em>?</p> <p>How can ...
<p>I think you need first same length <code>Series</code> with <code>DataFrame</code>, here <code>20</code>:</p> <pre><code>np.random.seed(456) df = pd.DataFrame(np.random.randn(20,10)) #print (df) s1 = pd.Series(range(0,20)) #print (s1) #set column by Series df[8] = s1 #set Series to range of columns cols = df.loc[:...
pandas
0
359,483
48,754,721
Downsampling pandas Dataframe to arbitrary length
<p>I have a time series of daily values over a year:</p> <pre><code>DATE VAL 2017-01-01 -0.298653 2017-01-02 -0.224910 2017-01-03 -0.216723 .... 2017-12-29 0.061681 2017-12-30 0.078109 2017-12-31 0.106636 Freq: D, Length: 365, dtype: float64 </code></pre> <p>I need to transform this series of ...
<p>You <em>can</em> use the <code>pd.DataFrame.resample</code> function for this, it allows also fractional time units. You just have to make sure to first set the date as index and make sure that it is a datetime object:</p> <pre><code>def resample(df, target_freq, unit_str): resample_str = "{:.4g}{}".format(len(...
python|pandas|dataframe
2
359,484
48,881,766
Pandas - Aggregate by each possible combination of keys
<p>I have a DataFrame Pandas, which I'd like to group by data the most possible with combinations of columns A, B, C and D.</p> <p>Let's say it has this form:</p> <pre><code> A B C D E F G 0 Y X Y Z 1 2 7 1 Y X Y Z 3 4 8 2 X Y U V 1 1 1 3 X...
<p>I think you need first all combination of columns values:</p> <pre><code>df = pd.DataFrame({'A':[5,3,6,9,2,4], 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], }) print (df) A B C D 0 5 4 7 1 1 3 5 8 3 2 6 4 9 5 3...
python|python-3.x|pandas|dataframe
2
359,485
48,667,362
Pandas count the occurrences of each value in column
<p>I have this dataframe: </p> <p><a href="https://i.stack.imgur.com/CteDJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CteDJ.png" alt="My DataFrame"></a></p> <p>I want to have a new column that counts only the first instances of the matchID in the column MatchID. </p> <p>Specifically, it check...
<p>How about:</p> <pre><code>df['Count'] = (~df['MatchID'].duplicated()).astype(int) </code></pre>
python|pandas
2
359,486
48,578,339
Sklearn: how to get mean squared error on classifying training data
<p>I'm trying to do some classification problems using sklearn for the first time in Python, and was wondering what was the best way to go about calculating the error of my classifier (like a SVM) solely on the training data.</p> <p>My sample code for calculating accuracy and rmse are as follows:</p> <pre><code> s...
<p>To evaluate you classifier you can use the following metrics:</p> <pre><code>from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report from sklearn.metrics import roc_curve from sklearn.metrics import roc_auc_score </code></pre> <p>The confusion matrix has the predicted labels ...
python|pandas|scikit-learn|sklearn-pandas
1
359,487
48,562,123
Python Interpolate Monthly value to Daily value (linear): Pandas
<p>I have a pandas dataframe with column of year month data(yyyymm). I am planning on interpolate data to daily &amp; weekly values. Here is my df below.</p> <pre><code>df: 201301 201302 201303 ... 201709 201710 a 0.747711 0.793101 0.771819 ... 0.818161 0.812522 b 0.7...
<p>First convert columns to <code>datetimes</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferre...
python|pandas|timestamp|time-series|interpolation
4
359,488
48,819,767
pandas dataframe apply lambda if else erro
<p>I am trying to apply lambda with if-else condition on a pandas df df looks like following:</p> <pre><code>col1 col2 col3 col4 &lt;---column names None None None col4 &lt;---column values in str col1 None None None None col2 None None df_twitter_archive_master[['col1','col2','col3','col4']].apply(lambda x: x=0 if...
<p>IIUC</p> <pre><code>df.replace('None',np.nan).notnull().astype(int) Out[31]: col1 col2 col3 col4 0 0 0 0 1 1 1 0 0 0 2 0 1 0 0 </code></pre> <p>Base on your lambda method</p> <pre><code>df.applymap(lambda x: 0 if x=='None' else 1) Out[33]: col1 col2 col...
python|pandas|lambda
6
359,489
48,446,926
Pandas format symbols xlsx
<p>I need a <code>%</code>symbol on my xlsx. I apply <code>format2 = workbook.add_format({'num_format': '0%'})</code> but with that my numbers are multiplicated for <code>100</code> and I don´t want it! I need only add the <code>%</code>symbol </p> <p>xlsx data:</p> <pre><code>1.72 </code></pre> <p>format2:</p> <pr...
<p>First divide your numerical columns by 100:</p> <pre><code>df.loc[:, df.dtypes.apply(lambda c: np.issubdtype(c, np.number))] = \ df.select_dtypes('number').div(100.) </code></pre> <p>alternatively:</p> <pre><code>cols = df.columns[df.dtypes.apply(lambda c: np.issubdtype(c, np.number))] df[cols] /= 100. </cod...
python|pandas|xlsx
1
359,490
48,776,217
Split (explode) range in dataframe into multiple rows
<p>This question is similar to <a href="https://stackoverflow.com/questions/12680754/split-explode-pandas-dataframe-string-entry-to-separate-rows">Split (explode) pandas dataframe string entry to separate rows</a> but includes a question about adding ranges.</p> <p>I have a DataFrame:</p> <pre><code>+------+---------...
<p>If I understand what you need </p> <pre><code>def yourfunc(s): ranges = (x.split("-") for x in s.split(",")) return [i for r in ranges for i in range(int(r[0]), int(r[-1]) + 1)] df.Options=df.Options.apply(yourfunc) df Out[114]: Name Options Email 0 Bob [1, 2, 4, 5, 6] bob@em...
python|pandas|numpy|dataframe
6
359,491
48,809,812
Forward rolling time windows in pandas.series
<p>I want to use rolling time windows in pandas for forward looking windows. How would I do that?</p> <pre><code>import pandas as pd data = pd.DataFrame({'t': ['2017-02-02 15:00:01', '2017-02-02 15:00:02', '2017-02-02 15:01:00', '2017-02-02 15:03:05', ...
<p>A possible solution is to shift the rolling window aggregation</p>
python|pandas|time
0
359,492
48,826,763
Is there a faster way of repeating a chunk of code x times and taking an average?
<p>Starting with:</p> <pre><code> a,b=np.ogrid[0:n+1:1,0:n+1:1] B=np.exp(1j*(np.pi/3)*np.abs(a-b)) B[z,b] = np.exp(1j * (np.pi/3) * np.abs(z - b +x)) B[a,z] = np.exp(1j * (np.pi/3) * np.abs(a - z +x)) B[diag,diag]=1-1j/np.sqrt(3) </code></pre> <p>this produces an n*n grid that acts as a matrix.</p>...
<p>I think you should rely more on numpy functionality, when approaching your problem. Not a numpy expert myself, so there is surely room for improvement:</p> <pre><code>from scipy.stats import gmean n = 2 z = 1 a = np.arange(n + 1).reshape(1, n + 1) #constructing the base array before modification by random x values...
python|numpy
2
359,493
48,821,218
tf.image.random_brightness giving negative values randomly in TensorFlow
<p>'I am trying image data augmentation in TensorFlow using various methods like rotation, random brightness, random saturation. What I observe that the output of tf.image.random_brightness is not consistent - sometimes it produces negative values. I understand the randomness, but is it correct to produce negative valu...
<p>You are allowing a random change in the intensities (delta) that is between -0.8 and 0.8:</p> <pre><code>tf.image.random_brightness(params[0], 0.8, 1) </code></pre> <p>Note that the images' intensities are in the range [0-1] because you did:</p> <pre><code>image = tf.image.convert_image_dtype(image, dtype=tf.floa...
python|tensorflow
8
359,494
48,716,396
Optimize an iteration through a numpy array for neighbours checking
<p>Is there a way to optimize the following iteration with neighbours checking: </p> <pre><code>for i in range(1, A.shape[0]): for j in range(1, A.shape[1]): v = (A[i, j], A[i-1,j-1], A[i-1, j], A[i, j-1]) if v == something: print(v) </code></pre> <p>where <code>A</code> is a (very big) numpy arra...
<p>Create the test data first:</p> <pre><code>import numpy as np np.random.seed(1) A = np.random.randint(0, 2, size=(10, 8)).astype(np.uint8) </code></pre> <p>A:</p> <pre><code>array([[1, 1, 0, 0, 1, 1, 1, 1], [1, 0, 0, 1, 0, 1, 1, 0], [0, 1, 0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 1, 0, 0, 0], [...
python|arrays|numpy|optimization
2
359,495
48,716,708
Read file with header and encoding issue into numpy array
<p>I have a file (PSF from Zemax if you want to know) that looks like this:</p> <pre><code>Listing of FFT PSF Data File : C:\G_Drive\Projects\MSE\Telescope\AAO_designs\MSE_PF_6u_1300-Shan-Nicolas_2.zmx Title: MSE Prime Focus WFC with CLADC Date : 2/9/2018 Configuration 1 of 4 FFT PSF 0.5510 µm at 0.5300, 0.0000 (deg...
<p>The solution is to use <code>loadtxt</code> with Numpy 1.14, which has the <code>encoding</code> parameter.</p> <p>However, to upgrade to Numpy 1.14 at the time, I had to switch to anaconda-64.</p>
python|arrays|numpy|unicode
0
359,496
48,552,589
Fastest Way to Combining csv Files Horizontally
<p>I have 3 large csv files, with size varying from 1.5GB-1.8GB. Each file has different metric columns from each other.</p> <pre><code>File1 (columns): key, metric1, metric2 File1 (sample values): k1, m1, m2 k2, m1, m2 File2 (columns): key, metric3, metric4, metric5 Fil...
<p>Most of the time is going to be file I/O. Here is non-pandas solution for you to test with:</p> <pre><code>import glob import csv from collections import defaultdict data = defaultdict(dict) metrics = [] for csv_filename in glob.glob('foo_bar*.csv'): with open(csv_filename, 'r', newline='') as f_input: ...
python|pandas|csv
0
359,497
48,497,939
RNN LSTM Keras custom loss function
<p>I'm beginning with Keras and TensorFlow.</p> <p>I have an LSTM model learning on a dataset of stocks prices. I don't want that my model learn to predict next steps like today. I want that my model learn on each step if it must buy, sell or do nothing and how much.</p> <p>I think that I need to make a custom loss f...
<p>I would try <a href="https://keras.io/losses/#categorical_crossentropy" rel="nofollow noreferrer">categorical cross-entropy,</a> </p> <p>I mean you have three options: buy (0) , sell (1), and do nothing (2). You can encode it like this:</p> <pre><code>[1,0,0] &lt; - means 'buy' [0,1,0] &lt; - means 'sell' [0,0,1] ...
tensorflow|deep-learning|keras|lstm|rnn
0
359,498
70,841,025
Matching part of a string with a value in two pandas dataframes
<p>Given the following df with street names:</p> <pre><code>df = pd.DataFrame({'street1': ['36 Angeles', 'New York', 'Rice Street', 'Levitown']}) </code></pre> <p>And df2 which contains that match streets and their following county:</p> <pre><code>df2 = pd.DataFrame({'street2': ['Angeles', 'Caguana', 'Levitown'], 'coun...
<p>Maybe a Naive approach, but works well.</p> <pre><code>df = pd.DataFrame({'street1': ['36 Angeles', 'New York', 'Rice Street', 'Levitown']}) df2 = pd.DataFrame({'street2': ['Angeles', 'Caguana', 'Levitown'], 'county': [&quot;Utuado&quot;, &quot;Utuado&quot;, &quot;Bayamon&quot;]}) output = {'street1':[],'county':[]...
python|pandas
1
359,499
70,808,388
RuntimeError: Expected all tensors to be on the same device
<p>I am getting the following error:</p> <pre><code>RuntimeError: Expected all tensors to be on the same device </code></pre> <p>However, both my tensor are using <code>.to(device=t.device)</code>.</p> <pre><code> self.indices_buf = torch.LongTensor().to(device=t.device) self.beams_buf = torch.Lo...
<p>When calling <code>self.beams_buf_float.type(torch.LongTensor)</code>, the resulting tensor device is set to the default one (i.e. <code>cpu</code>).</p> <p>The correct way to cast your tensor to a new type while maintaining the original device is by calling <code>self.brams_buf_float.to(torch.long)</code> or <code...
python|pytorch|tensor
1