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 |
|---|---|---|---|---|---|---|
18,900 | 59,074,280 | Why density histogram shows a bit weird values on y-axis? | <p>A have a dataframe with values:</p>
<pre><code>user value
1 0
2 1
3 4
4 2
5 1
</code></pre>
<p>When I'm trying to plot a histogram with <code>density=True</code> it shows pretty weird result</p>
<pre><code>df.plot(kind='hist', denisty=True)
</code></pre>
<p><a href="https://i.stack.imgur.com/iUcyJ... | <p>If you are interested in probability and not probability density I think you want to use <code>weights</code> instead of <code>density</code>. Take a look at this example to see the difference:</p>
<pre><code>df = pd.DataFrame({'x':np.random.normal(loc=5, scale=10, size=80000)})
fig, (ax0, ax1) = plt.subplots(1, 2... | python|pandas|matplotlib | 4 |
18,901 | 59,161,697 | Introduction to Deep Learning with Keras: 'X_train' is not defined? | <p>So I'm trying to better understand deep learning through Keras. I've installed python, pip, tensorflow, and jupyter notebook to run this with, but based on the following example from "Introduction to Deep Learning with Keras" from towardsdatascience.com, I've already run into an error. Sorry if this seems very obvio... | <p>This was in fact just a casing issue in the example.
x_test and x_train were both changed to</p>
<pre><code>x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
</code></pre>
<p>Big thanks to oneturkmen for noting this.</p> | python|tensorflow|machine-learning|keras|jupyter-notebook | 1 |
18,902 | 59,272,572 | Dataframe operations with nan: dtype not working, vectorize problems | <p>I frequently have dataframes that are missing an ID like so:</p>
<pre><code> ID Price
0 1000 900
1 1001 100
2 1002 150
3 NaN 600
</code></pre>
<p>I'll want to apply some kind of logic to the ID to determine if the record is special, to get this kind of an output:</p>
<pre><code> ID Price Spe... | <p><code>np.nan</code> type is float, so 'ID' column contains both floats and strings. As mentioned in the first comment you should try to avoid using vectorize, you can simply do</p>
<pre><code>df_with_nan['Special ID?'] = pd.isnull(df_with_nan['ID'])
</code></pre>
<p>no conversion is necessary.</p>
<p>As a side no... | python|pandas|numpy | 0 |
18,903 | 59,109,070 | Pandas df.astype('float32') loses a lot of precision | <p>Why does a <code>float64</code> value <code>123456789.0</code> in a Pandas.DataFrame gets converted to <code>123456792.0</code>, preserving only 7 significant digits?</p>
<pre><code>import pandas as pd
df = pd.DataFrame([123456789.0])
# 0
# 0 123456789.0
df = df.astype('float32')
# 0
... | <p>Essentially, <code>float32</code> is <code>numpy</code>'s <code>dtype</code>. The reason why you see some difference in the precision when converting <code>float64</code> to <code>float32</code> is because <code>123456789.0</code> cannot be accurately represented using <code>float32</code> which is a 32-bit dtype (1... | python|python-3.x|pandas|dataframe|precision | 2 |
18,904 | 44,865,908 | Does Word2Vec maintain the sequential information of the input text? | <p>I ask because i'd like to use it to process the text input that I will be using for my LSTM. </p>
<p>Any feedback would be much appreciated. </p> | <p>As the name suggests, it is "word" to vector. What it does is, to represent words in their vector form. It's more like placing similar words grouped together in the space. </p>
<p>Like, 'cat' and 'kitten' represent similar meaning, so they will be closer to each other, i.e, their vector representation will be simil... | tensorflow|neural-network|lstm|recurrent-neural-network|word2vec | 0 |
18,905 | 44,935,269 | SuperTrend code using pandas python | <p>I am trying to code the following algorithm for SuperTrend indicator in python using pandas.</p>
<pre><code>BASIC UPPERBAND = (HIGH + LOW) / 2 + Multiplier * ATR
BASIC LOWERBAND = (HIGH + LOW) / 2 - Multiplier * ATR
FINAL UPPERBAND = IF( (Current BASICUPPERBAND < Previous FINAL UPPERBAND) or (Previous Close >... | <p>SuperTrend Indicator is included in <a href="https://github.com/twopirllc/pandas-ta" rel="nofollow noreferrer">pandas_ta</a> where you can simply:</p>
<pre><code>import pandas_ta as ta
sti = ta.supertrend(df['High'], df['Low'], df['Close'], 7, 3)
</code></pre>
<p>given that <code>df</code> is a pandas DataFrame wit... | python|python-3.x|pandas|dataframe|technical-indicator | 3 |
18,906 | 56,987,200 | Sum along diagonal and anti-diagonal lines in 2D array - NumPy / Python | <p>I have a np array like below:</p>
<pre><code>np.array([[1,0,0],[1,0,0],[0,1,0]])
output:
array([[1, 0, 0],
[1, 0, 0],
[0, 1, 0]])
</code></pre>
<p>I wish to sum left diagonal and right right diagonal line elements to new array:</p>
<p>1) left diagonal line :</p>
<p><a href="https://i.stack.imgur.co... | <p><strong>Approach #1 : Using masking</strong></p>
<p>Here's a vectorized one based on <code>masking</code> -</p>
<pre><code>def left_diag_sum_masking(a):
n = len(a)
N = 2*n-1
R = np.arange(N)
r = np.arange(n)
mask = (r[:,None] <= R) & (r[:,None]+n > R)
b = np.zeros(mask.shape,dt... | python|python-3.x|numpy|diagonal | 3 |
18,907 | 56,998,120 | Why are my images not getting cropped correctly using basic NumPy slicing? | <p>I am trying to crop square patches from images based on center coordinates and scale, using basic NumPy slicing (the exact same as <a href="https://stackoverflow.com/questions/21878868/extracting-patches-of-a-certain-size-from-the-image-in-python-efficiently">this question</a>):</p>
<pre><code>label_index, photo_id... | <p>You are slicing it incorrectly. The syntax is <code>sub_image = full_image[y_start: y_end, x_start:x_end]</code>. </p>
<p>In your code, the first coordinate limits in the splice are x coordinates, where it should instead be y-coordinates. That is, you should correct your splicing line to</p>
<pre><code>patch = bgr... | python|numpy|opencv|indexing|slice | 0 |
18,908 | 57,083,743 | Fetch data from a DataFrame and insert into multiple rows in SQL table by generating queries | <ol>
<li>Have a dataframe with edited data from table1.</li>
<li>Use that dataframe to generate SQL queries (using python) that updates specific column and multiple rows in table1 in the SQL database. </li>
<li>These queries should not have any dependency i,e must be able to run directly on the SQL database.</li>
</ol>... | <p>You added a lot of superfluous information, I think. Try the sample script below and see if it does what you want, with the obvious specific changes to do exactly what you need to do, of course.</p>
<pre><code># Insert from dataframe to table in SQL Server
import time
import pandas as pd
import pyodbc
# create ti... | sql|sql-server|python-3.x|pandas | 2 |
18,909 | 46,157,848 | TensorFlow: CovNet returning same output for all the examples | <p>I have 200 images on a set, 100 identical squares and 100 identical circles. Images are 44x41 pixels and images are grayscale. I am trying to build a simple classifier to learn tensorflow.</p>
<p>The problem: the predictor vectors have always the same value regardless the input image. </p>
<p>Here's the code of my... | <p>Try not to give the same name to two tensors. For example, you have <code>conv_layer</code> that is equal to <code>tf.nn.conv2d(features, weights, strides=[1, 1, 1, 1], padding='SAME')</code> then rewriten to <code>tf.nn.bias_add(conv_layer, biases)</code>, then once more then its another shape and then ....</p>
<p... | tensorflow|deep-learning|conv-neural-network | 0 |
18,910 | 46,153,103 | Find mean based on a fixed time duration | <p>I have data in the below format.</p>
<pre><code>index timestamps(s) Bytes
0 0.0 0
1 0.1 9
2 0.2 10
3 0.3 8
4 0.4 8
5 0.5 9
6 0.6 7
7 0.7 8
8 ... | <p>John Galt suggests a <a href="https://stackoverflow.com/questions/46153103/divide-a-python-array-into-fixed-duration-parts-windowing/46153350?noredirect=1#comment79268746_46153350">simple alternative</a> that works well for your problem.</p>
<pre><code>g = df.groupby(df['timestamps(s)']//0.3*0.3).Bytes.mean().reset... | python|pandas|dataframe | 1 |
18,911 | 45,738,878 | using data from text file to construct linear regression | <p><a href="https://onlinecourses.science.psu.edu/stat462/sites/onlinecourses.science.psu.edu.stat462/files/data/poverty.txt" rel="nofollow noreferrer">Poverty.txt</a></p>
<p>I am using the poverty.txt file from the above link to construct linear regression in python. When I am trying to import the file using panda, I... | <pre><code>import pandas as pd
data = pd.read_csv("poverty.txt", delim_whitespace=True)
data
Out[2]:
Location PovPct Brth15to17 Brth18to19 ViolCrime TeenBrth
0 Alabama 20.1 31.5 88.7 11.2 54.5
1 Alaska 7.1 18.9 73.7 ... | python|pandas|linear-regression | 0 |
18,912 | 23,008,447 | Classification test in Scikit-learn, ValueError: setting an array element with a sequence | <p>Using the <a href="http://scikit-learn.org/stable/auto_examples/ensemble/plot_adaboost_multiclass.html" rel="nofollow">tutorial on multiclass adaboost</a>, I'm trying to classify some images that have two classes (but I don't suppose the algorithm shouldn't work if the problem is binary). Then I'm going to extend my... | <p>try:</p>
<pre><code>imgs = []
tmp_hogs = np.zeros((17, 256))
# 13 of the images are with vehicles, 4 are without
labels = [1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0]
i = 0
for file in out:
filepath = "C:\PATH_TO_SAMPLE_IMAGES\\" + file
curr_img = color.rgb2gray(io.imread(filepath))
imgs.append(resi... | python|numpy|scikit-learn | 1 |
18,913 | 35,681,889 | Multidimensional symbolic matrix in Python | <p>I would like to create a 3D matrix of specific size by calculating a value for each combination of indexes. Each value in the matrix will be symbolic.</p>
<p>What I tried up to now:</p>
<pre><code>import numpy as np
import sympy as sp
var1 = np.arange(1,10,2)
var2 = np.arange(1,10,2)
var3 = np.arange(20,50,5)
my... | <p>The first error you get is, as you suggested, because you try to save a <code>sympy</code> type object into a <code>numpy</code> zeros array which is of type numbers. One option would be to use a <code>numpy</code> array of objects, which works as follows,</p>
<pre><code>import numpy as np
import sympy as sp
var1 ... | python|numpy|matrix|sympy | 4 |
18,914 | 51,006,714 | Replacing each row with a column | <p>Given an array <code>X</code> of shape <code>(n, m)</code> and another given number <code>l</code> how can I get an array <code>Y</code> of shape <code>(n, l, m, l)</code> where <code>Y[i, j, :, :]</code> is the null matrix that has been replaced the <code>j</code>-th column by the <code>i</code>-th row of X.</p>
<... | <p>Use <code>np.einsum</code>:</p>
<pre><code>Y = np.zeros((n, l, m, l))
np.einsum('ijkj->jik', Y)[...] = X
</code></pre> | python|numpy|numpy-ndarray | 1 |
18,915 | 66,587,468 | How to insert long text from .txt file to a DataFrame | <p>I am building a CNN model, and I have to analyze its training history per epoch. Epoch history looks like this. This history is saved on a <code>.txt</code> file.</p>
<pre><code>Epoch 1/300
11/11 [==============================] - 4s 182ms/step - loss: 8.3641 - accuracy: 0.1382 - f1_m: 0.0676 - precision_m: 0.2398 -... | <p>I'm assuming that you can read the <code>.txt</code> file and save it to a variable like <code>text</code>. Then you could do the following:</p>
<pre><code>import pandas as pd
text = '''Epoch 1/300
11/11 [==============================] - 4s 182ms/step - loss: 8.3641 - accuracy: 0.1382 - f1_m: 0.0676 - precision_m... | python|pandas|dataframe|text-files | 1 |
18,916 | 66,611,777 | Denormalize/Restructure CDISC supplement data | <p>I have a data frame that looks like this:</p>
<pre><code> USUBJID IDVAR IDVARVAL QNAM QVAL
0 Dummy-01-0001 AESEQ 1.0 AEdummy1 2012-02-15
1 Dummy-01-0002 AESEQ 1.0 AEdummy1 2012-02-23
2 Dummy-01-0004 AESEQ 1.0 AEdummy1 ... | <p>Let us try with <code>unstacking</code> followed by <code>concat</code>:</p>
<pre><code>s = df.set_index([df.groupby('IDVAR').cumcount(), 'USUBJID'])
s1 = s.set_index('IDVAR', append=True)['IDVARVAL'].unstack()
s2 = s.set_index('QNAM', append=True)['QVAL'].unstack()
out = pd.concat([s1, s2], axis=1).reset_index(l... | python|pandas|dataframe|pivot | 6 |
18,917 | 66,551,758 | Is there a .any() equivalent in PySpark? | <p>I am wondering if there is a way to use <code>.any()</code> in Pyspark?</p>
<p>I have the following code in Python, that essentially searches through a specific column of interest in a subset dataframe, and if any of those columns contain <code>"AD"</code>, we do not want to process them.</p>
<p>Here is th... | <p>You can use Window function (the max of a boolean is true if there is at least one true value):</p>
<pre><code>from pyspark.sql import functions as F, Window
df1 = df.withColumn(
"to_exclude",
~F.max(F.when(F.col("Code") == "AD", True).otherwise(False)).over(Window.partitionBy(... | python|pandas|apache-spark|pyspark|apache-spark-sql | 4 |
18,918 | 66,534,480 | Python Pandas - Convert String-Class to Datetime | <p>I need to filter some data. I need to get some rows between 2 dates from a Pandas-DataSet.</p>
<p>The variables are defined as:</p>
<pre><code>start = datetime.strptime(diaginput[5],"%d.%m.%Y")
end = datetime.strptime(diaginput[6],"%d.%m.%Y")
# output: 2015-01-01 00:00:00
# type (start): <cla... | <p>I have <strong>solved</strong> it:</p>
<pre><code># Filter data between two dates
consumption = consumption.loc[(consumption['date'] >= start)
& (consumption['date'] < end )]
</code></pre> | python|pandas|string|datetime | 0 |
18,919 | 66,648,223 | How to use the gzip module to open a csv file | <p>I am looking to read in a .csv.gz file that is in the same directory as my python script using the gzip and pandas module only.</p>
<p>So far I have,</p>
<pre><code>import gzip
import pandas as pd
data = gzip.open(test_data.csv.gz, mode='rb')
</code></pre>
<p>How do I proceed in converting / reading this file in as ... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><strong><code>pandas.read_csv</code></strong></a> directly:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.read_csv('test_data.csv.gz', compression='gzip')
... | python|pandas|gzip | 4 |
18,920 | 66,524,703 | The last dimesion of the output of tf.boolean_mask is None | <p>I want to get the flatten form of upper triangle part of a matrix and feed it to a fully_connected network. I tried to use <code>tf.boolean_mask</code> to get the upper triangle part but it seems that the last dimension of the output is always <code>None</code>, which is invalid for the fully_connected layer. Is the... | <p>Trying setting the shape with <code>set_shape()</code></p>
<p><strong>Example</strong>:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import tensorflow.contrib.slim as slim
inputs = tf.constant(
[[[1, 2, 3], [3, 4, 5], [6, 7, 8]],
[[5, 6, 7], [7, 8, 9], [0, 0, 1]]], tf.float3... | python|tensorflow | 0 |
18,921 | 66,453,409 | Pandas data frame from dictionary returns values as tuple | <p>Hey guys If someone could give me an explanation I would be very grateful.
This is a code:</p>
<pre><code>#Dict-
hours_year={'2018': 900 , '2019':456}
# Making a df
df=pd.DataFrame({'Year': hours_year.keys(), 'Hours': hours_year.values()})
df
</code></pre>
<pre><code>#Output
Year Hours
0 (2018,... | <p>Founded <a href="https://stackoverflow.com/questions/25318639/create-python-dataframe-from-dictionary-where-keys-are-the-column-names-and-valu">here</a>:</p>
<pre><code>pd.DataFrame(hours_year, index=['i',])
</code></pre>
<p>Else, you should try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pan... | python|pandas|dictionary|tuples | 0 |
18,922 | 66,424,153 | Calculate the distance two points - from csv file | <p>I want to measure the distance of these two points. Is there an easier way to calculate the distance? I try by np.select. I know that I would have to do 3 more conditions . This is error which I have :</p>
<p><a href="https://i.stack.imgur.com/odzEG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com... | <p>you cant use this <code>&</code> in python as <code>&&</code> in C++ or C.</p>
<p>change this:</p>
<pre><code>(data['x_start'] < data['x_end']) & (data['y_start'] < data['y_end'])
</code></pre>
<p>to this:</p>
<pre><code>(data['x_start'] < data['x_end']) and (data['y_start'] < data['y_end... | python|pandas|math | 1 |
18,923 | 57,702,151 | How to Reccurently Transpose A Series/List/Array | <p>I have a array/list/pandas series :</p>
<pre><code>np.arange(15)
Out[11]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
</code></pre>
<p>What I want is:</p>
<pre><code>[[0,1,2,3,4,5],
[1,2,3,4,5,6],
[2,3,4,5,6,7],
...
[10,11,12,13,14]]
</code></pre>
<p>That is, recurently transpose this col... | <p>If the array is formatted like this : </p>
<pre><code>arr = np.array([1,2,3,4,5,6,7,8,....])
</code></pre>
<p>You could try it like this : </p>
<pre><code>recurr_transpose = np.matrix([[arr[i:i+5] for i in range(len(arr)-4)]])
</code></pre> | python|arrays|pandas|list | 0 |
18,924 | 43,814,236 | GroupBy All possible permutations | <p>Example dataset columns: ["A","B","C","D","num1","num2"]. So I have 6 columns - first 4 for grouping and last 2 are numeric and means will be calculated based on groupBy statements.
I want to groupBy all possible combinations of the 4 grouping columns.
I wish to avoid explicitly typing all possible groupBy's such as... | <p>When you group by <code>['A', 'B', 'C', 'D']</code> and calculate the mean, you'll get one particular group <code>(a0, b0, c0, d0)</code> with a mean of <code>m0</code>.</p>
<p>When you permute the columns and group by <code>['A', 'B', 'D', 'C']</code>, you'll get one particular group <code>(a0, b0, d0, c0)</code> ... | python|pandas|group-by | 0 |
18,925 | 43,506,115 | python numpy ImportError: No module named core | <p>Im unable to launch a python script using numpy - any idea what/where this core is?</p>
<pre><code>Traceback (most recent call last):
File "/scripts/python/foo.py", line 9, in <module>
import numpy
File "/packages/python/2.7.2/lib/python2.7/site-packages/numpy/__init__.py", line 156, in <module>... | <p>You are using a very old numpy version (older than 1.7, which was released 4+ years ago) that still uses implicit relative imports within the package. The error you're seeing is a common issue with such imports, and has been addressed in more recent NumPy releases. Update NumPy, and this problem should go away.</p> | python|numpy | 0 |
18,926 | 73,107,184 | How can I work on a large dataset without having to use Pyspark? | <p>I'm trying to work on a dataset with 510,000 rows and 636 columns. I loaded it into a dataframe using the dask dataframe method, but the entries can't be displayed. When i try to get the shape, it results in delays. Is there a way for me to analyze the whole dataset without using big data technologies like Pyspark?<... | <p>Firstly, spark, dask and vaex are all "big data" technologies.</p>
<blockquote>
<p>it results in delays</p>
</blockquote>
<p>If you read the documentation, you will see that dask is lazy and only performs operations on demand, you have to want to. The reason is, that just getting the shape requires reading... | python-3.x|pandas|data-science|bigdata|dask | 1 |
18,927 | 72,899,720 | Selecting specific columns from a Data Frame | <p>everybody!!
I have a question.
Imagine a Data Frame with columns [a, b, c, e, f, g, h, i, j]. I want to create a 2nd DF having only columns a, c-g. How can I do this in a single coman without creating a list putting ao the columns? For example, I'm writing in that way:</p>
<pre><code>columns = ['a', 'c', 'e', 'f', '... | <p>The easiest way will be to use slice notation <code>.loc</code> as you demonstrated along with a call to <code>.drop</code> to remove any specific unwanted columns:</p>
<h2>Create data</h2>
<pre class="lang-py prettyprint-override"><code>>>> df = pd.DataFrame([[*range(10)]]*5, columns=[*'abcdefghij'])
>&... | python|pandas | 1 |
18,928 | 73,066,908 | How do I fix this code error? ValueError: A target array with shape (6985, 10) was passed for an output of shape (None, 100) | <p>I was trying to follow a tutorial for audio classification, but came across two errors. I searched for solutions but they didn't work when I tried for example, putting -sparse_categorical_crossentropy in place of categorical_crossentropy. I am not very sure on how to fix these errors as one is about a num_labels re... | <p>As stated in the error,</p>
<blockquote>
<p>NameError: name 'num_labels' is not defined</p>
</blockquote>
<p>Because you haven't defined the 'num_labels' variable, the error occurs. Please define it as follows.</p>
<pre><code>#Defining num_labels
num_labels=len(extracted_features_df['class'].unique())
num_labels
</c... | python|tensorflow | 0 |
18,929 | 70,513,955 | Utilize Python Input() to apply conditionals on a dataset | <p>I have a dataset where, whenever a date value in the <code>mig2</code> column is entered into the input() prompt, <strong>mig1, de</strong> and <strong>re</strong>
values will be updated according to these rules:</p>
<pre><code> mig1 is 5 months from the date entered in the input() prompt
de is 3 months from ... | <p>Rather than to use a conditional statement, it's probably better to build a dataframe to update yours. For that, I slightly modified your input:</p>
<pre><code>data = {
'aa': {'mig1': pd.DateOffset(months=5),
'de': pd.DateOffset(months=3),
're': pd.DateOffset(months=1),
'mig2': p... | python|pandas|numpy|input | 1 |
18,930 | 70,718,307 | This pandas series is a view... into what? | <p>Consider the following example.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
"x": [1, 2, 3],
"y": [4, 5, 6]
})
x = df["x"]
df.drop(index=[0], inplace=True)
</code></pre>
<p>Now we have <code>x._is_view</code> is <code>True</code>, so I would expect <code>x</code> to ... | <p><code>inplace</code> does not guarantee that the dataframe will be modified in place. In this case, as in many cases, it creates a copy and reassigns it to <code>df</code>. See the discussion of <code>inplace</code> <a href="https://stackoverflow.com/questions/43893457/understanding-inplace-true-in-pandas">here</a>.... | python|pandas | 1 |
18,931 | 70,385,144 | numpy method instead of for | <p>I have a pandas dataframe like below (yellow highlight represent sample co-occurrence of columns):</p>
<p><img src="https://i.stack.imgur.com/Q0uKp.png" alt="yellow highlight represent sample co-occurrence of columns" /></p>
<p>I need to form a matrix in which elements are the sum of co-occurrence of columns through... | <p>if you can do it in pure numpy, i don't know how. but here's my solution anyway</p>
<pre><code>from itertools import permutations
co_occur=np.zeros((25,25))
# get all rows where sum>1
rows=np.where(np.sum(train_data,1)>1)
for row in rows[0]:
# get all indices of columns with value=1
idx=np.where(trai... | python|algorithm|numpy | 0 |
18,932 | 70,699,098 | HTTPError when appending DataFrame | <p>I am reading Python code from another programmer, particularly the following code block:</p>
<pre class="lang-py prettyprint-override"><code>try:
df.append(df_extension)
except HTTPError as e:
if ("No data could be loaded!" in str(e)):
print("No data could be loaded. Error was caught.&... | <p>According to comments to the question by @JCaesar and @Neither, you don't have to worry about an <code>HTTPError</code> arising from the use of <code>df.append</code>. The <code>try</code>-<code>except</code>-block does not seem to have any justification. The one-liner</p>
<pre class="lang-py prettyprint-override"><... | python|pandas|try-except|http-error | 0 |
18,933 | 42,632,029 | how to use python to select first X columns and last Y columns | <p>I am trying to select column 1 to 8 and the last column from a data frame. I have some dumb way to do that</p>
<p>step 1: select first 8 column</p>
<pre><code>df1 = df[df.columns[range(9)]]
</code></pre>
<p>step 2: select last column</p>
<pre><code>df2 = df[df.columns[-1]]
</code></pre>
<p>step 3: combine step1... | <p>Use smart column indexing:</p>
<pre><code>df.iloc[:, list(range(9)) + [-1]]
</code></pre> | python|pandas | 14 |
18,934 | 42,904,913 | Dictionary with custom tuples as keys, to circunvent a Pandas "bug" doesn't work as expected | <p>I'm trying to create a class which acts like a dictionary whose keys are tuples, but I don't want them to be "truly" tuples, because I'll use this dictionary to create Pandas dataframes, and Pandas assume that tuples as keys mean a multi-index (which is not correct in this case).</p>
<p>In the case of tuples of a s... | <p>You also need to implement either <code>__eq__</code> or <code>__cmp__</code> for being <a href="https://docs.python.org/2/glossary.html#term-hashable" rel="nofollow noreferrer"><code>hashable</code></a>:</p>
<blockquote>
<p>An object is hashable if it has a hash value which never changes
during its lifetime (i... | python|pandas|dictionary | 1 |
18,935 | 42,894,968 | Lag values and differences in pandas dataframe with missing quarterly data | <p>Though Pandas has time series functionality, I am still struggling with dataframes that have incomplete time series data. </p>
<p>See the pictures below, the lower picture has complete data, the upper has gaps. Both pics show correct values. In red are the columns that I want to calculate using the data in black. C... | <p>Solved the basic problem by using a merge. First, create a variable that shows the lagged date or quarter. Here we want last year's MV (4 quarters back):</p>
<pre><code>from pandas.tseries.offsets import QuarterEnd
dfg['lagQ'] = dfg['date'] + QuarterEnd(-4)
</code></pre>
<p>Then create a data-frame with the keys ... | python|pandas|dataframe|time-series|financial | 1 |
18,936 | 25,291,233 | ordering and concatinating two arrays based on one column elements | <p>I have a big array of data with the shape of <code>(24000, 5)</code>. I gave this array as an input to a code but the code shuffled and changed fourth columns and only the last column is intact. What is the fastest way that I can find the similar elements in the last column and stick the correspondence rows in the p... | <p>You can use <code>numpy.argsort()</code> to sort the last column of both arrays and then combine them using <code>numpy.hstack()</code>. </p>
<p>The <code>orig_order</code> is used to return the concatenated array to the original order...</p>
<pre><code>import numpy as np
as1 = np.argsort(a1[:,-1])
orig_order = n... | python|arrays|numpy|pandas|multidimensional-array | 1 |
18,937 | 30,585,025 | Retrieve indexes of min and max values in np.ndarray | <p>i am working on some tif files and i have to plot dependecies between temperature and vegatation index based on .tif file. It was just FYI. Now my programming problem.
I'm using python 2.7 (x64).
I have big ndarray form NumPy lib, contains values of temerature and second (same size) with vegetation idex. <code>mer... | <p><code>ndvi1[mergedmask==False].argmin()</code> will give you the index of the minimum in <code>ndvi1[mergedmask==False]</code>, i.e., the index into a new array, corresponding to the places where <code>mergedmask</code> is <code>False</code>.</p>
<p>The problem here is that <code>ndvi1[mergedmask==False]</code> isn... | python|numpy|gis | 0 |
18,938 | 30,539,352 | restrict filling in missing data for panda to a single index on multi-indexed DataFrame | <p>As an example, imagine i have a df with columns for 'year', 'quarter' (sequential through a year), a variable ('var'), and a measurement ('value'):</p>
<pre><code>year quarter var value
2015 1 A 0.1
2015 2 A 0.5
2015 3 A 0.6
2015 4 A 1.0
2015 ... | <p>You basically need your data in a table with time along your row indices and everything else in columns. You can use a pivot table or stack/unstack:</p>
<pre><code>df2 = df.set_index(['year', 'quarter', 'var']).unstack('var')
>>> df2
value
var A B C
year quarter ... | python|pandas | 5 |
18,939 | 38,970,767 | How can we append unbalanced row on Pandas dataframe in the fastest way? | <p>I am going to make pandas dataframe from unbalanced csv file</p>
<p>But the speed is too slow when I make it in a brute force way.</p>
<p>Here, I have the list of columns which can make Schema of Dataframe</p>
<p>And a bunch of rows in a file.</p>
<p>How could I make it fast?</p>
<p>(Should I make empty list in... | <p><code>pd.DataFrame</code> can build a DataFrame from a list of ragged rows:</p>
<pre><code>In [17]: pd.DataFrame([['a','b'],[1,2,3]])
Out[17]:
0 1 2
0 a b NaN
1 1 2 3.0
</code></pre>
<p>Moreover, it is faster to build the DataFrame with one call to <code>pd.DataFrame</code>
than many calls to <code>n... | python|performance|pandas | 2 |
18,940 | 39,129,224 | how to use *and* in pandas loc API | <p>I try do use <em>and</em> in a <code>.loc</code> API::</p>
<pre><code>df = pd.DataFrame(dict(age=[99, 33, 33, 22, 33, 44],
aa2=[199, 3, 43, 22, 23, 54],
nom=['a', 'z', 'f', 'b', 'p', 'a'],))
df.loc[df.age>30]
# aa2 age nom
# 0 199 99 a
# 1 3 33 z
# 2 ... | <pre><code>>>> df.loc[(df.age>30) & (df.age > df.aa2)]
aa2 age nom
1 3 33 z
4 23 33 p
</code></pre> | python|pandas | 4 |
18,941 | 12,995,222 | Pandas adding Series to keep a running sum | <p>I am just getting started in Python and using pandas to write a little stock portfolio app. The problem I am having is in my position class which creates pandas Series to represent the number of shares owned of each stock over time based on the trades. So If I bought 50 shares in IBM on 10/10/2012 and sold 10 shares... | <p>so Series.add <em>returns</em> the summed series...I thought it just added it to the already existing Series object. So I did this:</p>
<pre><code>self.shares = self.shares.add(shareSer, fill_value=0)
</code></pre>
<p>instead of </p>
<pre><code>self.shares.add(shareSer, fill_value=0)
</code></pre>
<p>and it work... | python|pandas | 1 |
18,942 | 28,921,065 | Interpolate between rows or columns of a Numpy array | <p>I have a W x H array A1. There is another W x M array A2, where M << H.
These M points along that dimension is supposed to be put in equal-spaced cells of the for all the W dimension.
I've achieved this by </p>
<pre><code>hopSize = H / M
A1[:, 0 : min(A1.shape[1], hopSize*M) : hopSize] = A2
</code></pre>
<p>... | <p>A general approach would be to use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d" rel="nofollow"><code>scipy.interpolate.interp1d</code></a>:</p>
<pre><code>import numpy as np
from scipy.interpolate import interp1d
# generate some example da... | python|numpy | 4 |
18,943 | 29,073,647 | Not able to sum values while using numpy | <p>I have created a script for calculating the sum of all the values in 32th column which has comma as delimiter. My script is printing the values but unable to sum the values. What I am doing wrong? Below is my script:</p>
<pre><code>import numpy as np
b=np.loadtxt(r'FileP3806520150316142845.txt',dtype=str,delimiter=... | <p>Try setting <code>dtype=int</code>. Numpy doesn't know what to do with a bunch of strings.</p>
<p>You can also convert <code>b</code> after the fact:</p>
<pre><code>b_ints = np.int_(b)
</code></pre> | python|numpy | 3 |
18,944 | 14,966,273 | Numpy ndarray subclass - forcing reshape in __array_finalize__ | <p>I am having trouble with the following:</p>
<p>I would like to write an ndarray subclass and enforce shape (-1,3) for any new instance of this subclass, whichever way it comes about- explicit constructor, view casting or from template.</p>
<p>I've tried loads of things but none seem to work.
I reckon I haven't fu... | <p>You should take a look at how the <a href="https://github.com/numpy/numpy/blob/master/numpy/matrixlib/defmatrix.py#L195" rel="noreferrer"><code>matrix</code> class</a> is implemented. It does similar tricks to maintain <code>ndims=2</code>.</p>
<p>However, I and many others consider such trickery more trouble than ... | python|numpy|subclass|multidimensional-array | 7 |
18,945 | 29,524,299 | Aggregating over a lagged time period in PANDAS | <p>I have a multi-index dataframe with indexes for day and stock ticker. Here's a subset:</p>
<p><img src="https://i.stack.imgur.com/2oLWG.png" alt="enter image description here"></p>
<p>I want to create several lag variables. I've figured out how to create a one-day lag:</p>
<pre><code>df['Number of Tweets [t-1]'] ... | <p>Use pd.rolling_sum on the shifted data. To calculate the rolling sum for t-3 through t-1, use a window length of 3 and shift the data by 1 (the default if no parameter is specified).</p>
<pre><code>from pandas import Timestamp
# Create series
s = pd.Series({(Timestamp('2015-03-30 00:00:00'), 'AAPL'): 2,
(Timesta... | pandas|time-series | 2 |
18,946 | 29,378,852 | When using dataframes as params for .fillna(), is identical shape required? | <p>According to the Docs, you can use a Dataframe as the value parameter for .fillna()</p>
<p><a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.fillna.html</a></p>
<p>But does the data... | <p>A workaround for this could be to use a <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow">transform</a> (rather than an aggregating) groupby method:</p>
<pre><code>df1.fillna(df1.groupby(level=0).transform("mean"))
</code></pre>
<p><em>It's unclear to me whether this ... | python|pandas | 2 |
18,947 | 62,362,015 | Rename a column based on values in another column | <p>I have a set of four dataframes: df_all = [df1, df2, df3, df4]</p>
<p>As a sample, they look like this:</p>
<p>df1: </p>
<pre><code>Name Dates a
Apple 5-5-15 NaN
Apple 6-5-15 42
Apple 6-5-16 36
Apple 6-5-17 36
df2:
Name Dates a
Banana 5-5-15 ... | <p>Try to change the column name in your first for loop before you drop that column.</p>
<pre><code>for cols in df_all:
name = cols['Name'][0]
cols.drop(['Name'],axis=1,inplace=True)
cols.rename(columns={'a':name},inplace=True)
a = df1.merge(df2, how='left', on = 'Date').merge(df3, how='left', on = 'Date'... | python|pandas | 2 |
18,948 | 62,103,867 | Pandas to create columns based on starting Character | <p>I have below data parsed Data from the Linux Machine into a text file.</p>
<p>What i Want..</p>
<blockquote>
<ol>
<li><p>Any line Startswith <code>cn:</code> should be comes under column <code>Group_Name</code> by constituting it.</p></li>
<li><p>Below <code>cn:</code> there are lines starting <code>nisNetgr... | <p>You would need to prepare data in a suitable way. This is how you could do that:</p>
<h2>Demo data in file:</h2>
<pre><code>with open ("data.txt", "w") as f:
f.write("""cn: Infra_SAT_IMEC_TR-KPQ01
nisNetgroupTriple: kht1562.khatigusain.com.com
nisNetgroupTriple: kht1187.khatigusain.com.com
cn: Infra_RDC_IMEC_... | python-3.x|pandas | 2 |
18,949 | 62,298,296 | Kernel freezes when running federated computation with tensorflow_federated and nest_asyncio | <p>I try to run a simple federated computation using tensorflow_federated.
tff.federated_computation() -> after running this, the kernel freezes and am not able to run other cells.</p>
<p>TF-Federated needs asyncio to prevent <a href="https://github.com/tensorflow/federated/issues/842" rel="nofollow noreferrer">this</... | <p>This can be fixed by downgrading the jupyter notebook and tornado version.</p>
<p>Default versions of notebook >= 6.x and tornado >= 6.0</p>
<p>By running the command,</p>
<blockquote>
<p>pip install jupyter notebook==5.7.8 tornado==4.5.0</p>
</blockquote>
<p>This issue is fixed</p> | tensorflow|jupyter-notebook|python-asyncio|tensorflow-federated|nest-asyncio | 0 |
18,950 | 62,068,860 | "None of [Float64Index([nan, nan], dtype='float64')] are in the [index]" setting col A value if col B contains string | <p>I have a dataframe (called <code>corpus</code>) with one column (<code>tweet</code>) and 2 rows:</p>
<pre><code>['check, tihs, out, this, bear, love, jumping, on, this, plant']
['i, can, t, bear, the, noise, from, that, power, plant, it, make, me, jump']
</code></pre>
<p>I have a list (called <code>vocab</code>) o... | <p>Your <code>corpus['tweet']</code> is list type, each is a skeleton. So <code>.str.contains</code> would returns <code>NaN</code>. You may want to do:</p>
<pre><code># turn tweets into strings
corpus["tweet"] = [x[0] for x in corpus['tweet']]
# one-hot-encode
for word in vocab:
corpus[word] = 0
corpus.loc[c... | python|pandas|nlp|text-mining | 1 |
18,951 | 62,069,567 | pandas data frame KeyError oop | <p>The purpose of this script is to read a csv file.</p>
<p>The file contains forex data.</p>
<p>The file has 7 columns Date, Time, Open, High, Low, Close and Volume, and around 600k rows.</p>
<p>After scraping the date and time the script must will make some date time calculation like month and day.</p>
<p>Then so... | <p>In the <code>__init__</code> function you are initializing empty DataFrame without any columns. But 1 line after, you are trying to convert <code>Open</code> column of the DataFrame to float.</p>
<pre><code>def __init__(self):
self.df = pd.DataFrame() # No columns
self.names = ['Date', 'Time', 'Open', 'High... | python|pandas|oop|ta-lib | 2 |
18,952 | 51,368,284 | can't use read_csv with fields having comma between \" | <p>I have the following table:</p>
<pre><code>\"Column,One\",Column Two, Column Three
</code></pre>
<p>I'm attempting to read it using Pandas <code>read_csv</code></p>
<pre><code>dataset = pd.read_csv(fin, header=None, quotechar='"', escapechar='\\', quoting=0)
</code></pre>
<p>My desired way to store the table is:... | <pre><code>df['0'] = df[['0', '1']].apply(lambda x: ''.join(x).translate(str.maketrans('','','"')), axis=1)
</code></pre>
<p>The only way out is to remove '"' after reading the data frame and followed by combining column 0 and column 1.</p> | python|python-3.x|pandas|csv | 0 |
18,953 | 48,212,694 | In what order are weights saved in a LSTM kernel in Tensorflow | <p>I looked into the saved weights for a <code>LSTMCell</code> in Tensorflow.
It has one big kernel and bias weights. </p>
<p>The dimensions of the kernel are </p>
<pre><code>(input_size + hidden_size)*(hidden_size*4)
</code></pre>
<p>Now from what I understand this is encapsulating 4 input to hidden layer affine ... | <p>The weights are combined as mentioned in the other answer, but the order is:
where <code>c</code> is the context and <code>h</code> is the history.</p>
<pre><code>input_c, input_h
new_input_c, new_input_h
forget_c, forget_h
output_c, output_h
</code></pre>
<p>The relevant code is <a href="https://gi... | python|tensorflow|lstm|recurrent-neural-network | 3 |
18,954 | 48,176,514 | Use original file name to save image | <p>I want to save image with original file name for example if original file name is <code>hero</code> so the processed image name should be <code>hero_Zero.png</code>.<br>
I dont know how to pass file name in <code>def run(dirs, img):</code><br>
Below code is correct and modified. </p>
<pre><code>def run(dirs, i... | <p>Add an extra argument to your function definition. Instead of just taking the directory and image, also pass the filename. The result will look like this:</p>
<pre><code>def run(dirs, img, f_name):
for (x, y) in labels:
component = uf.find(labels[(x, y)])
labels[(x, y)] = component
if l... | python|numpy|python-imaging-library|os.walk | 0 |
18,955 | 48,090,128 | Fill nulls until certain column value in Pandas | <p>I have the following time series dataframe. I would like to fill the missing values with the previous value. However i would only want to fill the missing values until a certain value is reached. This value is recorded in a different column. So the columns i wanna fill will be different for each row. How can i do th... | <p>Use <code>ffill</code> + <code>where</code> - </p>
<pre><code>m = df.columns[:-1].values <= df.fill_until.values[:, None]
df.iloc[:, :-1].ffill(axis=1).where(m)
2007 2008 2009 2010 2011
0 1.0 2.0 2.0 NaN NaN
1 1.0 3.0 3.0 3.0 NaN
2 4.0 4.0 7.0 7.0 7.0
</code></pre>
<hr>
<p... | python|pandas | 6 |
18,956 | 48,166,508 | Wheel depends on build-time numpy version | <p>I'm trying to build a python extension which uses the numpy C-API to manipulate numpy arrays. While setting up a deployment chain, I encountered a problem.</p>
<p>In my <code>requirements.txt</code> and <code>setup.py</code> I have added the dependency <code>numpy>=1.7</code>, because I'm using API features whic... | <p>I've solved this issue to my satisfaction by adding a minimal 'pyproject.toml' with an exact pinned numpy version. This makes pip install in the the PEP 517 compliant build isolation mode where ONLY the dependencies listed in this file are installed.</p>
<pre><code>[build-system]
requires = ['numpy==1.12.2', 'setup... | numpy|pip|python-wheel|python-manylinux | 2 |
18,957 | 48,288,839 | tensorflow cannot import name container_types | <p>I've just compiled tensorflow from source code with GPU support on OSX.
This was with a few hick-ups and hacks along the way:</p>
<ul>
<li>based on <a href="https://github.com/tensorflow/tensorflow/issues/14898" rel="nofollow noreferrer">this issue</a> I've checkout commit 49dcb6c769d60206eb845eb249fa3ef6bc333457 f... | <p>Eventually solved the issue by pulling the latest version from the repo (currently 1.6.0-rc0) and using a few super helpful github comments on Eigen and Protobuf errors.</p>
<p>More details in <a href="https://stackoverflow.com/questions/48833314/how-to-fix-tensorflow-protobuf-compilation-errors-on-osx">this answer... | python|macos|tensorflow|build | 0 |
18,958 | 48,141,933 | How to access csv file in the root folder of the Google Colaboratory? | <p>I am trying to access a CSV file uploaded right in the same folder that my python notebook is from the colaboratory.</p>
<p>when I simply do :</p>
<pre><code>pd.read_csv("train.csv")
</code></pre>
<p>It throws me : "File b'train.csv' does not exist" error.</p>
<p>Any idea is highly appreciated.</p> | <p>When you upload the file. It's not saved in the current folder.</p>
<pre><code>uploaded = files.upload()
</code></pre>
<p>It's stored as the value in the <code>uploaded</code> dictionary, with the filename as key.</p> | python|pandas|google-colaboratory | 0 |
18,959 | 48,494,853 | google colaboratory `ResourceExhaustedError` with GPU | <p>I'm trying to fine-tune a <code>Vgg16</code> model using <code>colaboratory</code> but I ran into this error when training with the GPU.</p>
<p><code>OOM when allocating tensor of shape [7,7,512,4096]</code></p>
<pre><code>INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors... | <p>Seeing a small amount of free GPU memory almost always indicates that you've created a TensorFlow session without the <code>allow_growth = True</code> option. See:
<a href="https://www.tensorflow.org/guide/using_gpu#allowing_gpu_memory_growth" rel="nofollow noreferrer">https://www.tensorflow.org/guide/using_gpu#allo... | tensorflow|google-colaboratory | 4 |
18,960 | 48,715,888 | Reading csv file with delimiter | using pandas | <pre><code>def main():
l=[]
for i in range(1981,2018):
df = pd.read_csv("ftp://ftp.cpc.ncep.noaa.gov/htdocs/degree_days/weighted/daily_data/"+ str(i)+"/Population.Heating.txt")
print(df[12:])
</code></pre>
<p>I am trying to download and read the "CONUS" row in Population.Heating.txt from 1981 t... | <p>Try this:</p>
<pre><code>def main():
l=[]
url = "ftp://ftp.cpc.ncep.noaa.gov/htdocs/degree_days/weighted/daily_data/{}/Population.Heating.txt"
for i in range(1981,2018):
df = pd.read_csv(url.format(i), sep='\|', skiprows=3, engine='python')
print(df[12:])
</code></pre>
<p>Demo:</p>
<pr... | python|pandas|csv | 2 |
18,961 | 48,727,939 | converting a list to numpy array resulting much larger memory than expected | <p>I have a list with 2940 elements - each element is a (60, 2094) numpy array. </p>
<pre><code>print('DataX:')
print('len:')
print(len(dataX))
print('shape:')
for i in range(5):
print(dataX[i].shape)
print('dtype:')
print(dataX[0].dtype)
print('size',sys.getsizeof(dataX)/1000000)
</code></pre>
<p>results in :</... | <p>From the <a href="https://docs.python.org/3/library/sys.html#sys.getsizeof" rel="nofollow noreferrer">sys.getsizeof docs</a>:</p>
<blockquote>
<p>Only the memory consumption directly attributed to the object is
accounted for, not the memory consumption of objects it refers to.</p>
</blockquote>
<p><code>sys.ge... | python|arrays|numpy | 1 |
18,962 | 70,925,117 | Transfer OpenGL image on GPU from C++ to Python for deep learning | <p>I built a simulator in C++ with a pybind11 interface to run deep learning in Python using PyTorch. At each time step, I draw certain things from the simulator's scene using the SFML library (wrapper around openGL). I draw that on a texture, then get the pixels from that texture as follows:</p>
<pre class="lang-cpp p... | <p>You should use PBO(Pixel Buffer Object) for this operation.</p>
<p>Data transferring operation is very fast using PBO</p>
<p><a href="https://www.khronos.org/opengl/wiki/Pixel_Buffer_Object" rel="nofollow noreferrer">https://www.khronos.org/opengl/wiki/Pixel_Buffer_Object</a></p>
<pre><code>GLuint w_pbo[2];
// Cre... | c++|opengl|pytorch|gpu | 3 |
18,963 | 70,964,440 | Equivalent of np.repeat() for uneven repetition without loops | <p>Given a matrix <code>m</code> and a pair of "counts" <code>count_x</code> and <code>count_y</code> I would like a new larger matrix that has every value in <code>m</code> repeated a different number of times. So, for example, the <code>m[i,j]</code> block in the new array would have size <code>(count_y[i],... | <p>Repeat lets you specify different numbers of repeats:</p>
<pre><code>In [100]: count_x = [1,2,1]
...: count_y = [1,1,3]
...:
...: arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
In [101]: arr.repeat(count_y, axis=0)
Out[101]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[7, 8, 9],
[... | python|arrays|numpy | 2 |
18,964 | 70,891,312 | pandas merge columns and adding the original column | <p>I have a Dataframe with value predictions.</p>
<p>The first column is for the exact value and each new column is a week in the future. For each week a new row is added.
As a result, I have the following example table:</p>
<pre><code>Index W1 W2 W3 W4
1. 5 7 4 9
2. 8 7 10 11
</code></pre>
<p>and ... | <p>First <code>rename</code> columns names with cast to integers and remove <code>W</code> and then reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> with some data cleaning by <a href="http://pandas.pyda... | python|pandas|dataframe | 1 |
18,965 | 42,067,771 | pandas select row without knowing number of columns | <p>I have an imported dataframe of which i do not know the number of columns or name of the columns (as this varies)</p>
<p>in this case it is I have a dataframe with 3 columns:</p>
<pre><code>a = {'Attempts': [10, 15, 5, 25, 30], '2nd Attempts': [10, 12, 15, 14, 0],
'3rd Attempts': [10, 10, 9, 11, 10]}
a = pd.DataF... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <code>mask</code> created by compare all values in <code>DataFrame</code> with <code>10</code> and then add <a href="http://pandas.pydata.org/pandas-docs/s... | python|pandas | 1 |
18,966 | 41,742,341 | Tensorflow crashes on sess.run() with no logs in python console | <p>I tried to implement style transfer using vgg-19 model. I loaded weights through existing keras model of vgg-19 using tensorflow as backend. First I tried it on my notebook and it ran fine though very slow on tf 0.11.0. Then I switched to my AWS instance with gpus, which has version 0.12.1, and tried the very same s... | <p>Got it fixed. The cudnn version mismatched the tensorflow version - it gave the error output only to python console, not to the jupyter notebook</p> | tensorflow | 0 |
18,967 | 64,441,894 | wrangling data from many columns to yes/no values in Pandas | <p>I have seen other posts on stackoverflow, which unfortunately don't solve my issue.</p>
<p>I have the below dataset, which I am trying to encode:</p>
<p>In the end, I just want 7 columns (bread, wine, eggs, meat, cheese....), with a 1 or 0 in it, depending on whether that item was purchased.</p>
<p>I have tried pd.g... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html" rel="nofollow noreferrer"><code>get_dummies</code></a> with <code>max</code> if need always <code>0,1</code> values in output:</p>
<pre><code>df1 = pd.get_dummies(df, prefix='', prefix_sep='').max(axis=1, level=0)
print (... | python|python-3.x|pandas | 1 |
18,968 | 47,567,655 | How BatchNormalization in keras works? | <p>I want to know how BatchNormalization works in keras, so I write the code:</p>
<pre><code>X_input = keras.Input((2,))
X = keras.layers.BatchNormalization(axis=1)(X_input)
model1 = keras.Model(inputs=X_input, outputs=X)
</code></pre>
<p>the input is a batch of two dimenstions vector, and normalizing it along axis=1... | <p><a href="https://www.tensorflow.org/api_docs/python/tf/nn/batch_normalization" rel="nofollow noreferrer">BatchNormalization</a> will substract the mean, divide by the variance, apply a factor gamma and an offset beta. <strong>If</strong> these parameters would actually be the mean and variance of your batch, the res... | tensorflow|keras|normalization | 2 |
18,969 | 47,917,888 | How to extend the pandas' Dataframe class with my own methods and functions | <p><strong>First question:</strong></p>
<p>I am working with pandas' DataFrames and I am frequently running the same routines as part of data pre-processing and other things. I'd like to write some of these routines as methods in a class called <code>ExtendedDataframe</code> that extends <code>pandas.DataFrame</code>.... | <p>This doesn't directly answer your question but it is a potential answer to your problem. Lot's of people use the pipe method in their workflows. </p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pipe.html" rel="noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated... | python|pandas|class|inheritance|dataframe | 8 |
18,970 | 49,155,113 | Load and Check Total Loss / Validation accuracy of Keras Sequential Model | <p>I didn't find any answers to the following question:</p>
<p>Is there a way to print the trained model accuracy, total model loss and model evaluation accuracy after loading the saved trained Keras model?</p>
<pre><code>from keras.models import load_model
m = load_model.load("lstm_model_01.hd5")
</code></pre>
<p>... | <p>Model is really a graph with weights and that's all that gets saved. You have to evaluate the restored model on data to get predictions and from that you'll obtain an accuracy.</p> | python|python-3.x|tensorflow|keras | 2 |
18,971 | 48,967,979 | Combining many 3D numpy arrays into one, from shape from (3, 2, 1) to (3, 2, 4) | <p>I know that this has probably been asked before, but in all of the questions i am looking, they are talking about a different type of reshaping. </p>
<p>Let's say that we have the following numpy arrays:</p>
<pre><code>data1 = np.array([[[12], [13]], [[14], [15]], [[16], [17]]])
data2 = np.array([[[22], [23]], [[2... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html#numpy.concatenate" rel="nofollow noreferrer"><code>np.concatenate()</code></a>:</p>
<pre><code>np.concatenate((data1, data2, data3, data4), axis=2)
</code></pre> | python|numpy | 4 |
18,972 | 48,948,616 | How to assign panda group data to a multi-index Dataframe? | <h1>Aim</h1>
<p>I have an initial data frame that looks like this:</p>
<pre><code> Serial No. Data One Data Two
0 01 0.258625 0.667996
1 01 0.192356 0.723055
2 01 0.738066 0.266488
3 01 0.374525 0.059664
4 01 0.193977 0.104213
5 01 0.213749 0.36660... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> for new indices created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>... | python|pandas|pandas-groupby | 1 |
18,973 | 48,892,348 | Add a vector as a new column in a csv file in python | <p>I have a for loop in python and at the end of each step I want the output to be added as a new column in a csv file. The output I have is a 40x1 array. So if the for loop consists of 100 steps, I want to have a csv file with 100 columns and 40 rows at the end. What I have now, at the end of each time step is the fol... | <p>Just because it is not stated clearly in your OP, I would break my answer in two cases:</p>
<p><strong>1. <code>myvector</code> is a list of lists</strong>:</p>
<p>Taken from here: <a href="https://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python">Rotating a two-dimensional array in P... | python|pandas|csv | 0 |
18,974 | 58,845,010 | Structured data gets flattened, how to get back structure by index? | <p>I have an array that has hierarchical structure. It gets flattened. I would like to retrieve a similar structure back. Maybe as a dictionary. </p>
<p>An example:</p>
<pre><code>flat_array = np.linspace(0,99,100)
_ = np.arange(0,10)
idx = np.repeat(_,10)
</code></pre>
<p>such that:</p>
<pre><code>dict = { 0:[1,2... | <p>In case this helps anyone this is the solution I came up with. </p>
<pre><code>a = {}
for i,key in enumerate(idx):
if key not in a:
a[key] = []
a[key].append(array[p])
</code></pre>
<pre><code>a
{0: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
1: [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.... | python|numpy|dictionary|for-loop | 0 |
18,975 | 58,883,638 | Creating different dataframe and outputting it to different csv based on list of indexes | <p>I have a list of indexes like below based on N value. Here is the code I used to create the list of indexes</p>
<pre><code>df = pd.DataFrame(np.arange(100).reshape((-1, 5)))
N = 4
ix = [[i, i+N] for i in range(0,len(df),N)]
ix
# [[0, 4], [4, 8], [8, 12], [12, 16], [16, 20]]
</code></pre>
<p>I want to create functi... | <p>You can use <code>iloc</code></p>
<pre><code>def write(df, ix):
c = 1
for i in ix:
try:
df_i = df.iloc[i[0]:i[1]] # use iloc
df_i.to_csv(f"df_{str(c)}.csv", index=False) # f-strings to name file
c+=1 # update your counter
except:
pass
df = pd.... | python-3.x|pandas | 0 |
18,976 | 58,655,654 | How to replace n numbers of top and bottom values with specific panda column value | <p>I have a data frame like this,</p>
<pre><code>col1 col2
1 N
2 N
3 N
4 Y
5 N
6 N
7 Y
8 N
9 N
10 N
</code></pre>
<p>I want to create another data frame from above data frame with this condition, if Y is found in col2, replace N with Y with top a... | <p>One idea is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.interpolate.html" rel="nofollow noreferrer"><code>Series.interpolate</code></a> with <code>limit</code> and <code>limit_direction='both'</code> parameters, but working only with numeric, so added <code>map</code> and the... | python|pandas|dataframe | 1 |
18,977 | 58,881,227 | How to manage multiple conditions in Pandas | <p>Let's assume a very simple example:</p>
<pre><code>import pandas as pd
import numpy as np
d = {'Col1': ['Yellow', 'Yellow', 'Cyan'], 'Col2': ['Cyan', 'Magenta', 'Magenta'], 'ColFin': ['', '', '']}
df = pd.DataFrame(data = d)
df['ColFin'] = np.where(((df['Col1'] == 'Yellow') & (df['Col2'] == 'Cyan')), 'Green', ... | <p>You can use 'and' instead of '&' to compare multiple conditions.</p>
<p>So it could be changed as:</p>
<pre><code>import pandas as pd
import numpy as np
d = {'Col1': ['Yellow', 'Yellow', 'Cyan'], 'Col2': ['Cyan', 'Magenta', 'Magenta'], 'ColFin': ['', '', '']}
df = pd.DataFrame(data = d)
df['ColFin'] = np.wher... | python|pandas | 0 |
18,978 | 70,314,973 | Replace duplicates in a group with the majority vote in Pandas | <p>I have this Pandas dataframe</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>image</th>
<th>user</th>
<th>answer</th>
</tr>
</thead>
<tbody>
<tr>
<td>img_01</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>img_01</td>
<td>2</td>
<td>0</td>
</tr>
<tr>
<td>img_01</td>
<td>2</td>
<td>1</td>
</tr>
... | <p>Feels like you may be over complicating it.
I'd just summarise, then take the top one.</p>
<pre><code>df.value_counts().reset_index().drop_duplicates(subset=['sample', 'user']).drop(columns = 0)
</code></pre>
<p>Let me know if that makes sense.</p> | python|pandas|dataframe | 1 |
18,979 | 70,050,745 | Count values using groupby function and using apply function at the same time | <p>I'm trying to count the occurance of grouped values and write values in a column using apply and grouby function on a dataframe. I have the following data frame:</p>
<pre><code>df = pd.DataFrame({'colA': ['name1', 'name2', 'name2', 'name4', 'name2', 'name5', 'name5'], 'colB': ['red', 'yellow', 'yellow', 'black', 'ye... | <p>You can join first to second as new column and use <code>colA</code> to assign values in correct places.</p>
<pre><code>df_new = df_2.join(df_1, on='colA')
</code></pre>
<p>It needed also <code>df_1.rename(columns={'colB': 'Count grouped A'})</code></p>
<hr />
<pre><code>import pandas as pd
df = pd.DataFrame({'colA... | python|dataframe|pandas-groupby|pandas-apply | 1 |
18,980 | 70,178,114 | Creating Data Frame with repeating values that repeat | <p>I'm trying to create a dataframe in Pandas that has two variables ("date" and "time_of_day" where "date" is 120 observations long with 30 days (each day has four observations: 1,1,1,1; 2,2,2,2; etc.) and then the second variable "time_of_day) repeats 30 times with values of 1,2,3,4... | <p>you need once <code>np.repeat</code> and once <code>np.tile</code></p>
<pre><code>df = pd.DataFrame({'date': np.repeat(range(1,31),4),
'time_of_day': np.tile([1, 2, 3, 4],30)})
print(df.head(10))
date time_of_day
0 1 1
1 1 2
2 1 3
3 1 ... | python|pandas | 5 |
18,981 | 56,056,097 | Read csv file and split in columns keeping column names. Pandas | <p>When i import csv file with ";" separator and then split columns, they appear without original names but indexed.</p>
<p>How to keep names when splitting columns?
I do it with the following code: (the test file can be found <a href="https://github.com/veronique-ka/tests/blob/master/test.csv" rel="nofollow noreferr... | <p>Use <code>split</code> for original columns:</p>
<pre><code>data= pd.read_csv('path')
df = data.iloc[:,0].str.split(';', expand=True)
df.columns = data.columns[0].split('; ')
print (df)
code units price
0 4017 142 20
1 808 76 15
2 316 39 7
3 209 27 45
4 344 14 32
</code></p... | python|pandas | 3 |
18,982 | 56,430,182 | How can I convert rows to columns (with custom names) after grouping? | <p>I'm trying to get some row data as columns with pandas.</p>
<p>My original dataframe is something like the following (with a lot more columns). Most data repeats for the same employee but some info changes, like salary in this example. Employees have different number of entries (in this case employee 1 has two entr... | <p>One way is using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pd.pivot_table</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ffill.html" rel="nofollow noreferrer"><code>ffill</code></a... | python|pandas | 3 |
18,983 | 56,240,887 | How to do a Z-projection (like in ImageJ) using numpy arrays? | <p>I'm currently processing Z-stack images of some cells I took. I want to project these images similar to the <code>ZProjection</code> function in ImageJ.</p>
<p>After importing them (see below), I have a 3d stack of images. I continue with perforing a numpy function on the 3rd / Z-dimension as follows:</p>
<pre cla... | <p>I answered it using the following, pretty cool commands:</p>
<pre class="lang-py prettyprint-override"><code>import fijibin.macro
in_folder = '/Infolder'
out_name = '/Outname'
macro = """run("Image Sequence...", "open=[{}] file=c1 sort use");
run("Z Project...", "projection=[Standard Deviation]");
saveAs("Tiff", ... | python|numpy|image-processing|data-science|imagej | 0 |
18,984 | 56,080,001 | How to use the fit method with an array of messages | <p>I'm trying to train and test multinomial bayes on a dataset, split accordingly. After processing the data I have an array of messages and an array of labels. I'm trying to use .fit() and .predict() with this data but it isn't working.</p>
<p>My data looks like:</p>
<pre><code>emails = ['example mail', 'another exa... | <p>You need to do some more processing on your data before training your model.
The model won't work directly on pure strings.
You can use any nlp libraries (I recommend <a href="https://spacy.io/" rel="nofollow noreferrer">Spacy</a>, or nltk stanford) to process you data (ex: tokenize, lemmatization and getting the ge... | python|scikit-learn|bayesian|sklearn-pandas|multinomial | 0 |
18,985 | 56,437,440 | Need assistance calculating unique values from multiple pandas columns | <p>I have a pd dataframe with two fields: DBA Name (facility name) & License#. There are multiple listings of the DBA name and some have the same license while others do not. </p>
<p>I want to find out how many instances of all the DBA names there are. Also I want to find out how many unique License #s they each h... | <p>Use <code>pd.DataFrame.groupby</code> with <code>nunique</code> and <code>agg</code>:</p>
<pre><code>import pandas as pd
df.groupby('DBA Name').agg({'DBA Name': 'count', 'License #': 'nunique'})
</code></pre>
<p>Output:</p>
<pre><code> DBA Name License #
DBA Name ... | python|pandas | 2 |
18,986 | 56,360,079 | Tensorflow.js: Error when checking target ... expected layer to have n dimensions | <p>I'm just starting out with Tensorflow.js, and am trying to build a simple model that takes as input 28 by 28 arrays (each representing a picture). Something isn't connecting quite right though. Running the snippet below, I get:</p>
<pre><code>errors.ts:48 Uncaught (in promise) Error: Error when checking target: exp... | <p>My input had shape (batch, 28, 28), while the model output had shape (batch, 100). However, I asked my model to predict <code>trainX</code> given inputs <code>trainX</code> (the second and first arguments to <code>model.fit</code>, respectively).</p>
<p>To fix this I just needed to update the shape of the values to... | javascript|tensorflow|keras|tensorflow.js | 0 |
18,987 | 55,944,393 | Getting values of specific indices inside tensor? | <p>I am following a tensorflow.js Udemy course and the teacher used a function <code>get</code> on a tensor object and passed in row and column indices to return the value at that position. I am unable to find this method in documentation and it also doesn't work inside nodejs, the function get() seems to not exist.</p... | <p><code>get</code> is deprecated since <strong>v0.15.0</strong> and removed from <strong>v1.0.0</strong>. Therefore the only way of retrieving a value at a specific index is to use either </p>
<ul>
<li><p><code>tf.slice</code> which will return a tensor of the value at the specific index or </p></li>
<li><p>if you wa... | javascript|tensorflow.js | 1 |
18,988 | 64,729,140 | Calculating Percent of Total using groupby | <p>I am having trouble trying to find a simple way to get the market share of products out of the total market. As an example, my dataframe is like the below:</p>
<p>For example, I have a dataframe like this below. Let's say product A, B and C belong to a market called 1, and D, E, F belong to markets 2, 3, 4 respectiv... | <p>You're on the right track to consider <code>groupby</code>!</p>
<p>Your dataframe needs to have the dimensions you mentioned, though -- the market, and the quarter. In addition, you probably want your Date column to be a <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html" rel="nofollow ... | python|pandas|numpy|dataframe|group-by | 1 |
18,989 | 65,027,847 | How to randomly mix two PyTorch tensors | <p>I have two same-shaped PyTorch tensors A and B, and I'd like to create a same-shape "randomly mixed" tensor C where C[i,...] = A[i,...] with probability alpha or B[i,...] with probability 1-alpha. Is there some Pythonic way to do this compactly?</p> | <p>consider using <code>torch.bernoulli</code> to create a mask tensor:</p>
<pre class="lang-py prettyprint-override"><code>import torch
prob = 0.8
x = torch.full((2, 6, 3), 10.2, dtype=torch.float)
y = torch.full((2, 6, 3), -1.6, dtype=torch.float)
mask = torch.bernoulli(torch.full(x.shape, prob)).int()
reverse_mask... | list|pytorch|tensor | 5 |
18,990 | 64,687,665 | How to reduce dimension of a tensor with keeping specific indexed elements of that dimension? | <p>The reduce of dimension is similar to what reduce_max() does, the difference is I want a specific index of the element in that dimension instead of simply picking the maximal one. For example, I have a 2x3 tensor A = [[0,1,2],[2,2,0]]. If I apply tf.argmax(A), I get index tensor [1, 1, 0]. How can I use this index t... | <p>You can use <code>tf.gather_nd</code> function to do that but you will need to convert that <code>[1, 1, 0]</code> index tensor into 2D tensor.</p>
<p>Here I assume that the index tensor is a numpy array (you can convert tensorflow tensor into numpy array by calling <code>.numpy()</code> method.</p>
<pre><code>idx =... | python|tensorflow|tensorflow2.0|tensor | 2 |
18,991 | 64,691,673 | How to get "dot addition" in numpy similar to dot product? | <p>I'm somewhat new to numpy and am strugging with this problem. I have two 2-dimensional numpy arrays:</p>
<pre><code>array1 = [a1, a2, ..., an]
array2 = [b1, b2, ..., am]
</code></pre>
<p><code>a1</code>, <code>a2</code>, <code>b1</code>, and <code>b2</code> are all 1-d arrays with exactly 100 floats in them. However... | <p>use <code>np.outer</code> ufunc which is for this purpose:</p>
<pre><code>np.add.outer(array1,array2)
</code></pre>
<p>example:</p>
<pre><code>array1 = np.array([1,2,3])
array2 = np.array([1,2])
</code></pre>
<p>output:</p>
<pre><code>[[2 3]
[3 4]
[4 5]]
</code></pre> | python|arrays|python-3.x|numpy|numpy-ufunc | 6 |
18,992 | 40,076,280 | How is numpy pad implemented (for constant value) | <p>I'm trying to implement the numpy pad function in theano for the constant mode. How is it implemented in numpy? Assume that pad values are just 0.</p>
<p>Given an array </p>
<pre><code>a = np.array([[1,2,3,4],[5,6,7,8]])
# pad values are just 0 as indicated by constant_values=0
np.pad(a, pad_width=[(1,2),(3,4)], m... | <p>My instinct is to do:</p>
<pre><code>def ...(arg, pad):
out_shape = <arg.shape + padding> # math on tuples/lists
idx = [slice(x1, x2) for ...] # again math on shape and padding
res = np.zeros(out_shape, dtype=arg.dtype)
res[idx] = arg # may need tuple(idx)
return res
</code></pre>
... | python|arrays|numpy|pad | 2 |
18,993 | 69,381,892 | How to mask a loss function (mae) in Keras? | <p>I am trying to implement a custom loss function for Keras LSTM, which would represent mask_MAE.</p>
<pre><code>def mask_MAE (y_true, y_pred, mask):# mask = 0 or 1
mae = K.abs(y_pred - y_true) * mask
return K.sum(mae)/K.sum(mask)
</code></pre> | <p>I found an answer to my question.
I am working with LSTM and 80 is num_steps</p>
<pre><code>def GBVPP_loss(y_true, y_pred, cols = 80):
u_out = y_true[:, cols: ]
y = y_true[:, :cols ]
w = 1 - u_out
mae = w * tf.abs(y - y_pred)
return tf.reduce_sum(mae, axis=-1) / tf.reduce_sum(w, axis=-1)
...
history =... | python-3.x|tensorflow|keras|tensor|loss-function | 1 |
18,994 | 69,663,556 | How to mark first entry per group satisfying some criterion? | <p>Let's say I have some dataframe where one column has some values occuring multiple times forming groups (column <code>A</code> in the snippet). Now I'd like to create a new column that with e.g. a <code>1</code> for the first <code>x</code> (column <code>C</code>) entries per group, and <code>0</code> in the other o... | <p>In your case do slice then <code>drop_duplicates</code> and assign back</p>
<pre><code>df['D'] = df.loc[df.C=='x'].drop_duplicates('A').assign(D=1)['D']
df['D'].fillna(0,inplace=True)
df
Out[149]:
A B C D
0 0 a y 0.0
1 0 b x 1.0
2 1 c y 0.0
3 2 d x 1.0
4 2 e y 0.0
5 2 f x 0.0
</code>... | python|pandas|dataframe|pandas-groupby | 1 |
18,995 | 69,386,176 | Make column rows the same value with matching value of another column when condition is met | <p>I have a dataframe like below</p>
<pre><code>df = pd.DataFrame({'col1': ['A', 'A', 'B', 'C', 'D', 'D'],
'col2': [1,0,1,0,0,1]})
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>1</td>
</tr>
<tr... | <p>You can chunk it in two steps:</p>
<p>Get the rows where col2 is 1:</p>
<pre class="lang-py prettyprint-override"><code>filters = df.loc[df.col2.eq(1), 'col1']
</code></pre>
<p>Assign the new values to rows, where col1 is in <code>filters</code>:</p>
<pre class="lang-py prettyprint-override"><code>df.loc[df.col1.isi... | python|pandas|dataframe|replace|matching | 3 |
18,996 | 53,838,150 | Resizing and storing dataset in .h5 format using h5py in python | <p>I am trying to resize dataset and store new values using <code>h5py</code> package in python. My dataset size keeps increasing at every time instance, and I would like to append the <code>.h5</code> file using the <code>resize</code> function. However, I run into errors using my approach. The variable <code>dset</co... | <h1>The problem</h1>
<p>Not sure about the rest of your code, but you can't use the context manager pattern (ie <code>with h5py.File(foo) as bar:</code>) within a function that returns a dataset. As you point out in the comment under your question, this means that by the time you try to access the dataset the actual H... | python|arrays|numpy|h5py | 3 |
18,997 | 66,304,295 | How to find the total amount of a column x sorted by another column y? | <p>I have a dataframe with a list of songs, they contain data such as name, artist, year, streams etc. I'm trying to find the 'year' in which songs got the most 'votes' i.o.w. the year with the highest number of total votes.</p>
<p>I'm pretty new to dataframes, and I know how to find things such as the total votes and ... | <p>Does this help?</p>
<pre><code>>>> df = pd.DataFrame({"year": [1, 1, 2, 3, 3], "votes": [2, 4, 1, 5, 2]})
>>> df
year votes
0 1 2
1 1 4
2 2 1
3 3 5
4 3 2
>>> df.groupby("year")["votes"].sum()
year
1 ... | python|pandas|dataframe | 0 |
18,998 | 65,950,687 | Problem Converting Index To TimeSeries Index Pandas | <p>I have a problem converting index to time series index pandas i have dataframe:</p>
<pre><code>df['Book Value Per Share *\xa0IDR']
</code></pre>
<p>Output :</p>
<pre><code> 2010-12 NaN
2011-12 326.22
2012-12 484.66
2013-12 596.52
2014-12 740.09
2015-12 878.66
201... | <p>You can convert <code>index</code> to <code>Series</code>, shifting and compare index by <code>TTM</code>, filter and add one year, last convert back to <code>YYYY-MM</code> string and pass to <code>rename</code>:</p>
<pre><code>s = df.index.to_series().shift()
s1 = pd.to_datetime(s[s.index == 'TTM'], format='%Y-%m... | python|pandas|dataframe|datetime|google-colaboratory | 0 |
18,999 | 66,020,046 | Calculating Hessian with tensorflow gradient tape | <p>Thank you for your interest in this issue.</p>
<p>I want to calculate hessian matrix of tensorflow.keras.Model</p>
<p>for high order derivates, i tried nested GradientTape.# example graph, and inputs</p>
<pre><code>xs = tf.constant(tf.random.normal([100,24]))
ex_model = Sequential()
ex_model.add(Input(shape=(24)))
... | <p>You already calculate the <code>ys</code> second order of gradients wrt <code>xs</code> which is zero, as it should be when you calculate gradients wrt constant, and that is why <code>tape1.jacobian(g, xs)</code> return <code>None</code></p>
<p>When second order of gradients <strong>not</strong> wrt constant:</p>
<p... | tensorflow|autodiff | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.