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
357,200
60,513,469
PyTorch FasterRCNN TypeError: forward() takes 2 positional arguments but 3 were given
<p>I am working on object detection and I have a dataset containing images and their corresponding bounding boxes (ground-truth values).</p> <p>I actually have built my own feature extractor which takes an image as input and outputs a feature map(basically an encoder-decoder system where the final output of the decode...
<p>This is because only the image inputs should be passed into the models, instead of both images and the ground truth targets. So instead of doing <code>output = model(images, targets)</code>, you can do <code>output = model(images)</code>.</p> <p>As for why the error message talks about being given 3 positional argu...
python|pytorch|object-detection|faster-rcnn|torchvision
2
357,201
60,609,673
How to fine tune BERT to summarize articles
<p>I'm learning nlp, and as a study project, i'm trying to face the <a href="https://www.kaggle.com/sunnysai12345/news-summary" rel="nofollow noreferrer">news summarization dataset</a>, using BERT.</p> <p>The dataset is simple (in the news_summary_more.csv) - it has <strong>articles</strong> and <strong>headlines</str...
<p>f1_score would the right measure for such a dataset</p>
nlp|artificial-intelligence|tensorflow2.0|word2vec|summarization
0
357,202
60,421,221
PyTorch: Convolving a single channel image using torch.nn.Conv2d
<p>I am trying to use a convolution layer to convolve a grayscale (single layer) image (stored as a numpy array). Here is the code:</p> <pre><code>conv1 = torch.nn.Conv2d(in_channels = 1, out_channels = 1, kernel_size = 33) tensor1 = torch.from_numpy(img_gray) out_2d_np = conv1(tensor1) out_2d_np = np.asarray(out_2d_...
<p>pytorch's <code>Conv2d</code> expects its 2D inputs to actually have <strong>4</strong> dimensions: mini-batch dim, channel dim, and the two spatial dimensions.<br> Your input tensor has only two spatial dimensions and it lacks the mini-batch and channel dimensions. In your case these two dimensions are actually sin...
pytorch|conv-neural-network|convolution|tensor
4
357,203
60,392,087
Merge two pandas dataframes where one is a subset of the other (or populate only a subset of columns)
<p>I want to update a sheet every time a certain process executes, but the data I have is missing some columns. My idea was to get all the columns names from the sheet, constructing an empty dataframe with these columns, and then merging it with my actual data (with columns renamed so as to match the ones in the sheet)...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html" rel="nofollow noreferrer"><code>df.append</code></a>:</p> <pre><code>&gt;&gt;&gt; df1.append(df2, sort=True) col0 col1 col2 col3 col4 col5 col6 col7 0 NaN 1 2 NaN 4 NaN NaN 7 </code></pre>
python|pandas|dataframe
1
357,204
60,631,240
find correlation between pandas time series
<p>I have two pandas data frames which I have taken from only one column and set dates column as index, so now I have two <strong>Series</strong> instead. I need to <strong>find the correlation for those Series</strong>.</p> <p>Here are a few rows from<code>dfd</code>:</p> <pre><code>index change 2018-12-31 -0....
<p>Problem is <code>dfp</code> is filled by string repr of numbers, so use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="nofollow noreferrer"><code>Series.astype</code></a> for convert to floats:</p> <pre><code>correlation=dfp.astype(float).corr(dfd.astype(float) pr...
python|pandas|dataframe|time-series|correlation
5
357,205
60,589,279
Tf 2.0 MirroredStrategy on Albert TF Hub model (multi gpu)
<p>I'm trying to run Albert Tensorflow hub version on multiple GPUs in the same machine. The model works perfectly on single GPU. </p> <p>This is the structure of my code:</p> <pre><code>strategy = tf.distribute.MirroredStrategy() print('Number of devices: {}'.format(strategy.num_replicas_in_sync)) # it prints 2 .. c...
<p>Two-part answer:</p> <p>1) TF Hub hosts two versions of ALBERT (each in several sizes):</p> <ul> <li><p><a href="https://tfhub.dev/google/albert_base/3" rel="nofollow noreferrer">https://tfhub.dev/google/albert_base/3</a> etc. from the Google research team that originally developed ALBERT comes in the <a href="htt...
tensorflow|tf.keras|multi-gpu|pre-trained-model|tensorflow-hub
1
357,206
60,517,804
python dataframe parsing using pandas
<p>I have a data frame as a sample below which is imported from csv. I'd like to extract first 6 letters as mentioned in the output and would like output as dataframe format only. </p> <p>Tab delimited Input:</p> <pre><code>123456789_abcd_dd 3456434534_abelom_ad 123987323_tyewer_qwer 562329872_zcxvzcv_mnbcc 345345345...
<p>If you need the exact same transformation for all values, you can use <code>applymap</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': ['123456789_abcd_dd', '345345345_abcd_dd'], 'B': ['3456434534_abelom_ad', '6834512342_llllom_ad'], 'C': ['123987323_tyewer_qwer', '368887323_jnb...
pandas|dataframe
0
357,207
60,470,700
Datetime fails when setting astype, date mangled
<p>I am importing a csv of 20 variables and 1500 records. There are 5 date columns that are in UK date format dd/mm/yyyy , and import as .str I need to be be able to subract one date from another.They are hsopital admissions, - I need to subtract discharge date from admission date to get length of stay. I have has a n...
<p><code>to_datetime</code> is the function you want. It does not support multiple columns so you just loop over the columns one by one. The strings are in UK format (day-first) so you simply tell <code>to_datetime</code> that:</p> <pre><code>df = pd.read_csv('/path/to/file.csv', usecols = ['ADMIDATE','DISDATE']).repl...
python|pandas|date|datetime
1
357,208
60,719,524
How can I determine the scale range in y axis in Seaborn Line Graph
<p>I want to arrange the values of y-axis in seaborn graph. I want to increase number in such kind of order -> 100,1000,10000</p> <p>How can I do that.</p> <p>I can use this seaborn graph code defined below.</p> <pre><code>ax = sns.lineplot </code></pre>
<p>You can use <code>ax.set_yticks</code> and pass a list of ticker values you want to set on y axis (and <code>ax.set_xticks</code> for x axis)</p> <pre><code>ax = sns.lineplot(x, y); ax.set_yticks([100,1000,10000]) </code></pre> <p>And of course you can generate your list using list comprehension</p> <pre><code>yt...
python|pandas|seaborn
1
357,209
60,739,251
When does a tensor output a value and when does it output a tensor object?
<p>I have had some experience with creating Neural networks graphs with input as tensorflow placeholders . Until now , i used to believe that those graphs could be evaluated with something like <code>sess.run()</code> or more precisely as described <a href="https://stackoverflow.com/questions/33633370/how-to-print-the-...
<p>Yes, this is because of the different versions of the tensorflow. </p> <p>In <strong>tensorflow version 1.14</strong> the output on running <strong>your code</strong> is as below(have added the print of tf version), </p> <pre><code>tensorflow version: 1.14.0 &lt;tf.Tensor 'sequential_3/dense_7/BiasAdd:0' shape=(1,...
python|tensorflow
1
357,210
60,405,263
Python Numpy in which Voxel is the Point?
<p>I have a Point-Cloud saved in a Numpy-Array like this: [[x1,y1,z1],[x2,y2,z2],....] Now I want to create a voxel grid with a grid size that I can change. After that Iwanna know all the Voxel in which a Point is. Is there a Numpy Method that could help me do that fast, the only idea i had so far was by solving it...
<p>If I understand you correcly one way you could populate a 3d numpy array with a set of 3d points is by using indexing.</p> <p>This will work as long as your grid size is at least as big as your largest xyz value along each axis.</p> <p>Note that your data will loose precision when voxelising in this way.</p> <pre><c...
python|numpy
2
357,211
60,472,196
Get column name based on condition in pandas
<p>I have a dataframe as below: <a href="https://i.stack.imgur.com/TgkOg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TgkOg.png" alt="enter image description here" /></a></p> <p>I want to get the name of the column if column of a particular row if it contains 1 in the that column.</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dot.html" rel="noreferrer"><code>DataFrame.dot</code></a>:</p> <pre><code>df1 = df.dot(df.columns) </code></pre> <p>If there is multiple <code>1</code> per row:</p> <pre><code>df2 = df.dot(df.columns + ';').str.rstrip(';') </c...
python|python-3.x|pandas|machine-learning
11
357,212
60,553,500
pandas value_counts with bins applied to a groupby produces incorrect results
<p>I can't see why value_counts is giving me the wrong answer. Here is a small example:</p> <pre><code>In [81]: d=pd.DataFrame([[0,0],[1,100],[0,100],[2,0],[3,100],[4,100],[4,100],[4,100],[1,100],[3,100]],columns=['key','score']) In [82]: d Out[82]: key score 0 0 0 1 1 100 2 0 100 3 2 ...
<p>Here is another way of doing it to keep the integrity of the indexes.</p> <pre><code>d.groupby('key')['score'].apply(pd.Series.value_counts, bins=[0,20,40,60,80,100]) </code></pre> <p>Output:</p> <pre><code>key 0 (80.0, 100.0] 1 (-0.001, 20.0] 1 (60.0, 80.0] 0 (40.0, ...
python|pandas
3
357,213
60,656,832
Syntax error when assigning an absolute path using pandas
<p>I am trying to import and graph a .csv dataset using pandas, though when assigning the file path for the csv to be read, It reads as: </p> <pre><code> File "C:\Users\17024\test.py", line 5 dataframe = pd.read_csv(C:/PY_ABS_PATH) ^ SyntaxError: invalid syntax </code></pre> <p>The code...
<p>You can call it as a raw string using 'r' and quotes like</p> <pre><code>dataframe = pd.read_csv(r'C:/PY_ABS_PATH/scottish_hills.csv') </code></pre> <p>or by replacing a single frontslash with double backslashes and adding quotes</p> <pre><code>dataframe = pd.read_csv('C:\\PY_ABS_PATH\\scottish_hills.csv') </code...
python|pandas
1
357,214
60,655,280
How to split an image dataset in X_train, y_train, X_test, y_test by tensorflow?
<p>How can I split the image data into X_train, Y_train, X_test and Y_test?</p> <p>I am using keras with tensorflow backend</p> <p>Thanks.</p>
<p>For example, you have folder like this</p> <pre><code>full_dataset |--horse (40 images) |--donkey (30 images) |--cow ((50 images) |--zebra (70 images) </code></pre> <p>FIRST WAY</p> <pre><code>import glob horse = glob.glob('full_dataset/horse/*.*') donkey = glob.glob('full_dataset/donkey/*.*') cow = glob.glob('fu...
tensorflow|image-processing|keras|artificial-intelligence
5
357,215
60,340,948
Pandas - how to sort week and year numbers formatted as strings?
<p>I have a pandas dataframe like this, which sorted like:</p> <pre><code>&gt;&gt;&gt; weekly_count.sort_values(by='date_in_weeks', inplace=True) &gt;&gt;&gt; weekly_count.loc[:9,:] date_in_weeks count 0 1-2013 362 1 1-2014 378 2 1-2015 201 3 1-2016 294 4 1-2017 300 5 1-2018 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.argsort.html" rel="nofollow noreferrer"><code>Series.argsort</code></a> with converted to datetimes with format <code>%W</code> week number of the year, <a href="https://strftime.org/" rel="nofollow noreferrer">link</a>:</p> <pre><...
python|pandas|dataframe|sorting|data-analysis
5
357,216
60,372,143
How to replace word in array of text in Python?
<p>I want to stem my text with my own array:</p> <pre class="lang-py prettyprint-override"><code>word_list1 = ["cccc", "bbbb", "aaa"] def stem_text(text): text = text.split() array = np.array(text) temp = np.where(array == word_list1, word_list1[0], array) text = ' '.join(temp) return text </...
<pre><code>word_list1 = ["cccc", "bbbb", "aaa"] def stem_text(text): text = text.split() for keyword in word_list1: text.replace(keyword, word_list1[0]) text = ' '.join(temp) return text </code></pre> <p>You can just run a replace on it. If it exists (<code>if keyword in text</code>) it will replace. Bu...
python|numpy|nlp|stemming
0
357,217
60,736,447
Setting x-axis manually
<p>I want to make 5 line plots, first should just include values from year 1960 and 5 dots (one for each country), next plot should include values from years 1960 and 1961 and line connecting values for each country, etc. Last plot should include values from all years. But I want x-axis to be constant from 1960 to 1964...
<p>The issue is that the years you provide are strings and not integers. The correct <code>xlim</code> is just <code>range(0, 5)</code>. The final two lines also set the <code>xticks</code> and <code>xticklabels</code> correctly.</p> <pre><code>years = list((range(1960,1965))) for i in years: yearsi = list((range(...
python|pandas|matplotlib
1
357,218
60,384,793
Python - preserve differing values in new column for near duplicate rows then delete duplicates
<p>I have a pandas dataframe that is the result of a query where 1 column creates duplicate rows. I need help identifying non-duplicate values for duplicates by name, then dynamically creating new columns with all values, then delete duplicates. Below Mike has duplicates in column "Code" and Mark in "Lang", so I'd like...
<p>We can mark the duplicates per group with <code>GroupBy</code>, <code>duplicated</code> and <code>cumsum</code> Then use <code>pivot_table</code> to pivot the rows to columns and finally we use <code>pd.concat</code> to get a single dataframe back:</p> <pre><code>columns = ['Code', 'Lang'] dfs = [] for col in colu...
python|pandas|dataframe|duplicates
1
357,219
60,627,975
How to fill minutes time series data with 0 in python?
<p>I've a dataset "nodup" as follows (not sorted by time). it's a subset from raw data, not sorted. I need to get a record by every 15 minutes, for example 08:15, 08:30, 08:45... but it only keeps records when occupancy = 1. </p> <p>What I need to do is to get occupancy=0, and auto fills the related newly generated co...
<p>I dont know what you are asking, but im going to answer based on the title</p> <p>(I dont understand why 10:17 would become 8:15 for example)</p> <pre><code>nodup = pandas.DataFrame({ 'time': pandas.date_range('2019-01-03 22:12:13','2019-05-08 11:11:27',periods=1000) }) </code></pre> <p>to make all the times h...
python|arrays|pandas|sorting
0
357,220
60,369,381
How do I remove whitespaces?
<p>I have a dataframe with a lot of special characters and multiple spaces. One column in particular has a lot of white spaces.</p> <p>It looks like this:</p> <p><a href="https://i.stack.imgur.com/jV3oQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jV3oQ.png" alt="enter image description here"></...
<p>I think there is something wrong with your code. Your function is getting an argument and in your case you are not passing a value for it.</p> <pre><code>def remove_whitespace(strings): x = strings.replace(" ", "") return x df['Clean'] = df[0].apply(remove_whitespace(strings)) </code></pre> <p><strong>App...
python|python-3.x|pandas
2
357,221
60,746,851
Sigmoid Function in Numpy
<p>For fast computations, I have to implement my sigmoid function in Numpy this is the code below </p> <pre><code> def sigmoid(Z): """ Implements the sigmoid activation in bumpy Arguments: Z -- numpy array of any shape Returns: A -- output of sigmoid(z), same shape as Z cache -- returns...
<p><strong>This worked for me.</strong> I think no need to use cache because you already initialized it. Try this code below.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np z = np.linspace(-10, 10, 100) def sigmoid(z): return 1/(1 + np.exp(-z)) a = sigmoid(z) plt.plot(z, a) plt.xlabel("z")...
numpy|sigmoid
7
357,222
60,600,085
Python - Obtain indices of intersecting values in two arrays
<p>If I have two arrays: </p> <pre><code>A=[1,2,3,4,5,6,7] B=[2,4,7] </code></pre> <p>I would like to obtain an array <code>C</code> that contains the indices of the the values of <code>B</code> also found in <code>A</code> </p> <pre><code>C=[1,3,6] </code></pre> <p>I'm quite new to Python and I'm frustra...
<p>Here's a linear-time solution: to efficiently test whether an element is in B, convert it to a set first.</p> <pre class="lang-py prettyprint-override"><code>B_set = set(B) C = [i for i, x in enumerate(A) if x in B_set] </code></pre> <p>For large inputs, this is better than using <code>.index</code> in a loop, sin...
python|python-3.x|list|numpy
4
357,223
60,711,659
Transforming a tf.data.dataset
<p>Let's say i have as source data a dataset of 32*32*3 images of type:</p> <p><code>&lt;DatasetV1Adapter shapes: {coarse_label: (), image: (32, 32, 3), label: ()}, types: {coarse_label: tf.int64, image: tf.uint8, label: tf.int64}&gt;</code></p> <p>After serializing the data i get:</p> <pre><code>&lt;MapDataset shap...
<p>You can get the image in uint8 by following the below steps. </p> <p>Create Serialized data.</p> <pre><code>list_ds = tf.data.Dataset.list_files("img_dir_path/*") </code></pre> <p>Create a function that will take the file_path as an argument and return the image in uint8 format.</p> <pre><code>def process_img(f...
python|tensorflow|machine-learning
0
357,224
60,709,832
Webscraping into Dataframes
<p>I'm new to Beautiful Soup and trying to scrape <a href="https://10times.com/losangeles-us/technology/conferences" rel="nofollow noreferrer">https://10times.com/losangeles-us/technology/conferences</a> and extract event data and their associated links.</p> <p>I've managed to scrape the event data and their links, bu...
<p>I added an check if there is information in "row" at the first block of code.</p> <pre><code>import bs4 as bs import urllib.request source = urllib.request.urlopen('https://10times.com/losangeles-us/technology/conferences').read() soup = bs.BeautifulSoup(source,'html.parser') table = soup.find('tbody') table_row...
python|pandas|beautifulsoup
0
357,225
60,428,712
How to edit the Pandas DataFrame as per the Required Template?
<p><a href="https://i.stack.imgur.com/00KXC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/00KXC.png" alt="This is the Original DataFrame."></a> <a href="https://i.stack.imgur.com/dE0WV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dE0WV.png" alt="Edit the Original DataFrame int...
<p>Suppose your df is:</p> <pre><code> Field A;mean;k B;mean;k A;std;k B;std;k 0 ct1 1 2 3 1 1 ct2 4 5 6 7 </code></pre> <hr> <pre><code>df.set_index('Field',inplace=True) df.columns = df.columns.str.split(';',expand=True, n=1) </code><...
python-3.x|pandas|dataframe
1
357,226
60,340,758
In pandas, how to open CSV with separators placed between sentences (in the wrong place)?
<p>In Python3 and pandas I want to open a CSV file with a separator ";" and enconding latin-1. It is a file without column names. The file can be seen <a href="https://drive.google.com/file/d/1dC9dxMsQoKUN04pGAI4UdKzibTr8gJJ6/view?usp=sharing" rel="nofollow noreferrer">here</a></p> <p>However, in a text editor I noti...
<p>You can use both separators with <code>delimiter=",|\";\""</code></p> <pre><code>import pandas as pd kwargs = {'sep': ';|\";\"', 'dtype': str, 'encoding': 'latin-1'} teste_2016 = pd.read_csv("/home/reinaldo/Documentos/Code/e_sic_federal/2016/20200215_Pedidos_csv_2016.csv", **kwargs) teste_2016.info() </code></pre>
python|pandas|csv|dataframe|separator
1
357,227
60,355,009
How to add two list with different length?
<p>I am trying to extract first and last element from array "x" and then repeat for five times then finally concatenate to original "x".</p> <p>Error: operands cannot be broadcast together with shapes (5,) (1000,)</p> <p>Here is the code</p> <pre><code>import numpy as np import random x= np.random.uniform(0, 1, 100...
<p>It is not clear what you are tying to achieve. There are not really two lists in your example. </p> <p>It seems like you're trying to do one of these two things:</p> <ul> <li>Add the first and last element (times 5) to all elements of the array</li> <li>Add the value of the previous and next elements (times 5) t...
python|numpy
0
357,228
60,710,315
Tensorflow 2 does not have a a fully_connected function How can I simulate that?
<p>I am making a CNN model to use for lane detection. But tensorflow 2 does not have tf.contrib therefore i cannot access the fully_connected layer. </p> <p>How can I make my own Fully connected layer function?</p> <p>This is my model so far:</p> <pre class="lang-py prettyprint-override"><code>conv2d = tf.nn.conv2d ...
<p>I think what you might be looking for is the Dense layer in the keras module - <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense</a></p>
python|deep-learning|tensorflow2.0
1
357,229
60,616,013
Pandas how to flatten columns after agg function?
<p>say I have a df:</p> <pre><code>data=[('a', 1), ('a', 1),('b', 1),('a', 3),('b', 2),('c', 1),('a', 2),('b', 3),('a', 2)] df=df=pd.DataFrame(data, columns=['project', 'duration']) # Then I made an aggregation: df_agg=df.groupby('project').agg({'duration': ['median', 'mean']}).reset_index() Out[11]: project dura...
<p>The <code>df_agg</code> dataframe has a MultiIndex for its columns. Only this has to be flattened.</p> <p>A trivial way is to convert it to a list and <code>join</code> each element:</p> <pre><code>df_agg.columns = ['_'.join(col) for col in df_agg.columns] </code></pre> <p>it gives:</p> <pre><code> project_ du...
python|pandas
3
357,230
60,752,926
How to use tensorflow.keras.preprocessing.image.ImageDataGenerator.flow_from_directory() in the model.fit()?
<p>Because I need train my model on the ImageNet with 1024 batchsize, I must use more than 2 GPUs, so I use the tf.distribute.MirroredStrategy() to trian, this Strategy can only use fit() not fit_generator(). However the ImageNet has large amount of data, I use the tensorflow.keras.preprocessing.image.ImageDataGenerato...
<p>I tried @Bashir Kazimi plan: </p> <pre><code>train_dataset = tf.data.Dataset.from_generator(make_train_generator, output_types=tf.float32, output_shapes=tf.TensorShape([224,224,3])) </code></pre> <p>then, another mistake: </p> <pre><code>Traceback (most recent call last): File "yolo3/models/backbones/imagenet_...
tensorflow|keras
-1
357,231
60,480,806
Invalid argument: indices[207,1] = 1611 is not in [0, 240) - Tensorflow 2.x (Python)
<p>I'm using a RNN <strong>LSTM model</strong> to classify personality types. I'm getting an unexpected indices error when I start to train the model. I tried to use some solutions using the tracebacks, but there is no information of this issue using TF 2.0.<br/><br/> I will leave my <a href="https://colab.research.goo...
<p>Check for the maximum value using <code>pd.DataFrame(x_train).max()</code></p> <p>I got 32552, so just add 32552+1 as input_dim</p> <pre><code>i.e input_dim = 32553 </code></pre>
python|tensorflow|keras|deep-learning
2
357,232
60,670,792
Use apply functions with classes
<p>I have created a function 'salary'. If salary is less than 30000, it will return 0; if salary is between 30000 and 40000, it will return 1; else if it is above 40000 it will return 2.</p> <pre class="lang-py prettyprint-override"><code>def salary(x): if x &lt; 30000: return 0 elif x &gt;= 30000 and ...
<p>If you are using a method from Class such in your case try this way:</p> <pre><code>df['salary_level']= df['salary'].apply(lambda x : Salary(x).sal()) </code></pre>
python|pandas|function|machine-learning
1
357,233
72,669,937
Viewing frequency of multiple values in grouped Pandas data frame
<p>I have a data frame with three column variables A,B,C, taking numeric values in {1,2}, {6,7}, and {11,12}. I would like to see the following. For what fraction of possible observed pairs (A,B) do we have both [observations for which C=11 and observations for which C=12].</p> <p>I start by entering the dataframe:</p>...
<p>Pass <code>normalize=True</code></p> <pre><code>out = df.groupby([&quot;A&quot;, &quot;B&quot;]).C.value_counts(normalize=True) Out[791]: A B C 1 6 11 0.75 12 0.25 7 11 1.00 2 6 12 1.00 7 12 1.00 Name: C, dtype: float64 </code></pre>
pandas|dataframe
0
357,234
72,571,584
pandas get data frame from uneven nested list
<p>I have a nested list</p> <pre><code>nl = [[['04-05-2021', '05-05-2021', '06-05-2021'],[2240, 3528, 2800]],[['03-05-2021', '04-05-2021', '05-05-2021'],[123032, 18312, 123872]]] </code></pre> <p>I want to convert it into a data frame that looks like this:</p> <pre><code>**Desired output is as follows:** DATE ...
<p>Use lsit comprehension with <code>Series</code> and pass to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>, last replace missing values:</p> <pre><code>df = pd.concat([pd.Series(b, index=a) for a, b in nl], axis=1).fillna(0).as...
python-3.x|pandas|list
1
357,235
72,549,925
I got error from calling json() when trying to running
<p>Hello i want asking somethin that i got when i tried to run my streamlit, so i got error like this on my frontend page, i import it from backend page: <a href="https://i.stack.imgur.com/b8r1z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b8r1z.png" alt="enter image description here" /></a></p> <...
<p>In your code, the conversion <code>res = r.json()</code> is unnecessary. Unless you really need this as JSON somewhere else, you can test the status code directly from the <code>r</code> object as <code>r.status_code</code>.</p> <p>After <code>if r.status_code == 200:</code>, you can then convert to JSON if you real...
pandas|streamlit
0
357,236
72,619,527
Creating list of lists using groupby dates in pandas dataframe
<p>df =</p> <pre><code> Date Slot 0 2022-02-23 34 1 2022-02-23 35 2 2022-02-24 0 3 2022-02-24 1 4 2022-02-25 0 5 2022-02-25 1 </code></pre> <p>This is my df and I want a list of lists for all the 'Slot' values having the same corresponding 'Date' value i.e my output should l...
<p>You can try</p> <pre class="lang-py prettyprint-override"><code>out = df.groupby('Date')['Slot'].agg(list).tolist() # out = df.groupby('Date')['Slot'].apply(list).tolist() </code></pre> <pre><code>print(out) [[34, 35], [0, 1], [0, 1]] </code></pre>
python|pandas|dataframe|sorting|group-by
0
357,237
72,569,661
Vectorized way to group a time series by hour of day, on a rolling window, and assign the rolling method to a new column
<p>We have a time series with a <code>values</code> column apart from the <code>date</code> column and for every day we have 24 rows (hours of the day). The goal is to create an additional column which contains the <strong>mean of the values for a specific hour of the day on a rolling window</strong>. For example for a...
<p>Use <code>droplevel</code> after <code>groupby</code> / <code>rolling</code> to drop the level created by <code>groupby</code>:</p> <pre><code># Or .droplevel('date') df['mean'] = df.groupby(df['date'].dt.hour).rolling(2)['values'].mean().droplevel(0) print(df) # Output date values mean ...
pandas|dataframe|numpy
1
357,238
72,539,545
combine rows according to columns into new columns
<p>I need to combine rows according to their rows (a simple example below based on row'id'):</p> <pre><code>id unit amount 1 m 10 1 kg 3 2 m 4 3 number 5 3 kg 7 3 m 6 </code></pre> <p>I want it converted to:</p> <pre><code>id unit amount unit amount uni...
<p>You can use <code>pivot</code>:</p> <pre><code>df.assign(col=df.groupby('id').cumcount()).pivot('id', 'col') unit amount col 0 1 2 0 1 2 id 1 m kg NaN 10.0 3.0 NaN 2 m NaN NaN 4.0 NaN NaN 3 number ...
python|pandas
1
357,239
72,742,129
Splitting a dataframe into multiple dataframe based on entries in a column
<p>I have such a dataframe:</p> <pre><code>time | text 01.01.2000 | None None | abc None | cde None | def 01.02.2000 | None None | abb None | bbc None | dde 01.03.2000 | None None | 123 None | 278 None | 782 </code></pre> <p>I now want to split this dataframe in multiple dataframes beginning with the value where time i...
<p>You can forward fill <code>time</code> column then groupby <code>time</code> column</p> <pre class="lang-py prettyprint-override"><code>df['time'] = df['time'].ffill() out = (df.groupby('time', as_index=False) ['text'].agg(lambda x: '\n'.join(x.dropna()))) </code></pre> <pre><code>print(out) time ...
python|pandas
2
357,240
72,706,255
Find the closest station id for the meter based on Latitude and longitude
<p>I have two data frames, the first one has the longitude and latitude for the meters, and the second data frame has the longitude and latitude of the stations. I am trying to link them by closest match. Here is my example:</p> <pre><code>df_id = pd.DataFrame() df_id ['id'] = [1, 2] df_id['lat'] = [32, 55] df_id['lo...
<p>Pandas' cross merge should help to pair ids and stations</p> <pre class="lang-py prettyprint-override"><code># cross merge the 2 dfs to pair all ids with stations df_merged = df_id.merge(df_station.add_suffix('_station'), how='cross') # find euclidean distance between all pairs of locations df_merged['distance'] = (...
python|pandas|dataframe
1
357,241
72,614,776
erase dataframe's columns containing 'illegal values'
<p>I was quite surprised looking on the web for something so basic, yet, I couldn't find any information regarding the issue.</p> <p>I have the following dataframe: <a href="https://i.stack.imgur.com/g9wsG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g9wsG.png" alt="dataframe image" /></a></p> <p>...
<p>This might do everything on all your columns</p> <pre><code>df.loc[df &lt; 0 ] = 5 df.loc[df &gt; 1 ] = 5 df.loc[df == 5] = '' </code></pre> <p>Basically I am converting all the invalid values to 5 and then dropping all the values equal to 5.</p> <p>if you want it as a function it could be</p> <pre><code> def repla...
python|pandas|dataframe
1
357,242
72,606,489
order while using pivot_table
<p>How can I keep the initial order of my pandas while I using pivot_table ?</p> <p>I use pandas version '1.2.5' (so I can't use the pivot_table &quot;order&quot; argument)</p> <p>For instance</p> <pre><code>data =pd.DataFrame(data={ 'x_values':[13.4, 13.08, 12.73], 'y_values': [1.54, 1.47, 1.46], 'experiment':['e', 'e...
<p>Due to nature of <code>pivot</code> it always sort the index. You might want to pivot with the original index.</p> <pre><code>data.reset_index().pivot_table(index=['index','x_values'], values='y_values', columns='experiment') </code></pre> <p>You can also use <code>set_index().unstack()</code>:</p> <pre><code>data.s...
python|pandas|pivot-table
1
357,243
72,807,507
how to use a list of strings in a sql query
<p>Alright, I have tried here this but it clearly doesn't work, I tried to find a similar question, but I didn't find the answer I seek, hence I ask here.</p> <p>First of all, I have a list of strings that I've made from df columns:</p> <pre><code>list_cols=df_cols['COLUMN_NAME'].values.tolist() list_cols </code></pre>...
<p>This code below should do the trick. Just use <code>','.join(list_cols)</code> instead of <code>list_cols</code> only.</p> <pre class="lang-py prettyprint-override"><code>sql=(f'''select {','.join(list_cols)} from big where date = '20220501' ''') </code></pre> <p>Check out the output:...
python|sql|pandas|list|select
0
357,244
72,726,900
pandas add brackets around part of string containing numbers
<p>I have a pandas dataframe, and I want to replace certain strings in one column. The string could be something like this: &quot;Spiderman is Nr 1&quot; and I want to turn it to &quot;Spiderman (Nr 1)&quot; The only part of the string that stays the same is &quot;is Nr&quot;. The superhero and the number change, but n...
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>df[&quot;Superheros&quot;] = df[&quot;Superheros&quot;].str.replace(r'\bis\s+(Nr\s*\d+)', r'(\1)', regex=True) </code></pre> <p>See the <a href="https://regex101.com/r/JWnakd/1" rel="nofollow noreferrer">regex demo</a></p> <p><em>Details</em></p> <ul> <...
python|regex|pandas
1
357,245
72,517,088
Using str.extract with regex on pandas df column
<p>I have some address info. stored in a pandas df column like below:</p> <pre><code>df['Addr'] LT 75 CEDAR WOOD 3RD PL LTS 22,25 &amp; 26 MULLINS CORNER LTS 7 &amp; 8 PT LT 22-23 JEFFERSON HIGHLANDS EXTENSION </code></pre> <p>I want to extract lot information and create a new column so for the example above, my expect...
<p>You could use</p> <pre><code>\b(?:LOT|LTS?) (\d+(?:(?:[-,]| &amp; )\d+)*) </code></pre> <p><strong>Explanation</strong></p> <ul> <li><code>\b</code> A word boundary</li> <li><code>(?:LOT|LTS?) </code> Match <code>LOT</code> or <code>LT</code> or <code>LTS</code></li> <li><code>(</code> Capture group 1 <ul> <li><code...
python|regex|pandas
1
357,246
72,749,455
Why is binary classification network not converging?
<p>I have created a binary classification neural network from scratch using ReLu for hidden layers, sigmoid for my final layer and the binary cross entropy loss function, I also use minibatch gradient descent. I'm struggling to understand why my network converges for smaller data sets completely fine, but just hovers a...
<p>First, you seem to forget to use the scaled data, i.e. <code>X_train=X[:1024]</code> should be indeed <code>X_train=X_scale[:]</code>. Second, the shape of bias gradient term does not look right, e.g. the last layer bias (<code>b3</code>) should be a scalar; however, in your update rule, <code>lr*self.error_term_out...
python|numpy|machine-learning|deep-learning|neural-network
0
357,247
72,799,030
How to convert pandas DataFrame to multiple DataFrame?
<p>My DataFrame</p> <pre><code>df= pandas.DataFrame({ &quot;City&quot; :[&quot;Chennai&quot;,&quot;Banglore&quot;,&quot;Mumbai&quot;,&quot;Delhi&quot;,&quot;Chennai&quot;,&quot;Banglore&quot;,&quot;Mumbai&quot;,&quot;Delhi&quot;], &quot;Name&quot; :[&quot;Praveen&quot;,&quot;Dhansekar&quot;,&quot;Naveen&quot;,&quot...
<p>You can groupby and create a dictionary like so:</p> <pre><code>dict_dfs = dict(iter(df.groupby(&quot;City&quot;))) </code></pre> <p>Then you can directly access individual cities:</p> <pre><code>Delhi = dict_dfs[&quot;Delhi&quot;] print(Delhi) # result: City Name Gender 3 Delhi Kumar M 7 Delhi Kons...
python|pandas|dataframe
3
357,248
72,667,735
How to read multiple 3d images and store them in 4D array using numpy python?
<p>I have used the code below to create an array with the shape of (2, 3, 365, 256, 256) (2, 365, 256, 256) for 3 images however I need my shape to be (2,365, 256, 256, 3) (2, 365, 256, 256) for my model to run, any tips please?</p> <pre><code>def Load_function(path): f_img= nib.load(path ) img_data= f_img.get_fdat...
<p>You can try the transpose in NumPy, check this <a href="https://numpy.org/doc/stable/reference/generated/numpy.transpose.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.transpose.html</a></p>
python|numpy|machine-learning|keras|mri
0
357,249
72,655,175
Filter a column which has multilevel column header in Pandas
<p>I have an excel like below</p> <p><a href="https://i.stack.imgur.com/uSBl0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uSBl0.png" alt="enter image description here" /></a></p> <pre><code>A B C x y 1 abc 3 5 2 abc 4 6 1 def 5 7 1 qrs 6 8 2 def 7 9 </code></p...
<p>It looks like you could use the columns <code>A</code> and <code>B</code> as index while reading the excel file, then use indexing with <code>loc</code> to query the index values:</p> <pre><code>df = pd.read_excel('...', header=[0, 1], index_col=[0, 1]) df.loc[[(1, 'def')]] </code></pre>
python|pandas|dataframe|multi-index
1
357,250
72,724,748
Huggingface transformers padding vs pad_to_max_length
<p>I'm running a code by using <code>pad_to_max_length = True</code> and everything works fine. Only I get a warning as follow:</p> <blockquote> <p>FutureWarning: The <code>pad_to_max_length</code> argument is deprecated and will be removed in a future version, use <code>padding=True</code> or <code>padding='longest'</...
<p>It seems that the documentation is not complete enough!</p> <p>You should add <code>truncation=True</code> too to memic the <code>pad_to_max_length = True</code>.</p> <p>like this:</p> <pre><code>encoding = self.tokenizer.encode_plus( poem, add_special_tokens=True, max_length=self.max_len, return_tok...
python|nlp|huggingface-transformers|huggingface-tokenizers
0
357,251
72,523,656
Is there a more effective way to generate this dataframe?
<p>I have a code which &quot;converts&quot; a dict into a <code>pd.DataFrame</code>. As result, I get the dataframe I need, but as I think code is not effective.</p> <pre><code>python import datetime import pandas as pd data = {} for index, row in get_data_row_by_row(): data[index] = row ''' As result i get somet...
<p>How about:</p> <pre><code>out = pd.DataFrame.from_dict(data, orient='index').rename_axis(index='Date') out.index = pd.to_datetime(out.index) </code></pre> <p>Output:</p> <pre><code> Open Close Low High Date 2022-04-22 ...
python|pandas|dataframe|data-analysis
4
357,252
72,812,128
Is there a way to normalize a json pulled straight from an api
<p>Here is the type of json file that I am working with</p> <pre class="lang-json prettyprint-override"><code>{ &quot;header&quot;: { &quot;gtfsRealtimeVersion&quot;: &quot;1.0&quot;, &quot;incrementality&quot;: &quot;FULL_DATASET&quot;, &quot;timestamp&quot;: &quot;1656447045&quot; }, &quot;entity&qu...
<p>The issue is, that pandas.json_normalize expects either a dictionary or a list of dictionaries but json.dumps returns a string.</p> <p>It should work if you skip the json.dumps and directly input the json to the normalizer, like this:</p> <pre><code>import pandas as pd import json import requests base_URL = reques...
python|json|pandas|json-normalize
1
357,253
72,598,879
How to detect sign change of values of a column of a pandas dataframe using numpy or pandas?
<p>I want to detect sign change of my data using either pandas or numpy. I want to count the number(s) of <code>id</code> which changes sign of <code>y</code> between two immediate <code>TIMESTEP</code> values (eg. for 2800 and 2900 TIMESTEPs, <code>id</code> 313 has changed sign (<code>y</code> becomes negative). I ha...
<p>There is a dedicated function in numpy <code>np.sign</code>, which is conveniently available as a method in pandas series:</p> <pre class="lang-py prettyprint-override"><code># this will return the sign of the float x df['x'].sign() </code></pre> <p>For sign change from one row to the next, it's possible to use the ...
python|pandas|dataframe|numpy
1
357,254
72,827,440
How to sort a confusion matrix by the diagonal value
<p>I have this confusion matrix:</p> <pre><code>import pandas as pd import seaborn as sn import matplotlib.pyplot as plt data = {'y_Actual': [3, 3, 1, 1, 0, 1, 2, 3, 1, 1, 1, 0, 2, 4, 3], 'y_Predicted': [1, 2, 2, 1, 0, 1, 3, 0, 1, 0, 0, 0, 3, 4, 2] } df = pd.DataFrame(data, columns=['y_Actual','y_P...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.argsort.html" rel="nofollow noreferrer"><code>numpy.argsort</code></a> on the diagonal (opposite values for descending order) and reindex:</p> <pre><code>import numpy as np order = np.argsort(-confusion_matrix.to_numpy().diagonal()) # array(...
python|pandas|seaborn|diagonal
3
357,255
72,547,932
Pandas ffill on section of DataFrame
<p>I am attempting to forward fill a filtered section of a DataFrame but it is not working the way I hoped.</p> <p>I have df that look like this:</p> <pre><code> Col Col2 0 1 NaN 1 NaN NaN 2 3 string 3 NaN string </code></pre> <p>I want it to look like this:</p> <pre><code> Col Col2 0 ...
<p>We can use boolean indexing to filter the section of <code>Col</code> where <code>Col2 = 'string'</code> then forward fill and update the values only in that section</p> <pre><code>m = df['Col2'].eq('string') df.loc[m, 'Col'] = df.loc[m, 'Col'].ffill() </code></pre> <hr /> <pre><code> Col Col2 0 1.0 NaN 1 ...
python|pandas|dataframe|fillna|ffill
1
357,256
72,721,449
Python: Iterating though dataframe columns as values in a function that prints charts
<p>I'm trying to iterate through numeric fields in a data frame and create two separate bar charts one for Test1 and another for Test2 scores grouped by Name. I have a for loop that I get a type error on. I have a small sample of the data below but this for loop would run for data frame larger than 25 fields. Below is ...
<p>Your program was having an issue with attempting to compare the data in the &quot;Name&quot; column with the integer value that you had in the variable definition line before it would move along to the other two columns.</p> <pre><code>data = df[(df.columns &gt; 80 )].groupby(df.Name, as_index = True).agg({columns: ...
python|pandas|for-loop|bar-chart|typeerror
0
357,257
72,807,337
Create a new dataframe based off of strings lengths of values from existing dataframe
<p>Sorry if the title is unclear - I wasn't too sure how to word it. So I have a dataframe that has two columns for old IDs and new IDs.</p> <pre><code>df = pd.DataFrame({'old_id':['111', '2222','3333', '4444'], 'new_id':['5555','6666','777','8888']}) </code></pre> <p>I'm trying to figure out a way to check the string ...
<p>In general, <code>DataFrame.applymap</code> is pretty slow, so you should avoid it. I would stack both columns in a single one, and select the ids with length 4:</p> <pre><code>import pandas as pd df = pd.DataFrame({'old_id':['111', '2222','3333', '4444'], 'new_id':['5555','6666','777','8888']}) ids = df.stack() b...
python|python-3.x|pandas|dataframe|lambda
2
357,258
72,628,077
variable substitution in pandas
<p>Can anyone please help, I am preparing the condition statement at the backend, that needs to be substituted in the pandas-dataframe but it is failing.</p> <pre><code>st=&quot;(df['ColA']&gt;48) &amp; (df['ColB']&lt;14)&quot; df[st] </code></pre> <blockquote> <p>~\AppData\Local\Continuum\anaconda3\lib\site-packages\...
<p>Remove the double quotes. Use:</p> <pre><code>st = (df['ColA']&gt;48) &amp; (df['ColB']&lt;14) df[st] </code></pre>
python|pandas|dataframe
0
357,259
72,534,843
Can't download tf nightly 2.0 preview
<p>I'm trying to download the tf nightly preview but keep getting the following error: <a href="https://i.stack.imgur.com/iVCt4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iVCt4.png" alt="enter image description here" /></a></p> <p>I read that it should download if you have the 3.6.x version of P...
<p>That library does simply not exist (anymore). Tensorflow 2.0 was released in September 2019, so they probably didn't keep the nightly preview of it around. If you want the <em>current</em> nightly, then you should do</p> <pre><code>pip install tf-nightly </code></pre> <p>If you want tensorflow 2.0, then do</p> <pre>...
python|tensorflow|pip
0
357,260
72,640,493
Fill na values in dataframe after merge
<p>I have 2 dataframes I want to merge on first name and contact email returning all of the values from df2.</p> <p>Sample of data:</p> <pre><code>df1 = pd.DataFrame([['Elle', 'Kelly', 'ellemoore@email.com', 2], ['Amanda','Johnson', 'johnson.amanda@email.com', 5], ['Jay', 'Rogers', 'jay.rogers@email.com', 4], ['David...
<p>Building on @Lazyer's comment, I would use pandas method chaining and use <code>combine_first</code> to combine the <code>Last Name_x</code> and <code>Last Name_y</code> columns and also the <code>Email</code> and <code>Contact Email</code>.</p> <pre><code>merged = ( df1 .merge(df2, left_on=['First Name', 'E...
python|pandas|pandas-merge
0
357,261
72,742,206
Divide two separate columns from two separate dataframes using common index
<p>I have two separate dataframes (<code>df1</code> and <code>df2</code>) with similar columns and I am trying to divide one column in <code>df1</code> by another column in <code>df2</code>.</p> <pre><code>dict1 = { 'sex': {6: 'SEX_M', 7: 'SEX_M', 8: 'SEX_M', 9: 'SEX_M', 10: 'SEX_M', 11: 'SEX_M', 12: 'SEX_F...
<p>You can use a left <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> to align the values, then divide as numpy array:</p> <pre><code>cols = ['classif1', 'classif2'] df1['Percentage_of_total'] = (df1['obs_value'] ...
python|pandas|dataframe
2
357,262
72,774,361
Pure Pandas approach to converting data in a text file into a table
<p>I am looking to convert data in a textile into a table (data frame) using just methods from Pandas.</p> <h2>Textfile</h2> <pre class="lang-bash prettyprint-override"><code>00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010 </code></pre> <h2>Table/Dataframe format</h2> <pre class="lang-bash prett...
<p>This should work in your case:</p> <pre><code>df = pd.read_fwf('untitled.txt', widths=[1,1,1,1,1], header=None) print(df) </code></pre> <p>Result:</p> <pre><code> 0 1 2 3 4 0 0 0 1 0 0 1 1 1 1 1 0 2 1 0 1 1 0 3 1 0 1 1 1 4 1 0 1 0 1 5 0 1 1 1 1 6 0 0 1 1 1 7 1 1 1...
python|pandas|text-files
3
357,263
72,666,582
Creating a list in a Dataframe column which is a range of values from other two data frame columns
<p>I need to create a list in a dataframe column, which is a range of numbers. The range limits should be the values in other two data frame columns.</p> <pre><code>df = pd.DataFrame({'A': [3, 7, 2, 8], 'B': [1, 3, 9, 3]},index=[1,2,3,4]) </code></pre> <p>Now In need a dataframe column which will be series of lists lik...
<p>You can try <code>DataFrame.apply</code> on rows</p> <pre class="lang-py prettyprint-override"><code>df['C'] = df.apply(lambda row: list(range(row.min(), row.max()+1)), axis=1) </code></pre> <pre><code>print(df) A B C 1 3 1 [1, 2, 3] 2 7 3 [3, 4, 5, 6, 7] 3 ...
python|pandas|dataframe
2
357,264
72,739,077
convert pandas column to to_datetime
<p>I am trying to convert 'Thursday - 6/13/2019' to pd.to_datetime in a pandas dataframe column called 'timestamp&quot;.</p> <p>Here is my attempt to solve the problem:</p> <p>df['timestamp'] = pd.to_datetime(df['timestamp'], format='%A - %x')</p> <p>Thanks.</p>
<p>How about <strong>%m/%d/%Y</strong> instead of <strong>%x</strong></p> <pre><code>pd.to_datetime(df['timestamp'], format='%A - %m/%d/%Y') </code></pre>
pandas|string-to-datetime
0
357,265
72,822,853
How to get the cumulative sum of n days in different months?
<p>I have this df:</p> <pre><code> CODE DATE PP 17594 000130 1991-01-01 0.5 17595 000130 1991-01-02 11 17596 000130 1991-01-03 1 17597 000130 1991-01-04 2 17598 000130 1991-01-05 5 17599 000130 1991-01-06 2 17598 000130 1991-01-07 5 17598 000130 1991-01-08 7 17598 000130 1991-01-09 5 17...
<p>I believe this should work:</p> <pre><code>s = df['DATE'] (df .groupby([ s.dt.year, s.dt.month, s.dt.day.clip(upper=30).sub(1).floordiv(10) ], as_index=False) .agg({'CODE':'first', 'DATE':'first', 'PP':'sum'})) </code></pre> <p>Output:</p> <pre><code> CODE DATE PP 0 130 1991-01-01 39....
python|pandas
3
357,266
72,737,643
how to sum up columns from different dataframes into a single dataframe in pandas
<p><strong>Sample data</strong></p> <pre><code>import pandas as pd df1 = pd.DataFrame() df1[&quot;Col1&quot;] = [0,2,4,6,2] df1[&quot;Col2&quot;] = [5,1,3,4,0] df1[&quot;Col3&quot;] = [8,0,5,1,7] df1[&quot;Col4&quot;] = [1,4,6,0,8] #df1_new = df1.iloc[:, 1:3] df2 = pd.DataFrame() df2[&quot;Col1&quot;] = [8,2,4,6,2...
<p>You can either sum the dataframes separately and then add the results, or sum the concatenated dataframes:</p> <pre class="lang-py prettyprint-override"><code>df1.iloc[:,1:3].sum() + df2.iloc[:,1:3].sum() pd.concat([df1,df2]).iloc[:,1:3].sum() </code></pre> <p>In both cases the result is</p> <pre><code>Col2 44 C...
python|pandas|dataframe
1
357,267
72,495,355
Is it possibe to change similar libraries (Data Analysis) in Python within the same code?
<p>I use the <a href="https://github.com/modin-project/modin" rel="nofollow noreferrer">modin</a> library for multiprocessing. While the library is great for faster processing, it fails at <code>merge</code> and I would like to revert to default pandas in between the code.</p> <p>I understand as per PEP 8: E402 convent...
<p>You can simply do the following :</p> <pre><code>import modin.pandas as mpd import pandas as pd </code></pre> <p>This way you have both modin as well as original pandas in memory and you can efficiently switch as per your need.</p>
python|pandas|dataframe|modin
2
357,268
72,764,342
Special Characters and Converting Problems Using Tabula for PDF to Proper CSV
<p>The code:</p> <pre><code>#Import the required Module import tabula # Read a PDF File df=tabula.read_pdf(&quot;C:/Users/Desktop/abstract/abstract.pdf&quot;,encoding='cp1252', pages='all') #Total page number can change. All pages must be taken. (to be generic) # convert PDF into CSV df1=df.to_csv('C:/Users/Desktop/ab...
<p>The code:</p> <pre><code>#libraries import pandas as pd import fitz import io def set_texts(pdf_files:list): print(&quot;starting to text process&quot;) #This function reads pdf and gets &quot;CRC-32&quot; components as texts for pdf_file in pdf_files: with fitz.open(pdf_file) as doc: ...
json|python-3.x|pandas|dataframe
0
357,269
72,660,877
Whas might be causing 'TypeError: can only concatenate str (not "int") to str' when calculating correlation?
<p>I am struggling with the following error: <strong>TypeError: can only concatenate str (not &quot;int&quot;) to str</strong>. It occurs when I'm trying to calculate correlation in steps 6 and 7.</p> <p>Although I am aware that int cannot be concatenated to str, I have no clue how this is related to my code (guess som...
<p>With a little help I was able to solve this, so I am posting an answer. Maybe someone will find it useful.</p> <p>The problem was indeed related to datatypes. It was caused by non-numeric values in columns SMA14 and SMA50 (those were like 'nan5', 'nan6' etc, not just 'nan'). When checking data.info(), it stated that...
python|pandas|dataframe|typeerror
0
357,270
72,638,841
Merge two columns from multiple panda series dataframes based on string matching from two columns with different values
<p>I need to merge two columns from a pandas series dataframe together on the last 4 digits of the first column <code>pack_number</code>. I currently have 2 dataframes with a different number of columns.</p> <p>So far, I thought about extracting the last 4 digits of the <code>ROOT_VIN</code> but I'm not sure how to pro...
<p>If I understand right then you have 2 data frames with a lot of columns.</p> <pre class="lang-py prettyprint-override"><code># df1 # pack_number Table # df2 # ROOT_VIN Table # @BeRT2me solution df2['pack_number'] = df2['ROOT_VIN'].str[-4:] # joining the 2 dataframes # we add '_remove' to the duplicate columns name...
python|pandas|dataframe|merge|multiple-columns
1
357,271
72,737,233
Get the count for Age >= 50 using pandas
<p>I have a dataset</p> <pre><code>{&quot;data&quot;: &quot;key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47, key=0Sr4C, age=68, key=CGEqo, age=76, key=IxKVQ, age=79, key=eD221, age=29, key=XZbHV, age=32, key=k1SN5, age=88&quot;} </code></pre> <p>Need to get the count of age where age is &gt;= 50 using Pandas. I...
<p>It's necessary to process your data before pass it to a pandas dataframe. So you can organize your data as recommended in the comments above, or if string is really huge, you can do this:</p> <pre class="lang-py prettyprint-override"><code>d = {&quot;data&quot;: &quot;key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt,...
python|pandas|dataframe
0
357,272
72,564,304
Count and Sum of distinct values of the tuple pairs in python
<pre><code>import pandas as pd dt = {'order_id': ['A','A','B','B','B','C'], 'XY_ID': [4,5,4,5,6,4]} print(pd.DataFrame(data=dt)) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>order_id</th> <th>XY_ID</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>4</td> </tr> <tr> <td>A</td> <td...
<p>Here is an approach using <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow noreferrer"><code>itertools.combinations</code></a>:</p> <pre><code>from itertools import combinations s = (df.groupby('order_id')['XY_ID'] .agg(lambda x: list(combinations(x, 2))) ...
python|pandas|data-manipulation
2
357,273
72,814,102
How to set datatime column?
<p>I have some datatime columns on my dataframe. One of them appear with the object type and the other appear as datatype. How to pass tho object type one as datatype also ?</p> <p><a href="https://i.stack.imgur.com/bitT9.png" rel="nofollow noreferrer">enter image description here</a></p> <p><a href="https://i.stack.im...
<p>According your comments, it seems you have some bad dates.</p> <p>Use <code>pd.to_datetime</code> with <code>errors='coerce'</code></p> <pre><code>DL_2.DATE_ENTREE_ = pd.to_datetime(DL_2.DATE_ENTREE_, errors='coerce') </code></pre> <p>To find bad dates:</p> <pre><code>DL_2.loc[pd.to_datetime(DL_2.DATE_ENTREE_, error...
python-3.x|pandas
0
357,274
72,786,491
How to count how many delimeters per row there are in Python
<p>I produce a query with 13 columns of values. Every single ones of these values are manually entered. That means there is roughly less than 10% chance that the rows entered are wrong. However that is not the issue. the issue is sometimes certain special characters are entered that can cause havoc to the database. I n...
<p>very very basic aproach, but maybe will be enough:</p> <pre><code>import pandas as pd df = pd.read_csv(r&quot;C:\Test\test.csv&quot;, sep = ';') data = df.iloc[:, : 13].copy() # data to use in later code excessive_data = df.iloc[:, 13: ].copy().reset_index(drop=True) # excessive data will land after columns 13 if...
python|pandas|postgresql|csv|count
0
357,275
59,625,993
How to extract data using groupby under specific condition?
<p>I have a data set as such:</p> <pre><code>x = {'column1': ['a','a','b','b','b','c','c','c','d'], 'column2': [1,0,1,1,0,1,1,0,1] } df = pd.DataFrame(x, columns = ['column1', 'column2']) print (df) </code></pre> <p>How would i extract only data from column two that have value of one (like this):</p> <pre><c...
<p>First question:</p> <pre><code>df[df.column2==1].reset_index(drop=True) </code></pre> <p>will give you</p> <pre><code> column1 column2 0 a 1 1 b 1 2 b 1 3 c 1 4 c 1 5 d 1 </code></pre> <p>Second question:</p> <pre><code>df['column3'] = df.groupby('column1').transform(len) </code>...
python|pandas|numpy|data-manipulation|data-cleaning
3
357,276
59,728,509
Cycle differents rows in tensor by different offsets
<p>I am trying to build a model that does the following:</p> <p>Given two time series drawn from the same underlying distribution of discrete values (in a finite cyclic group), take their element-wise difference and feed it to the model.</p> <p>The model's task is to reconstruct the two original time series when only...
<p>I figured it out: <code>gather</code> takes an argument <code>batch_dims</code> that does exactly what I need.</p>
python|tensorflow|keras|time-series|tensorflow2.0
0
357,277
59,490,139
Convert a pandas Timestamp list
<p>In my variable 'Datelist3' there is a pandas Timestamp list, in the following format:</p> <pre><code>[Timestamp('2019-12-04 09:00:00+0100', tz='Europe/Rome'), Timestamp('2019-12-04 09:30:00+0100', tz='Europe/Rome'), ....] </code></pre> <p>I'm having difficulty converting this list to a datetime string list, in thi...
<p>If your data is well formed, this would work :</p> <pre><code>time_list = [Timestamp('2019-12-04 09:00:00+0100', tz='Europe/Rome'), Timestamp('2019-12-04 09:30:00+0100', tz='Europe/Rome'), ....] str_list = [t.strftime("%Y-%m-%d %H:%M:%S") for t in time_list] </code></pre> <p>However, if you face the same error as ...
python-3.x|pandas|datetime|type-conversion|timestamp-with-timezone
3
357,278
59,887,150
Auto-allocate CUDA devices for Tensorflow
<p>I have multiple identical CUDA devices within one computer. I run multiple tensorflow training instances on that computer, each of them uses one and only one CUDA device. I would like to allocate one and only one CUDA device to a tensorflow instance automatically, whichever is free. I would like to do that when the ...
<p>All you need is a GPU scheduler, here is one: <a href="https://pypi.org/project/simple-gpu-scheduler/" rel="nofollow noreferrer">https://pypi.org/project/simple-gpu-scheduler/</a></p> <p>I am assuming you are running same model with different parameters right? So the sample command could be:</p> <pre><code>simple_...
tensorflow|cuda
1
357,279
59,788,063
Add Column based on information from other dataframe pandas
<p>I am looking for an answer to a question which I would have solved with for loops.<br> I have two pandas Dataframes:</p> <pre><code> ind_1 ind_2 ind_3 prod_id A = a 1 0 0 a 0 1 0 b 0 1 0 c 0 0 1 a 0 0 1...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> for <code>MultiIndex Series</code> in both <code>DataFrame</code>s, then filter only <code>1</code> values by callable, filter <code>b</code> values by <a hre...
python-3.x|pandas|dataframe
1
357,280
59,772,000
Pytorch, backprop and composite models
<p>Just a quick check for a question I have.</p> <p>I want to build a model that generates its output based on two models <code>F</code> and <code>G</code> like so.</p> <p><code>y = G(F(x))</code></p> <p>where x is of course the input, and y the output.</p> <p>However, first I want to update the weights of the <cod...
<p>If as you suggest, the optimizers and losses for <code>F</code> and <code>G</code> can be separated, then I don't think that it will be necessary to implement any different update functionalities since you can specify the set of parameters for each optimizer, <em>e.g.</em></p> <pre><code>optimizer_F = optim.SGD(F.p...
pytorch
1
357,281
59,802,467
Boolean mask within Seaborn Countplot
<p>I want to apply this Boolean mask</p> <pre><code>csv["country"].value_counts()&gt;5000 </code></pre> <p>to this function</p> <pre><code>sns.countplot(y = csv["country"].value_counts()&gt;5000, data = csv) </code></pre> <p>but it rises this error:</p> <pre><code>"Unalignable boolean Series provided as indexer (i...
<p>You can do something like:</p> <pre><code>s = csv['country'].value_counts() s[s &gt; 5000].plot(kind='bar') </code></pre> <p>To use seaborn, you can filter the data using:</p> <pre><code>s = csv['country'].value_counts() s = s[s &gt; 5000].index.tolist() sns.countplot(x='country', data=csv.query("country in @s"...
python|pandas|seaborn
0
357,282
59,668,597
Z-score normalization in pandas DataFrame (python)
<p>I am using python3 (spyder), and I have a table which is the type of object "pandas.core.frame.DataFrame". I want to z-score normalize the values in that table (to each value substract the mean of its row and divide by the sd of its row), so each row has mean=0 and sd=1. I have tried 2 approaches. </p> <p>First app...
<p>The code below calculates a z-score for each value in a column of a pandas df. It then saves the z-score in a new column (here, called 'num_1_zscore'). Very easy to do.</p> <pre><code>from scipy.stats import zscore import pandas as pd # Create a sample df df = pd.DataFrame({'num_1': [1,2,3,4,5,6,7,8,9,3,4,6,5,7,3...
python-3.x|pandas|spyder|normalization
5
357,283
59,873,794
How to split data of single column to separate columns in pairs
<p>I am using a csv file with dataframe name <code>content</code>. I am trying this code but it not providing expected output</p> <pre><code>new_content1 = content['Value1','Value2','Value3','Value4','Value5','Value6'] def get_pairs(x): arr = x.split(' ') return list(map(list, zip(arr, arr[1:]))) new_content1...
<p>IIUC, you can simply use:</p> <pre><code>new_content1['pairs'] = new_content1['ColName'].str.split(" ", n = 1, expand = True) </code></pre> <p>where ColName is column you want to split, it will return a values as list in <code>pairs</code> column</p> <p>Alternatively, if you want the output to make new columns ba...
python|pandas|dataframe
1
357,284
59,852,613
Multiply feature map by a scalar in pytorch
<p>I have a binary classification problem, there are image and variable in the data set, I have an idea for compare image and variable together.</p> <p>Every time when I pass conv-layer, I want to multiply a weight scalar to all feature map, where weight scalar is computed from a fc-layer.</p> <p>For example, suppose...
<pre class="lang-py prettyprint-override"><code>result = c1 * c2.reshape((-1,1,1,1)) </code></pre> <p>You can reshape your <code>c2</code> shape <code>torch.Size([8, 1])</code> to <code>torch.Size([8, 1, 1, 1])</code> using <a href="https://pytorch.org/docs/stable/torch.html#torch.reshape" rel="nofollow noreferrer"><c...
pytorch
0
357,285
59,483,067
hub.KerasLayer() always comsumes the same GPU memory despite the changing max_seq_len
<p>I am using Bert from tensorflow hub, and I want to save GPU memory by reducing the <code>max_seq_len</code> of Bert model after I noticed this in <a href="https://github.com/google-research/bert#out-of-memory-issues" rel="nofollow noreferrer">the original Bert repository</a> :</p> <blockquote> <p>max_seq_length: ...
<p>I used the code from <a href="https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth" rel="nofollow noreferrer">Tensorflow document</a> and solved the problem.</p> <pre class="lang-py prettyprint-override"><code>gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: # Currently, mem...
python|tensorflow|keras|tensorflow-hub
2
357,286
59,516,564
tensorflow error when installing turicreate?
<p>When I install turicreate package, it gives me the following error:</p> <pre><code>Collecting tensorflow&gt;=2.0.0 (from turicreate) Could not find a version that satisfies the requirement tensorflow&gt;=2.0.0 (from turicreate) (from versions: 0.12.1, 1.0.0, 1.0.1, 1.1.0rc0, 1.1.0rc1, 1.1.0rc2, 1.1.0, 1.2.0rc0, 1....
<p>Upgrade pip</p> <pre><code># On Linux or macOS: pip3 install -U pip # On Windows: python -m pip3 install -U pip </code></pre> <p>Install turicreate</p> <pre><code>pip3 install turicreate </code></pre> <p>This will solve your problem</p>
python|tensorflow|machine-learning|turi-create|coursera-api
3
357,287
59,489,073
How to not remove but handle outliers by transforming using pandas?
<p>I have a dataframe like as shown below</p> <pre><code>dfx = pd.DataFrame({'min_temp' :[-138,36,34,38,237,339]}) </code></pre> <p>As you can see below that there are three outliers in this data <code>-138</code>,<code>237</code> and <code>239</code></p> <p>What I would like to do is identify records </p> <p>a) wh...
<p>Here's a generalized function which follows the following logic tot detect <strong>non</strong> outliers.</p> <p>This function takes a dataframe as argument, so make sure you have numeric columns only.</p> <blockquote> <p>for each data point X: <code>abs(X - mean) &lt;= (std * 3)</code></p> </blockquote> <p>Or ...
python|python-3.x|pandas|dataframe|outliers
1
357,288
59,827,509
Multiplying and powering python float and pytorch integer
<p>Why does a python float multiplied by a torch.long gives a torch.float but powering a float by a torch.long gives a torch.long?</p> <pre><code>&gt;&gt;&gt; a = 0.9 &gt;&gt;&gt; b = torch.tensor(2, dtype=torch.long) &gt;&gt;&gt; foo = a * b &gt;&gt;&gt; print(foo, foo.dtype) tensor(1.8000) torch.float32 &gt;&gt;&g...
<p>This looks like a bug, probably in the way pytorch binds <code>**</code> to <code>__rpow__</code> or <code>__pow__</code>.</p> <p>E.g. if you tried <code>0.9 - torch.tensor(2)</code>, since 0.9 isn't a tensor, this gets interpreted as <code>torch.tensor(2).__rsub__(0.9)</code>, which works correctly. <code>**</code...
python|pytorch
1
357,289
59,696,944
Density Plot Python Pandas
<p>I want to create a plot that looks like the plot attached below.</p> <p>My data frame is built at this format:</p> <pre><code> Playlist Type Streams 0 a classical 94 1 b hip-hop 12 2 c classical 8 </code></pre> <p>The 'popularity' category can be replaced by the 'str...
<p>To augment the answer of @Student240 you could make use of the seaborn library, which makes it easy to fit 'kernal density estimates'. In other words, to have smooth curves similar to that in your question, rather than a binned histogram. This is done with the <a href="https://seaborn.pydata.org/generated/seaborn.kd...
python|pandas|density-plot
4
357,290
59,738,638
Change precision of floats and export to csv
<p>Simple problem i guess.</p> <pre><code>import pandas as pd df = pd.DataFrame.from_dict({'A': [1.2345, 2.3456, 1.3000], 'B': [1.2566, 3.5670, 6.7800]}) A B 1,2345 1,2566 2,3456 3,5670 1,3000 6,7800 </code></pre> <p>I actually just want to export the dataframe to a csv-file which looks like</p> <p...
<p>You can use <code>float_format='%.2f'</code> parameter in <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html#pandas-dataframe-to-csv" rel="nofollow noreferrer"><code>.to_csv()</code></a>:</p> <pre><code>df.to_csv('data.csv', float_format='%.2f', index=False, sep='\t', d...
python-3.x|pandas
1
357,291
59,613,083
Transforming the inputs using python scripts to feed into the tensorflow lite ML Kit for firebase connected to android app
<p>I have trained a keras model(converted to .tflite for ML kit) which doesn't take raw data coming from android sensors as input but instead it takes some preprocessed data. The preprocessing of data is too complicated to be done in Java, but is feasible enough to do using a python script. So I was wondering if there ...
<p>In terms for android app, Python might not integrate well locally. However, you can try following ways based on the resources you have.</p> <ul> <li><strong>Cloud computation</strong> - Use REST API call to get pre-processed data from Python script hosted on Google Cloud, store it if required and run the model pred...
java|python|android|machine-learning|tensorflow-lite
1
357,292
59,736,043
Select NumPy Values Around Index
<p>I have two NumPy arrays:</p> <pre><code>import numpy as np m = 3 x = np.array([1, 0, 0, np.inf, 0, 0, 1, 1, 2, np.inf, np.inf, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y = np.arange(x.shape[0]-m+1) </code></pre> <p>Let's say that where ever there is an <code>np.inf</code> in <code>x</code>, that index position is called <cod...
<p>The easiest solution I can think of is to use the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html" rel="nofollow noreferrer">np.convolve</a> function to dilate a mask. This can be done as follows:</p> <pre><code>mask = np.convolve(x==np.inf, [True]*(m*2-1), mode='same') y[mask[:-m+...
python|numpy
3
357,293
59,480,259
How to do element wise operation of Pandas Series to get a new DataFrame
<p>I have a Pandas Series of numbers, lets say <code>[1,2,3,4,5]</code>. I want an efficient way to create a dataframe with each combination of series element passed through a function and the result being the corresponding dataframe element</p> <p>Lets say the function is </p> <pre><code>def f1(a,b): return a*b +...
<p>You can do:</p> <pre class="lang-py prettyprint-override"><code>def f1(a,b): return a*b + 5 s=[1,2,3,4,5] df=pd.DataFrame(columns=s, index=s) df=df.apply(lambda x: f1(x.name, x.index)) </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code> 1 2 3 4 5 1 6 7 8 9 10 2 ...
python-3.x|pandas
2
357,294
59,667,208
checking convergence using python integrator
<p>I am looking to integrate the difference between my numerical and exact solution to the heat equation though I am not sure what would be the best to way to tackle this. Is there a specific integrator that would allow me to do this ? I hope to integrate it wrt to $x$. </p> <p>I have the following code so far: </p> ...
<p>By integration you mean you want to find the area between <code>y</code> and <code>heat_exact</code>? Or do you want to know if they are the same within a specific limit? The latter can be found with <code>numpy.isclose</code>. The former you can use several integration functions builtin numpy.</p> <p>For example:<...
python|numpy|matplotlib|scipy|numeric
0
357,295
59,618,208
Parallelizing GPflow 2.0 GP regression for large datasets
<p>I am trying to run a GP regression over 2D space + 1D time with ~8000 observations and a composite kernel with 4 Matern 3/2 covariance functions -- more than a single core can handle. </p> <p>It would be great to be able to distribute the GPR computation over multiple nodes rather than having to resort to variati...
<p>In terms of computation, the GPflow can do whatever TensorFlow does. In other words, if TensorFlow supported cloud evaluations, the GPflow would support it as well. But, it doesn't mean that you cannot implement your version of TensorFlow computation, maybe more efficient and be able to run it on the cloud. You can ...
python-3.x|tensorflow|tensorflow2.0|tensorflow-probability|gpflow
1
357,296
59,863,597
Python - if str in df.column enter in an if statement
<p>Basically my code import some configuration from a config file, where the user can toggle on/off part of the code. The config file looks something like and it is a json file:</p> <p>condition1: ['str1', 1] condition2: ['str2', 1]</p> <p>The string is the name it will be assigned to the df column and the integer ca...
<p>You should nest your checks in another check that verifies if the dataframe has a column called "str2" and handle the different possibilities that arise.</p> <p>The check you want to add to your code is:</p> <pre><code> if 'str2' in df.columns: # check df['str2'] # nested if ... elif 'str3' in df.colu...
python|pandas|if-statement
0
357,297
59,489,774
sort excel files using column value python
<p>I have n excel files and I need to sort them according to a column's value. In fact, I need to organize my excel files placed under a specific folder in creating subfolders and each subfolder contains excel files with the same <code>DEPTNAME</code>, knowing that <code>DEPTNAME</code> is a column name and each excel ...
<p>here is one way which combines all files in a folder and all sheets in each file and then groups on <code>DEPTNAME</code> and the filename + sorts the files in the folder(Note: if same <code>DEPTNAME</code> are in 2 different excel fies, they are saves as 2 different files in the same folder &lt;- as requested):</p...
python|python-3.x|pandas|sorting
3
357,298
59,620,769
Is there a way of getting multiple levels of hue in Seaborn or Matplotlib?
<p>I can get a table in the form I need, </p> <p><img src="https://i.stack.imgur.com/jf6Qt.jpg" alt="required table"> but the closest plot I can manage with 3 dimensions is: <img src="https://i.stack.imgur.com/ZFMRx.png" alt="achieved graph"></p> <p>When I'm trying to get something like this: <img src="https://i.stac...
<p>You want to define a list of colors for the color palette. For an example with seaborn, see <a href="https://seaborn.pydata.org/tutorial/color_palettes.html#using-named-colors-from-the-xkcd-color-survey" rel="nofollow noreferrer">here</a>.</p>
python|pandas|matplotlib|jupyter|seaborn
0
357,299
59,714,000
`x in pandas.core.series.Series` returns True even though there is no such value in it
<p>I have pandas series object that contains bunch of IDs. I wanted to filter out rows of other dataframe by checking if their ID was present in my pandas series object:</p> <p><code>DATA['y'] = DATA['ID'].apply(lambda x: 1 if x in IDs else 0)</code></p> <p>I noticed that ID 279779 in DATA had '1' in column 'y', even...
<p><code>1</code> is equal to <code>True</code> in Python.</p> <p>You may want to try with casting string type to ID column to avoid 1 be taken as bool value:</p> <pre><code>DATA['y'] = DATA['ID'].astype(str).apply(lambda x: 1 if x in IDs.values else 0) </code></pre>
python|pandas
0