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 |
|---|---|---|---|---|---|---|
354,900 | 68,337,848 | How to find all columns contains string and put in a new columns? | <p>I was wondering how could I find all values that start with 'orange' from all the columns and parse it into new columns.</p>
<pre><code>data = pd.DataFrame({'a':["mango 2","mango 3",'apple 3', 'orange 1345','orange 2456','banana 1', "watermelon 2","mango 2","mango 3"... | <p>Let's try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> then filter by <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>str.contains</code></a>:</p... | python|pandas|dataframe|loops | 1 |
354,901 | 68,353,566 | drop rows based on dates | <p>Hello Python Experts,
I import data into a python dataframe from a csv file which goes through April 2021. But then I want to drop any data after 2019. Playing around with the data.drop() feature, but cant' seem to figure out the syntax. How do i drop all data after 2019 in the dataframe?</p>
<p>Please see my code a... | <p>Try <code>loc</code>:</p>
<pre><code>index_data.loc[:"2019"]
</code></pre> | python|pandas|dataframe|time-series|drop | 2 |
354,902 | 68,330,917 | Python/Pandas: checking if values are fixed in a DataFrame | <p>I have a Pandas DataFrame that looks like this table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>index_1</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
</tr>
<tr... | <p>IIUC, here's one way:</p>
<pre><code>df['change'] = df.groupby('index_1').transform(lambda x: x.size > 1).astype(int)
</code></pre>
<h4>OUTPUT:</h4>
<pre><code> index index_1 change
0 0 0 0
1 1 1 0
2 2 2 1
3 3 2 1
4 4 2 ... | python|pandas|dataframe | 1 |
354,903 | 68,402,709 | How to populate a column base on another dataframe column in Python? | <p>I asked a similar question the other day, but couldn't use the advice which I received there in my current issue.</p>
<p>How can I fill the "quanitity" column in df, with the same ticker position from "port_df" ?</p>
<pre><code>dataA = {'ID': ['1407','1726','2910','1890'],
'quanitity': ['... | <p>Add these lines after your code:</p>
<pre><code>my_dict = dict(zip(port['Symbol'], port['Position']))
df['quanitity'] = [my_dict[id] for id in df['ID']]
</code></pre>
<p>Solution:</p>
<pre><code>import pandas as pd
dataA = {'ID': ['1407','1726','2910','1890'],
'quanitity': ['nan','nan','nan','nan'],
... | python|pandas|dataframe|conditional-statements|missing-data | 1 |
354,904 | 68,177,899 | convert pytorch model with multiple networks to onnx | <p>I am trying to convert pytorch model with multiple networks to ONNX, and encounter some problem.</p>
<p>The git repo: <a href="https://github.com/InterDigitalInc/HRFAE" rel="nofollow noreferrer">https://github.com/InterDigitalInc/HRFAE</a></p>
<p>The Trainer Class:</p>
<pre><code>class Trainer(nn.Module):
def _... | <p>After research and try, I found a method which maybe in correct way:</p>
<p>Convert each net(Encoder, Mod_Net, Decoder) to onnx model, and handle their input/output in latter logic-process or any further procedure (e.g convert to tflite model).</p>
<p>I'm trying to port onto Android using this method.</p>
<p>#Edit 2... | deep-learning|pytorch|onnx | 1 |
354,905 | 68,130,863 | comparing two timeseries dataframes based on some conditions in pandas | <p>I have two timeseries dataframes <code>df1</code> and <code>df2</code>:</p>
<pre><code>df1 = pd.DataFrame({'date_1':['10/11/2017 0:00','10/11/2017 03:00','10/11/2017 06:00','10/11/2017 09:00'],
'value_1':[5000,1500,np.nan,2000]})
df1['date_1'] = pd.to_datetime(df1.date_1.astype(str), format='%m/%d... | <p>Input data:</p>
<pre><code>>>> df1
value_1
date_1
2017-10-11 00:00:00 5000.0
2017-10-11 03:00:00 1500.0
2017-10-11 06:00:00 1200.0
2017-10-11 09:00:00 NaN
>>> df2
value_2
date_2
2017-10-11 00:00:00 1500.0
2017-10-11 00:30:00 2050.0
2017-10-1... | python|pandas|dataframe|datetime|time-series | 1 |
354,906 | 68,387,576 | After creating a list of csv files, how do I merge them? | <p>I've created a list of csv files and cleaned them. I've been stuck on merging these lists of csv files together. Each csv file, after cleaning, have the same column labels. They also have an extra column labels. I need to merge the columns with the same name.</p>
<p>Here is an example of my code:</p>
<pre><code>os.l... | <pre class="lang-py prettyprint-override"><code>os.listdir(os.getcwd())
filelist = glob.glob('*.csv')
dfs = []
for file in filelist:
file_df = pd.read_csv(file)
#cleaning code section
print(file_df.head())
dfs.append(file_df)
df = pd.concat(dfs, ignore_index=True) # ignore_index to reset index in ... | pandas|list|csv|join|merge | 0 |
354,907 | 68,108,161 | How can I return two variables from a function on python 3? | <p>I have this dataframe:</p>
<pre><code>df.head()
Open High Low Close Volume day_month
2006-04-13 10:00:00 1921.75 1922.00 1918.00 1918.25 11782 2006-04-13
2006-04-13 10:30:00 1918.25 1931.75 1918.00 1931.00 39744 2006-04-13
2006-04-13 11:00:00 1931.25 ... | <p>I'm not able to test this at the time, but based on the traceback; Your function isn't returning any values which is why it states (expected 3, got 0) if you add return df_2 to the end of mp_va() function, it should fix your issue</p>
<pre><code>def mp_va(df):
global df_2
mp = MarketProfile(df, tick_size = 0... | python|pandas|dataframe | 2 |
354,908 | 68,082,362 | Require Max Value of previous 5 high values : Based on conditions | <p>I need help in the following code for finding the max value in the window of previous 5 rows. i don't why its not working. Could anyone please help?
I am trying to put the conditions as:
if day(1), then max value = value[day(1)]
elif day(1<n<=5), then max value = value[day(n)] if value[day(n)]>value[day(n-1... | <p>answering my question, i got the result from the following code, hope it helps and any better code is welcomed.</p>
<pre><code>def high_change(i, j) :
last_hval = np.nan
for a in range(i, j) :
if a == i :
last_hval = high_df1[a]
elif high_df1[a] > high_df1[(a-1)] :
... | python|pandas|dataframe|loops|series | 0 |
354,909 | 68,196,953 | Pandas vectorization instead of loop for two dataframes | <p>I have 2 dataframes.
My main dataframe <code>dffinal</code></p>
<pre><code> date id och och1 och2 och3 cch1 LCH L#
0 3/27/2020 1 -2.1 3 3 1 5 NaN NaN
1 4/9/2020 2 2.0 1 2 1 3 NaN NaN
</code></pre>
<p>My second dataframe <code>df2</code></p>
<pre><code> ... | <p>Only way I can think of by pandas methods without loops is a cross join after resetting the index and comparing with <code>df.all(1)</code></p>
<pre><code>cols = ['och1','och2','och3','cch1']
u = df2.reset_index().assign(k=1).merge(
dffinal.reset_index().assign(k=1),on='k',suffixes=('','_y'))
#for new Version of... | python|pandas|vectorization | 3 |
354,910 | 68,137,562 | accuracy for 1D CNN model is very low | <p>I tried to build 1D CNN model to DNA mutation classification I built the model and it works correctly but I get test data with low accuracy I have dataset like the picture bellow<img src="https://i.stack.imgur.com/JsBg9.png" alt="1" /></p>
<p>and this is my model</p>
<pre><code>vocab_size = 100
embedding_dim = 150
m... | <p>There are several methods that you can employ to generalize your model and improve test accuracy:</p>
<p>1- check to see if your datasets are unbalanced or not. unbalancing datasets means that the size of data in each class has substantially different.</p>
<p>2- you can use the data/image augmentation technique to i... | python|tensorflow|machine-learning|keras|conv-neural-network | 1 |
354,911 | 68,284,184 | Creating multiple panda strings | <p>Good morning community,</p>
<p>my goal is to visualise my data from my experiment I perform daily (this is, i want to plot it).</p>
<p>I wish to work with only one CSV, with its data and then I add, per each row, the date I performed the experiment.
The thing is that, every day, I have multiple rows of data.
In the ... | <p>The basic thing here is that you’re using a single name, <code>nom</code>, for all your dataframes. As soon as you build another dataframe, the previous one is replaced.</p>
<p>Now you could use instead a dictionary of dataframes:</p>
<pre><code>final_date = x.Date.iloc[-1]
por_fecha = {}
for i in range(final_date ... | python|pandas | 0 |
354,912 | 68,389,375 | Python ord() equivalent in NumPy | <p>In Python, to get the ASCII value of a character we can do:</p>
<pre><code>>>> x = ord('k')
>>> x
107
</code></pre>
<p>What is the equivalent Python "ord" method in NumPy? I see some solutions say to do hacks like list comprehension before passing it NumPy. However, I want a NumPy method ... | <p><a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.view.html" rel="nofollow noreferrer">numpy.ndarray.view</a> returns a view of the same array with another (equally sized) datatype, and should due to not copying anything pretty much be instantaneous.</p>
<pre><code>>>> x = np.array(['g... | numpy | 4 |
354,913 | 643,699 | How can I use numpy.correlate to do autocorrelation? | <p>I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. </p>
<p>I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is <em>not</em> the largest, as it ought to be... | <p>To answer your first question, <code>numpy.correlate(a, v, mode)</code> is performing the convolution of <code>a</code> with the reverse of <code>v</code> and giving the results clipped by the specified mode. The <a href="http://mathworld.wolfram.com/Convolution.html" rel="noreferrer">definition of convolution</a>, ... | python|math|numpy|numerical-methods | 141 |
354,914 | 59,422,954 | How to conver excel contents into python dictionary | <p>I have an excel spreadsheet with 1st column = IP subnet & the 2nd column = Firewall name, trying to use this data to create a dictionary.
e.g. excel format - </p>
<p>10.1.1.0/24 ASA_01</p>
<p>10.2.2.0/24 ASA_02</p>
<p>10.3.3.0/24 ASA_03</p>
<p>I am using pandas module to achieve... | <p>There is no first row with columns names, so add parameter <code>header=None</code> and then select second column called <code>1</code> for <code>Series</code>:</p>
<pre><code>fw = pandas.read_excel(host_file, index_col=0, header=None)[1].to_dict()
</code></pre> | python-3.x|pandas|ordereddictionary | 1 |
354,915 | 59,090,404 | Keras that does not support TensorFlow 2.0. We recommend using `tf.keras`, or alternatively, downgrading to TensorFlow 1.14 | <p>I am having an error regarding (Keras that does not support TensorFlow 2.0. We recommend using <code>tf.keras</code>, or alternatively, downgrading to TensorFlow 1.14.) any recommendations. </p>
<p>thanks </p>
<pre><code>import keras
#For building the Neural Network layer by layer
from keras.models import Sequenti... | <p>You should only have to change the imports at the top:</p>
<pre class="lang-py prettyprint-override"><code>from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras import Sequential
classifier = Sequential()
classifier.add(Dense(6, init = 'uniform', activation = 'relu', input_dim = 11))
</code... | python|tensorflow|keras|neural-network|tf.keras | 14 |
354,916 | 59,307,269 | Removing last character from pandas series only where it has a value | <p>I am new to Pandas and Python.</p>
<p>I have a dataframe which looks like this:</p>
<pre><code>A B
15.00% 21.1564
21.1564
21.1564
16.00% 1.1564
</code></pre>
<p>I am trying to get the differences between <code>B</code> and <code>A</code></p>
<pre><code>df_final['A'] = ... | <p>You can cast values in pandas by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="nofollow noreferrer"><code>Series.astype</code></a>:</p>
<pre><code>df_final['A'] = df_final['A'].str[:-1].astype(float)
</code></pre>
<p>Or if possible some non numeric values use <a... | python|pandas | 1 |
354,917 | 59,450,618 | Vectorized way to combine two dataframes into a y=mx+b result | <p>I have two pandas dataframes. One is a timeseries of <code>m</code> and <code>b</code> values from the typical <code>y=mx+b</code> function. The other dataframe (could be considered a series) is the <code>x</code> value for several different categories. (yes, the <code>x</code> is held fixed, and the linear para... | <p>Create <code>final_df</code> <code>DataFrame</code> by constructor by columns and index names and data are converted first column to numpy array, then multiple by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mul.html" rel="nofollow noreferrer"><code>DataFrame.mul</code></a> and... | python|python-3.x|pandas | 1 |
354,918 | 59,290,651 | How to visualize more than one kernel per layer in histograms using tensorboard | <p>I am currently using Tensorflow 2.0 with a simple CNN, i am initializing the first layer with some handcrafted filters that i would like to visualize during the learning process.</p>
<p>In the histogram part of tensorboard i only see the first kernel of the layer but i would like to see all of them. Is there an eas... | <p>Creating a small function that does this on the displaycallback during the epoch end is the way i solved it, is not the cleanest , and would be nice if someone can correct it :)</p>
<pre><code>class DisplayCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
variables_names = [v.name... | tensorboard|tensorflow2.0 | 0 |
354,919 | 59,214,276 | Converting Python dataframe column to date format | <p>I have a column in a dataframe that I want to convert to a date. The values of the column are either <code>DDMONYYY</code> or <code>DD Month YYYY 00:00:00.000 GMT</code>. For example, one row in the dataframe could have the value <code>31DEC2002</code> and the next row could have <code>31 December 2015 00:00:00.000 ... | <p>For me working <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with <code>utc=True</code> for converting all values to <code>UTC</code> and <code>errors='coerce'</code> for convert not parseable values to <code>NaT</co... | python|pandas | 3 |
354,920 | 59,462,354 | Discrepancy between R's Keras and Python's Keras -- Accuracy bug? | <p>I'm playing with some 2D CNN using Keras to predict <a href="https://www.kaggle.com/c/bike-sharing-demand" rel="nofollow noreferrer">Bike Sharing Demand</a>.</p>
<p>R performs very poorly vs Python, which reach good accuracy easily. I thought it was because of arrays shape (and some differences between R and Python... | <p>Well, as Skeydan explained to me in <a href="https://github.com/rstudio/keras/issues/956" rel="nofollow noreferrer">the issue I opened</a>, the difference in accuracy falls in the Keras <em>version</em> used.</p>
<p>In the Python code, changing from <code>import keras</code> to <code>import tensorflow.keras as kera... | python|r|tensorflow|keras | 2 |
354,921 | 59,331,854 | single person detection in latest bodypix | <p>When I try the bokeh segmentation effect using body-pix@1.0.0, It detects/segments the person (A) in front of the camera. If another person (B) is standing behind, away from A, B is being blurred out. If the person B comes very close to the contour of A, then person B is also getting detected. This is the preferred ... | <p>For those who wants to know the answer. Source: <a href="https://github.com/tensorflow/tfjs/issues/2547" rel="nofollow noreferrer">https://github.com/tensorflow/tfjs/issues/2547</a></p>
<p>If you want to use BodyPix 2.0 to only blur just a subset of people (e.g. the large people), a quick way would be to use BodyPi... | tensorflow|tensorflow.js|bodypix | 0 |
354,922 | 59,092,945 | Array brodcasting in numba with parallel | <p>I'm trying to do a Monte Carlo simulation faster by using numba and numpy.
Numba'0.45.1' and Numpy '1.16.4'
However, I do have an error when I use the parallel option with the following code : </p>
<pre class="lang-py prettyprint-override"><code>@njit
def foo():
clock = np.array([1,4,5,7,11,15,19])
detector... | <p>We at a minimum, i dont think numba can take lists for literals. Try np.array((1,4,5,7,11,15,19)), etc (parents instead of solid brackets)</p> | python|numpy|optimization|numba|array-broadcasting | 0 |
354,923 | 59,165,706 | Display multiple columns in Pandas Dataframe, but group by and count only one | <p>I have a dataframe similar to the following:</p>
<pre><code>df:
facility, location, nickname
factory, floor, flr
office, reception, rec
office, execsuite, es
office, cubicle, cub
training, conference,conf
</code></pre>
<p>My desired output is a grouped list with a count of "facility" and all va... | <p>You could groupby by <code>facility</code> and the set as index <code>facility</code> and <code>count</code>:</p>
<pre><code>df['count'] = df.groupby('facility')['facility'].transform('size')
print(df.set_index(['facility', 'count']))
</code></pre>
<p><strong>Output</strong></p>
<pre><code> locat... | python|python-3.x|pandas | 2 |
354,924 | 59,432,918 | pandas: how to filter rows by selecting range of columns? | <p>I have the following dataframe:</p>
<pre><code> name c1 c2 c3 c4 c5 c6 c7 c8
--- -- -- -- -- -- -- -- --
0 img1 0 1 1 0 0 0 1 0
1 img2 1 0 0 0 0 0 1 1
2 img3 1 0 0 1 0 1 0 0
...
</code></pre>
<p>I would like to select those rows that have at least one non-zero value (i.e, 1... | <pre><code># test data
from io import StringIO
data = StringIO('''name,c1,c2,c3,c4,c5,c6,c7,c8
img1,0,1,1,0,0,0,1,0
img2,1,0,0,0,0,0,1,1
img3,1,0,0,1,0,1,0,0''')
import pandas as pd
df = pd.read_csv(data)
# list of columns to be used
# select using column name
# cols = ['c{}'.format(i) for i in range(2,7)]
# selec... | python|pandas|dataframe | 2 |
354,925 | 59,259,421 | Numpy array - pixel coordinates | <p>I am trying to convert a black and white picture, represented as a numpy array with the shape <code>(640,480,1)</code> - where <code>640 is the x</code> value, - <code>480 the y</code> value, and the last one either a <code>0 or a 1</code> representing the mask.
Now I am trying to covert this array in a <code>(640*4... | <p>It sounds like you're one-hot encoding (I think) and the easiest way to do that with <code>numpy</code> is by indexing <code>np.eye(number_of_categories)</code></p>
<pre><code>img = np.random.randint(2, (640,480,1))
out = np.eye(2)[img.ravel()]
out.shape
Out[]: (307200, 2)
</code></pre>
<p>Not sure why you'd want... | numpy|mask | 1 |
354,926 | 59,191,897 | Keep original string values after pandas str.extract() if the regex doesn't match | <p>My input data:</p>
<pre><code>df=pd.DataFrame({'A':['adam','monica','joe doe','michael mo'], 'B':['david','valenti',np.nan,np.nan]})
print(df)
A B
0 adam david
1 monica valenti
2 joe doe NaN
3 michael mo NaN
</code></pre>
<p>I need to <strong>extract strings after sp... | <p>I think solution should be simplify - split by spaces and get second lists and pass to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a> function:</p>
<pre><code>df['B'] = df['B'].fillna(df['A'].str.split().str[1])
... | python|pandas | 1 |
354,927 | 59,468,927 | pandas: how to check for nulls in a float column? | <p>I am conditionally assigning a column based on whether another column is null:</p>
<pre><code>df = pd.DataFrame([
{ 'stripe_subscription_id': 1, 'status': 'past_due' },
{ 'stripe_subscription_id': 2, 'status': 'active' },
{ 'stripe_subscription_id': None, 'status': 'active' },
{ 'stripe_subscription_id'... | <p>With <code>pandas</code> and <code>numpy</code> we barely have to write our own functions, especially since our <a href="https://stackoverflow.com/questions/54432583/when-should-i-ever-want-to-use-pandas-apply-in-my-code/54432584#54432584">own functions will perform slow</a> because these are not vectorized and <cod... | pandas | 1 |
354,928 | 59,410,905 | Interpolation between two images (Numpy arrays) | <p>I have two images represented by numpy arrays. Images were recorded by a camera using different exposure times (say 1sec., 2sec). I would like to interpolate linearily between the images, in order to get an image of say exposuretime 1.5 sec.
Using a for loop going through each image pixel I solved the problem like t... | <p>Since the interpolation is linear, you can just take a weighted average of the two images in a single operation</p>
<pre><code>interpolatedImage = (image2 * (exposureTime - exposureTimes[0]) + \
image1 * (exposureTimes[1] - exposureTime) / \
(exposureTimes[1] - exposureTimes[0])
</code></pre> | image|numpy|interpolation | 0 |
354,929 | 59,456,887 | Combining two columns in a pandas dataframe depending on their value | <p>I want to combine two columns of a dataframe depending on their values. The values per row are going to be in one of three states:</p>
<p>A) Either they are both the same value,</p>
<p>B) Only one cell has a value</p>
<p>C) They are different values</p>
<p>For example: </p>
<p><a href="https://i.stack.imgur.co... | <p>You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine.html" rel="nofollow noreferrer">combine</a> method in Pandas</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({"departure":[327,427,429,np.nan], "arrival":[np.nan,427,431,457]})
selec... | python|pandas|dataframe | 2 |
354,930 | 59,143,641 | How to get useful data from TFLite Object Detection Python | <p>I have a raspberry pi 4, and I want to do object detection at a good frame rate. I tried tensorflow and YOLO but both run at 1 fps. So I am trying TensorFlow Lite. I have downloaded the tflite file and the labelmap.txt file. I have used <a href="https://www.tensorflow.org/lite/guide/inference" rel="nofollow noreferr... | <p>I solved this issue with the help of @daverim at github, where I had opened an issue. <a href="https://github.com/tensorflow/tensorflow/issues/34761" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/34761</a>. Here is the code to get useful data:</p>
<pre class="lang-py prettyprint-override... | python|tensorflow|raspberry-pi|object-detection-api|tensorflow-lite | 0 |
354,931 | 59,445,668 | fastest way to create a list from a numpy array of lists | <p>I have a numpy array of lists. this is of type numpy.ndarray:</p>
<pre><code> array([list([2692, 2711]), list([2751, 2770]), list([3455, 3462]),
list([4020, 4027]), list([7707, 7726]), list([7893, 7912]),
list([8118, 8126]), list([8174, 8179]), list([8215, 8234]),
list([9227, 9246]), list([9518, 9537]),... | <pre><code>>>> m[:, 0]
array([2692, 2751, 3455, 4020, 7707, 7893, 8118, 8174, 8215, 9227, 9518,
9839, 10002, 10024, 10158, 11346], dtype=object)
</code></pre> | numpy|numpy-ndarray | 1 |
354,932 | 59,072,838 | Error While reading the CSV in Jupyter Notebook via Pandas | <p>I am new to python and pandas, i am trying to import a structured csv file in jupyter notebook by using conventional code .i.e</p>
<pre><code>import pandas as pd
df=pd.read_csv("Datasets/Border_Crossing_Entry_Data")
df.head(5)
</code></pre>
<p>but every time i am getting the below error, please help me since i am ... | <p>I think that you just need to add <code>.csv</code> in the filename. So, please try:</p>
<pre><code>import pandas as pd
df=pd.read_csv("Datasets/Border_Crossing_Entry_Data.csv")
df.head(5)
</code></pre> | python|pandas|jupyter-notebook | 0 |
354,933 | 59,139,741 | Python create new dataframe column based on different rows | <p>So I am having dataframe which looks like this</p>
<pre><code> v1 v2
day1 x x
day2 x x
day3 x x
day4 x x
day5 x x
</code></pre>
<p>What I need is to add new column v3 which will be the difference "today's v1 - yesterday's v2"</p>
<p>I've tried <code>df[v3] = df[v1][1:] - df[v2][:-... | <p>IIUC, as your days monotonic increasing, you may subtract <code>v1</code> by <code>v2.shift()</code></p>
<pre><code>df['v3'] = df.v1 - df.v2.shift()
</code></pre> | python|pandas|numpy|dataframe | 2 |
354,934 | 59,423,816 | extract json string values in a panda column into a new columns with dynamic key in the first level | <p>Hi I have a very large dataset in csv file, which I read into a panda dataframe. One column has json strings that I want to extract the values into new columns. The pic below shows a few rows in my csv file. </p>
<p><a href="https://i.stack.imgur.com/dMEch.png" rel="nofollow noreferrer"><img src="https://i.stack.im... | <p>In your example you're parsing the same JSON multiple times. It's enough to parse it only once. For example:</p>
<pre><code>import pandas as pd
d1 = '{"605":{"price":"570", "address":"946", "status": "done", "#result":"good" }... | python|json|pandas|dataframe | 6 |
354,935 | 59,142,961 | I get "IndexError: list index out of range" when installing Pandas in python | <p>So, I installed pandas with cmd :</p>
<p><img src="https://i.stack.imgur.com/KhGX9.png" alt="CMD Screenshot"></p>
<p>but when I try to import it i get this error: </p>
<blockquote>
<p>Traceback (most recent call last): File
"C:/Users/Uros/Desktop/fasda.py", line 1, in
import pandas ModuleNotFoundErr... | <p>As the second screenshot shows, you need to install pandas for your the python interpreter that you use, like this:</p>
<pre><code>C:\Users\Uros\untitled\Scripts\python.exe -m pip install -U pandas
</code></pre> | python|pandas | 0 |
354,936 | 59,254,565 | Memory consumption in Python - lists, subscripting, and pointers | <p>I'm trying to understand how much memory Python objects use.</p>
<p>In the following code, I check the memory of a numpy array vs list as well as a subscripted numpy array:</p>
<pre><code>import sys, os, psutil, numpy as np
def size_of(obj):
return f'{sys.getsizeof(obj) / 1000000:,.0f} MB'
def get_memory_usag... | <pre><code>ONE_HUNDRED_MIL_NP = np.random.randint(-128,127,int(10**8),dtype='int8')
</code></pre>
<p>This makes an array. <code>ONE_HUNDRED_MIL_NP.nbytes</code> is a good measure of the array size. An array has some basic info like shape, strides, dtype, but the bulk of the space is a 1d data buffer that contains b... | python-3.x|numpy|memory|profiling | 0 |
354,937 | 59,365,982 | How can I make a small array from a bigger one? Python | <p>Imagine I have this transit matrix, which comes from the distances between each geographic point in a city. However I only will need to access certain points which I will try to optimize a route for it. In this case for example this is the whole matrix. The data inside the matrix is a float</p>
<pre><code> A B... | <p>If you use numpy, the solution is even simpler as the one proposed by Alexandr:</p>
<pre><code>import numpy as np
source = np.array([
[0, 1, 3, 20, 60, 100],
[4, 0, 7, 95, 29, 98],
[6, 5, 0, 36, 68, 120],
[12, 97, 3, 0, 94, 30],
[33, 34, 87, 34, 0, 40],
[45, 35, 45, 51, 86, 0]])
need = (0,... | python|arrays|pandas|matrix | 2 |
354,938 | 59,435,119 | How to create a histogram chart in excel using xlsxwriter? | <p>I am trying to create histograms in multiple sheets of an excel workbook. I can very easily crate chart using pandas or matplotlib libraries and show it in python output window. However I would like to plot the histogram chart in excel. I am using office 360. Is there a way to do so?</p> | <p>You can create a histogram chart with XlsxWriter using an Excel "Column" chart type: <a href="https://xlsxwriter.readthedocs.io/example_chart_column.html" rel="nofollow noreferrer">Column chart example</a></p>
<p><a href="https://i.stack.imgur.com/Ovtic.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur... | python|excel|pandas|matplotlib|xlsxwriter | 0 |
354,939 | 59,175,360 | filtering pandas dataframe with array of unique values | <p>I have a pandas DF with two columns, one columns consists of unique filenames and the other consists of that filenames' label. I also have a numpy array of the filenames that i can use for training my model. I need to extract the labels from the DF that match the filenames i can use. I tried this:</p>
<pre><code>x ... | <pre><code>list(DF[DF['filenames'].isin(nparray)]['label'])
</code></pre>
<p>Will give you a list with <code>label</code>s in <code>DF</code> where it's value in <code>filenames</code> is in <code>nparray</code> </p> | python|pandas|numpy|dataframe | 1 |
354,940 | 59,269,960 | Convert Nested Dictionary into Table/Parent Child Structure, Python 3.6 | <p>Want to convert nested Dictionary from the below code.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
url = 'https://www.bundesbank.de/en/statistics/time-series-databases/time-series-databases/743796/openAll?treeAnchor=BANKEN&statisticType=BBK_ITS'
result = requests.get(url)
soup = BeautifulSoup(... | <p>You can handle this using a recursive function.</p>
<pre><code>def get_pairs(data, parent=''):
rv = [(data['name'], parent)]
for d in data['children']:
rv.extend(get_pairs(d, parent=data['name']))
return rv
Data_Dict = get_child_nodes(soup.find("div", class_="statisticTree"))
pairs = get_p... | python|python-3.x|pandas|dataframe|dictionary | 1 |
354,941 | 59,473,314 | IndexError: too many indices for array ... an error when running this code | <p>I get the following error</p>
<blockquote>
<blockquote>
<p>IndexError: too many indices
for array</p>
</blockquote>
</blockquote>
<p>when running this code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
y = np.array([[208500, 181500,
223500,
... | <p>First, your variable named <code>input</code> is a 1D array. You can't use two indexes to access an 1D array. A good example is that you can't access a matrix only with one index or you can't access a vector with two indexes. </p>
<p>You can check the size of <code>input</code> if you execute <code>input.shape</cod... | python|numpy | 0 |
354,942 | 59,460,973 | ValueError while trying to add a prefix to the values of a dataframe column | <p>I am a beginner in python.
I am trying to add a prefix to one of my columns in pandas if it meets a certain condition but i get the following error "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."</p>
<p>Below is my code</p>
<pre><code>import pandas as pd... | <p>Change your code to:</p>
<pre><code>df['sk'] = df['sk'].apply(lambda txt: ('CE0' if len(txt) == 3 else 'CE') + txt)
</code></pre> | python|pandas | 1 |
354,943 | 59,311,652 | Reading JSON formatted file into pandas DataFrame | <p>I would like to read JSON formatter file into pandas DataFrame organizing datasets into row and columns. I have attached the picture of how data in my JSON file looks like. The raw data has 30 days of daily temperature data from 2010/01/01 to 2010/01/30.</p>
<p><a href="https://i.stack.imgur.com/0p6B9.png" rel="nof... | <p>The file is not a valid JSON data hence the pasrser is not able to detect objects properly. Use any online JSON validator like this: <a href="https://jsonlint.com/" rel="nofollow noreferrer">https://jsonlint.com/</a>
Once you fix the JSON. I would also advise you to use </p>
<pre><code>pd.read_json(<Path>)
</... | json|python-3.x|pandas|dataframe | 0 |
354,944 | 59,450,821 | Preparing stock data for k-means clustering with unique value in column | <p>I have Dhaka stock exchange data combined 359 stocks</p>
<p><a href="https://i.stack.imgur.com/Ko7Mr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ko7Mr.png" alt="enter image description here"></a></p>
<p>I want to preprocess this for k-means clustering. But non-uniqueness of symbol I can't pr... | <p>You'll likely want to <em>pivot</em> the data to have one row per ticker.</p>
<p>But I doubt it makes much sense to use k-means on this data. If you are serious about results, you'd need an approach that can deal with missing values, series of different length, and that can use the trading volume as weighting inste... | pandas|machine-learning|cluster-analysis|k-means | 0 |
354,945 | 59,153,876 | Pandas - Converting dataframe object to numbers | <p>I have a dataframe which looks like this. </p>
<pre><code>x_train.info()
Int64Index: 8330 entries, 16 to 8345
Data columns (total 4 columns):
userId 8330 non-null object
base_id 8330 non-null object
rating 8330 non-null object
dtypes: object(3)
</code></pre>
... | <p>Can you try converting it to numpy.int64?</p>
<pre><code>.astype(numpy.int64)
</code></pre>
<p>If you give an extract of the real data, it will be helpful to answer</p> | pandas|dataframe|type-conversion|sparse-matrix|dtype | 0 |
354,946 | 59,078,738 | How to improve model to prevent overfitting for very simple image classification | <p>First of all: I'm a beginner with TensorFlow (version2). I'm learning a lot by reading. However, I don't seem to find an answer to the following problem.</p>
<p>I'm trying to build a model for classifying images into three labels.
As you see in the graphs below my training accurary is quite ok, but the validation a... | <p>You want the network to output 3 possible labels so the last layer in your model should be able to do that. In practice you can change it to <code>Dense(3, activation='sigmoid')</code>.</p>
<p>I don't know why it doesn't give you any error during training but you should also check the way you are feeding inputs and... | tensorflow|google-colaboratory|tensorflow2.0 | 0 |
354,947 | 59,411,587 | Python - find items with multiple occurences and replace with mean | <p>For df:</p>
<pre><code>sample type count
sample1 red 5
sample1 red 7
sample1 green 3
sample2 red 2
sample2 green 8
sample2 green 8
sample2 green 2
sample3 red 4
sample3 blue 5
</code></pre>
<p>I would like to find items in "type" with multiple occurences and repla... | <p>I believe you can simplify solution to <code>mean</code> per all groups, because mean by value is same like this value:</p>
<pre><code>df = df.groupby(["sample","type"], as_index=False, sort=False)["count"].mean()
print (df)
sample type count
0 sample1 red 6
1 sample1 green 3
2 sample2 re... | python|pandas | 1 |
354,948 | 59,115,861 | Python 3.6: tensorflow install on windows failed with TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType | <p>I am new to Python and Tensorflow. I tried to install tensorflow using the command pip install --upgrade tensorflow. However, the installation fails at two points:</p>
<ol>
<li>Building wheel for wrapt (setup.py)</li>
<li>Running setup.py install for wrapt</li>
</ol>
<p>During both these instances, the error is th... | <p>I had same failure, tried older Python, older TensorFlow but no luck. Then fell upon this and it works for me (I'm on Windows). Make sure you do the following:</p>
<p><code>set WRAPT_INSTALL_EXTENSIONS=false</code></p>
<p>before running having <code>pip install tensorflow</code>.</p>
<p>Hope this helps!</p> | python|tensorflow|pip|typeerror|setup.py | 7 |
354,949 | 59,328,300 | How to modify the tensor data dimension in pytorch, thanks | <p>I want to transform the tensor data to numpy data and save it through Opencv, But the opencv require the data dimension must like such style [1, something, something, something], but my tensor data is a blend one, it'e size like [30, something, something, something],how can I modify the data dimension in pytorch.</p... | <pre><code>batch = next(iter(dataloader_test))
batch.shape
torch.Size([4, 3, 160, 160])
np.transpose(batch.numpy(), (0,2,3,1)).shape
(4, 160, 160, 3)
image = np.transpose(batch.numpy(), (0,2,3,1))
cv2.imwrite("image.png", image[0])
</code></pre>
<p>You might have to unNormalize the data before saving it though.</p... | python|opencv|pytorch | 0 |
354,950 | 59,065,060 | difference between two values in a pandas dataframe that are variable lengths apart | <p>I am trying to automatically calculate the profit/loss from my trades. currently i have my pandas daatframe set up to return a hold column that contains 1's while the purcahse is active and a -1 once i have sold. the price column records the price of the stock while the hold time and count columns keep track of how ... | <p><code>pd.groupby</code> is your friend here, albeit in a somewhat roundabout way. You can use it to get each individual "holding" series in a separate bin by comparing the values to 0 and the previous value - the "0" series also create a group here which we have to drop subsequently. </p>
<pre class="lang-py pretty... | pandas|shift|stock | 0 |
354,951 | 59,130,689 | Weighted average of multiple columns using groupby, dropping NaNs column-wise | <p>I have a situation like
<a href="https://stackoverflow.com/questions/33574908/pandas-group-weighted-average-of-multiple-columns">Pandas Group Weighted Average of Multiple Columns</a> but where some values of one column are sometimes NaN.</p>
<p>That is, I am doing the following:</p>
<pre><code>import pandas as pd
... | <p>With no cleaner answer than my proposal, I am suggesting that using the function below is not so bad:</p>
<pre><code>import pandas as pd
import numpy as np
def weighted_means_by_column_ignoring_NaNs(x, cols, w="weights"):
""" This takes a DataFrame and averages each data column (cols),
weighting observ... | python|pandas|numpy|pandas-groupby | 3 |
354,952 | 59,192,066 | Python - How to make crosstable in pandas from non numeric data? | <p>So, the thing is I need to create a crosstable from string data. I mean like in excel, if You put some string data into crosstable it is going to be automatically transformed into counted values per the other factor. For instance, I have column 'A' which contains application numbers and column 'B' which contains dat... | <p>Is this what you are looking for:</p>
<pre><code>df = pd.DataFrame([['app1', '01/01/2019'],
['app2', '01/02/2019'],
['app3', '01/02/2019'],
['app4', '01/02/2019'],
['app5', '01/04/2019'],
['app6', '01/04/2019']],
... | python|pandas|numpy|scipy|data-science | 0 |
354,953 | 59,341,045 | What does indexing into the result of a pandas groupby do? | <p>Let's say I have this dataframe,</p>
<pre><code>df = pd.DataFrame([['a', 'b', 'c'],
['1', '2', '3'],
['4', '5', '6']],
index=['A', 'B', 'C'],
columns=['x', 'y', 'z'])
x y z
A a b c
B 1 2 3
C 4 5 6
</code></pre>
... | <p>The new index is the new group you made with <code>groupby()</code>. The <code>['y']</code> will return the column <code>y</code>. But, you also need to call a function on your aggregated rows, like <code>sum()</code>. Here's an example:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = ... | python|pandas | 2 |
354,954 | 59,205,234 | Iterate over a dataframe with condition in column | <p>Suppose a dataframe as the following:</p>
<pre><code>df=pd.DataFrame({'word':['Hello','Beautiful','World','Work'],'classification':['none','none','noun','none'],'pos':[0,1,2,3]}
</code></pre>
<pre><code> word classification pos
0 Hello none 0
1 Beautiful none 1
2 World ... | <p>A direct <code>loc</code> assignment. I also handle cases where string <code>none</code> having <code>blank</code> such as <code>' none'</code> or <code>' none '</code></p>
<pre><code>df.loc[df.classification.str.strip().eq('none'), 'classification'] = 'any'
In [280]: df
Out[280]:
word classification pos... | python|pandas|dataframe|for-loop | 0 |
354,955 | 59,285,058 | Batch normalization layer for CNN-LSTM | <p>Suppose that I have a model like this (this is a model for time series forecasting):</p>
<pre><code>ipt = Input((data.shape[1] ,data.shape[2])) # 1
x = Conv1D(filters = 10, kernel_size = 3, padding = 'causal', activation = 'relu')(ipt) # 2
x = LSTM(15, return_sequences = False)(x) # 3
x = BatchNormalizati... | <p><strong>Update</strong>: the LayerNormalization implementation I was using was <em>inter-layer</em>, not <em>recurrent</em> as in the original paper; results with latter may prove superior.</p>
<hr>
<p><code>BatchNormalization</code> <em>can</em> work with LSTMs - the linked SO gives false advice; in fact, in my a... | tensorflow|keras|conv-neural-network|lstm|batch-normalization | 7 |
354,956 | 59,359,766 | Python pandas grouping according to a column, counting the cumulative value of its corresponding column | <p>I have had to deal with some problems today with python.</p>
<p>According to the sales area grouping, the corresponding shipments are accumulated and the shipment results are rounded. The value of a large area is NULL or empty, hoping to skip the statistics. The output csv file needs to have a large area + sales ar... | <p>use <code>groupby</code> as follows</p>
<h3>1. read csv into dataframe by trimming the whitespaces.</h3>
<pre class="lang-py prettyprint-override"><code>df = pd.read_csv('/Users/prince/Downloads/test2.csv', sep=',', skipinitialspace=True)
</code></pre>
<p>Output is</p>
<pre><code>Id Message region shipping volume ... | python|pandas|dataframe | 0 |
354,957 | 59,056,512 | How can I add number of entries as a new row in pandas data frame? | <p>I am working with Python and have a series which is as follows:</p>
<pre><code> view_count comment_count like_count dislike_count ratio_of_comments_per_view ratio_of_likes_per_view
count 2.200000e+01 21.000000 22.000000 22.000000 21.000000 22.000000
mean ... | <p>We can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.count.html" rel="nofollow noreferrer"><code>DataFrame.count</code></a>:</p>
<blockquote>
<p>For each column/row the number of non-NA/null entries. </p>
</blockquote>
<p><strong>If you want count by columns and add a n... | python|pandas|row|series | 1 |
354,958 | 59,146,085 | Divide a Python dataframe into groups, do operations, and reconnect the groups into the original dataframe | <p>I'm currently trying to get the difference of commute time between multiple stops on subway trips. So my dataframe currently looks like:</p>
<pre><code>route date trip_id
1 2015-07-10 23:35:45 000550_1..S02X020
1 2015-07-10 23:40:50 000550_1..S02X020
1 2015-07... | <p>Try this:</p>
<pre><code>df.date = pd.to_datetime(df.date)
df2 = df.groupby('trip_id').apply(lambda x: x-x.iloc[0])
</code></pre> | python|pandas | 1 |
354,959 | 59,377,246 | Downsampling a CSV by a factor of 10 and saving it into another file | <p>I have a .csv file with many rows (i.e. 3000 to 4000) in which each row represent an event with a sampling rate of <strong>1Hz</strong>. I want to create another .csv in which each row represent an event with a sampling rate of <strong>0.1Hz</strong>. </p>
<p>In other words I want to go from a .csv with a resolutio... | <p>Not too clear in which language you want to implement it. Here is a language agnostic plan:</p>
<ul>
<li>Ask the user for the file to load</li>
<li>Open the file in Read</li>
<li>Open another file in Write mode</li>
<li>Iterate through the Read file line by line.</li>
<li>Keep a counter and increment it everytime y... | python|c|pandas|csv|awk | 4 |
354,960 | 59,053,331 | Consecutive values in array with periodic boundaries in Python | <p>I have some 2D-arrays filled with <code>0</code> and <code>1</code>:</p>
<pre><code>import numpy as np
a = np.random.randint(2, size=(20, 20))
b = np.random.randint(2, size=(20, 20))
c = np.random.randint(2, size=(20, 20))
d = np.random.randint(2, size=(20, 20))
</code></pre>
<p>and I want to count the consecut... | <p>You can use <code>groupby</code> from <code>itertools</code>:</p>
<pre><code>from itertools import groupby
a = [1, 1, 0, 0, 1, 1, 0, 1, 1, 1]
def get_longest_seq(a):
if all(a):
return len(a)
a_lens = [len(list(it)) for k, it in groupby(a) if k != 0]
if a[0] == 1 and a[-1] == 1:
m = m... | python|numpy|counting | 1 |
354,961 | 14,349,084 | Using vectorisation with numpy for the Bellman-Ford algorithm | <p>I've been having a go at writing the Bellman Ford algoritm for finding the shortest path in a graph and while I've got a working solution it doesn't run very quickly and I'm led to believe it could be faster if I use numpy instead of my current approach.</p>
<p>This is the solution I have using for loops:</p>
<pre... | <p>I ended up with the following vectorised code after following Jaime's advice:</p>
<pre><code>def initialise_cache(vertices, s):
cache = empty(vertices)
cache[:] = float("inf")
cache[s] = 0
return cache
adjacency_matrix = zeros((vertices, vertices))
adjacency_matrix[:] = float("inf")
for line in... | python|numpy|bellman-ford | 0 |
354,962 | 14,344,099 | Smooth spline representation of an arbitrary contour, f(length) --> x,y | <p>Suppose I have a set of x,y coordinates that mark points along contour. Is there a way that I can build a spline representation of the contour that I can evaluate at a particular position along its length and recover interpolated x,y coordinates?</p>
<p>It is often not the case that there is a 1:1 correspondence be... | <p>You want to use a parametric spline, where instead of interpolating <code>y</code> from the <code>x</code> values, you set up a new parameter, <code>t</code>, and interpolate both <code>y</code> and <code>x</code> from the values of <code>t</code>, using univariate splines for both. How you assign <code>t</code> val... | numpy|scipy|curve-fitting|bezier|spline | 29 |
354,963 | 14,345,739 | Replacing part of string in python pandas dataframe | <p>I have a similar problem to the one posted here: </p>
<p><a href="https://stackoverflow.com/questions/13682044/pandas-dataframe-remove-unwanted-parts-from-strings-in-a-column">Pandas DataFrame: remove unwanted parts from strings in a column</a></p>
<p>I need to remove newline characters from within a string in a D... | <p><code>strip</code> only removes the specified characters at the beginning and end of the string. If you want to remove <em>all</em> <code>\n</code>, you need to use <code>replace</code>.</p>
<pre><code>misc['product_desc'] = misc['product_desc'].str.replace('\n', '')
</code></pre> | python|csv|pandas | 48 |
354,964 | 44,885,238 | Pandas Datareader - Module not found after installation | <p>I am trying to install & use Pandas-Datareader, but when after I have installed it, I receive a <code>ModuleNotFoundError</code> when I try and import it.</p>
<p>I am using Jupyter Notebook installed using Anaconda - so use the conda installer to install new packages.</p>
<p>After typing <code>source activate ... | <p>Are you running the notebook in the <code>ipykernel_py3</code> environment?</p>
<pre><code> source activate ipykernel_py3
ipython notebook
</code></pre> | python-3.x|pandas|anaconda|conda|pandas-datareader | 1 |
354,965 | 44,858,973 | Tensorflow textsum error of Versioning | <p>I am trying to convert the training text file to bin file for training the textsum of tensorflow. But I encountered the following error: </p>
<pre><code>$ python textsum/data_convert_example.py --command text_to_binary --in_file data/tt.txt --out_file data/bin_data_train
Traceback (most recent call last):
File "t... | <p>You must have a problem with your install. </p>
<p>Please try the following commands:</p>
<p><code>
pip install --upgrade mock
pip install --upgrade distribute
</code></p>
<p>If it does not work, you should give us more details about how you installed tensorflow (pip? conda? clone & setup.py?) and try to rein... | python|python-2.7|tensorflow|textsum | 1 |
354,966 | 45,250,467 | Plot certain days only pandas dataframe | <p>trying to get better at using Python and pandas...</p>
<p>I have some stock market data, I have added a day_of_week column(Monday, Tuesday, Wednesday, Thursday, Friday) based on the "Date" columnn, obviously theres Open, High, Low and Close columns as well for each day, and I've also added and pct-chance column, no... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.mean.html" rel="nofollow noreferrer"><code>mean</... | python|python-3.x|pandas|matplotlib|statistics | 1 |
354,967 | 45,222,675 | TensorFlow, Variable weights/layer1 already exists, disallowed | <p>I was using TensorFlow and encountered an error related to the problem of variable reuse. My code is as follows:</p>
<pre><code>INPUT_NODE = 3000
OUTPUT_NODE = 20
LAYER1_NODE = 500
def get_weight_variable(shape, regularizer):
weights = tf.get_variable(
"weights", shape,
initializer = tf... | <p>If you try to call <code>inference</code> in part <code>#with other codes follows#</code> you need to additional parameter <code>reuse</code>, something like this:</p>
<pre><code>....
def inference(input_tensor, regularizer, reuse):
with tf.variable_scope('layer1', reuse = reuse):
....
def train():
x... | tensorflow | 0 |
354,968 | 44,833,904 | Extracting two, rather than four, digit year from datetime object | <p>I am using the following code to create a new time variable in a pandas dataframe from a datetime object:</p>
<pre><code>data['Date'] = pd.to_datetime(data['Date'])
data['Year'] = data['Date'].apply(lambda x: x.year)
data['Month'] = data['Date'].apply(lambda x: x.month)
data['Day'] = data['Date'].apply(lambda x: x.... | <p>Use the date accessor with <code>strftime</code>: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><strong><code>pd.Series.dt.strftime</code></strong></a><br>
Refer to <a href="http://strftime.org/" rel="nofollow noreferrer"><strong>http://strft... | python|pandas|datetime | 3 |
354,969 | 45,159,133 | Does tf.one_hot() supports SparseTensor as indices parameter? | <p>I would like to ask whether <a href="https://www.tensorflow.org/api_docs/python/tf/one_hot" rel="nofollow noreferrer">tf.one_hot()</a> function supports SparseTensor as the "indices" parameter. I want to do a multi-label classification (each example has multiple labels) which requires to calculate a cross_entropy lo... | <p>You could build up another SparseTensor of shape <code>(batch_size, num_classes)</code> from the initial SparseTensor. For example if you keep your classes in a single string feature column (separated by spaces), you could use the following:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as t... | tensorflow|tflearn | 1 |
354,970 | 44,941,796 | Fetching content from html and write fetched content in a specific format in CSV | <p>I have HTML Code like:</p>
<pre><code><!-- Snippet snippets/search_result_text.html end -->
</h2>
<p class="filter-list">
<span class="facet">Organisations:</span>
<span class="filtered pill">**Reserve Bank of Australia**
<a hr... | <p>I try a bit modify original solution - best is loop only once and create one big <code>DataFrame</code> with all data. then only select columns with subset <code>[['col1','col2']</code> for new <code>DataFrames</code>.</p>
<p>Also for remove numbers with <code>()</code> is possible use <a href="http://pandas.pydata... | python|csv|pandas|beautifulsoup | 1 |
354,971 | 44,930,789 | How to run the python script in batches? | <p>I am looking for a solution to run the python command for a set of data in batches. For example, i want to run the below mentioned code for the first 10 rows,print output and run for the next batch until the row ends. Reason for doing this is that currently it is taking a lot of time to run 1000 rows.</p>
<p>Trying... | <p>I'd suggest using the GNU Parallel. Create a text file with each line being a command you need to run, eg</p>
<pre><code>python mycode.py someargs
python mycode.py someotherargs
...
</code></pre>
<p>Then simply run</p>
<pre><code>parallel commands.txt -j 8
</code></pre>
<p>It will bring up 8 (or however many you... | python|excel|tensorflow | 0 |
354,972 | 45,250,581 | 'str.contains' not returning values in dataframe | <p>I'm cleaning some text data and I'm not able to locate rows containing certain strings. If I do a simple boolean, I get:</p>
<pre><code>'<! [CDATA[! function( d,s, id){varjs, fjs=d. getElementsByTagName( s)[0],p= ^' in articles.loc[25111, 'content']
True
</code></pre>
<p>But if I select rows with that exact sa... | <p>I think some values are read as regex, so need parameter <code>regex=False</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="noreferrer"><code>str.contains</code></a>.</p>
<pre><code>s = '<! [CDATA[! function( d,s, id){varjs, fjs=d. getElementsByTagNam... | python|string|pandas | 7 |
354,973 | 44,876,296 | Python: Create New Fields in Dataframe Efficiently Based on Values in Existing Fields | <p>Currently, I have the following data frame table: </p>
<p><a href="https://i.stack.imgur.com/gpPrZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gpPrZ.png" alt="enter image description here"></a></p>
<p>This is the table I want to create (desired columns highlighted in yellow): </p>
<p><a hre... | <p>If you have this data in Pandas DataFrame it's really simple:</p>
<p>here is my sample df:</p>
<pre><code>df = pd.DataFrame([[np.NaN, np.NaN, np.NaN],['Significant',np.NaN, np.NaN],[np.NaN, "Yes", np.NaN], ["Significant", np.NaN, "Top Advisor"]], columns=['Advisor', 'Retirement', 'Recognition'])
</code></pre>
<p>... | python|loops|pandas|dataframe|field | 0 |
354,974 | 45,094,948 | How to swap the 0 and 1 values for each other in a pandas data frame? | <p>I am working with a pandas dataframe that has a column of all 0's and 1's and I am trying to switch each of the values (ie all of the 0's become 1's and all of the 1's become 0's). Is there an easy way to do this?</p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="noreferrer"><code>replace</code></a>:</p>
<pre><code>df = df.replace({0:1, 1:0})
</code></pre>
<p>Or faster <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_xor.html" rel="noreferrer"><... | python|pandas|numpy|dataframe | 15 |
354,975 | 44,862,769 | Get a list of features which contain empty values (python/pandas) | <p>I am trying to clean a dataset and basically get rid of all the features which have a certain amount of empty values, in more than 100 empty values inclusive, with pandas/python. I am using the following command </p>
<pre><code>train.isnull().sum()>=100
</code></pre>
<p>which gets me:</p>
<pre><code>Id False
... | <p>in your case, just run:</p>
<pre><code>train[train.columns[train.isnull().sum()<100]]
</code></pre>
<hr>
<p>Full example:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[1,None,2],[3,4,None],[7,8,9]], columns = ['A','B','C'])
</code></pre>
<p>You'll get:</p>
<blockquote>
<pre><code> A B C
0 1... | python|pandas | 1 |
354,976 | 45,182,392 | tensorflow function tf.gfile.Glob cannot read files that are in a folder consisting of more than 4 files | <p>I am using tensorflow <code>tfRecord</code> to input my data. I find that if the number of <code>tfRecord</code> shards are more than 4, the function </p>
<pre><code>tf.gfile.Glob(tf_record_pattern)
</code></pre>
<p>always fails when it tries to get the list of files that match the given pattern. There is an erro... | <p>Faced the same problem. The solution in this discussion works.</p>
<p><a href="https://github.com/tensorflow/tensorflow/issues/8717" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/8717</a></p>
<pre><code>sudo apt-get install google-perftools
export LD_PRELOAD="/usr/lib/libtcmalloc.so.4" ... | python|tensorflow | 0 |
354,977 | 44,849,106 | Pandas data frame: plotting average for comma separated strings | <p>In my dataset I have a column with Topics which are strings separated by coma. </p>
<pre><code>df = pd.DataFrame({'Stats': [3377, 1843, 15234], 'Topics': ["A, B, C, D", "A, B", "C, D"]})
</code></pre>
<p><a href="https://i.stack.imgur.com/5TxFM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Tx... | <p>I'm not sure what your desired output is, but this should hopefully get you going in the right direction. Key point is to split out the topics, and then you can do whatever analytics you want.</p>
<pre><code>df2 = pd.DataFrame([(row.Stats, topic.strip())
for _, row in df.iterrows()
... | python-2.7|pandas | 2 |
354,978 | 45,269,790 | Tensorflow Multoprocessing; UnknownError: Could not start gRPC server | <p>I am working on computing hessian Matrix on Large data sets. I am trying to perform these computations in parallel on Multiple CPUs. My Set Up currently has 1 node with 10 CPU's. I am working on Python 2.7 </p>
<p>I wrote a small abstraction of my code to understand distributed tensorflow better. below is the error... | <p>In my case , I find ps raise this error and woker wait for response when I submit a tensorflowonspark job yarn cluster mode.</p>
<p><code>ps</code> error as follow </p>
<blockquote>
<p>2018-01-17 11:08:46,366 INFO (MainThread-7305) Starting TensorFlow ps:0 on cluster node 0 on background process
2018-01-17 11:... | python|multithreading|tensorflow|multiprocessing|grpc | 1 |
354,979 | 45,090,730 | SAS Proc Corr with Weighting in Python | <p>I have a SAS script that uses the "<a href="http://support.sas.com/documentation/cdl/en/procstat/66703/HTML/default/viewer.htm#procstat_corr_syntax01.htm#procstat.corr.covopt" rel="nofollow noreferrer">proc corr</a>" procedure, along with <a href="http://www.sascommunity.org/wiki/Tips:Weighting_in_PROC_CORR" rel="no... | <p>numpy's covariance takes two different kind of weights parameters - I don't have SAS to check against, but it is likely a similar approach.</p>
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html#numpy.cov" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/nu... | python|pandas|numpy|correlation | 1 |
354,980 | 44,957,372 | How do I build this block matrix in python? | <p>I want to build a block matrix for a system of equation with n points.
The result is an (2n+2)x(2n+2) matrix. In example, for 2 points the matrix is: </p>
<pre><code>1 0 0 0 0 0
a b c d 0 0
e f g h 0 0
0 0 a b c d
0 0 e f g h
0 0 0 0 0 1
</code></pre>
<p>For 3 points the matrix is</p>
<pre><code>1 0 0 0 0 0 0 0
... | <p>We can use <code>np.identity</code> to give us a "square" array (same dimensions in both axis) with the ones and zeros as you specified:</p>
<pre><code>myarr = np.identity(2*n+2)
</code></pre>
<p>Then, we define our little subset values for a-h:</p>
<pre><code>subset = np.array([[a,b,c,d],[e,f,g,h]])
</code></pre... | python|numpy|matrix|scipy | 1 |
354,981 | 45,060,387 | Polynomial fit doesn't plot high degrees | <p>I'm working now with regression and tried to fit polynomial model to my data with 3 different degrees and it plots only the lowest degrees. I have no idea where I'm going wrong. Here is my code and data points:</p>
<pre><code># -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotl... | <p>As @DavidG pointed out in a comment, the three curves are very close, so they look the same unless you zoom in.</p>
<p>That is just a symptom of the problem. You probably noticed the warnings that were printed when you ran the code. These indicate a numerical problem occurring in <code>polyfit</code>. Your <code... | python|numpy|matplotlib | 3 |
354,982 | 45,153,474 | Create a DataFrame from a heavily nested JSON in Pandas? | <p>I have a deeply nested JSON file taken from IBM's personality analysis tool. What is the shortest way I can create a DataFrame out of it. <strong>It doesn't matter if the parent "key" is repeated in multiple rows</strong>. I can use multi indexing to make it look good. My primary concern is to make spread out the JS... | <p>The json_normalize function is most likely what can help you out most here.</p>
<pre><code> from pandas.io.json import json_normalize
df = json_normalize(my_json_blob)
</code></pre> | python|json|pandas | 0 |
354,983 | 45,041,850 | TensorFlow 1.2.1 and InceptionV3 to classify an image | <p>I'm trying to create an example using the Keras built in the latest version of TensorFlow from Google. This example should be able to classify a classic image of an elephant. The code looks like this:</p>
<pre><code># Import a few libraries for use later
from PIL import Image as IMG
from tensorflow.contrib.keras.p... | <p>The reason why this error occured is that model always expects the <strong>batch</strong> of examples - not a <strong>single</strong> example. This diverge from a common understanding of models as mathematical functions of their inputs. The reasons why model expects batches are:</p>
<ol>
<li>Models are computationa... | machine-learning|tensorflow|neural-network|keras|coreml | 3 |
354,984 | 44,829,782 | Element-wise sum of arrays in loop python | <p>I am trying to make a loop that reads some arrays and then it calculates the element-wise sum of the arrays. A function that does this for 2 arrays is the numpy.add. In my case, I want to build a loop to do this for more than 3 arrays.</p>
<p>e.g.
file_1, file_2 and file_3 are arrays : [[1,2],[3,4]] , [[5,6],[7,8]... | <p>SOLVED</p>
<pre><code>import pandas as pd
from numpy import *
def my_mean():
N=array([[0,0],[0,0]])
numb = 4
subjs=range(1,numb)
for s in subjs:
X= pd.read_csv('file_{}.csv'.format(s),header=None)
N += X
N = N / float(3)
return N
X = my_mean()
print(X)
</code></pre> | python|csv|pandas | 1 |
354,985 | 45,222,592 | FillNa is not working? | <p>I have the following column of a dataframe:</p>
<pre><code> LC_REF
2C16
2C17
2C18
nan
nan
nan
</code></pre>
<p>However when I try to fill the nan with the values of another column:</p>
<pre><code> df['LC_REF'].fillna(df2['cycle'])
</code></pre>
<p>the nan values are not fille... | <p>Don't forget the <code>inplace</code> parameter</p>
<pre><code>df['LC_REF'].fillna(df2['cycle'], inplace=True)
</code></pre> | python|python-3.x|pandas | 4 |
354,986 | 45,002,775 | Imported data from CSV doesnt seem to be able to plot in PYTHON | <p>I can't seem to plot a graph using the below code. I wish to plot a graph with the total returns against the Date. What is wrong with my code?</p>
<p>I get KeyError: ' Date'</p>
<p>Spreadsheet is presented below</p>
<pre><code>import pandas as pd
import numpy as np
from pandas_datareader import data
import matplo... | <p>The problem you have here starts at the point where you create your csv file. One line of the file looks like this</p>
<pre><code>2-Jan-01," 1,283.27 "," 1,283.27 "," 1,331.00 "," 1,299.80 "," 1,336.75 "," 1,289.25 ",6.50%
</code></pre>
<p>As you can see, you are using commas (<code>,</code>) as field separators a... | python|csv|pandas|numpy|matplotlib | 1 |
354,987 | 57,081,408 | Need to make a flag if chatbot question is answered? | <p>I am trying to make a flag for the questions that were answered. Below is a sample data frame.</p>
<pre><code>userid message type
1 hi incoming
1 how may I help you outgoing
1 looking for a job incoming
1 whats your name ... | <pre><code>df['Flag'] = ((df['userid'] == df['userid'].shift(-1)) & (df['type'].eq('outgoing') & df['type'].shift(-1).eq('incoming')))
</code></pre> | python|numpy | 1 |
354,988 | 56,919,400 | How to protect (obfuscate/DRM) trained model weights in Tensorflow.js? | <p>I am working on a React-based web app that uses Tensorflow.js to run an AI model in realtime on the client in the browser. I've trained this AI model from scratch and I'd like to protect it from being intercepted and used in other projects. Are there any protections available to do this (obfuscation, DRM, etc.)? </p... | <p><strong>Client-side code obfuscation will never fully prevent it. Use a server instead.</strong></p>
<h3>Obfuscation</h3>
<p>If your client-side application contains the model, then the user will be able to somehow extract it. You can make it harder for the user, but it will always be possible. Some techniques to ... | javascript|reactjs|tensorflow|tensorflow.js | 5 |
354,989 | 57,185,548 | numpy 4D array advanced indexing with example | <p>I am reading some deep learning code. I have problem on advanced indexing in numpy array. The code I was testing:</p>
<pre><code>import numpy
x = numpy.arange(2 * 8 * 3 * 64).reshape((2, 8, 3, 64))
x.shape
p1 = numpy.arange(2)[:, None]
sd = numpy.ones(2 * 64, dtype=int).reshape((2, 64))
p4 = numpy.arange(128 // 2... | <p>I had the same issue when I first encountered fancy indexing in numpy. The short answer is that there is no trick to it: fancy indexing just selects elements into an output of the same shape as the index. With purely fancy indexing, your output array will be the same shape as your broadcasted <em>index</em> arrays (... | python|arrays|numpy|numpy-ndarray | 4 |
354,990 | 57,012,749 | How to find min value between several max values in a single column? | <p>Edit: please look at the end of this question. Made an edit.</p>
<p>I need to find minimum values between every two maximum values in a single column.
Minimum of the maximum values should be more than 10. </p>
<p>Here is the sample:</p>
<pre><code>Price Vol.
95 7
90 13
85 19
80 16
75 12
70 5
65 ... | <p>For your data, you can mask <code>max</code> and <code>min</code> by comparing to the neighbors:</p>
<pre><code>diff = df['Vol.'].diff()
is_max = diff.gt(0) & diff.shift(-1).lt(0)
is_min = diff.shift().lt(0) & diff.gt(0)
df['Result'] = np.select([is_max, is_min], ['max', 'min'])
df[df['Result'].ne('0')]
<... | python|pandas | 1 |
354,991 | 56,928,928 | TensorFlow Keras Custom Callbacks on_test_begin doesn't override itself | <p>I'm trying to create a custom callback that activates at the beginning and end of the training and validation parts when I call model.fit(...)</p>
<p>The training part (on_train_begin/on_train_end) works perfectly fine, but the testing part(on_test_begin/on_test_end) isn't called. In PyCharm, it doesn't even show t... | <p>The methods <code>on_test_*</code> and <code>on_predict_*</code> have been added to tensorflow 1.14+. Make sure you have tensorflow 1.14 or tensorflow 2 to be able to use those.</p> | python|tensorflow|keras | 1 |
354,992 | 56,969,420 | How to set the values of a column as columns in dataframe? | <p>I'm looking for a better code to transform my <code>DataFrame</code>.
My <code>DataFrame</code> looks like this:</p>
<pre><code> Period LASTDATE PRICE VAT SUM CLIENT
0 2018Q1 31/3/2018 1 2 3 NAME
1 2018Q2 30/6/2018 2 2 4 NAME
2 2018Q3 30/9/2018 3 3 6 NAME
3 20... | <p>Create <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> for index by <code>Period</code>, convert to one column <code>DataFrame</code> by <a href="http://pandas.pydata.org/pandas-d... | python-3.x|pandas | 4 |
354,993 | 57,144,928 | Unable to clear multi-line figure with callback | <p>I have a figure with a line plot and another one with a multi-line plot. The plot updates when a user selects a new option from a Select object.
The line plot updates correctly as is syncd with a ColumnDataSource. However, the multi-line plot pulls the info from a pandas dataframe.
The problem is that the lines accu... | <p>Calling glyph methods is <em>additive</em>. Calling <code>multi_line</code> over and over adds new multi-lines every time, without removing anything previously added. For this kind of use case, what you should do instead is call <code>multi_line</code> (or whatever glyph you might be using) only <em>once</em>, and t... | python|bokeh|pandas-bokeh | 1 |
354,994 | 56,886,364 | How to formatting a column data in a table using python? | <p>Let's assume I have a CSV file named "Student.csv". The CSV file contains a header "EmergencyNum". I have loaded the CSV data into the student table using Python.I want to format the "EmergencyNum" column as follows,
If the Emergency number is 8 digit, I should load like xx-xxx-xxx (e.g. 67-890-876)
If the Emergency... | <p><a href="https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals" rel="nofollow noreferrer">f-strings</a> in Python are relatively new. It allows you to place variables in <code>{}</code> to directly inject them into strings.</p>
<p>e.g</p>
<pre class="lang-py prettyprint-override"><code>cust... | python|pandas|csv | 3 |
354,995 | 57,060,273 | ssd_mobilenet_v1_coco How is SSD implemented with mobilenet | <p>I'd like to understand how SSD has been trained with mobilenet. Has mobilenet been taken as a pretrained model through transfer learning, and then SSD has taken its weights to start another training? </p>
<p>Please guidance on this model. </p>
<p>Thanks.</p> | <p>MobileNet is the backbone of SSD in this case, or in other words, served as the feature extractor network. The original SSD was using VGG for this task, but later other variants of SSD started to use MobileNet, Inception, and Resnet to replace it.</p> | tensorflow|object-detection|object-detection-api | 0 |
354,996 | 56,877,943 | Numpy concatenating along a new dimension | <p>I'm trying to do what this person is doing <a href="https://stackoverflow.com/questions/2357686/numpy-extending-arrays-along-a-new-axis">numpy: extending arrays along a new axis?</a> but I don't want to repeat the same array in the new dimension. I'm generating a new 2D array and want to append it along a 3rd dimens... | <p>You can also do this by storing the arrays in a list and using <code>np.stack</code>. Perhaps not as efficient, but I find it easier to read.</p>
<pre><code>import numpy as np
a = np.random.rand(256, 256) # array with shape (256, 256)
c = [a] # put initial array into a list
for i in np.arange(10):
b = np.rand... | numpy-ndarray | 2 |
354,997 | 57,130,470 | example_pb2 from tensorflow.core.example works in python 2, but not python 3 | <p>The following code will work with no issues in Python 2</p>
<pre><code>from tensorflow.core.example import example_pb2
tf_example = example_pb2.Example()
tf_example.features.feature['article'].bytes_list.value.extend(['test test testing'])
</code></pre>
<p>But in Python 3, it gives this error</p>
<pre><code>-----... | <p>It is as the error says:<br>
<code>but expected one of: bytes</code> : You need to provide byte values instead of string values. </p>
<p>You just need to use <code>b'test test testing'</code>.</p>
<pre><code>(pygpu) C:\Users\Ashutosh>python
Python 3.6.8 |Anaconda, Inc.| (default, Feb 21 2019, 18:30:04) [MSC v... | python|tensorflow | 1 |
354,998 | 56,896,663 | How to separate one column into multiple columns in python? | <p>I have one 'csv' file it looks like this:</p>
<p>sample data :</p>
<pre><code> Name : Jai
Age : 25
Address: N P IV
Country:
Name : Jack
Age : 18
Address: T U W IX
Country: USA
</code></pre>
<p>I want to split this single column into multiple, just like this,
Expected result:</p>... | <p>First create 2 columns <code>DataFrame</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> with separator <code>:\s+</code> for <code>:</code> with one or more spaces, then convert second column to numpy array and resh... | python|python-3.x|pandas | 2 |
354,999 | 57,292,444 | Equivalent of arcpy.Statistics_analysis using NumPy (or other) | <p>I am having a problem (I think memory related) when trying to do an <code>arcpy.Statistics_analysis</code> on an approximately 40 million row table. I am trying to count the number of non-null values in various columns of the table per category (e.g. there are x non-null values in column 1 for category A). After thi... | <p>You can convert a table to a numpy array using the function <a href="http://desktop.arcgis.com/fr/arcmap/10.4/analyze/arcpy-data-access/tabletonumpyarray.htm" rel="nofollow noreferrer">arcpy.da.TableToNumPyArray</a>. And then convert the array to a <code>pandas.DataFrame</code> object.</p>
<p>Here is an example of ... | python|numpy|arcpy | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.