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
356,300
41,046,630
Set time formatting on a datetime index when plotting Pandas Series
<p>I have a Pandas Dataframe with a DatetimeIndex with a monthly (<code>M</code>) frequency. However, when I plot a column from this Dataframe the labels on my plot show a date and time even though these bits are meaningless. How can I fix this so that a month is only displaying in <code>YYYY-MM</code> format?</p> <p>...
<p>Make a small modification to your <code>DateTimeIndex</code> before plotting by converting them to <code>PeriodIndex</code> and providing a monthly frequency, like so -</p> <pre><code>a.index = a.index.to_period('M') # Even a.index.astype('period[M]') works </code></pre> <hr> <p><strong><em>Demo:</em></strong></...
python|pandas|matplotlib|timestamp
5
356,301
40,834,806
Compare values between different rows in Pandas
<p>I'm new to <strong>pandas</strong> and I'm trying to compare values between rows without luck.<br> I want to find the <code>RSI</code> <strong>difference</strong> between the row where <code>DOJI</code> is <code>100</code> and <strong>next one</strong>.<br> In this case, <code>52.157595</code> - <code>45.430342</co...
<p>try using <code>diff</code> with <code>loc</code></p> <pre><code>df.RSI.diff(-1).loc[df.DOJI.eq(100)] 20161125 10:13:00 6.727253 Name: RSI, dtype: float64 </code></pre> <hr> <p><strong><em>explanation</em></strong><br> Hopefully <code>diff</code> is self explanatory. However, the <code>-1</code> aligns the ...
python|python-2.7|pandas|dataframe
3
356,302
40,914,819
pandas - using a column as a key for a dictionary
<p>One of the columns "<strong>Status</strong>" in my dataframe <strong>dfUnderInterpretation</strong> has values like "<strong>OK</strong>", "<strong>Missing</strong>" and "<strong>New</strong>".</p> <p>Another variable <strong>statusInterpretation</strong> is a dict: {'OK': 'INFO', 'New': 'WARN', 'Missing': 'ERROR' ...
<p>You can use<code>apply</code> method:</p> <pre><code>dfUnderInterpretation['Status_Desc'] = dfUnderInterpretation['Status'].apply(lambda x: statusInterpretation.get(x)) </code></pre>
python|pandas
1
356,303
41,225,548
(KeyError): MultiIndex Slicing requires the index to be fully lexsorted tuple ... Why is this caused by a list, but not by a tuple?
<p>This question is partially here to help me understand what lex-sorting is in the context of multi-indexes.</p> <p>Say I have some MultiIndexed DataFrame df, and for the index I want to use:</p> <pre><code>a = (1, 1, 1) </code></pre> <p>So to pull the value from the dataframe I write:</p> <pre><code>df.loc[a, df....
<p>I'll illustrate the difference between passing a tuple and a list to <code>.loc</code>, using the example with <code>df</code> being</p> <pre><code> 0 1 2 first second bar one 4 4 7 two 3 4 7 foo one 8 1 8 two 7 5 4 </code></pre> <p>Here <code>df.loc[...
pandas
8
356,304
40,876,571
Python: sum values of the third column if two columns have the same value
<p>I have the following dataframe <code>df</code></p> <pre><code>df a b i 0 1.0 3.0 2.0 1 1.0 3.0 3.0 2 1.0 3.0 1.0 3 1.0 3.0 3.0 4 1.0 3.0 7.0 5 1.0 3.0 8.0 6 1.0 4.0 4.0 7 1.0 4.0 0.0 8 1.0 3.0 2.0 9 1.0 3.0 1.0 10 1.0 3.0 2.0 </code></pre> <p>I want to make the sum over <code>i</code> ...
<p>I think you need add column <code>i</code> to the end of <code>groupby</code>, then it is use for <code>sum</code> function:</p> <pre><code>df2 = df2.groupby(['a', 'b'])['i'].sum().reset_index() print (df2) a b i 0 1.0 3.0 29.0 1 1.0 4.0 4.0 </code></pre> <p>Or add parameter <code>as_index=False...
python|pandas|group-by
6
356,305
41,103,788
genfromtxt in Python-3.5
<p>I am trying to fix a data set using genfromtxt in Python 3.5. But I keep getting the next error:</p> <pre><code>ndtype = np.dtype(dict(formats=ndtype, names=names)) TypeError: data type not understood </code></pre> <p>This is the code I'm using. Any help will be appreciated!</p> <pre><code>names = ["country", "ye...
<p><code>dtype = "S64,i4" + ",".join(["f18" for idx in range(682)])</code></p> <p>is going to produce something like:</p> <p><code>s64,i4f18,f18,f18,f18...</code></p> <p>Note the lack of a comma after the i4.</p>
numpy|python-3.5|genfromtxt
0
356,306
40,821,819
How to pivot a pandas dataframe using a modified index?
<p>I have a timeseries dataframe of the form:</p> <pre><code>rng = pd.date_range('1/1/2013', periods=1000, freq='10min') ts = pd.Series(np.random.randn(len(rng)), index=rng) ts = ts.to_frame(name=None) </code></pre> <p>I need to do two things to it:</p> <p><strong>Step 1:</strong> Modify the index, so that every day...
<p>You really do not need to use <code>np.where</code> here as you are merely performing filtering on just 1 parameter. Also, the <code>else</code> part is made 0. So, there is absolutely no reduction in the index obtained after this step.</p> <p>Instead you must, do: </p> <p>1.Build up a boolean mask to filter datet...
python|pandas|indexing|dataframe|pivot
2
356,307
41,077,997
How to remove the dtype, index and name while writing to a csv file
<p>my code is like this:</p> <pre><code>raw_data={'Crest_height':[crest_day.Crest], 'Date':[crest_day.Date], 'Flood_Response':[flood_response]} Flood_data=pd.DataFrame(raw_data) Flood_data.to_csv(r'crest_day.csv', index=False) </code></pre> <p>I have this output in a crest_day.csv file: </p> <p...
<p>can you try this block of code:</p> <pre><code>Flood_data=pd.DataFrame({ 'Crest_height' : list(crest_day.Crest), 'Date':list(crest_day.Date), 'Flood_Response':list(flood_response) }) Flood_data.to_csv('crest_day.csv', index=False) </code></pre> <p>Hope it helps.</p>
python-2.7|python-3.x|csv|pandas
0
356,308
41,025,416
Read data (.dat file) with Pandas
<p>How do I read the following (two columns) data (from a .dat file) with Pandas</p> <pre><code>TIME XGSM 2004 006 01 00 01 37 600 1 2004 006 01 00 02 32 800 5 2004 006 01 00 03 28 000 8 2004 006 01 00 04 23 200 11 2004 006 01 00 05 18 400 17 </code></pre> <p>Column separator is (at least) 2...
<p>You can use parameter usecols with order of columns:</p> <pre><code>import pandas as pd from pandas.compat import StringIO temp=u"""TIME XGSM 2004 006 01 00 01 37 600 1 2004 006 01 00 02 32 800 5 2004 006 01 00 03 28 000 8 2004 006 01 00 04 23 200 11 2004 006 01 00 05 18 400 17""" #after testing r...
python|pandas|dataframe
13
356,309
41,153,310
Python pandas - using apply funtion and creating new columns in dataframe
<p>I have a dataframe with 40 million records and I need to create 2 new columns (net_amt and share_amt) from existing amt and sharing_pct columns. I created two functions which calculate these amounts and then used apply function to populate them back to dataframe. As my dataframe is large it is taking more time to co...
<p>I think numpy <code>where()</code> will be the best choice here (after <code>import numpy as np</code>):</p> <pre><code>df['net_amount'] = np.where( df['sharing']==1, # test/condition df['amt']*df['sharing_pct'], # value if True df['amt'] ) ...
python|pandas
0
356,310
41,133,399
A presentable way to plot frequency of 43 distinct classes
<p>I created the following histogram from the frequeny of each class in a training set</p> <p><a href="https://i.stack.imgur.com/kY9NG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kY9NG.png" alt="enter image description here"></a></p> <p>The label of each class is too long and is similar to</p> ...
<p>Maybe something like this?</p> <p><a href="https://i.stack.imgur.com/x4LhB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x4LhB.png" alt="enter image description here"></a></p> <pre><code>import numpy as np import matplotlib.pyplot as plt N=5 xlabel = ["Speed limit ("+str(i)+"km/h)" for i in r...
numpy|matplotlib|machine-learning
3
356,311
40,915,796
Pandas Median on index not values
<p>My datas :</p> <pre><code>LogRatio Strength 0.555 9.1 0.542 9.6 0.533 9.7 0.532 9.3 0.519 9.2 0.508 9.5 </code></pre> <p>I want to have the point(LogRatio,Strength) that is the median <strong>position</strong> of my group indexA-indexB</p> <pre><code>indexA...
<p>you can try</p> <pre><code>median_position = (indexA+indexB)/2 point_logRatio = df.iloc[median_position]['LogRatio'] point_Strength = df.iloc[median_position]['Strength'] </code></pre>
python|pandas|dataframe|median
1
356,312
40,808,149
How to specify tensorflow dependency in requirements.txt system-agnostic
<p>I specify my project's dependencies in requirements.txt. For tensorflow currently I have to specify the whl provided by Google. Unfortunately, there is a <a href="https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation" rel="nofollow noreferrer">separate wheel depending on many system co...
<p>I think that this will be better if you use a file like setup.py or requirements.py. In python (.py) files you can easily get the os information by:</p> <pre><code>import sys sys.platform </code></pre> <p>And you can also fire any terminal command for installing any package by:</p> <pre><code>import os os.system(...
python|python-3.x|tensorflow
0
356,313
41,021,033
Pandas writing in csv file as columns not rows-Python
<p>This is my code: </p> <pre><code>import os file=[] directory ='/Users/xxxx/Documents/sample/' for i in os.listdir(directory): file.append(i) Com = list(file) df=pd.DataFrame(data=Com) df.to_csv('com.csv', index=False, header=True) print('done') </code></pre> <p>at the moment I am getting all the values for...
<p>You need to transpose the df first using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html#pandas.DataFrame.T" rel="noreferrer"><code>.T</code></a> prior to writing out to csv:</p> <pre><code>In [44]: l = list('abc') df = pd.DataFrame(l) df Out[44]: 0 0 a 1 b 2 c </code><...
python-3.x|csv|pandas|dataframe
5
356,314
41,051,043
How to eliminate the multiindex in pandas?
<p>I have the dataframe that you can see in figure A. I want it to be like figure B, so that I can plot bars. So, how can I eliminate all the indexes?</p> <p>Here is my code:</p> <pre><code> df2.reset_index('level_1',drop=True) df2.plot(kind='bar', subplots=True, figsize=(13,15), legend=False) </code></pre> <...
<p>You don't have a hierarchical index for either your index or your columns. What you are seeing is the names of the index and the columns. <code>level_0</code> is the name for the columns and <code>level_1</code> is the name for the index. They should not affect any code. If you want to eliminate them you can do <cod...
python-3.x|pandas|numpy
1
356,315
41,136,864
How can i find indices of element that bigger than special number from numpy 2d array?
<p>I want to find index of element that bigger than 2 from numpy 2d array.</p> <p>like this </p> <pre><code>import numpy as np a = np.array([[1,2,3],[4,5,6]]) # find indices of element that bigger than 2 # result = [[0,2],[[1,0],[1,1],[1,2]] </code></pre>
<p>You can use <code>np.where()</code> which will gives you the expected indices in a tuple mode (separate axis):</p> <pre><code>In [6]: np.where(a&gt;2) Out[6]: (array([0, 1, 1, 1]), array([2, 0, 1, 2])) </code></pre> <p>Or directly the <code>np.argwhere()</code>:</p> <pre><code>In [5]: np.argwhere(a&gt;2) Out[5]: ...
python|arrays|numpy|indexing|find
3
356,316
40,962,109
ImportError: numpy is not installed on your system
<p>I'm a new programmer with python. I'm using python 3.5 in a 64-bit windows. I was installed libpgm module but when i type <code>from libpgm.pgmlearner import PGMLearner</code> i got this error:</p> <p><code>ImportError, "numpy is not installed on your system." </code> Then i install numpy using pip. Now when i type...
<p>In order for the library to work, <code>"Python 2.7"</code> , <code>numpy</code> and <code>scipy</code>,are required,, unfortunately you are using <code>Python 3.5</code></p> <p>Go through <a href="http://pythonhosted.org/libpgm/" rel="nofollow noreferrer"><code>libpgm docs</code></a></p>
python|numpy
1
356,317
41,027,115
Are there any plans for ROI Pooling layer in tensorflow for object detection?
<p>I know this question has been asked several times before but I didn't find much on google except a few packages written by several authors. In any case is there any plan of including the roi pooling layer (officially) in tensorflow as it is a vital component for object detection and other tasks and not having access...
<p>I was able to find answer to my question with the paper above. You can use tf.image.crop_and_resize function to crop any part of the network and resize it. Similar to ROI pooling you can crop a bounding box (scale it down by the number of downsampling steps e.g. 32 in VGG16) and resize it to NxN (e.g. 7x7 in VGG16) ...
tensorflow
10
356,318
40,961,765
pandas read_excel() is reading thousands of empty lines and columns
<p>I am trying to read an excel file with pandas read_excel() function. I have around 50 filled lines and 15 columns. Strangely the function adds thousands of empty columns and lines to the DataFrame. I tried skipping the empty cells, but it still does not work.</p> <p>I assume that it has something to do with the for...
<p>This issue may be annoying, specially if a running R on a slow computer such as mine. I suggest one to erase all the useless cell formatting, such as borders and colors and delete every cell just after the last cell with data using CRTL + SHIFT + DOWN ARROW to select them.</p>
pandas
0
356,319
40,924,184
Error while feeding images to TensorFlow graph
<p>I am attempting to load some images into a <code>TensorFlow</code> graph which are <code>RGB</code>, however I would like the graph to transform them to grayscale before processing.</p> <pre><code>x = tf.placeholder(tf.float32, shape=[None, 32, 32, 1], name='x') gray = tf.image.rgb_to_grayscale(x, name='grayscale'...
<p>The function <a href="https://www.tensorflow.org/api_docs/python/tf/image/rgb_to_grayscale" rel="nofollow noreferrer" title="tf.image.rgb_to_grayscale"><code>tf.image.rgb_to_graycale</code></a> expects an input tensor with its last dimension having size 3. For instance a batch of images of shape <code>(250, 32, 32, ...
numpy|tensorflow|conv-neural-network|grayscale
3
356,320
41,210,126
Python - Adding fields and labels to nested json file
<p>I have a dataframe as follows:</p> <pre><code>Name_ID | URL | Count | Rating ------------------------------------------------ ABC | www.example.com/ABC | 10 | 5 123 | www.example.com/123 | 9 | 4 XYZ | www.example.com/XYZ | 5 | 2 ABC111 | www.example.com/ABC111 | 5...
<p>Quite an interesting problem and a great question!</p> <p>You can improve your approach by reorganizing the code inside the loops and using <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehensions</a>. No need to delete things and introduce temp varia...
python|json|pandas|dictionary|dataframe
10
356,321
54,201,799
Pandas cannot read parquet files created in PySpark
<p>I am writing a parquet file from a Spark DataFrame the following way:</p> <pre><code>df.write.parquet("path/myfile.parquet", mode = "overwrite", compression="gzip") </code></pre> <p>This creates a folder with multiple files in it.</p> <p>When I try to read this into pandas, I get the following errors, depending o...
<p>The problem is that Spark partitions the file due to its distributed nature (each executor writes a file inside the directory that receives the filename). This is not something supported by Pandas, which expects a file, not a path.</p> <p>You can circumvent this issue in different ways:</p> <ul> <li><p>Reading the f...
python|pandas|apache-spark|pyspark|parquet
5
356,322
54,032,515
spectral centroid of numpy array
<p>I have a <code>.wav</code> file (in this example it is called "piano2.wav").</p> <p>i want to find the spectral centroid of in python.</p> <p>using the code from another post on here i have this function :</p> <pre><code>import numpy as np from scipy.io.wavfile import read def spectral_centroid(x, samplerate=441...
<p>You are trying to multiply arrays of different shapes (<code>magnitudes</code> and <code>freqs</code>):</p> <pre><code>a = np.arange(10) b = np.arange(5) print(a*b) </code></pre> <blockquote> <p>ValueError: operands could not be broadcast together with shapes (10,) (5,) </p> </blockquote> <p>This could help:</p...
python|arrays|numpy|scipy|wav
1
356,323
54,237,421
How to iterate over a nested field in another column to create a new column based off another value?
<p>I have a column in a df that is nested json in a list like so:</p> <pre><code>col1 nested-filed 1 [{nested_data}] </code></pre> <p>the data in the nested filed looks like this:</p> <pre><code>[{'field': 1, 'timestamp': 1511404149332, 'changed-timestamp': 0, 'identities': [{'type': 'leadid', 'value': '1...
<p>You might try out this -</p> <pre><code>import ast df.nested_filed = df.nested_filed.apply(lambda x: ast.literal_eval(x)) # Store in a new column named email df['email'] = df.nested_filed.apply(lambda x: x[2]['value']) # Store in a new column named ID df['ID'] = df.nested_filed.apply(lambda x: x[1]['value']) </co...
json|python-3.x|pandas|dataframe|nested
0
356,324
53,938,167
Why is Mozilla Deepspeech using Tensorflow 0.11 when I have 0.12 installed?
<p>I use Anaconda3 with python 3.6 and use pip install tensorflow deepspeech.</p> <p>When I run the following command I get errors:</p> <p>deepspeech --model models/output_graph.pb --alphabet models/alphabet.txt --audio voice.wav</p> <pre><code>Loading model from file models/output_graph.pb TensorFlow: v1.11.0-9-g97...
<p>Just a side note: it seems like the current version of <code>deepspeech</code> on <code>pypi</code> uses <code>tensorflow == 1.11.0</code>. I did not inspected the <code>*.whl</code> packages, but the upload date <a href="https://pypi.org/project/deepspeech/#files" rel="nofollow noreferrer">here</a> indicates that t...
tensorflow|mozilla-deepspeech
0
356,325
54,150,070
Sort by descending order within each group
<p>I have following dataframe in pandas</p> <pre><code> code date time tank 123 01-01-2018 08:00:00 1 123 01-01-2018 11:00:00 1 123 01-01-2018 12:00:00 1 123 01-01-2018 13:00:00 1 123 01-01-2018 07:00:00 1 123 01-01-2018 09:00:00 ...
<p>How about sorting by every grouper key column, with "time" in descending?</p> <pre><code>df.sort_values(['code', 'date', 'tank', 'time'], ascending=[True]*3 + [False]) code date time tank 3 123 01-01-2018 13:00:00 1 2 123 01-01-2018 12:00:00 1 1 123 01-01-2018 11:00:00 1...
python|pandas|dataframe|group-by|pandas-groupby
2
356,326
53,835,823
Using the amount of bars to set the width/labelsize of a bar chart
<p>I am pretty new to using Matplotlib</p> <p>I couldn't figure out how to apply the things I found to my own graph, so I decided to make my own post</p> <p>I use this code to generate my bar chart:</p> <pre><code>p = (len(dfrapport.index)) p1 = p * 2.5 p2 = p * 1.5 height = dfrapport['aantal'] bars = dfrapport['s...
<p><code>plt.figure(figsize=(p1,p2))</code> is the correct approach. The question is hence a bit unclear, because you just need to put it in your code, e.g.</p> <pre><code>p = (len(dfrapport.index)) p1 = p * 2.5 p2 = p * 1.5 plt.figure(figsize=(p1,p2)) # ... plt.bar(...) </code></pre> <p>This is also shown in the q...
python|pandas|matplotlib
1
356,327
54,121,770
Get a column value to be replaced with another column value based on condition
<p>Getting errors when replacing a column value with another column's value based on condition.</p> <p>Here is the code...</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'A' : 1., 'B' : pd.Timestamp('20130102'), 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), 'D' : [1, 2, 1, 3], '...
<p>Setting the Categorical's categories allows this to work:</p> <pre><code>In [7]: df = pd.DataFrame({ 'A' : 1., ...: 'B' : pd.Timestamp('20130102'), ...: 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), ...: 'D' : [1, 2, 1, 3], ...: 'E' : pd.Categorical(["test","train","test","train"], categories...
pandas
1
356,328
53,856,695
DataFrame does not allow Timestamps conversion for resampling
<p>I have a 12 millions entries csv file that I imported as dataframe with pandas that looks like this.</p> <pre><code>pair time open close 0 AUD/JPY 20170102 00:00:08.238 83.774002 84.626999 1 AUD/JPY 20170102 00:00:08.352 83.774002 84.626999 2 AUD/JPY 20170102 00:00:13.662 84.184998 84.324...
<p>can you try:</p> <pre><code>import datetime as dt df['time']=pd.to_datetime(df['time'], format="%y/%m/%d") df['timeconvert'] = df['time'].dt.date </code></pre>
python|pandas|datetime|dataframe|timestamp
0
356,329
53,831,587
Trouble building tensorflow serving from source
<pre><code> Step 40/44 : RUN ln -s /usr/local/cuda/lib64/stubs/libcuda.so /usr/local/cuda/lib64/stubs/libcuda.so.1 &amp;&amp; LD_LIBRARY_PATH=/usr/local/cuda/lib64/stubs:${LD_LIBRARY_PATH} bazel build --color=yes --curses=yes --config=cuda --copt="-fPIC" ${TF_SERVING_BAZEL_OPTIONS} --verbose_failures ...
<p>The problem was because the CPU (Intel Celeron) was not good enough, upgrading the CPU to Intel I5 solved the problem.</p>
tensorflow|tensorflow-serving
0
356,330
53,852,279
Iterate over Pandas dataframe containing nested json dicts with arrays
<p>I have a list of more or less homogeneous json dicts, which I loaded into a Pandas dataframe. Any given dict can contain <strong>an arbitraty number</strong> of levels made only of another dicts or arrays, for example:</p> <p><code>[ {"id": [0], "options": [{"name": "dhl", "price": 10}]}, {"id": [0, 1], "op...
<p><strong>I did my vectorized solution for this using <code>apply(pd.Series)</code></strong>, although I had to write some additional code to make it work as expected.</p> <p><code>flatten_list_cols</code> - for columns with list of <strong>primitive</strong> elements in it<br> <code>flatten_list_of_dict_cols</code> ...
python|pandas|performance|dataframe
0
356,331
54,039,093
pandas to_sql insert ignore
<p>I want to incrementally keep adding data frame rows into MySQL DB avoiding any duplicate entries to go in MySQL.</p> <p>I am currently doing this by looping through every row using df.apply()and calling MySQL insert ignore(duplicates) to add unique rows into MySQL database. But using pandas.apply is very slow(45 se...
<p>You can create a temporary table:</p> <pre><code>nifty_data.to_sql(name='temporary_table', con=engine, if_exists = 'append', index=False) </code></pre> <p>And then run an INSERT IGNORE statement from that:</p> <pre><code>with engine.begin() as cnx: insert_sql = 'INSERT IGNORE INTO eod_data (SELECT * FROM temp...
python|pandas
14
356,332
54,041,992
Pandas dataframe use columns as rows (melt)
<p>I know, this questions has been asked several times, but I didn't manage to build my solution based on those already asked.</p> <p><strong>DF I have:</strong> </p> <pre><code>id| country | series name | 2015 | 2016 | 2017 --+----------+----------------+------+------+------ 0 | saudi | fertility rate | 1 ...
<p>IIUC <code>melt</code> + <code>pivot_table</code>. This answer assumes that <code>id</code> is your index. If it is not, just drop it, as it is not needed in the calculation.</p> <hr> <pre><code>d = df.melt(id_vars=["country", "series name"], var_name="year") d.pivot_table( index=["country", "year"], column...
python|pandas|melt
6
356,333
54,181,878
How do you isolate the night periods that fall between days, as the periods you want are not all on the same day?
<p>I want to pick the periods that fall over the night. So, for example, the evening on the 27th of April will run from (let's say) 2017-04-27 18:00 to 2017-04-28 06:30. </p> <p>I am currently running a for loop that takes the dates out of a Dataframe called data_input</p> <pre><code>for dates in data_input.index: <...
<p>So turns out writing the question helped me think through some ways of how to actually do it. </p> <p>I thought I would share my own solution, just in case anyone else has this issue. </p> <p>Basically, the solution is to create two masks, one for the night that ay, and another for the early morning the next day a...
python|pandas|datetime
1
356,334
54,203,177
Remove NaN Values From Right Column While Retaining Values In Left Columns
<p>I have three dataframes that I merge together that I then remove the duplicates from. But when I remove duplicates from my last three columns, I get NaN values at the tops of the dataframe that I want to remove but can't seem to find a way of doing so.</p> <p>Here is my code so far:</p> <pre><code>bDF=pd.read_csv(...
<blockquote> <p>I then go to remove duplicates from the first 4 columns, then the last three columns, finally the middle column:</p> </blockquote> <p>Assuming these are the steps you want to do, try <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow n...
python|pandas|numpy|dataframe
0
356,335
53,926,246
How to read a text file that has integers ranging from 0-255 (representing grayscale pixels of images) and convert into a 2D array?
<p>I have a text file that has integers ranging from 0-255 (grayscale values of images of digits) all separated by tabs. I want to read the file using pandas/numpy and arrange it into a 2D array with 784 columns(representing the pixel values for each image) and the number of rows corresponding to the number of sample i...
<blockquote> <p>I want to read the file using pandas/numpy and arrange it into a 2D array with 1 column</p> <p>So each row would have 784 integers</p> </blockquote> <p>If you want each row to have 784 integers, then you want 784 columns.</p> <p>You can probably do something like this:</p> <p><code>images = pd.read_csv(...
python|pandas|numpy|multidimensional-array
0
356,336
53,838,468
Aggregate DataFrame over Index
<p>I have following DataFrame</p> <pre><code> (polygon object) ASSAULT BURGLARY bank cafe crossing INCIDENTDATE 2009-01-01 02:00:00 A 1 0 0 1 0 2009-...
<p>The <code>max</code> function should do this:</p> <pre><code>df.groupby("INCIDENTDATE").agg("max") </code></pre>
python|pandas|aggregate|geopandas
2
356,337
54,197,329
Convert pandas df from long to wide and then into a sparse matrix
<p>I have this dataset:</p> <pre><code>ARTID INFO_1 INFO_2 00001 some_info_11 some_info_21 00002 some_info_12 some_info_22 00003 some_info_13 some_info_23 </code></pre> <p>and I want to transform like this</p> <pre><code>ARTID some_info_11 some_info_12 some_info_13 some_info_21 some...
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow noreferrer"><code>pd.get_dummies()</code></a> and <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.concat.html" rel="nofollow noreferrer"><code>pd.concat()</code></a></p> <pre><...
python|pandas|sparse-matrix
1
356,338
53,874,732
Same model produces consistently different accuracies in Keras and Tensorflow
<p>I'm trying to implement the same model in Keras, and in Tensorflow using Keras layers, using custom data. The two models produce consistently different accuracies over many times of training (keras ~71%, tensorflow ~65%). I want tensorflow to do as well as keras so I can go into the tensorflow iterations to tweak so...
<p>It seems to me that this is most probably the weight initialization problem. What I would suggest you to do is to initialize <code>keras</code> layers and before training get the layer weights and initialize <code>tf</code> layers with those values. </p> <p>I have ran into that kind of problems and it solved proble...
python|tensorflow|keras|neural-network
0
356,339
53,822,902
Pandas - skip NULL value in calculation
<p>I need to add field to my DataFrame with calculated distance between Location A and Location B. I have this code which works fine for fields with not empty coordinates:</p> <pre><code>df['Distance_AB'] = df.apply(lambda x: great_circle((x['latitude_A'],x['longitude_A']), (x['latitude_B'], x['longitude_B'])).meters,...
<p>I assume either your function <code>great_circle</code> is not vectorisable or vectorisation is out of scope for your question. Since <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>pd.DataFrame.apply</code></a> is already a Python-level lo...
python|pandas|dataframe|null|valueerror
5
356,340
54,001,880
make virtualenv with specific python version(MACOS)
<p>I installed brew, python3 (default and latest version) and pip3, pyenv.</p> <p>TensorFlow does not support python3.7 now, so I heard that I should make a virtualenv that runs 3.6 or lower version independently.</p> <p>I installed python 3.6.7 by <code>pyenv install 3.6.7</code> but can't make <code>virtualenv -p 3...
<p>You don't need the executable to be on the PATH. Assuming you want <code>/usr/local/bin/python3.6.7</code> to be used in the virtual environment,</p> <pre><code>virtualenv -p /usr/local/bin/python3.6.7 mydir </code></pre> <p>Updating your <code>PATH</code> is easy:</p> <pre><code>PATH=/usr/local/bin:$PATH </code...
python|macos|tensorflow|installation
2
356,341
53,891,542
Creating dataframe from Nested Dictionary
<p>I am calling an API that returns a batch request of multiple stock tickers in JSON format. It is a nested dictionary, with 2 levels of keys and then a list of dictionaries. Here is the script:</p> <pre><code>import json import requests import pandas as pd r = requests.get('https://api.iextrading.com/1.0/stock/mark...
<p>This will do the job, not sure if it's the cleanest way: </p> <pre><code>import json import requests import pandas as pd r = requests.get('https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,wpx,mnro,twnk,labl,plnt,fsct,qyls,vrns,tree&amp;types=chart&amp;range=3m') x = r.json() output = pd.DataFrame...
python|pandas|api|dictionary|nested
0
356,342
54,055,655
Pandas - how to pass variable as column into nested loop?
<p>I have a nested loop that I'm trying to pass values from a list into, but it will not recognize the list value. If I replace the <code>value[col]</code> with any list value like <code>value['OpNo']</code> it works. Is there a specific wrapper or something I need around either the list values or the assignment code?<...
<p>I'm not sure if this is going to help you exactly, but maybe it'll get you in the right direction. You can use Pandas.DataFrame.itertuples() to run across all rows in your dataframe, picking off values as you need them.</p> <p>I went a bit further and created a quick column label dictionary to help sync the nested...
python|pandas|loops|dataframe
2
356,343
53,840,372
Error while trying to read a csv using pandas.
<p>My xor.csv is: </p> <pre><code>x1,x2,x3,x4,y 0,0,0,0,0 0,0,0,1,1 0,0,1,0,1 0,0,1,1,0 0,1,0,0,1 0,1,0,1,0 0,1,1,0,0 0,1,1,1,1 </code></pre> <p>Code to fetch this file using pandas is: </p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt testing_data = pd.read_csv('..\Data_Set\x...
<p>Pass dataset path as either by single forward slash(/) or by double backward slash(\\).</p> <p>Try this: </p> <p>testing_data = pd.read_csv('../Data_Set/xor.csv')</p> <p>or</p> <p>testing_data = pd.read_csv('..\\Data_Set\\xor.csv')</p> <p>or </p> <p>testing_data = pd.read_csv(r'..\Data_Set\xor.csv')</p> <p>Bo...
python|pandas
1
356,344
54,158,555
What is the difference between .any() and .any(1)?
<p>I have come across the <code>.any()</code> method several times. I used it quite a few times to check if a particular string is contained in a dataframe. In that case it returns a n array/dataframe (depending on how I wish to structure it) of Trues and Falses depending on whether the string matches the values of the...
<p><code>.any(1)</code> is the same as <code>.any(axis=1)</code>, which means look row-wise instead of per column.</p> <p>With this sample dataframe:</p> <pre><code> x1 x2 x3 0 1 1 0 1 0 0 0 2 1 0 0 </code></pre> <p>See the different outcomes:</p> <pre><code>import pandas as pd df = pd.read_c...
python|python-3.x|pandas
2
356,345
53,963,918
Numpy array with repeating pattern
<p>How do you create a <code>1 x n</code> array in NumPy following an incrementing pattern?</p> <p>For example:</p> <p><code>[0, 5, 10, 15, ... (n-1)*5]</code></p>
<p><code>np.arange</code> is the correct answer (as pointed out in the comments). For completeness, here's a list of simple 1-liners that will produce the desired array:</p> <ul> <li><code>np.arange(n)*5</code></li> <li><code>np.arange(0, n*5, 5)</code></li> <li><code>np.linspace(0, (n-1)*5, n, dtype=int)</code></li> ...
python|numpy|array-broadcasting|numpy-ndarray
1
356,346
54,069,183
Python: Convert a date and time into integers
<p>I want to convert the following pandas time stamp column into float32. </p> <p>I have filled up the <code>Date</code>, <code>Time</code> by the codes as given below</p> <pre><code> TimeStamp Date Time Day Time float32 04-01-2019 21:58 04-01-2019 21:58:33 ...
<p>You can use:</p> <pre><code>df = pd.DataFrame({'TimeStamp':['04-01-2019 21:58', '04-01-2019 20:23', '31-12-2018 19:26'] }) df['TimeStamp'] = pd.to_datetime(df['TimeStamp']) df['Date'] = df['TimeStamp'].dt.date df['Time'] = df['TimeStamp'].dt.time df['Day'] = df['TimeStamp'].dt.day df['time_float'] = (df['TimeStamp'...
python|pandas|datetime|dataframe
2
356,347
54,112,504
Compute hessian with respect to several variables in tensorflow
<p>Computing Hessian in tensorflow is quite easy:</p> <pre><code>x = tf.Variable([1., 1., 1.], dtype=tf.float32, name="x") f = (x[0] + x[1] ** 2 + x[0] * x[1] + x[2]) ** 2 hessian = tf.hessians(f, x) </code></pre> <p>This correctly returns</p> <pre><code>[[ 8., 20., 4.], [20., 34., 6.], [ 4., 6., 2.]] </co...
<p>EDIT: Here is a more fleshed out solution, essentially the same but for an arbitrary number of variables. Also I have added the option of using Python or TensorFlow loops for the Jacobian. Note the code assumes all variables are 1D tensors.</p> <pre><code>from itertools import combinations, count import tensorflow ...
python|tensorflow|hessian-matrix
2
356,348
54,019,847
Split and map original values to different pandas column
<p>I would like to map a function that splits names with the help of the <code>nameparser</code> package in python. </p> <p>The function I use is the following:</p> <pre><code>def extract_parts(name): first, middle, last = (HumanName(name)).first,(HumanName(name)).middle, (HumanName(name)).last return first, ...
<p>Assuming your dataframe has a <code>names</code> column, for example:</p> <pre><code> names 0 Ben Jerry 1 John Jack Joe 2 Dr. Amelia von Lugenwitz 3 Cristian Maria de Angel </code></pre> <p>You could use <a href="https://docs.python.org/3/library/functions.html#z...
python|pandas
1
356,349
54,051,279
How to retrain a neural network in Keras without restart the jupyter notebook?
<p>I constructed a simple neural network using Keras. And when I run it in jupyter notebook for the first time, I works perfectly well. But If I rerun it without changing anything, some problems happens. The following two pictures showing the screenshot for the first time and second time respectively. You can see the d...
<p>This is the standard code we use to reset the session before training again.</p> <pre><code>from keras import backend as K curr_session = tf.get_default_session() # close current session if curr_session is not None: curr_session.close() # reset graph K.clear_session() # create new session s = tf.InteractiveSes...
python|tensorflow|machine-learning|keras|jupyter-notebook
0
356,350
54,230,817
Keras LSTM is not getting added
<p>Here is the model that I am trying to create: </p> <pre><code>def build_model(inputs_size): # create model model = Sequential() model.add(LSTM(100,activation="relu")) model.add(Dense(100, input_dim=inputs_size, init='normal', activation='relu')) model.add(Dense(200, input_dim=inputs_size, init=...
<p>The problem is that you feed sequences of 2 dimension to the network while LSTM needs 3-dimensional sequences. Change your input to one_hot encoding and then pass it to the LSTM or use the embedding layer. Here is how your Netowrk should be:</p> <pre><code>import numpy as np from tensorflow.python.keras.layers impo...
python|python-3.x|tensorflow|keras|lstm
1
356,351
54,096,576
FileNotFoundError in python using jupyter notebook
<p>Its just a simple problem I face. I m trying to read my csv file in jupyter notebook. It shows me an error saying the FileNotFoundError . I couldnt find the apt solutions for this anywhere. Please helpme in getting rid of this error and read the csv file. thanks in advance</p> <p>The error is</p> <pre><code> File...
<p>From the information I have gathered in the comments, seems like an encoding issue.</p> <p>you can find the encoding by first installing <a href="https://pypi.org/project/chardet/" rel="nofollow noreferrer"><code>chardet</code></a> followed by the below code:</p> <pre><code>import chardet rawdata = open('D:\\s...
python|python-3.x|pandas|jupyter-notebook
1
356,352
38,302,718
Using binary indexers on a multi-index
<p>I have a DataFrame of the form:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table border="1" class="dataframe"&gt;\n &lt;thead&gt;\n &lt;tr style="text-al...
<p>I think you get values if <code>p &lt; 1</code> if use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre><code>print (p) Panama Contract Date 201501 2014-04-29 -1416.0 2014-04-...
python|pandas
0
356,353
38,360,546
Get number of fails and successes from a dataframe in time series
<p>With a dataFrame like this:</p> <pre><code>Time Status ResponseTime PID 2016-07-13 17:33:49 OK 1623 42 2016-07-13 17:33:50 KO 1593 35 2016-07-13 17:33:50 OK 1604 19 2016-07-13 17:33:51 KO 1605 ...
<pre><code>text = """Time Status ResponseTime PID 2016-07-13 17:33:49 OK 1623 42 2016-07-13 17:33:50 KO 1593 35 2016-07-13 17:33:50 OK 1604 19 2016-07-13 17:33:51 KO 1605 28 2016-07-13 17:33:5...
python|pandas|dataframe
3
356,354
38,152,316
Why am I getting incorrect results from scipy.optimize.fmin?
<pre><code>import pandas as pd from scipy.optimize import fmin data = pd.DataFrame({'DIV': [1,2,3]*3, 'MONTH': ['May','May','May','June','June','Jun','Jul','Jul','Jul'], 'C':[8]*9, 'U':[3,2,1]*3, 'S':[9]*9}) data.to_csv(r'C:\Users\mba...
<p><code>scipy.optimize.fmin</code> will pass the value it is trying to minimize as the first argument to the function. If you rewrite your function as </p> <pre><code>def e(r,c,u,s): #calculates average of the MAPEs return np.mean(mape(c,u,s,r)) </code></pre> <p>You get the correct results</p> <pre><code>for d ...
python|python-2.7|pandas|optimization|scipy
3
356,355
38,220,143
Is there a resize function in Python to resize an image as the tf.image.resize_images function of TensorFlow?
<p>I have a 4D ndarray of image data, which is organized as [NumberOfImages, <strong>RowsOfImage</strong>, <strong>ColumnsOfImage</strong>, ChannelsOfImage].</p> <p>Now I want to resize the images in the 4D ndarray to the new size, which is with the size of [NumberOfImages, <strong>NewRowsOfImage</strong>, <strong>New...
<p>use <code>numpy.resize</code>. See below example. All images has the same shape (in this case 768 x 1024 x 3). In this example, I switched the row number with the column number. <code>im_all</code> is your 4d array.</p> <pre><code>from scipy.misc import imread import numpy as np import matplotlib.pyplot as plt f = ...
python|image|numpy|tensorflow|scikit-image
1
356,356
38,146,985
Inverse filtering using Python
<p>Given an impulse response <code>h</code> and output <code>y</code> (both one-dimensional arrays), I'm trying to find a way to compute the inverse filter <code>x</code> such that <code>h * x = y</code>, where <code>*</code> denotes the convolution product.</p> <p>For example, suppose that the impulse response <code>...
<p>This is called deconvolution: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.deconvolve.html" rel="noreferrer">scipy.signal.deconvolve</a> will do this for you. Example where you know the original input signal <code>x</code>:</p> <pre><code>import numpy as np import scipy.signal as signal...
python|numpy|scipy|signal-processing|sympy
8
356,357
38,067,486
Calculate the total counts using pandas pivot table
<p>I have a dataframe like this:</p> <pre><code>student class subject date status jack class-1 maths 20150101 fail jack class-1 maths 20150205 win jack class-1 maths 20150310 fail jack class-1 maths 20150...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p> <pre><code>df = df.p...
python|pandas|dataframe|pivot|multiple-columns
0
356,358
38,376,478
Changing the scale of a tensor in tensorflow
<p>Sorry if I messed up the title, I didn't know how to phrase this. Anyways, I have a tensor of a set of values, but I want to make sure that every element in the tensor has a range from 0 - 255, (or 0 - 1 works too). However, I don't want to make all the values add up to 1 or 255 like softmax, I just want to down sca...
<p>You are trying to normalize the data. A classic normalization formula is this one:</p> <pre><code>normalize_value = (value − min_value) / (max_value − min_value) </code></pre> <p>The implementation on tensorflow will look like this:</p> <pre><code>tensor = tf.div( tf.subtract( tensor, tf.reduce_min(t...
python|tensorflow|conv-neural-network
41
356,359
38,152,389
Coalesce values from 2 columns into a single column in a pandas dataframe
<p>I'm looking for a method that behaves similarly to coalesce in T-SQL. I have 2 columns (column A and B) that are sparsely populated in a pandas dataframe. I'd like to create a new column using the following rules:</p> <ol> <li>If the value in column A <strong><em>is not null</em></strong>, use that value for the ne...
<p>use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.combine_first.html" rel="noreferrer">combine_first()</a>:</p> <pre><code>In [16]: df = pd.DataFrame(np.random.randint(0, 10, size=(10, 2)), columns=list('ab')) In [17]: df.loc[::2, 'a'] = np.nan In [18]: df Out[18]: a b 0 ...
python|pandas|numpy|dataframe
167
356,360
38,241,410
TensorFlow: Remember LSTM state for next batch (stateful LSTM)
<p>Given a trained LSTM model I want to perform inference for single timesteps, i.e. <code>seq_length = 1</code> in the example below. After each timestep the internal LSTM (memory and hidden) states need to be remembered for the next 'batch'. For the very beginning of the inference the internal LSTM states <code>init_...
<p>I found out it was easiest to save the whole state for all layers in a placeholder.</p> <pre><code>init_state = np.zeros((num_layers, 2, batch_size, state_size)) ... state_placeholder = tf.placeholder(tf.float32, [num_layers, 2, batch_size, state_size]) </code></pre> <p>Then unpack it and create a tuple of LSTMS...
python|tensorflow|lstm|recurrent-neural-network|stateful
23
356,361
38,427,206
Python/Pandas data alignment when using plot()
<p>I am using pandas to plot some data from a larger data set. I have the following code that sorts out specific columns (categories/description) and plots them from one large DF.</p> <pre><code>df.amt[df.categ=='A'].cumsum().plot(legend=True,label='A',figsize=(11,5)) df.amt[df.descrip=='B'].cumsum().plot(legend=True,...
<p>Almost certainly, you've introduced data into</p> <pre><code>df.amt[df.descrip=='B'].cumsum().plot(legend=True,label='B',figsize=(11,5)) </code></pre> <p>prior to when you believe. The only way for us to really help is for you to take the time to provide more detail and more code.</p> <p>consider the following:<...
python|pandas|plot
0
356,362
38,358,184
Im trying to create an image while using a list full of RGB values
<p>I am trying to create an image using a list full of RGB values where every one of them is a pixel ,I am also using numpy so i can edit the list by transforming it to a multidimensional array ;However, when i transform the list to an array , the tuples that contain the RGB values becomes a list that contains RGB valu...
<p>You can use a <a href="https://docs.python.org/2.7/tutorial/datastructures.html?list-comprehensions#list-comprehensions" rel="nofollow">list comprehension</a> to convert a list of lists into a list of tuples, like:</p> <pre><code>&gt;&gt;&gt; l = [[1,2,3], [2,3,4], [3,4,5]] &gt;&gt;&gt; l = [tuple(i) for i in l] &g...
python|arrays|list|numpy|colors
0
356,363
38,426,422
two plots from pandas dataframe with different vertical axes on the same figure
<p>i'm trying to plot in python a line plot and a bar plot on the same figure using data from pandas dataframe. i manage to get two axes on the plot and the legend displays two entries, but the first of the plots is not present.</p> <p>here's my code:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd...
<pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np x = pd.date_range(start='2016-07-15',periods=50,freq='D') y1 = np.sin(np.linspace(0,50)) y2 = np.cos(np.linspace(0,0.3)) data = pd.DataFrame({'y1':y1,'y2':y2,'x':x}) data.set_index('x') </code></pre> <p>So here is a dataframe with a bun...
python|pandas|matplotlib
1
356,364
38,449,806
Collapsing identical adjacent rows in a Pandas Series
<p>Basically if a column of my pandas dataframe looks like this:</p> <pre><code>[1 1 1 2 2 2 3 3 3 1 1] </code></pre> <p>I'd like it to be turned into the following:</p> <pre><code>[1 2 3 1] </code></pre>
<p>You could write a function that does the following:</p> <pre><code>x = pandas.Series([1 1 1 2 2 2 3 3 3 1 1]) y = x-x.shift(1) y[0] = 1 result = x[y!=0] </code></pre>
python|pandas
1
356,365
38,436,122
Naming Columns of a dataset in python
<p>I have a dataset which consists of 1000 columns but is not labeled. I want to label them such as {A,B,C.....}. How can I do this in python ? Since the dataset is too large to name it manually.</p>
<p>You can use the string conversions of their ASCII equivalent numbers to assign as the new column names. Now, two methods could be suggested to get those names and do the assignment.</p> <p>Using <code>chr</code> on an array of ASCII equivalent numbers in a loop -</p> <pre><code>df.columns=[chr(item) for item in 65...
python|pandas
0
356,366
38,439,774
Saving attachments from outlook, error when loading with pandas/xlrd
<p>I have this script, which has previously worked for other emails, to download attachments:</p> <pre><code>import win32com.client as win import xlrd outlook = win.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder("6") all_inbox = inbox.Items subject = 'Email w/Attachment' attac...
<p>take a look at this <a href="https://stackoverflow.com/questions/9623029/python-xlrd-unsupported-format-or-corrupt-file">question</a>. It's possible the file you are trying to download is not a true excel file, but a csv saved as an .xls file. The evidence is the error message <code>Expected BOF record; found b'\r\...
python|pandas|xlrd
0
356,367
38,144,056
pandas: conditions with str.contains()
<p>I have data </p> <pre><code>url https://s.youtube.com/api/stats/qoe?fexp=9416891%2C9419451%2C9422596%2C9428269%2C9428398%2C9428492%2C9431012%2C9431657%2C9431674%2C9433096%2C9433380%2C9433946%2C9434803%2C9435467%2C9435526%2C9435876%2C9436275%2C9436302%2C9436484%2C9437553%2C9437967%2C9438327%2C9438699%2C9439362%2C943...
<p>try</p> <pre><code>df[df['myurl']=df.url.to_string() df[df['myurl'].str.contains('youtube', case=False)] </code></pre>
python|pandas
0
356,368
38,362,699
How to index a day's range of rows in a Dataframe, using a datetime.date?
<p>My multi-indexed data frame is as follows:</p> <pre><code>df.head() Output Unit Timestamp 1 2016-06-01 00:00:00 225894.9 2016-06-01 01:00:00 225895.9 2016-06-01 02:00:00 225896.9 2016-06-01 03:00:00 225897.9 2016-...
<p>When you pass a string that looks like a datetime to the pandas selector <code>ix</code>, it uses it like a condition and returns all elements that satisfy. In this case, the string you are using evaluates to a day. Pandas runs <code>ix</code> and returns all rows within that day. When you pass the datetime objec...
python|pandas
2
356,369
38,395,379
No weights change, only the bias of the last convnet?
<p>i got a one-file python game, where a pixel in the first array should hunt (on the same postion in his array) a pixel in the second array. I trained it now for hours and hours and the only thing changes in the neural net seemed to be the bias of the last convnet ? I think, mostly the weights should change and not so...
<p>It seemed that batch_norm does not exist anymore, but there is batch_normalization ? would that be an correct implementation in my case ? </p> <pre><code>h_conv1 = tf.nn.relu(tf.nn.conv2d(input_layer, conv_weights_1, strides=[1, 4, 4, 1], padding="SAME") + conv_biases_1) #batch normalization bn_mean, bn_variance =...
machine-learning|tensorflow
0
356,370
38,287,400
ValueError: Item wrong length 907 instead of 2000
<p>I have a csv file, that has 1000 columns. I need to read only the first 100 columns. I wrote this program for that:</p> <pre><code>import pandas as pd list = [] for i in range (1, 100): list.append(i) df = pd.read_csv('piwik_37_2016-07-08.csv',dtype = "unicode") df = df[df.columns.isin(list)] df.to_csv('abc.cs...
<p>There are a lot of things strange about your code. For example, there is no reason to iterate over the range object and update a list just to get a list of numbers. Just use <code>list(range(1,100))</code>. </p> <p>However, if you just need the first 100 columns in the csv, there is built-in functionality for what ...
python|python-2.7|pandas
3
356,371
38,481,409
Pandas deleting row with df.drop doesn't work
<p>I have a DataFrame like this (first column is <code>index</code> (786...) and second <code>day</code> (25...) and <code>Rainfall amount</code> is empty): </p> <pre><code>Day Rainfall amount (millimetres) 786 25 787 26 788 27 ...
<p>While dropping new DataFrame returns. If you want to apply changes to the current DataFrame you have to specify <code>inplace</code> parameter.</p> <p><strong>Option 1</strong><br> Assigning back to <code>df</code> -</p> <pre><code>df = df.drop(790) </code></pre> <hr> <p><strong>Option 2</strong><br> Inplace arg...
python|python-3.x|pandas|dataframe
77
356,372
66,164,638
Problem subsetting vector from an index that doesn't start from 0
<p>I am getting an error when subsetting a vector from an index that doesn't start from 0. In my code, I want to split to train and test sets. So I subset the first 158 elements for the train set and the last 78 elements for the test set. But the test set refuses to work and gives me a Key Error. Am I missing something...
<p>You are working with pandas Series here, not python list, that is why it does not work as you expect. <code>xts[0]</code> tries to find value <code>0</code> within the index of your testing set, but this index seems to start at <code>158</code>, so it raises a KeyError.</p> <p>You can convert your pandas Series to a...
python|pandas|dataframe
1
356,373
66,199,767
Formatting two arrays with a correlation Numpy Python
<p>I am trying to write a numpy function where <code>Numbers</code> and <code>value</code> are in correlation with each other and if the element of <code>Numbers</code> array is smaller than the <code>value</code> element than it will return the number 0 if the case is otherwise the returned number will be 1. If the nu...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a>:</p> <pre><code>&gt;&gt;&gt; np.select(condlist=[Numbers&gt;value, Numbers&lt;value, Numbers==value], choicelist=[1, 0, 2]) array([1, 1, 0, 1, 0, 2]) </code></pre>
python|arrays|function|numpy|format
2
356,374
66,243,548
How to check if a value is in 1 or 2 list-columns with pandas
<p>I build a pandas dataframe from json data :</p> <pre><code> { 'bundle': 'R_FLUSH_DEADLETTERS', 'envs': ['AG','DEV','QUAL','QUAL2','PREPROD','PREPROD2','PROD'], 'envsinfra2021': ['PREPROD2'], }, { 'bundle': 'R201_QA069_ETIQETTENS_FROMSAP', 'envs': ['DEV','QUAL','QUAL2','PREPROD'], '...
<p>Convert list to numpy arrays and add <code>|</code> for bitwise <code>OR</code>:</p> <pre><code>df = df[ np.array(['PROD' in x for x in df[&quot;envs&quot;]]) | np.array(['PROD' in x for x in df[&quot;envsinfra2021&quot;]])] print (df) bundle envs ...
python|pandas|list
1
356,375
66,098,224
Filter group by result in DataFrame
<p>I have DataFrame named 'concated'. It has columns: 'amount' - with a sums of transactions, 'mcccode_trtype' with a merchant type. I need to count only negative amounts of transactions by merchant code and count the mean of these transactions. And I need to filter merchants with more than 10 transactions.</p> <p>So, ...
<p>You can use <code>.loc</code> in combination with a lambda function as follows:</p> <pre><code>res = concated[concated.amount&lt;0].groupby('mcccode_trtype')['amount'].agg(['count', 'mean']).loc[lambda x: x[&quot;count&quot;] &gt; 10] </code></pre>
python|pandas|dataframe
1
356,376
66,145,627
Converting a pandas column to datetime with inconsistent format
<p>I have a pandas dataframe as below:</p> <pre><code>import pandas as pd df = pd.DataFrame({'col1':['abc', 'abc', 'xyz', 'xyz', 'cd'], 'col2':['2020-02-01 12:04:59', '2020.09.29.12.04.59', '2020.09.28.16.32.21', '2020-02-01 16:04:59', '2020-05-01 11:04:59']}) df col1 col2 0 abc 2020-02-01 12:04:59 1 abc 20...
<p>You can just remove all the non digit characters:</p> <pre><code>df['col2'] = pd.to_datetime(df['col2'].str.replace('\D','')) </code></pre> <p>Output:</p> <pre><code> col1 col2 0 abc 2020-02-01 12:04:59 1 abc 2020-09-29 12:04:59 2 xyz 2020-09-28 16:32:21 3 xyz 2020-02-01 16:04:59 4 cd 2020-05-0...
python-3.x|pandas
0
356,377
66,027,887
sort rows of each cell in pandas dataframe which are linked with columns
<p>I have dataframe like below.'prof' column and 'scores' col has a relation.i.e doctor in 'prof' col has score as -2.3 ,teacher has 9.1 score and nurse has 0.5 etc.,</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>val</th> <th>prof</th> <th>scores</th> </tr> </thead> <tbody> <tr> <td>F</td...
<p>Try this:</p> <pre><code>df.set_index('val').apply(pd.Series.explode).reset_index().sort_values(by=['val','scores'],ascending=False).groupby('val',as_index=False).agg(list) </code></pre>
pandas
0
356,378
65,961,108
Function to get Row and column of panda dataset
<p>I have a csv dataset with texts. I need to search through them. I couldn't find an easy way to search for a string in a dataset and get the row and column indexes. For example, let's say the dataset is like:</p> <pre><code>df = pd.DataFrame({&quot;China&quot;: ['Xi','Lee','Hung'], &quot;India&quot;: ['Roy','Rani','J...
<p>One vectorized (and therefore relatively scalable) solution to this is to leverage <code>numpy.where</code>:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np np.where(df == 'Rani') </code></pre> <p>This returns two arrays, corresponding to column and row indices:</p> <pre><code>(array([1]), ar...
python|pandas|csv
1
356,379
66,222,391
Can the Input of a trained U-Net (Convolutional Neural Network) be obtained from its Weights and Output?
<p>I have been given a trained U-Net (on tensorflow), but its performance is not great. For my research I would like to run this convolutional neural network in &quot;reverse&quot;. I would like to generate its Input by using the Weights (checkpoints) and its Output. I found a topic that had the same goal: <a href="htt...
<p>You can use <code>model.get_layer()</code> method to retrieve a layer based on either its name (unique) or index. I think using the index will be useful in your case. You can visit <a href="https://keras.io/api/models/model/#getlayer-method" rel="nofollow noreferrer">https://keras.io/api/models/model/#getlayer-meth...
python|tensorflow|neural-network|conv-neural-network
0
356,380
66,292,934
Cannot create pandas DataFrame from nested JSON file
<p>I am trying to retrieve <code>val1</code> and <code>val2</code> values from the following nested <code>json</code> file to build a pandas dataframe with two columns: <code>val1</code> and <code>val2</code>:</p> <pre><code>{ 'start': '2015-10-01 00:00', 'end': '2015-10-01 01:00', 'records': { 'val1':...
<p>Put your json to a variable or using <code>json.load</code>: then use <code>json_normalize</code></p> <p>[Here the example and the code]</p> <pre><code>import pandas as pd json = {'start': '2015-10-01 00:00','end': '2015-10-01 01:00','records': {'val1': [1,2,3,4,5],'val2':[0.1,0.5,0.2,0.1,0.0],'val3': 'abc'}} df =...
python|json|pandas
3
356,381
66,239,999
wide_to_long Valueerror : the id variables need to uniquely identify each row
<p>I have been using the pd.wide_to_long for quite some time in one of my scripts, however now there has been some underlying data change (in the rows) and it is giving the error: the id variables need to uniquely identify each row</p> <p>Some articles sugguest using reset_index twice, but that hasnt helped me. (not su...
<p>You can add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>DataFrame.reset_index</code></a> for another column passed to <code>i</code> parameter for avoid error:</p> <pre><code>df2 = pd.wide_to_long(df.reset_index(),stubnames=[&q...
python|pandas
1
356,382
66,201,175
Calculate dates differences in months beetwen dates in a groupby
<p>I have the following dataframe:</p> <pre><code>Id, country, date 1, ar, 2019-01-01 1, ar, , 2019-02-01 1, ar, 2019-03-01 1, it, , 2019-01-01 1, it, , 2019-02-01 1, it, 2019-03-01 1, it, , 2019-04-01 1, it, 2019-03-01 2, ar, 2019-01-01 2, ar, , 2019-02-01 2, ar, 2019-03-01 2, it, , 2019-01-01 2, it, , 2019-02-01 3, i...
<p>I adapted this <a href="https://stackoverflow.com/questions/40804265/how-to-calculate-time-difference-by-group-using-pandas">approach</a> to your case.</p> <p>Basically you have to deal with <code>NaT</code> values. I've chosen to treat them as <code>0</code>.</p> <p>And round the month to a integer, if you desire s...
python|pandas|datetime|pandas-groupby
0
356,383
66,019,541
Replace '-' Values in All Columns of Dataframe in For Loop
<p>I am scraping several financial metrics from Finviz using a for loop that iterates through a list of stock symbols. I am faced with an issue with the empty values ('-') on Finviz causing issues with subsetting the data down the line, as it is recognized as a string rather than a float, like the values I am trying to...
<p><code>df.replace()</code> is not an inplace operation. You need <code>df = df.replace()</code></p>
python|pandas|dataframe|replace
1
356,384
65,985,377
How to speed up reading DBF file to Dataframe in PYTHON?
<p>I am reading .dbf files into a dataframe using the following routine dbf2DF (<a href="https://gist.github.com/ryan-hill/f90b1c68f60d12baea81" rel="nofollow noreferrer">https://gist.github.com/ryan-hill/f90b1c68f60d12baea81</a>).</p> <pre><code>import pysal as ps import pandas as pd ''' Arguments --------- dbfile : ...
<p>You don't mention how many columns are in your file. That can have a significant impact on how long the following takes. The code below takes about 70 seconds on 1.3 million records with 33 columns. However, when the number of columns is reduced to 10, the time it takes is ~25 seconds.</p> <p>This code does not t...
pandas|dataframe|vectorization|dbf
3
356,385
66,119,489
distance euclidean in Python
<p>I am trying to compute the distance between a list of coordinates and one coordinate named <strong>cord</strong>.</p> <p>The expected result is a list with all distance between the i-th element of the list of coordinates and the cord.</p> <h1>Example:</h1> <p>I have a DataFrame <strong>df</strong> which has a column...
<p>You need to convert <code>x</code> of <code>numpy.linalg.norm</code> into <code>numpy.ndarray</code>:</p> <pre><code>df['Geo_Shape'].apply(lambda x: np.linalg.norm(np.array(x) - cord, axis=1)) </code></pre> <p>Output:</p> <pre><code>0 [3.0, 3.7107950630558943, 4.294182110716777] Name: Geo_Shape, dtype: object </c...
python|pandas|numpy|apply|distance
0
356,386
66,024,209
Pandas Series groupby specific hours
<p>I am looking for efficient implementation of grouping a pandas Series on <strong>gas day</strong> (related to trading of natural gas). This includes all hours/timestamps between 6AM and 6AM of the next day in CET timezone. Because of daylight saving time, once a year a gas day has 23 hours and once 25 hours. My curr...
<p>Is this equivalent to your code?</p> <pre><code>obj = pd.Series(pd.date_range('2020-10-23','2020-10-27', freq='H', tz='CET')[:-1]) cond = obj.dt.hour &lt; 6 obj2 = np.where(cond, obj.dt.date - pd.Timedelta(days=1), obj.dt.date) obj2 = pd.Series(obj2) obj3 = obj2.value_counts()....
pandas|time-series|pandas-groupby
2
356,387
66,306,094
How to remove column with number as index name?
<p>I have the following dataframe:</p> <p><a href="https://i.stack.imgur.com/92iqy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/92iqy.png" alt="enter image description here" /></a></p> <p>I tried to drop the data of <code>-1</code> column by using</p> <pre><code>df = df.drop(columns=['-1']) </code...
<p>You can test real columns names by converting them to list:</p> <pre><code>print (df.columns.tolist()) </code></pre> <hr /> <p>I think you need droping number <code>-1</code> instead string <code>'-1'</code>:</p> <pre><code>df = df.drop(columns=[-1]) </code></pre> <p>Or another solution with same ouput:</p> <pre><co...
python|pandas|jupyter-notebook
3
356,388
66,190,360
Isn't taking the mean of a pandas column of boolean values supposed to return the proportion that is True?
<p>So I took the mean of a pandas data frame column that contains boolean values. I've done this in the past multiple times and understood that it would return the proportion that is True. But when I wrote it in this particular instance, it didn't work. It returns the proportion that is False and not only that, the ...
<p>If we run your code, you can see that <code>datadf['increase']</code> is an object instead of a boolean, so taking mean on this is most likely converting the categories to a number and so on.. basically something weird:</p> <pre><code>import pandas as pd datadf = pd.DataFrame({'price':[470,488.51,489.33,490.43,499.5...
python|pandas|boolean|mean
0
356,389
66,337,762
Row-wise counting the number of a string occurrences in a column based on another column, for the same row?
<p>The data types in a dataframe (object)are as follows:</p> <pre><code>id :int64 id_contains :object categories :object category contents :object dtype: object </code></pre> <p>The data looks like this currently, organized by id and category contents:</p> <pre><code>id id_contains cat...
<pre><code>import pandas as pd data = [ { &quot;id&quot;: 1, &quot;id_contains&quot;: &quot;a,b,c&quot;, &quot;categories&quot;: &quot;cat1&quot;, &quot;category_contents&quot;: &quot;a,b,c&quot; }, { &quot;id&quot;: 2, &quot;id_contains&quot;: &quot;d,c,a&quot;, &quot;categories&quot;: &quot;cat2&quot;, &quot;categor...
pandas|string|dataframe|loops|rows
1
356,390
66,101,847
What's the most efficient way to replace some given indices of a NumPy array?
<p>I have three arrays, <code>indices</code>, <code>values</code>, and <code>replace_values</code>. I have to loop over <code>indices</code>, replacing each value in <code>old_values[indices[i]]</code> with <code>new_values[i]</code>. What's the fastest possible way to do this? It feels like there should be some way to...
<p>Use <code>zip</code> to separate <code>x</code> and <code>y</code> indices, then cast to <code>tuple</code> and assign:</p> <pre><code>&gt;&gt;&gt; values[tuple(zip(*indices))] = replace_values &gt;&gt;&gt; values array([[[140, 150, 160], [ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0], ...
python|arrays|numpy
2
356,391
66,110,752
How do I run expit function on an array on a GPU?
<p>I am trying to benchmark a simple neural network based handwritten digit recognition application. It currently uses Numpy for matrices, and scipy's expit function for activation. As good as this was ( pretty basic network really), I wanted to run this whole thing on GPU, and hence decided to use Cupy library.</p> <p...
<p>I've just met the exactly same problem today, you could try defining functions with CuPy's <a href="https://docs.cupy.dev/en/stable/user_guide/kernel.html" rel="nofollow noreferrer">User-Defined Kernels</a>.</p> <p>For the sigmoid function:</p> <pre><code>import cupy as cp expit = cp.ElementwiseKernel( 'flo...
python|numpy|scipy|cupy
1
356,392
66,049,426
Python how to search value in one csv based on another csv - pandas?
<p>I'm trying to create a program that needs to search a csv file for matching values in another csv file.</p> <p>Here is what I have so far:</p> <pre><code>import pandas as pd import numpy as np listings = pd.read_csv(&quot;data/listings.csv&quot;) inventoryValue = pd.read_csv(&quot;data/inventoryValue.csv&quot;) #g...
<p>I believe what you want can be achieved using <code>isin</code>. This method is used to filter data frames by selecting rows with having a particular value in a particular column.</p> <p>In your case, you can create a <code>list</code> that contains all the unique values of <strong>Listings['Item Number']</strong>,...
python|pandas
2
356,393
65,952,109
Python range with np.intc
<p>Yesterday I asked here a question about a weird behavior of python <code>range()</code>. I accidentally used <code>range()</code> instead of <code>np.arange()</code>. But depending on the input int-type it works for mathematical operations or not. It was in a huge context, so I simplified the problem.</p> <pre class...
<p>Python sequences and scalars behave differently from numpy 1d arrays and scalars. Let's run through a few basic examples to get the hang of it (or skip to bottom if in a hurry):</p> <pre><code># define our test objects a_range = range(2,6) a_list = list(a_range) a_array = np.array(a_list) # ranges don't add a_range...
python|numpy|integer|range
3
356,394
66,027,724
Deep Learning / Keras : Should I use a very small learning rate for very small data (Input and Output values)?
<p>I am trying to train a neural network, supervised, with a big set of data (let say over 1 mio samples).</p> <p>The NN should solve a regression problem; it takes 4 input numerical values and predicts one numerical value. The values are scaled between 0 and 1.</p> <p>Each sample in the training set looks like:</p> <p...
<p>The obvious problem is you are using <code>relu</code> in the last dense layer. You need to make your last dense layer a linear layer. With other words, if you are doing regression, you don't need to use non-linearity function like <code>relu</code> in the last dense layer.</p> <p>Also, you really don't need to use ...
python|tensorflow|machine-learning|keras|deep-learning
0
356,395
66,272,483
Sklearn ValueError: Complex data not supported from K-ways Spectral partitioning function
<p>I was studying Spectral Clustering and come across a paper by Satyaki Sikdar about Spectral Community Detection. Source: <a href="https://www3.nd.edu/%7Ekogge/courses/cse60742-Fall2018/Public/StudentWork/KernelPaperFinal/SCD-Sikdar-final.pdf" rel="nofollow noreferrer">https://www3.nd.edu/~kogge/courses/cse60742-Fall...
<p>I now found out that I need to make my eigenvector to have real float32 type.</p> <p>So I change my eigenvector line from <code>eigenvecs = eigenvecs[:, 1:]</code> to <code>eigenvecs = eigenvecs[:, 1:].real.astype(np.float32)</code>.</p>
python|numpy|scikit-learn|scipy|networkx
0
356,396
66,018,872
How to reset row's value in Pandas for a dataframe?
<p>For example:</p> <pre><code>for index, row in df.iterrows(): if row['name'] == 'x': row['name'] = 'xxx' </code></pre> <p>Then how to write the updated row back to the df? Something like:</p> <pre><code> df[index] = row </code></pre> <p>Does this work?</p>
<p>If you want update your column based on if, i suggest: df['column'] = df.column.apply(lambda x: &quot;value if true&quot; if x == 'x' else 'value if false')</p> <p>column is the name of the column that you want to update</p>
python|pandas
0
356,397
65,960,785
concatenation of matrix with different dimensions
<p>I did the concatenation of the matrices as shown below in the output.</p> <p>But it's not very efficient because my code is specific to these two matrices. Is it possible to make it more efficient so that I don't have to rewrite the matrices in the code all the time, but so that it works automatically?</p> <p>I auto...
<p>An alternative:</p> <pre><code>In [246]: arr1 Out[246]: array([[11, 21, 31], [12, 22, 32], [13, 23, 32], [14, 24, 34]]) In [247]: arr3=np.repeat(arr2[:,None],3,1) # a variation on your tile In [248]: arr3 Out[248]: array([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]) In [...
numpy|loops|python-3.7|numpy-ndarray
0
356,398
66,286,944
Pandas Dataframe - Rate Calculation
<p>In the below csv I have 3 columns - Pass,Sex,Age. 1- Denotes Pass and 0 - Denotes Fail.I am trying to calculate the % of Female candidates who have passed and % of female candidates who has failed.</p> <p>I dont want to convert this into a series and then calculate - I want to use pandas - groupby or loc functionali...
<pre><code>df[df['Sex'] == 'female'].Pass.value_counts(normalize=True).mul(100) </code></pre>
pandas
0
356,399
66,178,328
adding dimensions to existing np arrays
<p>I'm trying to make a clean connection between the dimensions in a numpy array and the dimensions of a matrix via classical linear algebra. Suppose the following:</p> <pre><code>In [1] import numpy as np In [2] rand = np.random.RandomState(42) In [3] a = rand.rand(3,2) In [4] a Out[4]: array([[0.61185289, 0.1394...
<ol> <li>yes</li> <li>yes</li> <li>yes</li> <li>three 2x1 matrices each of which contains one vector of size 1</li> </ol> <p>Just find out using <a href="https://numpy.org/doc/stable/reference/generated/numpy.shape.html" rel="nofollow noreferrer">.shape</a>:</p> <pre class="lang-py prettyprint-override"><code>import nu...
python|numpy|linear-algebra
1