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 |
|---|---|---|---|---|---|---|
353,300 | 71,400,036 | Pandas - Subtract one column from other columns in same dataframe for multiple files with varying column names and number of columns | <p>I want to subtract the 3rd from the right column from all other columns except for itself and the last column, then create new columns with these values with the header including the original column's header. The column names and the number of columns between each file vary, but the names of the 2 most right columns... | <p>We could subtract that particular column from the other columns horizontally using <code>sub</code> on <code>axis=0</code>; then <code>join</code> it back to <code>df</code>:</p>
<pre><code>out = (df.join(df.drop(df.columns[[-3,-1]], axis=1)
.sub(df[df.columns[-3]], axis=0)
.add_suffix(... | python|pandas|dataframe | 2 |
353,301 | 71,347,286 | DataFrame column type changes after filling blank cell with user input value in python | <p>I have a large excel file uploaded to spyder, just for an eg. I have made it simple -</p>
<pre><code> Date Name Project Age Pin_code Remarks Gender
0 2020-01-01 a proj_a 34 123456 grade_a M
1 2019-12-04 b proj_b 48 789012 ... | <p>If need not valid pandas datetime - <code>0000-00-00</code> is necessary convert dates to strings and for convert numeric to integers use <code>astype(int)</code></p>
<pre><code>ip = input('Please enter a value for blank cells : ')
for c in df.columns:
if is_string_dtype(df[c]):
df[c].fillna(ip, inplac... | python|pandas|spyder | 1 |
353,302 | 71,233,076 | Sort Tensorflow HashTable by value | <p>My Code :</p>
<pre><code>h_table = tf.lookup.StaticHashTable(
initializer=tf.lookup.KeyValueTensorInitializer(
keys=[0, 1, 2, 3, 4, 5],
values=[12.3, 11.1, 51.5, 34.3, 87.3, 57.8]
),
default_value=tf.constant(-1),
name="h_table"
)
</code></pre>
<p>I wanted to... | <p>You will have to create a new <code>tf.lookup.StaticHashTable</code>, since it is immutable once initialized:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
h_table = tf.lookup.StaticHashTable(
initializer=tf.lookup.KeyValueTensorInitializer(
keys=[0, 1, 2, 3, 4, 5],
... | python|tensorflow|tensorflow2.0|tensor | 1 |
353,303 | 71,231,821 | How do I search through a column of lists in python pandas and return the item in the list as well as the value from another column? | <p>I have made a pandas data frame where I have two main columns, one with a job name the other with a SQL script.</p>
<p>I need to extract tables ending in '_REP', I have split the script into lists of the words (note the csv doesn't have commas for the script in it originally) and need to return the EXCTRATION and th... | <p>I noticed that you want te extract the table name, which in SQL
occurs after "FROM". So my idea, for each row, is to:</p>
<ul>
<li>find "FROM" element in <em>sql_split</em>,</li>
<li>get the table name (the next element),</li>
<li>return either the table name (if it ends with "_REP") or... | python|sql|pandas|csv | 0 |
353,304 | 71,168,642 | Merge Rows in pandas dataframe having same string in a column | <p>I'm new to python.
I've 2 dataframes:</p>
<pre><code>df1:
Col1 Col2 Col3 Col4
0 A A1 A2 0
1 B B1 B2 0
2 C C1 Nan 0
df2:
Col1 Col2 Col3 Col4
1 B NaN NaN B3
4 C NaN C2 C3
</code></pre>
<p>Expected Out:</p>
... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>df.set_index</code></a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.update.html" rel="nofollow noreferrer"><code>df.update</code></a> and <a href="https://pandas.... | python|pandas|string|rows | 0 |
353,305 | 71,300,786 | TensorFlow Probability - want NN to output multiple distributions | <p>I have a simple model that currently outputs a single numerical value which I've adapted to instead output a distribution using TFP (mean + std deviation) so I can instead understand the model's confidence around the prediction.</p>
<pre><code> model = tf.keras.Sequential([
tf.keras.layers.Dense(10, input_shape... | <p>Check out this guide on shapes in TFP: <a href="https://www.tensorflow.org/probability/examples/Understanding_TensorFlow_Distributions_Shapes" rel="nofollow noreferrer">https://www.tensorflow.org/probability/examples/Understanding_TensorFlow_Distributions_Shapes</a></p>
<p>IIUC you'll want to output a distribution w... | python|tensorflow|keras|tensorflow-probability | 1 |
353,306 | 71,150,952 | Pandas Split a Column by Multiple delimiters into same column | <p>I have a pandas dataframe of multiple columns. But the Column of interest say is Col A which looks like :</p>
<pre><code> dfInput
A
12 - ksjksu,nsusi,9018,1.00uy,9.0Vm,+/ - 20%(0.22suns); 891- 1o19jsksuisolslskosBN
205 - lksiosslsoujhs%ysus(0.33mismsn);31 - jsks,msnu
22 - ... | <p>You can do that with something like the following.</p>
<p>The <code>get_nums</code> function splits on the <code>;</code>, then removes the integers based on the specified conditions</p>
<p>The <code>get_the_rest</code> function does the opposite, and substitutes those values with empty spaces</p>
<pre><code>def get... | python|regex|pandas|split | 2 |
353,307 | 71,404,750 | Remove strings that contain more 2 consecutive numbers | <p>I have a list of numbers (in hex form) and I’m trying to remove the strings that have more than two repeated numbers so, for example</p>
<ol>
<li>200005</li>
<li>200108</li>
<li>2AFAFA</li>
<li>2BBB40</li>
<li>244422</li>
</ol>
<p>The the script would remove number 5 and 1 since there are three in a row. Forgive me ... | <p><strong>You can try it with:</strong></p>
<pre class="lang-py prettyprint-override"><code>def check(strings: list):
_strings = strings
for i in strings:
val = ""
for p in i:
if i.isdigit() and val.endswith(p) and val[:-1].endswith(p): # Check all the conditions
... | python|list|numpy|hex | 0 |
353,308 | 71,348,205 | python pandas: Can you perform multiple operations in a groupby? | <p>Suppose I have the following DataFrame:</p>
<pre><code>df = pd.DataFrame(
{
'year': [2015,2015,2018,2018,2020],
'total': [100,200,50,150,400],
'tax': [10,20,5,15,40]
}
)
</code></pre>
<p>I want to sum up the total and tax columns by year and obtain the <code>size</code> at the same ti... | <p>You can specify for each column separately aggregate function in named aggregation:</p>
<pre><code>df = df.groupby('year', as_index=False).agg(total=('total','sum'),
tax=('tax','sum'),
size=('tax', 'size'))
print (df)
year to... | python|pandas|group-by | 3 |
353,309 | 71,218,681 | How to calculate standard deviation for 7 day intervals | <p>This is my dataframe, how could I calculate the <code>(standard deviation) * 7</code>for the first seven days, then the next 7 days then the 7 days after that, to get the weekly volatility from the column <code>log returns</code>. And put it into a dataframe, I tried a few functions that I wrote but they dont work.<... | <p>You could use a rolling window with a time-aware offset (7 days is represented by <code>"7D"</code>) using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html#pandas-dataframe-rolling" rel="nofollow noreferrer"><code>pandas.DataFrame.rolling</code></a>:</p>
<pre><code>>&g... | pandas|dataframe|jupyter | 0 |
353,310 | 71,391,324 | Create a new column after if-else in dask | <p><code>df[‘new_col’] = np.where(df[‘col1’] == df[‘col2’] , True, False)</code>, where col1 and col2 are both str data types, seems pretty straight forward. What is the more efficient method to create a column in dask after an if else statement? I tried the recommendation from this <a href="https://stackoverflow.com/q... | <p>IIUC use if need set column to boolean:</p>
<pre><code>df['new_col'] = df['col1'] == df['col2']
</code></pre>
<p>If need set to another values:</p>
<pre><code>df['new_col'] = 'val for true'
ddf = df.assign(col1 = df.new_col.where(cond=df['col1'] == df['col2'], other='val for false'))
</code></pre> | pandas|numpy|if-statement|dask-dataframe | 1 |
353,311 | 71,436,847 | How to set limits around (on both sides of) 0, in a polar Matplotlib plot (wedge diagram) | <p>I am making a wedge diagram (plotting quasars in space, with RA as theta and Dec as r). I need to set the limits of a polar plot on both sides of 0. My limits should go from 45 degrees to 315 degrees with 0 degrees in between those two values (45-0-315). How do I do this?</p>
<p>This is my code:</p>
<pre><code>impor... | <p>It appears that matplotlib will only make the theta limits span across theta=0 if you have a positive and negative value for <code>thetamin</code> and <code>thetamax</code>. From the docstring for <a href="https://matplotlib.org/stable/api/projections_api.html#matplotlib.projections.polar.PolarAxes.set_thetalim" rel... | python|numpy|matplotlib|astronomy | 0 |
353,312 | 71,229,899 | what does np.reshape(2, -1)? | <p>I'm making the exercise 8 of that list: <a href="https://www.machinelearningplus.com/python/101-numpy-exercises-python/" rel="nofollow noreferrer">https://www.machinelearningplus.com/python/101-numpy-exercises-python/</a></p>
<p>the exercise says that a array is given by the code <code>a = np.arange(10).reshape(2, -... | <p>The method reshape, like the name suggests, reshapes a numpy array to the given dimensions. <code>np.arange(10)</code> gives you an array of shape (1, 10). If you use the reshape function, it expects the dimensions (or a tuple containing them) for example (2, 5). However, the -1 means that it will take the right dim... | python|numpy | 1 |
353,313 | 71,179,101 | Tensorflow : convolutional autoencoder via subclassing | <p>I was playing with some Keras samples, defining models through subclassing, but I can't get it working.</p>
<pre><code>from keras import layers, Model
from keras.datasets import mnist
from keras.callbacks import TensorBoard
import numpy as np
import datetime
import os
class Encoder(Model):
def __init__(sel... | <p>In your code, there are many issues that need to be addressed. For example,</p>
<ul>
<li><strong>Issue 1</strong>: In the <code>call</code> method, the <code>inputs</code> argument should be tensor and not numpy array.</li>
<li><strong>Issue 2</strong>: In model subclassing, you should initiate the <strong>trainable... | python|tensorflow|keras | 0 |
353,314 | 71,423,965 | Invalid value error during converting string to int | <p>I have a data set and there is a feature which containing numbers in string like</p>
<pre><code>"153", "45", "13", "345"
</code></pre>
<p>I'd like to convert these values to integer with python and i wrote this line of code:</p>
<pre><code>df.column = df.column.astype("in... | <p>Problem isn't the scientific notation per se, but the fact that they are float values AND they're in scientific notation. I found that this works as a one line solution:</p>
<pre><code>df.column.astype('float64').astype('int64')
</code></pre>
<p>If your string values are in European convention, you can add the foll... | python|python-3.x|pandas|type-conversion|data-science | 1 |
353,315 | 71,278,054 | How can I alter TFRecords for my COCO format dataset? | <p>I am currently trying to get the Caltech camera traps benchmark dataset into TFRecords but I am struggling quite a bit. <a href="https://lila.science/datasets/caltech-camera-traps" rel="nofollow noreferrer">https://lila.science/datasets/caltech-camera-traps</a>. The annotations are displayed as follows:</p>
<pre><co... | <p>You can leave the iscrowd and segmentations as empty if you are doing object detection or classification or ... tasks. But You wouldn't make use of the data with missing bounding boxes for such tasks.</p> | python|tensorflow|dataset|tensorflow-datasets|tfrecord | 0 |
353,316 | 71,168,412 | Using BatchedPyEnvironment in tf_agents | <p>I am trying to create a batched environment version of an SAC agent example from the Tensorflow Agents library, the original code can be found <a href="https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/examples/v2/train_eval.py" rel="nofollow noreferrer">here</a>. I am also using a custom environ... | <p>It turns out I neglected to pass <code>batch_size</code> when initializing the <code>AverageReturnMetric</code> and <code>AverageEpisodeLengthMetric</code> instances.</p> | tensorflow|gpu|reinforcement-learning | 2 |
353,317 | 71,190,431 | animation.FuncAnimation mplfinance (candlestick and line togheter)? (python) | <p>I created a reproducible example of random data for <em>candlestick chart</em> ohlc that is working correctly.</p>
<ul>
<li>Now I need, in the same plot, to plot a random <em>line</em> (in the real application it will be a function of the ohlc data (not moving average)), so I created a random varialbe <code>y0</code... | <p>Notice that the error message is <code>KeyError: 'Open'</code>. This is because <code>mpf.plot()</code> expects the first argument to be a DataFrame with columns 'Open', 'High', 'Low', and 'Close' (or with OHLC column names that you specify using kwarg <code>columns=</code>).</p>
<p>Apparently your <code>y0_arr</co... | python|pandas|matplotlib|finance|candlestick-chart | 1 |
353,318 | 71,287,938 | Matching underlying row values with the column headers | <p>could you assist with mapping underlying row values with the header values. I have a few data-sets im scraping from the web, which include a dollar value as well as quantities. I created custom headers to represent the column names instead of using the scraped quantities.</p>
<p><strong>Context</strong>
If I had the... | <p>Take your first pair of arrays as an example,</p>
<pre><code>df1 = pd.DataFrame({'q': quantity1, 'dollar_val': dollar_val_1})
</code></pre>
<p>First we need <code>'q'</code> as integer,</p>
<pre><code>df1['q'] = df1['q'].str.replace(',', '').astype(int)
</code></pre>
<p><code>pd.cut</code> is the method for custom-b... | python-3.x|pandas|dataframe | 0 |
353,319 | 71,111,926 | Plotting in Pandas | <p>Very new to coding, so please excuse the lack of finesse. I will try to describe my problem as best as I can.</p>
<p>I have a tabular list of 'City_names' and 'Year_spending', and would like to create plots of spending versus time (Year), color coded by city_names. How would I best approach this in Pandas?</p>
<p>Th... | <p>You could start with this. This gives a bar graph of <strong>spending versus time (Year), color coded by city_names</strong>, as shown below.</p>
<p><a href="https://i.stack.imgur.com/rBGbm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rBGbm.png" alt="enter image description here" /></a></p>
<pr... | python-3.x|pandas | 0 |
353,320 | 71,168,398 | Tensorflow gives 0 results | <p>I am learning Tensorflow from this github
<a href="https://colab.research.google.com/github/instillai/TensorFlow-Course/blob/master/codes/ipython/1-basics/tensors.ipynb#scrollTo=TKX2U0Imcm7d" rel="nofollow noreferrer">https://colab.research.google.com/github/instillai/TensorFlow-Course/blob/master/codes/ipython/1-ba... | <p>It does not mean that the values of the tensors are zero. <code>Add_3:0</code> and <code>MatMul_3:0</code> are just names of the tensors and you can only use <code>print</code> in Eager Execution to see the values of the tensors. In <code>Graph</code> mode you should use <code>tf.print</code> and you should see the ... | python|tensorflow|tensor | 2 |
353,321 | 71,282,872 | How to count the amount of elements in a particular abstract n-dimensional NumPy array? | <p>I am intended to count how many integers are stored in a particular abstract n-dimensional array (I am not sure onthe proper term for this). For instance, here's the output of the numpy array named 'result':</p>
<pre><code>In [1]: print(f"{result} \n {type(result)}")
Out [1]: [list([[[[2, 5], [6, 8]]], [[[... | <p><code>result.size</code> will tell you how many elements are in a NumPy array (see <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.size.html" rel="nofollow noreferrer">numpy.ndarray.size</a>). The problem is that your array is not simply an array, but for some reason it is an array of lists ... | python|arrays|numpy|numpy-ndarray | 2 |
353,322 | 71,128,321 | Finding points in a convex hull and assigning true/false | <p>I have a pandas dataframe with 3 columns, <code>PointsA["x", "y", "z"]</code> and <code>PointsB["x", "y", "z"]</code>.</p>
<p>I can generate the convex hull <code>ConvexHull(PointsA)</code> Note I'm assuming this only uses the x and y since convex hull in a... | <p><a href="https://pypi.org/project/Shapely/" rel="nofollow noreferrer">Shapely</a> Library might be what you are looking for, you can consider the output of your ConvexHull as a polygon and check with Shapely if that polygon contains the point as in the below example.</p>
<pre><code>from shapely.geometry.polygon imp... | python|pandas|scipy|convex-hull | 1 |
353,323 | 71,401,193 | One-hot encoding in Python for array values in a DataFrame | <p>I am trying to do one-hot encoding for these clustered data frames. (grouped by length). Been trying to use sklearn's encoder but it seems to regard each individual row as one category instead of multiple.</p>
<p>Example input:</p>
<pre><code> ID trace length
3 [A, B, C, C] 4
... | <p>IIUC, and if target contains lists, you could do:</p>
<pre><code>(df.drop('trace',1)
.join(df['trace']
.apply('|'.join)
.str.get_dummies()
)
)
</code></pre>
<p>or for in place modification of <code>df</code>:</p>
<pre><code>df = (df.join(df.pop('trace')
.apply('|'.join)
... | python|pandas|dataframe|scikit-learn|encoding | 2 |
353,324 | 71,366,501 | How to reduce the number of columns after One-hot encoding | <p>I am working with a dataset that requires converting a categorical column into a numeric equivalent as the dataset requires a couple of ML techniques to be implemented. I used one-hot encoding technique to convert the categorical column (i.e. Nationalities) into numeric columns suitable for machine learning models. ... | <p>You can use <code>pd.factorize</code>.</p>
<pre><code>df['Nationalities_numeric'] = pd.factorize(df['Nationalities'])[0]
print(df)
# Output
Nationalities Nationalities_numeric
0 France 0
1 Spain 1
2 Italia 2
3 France ... | python|pandas|scikit-learn|jupyter|one-hot-encoding | 0 |
353,325 | 71,374,969 | Transfom values in dataset more quickly | <p>I need to transform values above than 100 in 0, but, in the dataset that i need make that tranform has a 2 billions of values, and, this is the problem. I speed a lot of time to do that... (i need to do that transfomation 5 times).</p>
<p>I using a loop, for, with the function ".replace".</p>
<p>So, have a... | <p>You could let pandas handle it for you by indexing a specific portion of your dataframe and setting a value for all columns or some columns:
Here is an example with a basic dataframe.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({
'a': list(range(200)),
'b': list... | python|pandas|dataframe|numpy | 0 |
353,326 | 71,191,987 | How to limit the floating point decimal while using describe function on dataframe? | <p>I get the below output on running <code>df['CodingHours'].describe()</code>.</p>
<ol>
<li>Is there a way to round this up to a few decimal places?</li>
<li>Also, why is the standard deviation not exactly 1, can someone help me understand this?</li>
</ol>
<pre><code>count 1.000000e+02
mean -2.220446e-17
std ... | <p>You may add <code>.round(3)</code> ad the end of your command.</p>
<p>Try below command:<br>
<code>df['CodingHours'].describe().round(3)</code></p> | python|pandas|dataframe|jupyter-notebook|data-science | 2 |
353,327 | 71,345,943 | Combining the Rows of All Columns into a Single Column | <p><a href="https://i.stack.imgur.com/oA8db.png" rel="nofollow noreferrer">Example Pandas DataFrame</a></p>
<p>How do you combine all the rows in all columns into a single column? I would like to append the rows in C2 and C3 to C1. That is, have one column, C1, with 15 rows, each with their respective values.</p> | <p>One way is to create a new DataFrame from the <code>reshape</code>d numpy array underlying the original DataFrame, using <code>order='F'</code> to stack columns on top of each other:</p>
<pre><code>df_new = pd.DataFrame(df.to_numpy().reshape(-1, 1, order='F'),
columns=['C1'])
</code></pre>
<p>... | python|pandas|dataframe|jupyter-notebook | 0 |
353,328 | 71,190,579 | how to remove the value counts in pandas | <p>I have a dataframe with unique numbers and their value counts in a dataframe. I would like to remove the value counts to get the mean of the numbers.</p>
<p>I have tried to convert it to a string and then slice it. <code>randompicks2 = randompicks.to_string()</code> then <code>randompicks2 = randompicks2[0:38]</code... | <p>Try this:</p>
<pre><code>l = df.columns.tolist()
print(l)
</code></pre>
<p>Output:</p>
<pre><code>[2, 16, 39, 47, 53, 10]
</code></pre> | python|pandas|dataframe|numpy | 0 |
353,329 | 71,101,769 | Numpy matrix multiplication causing windows exception | <p>This morning I updated my anaconda environment in the usual way using <code>conda update --all</code>. This seems to have broken matrix multiplication in Numpy. During the update Spyder, of which I use the iPython console to run this code, was updated from version 5.2.2.0 to version 5.2.2.2. <a href="https://i.stack... | <p>I was able to resolve the issue by reinstalling Spyder, Numpy and their dependencies. After each reinstall I ran the code in my original question to see if anything had broken yet. The list of packages that I manually reinstalled after uninstalling Spyder and Numpy were:</p>
<ol start="0">
<li>Numpy</li>
<li>Scipy</... | python|arrays|numpy|ipython|spyder | 0 |
353,330 | 71,248,276 | Exception has occurred: ValueError Exception encountered when calling layer "conv2d" (type Conv2D) | <p>I have this error when i try to build this file. Anyone knows how to fix it? Thank you a lot. Sorry for my bad english.</p>
<p><strong>Code:</strong></p>
<pre><code>import numpy as np
import pickle
import cv2, os
from glob import glob
from keras import optimizers
from keras.models import Sequential
from keras.layers... | <p>The input shape simply too small for the convolution that is applied in your model.</p>
<p>You can either decrease the Kernel size or apply padding='same' in the Conv2D layer as follows:</p>
<ul>
<li><p>Decreasing Kernel size</p>
<p><code>model.add(Conv2D(16, (1,1), input_shape=(image_x, image_y, 1), activation='re... | python|tensorflow | 0 |
353,331 | 71,416,317 | Python: How to assign elements of an array to multiple columns in DataFrame? | <p>So, I have a function like below:</p>
<pre><code>def do_something(row, args):
# doing something
return arr
</code></pre>
<p>where <code>arr = array([1, 2, 3, 4, 5])</code></p>
<p>and in my main function, I have a pandas DataFrame object <code>df</code>, it has columns <code>A, B, C, D, E</code> along with o... | <p>The error is telling you that you are trying to assign a sequence of values to a sequence of keys.
You can use the zip function to create a dictionary from the two lists.
Then you can use the dictionary to assign the values to the columns.</p> | python|pandas|dataframe | 1 |
353,332 | 71,212,281 | Aggregate group by response based on certain count (or size) Pandas | <p>I am looking to create a sum based on certain values obtained after a <code>groupby</code> count (or size). I have created a mock DataFrame and the desired output bellow. It should be self explanatory from the example what I am looking for. I checked quite a bit but it seems there is no straight answer.</p>
<pre><co... | <p>You could create dummy columns and <code>groupby</code> using those columns:</p>
<pre><code>out = (data
.assign(match=data['col1']==data['col2'], count=1)
.groupby(['col1','match'], as_index=False)
.agg({'col2': lambda x: '+'.join(x.unique()), 'count':'sum'})
.drop(columns='match'))
</cod... | python|python-3.x|pandas|dataframe|pandas-groupby | 2 |
353,333 | 71,250,377 | How to copy previous rows of a dataframe and copy them to the next one? | <p>I have this dataframe A:</p>
<pre><code>date_1 date_2 col1 col2 col1
2022-01-01 2022-01-01 product1 23 23
2022-01-01 2022-01-01 product2 25 50
2022-01-01 2022-01-01 product3 50 50
2022-01-02 2022-01-02 product1 60 23
2022-01-02 2022-01-02 pr... | <p>First, transform those date columns to a datetime format:</p>
<pre><code>>>> df["date_1"] = pd.to_datetime(df["date_1"])
>>> df["date_2"] = pd.to_datetime(df["date_2"])
</code></pre>
<p>Now, find the rows where "date_2" is <code>None</code> and find... | python-3.x|pandas | 1 |
353,334 | 71,399,352 | How to convert date into month name and day name in python? | <p>This is the orginal date that I have in my dataset 01/04/2021 in the format day/month/year.
When I use <strong>pandas time stamp</strong> to convert the date to month name and day name it switches the format to m/d/y for the days <12 and uses it as it is for dates > 12.
For eg 01/04/2021 - month- January
13/04... | <p>You can do this to achieve what I think your question is asking (or something close):</p>
<pre><code>import pandas as pd
records = [
{'Create Date/Time': '01/04/2021'},
{'Create Date/Time': '13/04/2021'}
]
df = pd.DataFrame(records)
print(df)
ser = pd.to_datetime(df['Create Date/Time'], dayfirst=True)
print(... | python|pandas|date | 0 |
353,335 | 71,186,180 | How to compute row-wise comparison of multiple columns? | <p>I got a table with lots of point informations and I need to fill the position field after row wise comparison of the four fields before.</p>
<p>If the X- & Y-Coordinate is equal and also the ID_01, a comparison of ID_02 is required to assign "End" into the Position field for the lower ID_02 value, henc... | <p>You can use a boolean mask. First sort your values by <code>ID_02</code> then check duplicated values. The position with row set to <code>True</code> has the <code>End</code> position, the other the <code>Start</code> position:</p>
<pre><code>m = df.sort_values('ID_02').duplicated(['X-Coordinate', 'Y-Coordinate', 'I... | python|pandas|dataframe|if-statement|row | 0 |
353,336 | 71,427,752 | Python: change column of strings with None to 0/1 | <p>My dataframe is</p>
<pre><code>df = pd.DataFrame({"label":['a', 'b', None, 'c', None]})
</code></pre>
<p>and I wish to change it such that all <code>None</code> are set to <code>0</code> and everything else is set to <code>1</code>.
I used <code>df.iterrows()</code> but it really feels barbaric and seems t... | <p>Try one of the following</p>
<pre><code>df.label.notna().mul(1)
</code></pre>
<pre><code>df.label.map({None: 0}).fillna(1).astype(int)
</code></pre>
<pre><code>import numpy as np
np.where(df.label.isna(), 0, 1)
</code></pre> | python|pandas | 1 |
353,337 | 71,254,088 | Pandas: Find difference in rows with same index in any column | <p><strong>Sample dataframe:</strong></p>
<pre><code>In [1898]: df = pd.DataFrame({'index':[0,0,5,5,6,6,8,8], 'table_name':['f_person', 'f_person', 'f_person', 'f_person', 'f_person', 'f_person', 'f_person', 'f_person'], 'column_name':['active', 'actv', 'ssn', 'ssn', 'pl', '
...: pl', 'prefix', 'prefix'], 'data_t... | <p>Don't set the index of <code>df</code> and then just run this:</p>
<pre><code>output = [(
df.groupby('index')
.apply(lambda data: {col: data[col].unique().tolist()
for col in data.columns
if len(data[col].unique()) > 1})
.to_dict()
)]
</code></... | python|pandas | 1 |
353,338 | 71,295,114 | JSON file loaded as one row, one column using pandas read_json; expecting a full dataframe | <p>I was provided with a JSON file which looks something like below when opened with Atom:</p>
<pre><code>["[{\"column1\":value1,\"column2\":value2,\"column3\":value3 ...
</code></pre>
<p>I tried loading it in Jupyter with pandas read_json as such:</p>
<pre><code>data = pd.read_json('... | <p>Ok so I think as <code>head()</code> only shows one entry that the outer brackets are not needed. I would try to read your file as a string and change the string to something that <code>pd.read_json()</code> can parse. I assume that your file contains data in a form like this:</p>
<pre><code>["[{\"column1\... | python|json|pandas|dataframe | 0 |
353,339 | 71,180,891 | How to solve AttributeError: Can't get attribute on<module 'x.py'> error? | <p>I have two files <code>x.py</code> and <code>y.py</code>.</p>
<p>Inside <code>y.py</code>, there are two classes, <code>A</code> and <code>B</code>. Class <code>A</code> calls class <code>B</code> inside <code>run</code> function.</p>
<p>In file <code>x.py</code>, I imported class <code>A</code> to run it:</p>
<pre>... | <p>That's very interesting. I don't have the same issue here. Could you post some code that's giving you the issue?</p>
<p>Update #1:</p>
<p>Here's mine:</p>
<p><code>x.py</code></p>
<pre><code># from y import RoBerta_CLS
from y import A
if __name__ == '__main__':
obj = A(model_path='/home/PATH/models/DistilRoBERT... | python|class|import|pytorch | 0 |
353,340 | 71,101,846 | Python create an xml file for every row in excel | <p>I have the following code which creates a xml file from each row in excel. I want to write the xml files in a new folder (currently generates files in same folder as python), how do i change the "output.write()" statement? I am new in programming, started with python 2 weeks ago.</p>
<p><a href="https://i.... | <p>Simply use absolute path especially with <code>os.path.join</code> to concatenate folder and file name:</p>
<pre class="lang-py prettyprint-override"><code>import os
...
xml_file_path = "/path/to/my/xml/outputs"
output.write(
os.path.join(xml_file_path, lista_xml[index_lista])
)
</code></pre>
<p>Howe... | python|pandas|xml | 0 |
353,341 | 71,115,139 | Verify if elements of pandas columns have been shuffled | <p>I have the following df:</p>
<pre><code>name id line_number add_el add_ver del_el del_ver
name1 1 1 elem2 1.3 elem1 1.2
name1 1 2 elem3 1.4 elem3 1.1
name1 1 3 ... | <p>One approach is to <code>merge</code> the DataFrame with itself on <code>name</code>, <code>id</code>, and <code>added_element</code> on the left, and <code>deleted_element</code> on the right:</p>
<pre><code># Create a copy of the original DataFrame and prefill an "action" column
right = df[['name', 'id',... | python|pandas | 1 |
353,342 | 71,347,783 | how to always ensure a 1D signal is the preferred way up (orientation) | <p>I have 1D signals coming as such as these...</p>
<p><a href="https://i.stack.imgur.com/WlDXA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WlDXA.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/qldZD.png" rel="nofollow noreferrer"><img src="https://i.stack... | <p>You can check whether the mean is above the median, and use a trick of 2*boolean-1 to map True/False to 1/-1 to swap the sign:</p>
<pre><code>def orient_up(sig):
return (2*(sig.mean()>np.median(sig))-1) * sig
plt.plot(orient_up(sig))
</code></pre>
<p>output:</p>
<p><a href="https://i.stack.imgur.com/N4kXj.pn... | python|numpy|scipy | 0 |
353,343 | 71,394,466 | wont create a csv file | <pre class="lang-py prettyprint-override"><code>df = pd.read_csv('C:/Users/bhila/Desktop/Pandas-Data-Science-Tasks-master/SalesAnalysis/Sales_Data/Sales_April_2019.csv')
files = [file for file in os.listdir('C:/Users/bhila/Desktop/Pandas-Data-Science-Tasks-master/SalesAnalysis/Sales_Data')]
all_months_data = pd.D... | <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html</a></p>
<p>According to this, 1st argument is path. From your example it will save your <code>.csv</code> in the same folder in which... | python|pandas|export-to-csv | 1 |
353,344 | 71,262,481 | How to avoid roundoff errors in numpy.random.choice? | <p>Say x_1, x_2, ..., x_n are n objects and one wants to pick one of them so that the probability of choosing x_i is proportional to some number u_i. Numpy provides a function for that:</p>
<pre><code>x, u = np.array([x_1, x_2, ..., x_n]), np.array([u_1, ..., u_n])
np.random.choice(x, p = u/np.sum(u))
</code></pre>
<p>... | <p>After reading the answer <a href="https://stackoverflow.com/a/60386427/6087087">https://stackoverflow.com/a/60386427/6087087</a> to the question pointed by @Pychopath, I have found the following solution, inspired by the documentation of numpy.random.multinomial <a href="https://docs.scipy.org/doc/numpy-1.15.0/refer... | python|numpy|random|floating-point|floating-accuracy | 4 |
353,345 | 71,143,724 | Python in Anaconda packages different from command line to jupyterhub (linux) | <p>Strange problem here. I am working on Ubuntu 20.04 using Anaconda to set up some python environments. Specifically I am trying to set up tensorflow to use my GPU but that is just a detail. The problem is that everything works correctly when I open up a terminal and execute the following commands (for environment cal... | <p>The environment in which your Jupyter notebook is running has a wrong LD_LIBRARY_PATH, then it doesn't find the CUDA or cudnn libraries needed to use the GPU.</p> | python|tensorflow|anaconda|environment | 1 |
353,346 | 52,306,279 | pytorch gradient / derivative / difference along axis like numpy.diff | <p>I have been struggling with this for quite some time. All I want is a torch.diff() function. However, many matrix operations do not appear to be easily compatible with tensor operations. </p>
<p>I have tried an enormous amount of various pytorch operation combinations, yet none of them work.</p>
<p>Due to the fac... | <p>A 1D convolution with a fixed filter should do the trick:</p>
<pre><code>filter = torch.nn.Conv1d(in_channels=1, out_channels=1, kernel_size=2, stride=1, padding=1, groups=1, bias=False)
kernel = np.array([-1.0, 1.0])
kernel = torch.from_numpy(kernel).view(1,1,2)
filter.weight.data = kernel
filter.weight.requires_g... | python|numpy|pytorch | 4 |
353,347 | 52,273,729 | Tensorflow root directory in Mac | <p>I need to use the <code>transform_graph</code> in Tensorflow. However, according to <a href="https://stackoverflow.com/questions/46065555/tensorflow-quantization-error-analysis-of-target-tensorflow-tools-graph-tra">TensorFlow: Quantization Error "Analysis of target '//tensorflow/tools/graph_transforms:trans... | <p>use the following to find the location:</p>
<pre><code>pip3 show tensorflow
</code></pre>
<p>or</p>
<pre><code>pip show tensorflow
</code></pre>
<p>Output on my MAC OS:</p>
<pre><code>Name: tensorflow
Version: 1.12.0
Summary: TensorFlow is an open source machine learning framework for everyone.
Home-page: https... | python|tensorflow | 0 |
353,348 | 52,439,364 | How to convert RGB images to grayscale in PyTorch dataloader? | <p>I've downloaded some sample images from the MNIST dataset in <code>.jpg</code> format. Now I'm loading those images for testing my pre-trained model.</p>
<pre><code># transforms to apply to the data
trans = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
# MNIST dataset
test... | <p>When using <code>ImageFolder</code> class and with no custom loader, pytorch uses PIL to load image and converts it to RGB. Default Loader if torchvision image backend is PIL:</p>
<pre><code>def pil_loader(path):
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
</code></p... | python|pytorch | 12 |
353,349 | 52,393,787 | Alternative way of finding the frequency of a term and process the respective values | <p>I have a question regarding the structure of my code. I have the following csv </p>
<pre><code>name product country
A game1 USA
A game2 USA
B bis World
.
.
</code></pre>
<p>Basically, the name of each vendor appears multiple times (as many as the number of products the vendor has). My pu... | <p>Use <code>groupby.agg</code> with a dictionary of aggregation functions for each column.</p>
<pre><code>import pandas as pd
d = {'product': pd.Series.nunique,
'country': lambda x: 5 if (x=='World').any() else 1}
df.groupby('name').agg(d).reset_index()
</code></pre>
<h3>Output:</h3>
<pre><code> name produc... | python|pandas|loops|csv | 1 |
353,350 | 52,311,171 | Numpy and memory with big arrays | <p>I have to work with big arrays, says for example <code>x = np.arange(0, 750*350*365, dtype=np.int32)</code></p>
<p>I know python hold a variable in memory as long as it has at least one reference to it.</p>
<p>But lets say i have to import a big array, do some math on it, and save a smaller array computed from the... | <p>Fancy indexing, unlike slicing, does not return a view, so you will not end up holding a reference to the your big array. See <a href="https://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html" rel="nofollow noreferrer">official explanation on views vs copies in Numpy</a>.</p>
<p>To directly answer your questi... | python|numpy|memory|scope | 2 |
353,351 | 52,090,848 | how to make embedding column through features directly? | <p>I'm learning wide&deep model for ctr. My data has a feature user_id which has more than 2**26 values. How I can get embedding column through this feature? I used
<code>user_id = tf.feature_column.categorical_column_with_hash_bucket('user_id', hash_bucket_size=2**26)</code>,
<code>user_id_emb = tf.feature_colum... | <p>So, 2**26 is about 64M. You want 95 embedding dimensions. Each will be a float32 by default. That is 4 bytes. 4 * 95 ~= 400 bytes per user_id. So you need 64M * 400 ~= 25.6 Gbytes of memory to store the embedding.</p>
<p>Make sure you can allocate that much on your system. It should be all in ram (swap will make ev... | tensorflow|embedding | 0 |
353,352 | 52,142,773 | what happens when I write a function using tensorflow ops | <p>I write a function using tensorflow ops. I know the fact when I run the function, it will add many ops to the graph. But I am confused with how to get access of these ops.</p>
<p>for example:</p>
<pre><code>def assign_weights():
with tf.name_scope('zheng'):
v = tf.Variable(0, 'v', dtype=tf.float32)
... | <p>Obviously, it's true that to access an op (or tensor) we need some reference to it. IMHO, one standard workaround is to build your graph in a class and make certain tensors attributes of the class and access them through the object.</p>
<p>Alternatively, if you're more inclined to the functional approach, a better ... | python|tensorflow | 1 |
353,353 | 52,215,318 | Merging two Dataframes in Pandas based on time-range difference | <p>I have these two dataframes, <code>df1</code>,<code>df2</code>.</p>
<p>df1:</p>
<pre><code>dateTime userId session
2018-08-30 02:20:19 2233 1
2018-08-30 05:32:10 1933 1
2018-08-30 09:10:39 2233 2
2018-08-30 10:26:59 2233 3
2018-08-30 11:56:25 4459 ... | <p>IIUC: Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_asof.html" rel="nofollow noreferrer"><strong><code>pandas.merge_asof</code></strong></a></p>
<pre><code>pd.merge_asof(
df1, df2,
left_on='dateTime',
right_on='clickTime',
by='userId',
direction='nearest'
)
... | python|pandas|numpy | 1 |
353,354 | 52,309,420 | Rasa NLU: Confidence Score Computation | <p>I was trying to understand what the confidences score outputted by rasa nlu(ver-0.12.3) actually are and how they are computed.</p>
<p>I have been working on intent classification task with tensorflow embedding. Once my model is trained and I parse new/test data, I receive a confidence score along with each probabl... | <p>The intent classifier <code>intent_classifier_tensorflow_embedding</code> (<a href="https://rasa.com/docs/nlu/components/#intent-classifier-tensorflow-embedding" rel="nofollow noreferrer">docs</a>) is an approach based on the <a href="https://rasa.com/docs/nlu/components/#intent-classifier-tensorflow-embedding" rel=... | python|tensorflow|metrics|rasa-nlu | 2 |
353,355 | 52,331,557 | python: How to count the elements of a row? | <p>For example, I have a DataFrame named <code>a</code>. I want to count the element of each row.</p>
<pre><code>import numpy as np
a=pd.DataFrame({'A1':['financial','game','game'],'A2':['social','food','sport'],'A3':['social','sport','game']})
</code></pre>
<p><code>Input:</code></p>
<pre><code> A1 A2... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="noreferrer"><code>pandas.get_dummies</code></a> with <code>sum</code>:</p>
<pre><code>df = pd.get_dummies(a, prefix_sep='', prefix='').sum(axis=1, level=0)
print (df)
financial game food social sport
0 1... | python|pandas|dataframe | 6 |
353,356 | 52,114,889 | Loop column names in get_dummies for pandas? | <p>For pandas I have written the code below in order to convert all categorical features. However after I run it on my data set and check data types, nothing changes.</p>
<p>Thank you in advance.</p>
<p>Code:</p>
<pre><code>def dummy_conv(data):
names=data.select_dtypes(exclude=['number']).columns
for c in n... | <p>Looping is not necessary, filter by list of columns, also not forget for <code>return</code>:</p>
<pre><code>data_train = pd.DataFrame({'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
... | python|pandas|loops | 0 |
353,357 | 52,194,190 | Does TensorFlow automatically parallelize graph computations? | <p>Is there a resource for how and if they do it exactly? I'm curious if dependencies are recognized in the graph and parallelized accordingly.</p>
<p><a href="https://www.tensorflow.org/tutorials/images/deep_cnn" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/images/deep_cnn</a></p>
<p><a href="https... | <p>The reason is that TensorFlow does not supply an automatic mechanism for distributing a graph over multiple execution units, it is assumed that the developers do that themselves. However, it obviously keeps track of all the dependencies in the graph so that if you do it manually, it will make sure things are compute... | tensorflow|tensorflow-estimator | 0 |
353,358 | 52,120,236 | Pandas: Check two dataframes for matching values, then fill a row depending on the label | <p>I primarily used MATLAB all through college as a math major and my programming was just building math equations and modeling. Now I have been learning to use Python and in particular, pandas. I am trying to search for values in a column of one dataframe and match them with a value in a column of a different datafram... | <p>Simple <code>map</code> </p>
<pre><code>df1.col3=df1.col1.map(df2.set_index('col1').col2)
df1
Out[31]:
col1 col2 col3
0 aliceA CO Non-Busy
1 aliceB WA Busy
2 aliceC PA Busy
</code></pre> | python|pandas|dataframe | 4 |
353,359 | 52,054,719 | How do I pair multiplication across dataframe efficiently | <p>I want to do feature engineering using multiple numeric features, the idea is do pair multiplication across dataframe, preferred answer is something that available on machine learning library, such as <a href="https://www.tensorflow.org/api_docs/python/tf" rel="nofollow noreferrer">TensorFlow</a>, <a href="https://k... | <p>There are other more specialised ways to do it automatically. E.g. <code>PolynomialFeatures</code>:</p>
<pre><code>import pandas as pd
from sklearn.preprocessing import PolynomialFeatures
# original data
df = pd.DataFrame(data = [[1, 10, 20, 30], [2, 20, 30, 40]], columns = ['No', 'feature_1', 'feature_2', 'feature... | python|pandas|dataframe|feature-extraction | 2 |
353,360 | 52,367,739 | Numpy broadcasting on multiple arrays | <p>I have a basis for a plane in 3 dimensions: (u, v).</p>
<p>I would like to obtain all linear combinations of this basis to basically go through my whole plane:</p>
<p>for i in [0, 512[ and j in [0, 512[, get all (i * u + j * v).</p>
<p>I need this to be fast so for loops are not really an option. How can I do tha... | <p>Multiply (u, v) with a 2D index grid:</p>
<pre><code>ind = np.indices((512, 512))
pixels = ind[0, ..., np.newaxis] * u + ind[1, ..., np.newaxis] * v
>>> %timeit ind = np.indices((512, 512)); pixels = ind[0, ..., np.newaxis] * u + ind[1, ..., np.newaxis] * v
8.06 ms ± 69.8 µs per loop (mean ± std. dev. of ... | python|arrays|numpy | 2 |
353,361 | 52,274,697 | error in building transform_graph in Tensorflow | <p>I am optimizing my frozen Tensorflow model using <code>transform_graph</code> by using this command in bash:</p>
<pre><code>bazel build tensorflow/tools/graph_transforms:summarize_graph
</code></pre>
<p>But I get this error:</p>
<pre><code>ERROR: Skipping 'tensorflow/tools/graph_transforms:summarize_graph': no su... | <p>I think your Tensorflow is installed in PIP library.</p>
<p>When using the Tensorflow tools with bazel, should be installed by Tensorflow source code with bazel.</p>
<p>Then you can use the Tensroflow tools.</p>
<p>Please check the installation and links.</p>
<p><a href="https://www.tensorflow.org/install/instal... | python|tensorflow | 1 |
353,362 | 52,377,346 | Percent Change in for-loop | <p>I have a dataframe where I've set both the District and the Year as a multilevel index. I want to calculate the percentage change for each column ('DEM', 'REP', etc) for each district for each year.</p>
<p><a href="https://i.stack.imgur.com/XZA7Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X... | <p>You can simply specify the level in your <code>groupby</code>.</p>
<pre><code>districts_bydistrict.groupby(level='Year').pct_change()
</code></pre>
<p>You can unstack the districts so that you just have time in the index, compute <code>pct_change</code>, and then restack the districts.</p>
<pre><code>districts_by... | python|pandas|for-loop | 2 |
353,363 | 52,145,755 | Calculate new Position of coordinates with numpy | <p>I have a dataset of images for Key point detection. Each Image got labeled with one keypoint (x|y). </p>
<p>I use numpy to flip images for data augmentation. </p>
<p>I flip an Image horizontal with this code: </p>
<pre><code>img = img[:, ::-1]
</code></pre>
<p>And vertical with this code</p>
<pre><code> img = i... | <p>Use the rotation matrix:</p>
<pre><code>x_new = x_old * np.cos(alpha) - y_old * np.sin(alpha)
y_new = x_old * np.sin(alpha) + y_old * np.cos(alpha)
</code></pre>
<p>Alpha is a roatation angle in radians, but i don't know what gives <code>img = img[:, ::-1]</code>)))</p> | python|numpy|data-augmentation | 0 |
353,364 | 52,088,709 | Reduce 3D volume mask by uniform margin in python | <p>I'm working with 3D boolean arrays that mask a volume. My goal is to take a mask and reduce the area of the mask by some margin, m, in all dimensions.</p>
<p>Is there an easy way to do this using some common libraries (numpy, scipy, pandas, etc..)? </p>
<p><a href="http://www.siafoo.net/snippet/82" rel="nofollow n... | <p>You might be looking for <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.binary_erosion.html#scipy.ndimage.binary_erosion" rel="nofollow noreferrer"><code>scipy.ndimage.binary_erosion(a)</code></a>:</p>
<pre><code>a = np.array([
[0., 0., 1., 0., 0.],
[0., 1., 1., 1., 0.],
[1.... | python|numpy|scipy | 2 |
353,365 | 52,320,409 | Verify that file exists inside the Tensorflow flow. Using tf.gfile.Exists with string Tensor as input | <p>Using Tensorflow I am trying to verify that a file exists before reading it with <code>tf.read_file(filename)</code>. Unfortunately, the way my pipeline is setup, I am generating the filename string on the fly using <code>tf</code> commands. I generate my filename string using <code>tf.string_join</code> and then wo... | <p>I just wrapped it inside a <code>tf.py_func</code></p>
<pre><code>def file_exists(file_path):
[exists] = tf.py_func(_file_exists, [file_path], [tf.bool])
exists.set_shape([])
return exists
def _file_exists(file_path):
return tf.gfile.Exists(file_path)
</code></pre> | python|tensorflow | 1 |
353,366 | 52,328,843 | I want to change the data frame structure | <p>My current data frame look like:</p>
<pre><code>CREATED_DATE STATE
02/03/15 0:00 Texas
02/03/15 0:00 Texas
02/03/17 16:19 Texas
02/03/15 16:19 Florida
02/03/16 16:19 Florida
02/03/16 16:19 Florida
02/03/15 16:19 Alabama
02/03/16 16:19 Alabama
02/03/15 16:19 North Carolina
02/03/15 16:19 North Carolin... | <p>Try:</p>
<pre><code>df.groupby(['STATE', df.CREATED_DATE.dt.year]).size().unstack(1, fill_value=0)
</code></pre>
<p>Alternatively, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>pandas.crosstab</code></a> here:</p>
<pre><code>p... | python-3.x|pandas|dataframe|pivot-table | 1 |
353,367 | 52,133,347 | How can I clear a model created with Keras and Tensorflow(as backend)? | <p>I have a problem when training a neural net with Keras in Jupyter Notebook. I created a sequential model with several hidden layers. After training the model and saving the results, I want to delete this model and create a new model in the same session, as I have a <code>for</code> loop that checks the results for d... | <p><code>keras.backend.clear_session()</code> should clear the previous model. From <a href="https://keras.io/backend/" rel="noreferrer">https://keras.io/backend/</a>:</p>
<blockquote>
<p>Destroys the current TF graph and creates a new one.
Useful to avoid clutter from old models / layers.</p>
</blockquote> | python|tensorflow|keras|jupyter-notebook | 61 |
353,368 | 52,228,899 | Keras, auc on validation set during training does not match with sklearn auc | <p>I am using my test set as a validation set. I used similar approach as <a href="https://stackoverflow.com/questions/41032551/how-to-compute-receiving-operating-characteristic-roc-and-auc-in-keras">How to compute Receiving Operating Characteristic (ROC) and AUC in keras?</a></p>
<p>The issue is that my val_auc durin... | <p>First of all, <code>tf.contrib.metrics.streaming_auc</code> is deprecated, use <code>tf.metrics.auc</code> instead. <br/></p>
<p>As you have mentioned, TF uses a different method to calculate the AUC than Scikit-learn. <br/>
TF uses an approximate method. Quoting its documentation:</p>
<blockquote>
<p>To discret... | tensorflow|scikit-learn|keras|roc|auc | 10 |
353,369 | 52,397,773 | Quirky behavior of pandas.DataFrame.equals | <p>I have noticed a quirky thing. Let's say A and B are dataframe. </p>
<p>A is: </p>
<pre><code>A
a b c
0 x 1 a
1 y 2 b
2 z 3 c
3 w 4 d
</code></pre>
<p>B is:</p>
<pre><code>B
a b c
0 1 x a
1 2 y b
2 3 z c
3 4 w d
</code></pre>
<p>As we can see above, the elements under column <c... | <p>Alternative to sacul and U9-Forward's answers, I've done some further analysis and it looks like the reason you are seeing <code>True</code> and not <code>False</code> as you expected might have something more to do with this line of the <a href="http://pandas-docs.github.io/pandas-docs-travis/generated/pandas.DataF... | python|pandas | 2 |
353,370 | 52,423,390 | assigning title to intervals in pandas | <pre><code>import numpy as np
xlist = np.arange(1, 100).tolist()
df = pd.DataFrame(xlist,columns=['Numbers'],dtype=int)
pd.cut(df['Numbers'],5)
</code></pre>
<p>how to assign column name to each distinct intervals created ?</p> | <p>IIUC, you can use <code>pd.concat</code> function and join them in a new data frame based on indexes:</p>
<pre><code># get indexes
l = df.index.tolist()
n =20
indexes = [l[i:i + n] for i in range(0, len(l), n)]
# create new data frame
new_df = pd.concat([df.iloc[x].reset_index(drop=True) for x in indexes], axis=1)... | pandas|numpy | 0 |
353,371 | 52,325,851 | How to get the pandas columns into rows with custom condition? | <p>I have a dataframes like that</p>
<p><strong>df1</strong></p>
<pre><code> A B C SN
0 10 23 48 456123
1 15 45 98 789456
2 16 62 55 123789
</code></pre>
<p><strong>df2</strong></p>
<pre><code> A B C SN
0 10 19 48.0 456123
1 15 45 NaN 789456
2 68 77 55.0 123789
</cod... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with replace <code>0</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a... | python|pandas | 1 |
353,372 | 52,140,654 | Taking Same Worksheet from a Folder of xlsm Files with Python | <p>I'm new to pandas/python and Ive come up with the following code to extract data from a specific part of a worksheet. </p>
<pre><code>import openpyxl as xl
import pandas as pd
rows_with_data = [34,37,38,39,44,45,46,47,48,49, 50,54,55,57,58,59,60,62,63,64,65,66,70,71,72,76,77, 78,79,80,81,82,83,84,88,89,90,91,92]
... | <p>I was having hard time to read your code to understand that what you want to do finally. <strong>So it is just an advice not a solution.</strong> You can iterate through all files in the folder using <code>os</code> then read the files in to one dataframe then save the single big data frame in to csv. I usually avoi... | python|excel|pandas|openpyxl | 0 |
353,373 | 52,338,033 | How to apply (call) a single layer on data in Keras? | <p>Is there an easy way to give data to a layer in Keras (over TF) and see the return values, for test purposes, without actually building a full model and fitting data to it?</p>
<p>If not, how can one test a customized layer that they develop?</p> | <p>You can define and use a <a href="https://keras.io/backend/#function" rel="nofollow noreferrer">backend function</a> for this purpose:</p>
<pre><code>from keras import backend as K
# my_layer could be a layer from a previously built model, like:
# my_layer = model.layers[3]
func = K.function(model.inputs, [my_laye... | python|tensorflow|keras | 3 |
353,374 | 52,321,121 | Failed to filter rows containing a specific value in the index column after resetting index | <p>I'm organizing data of a number of plans, which contains the information of the phase of the plan, P(Preliminary) or F(Final). I'm using the methods shown in the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow noreferrer">examples</a> in the pandas document... | <p><code>filter</code> may intuitively feel like the right function, but you almost certainly should use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> to filter your data (on your examples link above, it says "See also: loc" in ... | python|pandas|filter | 4 |
353,375 | 52,008,168 | Assertion error when making an MP4 video out of numpy arrays with OpenCV | <p>I have this python code that should make a video:</p>
<pre><code>import cv2
import numpy as np
out = cv2.VideoWriter("/tmp/test.mp4",
cv2.VideoWriter_fourcc(*'MP4V'),
25,
(500, 500),
True)
data = np.zeros((500,500,3))
for i in ... | <p>The problem is that you did not specify the data type of elements when calling <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html" rel="nofollow noreferrer"><code>np.zeros</code></a>. As the documentation states, by default numpy will use <code>float64</code>.</p>
<pre><code>>>>... | numpy|opencv|mp4|fourcc | 2 |
353,376 | 52,315,230 | identify non Latin Charset text Ph | <p>From a huge text file , Need to be able to identify lines that contains non Latin characters (\w plus Special characters) technically i should exclude other alphabets than Latin. the output is stored in a log file for further processing.
my attempts with <code>re</code> have not been successful, do you see an smart ... | <p>Python contains the <code>unicodedata</code> module for things like that:</p>
<pre><code>import unicodedata
...
for index, line in enumerate(inputfile):
if any(unicodedata.category(ch).startswith("L") and not unicodedata.name(ch).startswith("LATIN")):
... # contains non-latin alphabetic chars
else... | regex|python-3.x|pandas | 0 |
353,377 | 52,255,450 | Unnamed column and Nan in Pandas | <p>i'm getting Unnamed and Nan in output when i try to print the headers of .csv file.</p>
<p>import pandas as pd</p>
<pre><code>df = pd.read_csv('testextract.csv', error_bad_lines=False,sep=' ',dtype=unicode,index_col=0,low_memory=False)
print(df.head())
</code></pre>
<p>Output :</p>
<pre><code> Unnamed: 1 Unnamed... | <pre><code>data = df.loc[:, ~df.columns.str.contains('^Unnamed')]
print(data)
</code></pre> | python|pandas | 2 |
353,378 | 52,291,423 | Plot time without date in matplotlib or seaborn | <p>Hi I am working on a categorical data. I want to see device behavior on a given day. I have these as my dataframe:</p>
<p>On <code>toronto_time</code>, I have a <code>datetime64[D]</code>. I previously used <code>dt.time</code> to remove the date. However, it presents a datatype problem which makes it a type <code>... | <p>I'm not sure why you want the minutes and seconds on the graph if your ticks are only on the hour? But you can do it by setting a formatter for your axis. Although I would suggest also changing you axis limits if you're looking for ticks by the hour.</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as p... | python|pandas|matplotlib|seaborn | 2 |
353,379 | 52,331,082 | pandas filter by values in 2 columns, return entire row | <p>I've looked around multiple questions on here and no solution works.
I have a matrix, where I want to filter values in 2 columns and return the <em>entire row</em> where this filter applies.</p>
<p>At the moment I have tried:</p>
<p><code>mask = (data['sender'] == 'me') & (data['status'] == 'done')
data[mask]
... | <p>Hope this helps </p>
<pre><code> k=pd.DataFrame()
k=data[(data['sender'] == 'me') & (data['status'] == 'done')]
k.head()
</code></pre> | python|python-3.x|pandas|jupyter-notebook | 2 |
353,380 | 60,704,199 | How to plot velidation and training loss in same figure in Tensorboard | <p>I'm working with a Tensorflow object detection model with a config file similar to this <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/samples/configs/faster_rcnn_inception_resnet_v2_atrous_coco.config" rel="nofollow noreferrer">tensorflow/research/object_detection/samples/config... | <p>Please refer below sample code to plot both validation and training loss</p>
<pre><code>import os
import tqdm
import tensorflow as tf
def tb_test():
sess = tf.Session()
x = tf.placeholder(dtype=tf.float32)
summary = tf.summary.scalar('Values', x)
merged = tf.summary.merge_all()
sess.run(tf.... | python|tensorflow|tensorboard | 0 |
353,381 | 60,556,270 | Problems with Jax's JIT and Numpy restrictions | <p>I've recently started experimenting with the interesting python library <a href="https://github.com/google/jax" rel="nofollow noreferrer">Jax</a>, which contains a boosted Numpy as well as Automatic Differentiator. What I wanted to try to create, is a crude "differentiable renderer", by writing a shader and loss fun... | <p>Replace</p>
<pre><code>if first_col:
return self.color1
else:
return self.color2
</code></pre>
<p>with</p>
<pre><code>return np.where(first_col, self.color1, self.color2)
</code></pre> | python|numpy|automatic-differentiation|jax | 3 |
353,382 | 60,708,508 | pandas combine a data frame with another groupby dataframe | <p>I have two data frames with structure as given below.</p>
<pre><code>>>> df1
IID NAME TEXT
0 10 One AA,AB
1 11 Two AB,AC
2 12 Three AB
3 13 Four AC
>>> df2
IID TEXT
0 10 aa
1 10 ab
2 11 abc
3 11 a,c
4 11 ab
5 12 AA
6 13 AC
7 13 ad
... | <p>I believe you need <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with <a href="https://pandas.pydata.org/pandas-docs/version/0.22.0/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>grou... | python-3.x|pandas | 1 |
353,383 | 60,528,589 | Write Pandas dataframe to list of rows | <p>How can i write out a pandas dataframe to lists</p>
<pre><code> X Y Z Value
0 18 55 1 70
1 18 55 2 67
2 18 57 2 75
3 18 58 1 35
4 19 54 2 70
</code></pre>
<p>Output to text file like</p>
<pre><code>[
["X", "Y", "Z", "V... | <p>Convert data and columns separately and join by <code>+</code>:</p>
<pre><code>L = [df.columns.tolist()] + df.reset_index().values.tolist()
[['X', 'Y', 'Z', 'Value'],
[0, 18, 55, 1, 70],
[1, 18, 55, 2, 67],
[2, 18, 57, 2, 75],
[3, 18, 58, 1, 35],
[4, 19, 54, 2, 70]]
</code></pre>
<p>For avoid index remov... | python|pandas | 4 |
353,384 | 60,559,447 | How to count the occurrence of strings in Dataframe that exists in another list of dicts? | <p>I have a Dataframe which look like this:</p>
<pre><code> ngram
--------------------------
0 []
1 [_ting, tingk, ...]
2 [_pend, pendi, ...]
3 [_teat, teate, ...]
... ...
999 []
</code></pre>
<p>I also have a list of dicts which ... | <p>Idea is first change list of dicts to dictinary in dict comprehension:</p>
<pre><code>L = [
{
"label": "Academic",
"gram": "_ting"
},
{
"label": "Facility",
"gram": "_pend"
},
{
"label": "Services",
"gram": "_aaa"
},
{
"label": "Others",
"gram": "meing"
},
]
d = {x['... | python|pandas|dataframe | 0 |
353,385 | 60,571,934 | Which axis does Keras SimpleRNN / LSTM use as the temporal axis by default? | <p>When using a <code>SimpleRNN</code> or <code>LSTM</code> for classical <a href="https://keras.io/examples/imdb_lstm/" rel="nofollow noreferrer">sentiment analysis</a> algorithms (applied here to sentences of length <= 250 words/tokens):</p>
<pre><code>model = Sequential()
model.add(Embedding(5000, 32, input_leng... | <p><strong>Temporal axis</strong>: it's always dim 1, unless <code>time_major=True</code>, then it's dim 2; the <code>Embedding</code> layer outputs a 3D tensor. This can be seen <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/keras/layers/recurrent.py#L540" rel="nofollow noreferrer">her... | python|tensorflow|keras|recurrent-neural-network | 3 |
353,386 | 60,455,539 | Rolling over values from one column to other based on another dataframe | <p>I have two dataframes:
<code>DF1</code></p>
<pre><code>ID DatePaid Remaining
A1 2018-01-01 8500
A2 2018-02-15 2000
A2 2018-02-28 1900
A3 2018-04-12 3000
A3 2018-05-12 2700
A3 2018-05-17 110
A3 2018-06-17 0
A4 2018-06-18 10
A5 2018-07-13 500
</code></pre>
<p>Now I have another datafra... | <p>This gives you the data in <code>df2</code> form:</p>
<pre><code>month_ends = pd.to_datetime(df1.DatePaid).dt.to_period('M')
# also
# month_ends = pd.to_datetime(df1.DatePaid).add(pd.offsets.MonthEnd(0))
(df1.groupby(['ID', month_ends])
['Remaining'].last()
.unstack(-1)
.ffill(1)
.reset_index()
... | python|pandas|dataframe | 2 |
353,387 | 60,535,110 | Tensorflow model accuracy low | <p>So my main goal is to use data from 2018 and try to predict data for 2019. I'm using a GRU model and I have the following code. I have a few issues, I'm not sure if the code is actually correct or if I am missing something, and also for model.fit should I use validation_split=0.1 or validation_data=X_test,y_test sin... | <p>It sounds to me that you are trying to solve a regression problem here. if it is so, It does not make sense to measure <code>accuracy</code> as a metric, since accuracy is about to measure the exact label matching. <code>MSE</code> should be pretty good for the regression</p> | python|tensorflow|machine-learning|keras|deep-learning | 3 |
353,388 | 60,603,660 | Pandas: filter by date proximity | <p>I have a frame like:</p>
<pre><code> id title date
0 1211 jingle bells 2019-01-15
1 1212 jingle bells 2019-01-15
2 1225 tom boat 2019-06-15
3 2112 tom boat 2019-06-15
4 3122 tom boat 2017-03-15
5 1762 tom boat 2017-03-15
</code></pre>
<p>An <code>item</code> is defined... | <p>I think sorting your dataframe can help you solve the problem much more efficiently. </p>
<pre><code>df = df.sort_values(['title', 'date'])
itemlist = []
counter = 0 # to get items at constant time
for title in set(df.title):
dates = df.loc[df['title']==title].date.tolist()
item = []
min_date = dates... | python|pandas|dataframe | 1 |
353,389 | 60,491,368 | Compute standard deviation for each row and by group based on a specific variable | <p>I am fresh user of python, my issue is to compute standard deviation for the column <em>residual</em>.
to do it :</p>
<ol>
<li>I have to calculate the mean residual in each group</li>
<li>I need the size of ID for each group</li>
</ol>
<p>I happened to do some calculation and this is my code:</p>
<pre><code>impor... | <p>I apologize as I don't have enough points to just leave a comment, has to be an answer. Anyway, could you maybe try something like this:</p>
<pre><code>new_df = df.loc[:, 'residual'].groupby(df['ID']).std()
</code></pre> | python|pandas|group-by|statistics|standard-deviation | 0 |
353,390 | 60,586,503 | TypeError: an integer is required (got type Timestamp) | <p>I have an Excel table in the following format:</p>
<p><a href="https://i.stack.imgur.com/HcPQz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HcPQz.png" alt="enter image description here"></a></p>
<p>I want to read this table with Python using the <code>pandas</code> modules and calculate the difference... | <p>The <code>datetime</code> module is part of the Python standard library. The constructor of the <code>datetime.datetime</code> class takes a specific year, month and day as parameter (<a href="https://docs.python.org/3/library/datetime.html#datetime.datetime" rel="noreferrer">Reference</a>). You would invoke it e.g.... | python|python-3.x|pandas|python-datetime | 20 |
353,391 | 60,588,401 | Add column to pandas Dataframe (ascending block of numbers) | <p>I have a data looking like this:</p>
<pre><code>Col1
aaa1
bbb1
ccc1
1
2
3
aaa2
bbb2
ccc2
4
5
6
</code></pre>
<p>I want to add a new column to make it look like this:</p>
<pre><code>Col1 Col2
aaa1 1
bbb1 1
ccc1 1
1 1
2 1
3 1
aaa2 2
bbb2 2
ccc2 2
4 2
5 ... | <p>IIUC, you can check if <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>str.contains</code></a> <code>aaa</code> and then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow no... | python|pandas | 0 |
353,392 | 60,399,785 | how to look back values of previous row for select cases only in pandas | <p>My data looks like below. </p>
<pre><code> col_1 col_2
1 1
1 1
p 0
1 1
n 2
n 2
p 0
p 0
</code></pre>
<p>I want to calculate values in col_2 from col_1. The logic that i want to apply is: When col_1 value ='p'... | <p>You can use <code>mask</code> then <code>ffill</code>:</p>
<pre><code>df['col_2'] = df['col_2'].mask(df['col_1']=='p').ffill()
</code></pre> | python|pandas|pandas-groupby|pandasql | 4 |
353,393 | 60,548,040 | Merging/Concat non unique multi index with Date | <p>I have 2 data frames as below:</p>
<pre><code>df1 =
City Date Data1
LA 2020-01-01 20
LA 2020-01-02 30
NY 2020-01-01 50
df2 =
City Date Data2
LA 2020-01-01 2.5
LA 2020-01-02 1
LA 2020-01-03 7
NY 2020-0... | <p>Idea is deduplicated pairs by new column created by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a>:</p>
<pre><code>print (df2)
City Date Data2
0 LA 2020-01-01 2.5
1 LA 2020-0... | pandas|concat | 2 |
353,394 | 60,429,916 | How to create tensor with shape(?,) and dtype=string from image with tensorflow in python | <p>I have a trained model with input layer specified below:</p>
<pre><code>Model input: [<tf.Tensor 'encoded_image_string_tensor:0' shape=(None,) dtype=string>, <tf.Tensor 'key:0' shape=(None,) dtype=string>]
</code></pre>
<p>I have problem to create a tensor with these properties. Either i get right dty... | <p>You can do</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
a = tf.placeholder(dtype=tf.string, shape=[None, ], name="encoder_image_string_tensor")
print(a)
</code></pre>
<p>which prints</p>
<p><code>Tensor("encoder_image_string_tensor:0", shape=(?,), dtype=string)</code></p>
<p>For f... | python|tensorflow | 1 |
353,395 | 60,427,975 | Collapse values from multiple rows of a column into an array when all other columns values are same | <p>I have a table with 7 columns where for every few rows, 6 columns remain same and only the 7th changes. I would like to merge all these rows into one row, and combine the value of the 7th column into a list.</p>
<p>So if I have this dataframe:</p>
<pre><code> A B C
0 a 1 2
1 b 3 4
2 c 5 6
3 c 7 6
<... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> with custom lambda function, last add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow nor... | python-3.x|pandas | 2 |
353,396 | 60,378,466 | If BERT's [CLS] can be retrained for a variety of sentence classification objectives, what about [SEP]? | <p>In BERT pretraining, the [CLS] token is embedded into the input of a classifier tasked with the Next Sentence Prediction task (or, in some BERT variants, with other tasks, such as ALBERT's Sentence Order Prediction); this helps in the pretraining of the entire transformer, and it also helps to make the [CLS] positio... | <p>In theory it can give 'some' results so it would work (it's just a token), but the question is why you would want to that. These tokens have been pretrained for a specific purpose. I suppose that by 'retrain' you mean finetuning, so if you would finetune the SEP token suddenly as a classification token, I think you ... | transformer-model|bert-language-model|huggingface-transformers | 2 |
353,397 | 60,358,461 | How to drop floating point values from dataframe in pandas? | <p>I have a large dataframe but has similar contents to the one below.</p>
<pre><code>d = {'col1': [1, -2.654, 3, 1.995]}
df = pd.DataFrame(data=d)
Output
col1
0 1
1 -2.654
2 3
3 1.995
</code></pre>
<p>I would like to delete the floating point values so rows 1 and 3 would be deleted.... | <p>try:</p>
<pre><code>d = {'col1': [1, -2.654, 3, 1.995]}
df = pd.DataFrame(data=d)
df[df.col1 == round(df.col1)]
# col1
# 0 1.0
# 2 3.0
</code></pre> | python|pandas | 2 |
353,398 | 60,342,888 | LineString - get coordinates as DataFrame | <p>I have a geopandas Dataframe with one <code>GeoSeries</code>.</p>
<p>There is only one entry for this column, a <code>shapely.geometry.linestring.LineString</code>.</p>
<pre><code>LineString (first_lon first_lat, second_lon second_lat, ...)
</code></pre>
<p>I could not find an easy way to get the coordinates of t... | <pre><code>x,y = LineStringObject.coords.xy
pd.DataFrame(list(zip(x,y)), columns=['LAT', 'LON'])
</code></pre>
<p>seem to do the job ok.</p>
<p>[EDIT]</p>
<pre><code>x,y = LineStringObject.coords.xy
pd.DataFrame({'LAT':x,'LON':y})
</code></pre> | python-3.x|pandas|geopandas|shapely | 4 |
353,399 | 60,541,715 | Convert date manipulation code to a function then apply it to multiple columns | <p>Let's say a given dataframe <code>df</code> contains two date type columns <code>start_date</code> and <code>end_date</code>, they both need to be manipulated with the code below:</p>
<pre><code>df['date'] = df['date'].str.split('d').str[0].add('d')
df['date'] = df['date'].str.replace('Y', '-').str.replace('m', '-'... | <p>Change <code>df['date']</code> for <code>x</code>, because <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> processing both columns like <code>Series</code>:</p>
<pre><code>def date_manipulate(x):
x = x.str... | pandas|function|dataframe|python-3.6 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.