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 |
|---|---|---|---|---|---|---|
15,500 | 30,687,786 | Solving nonlinear differential first order equations using Python | <p>I would like to solve a nonlinear first order differential equation using Python. </p>
<p>For instance, </p>
<p>df/dt = f**4</p>
<p>I wrote the following program, but I have an issue with matplotlib, so I don't know if the method I used with scipy is correct.</p>
<pre><code>from scipy.integrate import odeint
imp... | <p>In this case, you might be better of using <a href="http://docs.sympy.org/dev/modules/solvers/ode.html" rel="noreferrer">Sympy</a>, which allows you to obtain the closed form solutions:</p>
<pre><code>from IPython.display import display
import sympy as sy
from sympy.solvers.ode import dsolve
import matplotlib.pyplo... | python|math|numpy|matplotlib|scipy | 5 |
15,501 | 39,010,111 | pandas calculate the strangeness of the topic | <p>Here is a very short description of my task. I have a dataframe that looks like this: <code>df = pd.DataFrame([[2, 0], [2, 1], [1, 0], [1, 0], [1, 1], [3, 0]], columns=['topic', 'strange'])</code></p>
<p>For every topic, I need to caclulate the percentage of rows that are 'strange'. So the result will be like this... | <p>If <code>strange</code> is guaranteed to be 0 or 1 only, you can just take the mean:</p>
<pre><code>In [7]: df.groupby("topic").mean()
Out[7]:
strange
topic
1 0.333333
2 0.500000
3 0.000000
</code></pre> | python|pandas | 2 |
15,502 | 39,326,503 | Sort Multi-index pandas dataframe based on specific indexes | <p>I have the following dataframe:</p>
<pre><code> x y
a b c a b c
kk ii jj kk jj ii kk jj ii ii jj kk jj kk ii kk ii jj
1 .1 .01 2 .5 .2 .4 .6 .01 .3 .5 .7 1. 1. 2 .3 .2 .01 .4
2 ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a>:</p>
<pre><code>df = df.reindex(columns=['ii','kk','jj'], level=2)
print (df)
x y \
a ... | python|sorting|pandas|dataframe|multi-index | 2 |
15,503 | 39,400,684 | Pandas: keeping only first row of data in each 60 second bin | <p>What's the best way to keep only the first row of each 60 second bin of data in pandas? i.e. For every row that occurs at increasing time <code>t</code>, I want to delete all rows that occur up to <code>t+60</code> seconds.</p>
<p>I know there's some combination of <code>groupby().first()</code> that I can probably... | <p><strong>UPDATE:</strong> thanks to <a href="https://stackoverflow.com/questions/39400684/pandas-keeping-only-first-row-of-data-in-each-60-second-bin/39400864?noredirect=1#comment66127957_39400864">@piRSquared</a> - he noticed that my previous solution was incorrect. Here is another attempt:</p>
<p>data:</p>
<pre><... | python|pandas|dataframe | 3 |
15,504 | 39,324,520 | Understanding Tensorflow LSTM Input shape | <p>I have a dataset X which consists <strong>N = 4000 samples</strong>, each sample consists of <strong>d = 2 features</strong> (continuous values) spanning back <strong>t = 10 time steps</strong>. I also have the corresponding 'labels' of each sample which are also continuous values, at time step 11. </p>
<p>At the ... | <p>The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#dynamic_rnn" rel="noreferrer">documentation of <code>tf.nn.dynamic_rnn</code></a> states:</p>
<blockquote>
<p><code>inputs</code>: The RNN inputs. If <code>time_major == False</code> (default), this must be a Tensor of shape: <code>[ba... | python|tensorflow|regression|lstm | 19 |
15,505 | 39,235,303 | Why 'tf.python_io.TFRecordWriter' is so SLOW and STORAGE-CONSUMING in TensorFlow? | <p>I'm going to write to TFRecord file using <a href="https://github.com/dennybritz/chatbot-retrieval/blob/master/scripts/prepare_data.py#L132-L137" rel="noreferrer">this code</a>: </p>
<pre><code> writer = tf.python_io.TFRecordWriter(output_filename)
print("Creating TFRecords file at {}...".format(output_filename... | <p>I had a similar problem when the dataset I wanted to use was expensive to create and preprocess. </p>
<p>Using TFRecordWriter was incredibly slow, so instead I used the caching option available on Dataset objects.</p>
<pre><code>ds.cache('./cache/train.cache').repeat().batch(32).prefetch(1)
</code></pre>
<p>The f... | tensorflow | 0 |
15,506 | 39,049,716 | How to randomly assign values row-wise in a numpy array | <p>My google-fu has failed me!
I have a 10x10 numpy array initialized to <code>0</code> as follows:</p>
<pre><code>arr2d = np.zeros((10,10))
</code></pre>
<p>For each row in <code>arr2d</code>, I want to assign 3 random columns to <code>1</code>. I am able to do it using a loop as follows:</p>
<pre><code>for row in ... | <p>Once you have the <code>arr2d</code> initialized with <code>arr2d = np.zeros((10,10))</code>, you can use a vectorized approach with a <code>two-liner</code> like so -</p>
<pre><code># Generate random unique 3 column indices for 10 rows
idx = np.random.rand(10,10).argsort(1)[:,:3]
# Assign them into initialized ar... | python|numpy|vectorization | 2 |
15,507 | 33,962,946 | How to input exponentiation in label using set_yticklabels in matplotlib | <p>Hi I want to set tick labels as multiplication of some numbers by 6th power of 10. The problem is that I don't know how to make matplotlib to show it nicely. I do following:</p>
<pre><code>ax.set_yticks([1000000, 1200000, 1400000, 1600000, 1800000, 2000000, 2200000, 2400000])
ax.set_yticklabels([ '1.0*10^6', '1.2*1... | <p>You can use unicode in string:</p>
<pre><code>ax.set_yticklabels([ '1.0∙10⁶', '1.2∙10⁶', '1.4∙10⁶', '1.6∙10⁶', '1.8∙10⁶', '2.0∙10⁶', '2.2∙10⁶', '2.4∙10⁶' ], rotation=0, ha='center', va='top')
</code></pre> | python|numpy|matplotlib|axis-labels | 2 |
15,508 | 33,762,175 | Numpy, replace a broadcast by iteration | <p>I have the following code snippet</p>
<pre><code>def norm(x1, x2):
return np.sqrt(((x1 - x2)**2).sum(axis=0))
def call_norm(x1, x2):
x1 = x1[..., :, np.newaxis]
x2 = x2[..., np.newaxis, :]
return norm(x1, x2)
</code></pre>
<p>As I understand it, each <code>x</code> represents an array of points in... | <p>There is no way to do this kind of computation without the memory penalty with numpy vectorization. For the specific case of efficiently computing pairwise distance matrices, packages tend to get around this by implementing things in C (e.g. <a href="http://docs.scipy.org/doc/scipy/reference/spatial.distance.html" r... | python|numpy|generator|broadcast | 1 |
15,509 | 13,772,227 | Ordering of python set from NumPy array | <p>I am having trouble figuring out why I make a set from a NumPy array, Python swaps the order of elements:</p>
<pre><code>import numpy as np
A = np.array([2])
B = np.array([2, 8])
setA = set(A)
setB = set(B)
In [6]: A
Out[6]: [2]
In [7]: B
Out[7]: [2, 8]
In [8]: setA
Out[8]: set([2])
In [9]: setB
Out[9]: set([8,... | <p><code>set</code>s by definition have no order - they are instead created so as to optimize certain operations such as those testing for containment. Therefore, you should never rely on order preservation when you create / add elements to a set.</p> | python|numpy|set | 3 |
15,510 | 62,420,881 | Getting values using python-pandas groupby-aggregate function | <p>So I have a dataframe that looks like this:</p>
<pre><code> Date Forward_Date A B C D Amount
2010-01-01 2010-02-01 a a a a 20
2010-01-01 2010-03-01 b b b b 10
2010-01-01 2010-04-01 c c c c 5
2010-01-02 2010-02-01 d ... | <p>Set the <code>Date</code> column as the index, perform a groupby on the <code>Amount</code> column, get a boolean for rows in the original dataframe that are equal to the groupby result and index with <code>loc</code> :</p>
<pre><code>df = df.set_index("Date")
df.loc[lambda x: x.Amount.eq(df.groupby("Date").Amount... | python|pandas|pandas-groupby | 0 |
15,511 | 62,309,066 | Bifurcate/Split Numbers to lower granularity pandas | Integers rounding off | <p>I have two dataframes </p>
<ol>
<li>DF1: Products and their respective sales projections like below</li>
<li>DF2: Product wise sub components with respective percentage contributions</li>
</ol>
<p>I want to divide product projections to its sub components into integers basis given ratios without disturbing overal... | <p>Use:</p>
<pre><code>df3 = pd.merge(df2, df1, on='Product Name', how='left')
df3['Projections'] = df3['Projections']*df3['Contribution']
del df3['Product Name']
del df3['Contribution']
</code></pre> | python|pandas | 0 |
15,512 | 62,298,790 | How to compare two dataframes and update with the new value | <p>Using Panda Dataframes, I would like to compare two DFs and update the excel sheet.
The problem, I'm seeing from my code, it only appends new row. It doesn't update pervious row.
For example:
DF1:</p>
<pre><code>{'Sheet1': [{'ID': 1.0, 'NAME': 'hostname1', 'IP_ADDRESS': '192.168.1.1', 'STATUS': 'completed'}, {'ID... | <p>If you don't need to use openpyxl for anything specific then you could just stick with pandas:</p>
<pre><code>import pandas as pd
df_o = pd.read_excel(file_name)
df_n = pd.read_csv(file_path + 'df_b.csv')
</code></pre>
<p>df_o</p>
<pre><code> ID HOSTNAME IP STATUS
0 1 hostname1 192.168.0.... | python|pandas|dataframe | 1 |
15,513 | 62,453,657 | Extracting month from timestamp by specifying the date format of the timestamp in Python | <p>I have a data set with a timestamp in format dd/mm/yyyy hh:mm:ss. I would like to extract the month and the year for the whole column. So I used the following code: </p>
Extracting the year
<pre><code>`df['Year'] = pd.DatetimeIndex(df['timestamp']).year`
</code></pre>
Extracting the month
<pre><code>`df['month_n... | <p>use <code>strftime('%b')</code> and <code>assign</code></p>
<p>ensure your datecolumn is a proper date <code>pd.to_datetime(df['date'])</code></p>
<pre><code>df.assign(year = df[0].dt.year,
month = df[0].dt.strftime('%b'))
print(df)
0 1 2 3 4 year month
0 2020-02-01... | python|pandas|date|datetime | 1 |
15,514 | 62,156,626 | Pandas - Calculate row values based on prior row value, update the result to be the new row value (and so on) | <h3>Below is some dummy data that reflects the data I am working with.</h3>
<pre><code>import pandas as pd
import numpy as np
from numpy import random
random.seed(30)
# Dummy data that represents a percent change
datelist = pd.date_range(start='1983-01-01', end='1994-01-01', freq='Y')
df1 = pd.DataFrame({"P Change_1... | <p>[EDITED] Perhaps there are better/more elegant ways to do this, but this worked fine for me:</p>
<pre><code>def fill_values(df1, df2, cols1=None, cols2=None):
if cols1 is None: cols1 = df1.columns
if cols2 is None: cols2 = df2.columns
for i in reversed(range(df2.shape[0]-1)):
for col1, col2 in ... | python|python-3.x|pandas|dataframe|iteration | 1 |
15,515 | 51,119,874 | ValueError: setting an array element with a sequence from BatchNormalization layer of Keras | <p>I was implementing something and I found that batch normalization layer was throwing weird Value Error.</p>
<p>The code I used to generate error is following :</p>
<pre><code>x = Input(shape=(25,14,19))
bn = BatchNormalization(
momentum=0.1,
epsilon=0.00001,
gamma_regularizer=keras.initia... | <p>I think you have mistakenly used the <strong>regularizer</strong> and <strong>constraint</strong> arguments instead of <strong>initializer</strong> arguments:</p>
<pre><code>bn = BatchNormalization(
momentum=0.1,
epsilon=0.00001,
gamma_initializer=keras.initializers.ones(),
beta_i... | python|tensorflow|keras|keras-layer|batch-normalization | 1 |
15,516 | 51,142,844 | Efficient way to solve matrix equation in Python | <p>Right now I am using the <code>numpy.linalg.solve</code> to solve my matrix, but the fact that I am using it to solve a 5000*17956 matrix makes it really time consuming. It runs really slow and It have taken me more than an hour to solve. The running time for this is probably O(n^3) for solving matrix equation but I... | <p><strong>Update (2 July 2018):</strong> The updated question asks about the impact of a regularization term and the type of data in the matrices. In general, this can make a large impact in terms of the datatypes a particular CPU is most optimized for (as a rough rule of thumb, AMD is better with vectorized integer m... | python|performance|numpy|matrix | 2 |
15,517 | 51,273,000 | solution for the flipping coin issue | <p>I am trying to solve this prolem :
a random experiment of tossing a coin 10000 times and determine the count of Heads::
defining a binomial distribution with <code>n = 1</code> and <code>p = 0.5</code>. using binom function from scipy.stats setting random seed to 1
Draw a sample of 10000 elements from defined dis... | <p>If you want 10000 trials, then change <code>n, p = 1, .5</code> to <code>n, p = 10000, .5</code></p> | python|numpy|scipy|coin-flipping | 1 |
15,518 | 51,229,932 | Tensorflow timeline shows long pauses between train steps. What is a reason of this? | <p>There are strange pauses in execution process while running train process in tensorflow. What can be reason of this pauses? I've attached output of timeline for first 20 train iterations<a href="https://i.stack.imgur.com/dBS4t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dBS4t.png" alt="enter ... | <p>It is hard to tell without looking at the code but, usually when the GPU is idle, it is because data is being copied to or from the RAM onto VRAM. (device to host or vice versa). </p>
<p>Try <a href="https://www.tensorflow.org/programmers_guide/datasets" rel="nofollow noreferrer">TF Records</a> here is a nice <a hr... | python|tensorflow|neural-network | 1 |
15,519 | 48,529,169 | Which dim to use on tf.metrics.mean_cosine_distance? | <p>I'm confused about which <code>dim</code> refers to which actual dimension in Tensorflow in general, but concretely, when using <a href="https://www.tensorflow.org/api_docs/python/tf/metrics/mean_cosine_distance" rel="nofollow noreferrer">tf.metrics.mean_cosine_distance</a></p>
<p>Given</p>
<pre><code>x = [
[1,... | <p>It is along <code>dim 0</code> for your input <code>x</code>. It's intuitive to see this once you construct your input <code>x</code> as a numpy array.</p>
<pre><code>In [49]: x_arr = np.array(x, dtype=np.float32)
In [50]: x_arr
Out[50]:
array([[ 1., 2., 3., 4., 5.],
[ 0., 2., 3., 4., 5.]], dtype=f... | python|tensorflow|machine-learning|deep-learning|linear-algebra | 3 |
15,520 | 48,588,932 | Add comments before each line when exporting array with numpy.savetxt | <p>I would like to export an array adding comments at the start of each line and of each column.</p>
<p>For instance with the following array :</p>
<pre><code>[[10,5,2],
[7,2,6],
[8,3,1]]
</code></pre>
<p>I would like the output file to look like this (or similar):</p>
<pre><code> 1C 2C 3C
1L 10; 5; 2
2L ... | <p>I don't know of a way to do this directly in <code>numpy</code>, but you could always iterate through the array and write your comments and the line to a file.</p>
<pre><code>a = np.array([[10,5,2],[7,2,6],[8,3,1]])
print(" " + " ".join([str(x+1)+"C" for x in range(a.shape[1])]))
for i, row in enumerate(a):
... | python|arrays|numpy|export | 1 |
15,521 | 48,443,208 | Removing columns and rows from ndarray Python 2.7 | <p>I have implemented and algorithm to remove some columns and rows from an ndarray in Python 2.7, however I feel there should be a better way to do it. Probably I do not know how to do it well in Python, this is why I put the questions here. I have been searching but I have been not succesful finding similar questions... | <p>For <strong>Question 2)</strong></p>
<p>Instead of :</p>
<pre><code>a[rows_to_keep,:][:,columns_to_keep]
</code></pre>
<p>use: </p>
<pre><code>a[np.ix_(rows_to_keep,columns_to_keep)].
</code></pre>
<p>This is called Advanced Indexing (see [Numpy documentation<a href="https://docs.scipy.org/doc/numpy-1.13.0/refe... | python-2.7|multiple-columns|rows|slice|numpy-ndarray | 0 |
15,522 | 48,774,426 | Pandas Data frame combination of columns based on value | <p>I have a pandas dataframe with 13 columns - ID(unique identifier),A1,A2,..A12.
all A columns can have 2 values- 0 or 1</p>
<pre><code> d = {'ID': ['ID1', 'ID2','ID3', 'ID4'], 'A1': [0,0,0,1], 'A2': [1,0,0,1], 'A3': [0,0,0,0], 'A4': [1,1,0,1], 'A5': [0,0,0,1]
, 'A6': [0,1,0,0], 'A7': [1,1,0,1], 'A8': [1,0,0,0], ... | <p>Not to sure if I am following your example completely (i.e. "combination of the 12 other columns, if their value is 1", if what is 1, the first column?).</p>
<pre><code>df.loc[df['A1'] == 1, 'A_'] = [df['A1'].astype(str)+df['A2'].astype(str)+df['A3'].astype(str)]
</code></pre>
<p>This code reads like so: if column... | python|pandas | 1 |
15,523 | 48,586,174 | Error When Trying to Create Function Grapher | <p>I am trying to make a program using Python that allows the user to pick a function and graph it over specified values. I have this:</p>
<pre><code>import matplotlib.pyplot as plt
import math
import numpy as np
from sympy import Symbol, Derivative, sin, sympify
from sympy.core.sympify import SympifyError
x = Symbo... | <p>I cannot reproduce the error. I get the same error as Georgy: a shape mismatch when plotting. But why don't you try using lambdify to evaluate the function like this:</p>
<pre><code>import matplotlib.pyplot as plt
import math
import numpy as np
from sympy import Symbol, Derivative, sin, sympify, lambdify
from sympy... | python|numpy|matplotlib|sympy | 3 |
15,524 | 48,736,206 | Convert 2D numpy array to Tensorflow Dataset | <p>I have a numpy array of the shape (n, 12) representing the input datapoints of my data, of floating point formal, and a numpy array of shape (n,) containing the labels of the datapoints (integer). </p>
<p>However, I can't work out how to convert it into a tensorflow dataset - the guide method throws an error:</p>
... | <p>It appears that one of your input arrays contains elements of type <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow noreferrer"><code>decimal.Decimal</code></a>. TensorFlow does not support this type natively, so you will have to convert the array to either <code>np.float32</code> or <code>np.f... | python|numpy|tensorflow|tensorflow-datasets | 0 |
15,525 | 48,790,320 | libcublas.so.9.0: cannot open shared object file while installing tensorflow in ubuntu 16.04 | <p>I have installed <code>cuda-8.0</code> and installed TensorFlow using:</p>
<pre><code>sudo pip install tensorflow-gpu
</code></pre>
<p>When I try <code>import tensorflow as tf</code>, it says:</p>
<blockquote>
<p>ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory</p>
</bloc... | <p>You don't have to go back for your tensorflow version. I'm using <strong>tensorflow 1.13</strong> with <strong>cuda 10.1</strong>. The problem was related with old installations. I don't have <strong>libcublas.so.9.0</strong> in my directories. I'm using <strong>cuda 10.1</strong>, but it says the same error. if you... | tensorflow | 0 |
15,526 | 48,481,223 | ValueError: The truth value of a DataFrame is ambiguous | <p>I have a dataframe that looks like this:</p>
<pre><code> total downloaded avg_rating
id
1 2 2 5.0
2 12 12 4.5
3 1 1 5.0
4 1 1 4.0
5 0 0 0.0
</code></pre>
<p>I'm trying to add a new column... | <p>The reason for your error is you are attempting to do a row-wise (vectorised calculation), but in fact in your function <code>diff()</code> <code>ratings[ratings.downloaded > 0]</code> returns a subset of the dataframe and preceding it by <code>if</code> is ambiguous. The error message reflect this.</p>
<p>You m... | python|python-3.x|pandas|valueerror | 1 |
15,527 | 71,031,039 | finding id name of 5 most frequent value in a column in pandas | <p>We have a data which has column name "birth_country"
i executed following code;</p>
<pre><code>import pandas as pd
df=pd.read_csv("data.csv")
df['birth_country'].value_counts()[:5]
</code></pre>
<p>output:</p>
<pre><code>United States of America 259
United Kingdom 85
Germany ... | <p>For series by <code>index</code> values use:</p>
<pre><code>pd.Series(df['birth_country'].value_counts()[:5].index)
</code></pre> | python|pandas|dataframe | 1 |
15,528 | 70,964,382 | Grep columns by values in different dataframe in python | <p>I have this <code>df1</code>:</p>
<pre><code>CHR SNP Pos Ref Min
1 rs3094315 113934 A G
1 rs12124819 126070 A G
1 rs28765502 135853 C T
1 rs9419478 158202 C T
1 rs4881551 159076 G A
</code></pre>
<p>and this <code>df2</code>:</p>
<pre><code>CHR SNP A1 A2 MAF ... | <p>You can first right <code>merge</code> on "SNP", then use <code>np.where</code> to evaluate the condition. Then fill NaN values with the corresponding values. Finally drop the columns with missing values and rearrange to fit the desired outcome:</p>
<pre><code>merged_df = df1.merge(df2, on='SNP', how='righ... | python|pandas|dataframe | 2 |
15,529 | 51,760,639 | How to modify the column values in pd.dataframe | <p>Background:
Actually I wanna modify the value in dataframe, only top 20 sport should be kept, and the others should be displayed like "Others".
It's a copy of existed columns, as following:</p>
<pre><code>athlete_events['Sport_modified'] = athlete_events['Sport']
</code></pre>
<p>And the filter that contains top2... | <p>Your first method will never work, since your function does not return a series, nor does it <code>return</code> anything for a row-wise calculation.</p>
<p>Your second method is not <em>in-place</em>, you need to assign back to a series. For instance:</p>
<pre><code>df['sport_modified'] = df['sport'].apply(lambda... | python|pandas | 2 |
15,530 | 51,954,307 | What is difference between Noise Filters (Savitzki Golay) and Interpolation(interp1d) Python | <p>I am wondering what is difference between filtering and interpolating data.</p>
<p>I am now comparing </p>
<pre><code>savgol_filter(itp(xx), window_size, poly_order)
</code></pre>
<p>and </p>
<pre><code>itp = interp1d(x,y, kind='nearest')
</code></pre>
<p>I understand that filter filters noise in data, so that ... | <p>Suppose you have a series of discrete data points, measured for example at specific time. </p>
<ul>
<li><p>Interpolation is a way to guess the value of the series at a time in-between two measurements. For example, the temperature is measured every hours, but you want to have the temperature value every half-hour. ... | python|pandas|filter|scipy|interpolation | 0 |
15,531 | 41,874,636 | add two numpy arrays using lamdify - pass expression as function argument | <p>I have this piece of code:</p>
<pre><code>import numpy as np
import sympy
from sympy import symbols
from sympy.utilities.autowrap import ufuncify
from sympy.utilities.lambdify import lambdify
def test(expr,a,b):
a_var, b_var = symbols("a b")
#f = ufuncify((a_var, b_var), expr, backend='numpy')
f = la... | <p><code>lambdify</code> converts SymPy expressions into NumPy functions. You are trying to convert a NumPy array into a NumPy function. The arguments to <code>lambdify</code> need to be SymPy objects. </p>
<p>You want something like</p>
<pre><code>a_var, b_var = symbols("a b")
expr = a_var + b_var
f = lambdify((a_va... | python|numpy|sympy | 1 |
15,532 | 42,126,666 | how to split date and time from same column in csv using python? | <p>I have first column (PERIOD_START_TIME) in csv file with date and time, but I need to separate them into two different columns (Date, Time), so I need your help... </p>
<pre><code>PERIOD_START_TIME
01.31.2017 13:00:00
01.31.2017 14:00:00
01.31.2017 15:00:00
01.31.2017 16:00:00
01.31.2017 17:00:00
01.31... | <p>Your <code>PERIOD_START_TIME</code> might not be <code>datetime</code>. To make sure that it is.</p>
<pre><code>df['PERIOD_START_TIME'] = pd.to_datetime(df['PERIOD_START_TIME'])
</code></pre>
<p>Access the <code>date</code> and <code>time</code> attributes via the <code>dt</code> accessor.</p>
<pre><code>df['dat... | python|date|csv|pandas|datetime | 1 |
15,533 | 41,898,195 | Replace values in a column, with certain values from another, ignoring any 'nan' entries | <p>I have the following pandas dataframe:</p>
<pre><code>A B C D
2 a 1 F
4 b 2 G
6 b 3 nan
1 c 4 G
5 c 5 nan
7 d 6 H
</code></pre>
<p>I want to replace any values in column B, with the values in column D, while not doing anything for the 'nan' entries in column D.</p>
<p>Desired... | <p>You can mask the rows of interest using a boolean mask and pass this to <code>loc</code> so only those rows are overwritten:</p>
<pre><code>In [3]:
df.loc[df['D'].notnull(), 'B'] = df['D']
df
Out[3]:
A B C D
0 2 F 1 F
1 4 G 2 G
2 6 b 3 NaN
3 1 G 4 G
4 5 c 5 NaN
5 7 H 6 H
</c... | python|pandas|replace | 2 |
15,534 | 41,798,519 | State resetting in LSTMs during training and testing | <p>I am trying to understand and implement LSTMs. I understand that they one needs to define a sequence length T, and the training is performed in batches. So we fed to the network several sequences of length T. Now the LSTM needs a previous state as input, which as I understand, it is initialized to zero. My question ... | <p>In Tensorflow, I am 95% sure the starting state for every sequence is reset to zero for every element in your batch and between batches. (5% because the "Never say never" rule :)</p>
<p>EDIT:</p>
<p>I should probably elaborate more. How Tensorflow works, it first constructs a graph and then pushes your data throug... | tensorflow|deep-learning|lstm|recurrent-neural-network | 0 |
15,535 | 64,422,882 | How to use column positions from one dataframe to select indices for another dataframe | <p>I have a df1:</p>
<pre><code>Col1 Col2
10 100
5 90
7 87
1 83
3 70
</code></pre>
<p>I need to use Col1 indices from df1 for selecting columns from df2.</p>
<p>df2</p>
<pre><code>Col1 Col2 Col3 Col4 Col5 Col6 ...................Col 20
</code></pre>
<p>So basically I need columns 10,5... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>DataFrame.iloc</code></a> with subtract <code>Col1</code> by <code>1</code>, because python count from <code>0</code>, so for select first column need <code>0</code>:</p>
<pre><code>np.r... | python|pandas|dataframe | 1 |
15,536 | 64,593,205 | Change values in DF Column based first digit of value in another DF Column | <p>I have the following dataframe and for my purposes, when the first digit in the Subref is X, the Centre should be X and when the fist letter of the Subref is Y, the Centre value should be Y.</p>
<p>So how do I go from this df</p>
<pre><code> Subref Det Centre
0 C12345 JOHNEL 1
1 C3245 BVDI ... | <p>You can use <code>str[0]</code> to get the first character, then <code>where</code> or <code>loc</code> or <code>np.where</code> to replace</p>
<pre><code>first_chars = df['Subref'].str[0]
df['Centre'] = df['Centre'].where(first_chars=='C', first_chars)
# or
# df['Centre'] = np.where(first_char=='C', df['Center']... | python|pandas | 1 |
15,537 | 64,493,093 | Unstack Groupby does not group the data in proper dataset using Pandas | <p>Hello Data Scientist and Pandas Experts,</p>
<p>I need some help as I can’t get my data organized properly.</p>
<p>When using unstack in groupby it does not group the data in properly.
Here is my dataframe:</p>
<pre><code>data = [
{'Store': 'Store1', 'Date': pd.Timestamp('2020-08-01 00:00:00'), 'Employee': 'aemp', '... | <p>Almost there, you just need to:</p>
<ol>
<li>Change the order of your <code>.groupby</code> columns as it will unstack in order and <code>date</code> needs to be at the end rather than the beginning OR</li>
<li>You can sort by the index, but rearranging correctly in step 1 prevents you from having to do this extra s... | python|pandas|pandas-groupby | 1 |
15,538 | 64,359,945 | How can I explore and modify the created dataset from tf.keras.preprocessing.image_dataset_from_directory()? | <p>Here's how I used the function:</p>
<pre><code>dataset = tf.keras.preprocessing.image_dataset_from_directory(
main_directory,
labels='inferred',
image_size=(299, 299),
validation_split=0.1,
subset='training',
seed=123
)
</code></pre>
<p>I'd like to explore the created dataset much like in thi... | <p>I think it would be much easier to use <code>glob2</code> to get all your filenames, process them as you want to, then make a simple loading function that will replace <code>image_dataset_from_directory</code>.</p>
<p>Get all your files:</p>
<pre><code>files = glob2.glob('class_*\\*.jpg')
</code></pre>
<p>Then manip... | python|tensorflow|machine-learning|keras|deep-learning | 2 |
15,539 | 64,248,226 | How to convert panda series index date into DatetimeIndex? | <p>The following data below is from a pandas series, but I need the date converted to DatetimeIndex like this format: 2020-08-17. The index of this series should be a pd.DatetimeIndex. What are some ways to convert it as such?</p>
<pre><code>8/17/20 14082780.0
8/18/20 14277100.0
8/19/20 14483216.0
8/20/20 1... | <p>Just change the index to be as type of datetime:</p>
<pre><code>df.index = pd.to_datetime(df.index)
</code></pre>
<p>More generally for a non-index column:</p>
<pre><code>df['Date']= pd.to_datetime(df['Date'])
</code></pre> | python|pandas | 1 |
15,540 | 64,367,154 | Pandas Row mean with NaN | <p>I have a sample pandas DF:</p>
<pre><code>df = pd.DataFrame(np.random.randint(0,10,size =(6,2)),columns=["A","B"])
df.loc[2,"B"]=np.NaN
df
</code></pre>
<p>Sample DF:</p>
<pre><code> A B
0 5 0.0
1 4 8.0
2 6 NaN
3 8 9.0
4 4 7.0
5 5 4.0
</code></pre>
<p>I am ... | <p>Simplier is replace missing values to <code>0</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_frame.html" rel="nofollow noreferrer"><code>Series.to_frame</code></a> for one column <code>DataFrame</code> and transpose:</p>
<pre><code>df = df.fillna(0).mean().to_frame()... | python|pandas|numpy | 3 |
15,541 | 47,552,255 | TypeError: '<' not supported between instances of 'str' and 'float' is returned when trying to determine the mode of a column in a data | <p>While trying to determine the mode of a particular column of a data the following error was returned:
TypeError: '<' not supported between instances of 'str' and 'float'</p>
<pre><code>data = pd.read_csv('train.csv.txt', index_col='Loan_ID')
from scipy.stats import mode
mode((data['Gender'])) # determine mode of... | <p>Replace all missings by <code>np.Nan</code> and u have param <code>nan_policy</code> in function mode</p>
<p><strong>nan_policy</strong> : <code>{‘propagate’, ‘raise’, ‘omit’}</code>, optional
Defines how to handle when input contains nan. ‘propagate’ returns nan, ‘raise’ throws an error, ‘omit’ performs the calcul... | python|pandas|scipy | 0 |
15,542 | 47,561,012 | Using my own data in tensorflow for neuralnetwork implementation | <p>I'm very new to TensorFlow and Python. I have a dataset, very similar to the MNIST dataset (28 * 28 image). I have been following a lot of the online tutorials on how to implement a basic neural network with tensorflow and found that most of them just use:</p>
<pre><code>from tensorflow.examples.tutorials.mnist imp... | <p>The MNIST dataset used in tensorflow tutorial includes 4 files:</p>
<ul>
<li><code>train-images-idx3-ubyte</code></li>
<li><code>train-labels-idx1-ubyte</code></li>
<li><code>t10k-images-idx3-ubyte</code></li>
<li><code>t10k-labels-idx1-ubyte</code></li>
</ul>
<p>The first two are training data and training labels... | python|machine-learning|tensorflow|neural-network|mnist | 0 |
15,543 | 47,696,706 | Indexing Dataframe similar to numpy ndarray with 2d index | <p><strong>Motivation:</strong></p>
<p>I have 3-dimensional velocity data stored in an Nx3 DataFrame. I need to detect events in the data and extract fixed length epochs for further analysis. I would like to store the detected epochs as an additional index/column in the DataFrame and use it to get a compact 2d represe... | <p>Consider the following Pandas approach:</p>
<pre><code>In [270]: x = df.loc[df.index.notnull()]
In [271]: x
Out[271]:
X Y Z
0.0 6 7 8
0.0 9 10 11
1.0 15 16 17
1.0 18 19 20
2.0 24 25 26
2.0 27 28 29
In [278]: (x.set_index(np.arange(len(x)) // 2)
.set_index(np.arange(len(... | python|pandas|indexing | 2 |
15,544 | 47,736,951 | tensorflow : load csv data file and training the model | <p>I am new to tensorflow . I need to load the dataset to train my model . And sample of my dataset looks like</p>
<pre><code>TRAINING_FILE.iloc[0:5,0:5]
num_var_1 num_var_2 num_var_3 num_var_4 num_var_5
0 -0.010655 0.040182 0.0 1.800000e-07 -0.011319
1 -0.006542 0.157872 0.0 2.10... | <p>Those all look like floats, but <code>load_csv_with_header</code> is looking for a label column with dtype <code>target_dtype</code> (integer in your case). You can select this column with the <code>target_column</code> argument, but it's the last one by default.</p>
<p>So you either need to switch the label dtype ... | python|tensorflow | 1 |
15,545 | 49,067,543 | Check null values in data fetched from SQL database | <p>I want to store the data in numpy arrays fetched from the database. I want to make sure that no null value (None) go to the numpy array(throws an error anyway doing that). I have tried to do it the following way but it does not work. For some reason, NullValueCheck() always returns true How can I know about null val... | <p>I've found this is easiest to address in your source SQL. <code>COALESCE</code> is helpful here:</p>
<pre><code>df = pd.io.sql.read_sql("""SELECT ID, COALESCE(BuildingID, 0) AS BuildingID, Title FROM Something""", cnxn)
</code></pre>
<p>This will return <code>0</code> if the value of <code>BuildingID</code> is NUL... | python-3.x|numpy|pyodbc | 1 |
15,546 | 49,279,392 | Pairwise substraction of multiindexed columns in pandas | <p>I have a pd dataframe of this type (multiindex in the columns):</p>
<pre><code> measurement meas1 meas2 ...
observer obs1 obs2 obs1 obs2 ...
1 1 1 1 1
2 2 1 6 3
3 2 3 3 2
</code></pr... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="nofollow noreferrer"><code>xs</code></a> for select column in <code>MultiIndex</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sub.html" rel="nofollow noreferrer"><code... | python|pandas | 1 |
15,547 | 49,193,238 | Normalize 2d arrays | <p>Consider a square matrix containing positive numbers, given as a 2d numpy array A of shape ((m,m)). I would like to build a new array B that has the same shape with entries</p>
<pre><code>B[i,j] = A[i,j] / (np.sqrt(A[i,i]) * np.sqrt(A[j,j]))
</code></pre>
<p>An obvious solution is to loop over all (i,j) but I'm w... | <p>Two approaches leveraging <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> could be suggested.</p>
<p>Approach #1 :</p>
<pre><code>d = np.sqrt(np.diag(A))
B = A/d[:,None]
B /= d
</code></pre>
<p>Approach #2 :</p>
<pre><code>B ... | python|arrays|numpy|matrix | 4 |
15,548 | 49,247,016 | draw multiple transparent masks on an image | <p>I have an image and some binary masks I want to apply to the image to highlight certain areas. I'm able to draw one mask, but each subsequent applied mask lightens the previous mask and the original image more and more. </p>
<p>How can I apply multiple masks while keeping each mask and the image brightness constant... | <p>You can use <a href="http://pillow.readthedocs.io/en/latest/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.ImageDraw.bitmap" rel="noreferrer">ImageDraw.bitmap(xy, bitmap, fill=None)</a> to draw masks from bitmaps. You can have multiple shades per mask, but only one color.</p>
<pre><code>url = 'https://upload.... | python|numpy|python-imaging-library|pillow | 5 |
15,549 | 58,722,479 | Sum only if Previous > Current | <p>The problem I have having is that I would like to keeping summing up the values only if previous value is greater than my current value. </p> | <p>This can be done by use <code>groupby</code> , with <code>diff</code> and <code>cumsum</code> create the addtional key , then we just need <code>cumsum</code> the value by reverse order </p>
<pre><code>df['finalvalue']=df.iloc[::-1,:].groupby([df.id,df.value.diff().lt(0).cumsum()]).value.cumsum()
df
Out[208]:
... | python|python-3.x|pandas|dataframe | 0 |
15,550 | 59,039,019 | Using R packages in Python using rpy2 | <p>There is a package in R that I need to use on my data. All my data preprocessing has already been done in python and all the modelling as well. The package in R is 'PMA'. I have used r2py before using Rs PLS package as follows</p>
<pre><code>import numpy as np
from rpy2.robjects.numpy2ri import numpy2ri
import rpy2... | <p>The error for some reason is a mac-os issue. <a href="https://stackoverflow.com/a/53014308/1628393">https://stackoverflow.com/a/53014308/1628393</a></p>
<p>Thus all you have to do
is modify it with this command and it works well </p>
<pre><code>os.environ['KMP_DUPLICATE_LIB_OK']='True'
string<-'''SCCA<-func... | python|r|numpy|rpy2 | 1 |
15,551 | 59,020,355 | Can I build a loop function that automatically creates multiple data-frames at one go? | <p>I have been struggling to try to nail down this coding dilemma. I have built a program that models and forecasts individual stock symbols. It works great, but I'm ready to take it to the next level where a user like myself can forecast multiple stock symbols at one go, instead of running the application multiples ti... | <p>This answer might help: <a href="https://stackoverflow.com/questions/40973687/create-new-dataframe-in-pandas-with-dynamic-names-also-add-new-column">Create new dataframe in pandas with dynamic names also add new column</a></p>
<p>The approach suggested in the post would be to create a dictionary that would store th... | python|pandas | 2 |
15,552 | 58,653,426 | Why my web scraping code is not extracting data like it should? | <p>I am trying to get data from a online shopping website. My code runs without any error but the data is not getting extracted to the csv file like it should. Where am I going wrong with the code?</p>
<pre><code>from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
driver = webdriver.Chrom... | <p>flipkart : It is loaded dynamically from a script tag when the browser executes javascript in the webpage. You can regex out this info and parse with json parser to retrieve required info just using <code>requests</code>; without the overhead of selenium.</p>
<pre><code>import requests, re, json
p = re.compile(r'w... | python|pandas|selenium|web-scraping | 0 |
15,553 | 58,742,524 | Using three different labels in machine learning | <p>I'm really freshman on machine learning. I'm reviewing code that separates spam or ham values on an email. I have a problem when I set up codes for another data set. So, my dataset doesn't just have ham or spam values. I have 2 different classification values (age and gender). When I try to use 2 classification valu... | <p><code>train_test_split</code> splits each argument you pass to it into train and test sets. Since you are splitting three separate types of data, you need 6 variables:</p>
<pre><code>X_train, X_test, age_train, age_test, gender_train, gender_test = train_test_split(messages_bow, import_data['age'], import_data['gen... | python|pandas|machine-learning|sklearn-pandas | 1 |
15,554 | 70,086,461 | "IndexError: tuple index out of range" on train_test_split train data once attempting to fit for preprocessing | <p>I was trying to pre-process my data using normalization.</p>
<pre><code># preprocessing
import tensorflow as tf
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from tensorflow.keras import layers
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import MinMaxScaler... | <p>You extracted the X_btc as a Pandas Series which is like 1D array, you need to extract DataFrame (2D array/matrix). Replace:</p>
<pre><code>X_btc = btc_data["Time"]
</code></pre>
<p>with:</p>
<pre><code>X_btc = btc_data[["Time"]]
</code></pre>
<p>to extract the DataFrame</p>
<h3>Edit for the new... | python|pandas|numpy|tensorflow|scikit-learn | 1 |
15,555 | 70,087,211 | Create duplicate row in Pandas dataframe with a one to many mapping | <p>Suppose I have the following dataframe:</p>
<pre><code>df = pd.DataFrame({"A":[1,2], "B":["Q1", "Q2"], "C":[5,6]})
print(df)
A B C
1 Q1 5
2 Q2 6
</code></pre>
<p>I want to expand the dataframe by replacing the values of the 'B' column as follows. I want to... | <p>You can <code>map</code> a list and <code>explode</code>:</p>
<pre><code>df = pd.DataFrame({"A":[1,2], "B":["Q1", "Q2"], "C":[5,6]})
sub = {'Q1': ['Jan', 'Feb', 'Mar'], 'Q2': ['Apr', 'May', 'Jun']}
(df.assign(B=df['B'].map(sub))
.explode('B')
.reset_index(dro... | python|pandas|dataframe | 4 |
15,556 | 70,356,988 | Pytorch, retrieving values from a 3D tensor using several indices. Most computationally efficient solution | <p>Related:</p>
<p><a href="https://stackoverflow.com/questions/70342431/pytorch-retrieving-values-from-a-tensor-using-several-indices-most-computation">Pytorch, retrieving values from a tensor using several indices. Most computationally efficient solution</a></p>
<p>This is another question about retrieving values fro... | <p>You can use <a href="https://numpy.org/doc/stable/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer">advanced indexing</a> specifically <em>integer array indexing</em></p>
<pre class="lang-py prettyprint-override"><code>tensor_b = torch.tensor([[[4, 20], [1, -1]], [[1, 2], [8, -1]], [[92, 4]... | pytorch | 1 |
15,557 | 56,261,588 | Creating new Pandas DataFrame rows from multiple ID columns | <p>I have a Pandas dataframe where rows have attributes and the potential for multiple IDs. For example:</p>
<pre><code>Name Weapon Color ID1 ID2 ID3
Leo Sword Blue 11 12
Raph Sai Red 13
Don Bo Purple 14 15 16
Mike Nunchuck Orange 17
</code></pre>
<p>... | <p>You can use:</p>
<pre><code>df.melt(['Name','Weapon','Color'],value_name='ID').drop('variable',1).dropna()
</code></pre>
<hr>
<pre><code> Name Weapon Color ID
0 Leo Sword Blue 11.0
1 Raph Sai Red 13.0
2 Don Bo Purple 14.0
3 Mike Nunchuck Orange 17.0
4 Leo ... | python|pandas | 4 |
15,558 | 56,147,913 | How to pass parameters to tensorflow's predict function in siddhi? | <p>What parameters are passed to the predict function? Is there any documentation available for using siddhi's tensorflow plugin? </p>
<p>While there is a pbtxt model as part of the sample, that itself is very vague, with no background on what is being used to predict what.</p>
<pre><code>@App:name("TensorFlowTestApp... | <p>Pleas find the documentation <a href="https://siddhi-io.github.io/siddhi-execution-tensorflow/api/2.0.0/" rel="nofollow noreferrer">here</a>. In the sample provided a simple linear regression model is used. You give a 2 dimensional x coordinate for which you will receive a 2 dimensional y coordinated predicted from ... | tensorflow|siddhi|stream-processing|wso2-streaming-integrator | 1 |
15,559 | 64,755,250 | Count changes of value in groupby aggregated data frame | <p>I have a data frame with 5 columns that I need to count the value changes of in the hour of data the frame is grouped and aggregated by. The data is in 30 second intervals and my groupby aggregates that data to an hour, so within the 1 hour dataframe, there are 120 samples that I need to count the changes for in eac... | <p>So I battled through it, and came up with this that is working:</p>
<h3>First, fillna:</h3>
<pre><code>df_taps[['Z_A', 'Z_B', 'Z_C']] = df_taps.groupby(['DeviceUUID'])['Z_A', 'Z_B','Z_C'].apply(lambda x: x.fillna(value=0))
</code></pre>
<h3>Then, add columns that sum the count of diffs in the group:</h3>
<pre><code>... | python|pandas | 0 |
15,560 | 64,961,162 | Use numpy.einsum to calculate the covariance matrix of data | <p>My aim is to calculate the covariance matrix of a set of data using <code>numpy.einsum</code>. Take for instance</p>
<pre class="lang-py prettyprint-override"><code>example_data = np.array([0.2, 0.3], [0.1, 0.2]])
</code></pre>
<p>The following is code I tried:</p>
<pre class="lang-py prettyprint-override"><code>im... | <p>Based on the definition of a <a href="https://en.wikipedia.org/wiki/Covariance_matrix" rel="nofollow noreferrer">covariance matrix</a>, the task can be solved quite easily with</p>
<pre><code>tmp = np.random.rand(5,3) # 5 corresponds to 5 observations, 3 corresponds to 3 variables
tmp_mean = np.mean(tmp,axis=0)[:,No... | python|numpy|covariance|numpy-einsum | 2 |
15,561 | 64,898,358 | How to create the table of frequency for a list that contains arrays | <p>I have a list that has a few hundred thousand arrays of the same size. I need to remove the first element in each array and then create a table of frequency using <code>np.unique(my_array,return_counts=True)</code>.</p>
<p>For instance, consider</p>
<pre><code>data = [[0,1,5,6,3,4,5],[2,3,1,2,4,0,5],[9,7,0,2,4,0,3],... | <p>You can turn <code>data</code> into numpy array for advanced slicing:</p>
<pre><code>np.unique(np.array(data)[:,1:], return_counts=True)
</code></pre>
<p>Output:</p>
<pre><code>(array([0, 1, 2, 3, 4, 5, 6, 7]), array([4, 3, 3, 3, 4, 3, 1, 3]))
</code></pre> | python|numpy | 2 |
15,562 | 64,979,906 | Keeping track of total number of runs of inner loops | <p>I have a nested function, simplified below. I would like to keep track of the total runs in the inner loop, in order those values might be used later on, when naming output files.</p>
<p>Here is my current, nested loop, which prints the column name, and the item in an enumerated class attribute, <code>self.vals</cod... | <p><code>enumerate()</code> is simply counting each value in <code>self.vals</code>, so once all the items have been exhausted and the loop is run again, the count starts over.</p>
<p>To prevent it from being reset each time, the variable storing the index needs to defined outside the loop. Try setting <code>idx</code>... | python|python-3.x|pandas | 1 |
15,563 | 64,802,166 | Pandas: Combine pandas columns that have the same column name | <p>If we have the following df,</p>
<pre><code>df
A A B B B
0 10 2 0 3 3
1 20 4 19 21 36
2 30 20 24 24 12
3 40 10 39 23 46
</code></pre>
<p>How can I combine the content of the columns with the same names?
e.g.</p>
<pre><code> A B
0 10 0
1 20 19
2 30 24
3 40 39... | <p>If columns names are duplicated you can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><c... | python-3.x|pandas | 2 |
15,564 | 64,744,815 | Show NaN rows in a dataframe in Python | <p>I would like to print all NaN rows in <code>df</code>:</p>
<p><code>df</code>:</p>
<pre><code>from pandas import *
from numpy import *
df = pd.DataFrame({'Timestamp': {383439: Timestamp('2000-10-26 23:37:43.880000'),
304351: Timestamp('2000-10-26 23:37:52.880000'),
311295: Timestamp('2000-10-26 23:38:18.880000'... | <p>We check for row so we need add <code>any</code></p>
<pre><code>dfx[dfx.isna().any(1)]
Out[212]:
Timestamp Flag Value Number Id
383439 2000-10-26 23:37:43.880 1.0 NaN 0 30
358356 2000-10-26 23:38:21.880 NaN NaN 0 30
372410 2000-10-26 23:38:27.450 0.0 NaN 0... | python|pandas|numpy|dataframe|nan | 2 |
15,565 | 64,656,458 | Python pandas `replace` is not acting consistent | <p>I have a substantial database where I'm removing leading text of various lengths. Here's a minimal working example:</p>
<pre><code>data = {'Title' : ['Bertram, C. et al., 2015a: Carbon',
'Bertram, C. et al., 2015b: Complementing',
'Bertram, C. et al., 2018: Targeted']}
df = p... | <p><code>"[ab:]"</code> means "either a, or b, or :". You need <code>"[ab:]+"</code> ("either a, or b, or :, possibly repeated"), because they are repeated in, e.g., <code>"2015a:"</code>. With this correction, the first method will work.</p> | python|pandas|python-re | 1 |
15,566 | 40,269,366 | change the value in reduced matrix pandas | <p>I'm trying to implement algorithm, where given matrix(matrix represents cities) should be reduced by condition:</p>
<p>here the matrix(data frame matrix):</p>
<pre><code> 0 1 2 3 4
0 9992 1 0 2 0
1 2 99991 5 0 0
2 0 4 9992 0 ... | <p>Is <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.loc.html" rel="nofollow">this</a> what you want? </p>
<pre><code>reducedMatrix.loc[2][0] = 9999
</code></pre>
<p>where loc is used to index by label.</p>
<p>If you instead want to index by the new row/col <em>positions</em>... | python|pandas|matrix|dataframe | 1 |
15,567 | 69,549,921 | One Hot Encoding in Tensorflow | <p>I've been following the tensorflow walkthrough <a href="https://www.tensorflow.org/tutorials/structured_data/preprocessing_layers" rel="nofollow noreferrer">here</a> to create my own categorical OHE layer. The layer suggested is below and I've followed the preceding steps to the guide very closely:</p>
<pre><code> d... | <p>By default, CategoryEncoding uses output_mode="multi_hot". That's why you're getting output of size (1, vocab_size). To get OHE of size (n, vocab_size), make this change in your code</p>
<p><code>encoder = preprocessing.CategoryEncoding(num_tokens=index.vocabulary_size(), output_mode='one_hot')</code></p> | python|tensorflow|deep-learning|one-hot-encoding | 1 |
15,568 | 69,401,285 | "Attempting to perform BLAS operation using StreamExecutor without BLAS support" error occurs | <p>my computer has only 1 GPU.</p>
<p>Below is what I get the result by entering someone's code</p>
<pre><code>[name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456
locality {} incarnation: 16894043898758027805, name: "/device:GPU:0"
device_type: "GPU" memory_limit: 1... | <p>For the benefit of community providing solution here</p>
<blockquote>
<p>This problem is because when
keras run with gpu, it uses almost all <code>vram</code>. So we needed to give
<code>memory_limit</code> for each notebook as shown below</p>
<pre><code>gpus = tf.config.experimental.list_physical_devices('GPU')
if... | tensorflow|jupyter-notebook|gpu|tensorflow2.0|blas | 6 |
15,569 | 54,016,679 | tensorflow tf.py_func loading pickle Iterator throwing error, unknown shapes | <p>I am writing a tf.data pipeline for input into <code>keras</code> later on. The thing is my data is in the form of pickle files. I have a list of file names passed to tf data, that I am going to load using a custom tf.py_func calling pickle within. </p>
<p>The problem arises when I try to build an iterator from the... | <p>Your problem is that you are passing the wrong arguments to<code>tf.data.Iterator.from_structure</code>. It should take (output_types, output_shapes), but you are giving a dataset and its shapes.
Try this:</p>
<pre><code>training_iterator = tf.data.Iterator.from_structure(dataset.output_types, dataset.output_shapes... | python|machine-learning|deep-learning|tensorflow-datasets | 0 |
15,570 | 54,199,284 | Filter by index and flattened in numpy, like tf.sequence_mask | <p>I would like to filter my array 2D with an index and then flat this array only with values in the filter. This is pretty much what tf.sequence_mask would do but I would need this in numpy or another light library.</p>
<p>Thanks!</p>
<p>PD:
This is an example:</p>
<pre><code>array_2d = [[0,1,2,3,4,5],[8,9,10,11,12... | <p>Here's a <code>vectorized</code> solution, using a boolean mask to index <code>array_2d</code>:</p>
<pre><code>array_2d = np.array([[0,1,2,3,4,5],[8,9,10,11,12,0],[21,22,21,0,0,0]])
array_len = [6,5,3]
m = ~(np.ones(array_2d.shape).cumsum(axis=1).T > array_len).T
array_2d[m]
array([ 0, 1, 2, 3, 4, 5, 8, ... | python|numpy|tensorflow|masking | 2 |
15,571 | 53,899,315 | tf.reshape is not working in the cases where you are adding an extra dimension | <p>According to the tensorflow website, tf.reshape takes a tensor of a certain shape and maps it to a tensor of another shape. I want to map a tensor of size [600, 64] to a tensor of size [-1, 8, 8, 1] (in which the dimension at the -1 position is 600). This doesn't seem to be working though.</p>
<p>I am running this ... | <p><code>images[:600]</code>'s shape is <code>(600, 64)</code>, which does not correspond to the placeholder expected shape, <code>(None, 8, 8, 1)</code>.</p>
<p>Either reshape your data or change the shape of the placeholder.</p>
<p>Note that the fact that you originally defined the placeholder shape to be <code>(No... | python|tensorflow | 0 |
15,572 | 53,986,230 | How to count the number of unique entries in a dataframe using pandas and Python 3 | <p>I have a dataframe which has been reduced to a single column called Filename (already sorted in order) which contains a list of filenames which may or may not repeat themselves.</p>
<p>For example</p>
<pre><code>Filename
/dir1/dir2/abc.jpg
/dir1/dir2/abc.jpg
/dir1/dir2/def.jpg
/dir1/dir2/hij.jpg
/dir1/dir2/hij.jp... | <p>You can try like this.</p>
<blockquote>
<p>Using <strong>pandas.DataFrame.groupby()</strong></p>
</blockquote>
<pre><code>>>> import pandas as pd
>>>
>>> s = """/dir1/dir2/abc.jpg
... /dir1/dir2/abc.jpg
... /dir1/dir2/def.jpg
... /dir1/dir2/hij.jpg
... /dir1/dir2/hij.jpg
... /dir1/dir2... | python-3.x|pandas|dataframe | 0 |
15,573 | 66,124,388 | Add one column to all columns in other dataframe based on share index | <p>I am trying to add the values of one column in dataframe <code>df2</code> to all columns of dataframe <code>df</code>. They share a (unique) index, but the order maybe different.</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({"id":[1,2,3], "value1":[1,2,3], "value2&qu... | <p>I don't have a numpy styled answer, but here is a pandas style answer:</p>
<pre><code>df = pd.DataFrame({"id":[1,2,3], "value1":[1,2,3], "value2":[4,5,6]}).set_index("id")
df2 = pd.DataFrame({"id":[3,2], "add":[4,5]}).set_index("id")
print(df.upd... | python|pandas | 1 |
15,574 | 52,720,628 | how to groupby and aggregate in pandas | <p>I have following pandas dataframe</p>
<pre><code> index key start end nozzle tank
0 2018-01-01 02:00:01 - 02:30:00_1_1 2000 2003 1 1
1 2018-01-01 02:00:01 - 02:30:00_1_1 2003 2006 1 1
2 2018-01-01 02:00:01 - 02:3... | <p>Use:</p>
<pre><code>df1 = (df.groupby(['key','nozzle'])
.agg({'start':'first','end':'last'})
.assign(dif = lambda x: x['end'] - x['start'])['dif']
.unstack(fill_value=0)
.add_prefix('nozzle_')
.reset_index()
.rename_axis(None, axis=1))
print (df1)
... | python|pandas | 2 |
15,575 | 52,888,010 | Masking arrays in Java as with numpy in python | <p>Is there an elegant way to select elements of an array in Java similar to Numpy in Python?</p>
<pre><code>mask = np.array([True, False, False, True])
myArray = np.array([4, 3, 1, 2])
result = myArray[mask]
print(result)
</code></pre>
<p>This will give me
[4, 2]</p>
<p>Now I want to do the same in Java (withou... | <p>There is no such a built-in mechanism in Java, the array utility classes don't have it either.</p>
<pre><code>int[] array = {4, 3, 1, 2};
boolean[] mask = {true, false, false, true};
int[] result = IntStream.range(0, array.length)
.filter(i -> mask[i])
.map(i ->... | java|python|arrays|numpy | 2 |
15,576 | 46,183,442 | How to integrate tensorflow into QNX operating system | <p>I want to use the tensorflow in a QNX operating system? The very first step is to integrate the tensorflow into QNX. Any suggestions?</p> | <p>There is an issue on that on GitHub, unfortunately w/o a result but it's a starting point: <a href="https://github.com/tensorflow/tensorflow/issues/14753" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/14753</a></p>
<p>Depending on your objective, NVIDIA's TensorRT can load TensorFlow mod... | tensorflow|qnx | 1 |
15,577 | 46,621,302 | Selecting the last year for each index in Pandas | <p>I have this dataframe:</p>
<pre><code> score year ...
index
0 123 2015
0 5354 2016
0 4314 2014
12 4542 2018
12 4523 2017
13 123 2014
13 123 2012
13 231 2016
...
</code></pre>
<p>I want to select only the last year... | <p><strong>Option 1:</strong></p>
<pre><code>In [188]: df.groupby(level=0, group_keys=False).apply(lambda x: x.nlargest(1, 'year'))
Out[188]:
score year
index
0 5354 2016
12 4542 2018
13 231 2016
</code></pre>
<p><strong>Option 2:</strong></p>
<pre><code>In [193]: df.sort_va... | python|pandas|grouping | 3 |
15,578 | 46,398,078 | Fetch rows from pandas dataframe based on fixed counts from first row | <p>Here's my dataframe with 2500 rows.<a href="https://i.stack.imgur.com/nWptv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nWptv.png" alt="Dataframe" /></a></p>
<p>This is the index of my dataframe</p>
<pre><code>Index([u'Volume(%)1', u'Height(um)1', u' Area(%)1', u'OffsetX(mm)1',
u'Offset... | <p>Grouping rows (or columns) separately, in order to analyze is doing what pandas refers to as <a href="https://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow noreferrer"><strong>split-apply-combine</strong></a></p>
<p><strong>Setup Example Data</strong> </p>
<pre><code>import pandas as pd, numpy ... | python|pandas|dataframe | 2 |
15,579 | 46,332,235 | Find max values for each 5 rows in pd.DateFrame | <p>I have some marketing data with 1-minute interval.
As a sample of csv-table, each row represents max values for each minute: </p>
<pre><code>time ch1 ch2 ch3 ch4
20:03 1754 539 149 1337
20:04 2073 576 160 1448
20:05 2246 599 176 1515
20:06 2246 637 176 1531
20:... | <pre><code>g = df.groupby(np.arange(len(df)) // 5)
g.max().assign(time=g.time.first())
time ch1 ch2 ch3 ch4 ch5
0 20:03 2457 651 183 1549 4840
1 20:08 2792 717 199 1699 5376
2 20:13 3067 725 196 1685 5670
</code></pre> | python|pandas | 4 |
15,580 | 69,183,097 | How to modify format of time in AM and PM in Python Pandas? | <p>I have code in Python Pandas like below:</p>
<pre><code>print("Date: ", datetime.now().strftime("%d-%m-%Y %I:%M:%S"))
</code></pre>
<p>And it generates result: <code>Date: 14-09-2021 08:36:23</code></p>
<p>Nevertheless, I would like to have something like <code>Date: 14-09-2021 20:36:23</code>.... | <p>%I indicates 12 hour format. I believe to solve your issue you have to switch %I to %H (24 hour format).</p> | python|pandas|datetime|strftime | 0 |
15,581 | 69,118,426 | .txt to .csv via python delivers csv with only one column | <p>I'm a beginner in python coding
I wrote a little script to convert text files in a folder to csv files. The script is running but it delivers a csv file with only one column. Where's my fault? Also the converted files contain always .txt.csv. I would appreciate some help. Thanks a lot!</p>
<p><a href="https://i.stac... | <p>The problem could be the delimiter, try changing it to '\t' since from the picture you have posted it seems like the tabulation is the actual delimiter, another possible approach could be to change the read function to pd.read_table</p> | python|pandas|csv|txt | 0 |
15,582 | 69,047,024 | format excel data into database format with pandas - data cleaning | <p>want to know if this type of data cleaning has been done in pandas.
I have the following data frame (the columns continues with more dates but this is a sample)</p>
<pre><code>
d = {'Date' : ["Spiderman total",
"Division A",
"Division B",
"Division C",
"Superman total&quo... | <p>With a little post and pre processing you could use <code>melt</code> from Pandas to transform the data as you want.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
d = {
"Date": [
"Spiderman total",
"Division A",
"Division B&quo... | python|pandas|dataframe | 1 |
15,583 | 69,276,560 | Read checkbox values from excel using python without using win32 library | <p>I Need to read check boxes and have accomplished using below</p>
<pre><code>import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'\Test.xlsx')
ws = wb.Worksheets("Sheet1")
cb_dict = {}
for cb in ws.CheckBoxes():
cb_dict[cb.Name] = cb.Val... | <p>Unzip the <code>name.xlxs</code> table file to the folder. You'll find a file <code>name/xl/drawings/vmlDrawing1.vml</code>. There is the information including <code>Anchor</code>, <code>Checked</code>. The <code>value</code> of the checkbox in the front of the <code>shape</code>.</p>
<p>We can parse the <code>vmlDr... | python|pandas|python-requests | 0 |
15,584 | 60,803,891 | Find unique values between two columns | <p>I have been going through various questions, but haven't found one that fits to this case.</p>
<p>I have two columns with emails. The first column(CollectedE) consists of 32000 and the second column(UndE) consists of 14987. </p>
<p>I need to find all emails in the second column, which does not exist in the first c... | <p>Maybe <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.difference.html" rel="nofollow noreferrer"><code>pandas.Index.difference</code></a> can help you.</p> | python|pandas|dataframe|duplicates | 1 |
15,585 | 71,684,344 | How does one create ndarrays from a function? | <p>I am currently writing a neural network using the keras API. Therefore, I am structuring data that has a comparable input datastructure as that of the MNIST training dataset. It is a tuple consisting of 2 numpy ndarrays with shapes (60000, 28, 28) and (60000,)</p>
<p>I would like to extract 10 random samples out of ... | <p>I did not know there was a way to do a numpy list comprehension. I turns out there is and here is the answer to my own question:</p>
<pre><code>def mainTest():
random_samples = np.array([PrepareTestData.randomSamples() for x in range(SAMPLES)])
inputArraySample = np.array([PrepareTestData.inputData(samples )... | python|tuples|numpy-ndarray | 0 |
15,586 | 71,775,175 | Convert Pandas pivot_table function into Polars pivot Function | <p>I'm trying to convert some python pandas into polars. I'm stuck trying to convert pandas pivot_table function into polars. The following is the working pandas code. I can't seem to get the same behavior with the Polars pivot function. The polars pivot function forces the column parameter and uses the column values a... | <p>In Polars, we would not use a pivot table for this. Instead, we would use the <code>groupby</code> and <code>agg</code> functions. Using your data, it would be:</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
df = pl.from_pandas(df)
df.groupby("obj").agg(pl.all().n_unique())
</co... | python|pandas|python-polars | 3 |
15,587 | 71,449,837 | Lottery analysis for learning | <p>I'm trying to learn how to use the <code>pandas</code> library.</p>
<p>For the data source, I use the lottery combinations draws so far.</p>
<p>One of many tasks I'm trying to solve is to count the frequency of pairs of numbers in combinations.</p>
<p>I create a data frame from the list like this:</p>
<pre class="la... | <p>Here is a one-liner for it:</p>
<pre><code>from itertools import chain, combinations
from collections import Counter
lottery = [np.random.randint(1,100, size=6) for _ in range(1000)]
def commmon_combs(matrix, n_common, combs_r):
return Counter(chain(*[combinations(lottery[i], combs_r) for i in range(len(lotter... | python|pandas|combinations|analytics|analysis | 2 |
15,588 | 69,791,575 | Check if every element in 2D numpy array is in set | <p>I want to efficiently check, for every element in a numpy array, whether that element is present in a set. For example:</p>
<pre><code>segmask = np.array([[1,2,3,4]])
numbers = {2,4}
check_if_in_set(numbers, segmask)
</code></pre>
<p>should return</p>
<pre><code>[[False True False True]]
</code></pre>
<p>or simil... | <p><code>np.isin(segmask, list(numbers))</code></p>
<p>will give you the result you want. According to <a href="https://numpy.org/doc/stable/reference/generated/numpy.isin.html" rel="nofollow noreferrer">the isin documentation</a>, you <em>must convert the set to a list</em> before feeding it into the isin function.</... | python|numpy|set|where-clause | 2 |
15,589 | 43,147,435 | How does asynchronous training work in distributed Tensorflow? | <p>I've read <a href="https://www.tensorflow.org/deploy/distributed" rel="noreferrer">Distributed Tensorflow Doc</a>, and it mentions that in asynchronous training, </p>
<blockquote>
<p>each replica of the graph has an independent training loop that executes without coordination.</p>
</blockquote>
<p>From what I un... | <p>When you train asynchronously in Distributed TensorFlow, a particular worker does the following:</p>
<ol>
<li><p>The worker <strong>reads</strong> all of the shared model parameters in parallel from the PS task(s), and copies them to the worker task. These reads are uncoordinated with any concurrent writes, and no ... | python|asynchronous|tensorflow|neural-network|distributed | 32 |
15,590 | 43,058,477 | Python_Pandas: Among duplicate columns, choose the column with the most recent date AND THEN choose the one with maximum score | <pre><code>import pandas as pd
import numpy as np
#Create sample df with following columns; iP,date,score,appOwner,color
df = pd.DataFrame(
{"iP":['111.11.111.112', '111.11.111.113', '111.11.111.112', '111.11.111.112', '111.11.111.113', '111.11.111.113', '111.11.111.114', '111.11.111.114', '111.11.111.... | <p>I use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html" rel="nofollow noreferrer"><code>idxmax</code></a> to identify the location of the maximum value. This makes it easier to keep other relevant data in the same row.</p>
<p>So <code>ndf</code> will be a subset of <code>... | python|pandas | 2 |
15,591 | 43,077,525 | Pandas DataFrame Apply function, multiple arguments | <p>I have a Pandas dataframe and one of the columns is a string. I imported a function from an external module to do some RegEx checking and reduce this string to a short classification.</p>
<p>This works:</p>
<pre><code>df['PageCLass'] = df['PageClass'].apply(lambda x: PageClassify.page_classify(x))
</code></pre>
... | <p>The method above is ok I guess if it worked... In my opinion it does not answer the question because you're concatenating two arguments into one.</p>
<p>A way to do this to allow you to pass two arguments to apply:</p>
<pre><code>df['PageCLass'] = df[['PageClass','Rev']].apply(lambda x: PageClassify.page_classify(... | python|pandas|dataframe|apply | 2 |
15,592 | 43,379,401 | Divide each element of numpy matrix by the unit vector of that row | <p>How to divide each row element of numpy array by the unit vector of that row?</p>
<p>For eg : </p>
<pre><code>A = np.array([[ 0. , 1.],[ 2., 4.],[ 1., 5.]])
</code></pre>
<p>So, needed output matrix should be : </p>
<pre><code>[[ 0.0 , 1.][0.0, 0.0][0.19611614 , 0.98058068]]
</code></pre>
<p>I obtained this... | <p>Here's one approach -</p>
<pre><code>from __future__ import division
dists = np.linalg.norm(A,axis=1,keepdims=1)
out = np.where(np.isclose(dists,0), 0, A/dists)
</code></pre>
<p>Basically, with <code>np.where</code> we are choosing between two options, the syntax being :</p>
<pre><code>np.where(condition, option... | python-3.x|numpy | 0 |
15,593 | 50,651,633 | Combine keras functional api with tensorflow | <p>It's possible to combine tensorflow with keras sequential models like this: (<a href="https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html" rel="nofollow noreferrer">source</a>)</p>
<pre class="lang-python prettyprint-override"><code>from keras.models import Sequential, Model
model =... | <p>The functional and seqential apis are two different ways to create a model object. But once that object you can treat them the same way. For example calling them whith tensorflow objects.</p>
<p>Here you can find <a href="https://keras.io/getting-started/functional-api-guide/" rel="nofollow noreferrer">documentatio... | tensorflow|keras | 1 |
15,594 | 50,277,108 | Pandas find content by label not working | <p>Getting Key error in Python (3.5) pandas (0.22.0) under the following circumstances.
importing this csv data for example:</p>
<pre><code>'First', 'Name', 'Second', 'Number', 'Another Number', 'Random Exclamation', 'Time', 'Left', 'Anyway'
91004, 'Freddy', 1.518990585, 1.1000082, 5790, 'Hooray', 7241606319.947, 1939... | <p>You are missing inner quotation marks. In Python, quotation marks (single or double) may denote a string, so you need to use double outer quotes with single inner quotes. Try this instead:</p>
<pre><code>test.loc[0, "'First'"]
</code></pre>
<p>I strongly advise you clean up the column names by removing punctuation... | python|string|python-3.x|pandas | 1 |
15,595 | 45,382,917 | How to optimize for inference a simple, saved TensorFlow 1.0.1 graph? | <p>I cannot successfully run the <code>optimize_for_inference</code> module on a simple, saved TensorFlow graph (Python 2.7; package installed by <code>pip install tensorflow-gpu==1.0.1</code>).</p>
<h1>Background</h1>
<h2>Saving TensorFlow Graph</h2>
<p>Here's my Python script to generate and save a simple graph to... | <p><strong>Here is the detailed guide on how to optimize for inference:</strong></p>
<p>The <code>optimize_for_inference</code> module takes a <code>frozen binary GraphDef</code> file as input and outputs the <code>optimized Graph Def</code> file which you can use for inference. And to get the <code>frozen binary Grap... | python|python-2.7|tensorflow | 50 |
15,596 | 45,556,499 | Changing alpha of a line in seaborn factorplot | <pre><code>import seaborn as sns
sns.set(style="ticks")
exercise = sns.load_dataset("exercise")
g = sns.factorplot(x="time", y="pulse", hue="kind", data=exercise)
</code></pre>
<p>In the code above, how can I change the <code>rest</code> line to an alpha of 0.5?</p> | <p>Find proper objects of <code>FacetGrid</code> axes with <code>get_children()</code> method and set alpha for lines and markers. To change marker property in legend (<code>g._legend</code> object) find suitable element of <code>legendHandles</code> and apply <code>set_alpha()</code> method:</p>
<pre><code>import se... | python|pandas|matplotlib|seaborn | 6 |
15,597 | 62,711,656 | check in pandas if one value in a data frame is NaN and replace it with 0 | <p>I have the following data frame:</p>
<pre><code> EO EW Inc20 Inc100
bike 6 4.0 7 5
other 1 NaN 1 1
</code></pre>
<p>I want to replace the NaN value to Zero. and I have written the following code:</p>
<pre><code>for column in df:
df.loc[df.isnull().any(axis=1), column] = 0
df
</cod... | <p>If need only replace if exist one missing value create mask for count missing values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isna.html" rel="nofollow noreferrer"><code>DataFrame.isna</code></a> with <code>sum</code> and filter in <a href="http://pandas.pydata.org/pandas... | pandas|dataframe | 0 |
15,598 | 62,519,601 | Custom loss function Keras for y_pred above a certain threshold value only | <p>how to write a custom loss function in keras regression where MAE is calculated for y_pred above a certain threshold only.
For eg. y_true = [10 , 14 , 23 , 30 , 5 , 4] ,<br />
y_pred = [8 , 12 , 27 , 38 , 10 , 8]</p>
<p>How to write a custom loss function where MAE(Mean absolute error) of y_pred values above 20 onl... | <p>try in this way</p>
<pre><code>def custom_loss(y_true, y_pred):
y_pred = y_pred[y_pred>20]
y_true = y_true[y_pred>20]
return tf.reduce_mean(tf.abs(y_true-y_pred))
n_sample = 1000
X = np.random.uniform(0,5, (n_sample,10))
y = np.random.randint(0,50, n_sample)
inp = Input((10,))
x = Dense... | python|tensorflow|keras|deep-learning|neural-network | 2 |
15,599 | 54,410,302 | Split a large pandas column and affiancate as new column without considering index | <p>As stated in title, I need to split a pandas dataframe with columns containing million of rows in 2 equal parts. Than I need to merge the second half as new columns.</p>
<p>Here a small sample:</p>
<pre><code>AAA 125
BBB 467
XXX 321
YYY 568
</code></pre>
<p>Must be reshaped in:</p>
<pre><code>AAA 125 XXX 321... | <p>One way is by horizontally stacking the underlying array</p>
<pre><code>pd.DataFrame(np.hstack( (df.values[:len(df)//2], df.values[len(df)//2:])))
0 1 2 3
0 AAA 125 XXX 321
1 BBB 467 YYY 568
</code></pre>
<p>Option 2: Using reshape</p>
<pre><code>pd.DataFrame(np.reshape(df.values, (df.shape[0]//2, ... | pandas | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.