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 |
|---|---|---|---|---|---|---|
3,800 | 61,933,021 | How to overwrite data on an existing excel sheet while preserving all other sheets? | <p>I have a pandas dataframe <code>df</code> which I want to overwrite to a sheet <code>Data</code> of an excel file while preserving all the other sheets since other sheets have formulas linked to sheet <code>Data</code></p>
<p>I used the following code but it does not overwrite an existing sheet, it just creates a n... | <p>You can do it using <strong><a href="https://openpyxl.readthedocs.io/en/stable/" rel="noreferrer"><code>openpyxl</code></a>:</strong></p>
<pre><code>import pandas as pd
from openpyxl import load_workbook
book = load_workbook(filename)
writer = pd.ExcelWriter(filename, engine='openpyxl')
writer.book = book
writer... | python|excel|pandas|dataframe | 14 |
3,801 | 61,871,562 | Maintain column consistency when writing into an existing excel file with pandas to_excel | <p>this might be a simple and easy problem but I can't find out how to solve it. The problem is more complex but I made a simple version in order to focus in the real issues.</p>
<pre><code>import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
e = {'col1': [11, 33], 'ab1': [55,44], 'col... | <p>Let us try <code>concat</code> before write into excel </p>
<pre><code>s=pd.concat([df,df2],keys=['df','df2'],sort=True)
s
Out[129]:
ab1 col1 col2
df 0 NaN 1 3
1 NaN 2 4
df2 0 55.0 11 22
1 44.0 33 66
with pd.ExcelWriter('file.xlsx',mode='a') as writer:
s.l... | python|pandas|mongodb|dataframe | 1 |
3,802 | 61,706,381 | How to conditionally groupby a column and transform a pandas dataframe on the basis of row wise operations? | <p>I have a pandas dataframe <em>df</em> of the form:</p>
<pre><code> id start_time end_time label
1 0 2 A
1 3 6 C
1 9 11 A
2 0 4 B
2 5 7 A
3 1 ... | <p>We need to use <code>groupby</code> with <code>shift</code> to create the sub group key , then we just do the <code>groupby</code> with <code>agg</code> </p>
<pre><code>s=df.groupby('id').apply(lambda x : (x.start_time-x.end_time.shift(1)).gt(1).cumsum()).reset_index(level=0,drop=True)
df['times']=list(zip(df.start... | python|pandas|numpy | 5 |
3,803 | 61,728,624 | Get the pandas dataframe first row with index | <p>Recently I have started using Pandas in my work to handle the data obtained by some sensors
I have a dictionary with the sensor values in the following format:</p>
<pre class="lang-py prettyprint-override"><code>data={
2019-10-23 00:00:00: {
key1: value1,
key2: value2,
...
keyN: valueN
},
2019... | <p>you can use <code>head</code> instead like:</p>
<pre><code># example data
df = pd.DataFrame({'a':range(2), 'b':range(2,4)},
index=pd.to_datetime(['01/01/2018','02/01/2018']).strftime('%Y-%m-%d %H:%M:%S'))
print (df.head(1).to_json(orient='index'))
{"2018-01-01 00:00:00":{"a":0,"b":2}}
#or to_dic... | python|pandas | 0 |
3,804 | 61,949,695 | NeuralNet regression, input normalization/ouput denormalization and role of activation funcions? | <p>Given a training dataset, Xtrain (m x n) and ytrain(m,) and some neural net sequential model.</p>
<p>When and to what range does the training data have to be normalized too? How should predicted values be denormalized? And how do the choices of activation functions of different layers effect this?</p>
<ul>
<li>do ... | <p><strong>Do we have to normalize the Xtrain data?</strong><br>
- Yes, we have to</p>
<p><strong>Does the range we normalize depend on the input layers activation function?</strong><br>
- No, it doesn't</p>
<p><strong>Does that have to denormalized?</strong><br>
- No</p>
<p><strong>Does it have to be normalized to ... | tensorflow|keras|normalization|denormalization | 1 |
3,805 | 54,892,653 | Tensorflow Embedding using Continous and Categorical Variable | <p>Based on <a href="https://stackoverflow.com/questions/43574889/tensorflow-embedding-for-categorical-feature">this</a> post, I tried to create another model, where I'm adding both categorical and continous variables.
Please find the code below:</p>
<pre><code>from __future__ import print_function
import pandas as pd... | <p>If by <code>embedding_agregated</code> you mean <code>embed</code> (probably typo) </p>
<p>The error is that there is no <code>axis=2</code> in your case , it should be <code>axis=1</code></p>
<p><code>inputs_with_embed = tf.concat([x, embed], axis=1, name="inputs_with_embed")</code></p>
<p><code>embed</code> has... | tensorflow|embedding | 1 |
3,806 | 54,752,195 | How to define ConvLSTM encoder_decoder in Keras? | <p>I have seen examples of building an encoder-decoder network using LSTM in Keras but I want to have a ConvLSTM encoder-decoder and since the ConvLSTM2D does not accept any 'initial_state' argument so I can pass the initial state of the encoder to the decoder, I tried to use RNN in Keras and tried to pass the ConvLSTM... | <p>Below is my approach for encoder-decoder-based solution with ConvLSTM.</p>
<pre><code>def convlstm(input_shape):
print(np.shape(input_shape))
inpTensor = Input((input_shape))
#encoder
net1 = ConvLSTM2D(filters=32, kernel_size=3,
padding='same', return_sequences=True)(inpTensor)
... | tensorflow|keras|conv-neural-network|recurrent-neural-network|encoder-decoder | 0 |
3,807 | 54,934,019 | replacing a column's values (if it meets a condition) from another existing column's values | <p>I have a <code>data frame</code> that consists of 3 columns: </p>
<pre><code>Id, Summary, Description
</code></pre>
<p>What I am trying to do is if any values in <code>Description</code> exactly match this string: "This is an empty description", then replace those contents with those of <code>Summary</code>.</p>
... | <p>This is a really common warning when you are chaining multiple indexing operations in <code>Pandas</code>. You can read about it in details <a href="https://www.dataquest.io/blog/settingwithcopywarning/" rel="nofollow noreferrer">here</a>. If you want to leverage <code>Pandas</code> native methods, you can do someth... | python-3.x|pandas|dataframe|series | 0 |
3,808 | 54,975,556 | Check if Column Has String Object Then Convert to Numeric | <p>I need to check if a column in my dataframe is of type 'object' and then based on that information, change all the values in that column to an integer. Here is the function I wrote to do that:</p>
<pre><code>def multiply_by_scalar(self):
self.columns_to_index()
i = ask_user("What column would you like to m... | <p>Here my solution: </p>
<pre><code>#df.dtypes.to_dict() create a dictionary with name column as index and dtype as values
for colname, coltype in df.dtypes.to_dict().items():
if coltype == 'object' : df[colname] = df[colname].astype(int)
</code></pre>
<p>or if you have a function fc to execute</p>
<pre><code... | python|pandas|dataframe | 0 |
3,809 | 55,113,824 | pandas valueError when using agg function | <p>I am getting myself acquainted with pandas and I have encountered an issue I cannot find an answer to.</p>
<p>I am using the dataset available here <a href="https://raw.githubusercontent.com/Shreyas3108/house-price-prediction/master/kc_house_data.csv" rel="nofollow noreferrer">https://raw.githubusercontent.com/Shre... | <p>I have tried below code and able to done Successfully which you have mentioned in your question.</p>
<pre><code>df = pd.read_csv('https://raw.githubusercontent.com/Shreyas3108/house-price-prediction/master/kc_house_data.csv')
df = df.agg([min, max]).T
CLM = ['max', 'min']
df = (df.drop(CLM, axis=1)
.join(d... | python|pandas|data-science | 0 |
3,810 | 49,373,835 | String substitution in str.replace vs Pandas str.replace | <p>I need to replace a backslash with something else and wrote this code to test the basic concept. Works fine:</p>
<pre><code>test_string = str('19631 location android location you enter an area enable quick action honeywell singl\dzone thermostat environment control and monitoring')
print(test_string)
test_string =... | <p>There's a difference between <code>str.replace</code> and <code>pd.Series.str.replace</code>. The former accepts substring replacements, and the latter accepts regex patterns.</p>
<p>Using <code>str.replace</code>, you'd need to pass a <em>raw string</em> instead.</p>
<pre><code>df['col'] = df['col'].str.replace(r... | python|string|pandas|replace | 2 |
3,811 | 49,441,151 | How to control FEA software like MSC NASTRAN using Python code? | <p>I would like to run MSC NASTRAN using python. I have seen a similiar function in MATLAB using
<code>system('nastran.exe file_name.bdf')</code> #where file_name.bdf is the input file to Run using nastran.</p>
<p>Hence i tried below using python code, but it did not work,</p>
<pre><code>import os
os.system('nastran.... | <p>I can't speak directly for MSC Nastran, its been a while since I've used it. But most modern FEA programs have an API (application program interface) to allow you to call commands from a external program like python or matlab. </p>
<p>Without an API, you may be limited to using python to start the program from the ... | python|numpy|system | 1 |
3,812 | 67,235,753 | Replace table with dependencies using pandas to_sql's if_exists='replace' | <p>Pandas <code>pd.to_sql()</code> function has the parameter <code>if_exists='replace'</code>, which drops the table and inserts the given <code>DataFrame</code>. But the table I'm trying to replace is part of a <code>view</code>. Is there a way to replace the table and keep the view without having to delete and recre... | <p>If update has same columns. You can truncate table,</p>
<pre><code>con.execute('TRUNCATE table RESTART IDENTITY;')
</code></pre>
<p>and then run <code>pd.to_sql</code> with <code>if_exists='append'</code></p> | python|sql|pandas|psql|pandas-to-sql | 1 |
3,813 | 60,246,599 | get specific value in each group and add it as new column in each group | <p>I want to have something like this:</p>
<hr>
<p>dataframe:</p>
<pre><code> col1 col2 col3
A 'aa' date1
A 'aa' date2
A 'aa' date3
A 'bb' date4
B 'aa' date5
B ... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>df=df.sort_values("col2", ascending=False).set_index("col1")
df["col4"]=df.groupby("col1")["col3"].first()
df=df.reset_index(drop=False)
</code></pre>
<p>Outputs:</p>
<pre class="lang-py prettyprint-override"><code> col1 col2 col3 col4
0 A bb d... | python|python-3.x|pandas|dataframe | 4 |
3,814 | 59,913,977 | Why does very simple port of the official Keras mnist example to tensorflow 2.x result in massive drop in accuracy? | <p>Here is the mnist example from the Keras documentation:
<a href="https://keras.io/examples/mnist_cnn/" rel="nofollow noreferrer">https://keras.io/examples/mnist_cnn/</a></p>
<p>I put it into google colab, under Tensorflow 1.x, and it performs really well:
<a href="https://colab.research.google.com/drive/15NW-lXhRUx... | <p>The difference is in the optimizers. <code>tf.keras.optimizers.Adadelta</code> uses a learning rate of 0.001. <code>keras.optimizers.Adadelta</code> uses a learning rate of 1.0.</p>
<p>Check <a href="https://keras.io/optimizers/" rel="nofollow noreferrer">keras.optimizers</a> and <a href="https://www.tensorflow.org... | tensorflow2.0|mnist|tf.keras | 1 |
3,815 | 65,289,194 | How to correctly use apply and int inside values of a single key | <p>I've a basic question: I'm using the following script:</p>
<pre><code>import pandas as pd
from collections import OrderedDict
df = pd.DataFrame({'ID' : ['ID1', 'ID1', "ID1","ID2","ID2"], "pdb" : ["a", "b", "c","d","e"], "... | <p>I think you can create new column <code>r</code> with ranges and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a>, then sorting, remove duplicates and convert to strings before <code>join</code> per groups b... | python|pandas|string|dataframe|integer | 1 |
3,816 | 49,804,230 | Integer-based offset from index label | <p>In <a href="https://pandas.pydata.org/" rel="nofollow noreferrer">Pandas</a>, is it possible to determine the index's label at a given integer offset from a known index label? For instance,</p>
<pre><code>>>> df
a b
10 1 2
20 3 4
30 5 6
40 7 8
>>> df.index.offset(10, 3)
40
>>>... | <p>Use <code>pd.Index.get_loc</code></p>
<pre><code>df.index[df.index.get_loc(10) + 3]
40
</code></pre>
<hr>
<pre><code>df.index[df.index.get_loc(30) - 1]
20
</code></pre> | python|python-3.x|python-2.7|pandas | 1 |
3,817 | 46,856,221 | Numpy 3D array indexing using lists | <p>Suppose I have a numpy array with shape (10, 1000, 1000), and I have three lists, which are supposed to represent the range of indexes of each axis like so:</p>
<pre><code>z_range = [0, 5]
y_range = [200, 300]
x_range = [300, 500]
</code></pre>
<p>I know I can do the following, but it seems rather verbose:</p>
<p... | <p>Indexing takes a tuple, so you can just construct your tuple dynamically, using a generator expression:</p>
<pre><code>>>> z_range = [0, 3]
>>> y_range = [2, 3]
>>> x_range = [3, 5]
>>> arr = numpy.arange(5*5*5).reshape(5,5,5)
>>> arr[tuple(slice(a, b) for a,b in (x_rang... | python|arrays|numpy|indexing | 3 |
3,818 | 46,836,389 | How can I get access to intermediate activation maps of the pre-trained models in NiftyNet? | <p>I could download and successfully test <a href="https://cmiclab.cs.ucl.ac.uk/CMIC/NiftyNet/tree/dev/demos/brain_parcellation" rel="nofollow noreferrer">brain parcellation demo</a> of <a href="http://niftynet.io/" rel="nofollow noreferrer">NiftyNet</a> package. However, this only gives me the ultimate parcellation re... | <p>To answer your 'Finally' question first, NiftyNet has some network architectures implemented (e.g., VNet, UNet, DeepMedic, HighRes3DNet) that you can train on your own data. For a few of these, there are pre-trained weights for certain applications (e.g. brain parcellation with HighRes3DNet and abdominal CT segmenta... | tensorflow|pre-trained-model|niftynet | 2 |
3,819 | 63,225,734 | Mix of line and scatter plots from pandas dataframe in a single plot using the tick frequency of the first plot only | <p>I am wanting to compare data within a dataframe, plotting some of the data as lines, and other columns as scatter. My actual data is a combination of model output and observations, I want the observations to be scatter, and the model to be lines.</p>
<p>The observations have a LOT of Nan values (most times steps do... | <p>Just add <code>plt.xticks(rotation=45)</code> to the end of your script and you will be fine.</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(40)]
df = pd.DataFrame(d... | python|pandas|matplotlib|plot | 0 |
3,820 | 63,185,421 | RuntimeError: The expanded size of the tensor (7) must match the existing size (128) at non-singleton dimension 3 | <p>When I run AdaIN code</p>
<pre><code>def adaptive_instance_normalization(content_feat, style_mean, style_std):
size = content_feat.size()
content_mean, content_std = calc_mean_std(content_feat)
normalized_feat = (content_feat - content_mean.expand(
size)) / content_std.expand(size)
return no... | <p>You should be more precise and descriptive while explaining your issue. You cannot expect from people to read your mind or be familiar with your exact problem. So first, what should be the expected output and which line is failing ? I guess from the <code>expand</code> calls that you would like to enable broadcastin... | pytorch | 1 |
3,821 | 67,631,676 | topography data, string '-' can't be converted to float | <p>I'm attempting to import cornea topography data from a CSV file. The imshow fails to plot the data after slicing the axes and converting all to np.array, displaying the error message</p>
<p>"raise TypeError("Image data of dtype {} cannot be converted to "
TypeError: Image data of dtype object cannot b... | <p>When reading the.csv file, it appears that the key thing is to define the separator manually. As a result, the line should be:</p>
<p>df= read_csv (filename, header=None, error_bad_lines=False, sep=';')</p> | python|pandas|dataframe|imshow|topography | 0 |
3,822 | 67,829,360 | handle comment lines when reading csv using pandas | <p>Here is a simple example:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from io import StringIO
s = """a b c
------------
A1 1 2
A-2 -NA- 3
------------
B-1 2 -NA-
------------
"""
df = pd.read_csv(StringIO(s), sep='\s+', comment='-')
df
a b ... | <p>Another solution: You can "preprocess" the file before <code>.read_csv</code>. For example:</p>
<pre class="lang-py prettyprint-override"><code>import re
import pandas as pd
from io import StringIO
s = """a b c
# comment line
------------
A1 1 2
A-2 -NA- 3
------------
B-1 2 ... | python|pandas|dataframe|csv|comments | 2 |
3,823 | 67,989,036 | How to find the first point of intersection between two arrays? | <pre><code>wavelength_one=target[60].wavelength.value
flux_one=target[60].flux.value
wavelength_two=target[61].wavelength.value
flux_two=target[61].flux.value
f,ax=plt.subplots(figsize=(15,10))
ax.plot(wavelength_one,flux_one,color='green')
ax.plot(wavelength_two,flux_two,color='black')
ax.grid(True)
</code></pre>
<... | <p>You can try this code snippet:</p>
<pre class="lang-py prettyprint-override"><code>from math import isclose
For i in range(len(flux_one)):
if flux_one[i] == flux_two[i] and isclose(wavelength_one, wavelength_two):
print(flux_one[i], flux_two[i])
</code></pre> | python|numpy|matplotlib|numpy-ndarray | 0 |
3,824 | 68,021,867 | CNN model is not learn well | <p>I started to learn CNN implementation in PyTorch, and I tried to build CNNs to process the grayscale images with 4 classes from 0 to 3. I got in the beginning accuracy around 0.55. The maximum accuracy I got is ~ 0.683%.</p>
<p>I tried SGD and Adam optimizer with different values for lr and batch_size, but the accur... | <p>How many images are in the train set ? the test set ? What are the size of the images ? How would you consider the difficulty of classification of the images ? Do you think it should be simple or difficult ?</p>
<p>According to the numbers you have, you're overfitting as your loss is near 0 (meaning nothing much wil... | pytorch|conv-neural-network|classification | 1 |
3,825 | 61,184,276 | Exec format error: Try to compile .proto files into .py files with Raspberry Pi | <p>I`m a german studant. For the school I have to make a physics or chemistry project, I decided to install tensorflow on a raspberry pi to train a object detection modal. But there is an error I don´t understand. 'sh: 1: bin/protoc: Exec format error'</p>
<p>I tried all versions of protobuf from the source here:
<a h... | <p><code>Exec format error</code> means that you're trying to run a binary that's not compatible with your system.<br>
The Raspberry Pi 4 has an ARM Cortex-A72 CPU, and Raspbian is a 32-bit operating system, so you need a 32-bit ARM binary.<br>
At first glance, none of the binaries that you can download from the GitHub... | tensorflow|raspberry-pi|proto | 0 |
3,826 | 61,436,770 | SSD’s loss not decreasing in PyTorch | <p>I am implementing SSD(Single shot detector) to study in PyTorch.
However, my custom training loss didn't decrease...
I've searched and tried various solution for week, but problem is still remaining.</p>
<p>What should I do?
My loss function is incorrect?</p>
<p>Here is my SSD300 model</p>
<pre><code>SSD300(
(f... | <p>I must normalize predicted boxes before calculating loss function.</p>
<p>The word of variance caused to mislead...
<a href="https://leimao.github.io/blog/Bounding-Box-Encoding-Decoding/" rel="nofollow noreferrer">link</a> </p>
<pre class="lang-py prettyprint-override"><code>class Encoder(nn.Module):
def __ini... | python|python-3.x|deep-learning|pytorch | 0 |
3,827 | 61,574,046 | Pandas pivot table: Aggregate function by count of a particular string | <p>I am trying to analyse a DataFrame which contains the Date as the index, and Name and Message as columns. </p>
<p>df.head() returns:</p>
<pre><code> Name Message
Date
2020-01-01 Tom image omitted
2020-01-01 Michael image omitted
2020-01-02 James image H... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html" rel="nofollow noreferrer"><code>Series.str.count</code></a> for number of matched values to new column added to DataFrame by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.... | python|pandas|lambda|pivot-table|aggregate-functions | 2 |
3,828 | 61,557,662 | Vectorize two pandas columns at once with CountVectorizer | <p>I want I want to apply Sklearn's CountVectorizer at two columns at once.
I have tried this:</p>
<pre><code>features = df[['col 1', 'col2']]
results = df[['col 3']
vectorizer = CountVectorizer(lowercase=False)
features = vectorizer.fit_transform(features)
results = vectorizer.fit_transform(results)
</code></pre>
... | <p>This is the solution:</p>
<pre><code>features = df.iloc[:, [-2,-3]]
results = df.iloc[:, -1]
from sklearn.compose import make_column_transformer
vectorizer = CountVectorizer(lowercase=False)
transformer = make_column_transformer((vectorizer, 'col 1'), (vectorizer, 'col 2'))
features = transformer.fit_transform(f... | python|pandas|scikit-learn | 0 |
3,829 | 68,771,230 | Pandas: How to concat or merge two incomplete dataframe into one more complete dataframe | <p>I would like to concatenate two incomplete data frame with the same data (in theory) regarding a similar index.
I tried with pd.concat but I don't managed to get what I need.</p>
<p>Here is a simple example of what I would like to do :</p>
<pre><code> df1 = pd.DataFrame(
{
"A": ["A0&qu... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>combine_first()</code></a>, as follows:</p>
<pre><code>df_result = df1.combine_first(df2)
</code></pre>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/referen... | python|pandas|merge|concatenation|outer-join | 2 |
3,830 | 65,808,296 | How to change only xticks fontsize in pandas Dataframe barplot? | <p>I want to create a barplot from pandas. But I want to change fontsize for x and y-axis separately.</p>
<p>This code:</p>
<blockquote>
<pre><code>max_coef.plot.bar(fontsize = 15, x = 'coef_word', y = 'coefficient', color=['yellow'])
</code></pre>
</blockquote>
<p>Creates this plot:</p>
<p><a href="https://i.stack.img... | <p>See the code below for changing the font size:</p>
<pre><code>import matplotlib.pyplot as plt
SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIG_SIZE = 12
plt.rc('font', size=SMALL_SIZE) # default text sizes
plt.rc('axes', titlesize=MEDIUM_SIZE ) # axes title fontsize
plt.rc('axes', labelsize=MEDIUM_SIZE) # x and y... | python|pandas|bar-chart | 2 |
3,831 | 65,697,424 | Pandas: drop out of sequence row | <p>My Pandas df:</p>
<pre><code>import pandas as pd
import io
data = """date value
"2015-09-01" 71.925000
"2015-09-06" 71.625000
"2015-09-11" 71.333333
"2015-09-12" 64.571429
"2015-09-21" 72.285714
"""
df = pd.... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> for filter by mask, here convert input values to datetimes and then timedeltas to days by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/... | pandas | 1 |
3,832 | 63,582,377 | How do I search for index values in each row of an array in numpy creating a boolean array | <p>Given an array with size MxN and an array with size Mx1, I want to compute a boolean array with MxN.</p>
<pre><code>import numpy as np
M = 2
N = 3
a = np.random.rand(M, N) # The values doesn't matter
b = np.random.choice(a=N, size=(M, 1), replace=True)
# b =
# array([[2],
# [1]])
# I found this way to comp... | <p>You could simplify by leveraging broadcasting an comparing with a single 1d range directly:</p>
<pre><code>M = 2
N = 3
a = np.random.rand(M, N)
b = np.random.choice(a=N, size=(M, 1), replace=True)
print(b)
array([[1],
[2]])
b == np.arange(N)
array([[False, True, False],
[False, False, True]])
</co... | python|numpy|numpy-ndarray|boolean-algebra | 0 |
3,833 | 63,675,583 | How to replace every row that are filled with zero with a certain value from a Pytorch tensor? | <p>I have a Pytorch tensor of the size <code>bsize x 50 x 50</code> where some of the rows are completely filled with zeros:</p>
<pre class="lang-py prettyprint-override"><code> [[0, 2, 0, ..., 0, 0, 0],
[2, 0, 2, ..., 0, 0, 0],
[0, 2, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ...... | <p>Assuming <code>x</code> is your tensor with <code>BxRxC</code> (batch, rows, and columns), you can do something like this:</p>
<pre class="lang-py prettyprint-override"><code>x[(x == 0).all(dim=-1)] = -100
</code></pre>
<p>Basically:</p>
<ul>
<li><code>x == 0</code> returns a boolean tensor (shape <code>BxRxC</code>... | python|pytorch|vectorization|tensor | 3 |
3,834 | 63,715,025 | Tricky cascade grouping in pandas | <p>I have a bit of an odd problem that I am trying to solve in pandas. Let's say I have a bunch of objects that have different ways to group them. Here is what our dataframe look like:</p>
<pre><code>df=pd.DataFrame([
{'obj': 'Ball', 'group1_id': None, 'group2_id': '7' },
{'obj': 'Balloon', 'group1_id': '92'... | <p>This is not odd at all ~ network problem</p>
<pre><code>import networkx as nx
#we need to handle the miss value first , we fill it with same row, so that we did not calssed them into wrong group
df['key1']=df['group1_id'].fillna(df['group2_id'])
df['key2']=df['group2_id'].fillna(df['group1_id'])
# here we start to c... | python|pandas | 2 |
3,835 | 63,460,065 | Optimizer for an RNN using pytorch | <p><a href="https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html" rel="nofollow noreferrer">The pytorch RNN tutorial</a> uses</p>
<pre><code>for p in net.parameters():
p.data.add_(p.grad.data, alpha = -learning_rate)
</code></pre>
<p>as optimizer. Does anyone know the difference between ... | <p>It looks like the example uses a simple gradient descent algorithm to update:</p>
<p><a href="https://i.stack.imgur.com/RBAsN.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RBAsN.gif" alt="p_{t+1}=p_t-\alpha \mathrm{grad}_pJ_t" /></a>
where J is cost.</p>
<p>If the optimizer your using is a simpl... | python|pytorch | 1 |
3,836 | 63,492,730 | Pandas not converting certain columns of dataframe to datetimeindex | <p>My dataframe until now,
<a href="https://i.stack.imgur.com/TBwoo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TBwoo.png" alt="enter image description here" /></a></p>
<p>and I am trying to convert <code>cols</code> which is a list of all columns from <strong>0 to 188</strong> <code>( cols = lis... | <p>In order to modify some of the labels from an Index (be it for rows or columns), you need to use <code>df.rename</code> as in</p>
<pre><code>for i in range(188):
df.rename({df.columns[i]: pd.to_datetime(df.columns[i])},
axis=1, inplace=True)
</code></pre>
<p>Or you can avoid looping by building a full si... | python|pandas|dataframe|datetimeindex | 1 |
3,837 | 71,836,954 | Numpy slicing with index | <pre><code>x = np.array([
[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]
])
end_point = [3, 4] # Slicing end point
# Want: Slicing along the row, like this
x[end_point-2 : end_point]
= np.array([[2, 5], [4, 7], [6, 9]])
</code></pre>
<p>Can I do this thing in an elegant way? Of course, the above code induces a type err... | <p>Here's how I went about figuring out a solution:</p>
<pre><code>In [21]: x = np.arange(10).reshape(5,2)
In [22]: x
Out[22]:
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
</code></pre>
<p>Looks like you want several 'diagonals', which we can get with pairs of indexing lists/arrays:</p>
... | numpy | 1 |
3,838 | 55,490,404 | Convert pandas data frame to categorical for keras | <p>I am trying to preprocess data in python for use in deep learning keras functions.</p>
<p>I use <code>categorical crossentropy</code> as loss function in model fit. It requires categorical variable as target.</p>
<p>My target data sample:</p>
<pre class="lang-py prettyprint-override"><code> y_train = y_train.a... | <p>Unfortunately i didn't manage to reproduce your error.
Running:</p>
<pre><code>a=pd.DataFrame(np.concatenate([np.zeros(3),np.ones(3)]) ).astype('int').astype('category')
from keras.utils import to_categorical
to_categorical(a, 2)
</code></pre>
<p>I get an output:</p>
<pre><code>array([[1., 0.],
[1., 0.],
... | python|pandas|machine-learning|keras | 1 |
3,839 | 56,835,074 | AttributeError: 'Series' object has no attribute 'has_z' | <p>I got the following <code>GeoDataFrame</code> taken from a CSV file and after some slincing and <code>CRS</code> and <code>geometry</code> asignment</p>
<pre><code> ctf_nom geometry id
0 Prunus mahaleb POINT (429125.795043319 4579664.7564311) 2616
1 Be... | <p>You need to explicitly set the geometry column in the <code>GeoDataFrame</code>:</p>
<pre><code>df_geo.set_geometry(col='geometry', inplace=True)
</code></pre>
<hr />
<p><sub>Taken from: <a href="https://gis.stackexchange.com/a/342635/6998">https://gis.stackexchange.com/a/342635/6998</a></sub></p> | python-3.x|attributeerror|geopandas|writetofile | 0 |
3,840 | 47,288,914 | Splitting words to rows in DataFrame | <p>I have a DataFrame where one of the columns contains strings. I would like to split the strings by spaces and then transform the DataTable, so that it contains one word per row.</p>
<pre><code>dat = pd.DataFrame(data = {'x' : [1,2],
'y' : ['Lorem ipsum dolor sit amet',
... | <p>str to <code>list</code> , then we using <code>stack</code></p>
<pre><code>dat.y=dat.y.str.split(' ')
dat.set_index('x').y.apply(pd.Series).stack().reset_index().\
drop('level_1',1).rename(columns={0:'y'})
Out[484]:
x y
0 1 Lorem
1 1 ipsum
2 1 dolor
3 1 sit
4... | python|python-3.x|pandas | 1 |
3,841 | 47,422,603 | pandas parse dates with two columns and replace a single point to a double point | <p>this is how i want to read my csv file in:</p>
<pre><code>data01 = pd.read_csv('data/file.csv', sep=';', decimal=',', parse_dates=[['date', 'time']])
</code></pre>
<p>Time is given as <i>hh.mm.ss</i> and i want it like this:<i>hh:mm:ss</i>
Is there a way to do this inside the pd.read_csv?</p> | <p>For this, you can use </p>
<pre><code>data01["(insert name of column with time)"].replace({".",":"}
</code></pre> | python|pandas | 0 |
3,842 | 68,369,649 | Problems casting dtypes | <p>i have a df lke this:</p>
<pre><code>value_1 Value_2
10.0 20.0
</code></pre>
<p><code>value_1</code> and <code>value_2</code> as <code>float64</code>.</p>
<p>How do i cast it to int ad get this:</p>
<pre><code>value_1 Value_2
10 20
</code></pre>
<p>I tried:</p>
<pre><code> df.astype('int32').dtypes
</... | <p>Let us try</p>
<pre><code>df.astype(int)
value_1 Value_2
0 10 20
</code></pre> | pandas|jupyter | 1 |
3,843 | 68,105,079 | PyTorch Error while building CNN: "1only batches of spatial targets supported (3D tensors) but got targets of size: : [1, 2, 64, 64]" | <p>I want to build a CNN like the one in this paper: <a href="https://arxiv.org/abs/1603.08511" rel="nofollow noreferrer">https://arxiv.org/abs/1603.08511</a> (<a href="https://richzhang.github.io/colorization/" rel="nofollow noreferrer">https://richzhang.github.io/colorization/</a> ).
As data I got images from the LAB... | <p>Why are you using <code>CrossEntropyLoss()</code> for this task?<br />
Why does your network outputs 128dim "pixels"?<br />
What are the <em>spatial</em> dimensions of your prediction vs the targets?<br />
You are using only 1x1 kernels, meaning your model makes its predictions for each pixel <em>independa... | python|deep-learning|neural-network|pytorch|conv-neural-network | 0 |
3,844 | 68,238,588 | Assigning header names to panda datasheets with varying number of columns | <p>I am looking to assign a header row to panda dataframes with a varying number of columns. The underlying data sheet are targets disclosed by companies, the number of which differ per company</p>
<p>Eg. this could be:</p>
<pre><code>df = pd.DataFrame([['apple','become carbon neutral','100% renewable'],['Microsoft','c... | <p>Assuming default column names <code>0</code>, <code>1</code>, <code>2</code> etc:</p>
<pre><code>df.columns = ['company name', *map('target {}'.format, df.columns[1:])]
</code></pre>
<p>Or based on a <code>range</code> if columns are already named:</p>
<pre><code>df.columns = ['company name', *map('target {}'.format... | python|pandas|dataframe | 0 |
3,845 | 68,048,692 | Pandas: eror when checking for a binary flag pattern | <p>I have a dataframe where one of the columns of type <code>int</code> is storing a binary flag pattern:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'flag': [1, 2, 4, 5, 7, 3, 9, 11]})
</code></pre>
<p>I tried selecting rows with value matching 4 the way it is typically done (with binary and operator):</p>
... | <p>The bitwise-flag selection works as you’d expect:</p>
<pre><code>>>> df['flag'] & 4
0 0
1 0
2 4
3 4
4 4
5 0
6 0
7 0
Name: flag, dtype: int64
</code></pre>
<p>However if you pass this to <code>df.loc[]</code>, you’re asking to get the indexes <code>0</code> and <code>4</code> repe... | python|pandas|series|binary-operators | 1 |
3,846 | 56,885,523 | How to pivot a dataframe with pandas to display values with aggregation and without aggregation | <p>I want to pivot my dataframe using pandas, my dataframe look like this</p>
<p><a href="https://i.stack.imgur.com/ZD0yg.png" rel="nofollow noreferrer">Dataframe</a></p>
<p>I want <code>shop_id</code> with maximum <code>item_cnt_day</code> with maximum sold <code>item_id</code> sorted by <code>date_block_num</code> ... | <p>You can do that in two aggregation steps like:</p>
<pre><code># first group by all three attributes to get one line per
# this three columns
grouped=df.groupby(['date_block_no', 'shop_id', 'item_id'])
# and just aggregate the item_cnt_day you want to have listed
aggregated=grouped.aggregate({'item_cnt_day': 'sum'}... | python|pandas | 0 |
3,847 | 57,102,089 | C++: Passing Operator as Parameter leads to Error "expected an identifier" | <p>I compiled Tensorflow for C++ by using bazel 0.20.0 and VS2015</p>
<p>I created a simple C++-Project in VS2019 and tried to build it
but following problem occurs:</p>
<p>The code part in ...\tensorflow\core\platform\default\logging.h ,that is affected:</p>
<pre><code>// Helper functions for CHECK_OP macro.
// The... | <p>try to <a href="https://www.tensorflow.org/install/source_windows" rel="nofollow noreferrer">update</a> bazel version, cause MS2015 may be compatible with bazel 0.20, but MS2019 is not. </p>
<p><a href="https://www.tensorflow.org/install/source_windows#cpu" rel="nofollow noreferrer">Checkout compatibility table</a>... | c++|tensorflow|visual-studio-2015|compilation|parameter-passing | 0 |
3,848 | 57,094,179 | How do I upsample an irregular dataset based on a data column? | <p>I have a pandas dataframe that contains logged data based on depth. The depth is spaced irregularly.
I need the dataset to be spaced in regular dx steps. </p>
<p>Is there a way of doing this without stuffing it into separated numpy arrays and interpolating them seperately?</p>
<p>Seperate interpolation of all col... | <p>I ended up with <code>interp1d</code> from the <code>signal</code> package.</p> | python|pandas|resampling | 0 |
3,849 | 57,075,168 | How to generate new Python dataframe series based on dataframe values | <p>I have a data frame as the one generated by the script below - bringing in dataframe "data".</p>
<p>Ideally I would like to generate a new dataframe that combines the id and a sequence of 1 : value. </p>
<pre class="lang-py prettyprint-override"><code>d = {'id': ['a', 'b','c'], 'value': [1, 2,1]}
data = pd.DataFra... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.repeat.html" rel="nofollow noreferrer"><code>Index.repeat</code></a> by column <code>value</code> and reassign values by counter by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumco... | python|pandas|dataframe|series | 2 |
3,850 | 57,085,178 | How to assign value to a pandas dataframe, when subset by complex index and boolean based conditions? | <p>I would like to replace values in a pandas dataframe, with a complex subsetting pattern. </p>
<p>With the .loc accessor, I was only able to subset by chaining multiple conditions, because some of the conditions are index based. But it seems I can not assign values after such a chain of subsetting.
<strong>UPDATE:</... | <p>You can do with one <code>.loc</code> chain of <code>loc</code> assignment will be not safe</p>
<pre><code>df.loc[df.index.isin(['2019-01-05','2019-01-09'])&df.a.eq('foo'),'b']=np.nan
</code></pre> | python|pandas|dataframe|subset | 4 |
3,851 | 45,929,439 | How can I insert a column into a dataframe if the column values come from a different file? | <p>Currently I am reading in from a file and it is generating this file (<code>output.txt</code>): </p>
<pre><code>Atom nVa avgppm stddev delta
1.H1' 2 5.73649 0.00104651803616 1.0952e-06
1.H2' 1 4.85438
1.H8 1 8.05367
10.H1' 3 5.33823 0.136655138213 0.0186746268
10.H2' 1 4.20449
10.H5 3 5.27571333333 0.231624986634 0... | <p>The easiest way is to make an <code>index</code> on the <code>pandas.DataFrame</code>. Pandas has nice logic for matching up indexes.</p>
<pre><code>from io import StringIO
import pandas as pd
# if python2, do:
# data = u"""\
data = """\
Atom nVa avgppm stddev delta
1.H1' 2 5.73649 0.00104651803616 1.0952e-06
1.H2... | python|pandas | 1 |
3,852 | 50,909,879 | which performance will gain if more memory available? | <p>I got the log:</p>
<pre><code>2018-06-18 20:33:24.218811: W tensorflow/core/common_runtime/bfc_allocator.cc:217] Allocator (GPU_1_bfc) ran out of memory trying to allocate 2.27GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory is available.
</code... | <p>If your GPU lacks memory, but the program still runs, then it means that some optimizations won't take place, or some operations will be run on your CPU instead of the GPU, which will decrease the computation speed of your program.</p>
<p>So, if more memory is available, you'll improve your training and testing spe... | tensorflow | 1 |
3,853 | 50,959,561 | Convert `String Feature` DataFrame into Float in Azure ML Using Python Script | <p>I am trying to understand how to convert azure ml <code>String Feature</code> data type into float using python script. my data set is contain "HH:MM" data time format. It recognized as <code>String Feature</code> like the following img:</p>
<p><a href="https://i.stack.imgur.com/gy4A7.jpg" rel="nofollow noreferrer"... | <p>The to_numeric conversion seems to be the problem, as there's no default parsing from string to number.</p>
<p>Does it work if you just use pd.apply(timeToFloat) ?</p>
<p>Roope - Microsoft Azure ML Team</p> | python|pandas|csv|azure-machine-learning-studio | 0 |
3,854 | 66,377,478 | Can not get entire table from html - Pandas | <p>I was trying to get data using pandas from a wikipedia article about the largest bankrupts <a href="https://en.wikipedia.org/wiki/List_of_largest_U.S._bank_failures" rel="nofollow noreferrer">DATA</a> but for some reason the table was incomplete. I used this:</p>
<pre><code>df = pd.read_html('https://en.wikipedia.o... | <p>You are getting the whole table. By default, only some number of rows is displayed, hence the <code>...</code> signs in the middle. If you want to display all rows you can change pandas display default as follows:</p>
<pre><code># show at most 100 rows
pd.options.display.max_rows = 100
</code></pre>
<p>Note that thi... | python|pandas|data-science | 0 |
3,855 | 57,322,649 | Converting from list format to matrix showing equality | <p>I'm trying to convert from a pandas dataframe that looks like: </p>
<pre><code>Item | Country
A | UK
B | FR
C | DE
D | FR
</code></pre>
<p>And I want to create a matrix that compares each item to each other item based on country, so:</p>
<pre class="lang-none prettyprint-override"><code> A B C D
A 1 0 0 0
B 0 1 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a>:</p>
<pre><... | python|pandas | 1 |
3,856 | 51,218,923 | Does tf.train.CheckpointSaverHook in tf.train.MonitoredTrainingSession block training while checkpointing or it is done asynchronously? | <p>I am pretty new in TensorFlow. I am currently curious to track the IO time and bandwidth (preferably percentage of IO time taken in the training process for checkpointing) for checkpointing which is performed by the internal checkpointing mechanism provided by high level <code>tf.train.MonitoredTrainingSession</code... | <p>I believe it will.</p>
<p>The checkpointing isn't done asynchronously. You'd want the checkpoint to contain a consistent snapshot of the variables/parameters and thus do not want to checkpoint asynchronously with other operations that may update the parameter values.</p>
<p>The <code>CheckpointSaverHook</code> exp... | tensorflow|io|profiling|checkpointing | 1 |
3,857 | 51,536,090 | Pandas DataFrame rolling count | <p>I have the following pandas dataframe (just an example):</p>
<pre><code>import pandas as pd
df = pd.DataFrame(pd.Series(['a','a','a','b','b','c','c','c','c','b','c','a']), columns = ['Data'])
</code></pre>
<p><br></p>
<pre><code> Data
0 a
1 a
2 a
3 b
4 b
5 c
6 c
7 c
8 c
9 ... | <p>Here's one way using <code>groupby</code>:</p>
<pre><code>counts = df.groupby((df['Data'] != df['Data'].shift()).cumsum()).cumcount() + 1
df['Stats'] = np.where(df['Data'] != df['Data'].shift(-1),
df['Data'] + counts.astype(str), '')
print(df)
Data Stats
0 a
1 a
2 ... | python|pandas|dataframe|counting | 2 |
3,858 | 70,879,159 | Get datetime format from string python | <p>In Python there are multiple DateTime parsers which can parse a date string automatically without providing the datetime format. My problem is that I don't need to cast the datetime, I only need the datetime format.</p>
<p>Example:
From "2021-01-01", I want something like "%Y-%m-%d" or "yyyy... | <p>In <code>pandas</code>, this is achieved by <code>pandas._libs.tslibs.parsing.guess_datetime_format</code></p>
<pre class="lang-py prettyprint-override"><code>from pandas._libs.tslibs.parsing import guess_datetime_format
guess_datetime_format('2021-01-01')
# '%Y-%m-%d'
</code></pre>
<p>As there will always be an a... | python|pandas|datetime|format | 4 |
3,859 | 71,048,186 | How to select one and remove correlated features from a long format correlation dataframe directly? | <p>I have a long format pandas dataframe containing feature correlation pairs (with duplicate pairs). I want to select one out of every correlated pair from this long table (100s of feature). Is their a pythonic way to do this without transforming this table into a matrix? Ideally in this example, we need to keep only ... | <p>Solved this by lexicographical sorting the rows and then removing everything from <code>feature2</code> column.</p>
<pre><code>features_list = ['a', 'b', 'c']
def custom_sort(x):
min_val = min(x["feature1"], x["feature2"])
max_val = max(x["feature1"], x["feature2"])
... | python|pandas | 0 |
3,860 | 70,809,444 | How to filter a dataframe and each row, based on the presence of strings (from another list) in different columns and add a new column with annotation | <p>I have a dataframe (df1) where I would like to search each row for items from listA. If the dataframe has a row that contains 'positive' and one or more of the items from listA, I would like to generate another dataframe (df2) by adding a column called result, listing the listA item + present. Items in list A, may ... | <p>Updated:</p>
<p>I have created a function first which is applied to every row ('axis=1') and the results are added to the result column.</p>
<pre><code>def check_rows(row):
same_values = ', '.join([term for term in listA for substring in row.values if term in substring])
if same_values:
return same_v... | python|pandas|dataframe | 0 |
3,861 | 70,977,136 | Is there a way to add a new column to a pandas multiindex that only aligns with one level? | <p>I'm looking for a clean way to add a column to a multiindex dataframe, where the value is only repeated once per level=0.</p>
<p>For example,</p>
<p><strong>I want to add a column to this:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Index level=0</th>
<th>Index level=1</th>
... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.IndexSlice.html" rel="nofollow noreferrer"><code>pd.IndexSlice</code></a>:</p>
<pre><code>idx = pd.IndexSlice
df.loc[idx[:, 1], 'Color'] = ['Yellow', 'Red']
print(df)
# Output
Value Color
A 1 300 Yellow
2 850 NaN
3 2000 NaN... | python|pandas|dataframe|multi-index | 3 |
3,862 | 51,862,276 | Creating a numeric variable issue | <p>I'm trying to create a new variable as the mean of another numeric var present in my database <code>(mark1 type = float)</code>.
Unfortunately, the result is a new colunm with all <code>NaN</code> values.
still can't understand the reanson why.
The code i made is the following:</p>
<pre><code>df = pd.read_csv("stud... | <p>You need <code>GroupBy</code> + <code>transform</code> with <code>'mean'</code>.</p>
<p>For the data you have provided, this is trivially equal to <code>mark1</code>. You should probably map your genders to categories, e.g. <code>M</code> or <code>F</code>, as a preliminary step.</p>
<pre><code>df['mean_m1'] = df.... | python|python-3.x|pandas|pandas-groupby | 0 |
3,863 | 35,895,194 | Create a list of pandas dataframes with names in pattern | <p>I want to create a list of pandas dataframes with names in some pattern, like list = [df_1, df_2, df_3....] (there are about 15 of them)
I know I can define them one by one and append them into a list. Is there any efficient way to do it?</p> | <p>I believe this should work. Naming variables dynamically in python is not great practice, however, so I would recommend against it:</p>
<pre><code>dct = {}
for i in range(0,16):
dct['df_%s' % i] = pd.DataFrame()
for k,v in dct.items():
locals()[k] = v
</code></pre> | list|pandas|dataframe | 0 |
3,864 | 36,209,830 | pandas, slice multi-index df with multiple conditions | <p>This question is a continuation of <a href="https://stackoverflow.com/questions/36204249/pandas-re-indexing-with-missing-dates">pandas re-indexing with missing dates</a></p>
<p>I want to compute the sum of the values for the most recent 3 months (2015-12, 2015-11, 2015-10). If a stock doesn't have sufficient data i... | <p>try this:</p>
<pre><code>In [142]: df
Out[142]:
value date stock
0 4 2015-01-01 amzn
1 2 2015-02-01 amzn
2 5 2015-03-01 amzn
3 6 2015-04-01 amzn
4 7 2015-05-01 amzn
5 8 2015-06-01 amzn
6 6 2015-07-01 amzn
7 5 2015-08-01 amzn
8 4 2015-09-01 amz... | python|pandas|indexing|slice|object-slicing | 0 |
3,865 | 37,265,159 | Lasagne/Theano doesn't consume multi cores while check_blas.py does | <p>I'm running a Logistic Regression classifier on Lasagne/Theano with multiple <strong>cpu</strong> cores.</p>
<p>This is my <em>~/.theanorc</em> file:</p>
<pre><code>[global]
OMP_NUM_THREADS=20
</code></pre>
<p>theano/misc/<strong>check_blas.py</strong> consumes all 20 cores but my script doesn't.
when I run:</p>
... | <p>I found the reason. Besides <em>OMP_NUM_THREADS=20</em>, <strong>openmp=True</strong> should also be set in the ~/.theanorc file and now it consumes all the 20 cores.
My <strong>~/.theanorc</strong> file now looks like:</p>
<pre><code>[global]
OMP_NUM_THREADS=20
openmp=True
</code></pre> | numpy|theano|keras|multicore|lasagne | 4 |
3,866 | 37,186,066 | Python: Running maximum by another column? | <p>I have a dataframe like this, which tracks the value of certain items (ids) over time:</p>
<pre><code>mytime=np.tile( np.arange(0,10) , 2 )
myids=np.repeat( [123,456], [10,10] )
myvalues=np.random.random_integers(20,30,10*2)
df=pd.DataFrame()
df['myids']=myids
df['mytime']=mytime
df['myvalues']=myvalues
+------... | <p>Here you go. Assumption is mytime is sorted.</p>
<pre><code>mytime=np.tile( np.arange(0,10) , 2 )
myids=np.repeat( [123,456], [10,10] )
myvalues=np.random.random_integers(20,30,10*2)
df=pd.DataFrame()
df['myids']=myids
df['mytime']=mytime
df['myvalues']=myvalues
groups = df.groupby('myids')
df['run_max_group'] = ... | python|numpy|pandas|max | 2 |
3,867 | 37,578,346 | Extract Values from heavily nested list of dictionaries with duplicate key value pairs | <p>Trying to extract Total Cash and Cash Equivalent values from complex and messy list of dictionaries. A shortened version of the structure follows below. </p>
<p>I've tried: maps, Dataframe.from_dict & .from_records. Trying to avoid using RE.</p>
<p>I'm stumped.</p>
<p><div class="snippet" data-lang="js" data-... | <p>If you know that the data will have exactly the format from above and you really just need these two values, you can access it directly (assuming <code>data</code> is your above structure):</p>
<pre><code>print data[0]['Rows'][2]['Rows'][3]['Cells'][1]['Value']
print data[0]['Rows'][2]['Rows'][3]['Cells'][2]['Value... | python|dictionary|pandas | 1 |
3,868 | 41,701,884 | How to efficiently set values of numpy array using indices and boolean indexing? | <p>What is the most efficient way to use a mask to select elements of a multidimensional numpy array, when the mask is to be applied with an offset? For example:</p>
<pre><code>import numpy as np
# in real application, following line would read an image
figure = np.random.uniform(size=(4, 4)) # used as a mask
canvas... | <p>The problem, it seems, is that using the arrays returned by <code>np.ix_</code> as index means you are doing advanced indexing, and, <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer">as the documentation of NumPy states</a>:</p>
<blockquote>
<p>A... | python|numpy|multidimensional-array | 2 |
3,869 | 37,869,744 | Tensorflow LSTM Regularization | <p>I was wondering how one can implement l1 or l2 regularization within an LSTM in TensorFlow? TF doesn't give you access to the internal weights of the LSTM, so I'm not certain how one can calculate the norms and add it to the loss. My loss function is just RMS for now.</p>
<p>The answers <a href="https://stackoverfl... | <p>The answers in the link you mentioned are the correct way to do it. Iterate through <code>tf.trainable_variables</code> and find the variables associated with your LSTM.</p>
<p>An alternative, more complicated and possibly more brittle approach is to re-enter the LSTM's variable_scope, set reuse_variables=True, an... | tensorflow|lstm | 1 |
3,870 | 31,674,195 | plot normal distribution given mean and sigma - python | <p>I have some data in pandas dataframe</p>
<pre><code>df['Difference'] = df.Congruent.values - df.Incongruent.values
mean = df.Difference.mean()
std = df.Difference.std(ddof=1)
median = df.Difference.median()
mode = df.Difference.mode()
</code></pre>
<p>and I want to plot a histogram together with normal distributio... | <p>You can use matplotlib/pylab with <code>scipy.stats.norm.pdf</code> and pass the mean and standard deviation as <code>loc</code> and <code>scale</code>:</p>
<pre><code>import pylab
import numpy as np
from scipy.stats import norm
x = np.linspace(-10,10,1000)
y = norm.pdf(x, loc=2.5, scale=1.5) # for example
pylab... | python|pandas|matplotlib|plot|seaborn | 7 |
3,871 | 31,254,392 | Sorting a scipy.stats.itemfreq result containing strings | <p><strong>The Problem</strong></p>
<p>I'm attempting to count the frequency of a list of strings and sort it in descending order. <code>scipy.stats.itemfreq</code> generates the frequency results which are output as a numpy array of string elements. This is where I'm stumped. How do I sort it?</p>
<p>So far I have t... | <p>It is unfortunate that <code>itemfreq</code> returns the unique items <em>and</em> their counts in the same array. For your case, it means the counts are converted to strings, which is just dumb.</p>
<p>If you can upgrade numpy to version 1.9, then instead of using <code>itemfreq</code>, you can use <code>numpy.un... | python|arrays|sorting|numpy|scipy | 2 |
3,872 | 64,362,395 | processing a dataframe in parallel | <p>I have a process that requires each row of a dataframe processed and then a new value appended to each row. It's a large dataframe and taking hours to process one dataframe at a time.</p>
<p>If I have a iterrow loop that sends each row to a function, can I parallize my processing for a speedup? The results of the ro... | <p>While iterating over rows isnt good practice and there can be alternate logics with grouby/transform aggregations etc, but if in worst case you really need to do so, follow the answer. Also, you might not need to reimplement everything here and you can use libraries like <a href="https://dask.org/" rel="nofollow nor... | python|pandas | 1 |
3,873 | 64,418,138 | Snowflake pandas Connector Kills Kernel | <p>I'm having trouble with the pandas connector for Snowflake.</p>
<p>The last line of this code causes the immediate death of the python kernel. Any suggestions on how to diagnose such a situation?</p>
<pre><code>import pyarrow
import snowflake.connector
import pandas as pd
ctx = snowflake.connector.connect(
use... | <p>This worked for me:</p>
<pre><code>import pandas as pd
from snowflake.connector import connect
qry = "SELECT * FROM TABLE LIMIT 5"
con = connect(
account = 'ACCOUNT',
user = 'USER',
password = 'PASSWORD',
role= 'ROLE',
warehouse = 'WAREHOUSE',
database = 'DATABASE',
schema = 'SCHEMA'
)
d... | pandas|jupyter|snowflake-cloud-data-platform | 1 |
3,874 | 47,687,872 | pandas.DataFrame.replace doesn't seems to work | <p>I'm currently working on Kaggle's Titanic Survival Prediction.
There's a problem when I wanted to encode the 'Sex' feature to 0 or 1.
I've followed the official documentation on Pandas but it's does not help.</p>
<p>Edit: I've noticed that I wrote 'Male' instead of 'male' but still not working after i change to 'ma... | <p>Try this: </p>
<pre><code>df['Sex'] = df['Sex'].replace(['male', 'female'], [1,0])
</code></pre>
<p>or this</p>
<pre><code>df['Sex'].replace(['male', 'female'], [1,0], inplace=True)
</code></pre>
<p>The problem is that you've set inplace=True while performing an assignment. This will change the series in place (... | python|pandas|dataframe|machine-learning | 4 |
3,875 | 47,884,987 | pandas create a Boolean column for a df based on one condition on a column of another df | <p>I have two <code>df</code>s, <code>A</code> and <code>B</code>. <code>A</code> is like,</p>
<pre><code>date id
2017-10-31 1
2017-11-01 2
2017-08-01 3
</code></pre>
<p><code>B</code> is like,</p>
<pre><code>type id
1 1
2 2
3 3
</code></pre>
<p>I like to create a new boolean column ... | <p>First merge <code>A</code> and <code>B</code> on <code>id</code> -</p>
<pre><code>i = A.merge(B, on='id')
</code></pre>
<p>Now, compute <code>has_b</code> - </p>
<pre><code>x = i.type.ne(1)
y = (pd.to_datetime('today') - i.date).dt.days.gt(90)
i['has_b'] = (x & y)
</code></pre>
<p>Merge back <code>i</code> a... | python-3.x|pandas|dataframe | 1 |
3,876 | 58,864,339 | skimage rotated image displays as black | <p>I'm trying to do a simple rotation of a sample image, but when I try to display it, the file just shows black pixels. I can tell that it has rotated, because the dimensions are changed properly.</p>
<pre><code>from io import BytesIO
import numpy as np
from PIL import Image
from skimage.transform import rotate
from ... | <p>scikit-image automatically converts images to floating point any time that interpolation or convolution is necessary, to ensure precision in calculations. In converting to float, the range of the image is converted to [0, 1]. You can read more about how it treats data types here:</p>
<p><a href="https://scikit-imag... | numpy|python-imaging-library|scikit-image|numpy-ndarray | 2 |
3,877 | 58,837,753 | For loop is not giving expected output using pandas DataFrame | <p>I want to write a bill program where i want the cgst, sgst from the bill as output. All was going fine but i got stuck on a problem. I want separate names of product from the result of dataframe's output but i am getting only the name of only one product but the amount was sum of two...</p>
<p><strong>Here's my cod... | <p>In each iteration of your loop you are creating a new data frame with only this loops data and overwitting any data that was in the last data frame. So when you finish your loops and print the dataframe all thats in it is the data from the last iteration of the loop since you created a new dataframe on each iteratio... | python|python-3.x|pandas | 0 |
3,878 | 70,291,074 | pandad reader :TypeError: only integer scalar arrays can be converted to a scalar index | <p>I am facing an error on this, how to I solve it? I think its on the reshape part but I'm not sure about it.</p>
<pre><code> dataset = data.values
print(len(dataset))
training_data_size = math.ceil(len(dataset)*.7)
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(datas... | <p>you are missing shape in the second element of tuple</p>
<pre><code>x_train = np.reshape(x_train,(x_train.shape[0],x_train[1],1))
</code></pre>
<p>correct :</p>
<pre><code>x_train = np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1))
</code></pre> | python|numpy | 1 |
3,879 | 70,240,761 | Changing row values based on previous row values | <p>I have a dataframe which looks like this:</p>
<pre><code>Province Admissions
Eastern Cape 10
Private 3
Public 7
Free State 20
Private 15
Public 5
</code></pre>
<p>I want to change the 'Private' and 'Public' to reference the ... | <p>You can do <code>mask</code> and <code>ffill</code> create the adding array</p>
<pre><code>s = df.Province.mask(df.Province.isin(['Private','Public'])).ffill()
df['Province'] = np.where(df.Province.isin(['Private','Public']), s + ' ' + df.Province, df.Province)
</code></pre> | python|pandas | 2 |
3,880 | 55,750,229 | How to Save a Data Frame as a table in SQL | <p>I have a SQL Server on which I have databases that I want to use pandas to alter that data. I know how to get the data using pyodbc into a DataFrame, but then I have no clue how to get that DataFrame back into my SQL Server.</p>
<p>I have tried to create an engine with sqlalchemy and use the <code>to_sql</code> com... | <p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html" rel="nofollow noreferrer">use pandas.DataFrame.to_sql</a> to insert your dataframe into SQL server. Databases supported by <a href="https://docs.sqlalchemy.org/en/13/core/engines.html" rel="nofollow noreferrer">... | sql-server|pandas|pyodbc | 2 |
3,881 | 55,923,126 | How to efficiently save a large pandas.Dataframe with million even billion rows with no error? | <p>How to save a large Dataframe to disk with good reading speed?</p>
<p>I have a large datasets (youtube 8M), now I have extract the raw data to dict. And I want to save it as dataframe for reading by index with pytorch dataset.</p>
<p>For concrete, the validate data seems like this:</p>
<pre class="lang-py prettyp... | <p>Joblib and klepto python packages might help you.</p>
<p>On other hand, you do chunking store at-max you can in one chunk while storing and load iteratively and merge at the end.</p> | python|pandas|csv|hdf5 | 0 |
3,882 | 55,728,846 | Merge 3 pandas based on key columns | <p>I am new to pandas I have 3 CSV files extracted from a MySql database and stored in pandas dataframes. I have generated a sequential id for all the 3 files they look like this:</p>
<pre><code>df1
id1 key_column1 name1
1 567 qqq
2 898 rrr
3 345 bbb
df2
id2 key_column2 name2
4 967 ... | <p>This seems like it works for me.</p>
<pre><code>df3.merge(df1,how='left',on='key_column1').merge(df2,how='left',on='key_column2')
id3 key_column1 key_column2 id1 name1 id2 name2
0 7 345 967 3 bbb 4 qqqq
1 8 567 945 1 qqq 6 bbbb
</code></pre> | python|pandas | 1 |
3,883 | 64,702,326 | How to ignore NaN in column length check | <p>I am trying to calculate the maximum and minimum length of each column in a dataframe which has some missing values. Pandas treat those missing values as "NaN" and counts the length as 3. How do I completely ignore missing values while calculating maximum and minimum length?
Here is my code:</p>
<pre><code... | <p>Taking method from previous answer, but you may want to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">pandas.fillna()</a> to get rid of NaN's and convert each value into string before counting min and max lengths.
My suggestions is:</p... | python|pandas|dataframe | 2 |
3,884 | 64,628,281 | fatal error: numpy/arrayobject.h: No such file or directory #include "numpy/arrayobject.h" in google colab | <p>hello i am trying to run a git repo in google colab,
i installed all requirements as per the git instruction</p>
<p>while running the certain file i am getting this error</p>
<p>fatal error: numpy/arrayobject.h: No such file or directory<br />
#include "numpy/arrayobject.h"</p>
<p>i already checked solutio... | <p>I had a similar problem and I solved it by editing <code>build.py</code>:</p>
<pre><code>ext_modules=[
Extension("my_module", ["my_module.c"],
include_dirs=[numpy.get_include()]),
]
</code></pre>
<p>Here <code>include_dirs=[numpy.get_include()]</code> is the part tha... | python|python-3.x|numpy|jupyter-notebook|google-colaboratory | 1 |
3,885 | 64,618,229 | Using Python Selenium to download a file in memory, not in disk | <p>I have a bunch of scripts that do web scraping, download files, and read them with pandas. This process has to be deployed in a new architecture where download the files on disk is not appropriate, instead is preferable to save the file in memory and read it with pandas from there. For demonstration purposes I leave... | <p>Your question can be accomplished by adding the <em>selenium add_experimental_option</em>.
I also redesigned your code to loop through the table to extract the href to pass them to StringIO. No files are downloaded to my local system using this code.</p>
<p>If I missed something please let me know.</p>
<pre><code>im... | python|pandas|selenium|selenium-webdriver | 6 |
3,886 | 40,226,883 | I don't understand the usage of 'Lambda' and 'Transform' and from this code (pandas docs) | <p>I am scouring the pandas docs to try to understand how transform is used and can upon this example from the docs:
<a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/groupby.html</a> (under 'Transformation")</p>
<pre><code>import pandas as pd... | <p>using <code>key = lambda x: x.year</code> implies that your index is of <code>dtype='datetime64[ns]'</code></p>
<p>this would call the year of each index and group the df by year.</p>
<p>now that you have a groupby object you can transform each group:</p>
<pre><code>zscore = lambda x: (x - x.mean()) / x.std()
</c... | pandas|lambda|transform | 3 |
3,887 | 39,788,542 | Distributed Tensorflow Training of Reinpect Human detection model | <p>I am working on Distributed Tensorflow, particularly the implementation of Reinspect model using Distributed Tensorflow given in the following paper <a href="https://github.com/Russell91/TensorBox" rel="nofollow">https://github.com/Russell91/TensorBox</a> .</p>
<p>We are using Between-graph-Asynchronous implementat... | <p>In general, I wouldn't be surprised if moving from a single-process implementation of a model to a multi-machine implementation would lead to a slowdown. From your question, it's not obvious what might be going on, but here are a few general pointers:</p>
<ul>
<li><p>If the model has a large number of parameters re... | computer-vision|tensorflow|distributed|multi-gpu | 2 |
3,888 | 39,500,258 | Pandas: how to get the unique values of a column that contains a list of values? | <p>Consider the following dataframe</p>
<pre><code>df = pd.DataFrame({'name' : [['one two','three four'], ['one'],[], [],['one two'],['three']],
'col' : ['A','B','A','B','A','B']})
df.sort_values(by='col',inplace=True)
df
Out[62]:
col name
0 A [one two, three four]
2 ... | <p>Here is the solution </p>
<pre><code>df['unique_list'] = df.col.map(df.groupby('col')['name'].sum().apply(np.unique))
df
</code></pre>
<p><a href="https://i.stack.imgur.com/S8IdI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S8IdI.png" alt="enter image description here"></a></p> | python|pandas | 4 |
3,889 | 39,824,469 | Replacing Elements in 3 dimensional Python List | <p>I've a Python list if converted to NumPy array would have the following dimensions: (5, 47151, 10)</p>
<pre><code>np.array(y_pred_list).shape
# returns (5, 47151, 10)
len(y_pred_list)
# returns 5
</code></pre>
<p>I would like to go through every element and replace the element where:</p>
<ul>
<li>If the element... | <p>To create an array with a value True if the element is >= 0.5, and False otherwise:</p>
<pre><code>new_array = y_pred_list >= 0.5
</code></pre>
<p>use the .astype() method for Numpy arrays to make all True elements 1 and all False elements 0:</p>
<pre><code>new_array.astype(int)
</code></pre> | python|arrays|list|numpy | 1 |
3,890 | 44,245,229 | Drop duplicates with less precision | <p>I have a pandas DataFrame with string-columns and float columns I would like to use <code>drop_duplicates</code> to remove duplicates. Some of the duplicates are not exactly the same, because there are some slight differences in low decimal places. How can I remove duplicates with less precision?</p>
<p>Example:</p... | <p>round them</p>
<pre><code>df.loc[df.round().drop_duplicates().index]
result text
0 1.000001 aaa
2 2.000000 aaa
3 2.000000 bb
</code></pre> | python|pandas | 3 |
3,891 | 44,353,509 | Tensorflow tf.constant_initializer is very slow | <p>Trying to use pre trained word2vec embeddings of 100 dim for training a LSTM </p>
<pre><code>@staticmethod
def load_embeddings(pre_trained_embeddings_path, word_embed_size):
embd = []
import time
start_time = time.time()
cnt = 4
with codecs.open(pre_trained_embeddings_path, mode="r", encoding='u... | <p>Loading large constants into a graph is not only slower, it also leaks lots of memory. I had a similar issue which <a href="https://github.com/tensorflow/tensorflow/issues/9742" rel="nofollow noreferrer">I reported not long ago</a> and the best workaround for me was:</p>
<pre><code># placeholder for loading your sa... | python|tensorflow|lstm|word2vec | 0 |
3,892 | 44,006,497 | Check values in dataframe against another dataframe and append values if present | <p>I have two dataframes as follows:</p>
<pre><code>DF1
A B C
1 2 3
4 5 6
7 8 9
DF2
Match Values
1 a,d
7 b,c
</code></pre>
<p>I want to match DF1['A'] with DF2['Match'] and append DF2['Values'] to DF1 if the value exists</p>
<pre><code>So my result will be:
A B C Values
1 2... | <p>Instead of doing a lookup, you can do this in one step by merging the dataframes:</p>
<p><code>pd.merge(df1, df2, how='inner', left_on='A', right_on='Match')</code></p>
<p>Specify <code>how='inner'</code> if you only want records that appear in both, <code>how='left'</code> if you want all of df1's data.</p>
<p>I... | python|pandas | 3 |
3,893 | 44,087,637 | Pandas how does IndexSlice work | <p>I am following this tutorial: <a href="https://github.com/TomAugspurger/pydata-chi-h2t/blob/master/3-Indexing.ipynb" rel="noreferrer">GitHub Link</a></p>
<p>If you scroll down (Ctrl+F: Exercise: Select the most-reviewd beers ) to the section that says <code>Exercise: Select the most-reviewd beers</code>:</p>
<p>Th... | <p>To complement the previous answer, let me explain how <code>pd.IndexSlice</code> works and why it is useful.</p>
<p>Well, there is not much to say about its implementation. As you read in the <a href="https://github.com/pandas-dev/pandas/blob/main/pandas/core/indexing.py" rel="nofollow noreferrer">source</a>, it jus... | python|pandas | 16 |
3,894 | 69,543,880 | How to create sum of binary dummy variable grouped by month in pandas? | <p>I have a dataframe</p>
<pre><code>Month | Acct_id| Sku
2020-01-01 |1 |book
2020-01-02 |2 |phone
2020-01-01 |3 |book
</code></pre>
<p>Now, I want to create dummies of the "Sku" column and sum of the resulting binary values when grouping by month. Additionally, I also want to... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a></p>
<pre><code>res = pd.crosstab(index=df["Month"], columns=df["Sku"], margins=True, margins_name="total_counts").drop("total_counts")
print(res)... | python|pandas | 1 |
3,895 | 69,556,486 | How to expand pandas column containing values in arrays to multiple columns? | <p>I have a data frame with column named 'gear' which contains lists of values... what i want to do now is to move each element in every list to the corresponding column.
<a href="https://i.stack.imgur.com/Sa25i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sa25i.png" alt="enter image description h... | <p>Try <code>explode</code>, then <code>groupby().value_counts()</code>:</p>
<pre><code>#sample data
df = pd.DataFrame({'col':[['a','b','c'], ['a','c','x'],[],['b','x','y']]})
(df['your_list_col'].explode()
.groupby(level=0).value_counts()
.unstack(fill_value=0)
.reindex(df.index, fill_value=0)
)
</code></pr... | arrays|pandas|list|dataframe|mapping | 1 |
3,896 | 54,110,888 | How can I vectorize my function to speed up the operation on my dataframe? | <p>I have a dataframe (below, i.e, membership), one field (A) has some row with the value in a sorted manner. There is also a new field (new) which at the beginning of the process is a copy of the field <code>C</code>. What I would like to do is that, if the previous row in <code>A</code> is the same as the current row... | <p>IIUC, Let me explain a little logic and see if this matches.</p>
<p>If in any group of A, a value of C is equal to 1, then assign to the last records in that group a value of 1 to column 'new'. </p>
<pre><code>membership['new'] = membership.groupby('A')['C']\
.transform(lambda x: np.w... | python|pandas|dataframe|data-science | 0 |
3,897 | 53,870,486 | Fastest way to add rows to existing pandas dataframe | <p>I'm currently trying to create a new csv based on an existing csv.</p>
<p>I can't find a faster way to set values of a dataframe based on an existing dataframe values.</p>
<pre><code>import pandas
import sys
import numpy
import time
# path to file as argument
path = sys.argv[1]
df = pandas.read_csv(path, sep = "\... | <p>Indeed, using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> will do what you look for such as:</p>
<pre><code>import pandas as pd
new_df = pd.pivot(df.datetime, df.name + '-' + df.type, df.response_time)
print (new_df.he... | python|pandas | 3 |
3,898 | 38,445,281 | creating text file with multiple arrays of mixed types python | <p>I am trying to create a text file with multiple array as the columns in this file. The trick is that each array is a different datatype. For example:</p>
<pre><code>a = np.zeros(100,dtype=np.int)+2 #integers all twos
b = QC_String = np.array(['NA']*100) #strings all 'NA'
c = np.ones(100,dtype=np.float)*99.9999 #flo... | <p>I recommending using <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> to accomplish this task, which can easily handle multiple data types while writing out a new text file.</p>
<pre><code>import numpy as np
import pandas as pd
# Create an empty DataFrame
df = pd.DataFrame()
# Populate columns in the... | python|arrays|file|numpy|text | 2 |
3,899 | 66,094,075 | Filtering all entries on today's date (pandas) | <p>I want to filter out all the rows in my data that have today's date in a column.</p>
<p>The (Fixture,Date) column has pandas datetime type of values.</p>
<pre><code>0 2021-05-02
1 2021-06-02
2 2021-06-02
3 2021-06-02
4 2021-06-02
189 2021-06-02
190 2021-06-02
191 2021-07-02
192 2021-0... | <p>Your error is that you misunderstand the date format. 2021-08-02 means August 2nd, 2021 not February 8th, 2021 (which may now be today in some time zones).</p>
<p>Your code is fine, your dates aren't.</p>
<p>Edit:</p>
<p>To answer the source problem, which seems to be your ingestion of a CSV file. I have had some su... | python|pandas|dataframe|datetime | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.