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 |
|---|---|---|---|---|---|---|
364,200 | 69,989,331 | How to write in a dat file in python | <p>I have this content in a dat file I can access easily, it's not at the beggining of the file but in the middle. I insert only the part of the file that I need to modify.</p>
<pre><code>{
....,
",>=,",
",>=,",
.......
}
</code></pre>
<p>Instead of a line with <cod... | <pre><code>prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
# Read lines
file = open(prefixed[i], 'r')
file_content = file.readlines()
file.close()
# Treatment
for pos, line in enumerate(file_content):
... | python|pandas | 1 |
364,201 | 69,685,054 | pandas pivot table: How to find count for each group in Index and Column | <p>I am new to pivot table. I just want the count of each Age Grp by Mth. I tried</p>
<pre><code>pivot1=pd.pivot_table(df,index=[ "Age Grp"], columns=["Mth"], values=["Age Grp"], aggfunc=pd.Series.nunique)
</code></pre>
<p>but get <code>ValueError: Grouper for 'Age Grp' not 1-dimensional<... | <p>Or:</p>
<pre><code>df.groupby(['Age Grp', 'Mth']).size().unstack(fill_value=0)
</code></pre>
<p><code>Output:</code></p>
<pre><code>Mth 1 5 10
Age Grp
0-4 1 0 1
10-14 0 1 0
5-9 0 1 0
</code></pre> | python|pandas|pivot | 0 |
364,202 | 69,931,816 | Python error: TypeErrpr: Object of type int64 is not JSON serializable | <p>I am trying to convert a csv file into a dataset. Here is that code.</p>
<pre><code>import csv
import json
import pandas as pd
def csv_to_json(csvFilePath, jsonFilePath):
dataset = {
"dataset_id": "???",
"areas": []
}
areas = []
cnt = 0
with open(cs... | <p>You should convert the data from <code>int64</code> to a normal python <code>int</code> so that the built in libraries are better able to handle it.</p> | python|json|pandas|csv | 1 |
364,203 | 69,844,454 | How to merge dataframe rows based on empty cells in a column | <p>If I have the following dataframe:</p>
<pre><code>Index Col1 Col2 Col3
1 10 x 40
2 y 50
3 z 60
4 20 a 30
</code></pre>
<p>I would like to merge rows that have a blank Col1 with the previous row that is not blank in Col1.</p>
<p>Expected output:</p>
<pre><code>Index Col1 Col2... | <p>We can do</p>
<pre><code>out = df.drop(labels = 'Col1',axis = 1).astype(str).groupby(df['Col1'].mask(df['Col1']=='').ffill()).agg(','.join).reset_index()
Out[85]:
Col1 Col2 Col3
0 10.0 x,y,z 40,50,60
1 20.0 a 30
</code></pre> | python|pandas|dataframe | 2 |
364,204 | 69,838,994 | How can I read pytorch model file via cv2.dnn.readNetFromTorch()? | <p>I am able to save a PyTorch custom model? (it can work any PyTorch version above 1.0)</p>
<p>However, I am not able to read the saved model. I am trying to read it via cv2.dnn.readNetFromTorch() so as to use the model in Opencv framework (4.1.0).</p>
<p>I saved the PyTorch model with different methods as follows to ... | <p><a href="https://docs.opencv.org/4.5.4/d6/d0f/group__dnn.html#ga65a1da76cb7d6852bdf7abbd96f19084" rel="nofollow noreferrer">OpenCV documentation</a> states can only read in <code>torch7</code> framework format. There is no mention of <code>.pt</code> or <code>.pth</code> saved by pytorch.</p>
<p><a href="https://dis... | opencv|deep-learning|pytorch|opencv-python | 1 |
364,205 | 69,731,570 | How can I assign a strin to an element in numpy arrays | <p>When I assign strings to the array it just picks up the first character and I need the entire string. Am I using the wrong method?</p>
<pre><code>import numpy
i=0
def func(name,number,array,i):
arry[i,0]=number
array[i,1]=name
print(array)
People= numpy.zeros([5,2],dtype=str)
func("qwe",&qu... | <p>Assign the people array to hold objects instead of strings:</p>
<pre><code>People= numpy.zeros([5,2], dtype=object)
print(func("qwe","123",People,i))
# [['123' 'qwe']
# ['' '']
# ['' '']
# ['' '']
# ['' '']]
</code></pre> | arrays|numpy|variable-assignment | 0 |
364,206 | 69,726,203 | Adding column titles between current titles in pandas | <p>I'm relatively new to coding so may be an easy answer! Basically I'm using pandas to import data and I want to add a column header between the original header titles. I've added the code with the names= section showing essentially what I would like to see. Help with how that is actually implemented would be a great ... | <p>If you would like to rename the column names, you can do it this way:</p>
<p><strong>By location:</strong></p>
<pre><code>dfFQExp.rename(columns={ dfFQExp.columns[0]: 'new header1'}, inplace = True)
</code></pre>
<p><strong>By original name:</strong></p>
<pre><code>dfFQExp.rename(columns={ 'Original header1': 'new h... | python|pandas|dataframe | 1 |
364,207 | 70,011,107 | Why is my scheduled job running automatically? | <p>I run the cell and it just runs continuously without stopping. Instead id like to have the script not start until the time period is triggered.</p>
<p>I have 4 functions being called in the main function. What am I missing?</p>
<p>Here's my script:</p>
<pre><code>
def main():
print("Lets connect to Snowfl... | <p>u are running the code inside a while loop with true condition so it will start executing infinitely .</p> | python|pandas|dataframe|schedule | 1 |
364,208 | 70,021,535 | Flipping a python dictionary obtained from python dataframe | <p>I have a pandas dataframe and it looks like so:</p>
<pre><code>person weight height skill
kate 160 200 100
john 170 150 70
</code></pre>
<p>I have set the person column as the index of my python dataframe. And then i turned it into a dictionary using the <code>.to_dict()<... | <p>You can set <code>person</code> as the index and use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>to_dict</code></a> with <code>orient</code> arg set to <code>index</code>.</p>
<pre><code>df.set_index('person').to_dict('index')
# {'kate': {'wei... | python|python-3.x|pandas|dataframe|dictionary | 3 |
364,209 | 69,852,545 | pandas groupby vs minimum | <p>I have a data frame with the following columns:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>var1</th>
<th>var2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>A</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>A</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>B</td>
</tr>
<... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>DataFrame.join... | python|pandas | 1 |
364,210 | 69,982,248 | Is there a rapid way in Python to Group by a column and lines to split? | <p>I have a quick question. I want to import a .cvs file, and then i want to export it back. But in some cells there are more informations separated by \n. I manage to separete it but, i want to know is there a more faster way to do it? And after i finish with the data, i want to export it back, with the \n. I know is ... | <p>Assuming every cell of each row has the same number of <code>'\n'</code> characters, you can split each cell on <code>'\n'</code> into a list using <code>Series.str.split</code>. Then, explode each list into a different row using <code>Series.explode</code>. You can apply that logic to every column using <code>Serie... | python|pandas|dataframe | 1 |
364,211 | 69,689,141 | Drop specific column and indexes in pandas DataFrame | <p>DataFrame:</p>
<pre><code> A B C
0 1 6 11
1 2 7 12
2 3 8 13
3 4 9 14
4 5 10 15
</code></pre>
<p>Is it possible to drop values from index 2 to 4 in column B? or replace it with <code>NaN</code>.</p>
<p>In this case, values: <code>[8, 9, 10]</code> should be removed.</p>
<p>I tried this: <code... | <p>Drop values does not make sense into <code>DataFrame</code>. You can set values to <code>NaN</code> instead and use <code>.loc</code> / <code>.iloc</code> to access index/columns:</p>
<pre><code>>>> df
A B C
a 1 6 11
b 2 7 12
c 3 8 13
d 4 9 14
e 5 10 15
# By name:
df.loc['c':'e', ... | python|pandas|dataframe | 1 |
364,212 | 70,010,744 | Jupyter Notebook/Pandas not reading excel file after moving ipynb | <p>I'm working on automating some reporting for work which starts off with a pd.read_excel method. It worked fine and I moved on with the rest of my code. When I was done, I had a few ipynb files on my desktop and moved them into a folder called "Python". After doing so, I'm getting a "No such file or di... | <p>Try using an absolute path rather than a relative path.
Right now your path assumes that the file is within the same directory as the notebook.
you can either:</p>
<ol>
<li>use a full path a.i - "C:\User{user_name}\Desktop\LS_Questions.xlsx"</li>
<li>Move the CSV/XL file to the directory of the notebook.</... | python|pandas|jupyter-notebook | 0 |
364,213 | 69,747,683 | creating order queue based on starttime and endtime in pandas python | <p>I have a pandas dataframe that contains four date columns, a starttime and an end time and date column that defines a range. I'd like to be able to collectively create a queue count for all time and date across all rows in the data frame, as defined by these columns.</p>
<pre><code>date start
1. date starttime ... | <p>The size of a queue at any point is a step function. There is a package called <a href="https://staircase.dev" rel="nofollow noreferrer">staircase</a>, which is built on pandas and numpy, for step functions. It even has a <a href="https://www.staircase.dev/en/latest/case_studies/queues.html" rel="nofollow noreferr... | python|pandas|datetime | 0 |
364,214 | 69,952,475 | how to solve the pytorch_geometric install error. Undefined symbol: _ZN5torch3jit17parseSchemaOrNameERKSs #999 | <p>how to solve the pytorch_geometric install error. Undefined symbol: _ZN5torch3jit17parseSchemaOrNameERKSs #999</p>
<p>solution:
conda install pytorch pyg -c pytorch -c pyg -c conda-forge</p>
<p>conda create -n py38 pip</p>
<p>conda install pytorch pyg -c pytorch -c pyg -c conda-forge</p>
<p>conda install pyg -c pyg ... | <p>Maybe check here:
<a href="https://github.com/pyg-team/pytorch_geometric/issues/999" rel="nofollow noreferrer">https://github.com/pyg-team/pytorch_geometric/issues/999</a></p>
<p>Most people say it is due to how you installed pytorch and two versions (the cpu and gpu versions are both installed)</p> | pytorch | 0 |
364,215 | 69,749,664 | Modify DataFrame based on previous row (cumulative sum with condition based on previous cumulative sum result) | <p>I have a dataframe with one column containing numbers (quantity). Every row represents one day so whole dataframe is should be treated as sequential data. I want to add second column that would calculate cumulative sum of the quantity column but if at any point cumulative sum is greater than 0, next row should start... | <p>Iterating over <code>DataFrame</code> rows is very slow and should be avoided. Working with chunks of data is the way to go with <code>pandas</code>.</p>
<p>For you case, looking at your <code>DataFrame</code> column <code>quantity</code> as a <code>numpy</code> array, the code below should speed up the process quit... | python|pandas|sequential | 1 |
364,216 | 69,784,393 | How to Remove additional information Executing op __inference_train_function_88100 in device in Tensorflow version >2.0 | <p>I was just testing the code to verify whether the code is running in GPU or not and I got this additional information along with accuracy & loss info.</p>
<pre><code>Executing op __inference_train_function_88100 in device /job:localhost/replica:0/task:0/device:GPU:0
Executing op __inference_train_function_88100 ... | <p>Thank you @Dev Patel for the confirmation. For the benefit of community please refer sample code as shown below</p>
<pre><code>import logging, os
logging.disable(logging.WARNING)
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow as tf
with tf.device("/gpu:0"):
model = kera... | python|tensorflow|deep-learning|jupyter-notebook | 0 |
364,217 | 69,749,212 | Python pandas dataframe reshape value of col to new col | <p>I have a dataframe that looks like this:</p>
<pre><code> col1 col2 col3 col4 col5 col6
0 1.1 a 29 b c d
1 2.3 a 29 b c d
2 10.3 a 29 b c d
3 6.5 a 29 b c d
4 34.7 a 29 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>DataFrame.... | python|pandas | 3 |
364,218 | 69,999,534 | How to merge dataframes based on column names? | <p>I have two tables (data frames). 1. One that contains years and production. 2. Another that contains years and area. I want to merge these two and get results as shown in table 3. How to do this is python3 (preferably using pandas)?</p>
<p>Table1</p>
<p><a href="https://i.stack.imgur.com/kfRHD.png" rel="nofollow nor... | <p>IIUC use:</p>
<pre><code>df = pd.concat([df1, df2]).T
</code></pre> | python|pandas|dataframe | 0 |
364,219 | 69,728,563 | Grab certain values from dataframe column and making new dataframe in python | <p>A column in my <code>DataFrame</code> is labeled as <code>Occupation</code>. In that column, <code>Real Estate</code> is represented in several different ways. These are the three ways it's represented:</p>
<pre><code>RealEstate
REALESTATE
RealEstateDeveloper
Other occupations I don't want
</code></pre>
<p>I want to... | <p>Try to clean your rows before:</p>
<pre><code>df['Occupation'].str.strip().str.casefold().str.contains('realestate')
</code></pre> | python|pandas|dataframe | 0 |
364,220 | 69,812,608 | Accessing dd/mm/yy to calculate the total amount of sales per year? | <p>Edit: Re-structured the whole question for it to make more sense (I think?)</p>
<p>Here is the dataframe I am trying to analyse (or as close as I could make).</p>
<pre><code>Customer_ID = [1,2,3,4,5,6,7]
Sales_Info = [11,22,33,44,55,66,77]
begin_date = '2019-10-16'
df = pd.DataFrame({'Customer_ID':Customer_ID,'Sales... | <p>Not sure exactly how you are using your data and how it's formatted but a pretty easy way to sum all sales_info for a year would look something like this:</p>
<pre><code>data = [{"id": 1 "date": "11/12/2020", "Sales_info": 2}, ...]
yearly_sum = {}
for datum in data:
year =... | python|pandas|jupyter-notebook|analysis | 0 |
364,221 | 70,011,142 | Concatenate files into one Dataframe while adding identifier for each file | <p>The first part of this question has been asked many times and the best answer I found was here: <a href="https://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-pandas-and-concatenate-into-one-dataframe">Import multiple csv files into pandas and concatenate into one DataFrame</a>.</p>
<p>But what... | <p>If I understand you correctly, it's simple:</p>
<pre class="lang-py prettyprint-override"><code>import re # <-------------- Add this line
path = r"/Users/jamesades/desktop/Watch_data_1/Re__Personalized_MH_data_call"
all_files = glob.glob(path + "/*.xlsx")
li = []
for filename in all_files:
... | python|pandas | 1 |
364,222 | 69,905,305 | Compare values from a DataFrame and replace with closest values, given a list | <p>I have a DataFrame called 'Dataex', and an ascending list called 'steps'.</p>
<pre><code>import pandas as pd
import numpy as np
if __name__ == "__main__":
Dataex = [[0.6, 0.36],
[0.6, 0.36],
[0.9, 0.81],
[0.8, 0.64],
[1.0, 1.00],
... | <p>This can be accomplished using <code>apply</code> and a lambda function to find the index of the closest value in <code>steps</code>.</p>
<pre><code>steps = np.array(steps)
Dataex["Lx_new"] = Dataex["Lx"].apply(lambda x: steps[np.argmin(np.abs(x-steps))])
</code></pre> | python|python-3.x|pandas|numpy | 3 |
364,223 | 69,951,324 | Pandas DataFrame MultiIndex Pivot - Remove Empty Headers and Axis Rows | <p>this is closely related to the question I asked earlier here <a href="https://stackoverflow.com/questions/69762822/python-pandas-dataframe-pivot-table-column-and-values-order">Python Pandas Dataframe Pivot Table Column and Values Order</a>. Thanks again for the help. Very much appreciated.</p>
<p>I'm trying to autom... | <p>In pandas 1.4.0 the options for A and B are directly available using the <code>Styler.hide</code> method:</p>
<p><a href="https://i.stack.imgur.com/XjrIt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XjrIt.png" alt="enter image description here" /></a></p> | python|pandas|dataframe|pivot-table|multi-index | 0 |
364,224 | 69,744,372 | Select all rows with 2 most recent dates by ID | <p>I would like to select all rows with the 2 most recent dates by each ID. Max and Max-1 dates and number of rows for each ID may differ for ID's.</p>
<p>Example Data:</p>
<pre><code>data = {'id': np.repeat((['a','b','c']), 6),
'date': ['2020-12-07', '2020-12-07','2020-12-05','2020-12-05','2020-12-04','2020-1... | <p>You can try with a "dense" ranking:</p>
<pre><code>>>> df[df.groupby("id")["date"].transform(pd.Series.rank, ascending=False, method="dense")<=2]
id date value1 value2
0 a 2020-12-07 10 1000
1 a 2020-12-07 10 1000
2 a 2020-12-05 ... | python|python-3.x|pandas | 3 |
364,225 | 69,724,957 | Pandas `pivot_table` working with `decimal.Decimal` type | <p>I have a dataframe looks like this:</p>
<pre><code>date id value type
2021-01-02 123123 0.3 apple
2021-01-02 123123 2.05 banana
2021-01-02 456456 2.01819 apple
2021-01-02 456456 606800000 banana
2021-01-02 567567 2.2 apple
2021-01-02 891891... | <p>Your code works for me, I can't reproduce your issue.</p>
<p>My setup:</p>
<pre><code>import pandas as pd
from pandas import Timestamp
from decimal import Decimal
data = {'date': [Timestamp('2021-01-02 00:00:00'),
Timestamp('2021-01-02 00:00:00'),
Timestamp('2021-01-02 00:00:00'),
... | python|pandas|types|decimal|pivot-table | 2 |
364,226 | 69,895,652 | Pandas, how to check which date_range values are in pd.Interval column's time range | <p>I have a dataframe that represents (multiple) hour intervals that are not free:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
{
'reserved': [
pd.Interval(pd.Timestamp(2011,11,9,8), pd.Timestamp(2011,11,9,12), closed='left'),
pd.Interval(pd.Timestamp... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_indexer.html" rel="nofollow noreferrer"><code>Index.get_indexer</code></a> for positions, if no match is returned <code>-1</code>, so possible filter <code>working_hours</code>:</p>
<pre><code>i = pd.IntervalIndex(df.reserved)
s ... | python|pandas|time-series|intervals|between | 0 |
364,227 | 69,971,833 | Replace negative numbers, NaN and 0s with mean of next and previous positive number | <p>I want to replace negative numbers, NaNs and 0s with mean of next and previous positive number of same column.</p>
<p>Original dataframe</p>
<pre><code> a c
0 1 1
1 2 2
2 0 5
3 -3 NaN
4 -1 5
5 3 3
</code></pre>
<p>Expected output dataframe is</p>
<pre><code> a c
0 1 1
1 2 ... | <p>I edited my answer to better address your question. Note however, that the mean of 5 and 5 is 5, and not 2.5 as you wrote in yout expected result.</p>
<p>This new answer is based on hpchavaz's answer below.</p>
<pre><code># Replace 0 and negative values with NaN
df = df.mask(df<=0)
# Compute rank of consecutive ... | python|python-3.x|pandas|replace|time-series | 3 |
364,228 | 69,879,845 | How to plot my pandas dataframe in matplotlib | <p>I have the following code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
data = pd.read_csv("Ari_atlag.txt", sep = '\t', header = 0)
#Num_array = pd.DataFrame(data).to_numpy()
print(data.head())
data.plot()
#data.columns = ['Date', 'Number_of_test', 'Avarage_of_... | <p>Use <code>x='Date'</code> as parameter of <code>plot</code>:</p>
<pre><code>df.plot(x='Date')
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/Z911U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z911U.png" alt="enter image description here" /></a></p> | python|pandas|matplotlib | 4 |
364,229 | 69,856,133 | Given a numpy array of strings, what is the best way to extract their indices based on a specific conditional slice of each string? | <p>I'm working with weather data, and I've been given dates corresponding to this data. I have a numpy array with every date, but I'd like to index based on the month. My current coding for this is the below, where I append the index value to the list with the respective month. Although this works, I feel as though thi... | <p>Starting with numpy 1.23.0 (and available in the current <code>main</code>), <code>np.view</code> will not crash off-hand with non-contiguous arrays when changing to a different dtype size. What that means is that you will be able to do as follows:</p>
<pre><code>mos = DATE_np[:, None].view('U1')[:, 4:6].view('U2').... | python|numpy|indexing | 0 |
364,230 | 69,925,889 | Cleaning multiple entries based on date and entry type | <p>I need to clean up the rows of a df in order to calculate the time spent inside the building. Sometimes the reader has entered multiple entries or exits within a short space of time - obviously an error. The errors are not always duplicates, they may have a few seconds or minutes between them.</p>
<p>What is the mos... | <p>You could use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>shift</code></a></p>
<p>I created a dummy <code>DataFrame</code> to match yours (just without the <code>datetime</code> type):</p>
<pre><code>df = pd.DataFrame({'Date': ['2021-11-10 19:31:... | python|pandas | 3 |
364,231 | 69,961,172 | Drop only cell values in Pandas where value is NAN | <p>I have a dataframe with multiple columns. Many of the cells have NaN values that I want to drop but only that cell, not the entire row or even the column just that cell. The DataFrame looks something like this</p>
<pre><code>Column1 | Column2 | Column3 | ... |ColumnX
1 | NaN | NaN | ....| NaN
2 |... | <p>From your expected output, it does look you want to "count" the <code>NaN</code>s in each column, and substitute them with their occurrence number.</p>
<p>A quick way to achieve this could be the following:</p>
<ul>
<li><p>you define a function which does the substitutions you need</p>
<pre><code>import pa... | python|pandas | 1 |
364,232 | 69,806,371 | Combining all csv files from Github Repository Link and make it a one csv file | <p>I want to collect all <code>csv</code> files from the following Github Repository link below and want to make it a new <code>csv</code> file (for data cleaning purpose):</p>
<p><a href="https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data/csse_covid_19_daily_reports" rel="nofollow noreferrer">ht... | <p>Here is a short solution using <code>pandas</code>, <code>requests</code> and <code>BeautifulSoup</code> to filter all the csv links:</p>
<pre><code>import pandas as pd
import requests
from bs4 import BeautifulSoup, SoupStrainer
html = requests.get('https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_... | python|pandas|csv|github|data-analysis | 2 |
364,233 | 69,866,128 | seaborn heatmap displays axis labels, but no values when df.corr is NaN | <p>I am trying to come up with heatmap for correlation and I realized some are wrong.</p>
<p>Below is my heatmap. As you can see, the number for the action are not appearing.</p>
<p><a href="https://i.stack.imgur.com/gpPBT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gpPBT.png" alt="heatmap" /></a... | <p>Seaborn doesn't show the rows and columns which are fully <code>NaN</code>; these are just left empty. It might look strange, but it is a perfectly logical behavior.</p>
<p>The correlation matrix sets the row and column corresponding to a constant value dataframe column to <code>NaN</code>.</p>
<p>A workaround could... | python|pandas|seaborn|heatmap|correlation | 4 |
364,234 | 69,842,021 | Apache Zeppelin Error When Importing Pandas | <p>I'm facing a strange error when importing the Pandas library into my Zeppelin notebook. Here is the basic code that I have as part of my cell:</p>
<pre><code>%python
import pandas as pd
df = pd.read_csv (r'target/youtube_videos.csv')
print (df)
</code></pre>
<p>I get the following Error:</p>
<pre><code>Fail to exe... | <p>Are you sure you even have <code>pandas</code> installed? Unless Zeppelin uses its own Python, that would be the problem. Give <code>pip3 install pandas</code> a shot.</p> | python|pandas|apache-zeppelin|spark-notebook | 2 |
364,235 | 70,020,688 | Slicing of List contain datafram and strings | <pre><code>R_1 = {
'market': 'Boston',
'summary': pd.DataFrame({
"year": [2022, 2023],
"customers": [400, 230],
"count": [180, 1150]}),
}
}
R_2 = {
'market': 'New York',
'summary': pd.DataFrame({
"year": [2022, 2023],
&... | <p>You could try:</p>
<pre><code> ...
def get_results_max(self, market, metric, year):
metrics = [
result["summary_yearly"].loc[
result["summary_yearly"].year.eq(year), metric
].max()
for result in self.results if result["marke... | python|python-3.x|pandas|list|slice | 1 |
364,236 | 69,783,742 | Pandas Weighted Stats | <p>I have a dataframe that looks like the one below.</p>
<p>The <strong>weight column</strong> essentially represents the <strong>frequency of each item</strong>, so that for each location the weight sum will equal to 1</p>
<p>Please keep in mind that this is a simplified dataset, in reality there are more than 100 col... | <p>Because the weights are frequency weights, the most accurate method is to duplicate the observations according to the weights.</p>
<h2>Adjusting the weights</h2>
<p>Normally, frequencies are whole numbers. However, the frequencies here merely show how frequently an item appears relative to the other items of the sam... | python|pandas|dataframe|mean|weighted-average | 3 |
364,237 | 43,435,393 | The meaning of 'hx,xedge = np.histogram(x,xgrid)' | <p>Below is a program about binomially distributed random. In this code, I don't understand the sentence <code>hx,xedge = np.histogram(x,xgrid)</code>.</p>
<p>What does it do? Is histogram used to draw a bar graph?</p>
<p>I make the line chart with this code:</p>
<pre><code>import numpy as np
import matplotlib.pyplo... | <p>Did you look at the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html#numpy.histogram" rel="nofollow noreferrer">documentation for <code>numpy.histogram</code></a>?</p>
<p>This function takes some data (here <code>x</code>), and a sequence of bins (here <code>xgrid</code>), and retu... | python|numpy|matplotlib|histogram | 0 |
364,238 | 43,349,686 | Is there a way to automatically get the shape of feature map and use it to build the graph in Tensorflow? | <p>I am building my own CNN<br>
Between the convolution layer and fully connect layer
I need to know the size of the output of convolution layer, namely</p>
<blockquote>
<p>width_feature map * height_feature map * number_feature map</p>
</blockquote>
<p>so I can know the shape of weighting between this two layer, t... | <p>It looks like your input still has a variable batch dimension. (The ? in <code>shape=(?, 150)</code> tells you this, since ? stands for variable size). And no, you cannot initialize a variable with changeable size, since tensorflow cannot allocate memory properly then.</p>
<p>Although you seem to strip the batch di... | python|tensorflow|conv-neural-network | 0 |
364,239 | 43,288,505 | Python input/output more efficiently | <p>I need to process over 10 million spectroscopic data sets. The data is structured like this: there are around 1000 .fits (.fits is some data storage format) files, each file contains around 600-1000 spectra in which there are around 4500 elements in each spectra (so each file returns a ~1000*4500 matrix). That means... | <p>If I understand your code correctly, <code>n1</code> and <code>n2</code> determine which file to open. So why do you not just <code>lexsort</code> them. You can then use <code>itertools.groupby</code> to group records with the same <code>n1</code>, <code>n2</code>. Here is a down-scaled proof of concept:</p>
<pre><... | python|loops|numpy|input|processing-efficiency | 1 |
364,240 | 43,121,822 | How to show and close plot in matplitlib.pyplot? | <p>I have a real-time updating pandas dataframe with two columns of coordinates. I want to use geopandas to insert a shapefile map in jupyter notebook as a background, and plot the real time coordinates in the map in every 5 seconds, without closing and opening the background map every time. Here are the simplified cod... | <p>Try <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.clf" rel="nofollow noreferrer">plt.clf()</a> instead of plt.close(). It keeps the plot open but clears it so it can be used for a new plot.</p> | python|matplotlib|plot|geopandas | 0 |
364,241 | 43,398,130 | Graph dependencies in tensorflow: how to validate that dependencies exist or not? | <pre><code>op1=tf.image.random_brightness(placeholder_img3d_float32, max_delta=...)
op2=tf.image.random_contrast(placeholder_img3d_float32, lower=..., upper=...)
op3=tf.image.per_image_standardization(placeholder_img3d_float32)
</code></pre>
<p>If I defined these 3 ops, and then I run:</p>
<pre><code>sess.run(op1, ..... | <p>In a session you can give the command to run all 3 operations same time. But inside of the tensorflow will automatically looks for dependencies.</p>
<p>Let's say your 3rd operation depends on 2nd operation and 2nd operations depends on 1st operation and you need to run 3rd operation first, then session object will ... | tensorflow | 0 |
364,242 | 43,367,097 | Creating an array with a single staggered values in each row? | <p>I need to generate an nX3 array of zeros but one of the columns has the value (1.0) staggered in each row. </p>
<p>Desired Output:</p>
<pre><code>n = 10
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 1., 0., ... | <p>It's a bit quirky but it works by realizing the fact that you've (vertically) stacked identity arrays but you need to adjust the rows based on <code>n</code></p>
<pre><code>n = 10
np.vstack([np.identity(3)]* (n//3 + 1))[:n, :]
</code></pre>
<p>Alternatively, you can use <code>np.concatenate</code> if you want impr... | python|numpy | 1 |
364,243 | 43,224,900 | Function columns Python | <p>I am strugling with something probably easy in python/pandas... </p>
<p>I have a dataFrame with in columns dates, in index fruit names and inside, prices. </p>
<p>I am looking for a function which, when I input a date, give me the prices of my fruits for this date. </p>
<pre><code>[in] mylist
[out]
... | <p><code>pandas</code> allows you to access columns via the column name with the <code>[]</code> selector</p>
<pre><code>mylist['2017-03-23']
</code></pre>
<p>However, to be more explicit, you can use <code>.loc[]</code></p>
<pre><code>mylist.loc[:, '2017-03-23']
</code></pre>
<p>Or even use the <code>xs</code> met... | python|python-2.7|pandas|dataframe|sklearn-pandas | 3 |
364,244 | 43,104,877 | Passing two queues to Tensorflow training | <p>I'm trying to create a train operation based on CIFAR10 example from Tensorflow that uses <code>tf.RandomShuffleQueue</code> and my labels comes from the name of the files as mentioned in (<a href="https://stackoverflow.com/questions/34051205/accessing-filename-from-file-queue-in-tensor-flow">Accessing filename from... | <p>I changed my code to:</p>
<pre><code>filenames = [os.path.join(FLAGS.data_path, f) for f in os.listdir(FLAGS.data_path)][1:]
np.random.shuffle(filenames)
file_fifo = tf.train.string_input_producer(filenames, shuffle=False, capacity=len(filenames))
reader = tf.WholeFileReader()
key, value = reader.read(file_fifo)
im... | tensorflow | 0 |
364,245 | 43,312,995 | pandas to_html: add attributes to table tag | <p>I'm using the pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html" rel="nofollow noreferrer">to_html()</a> method to build a table for my website. I want to add some attributes to the <code><table></code> tag; however I'm not sure how to do this.</p>
<pre><code>... | <p>This can be achieved simply by manipulating the rendered html with a simple regular expression:</p>
<pre><code>import re
df = pd.DataFrame(1, index=[1, 2], columns=list('AB'))
html = df.to_html(classes="table")
html = re.sub(
r'<table([^>]*)>',
r'<table\1 attribute="value" a... | python|html|pandas | 5 |
364,246 | 43,309,877 | scipy.optimize with non linear constraints | <p>I have non-linear function with non-linear constraints and I'd like to optimize it. I don't know how to define non-linear constraints using scipy.optimize. My code so far looks like:</p>
<pre><code>from math import cos, atan
import numpy as np
from scipy.optimize import minimize
import sympy as sy
def f(x):
re... | <p>The were a few minor issues with the code; here is the modified version (explanation below):</p>
<pre><code>from math import cos, atan
import numpy as np
from scipy.optimize import minimize
def f(x):
return 0.1 * x[0] * x[1]
def ineq_constraint(x):
return x[0]**2 + x[1]**2 - (5. + 2.2 * cos(10 * atan(x[0... | python|numpy|optimization|scipy | 4 |
364,247 | 43,096,944 | How to import csv with complex fields | <p>I have the following line in a csv file </p>
<pre><code>"\"xyz\"; blabla";"u98r34u98r3"
</code></pre>
<p>This is supposed to contain two fields: </p>
<p><code>"\"xyz\"; blabla"</code> and <code>"u98r34u98r3"</code></p>
<p>I'm trying to import it with <code>pandas.read_csv()</code> on python 3.4.3 but it only giv... | <p>Works for me using <code>sep=";"</code> and <code>escapechar="\\"</code> in pandas 0.19.2:</p>
<pre><code>In [27]: df = pd.read_csv("quote.csv", header=None, sep=";", escapechar="\\")
In [28]: df
Out[28]:
0 1
0 "xyz"; blabla u98r34u98r3
In [29]: df.values
Out[29]: array([['"xyz"; bla... | python|python-3.x|csv|pandas | 1 |
364,248 | 43,452,978 | how to modify tensorflow example "census" with LABEL_COLUMN as continuous base column? | <p>In the <a href="https://github.com/GoogleCloudPlatform/cloudml-samples/tree/master/census" rel="nofollow noreferrer">census example</a> of tensorflow, The LABEL_COLUMN(income_bracket) has predefined values <strong>[' <=50K', ' >50K']</strong>. It is a Categorical base column. </p>
<p>1) How to modify the <strong... | <p>To make the "labels" floats, you need to make sure the default value for the label column is a float. The following changes are needed:</p>
<pre><code>CSV_COLUMN_DEFAULTS = [[0], [''], [0], [''], [0], [''], [''], [''], [''], [''],
[0], [0], [0], [''], [0.0]]
label_tensor = features.pop(LABEL_... | python|machine-learning|tensorflow|google-cloud-ml-engine | 1 |
364,249 | 43,423,311 | Speed up Pandas on Multi-core machine | <p>I have a pandas data frame that fits comfortably in memory. I do serval maps on the data frame, but each map is time-consuming due to the complexity of the call-back functions passed to map.
I own a AWS C4 instance, which is 8-core and 16GB-RAM. I ran the python script on the machine and found that more than 80% of... | <p>Pandas does not support this. <a href="http://docs.dask.org/en/latest/" rel="nofollow noreferrer">Dask</a> arrays are mostly API compatible with Pandas and support parallel execution for <code>apply</code>.</p>
<p>You might also consider some bleeding edge solutions such as <a href="https://medium.com/@jmcarpenter2... | multithreading|python-3.x|pandas | 3 |
364,250 | 43,152,505 | Unexpected Fourier Transform result in Python Numpy | <p>I am having a problem plotting the fourier transform of a data series (Y = intensity, X = wavelength). The goal is to remove the sinusoidal oscillation but applying a notch filter to the fourier transform of the data, followed by another fourier transform.</p>
<p>Here's the original data series:</p>
<pre><code>df... | <p>Three-ish problems.</p>
<p>(1) Compare the following two:</p>
<pre><code>df[['Y']].as_matrix().shape # (801, 1), yours
df['Y'].as_matrix().shape # (801,), better
</code></pre>
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html" rel="nofollow noreferrer"><code>np.fft.fft</code></... | python|python-2.7|numpy|signal-processing|fft | 2 |
364,251 | 43,269,453 | How to use ScipyOptimizerInterface in tf.learn.LinearClassifier? | <p>I want to try some second order optimization in tf.learn, but I couldn't figure out how. Thanks in advance!</p> | <p>With older TensorFlow (dating it to your question):</p>
<pre class="lang-python prettyprint-override"><code>import tensorflow as tf
vector = tf.Variable([7., 7.], 'vector')
# Make vector norm as small as possible.
loss = tf.reduce_sum(tf.square(vector))
optimizer = tf.contrib.opt.ScipyOptimizerInterface(
loss, ... | tensorflow|scipy|scipy-optimize | 0 |
364,252 | 43,333,306 | Python pandas - Combine columns from different files | <p>I have two CSV files. They actually have over 2 million records in each, but here's a simplified version:</p>
<p>File 1 :</p>
<pre><code>col1
----
1
54
744
45
65
</code></pre>
<p>File 2 :</p>
<pre><code>col2
----
sdf
322
d3
d
2
</code></pre>
<p>What is the quickest way of combining the two of these to end up wi... | <pre><code>import pandas as pd
df1 = pd.read_csv("csv1")
df2 = pd.read_csv("csv2")
result = pd.concat([df1, df2], axis=1)
</code></pre>
<p>This should do the trick</p> | python|pandas | 3 |
364,253 | 43,151,213 | CNTK: Create MinibatchSource from numpy array for multi GPU training | <p>I have my pre-processed image data in numpy array, and my script works fine with a single GPU by <a href="https://www.cntk.ai/pythondocs/gettingstarted.html" rel="nofollow noreferrer">feeding numpy array</a>. From what I understood, we need to create <a href="https://www.cntk.ai/pythondocs/cntk.io.html?highlight=min... | <p>You can create composite readers that combine multiple image deserializers into one source. First you need to create two map files (with dummy labels). One will contain all input images and the other will contain the corresponding target images. The following code is a minimal implementation, assuming the files are ... | python|numpy|deep-learning|cntk | 1 |
364,254 | 43,128,106 | pcolormesh ticks center for each data point/tile | <p>I have some z=f(x,y) data that I would like to display in a heat map. So I am using <code>np.meshgrid</code> to create a (x,y)-grid and then call <code>pcolormesh</code>. However the ticks are not centered for each "tile" that correspond to a data point -- in the docs, I did not find any instructions on how to cente... | <p>In a pcolormesh the grid is defined by the edge values. In the following example the value of 6 in the lower left corner is the value between 0 and 1 in each dimension. I think this is perfectly understandable to everyone.</p>
<p><a href="https://i.stack.imgur.com/EmzIj.png" rel="noreferrer"><img src="https://i.sta... | python|numpy|matplotlib|plot|heatmap | 6 |
364,255 | 43,182,318 | merging returns odd length | <p>I am having a problem with a relatively simple task...</p>
<p>I have two dataframes:
<code>df_sample</code> which I read from csv</p>
<pre><code>+------+-----------+-------+-----------+
| key | Full Text | Date | Publisher |
+------+-----------+-------+-----------+
| abcd | foofoo | date1 | a |
| bcde... | <p>You're seeing additional rows because the keys are not unique across both dfs, in your case the second df. You'll need to decide whether you want repeated rows which is the current behaviour or you want to drop the duplicates in the second df:</p>
<pre><code>df_labels = df_labels.drop_duplicates(subset='key')
</cod... | python|python-3.x|pandas | 2 |
364,256 | 43,282,365 | Difference of a date and int column in Pandas | <p>I have a DataFrame that looks like this:</p>
<pre><code>raw_data = {'SeriesDate':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'Test':['1','2','3','4']}
import pandas as pd
df = pd.DataFrame(raw_data,columns=['SeriesDate','Test'])
df['SeriesDate'] = pd.to_datetime(df['SeriesDate'])
</code></pre>
<p>I want ... | <p>You can use <code>to_timedelta</code>:</p>
<pre><code>df['TestDate'] = df['SeriesDate'] - pd.to_timedelta(df['Test'].astype(int), unit="d")
print(df)
SeriesDate Test TestDate
0 2017-03-10 1 2017-03-09
1 2017-03-13 2 2017-03-11
2 2017-03-14 3 2017-03-11
3 2017-03-15 4 20... | python|python-2.7|pandas | 1 |
364,257 | 43,383,114 | ValueError: The shape of the input to "Flatten" is not fully defined | <p>I'm trying to run <a href="https://gist.github.com/fchollet/7eb39b44eb9e16e59632d25fb3119975" rel="nofollow noreferrer">this code</a>, but getting the following error:</p>
<pre><code>Using TensorFlow backend.
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943... | <p>Just in case someone else is facing a similar problem, and is wondering why the error in question was thrown, I will just add more details to <a href="https://stackoverflow.com/a/43383510/5695374">@Simplicity's answer</a>:</p>
<p>As mentioned in the <a href="https://keras.io/backend/" rel="noreferrer">keras document... | python|tensorflow|neural-network|keras|conv-neural-network | 5 |
364,258 | 43,109,488 | 5 input and 3 output features for machine learning | <p>Need some advise here.</p>
<p>I am trying to build a model where it can predict the 3 different output features when 5 input features are given.</p>
<p>for example,
5 input features: size of the house, house floor, house condition, number of rooms, parking.
3 output features: price for selling, price for buying,... | <p>Neural network definitely can predict/approximate more outputs. I have experience with neuron regulator and there net produce control signal for two motors.</p>
<p>So I don't have experience with tensorflow. But this framework is from Google and is quite popular, so I'm almost sure, there is multioutput functionali... | machine-learning|tensorflow|neural-network|regression | 1 |
364,259 | 43,160,879 | Replace indices with values from a list in a data frame | <p>I have the following data frame:</p>
<pre><code>A | B | C | D | ListVal
---------------------------------
0 | 3 | 2 | 1 | [0.0,0.1,0.2,0.3]
---------------------------------
2 | 1 | 0 | 3 | [0.5,0.6,0.7,0.8]
---------------------------------
2 | 3 | 1 | 0 | [0.15,0.25,0.35,0.45]
</code></pre>
<p>For each row, I wo... | <p>Here is how I would do it in 2 lines of code:</p>
<p>the dataframe:</p>
<pre><code>df1=pd.DataFrame({'A':[0,2,2],'B':[3,1,3],'C':[2,0,1],'D':[1,3,0],'ListVal':[[0.0,0.1,0.2,0.3],[0.5,0.6,0.7,0.8],[0.15,0.25,0.35,0.45]]})
</code></pre>
<p>convert it to a list of lists:</p>
<pre><code>df_vals=df1.values.tolist()
<... | python|pandas|numpy|dataframe | 2 |
364,260 | 43,244,589 | Mixed date formats dd/mm/yyyy and d/m/y in pandas | <p>I have a dataframe with mixed date formats in a column. Some of it is in the format dd/mm/yyyy and some of it is in the format d/m/y. How can I set the column as datetime by applying the appropriate format depending on the value of the cell?
I am reading from a csv file:</p>
<pre><code>DayofWeek,Date
Friday,22/05/... | <pre><code>df = pd.read_csv('dates.txt', parse_dates=['Date'], dayfirst=True)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
DayofWeek 5 non-null object
Date 5 non-null datetime64[ns]
dtypes: datetime64[ns](1), object(1)
memory usage: 100.... | python-3.x|date|pandas|datetime | 0 |
364,261 | 43,466,582 | How to refresh Excel Formula at read | <p>I want to use Excel sheet in pandas. The excel sheet has some automatic calculate formula base on the date of the day.</p>
<p>There are any way to update Excel formula before or during the open of Excel file in pandas.</p> | <p>This should work:</p>
<pre><code>import pandas as pd
import win32com.client
office = win32com.client.Dispatch("Excel.Application")
wb = office.Workbooks.Open(your_file_path)
wb.RefreshAll()
wb.Save()
wb.Close()
df = pd.read_excel(your_file_path) #updates should be applied
</code></pre> | pandas | 3 |
364,262 | 43,367,615 | Dataframe Warning : SettingWithCopyWarning in python | <p>Processing file from <br>
<a href="http://portal.amfiindia.com/spages/NAV0.txt" rel="nofollow noreferrer">http://portal.amfiindia.com/spages/NAV0.txt</a><br>
to get output as follows:<br>
31012017,1,1,135765,12,10.8536000,<br>
31012017,1,1,135762,12,10.8543000,<br>
31012017,1,1,135760,12,10.6599000,<br>
31012017,1,1... | <p>I think you need add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow noreferrer"><code>copy</code></a>:</p>
<pre><code>fil_df=df[df['Scheme Code'].apply(lambda x : str(x).isdigit())].copy()
</code></pre>
<p>If you modify values in <code>fil_df</code> later y... | python|pandas|dataframe | 1 |
364,263 | 72,188,393 | Filtering rows in Pandas Groupby based on a condition within the group | <p>I've been wrestling with this for a couple of days now, despite a lot of searching. I've come across a number of similar problems, but I've not been able to make any of the solutions work for me.</p>
<p>Here's my starting dataframe:</p>
<pre><code>data = {
"account_id": ["1001", "1001",... | <p>This does the job.</p>
<pre><code>grouped_df = df.groupby("account_id")
groups = []
for group in df["account_id"].unique():
group_df = grouped_df.get_group(group)
group_df = group_df.loc[group_df[group_df["data_type"] == "initial_balance"].index[0]:, :]
group_df["a... | python|pandas|pandas-groupby | 0 |
364,264 | 72,243,721 | How to get this single column data into data frame with appropriate columns | <p>I am learning pandas and Data Science and am a beginner.
I have a data as following</p>
<pre><code>Rahul
1
2
5
Suresh
4
2
1
Dharm
1
3
4
</code></pre>
<p>I would like it in my dataframe as</p>
<pre><code>Rahul 1
2
5
Suresh 4
2
1
Dharm 1
3
4
</code></pre>
<p>How can... | <p>How it'd be best formatted depends on what you plan to do with it, but a good starting place would be doing this:</p>
<p>Given:</p>
<pre><code>Rahul
1
2
5
Suresh
4
2
1
Dharm
1
3
4
</code></pre>
<p>Doing:</p>
<pre><code># Read in the file and call the column 'values':
df = pd.read_table(filepath, header=None, names=[... | python|pandas|dataframe|data-science | 1 |
364,265 | 72,251,154 | data restructuring offset 3 year rolling window new columns pandas | <p>a little new to data manipulation and might be a tough question to follow so bear with me, please.</p>
<p>I have this dataframe in pandas (apologies for the sketchy creation of a dataframe with transpose - sure there's a more efficient way):</p>
<pre><code>f2 = np.transpose(pd.DataFrame(np.array([[10,30,50,11,21],[2... | <p>Using your specific starting and ending examples, you can create the "-1year" and "1year" columns using <code>.shift()</code>, then drop rows with missing data introduced by <code>shift</code>ing at the start and end, and finally rename and rearrange columns:</p>
<pre><code>df = f2.copy()
df['one... | pandas | 0 |
364,266 | 72,472,740 | I want to run tensorFlow JS model in a framework that have frontend and backend what are you recommendations? | <p>Currently we have a web app (single html page with a script tag) which runs a TensorFlow JS model, that we trained using teachable machine website.</p>
<p>The code runs correctly, and we can see the predictions.</p>
<p>Now, and according to our knowledge transferring into a framework that have frontend and backend w... | <p>The React + Node.js stack you're looking for is implemented in <a href="https://remix.run/" rel="nofollow noreferrer">Remix</a> (not affiliated). You are able to define both backend and frontend logic in the same file which is then compiled for both the browser and Node:</p>
<pre class="lang-js prettyprint-override... | node.js|reactjs|machine-learning|artificial-intelligence|tensorflow.js | 0 |
364,267 | 72,260,789 | How to do prediction when use tensorflow nce_loss for training | <p><a href="https://www.tensorflow.org/api_docs/python/tf/nn/nce_loss" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/nn/nce_loss</a>
Here it says <code>calculate the full sigmoid loss for evaluation or inference</code>, can anyone explain some detail how to predict the label in the inference p... | <p>It is possible when you consider the sequence input, NCE_loss is the noise-contrastive estimation that varies input to create the output by selecting acandidate sampler.</p>
<p>Ref 0: <a href="https://www.tensorflow.org/api_docs/python/tf/nn/nce_loss" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/pyt... | python|tensorflow|deep-learning|classification|loss-function | 0 |
364,268 | 72,392,807 | Create time index of integers based on date values using Pyspark | <p>I have a pandel dataframe in spark,including dates for all items:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Item ID</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>2021-01-01</td>
<td>1</td>
<td>34</td>
</tr>
<tr>
<td>2021-01-01</td>
<td>2</td>
<td>45</td>
</tr>
<... | <p>In <code>pandas</code> try <code>rank</code></p>
<pre><code>df['new'] = df['Date'].rank(method = 'dense')
Out[61]:
0 1.0
1 1.0
2 2.0
3 3.0
4 2.0
Name: Date, dtype: float64
</code></pre> | python|pandas|datetime|pyspark|indexing | 0 |
364,269 | 72,197,861 | How to read a csv column value like: "[1,2,3,nan]" with pandas dataframe? | <p>I'm trying to read in a csv file that has a list for each column value.
Example:</p>
<pre><code>accuracy_per_item
"[0.2,0.3,0.4]"
"[0.4,0.2,nan]"
</code></pre>
<p>While I can read in the column values without nan using:</p>
<pre><code>pd.read_csv('accuracy_per_item.csv', converters={'accuracy_per... | <p>You can define a customized converter</p>
<pre class="lang-py prettyprint-override"><code>def handle_nan(x):
x = x.replace('nan', '"nan"')
lst = pd.eval(x)
lst = [np.nan if i == 'nan' else i for i in lst]
return lst
df = pd.read_csv('accuracy_per_item.csv', converters={'accuracy_per_item':... | python|pandas|dataframe | 2 |
364,270 | 72,279,924 | Pandas DataFrame - 1 Column to Multiple Columns and 1 Column as Values | <p>I have the following dataset:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Stages</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>Interview</td>
<td>02/01/2022</td>
</tr>
<tr>
<td>2</td>
<td>Mario</td>
<td>Apply</td>
<td>01/01/2022... | <p><code>reset_index</code> after the pivot, not before, and use <code>ID</code> not <code>index</code> as new index:</p>
<pre><code>(df.pivot(index=['ID','Name'], columns='Stages', values='Date')
.reset_index()
.rename_axis(columns=None)
)
</code></pre>
<p>output:</p>
<pre><code> ID Name Apply Interv... | python|pandas | 1 |
364,271 | 72,462,444 | Function for replacing missing values with median from pivot table | <p>My goal is to write a function to replace missing values in the 'total_income' column with the median 'total_income' provided by the pivot table, using the row's 'education' and 'income_type' to index the pivot table. I want to populate using these medians so that the values are as optimal as they can be. Here is wh... | <h3>Annotated code (no need to <code>pivot</code>)</h3>
<pre><code># Change the dtype to numeric
df['total_income'] = df['total_income'].astype(float)
# Calculated median per unique age_group, education and income_type
median = df.groupby(['age_group', 'education', 'income_type'])['total_income'].transform('median')
... | python|pandas|dataframe|pivot-table | 1 |
364,272 | 72,488,131 | Get dict keys using pandas apply | <p>i want to get values from the dict that looks like</p>
<pre><code>pair_devices_count =
{('tWAAAA.jg', 'ttNggB.jg'): 1,
('tWAAAM.jg', 'ttWVsM.jg'): 2,
('tWAAAN.CV', 'ttNggB.AS'): 1,
('tWAAAN.CV', 'ttNggB.CV'): 2,
('tWAAAN.CV', 'ttNggB.QG'): 1}
</code></pre>
<p>(Pairs of domain)</p>
<p>But when i use</p>
<pre><code... | <p>you cannot apply on multiple columns. You can try this :</p>
<pre><code>train_data.apply(lambda x: pair_devices_count[(x.domain, x.target_domain)], axis=1)
</code></pre> | python|pandas|dictionary|hashable | 0 |
364,273 | 72,318,774 | Zillow web scraping using Selenium & BeautifulSoup | <p>I need to do web scraping of 3 pages of California on Zillow of rent houses and put all the data into a pandas data frame. I need to pull all the features of every listing - Address, City, number of bedrooms and bathrooms, size of the house, size of the lot, Year built, rent price, rent date</p>
<p>My code:</p>
<pre... | <p>The data is generated from an external source via API, and also stored in script as JSON format, within an HTML comment. So you can easily pull all the data using <code>re</code> or the API. Here I use the <code>re</code> module:</p>
<pre><code>import requests
import re
import json
r = requests.get('https://www.zil... | python|pandas|selenium|web-scraping|beautifulsoup | 0 |
364,274 | 72,408,683 | Plotly: Plotting columns of a dataframe resulting in blank plot | <p>I've been attempting to create a line graph with subplots for each column of a dataframe in Pandas. My dataframe has variable names as the column names, datetime objects as the columns, and percentages (floats) as the values.
I'm referencing <a href="https://stackoverflow.com/questions/58621197/plotly-how-to-create-... | <p>For anyone else who comes across this: This happens when running plotly in jupyterlab sometimes apparently - I found some additional questions with suggested solutions, but none of them worked for me; What did work however was running it in plain old Jupyter. That's what I'd recommend.</p> | python|pandas|plotly | 0 |
364,275 | 72,143,554 | Pandas create rows based on interval between to dates | <p>I am trying to expand a dataframe containing a number of columns by creating rows based on the interval between two date columns.</p>
<p>For this I am currently using a method that basically creates a cartesian product, which works well on small datasets, but is not good in large sets because it is very inefficient.... | <p>I don't know if this is an approvement, here the <code>pd.date_range</code> only gets created for each start and end date in each row. the created list gets exploded and joined to the original <code>df</code></p>
<pre><code>from datetime import date
import pandas as pd
raw_data = {'id': ['aa0', 'aa1', 'aa2', 'aa3']... | python|pandas|dataframe | 1 |
364,276 | 72,488,981 | In keras-tuner I got the valueError: `logits` and `labels` must have the same shape, received ((None, 2) vs (None, 1)) | <pre><code>def build_model(hp):
model = keras.Sequential()
for i in range(hp.Int('input_shape', 2, 20)):
model.add(layers.Dense(units=hp.Int('units_' + str(i),
min_value=32,
max_value=512,
step=32... | <p>Binary Crossentropy loss expects the model to output a single floating-point value. Your model seems to be outputting 2. Change the last layer of your model to output a single value like so:</p>
<pre><code>model.add(layers.Dense(1, activation='sigmoid'))
</code></pre> | python|tensorflow|keras|deep-learning|keras-tuner | 1 |
364,277 | 72,447,212 | LBFGS Giving Tensor Object not Callable Error when using Optimizer.step | <p>I am trying to use <code>sgd, adam</code>, and <code>LBFGS</code> optimizer.</p>
<p>The part of the code is:</p>
<pre><code>for batch_idx, (inputs, targets) in enumerate(trainloader):
batch_size = inputs.size(0)
total += batch_size
one_hot_targets = torch.FloatTensor(batch_size, 1... | <p>You need to pass a function callback to the <a href="https://pytorch.org/docs/stable/optim.html#optimizer-step-closure" rel="nofollow noreferrer"><code>optimizer.step</code></a> function, don't call it:</p>
<pre><code>optimizer.step(closure)
</code></pre> | optimization|pytorch|closures | 2 |
364,278 | 72,473,409 | How to stop updating the parameters of a part of a layer in a CNN model (not the parameters of the whole layer)? | <p>For example, there are ten parameters(filters) in a CNN layer, how I can do to only update five of them and keep the rest unchanged?</p> | <p>In Pythorch is easy to freeze only part of the net thanks to the requires_grad property:
Here is a simple script:</p>
<pre><code>def freeze_layers(model, num_of_layers):
freezed = 0
for layer in model.children():
freezed += 1
if layer < num_of_layers:
layer.requires_grad = Fals... | python|pytorch|conv-neural-network | 1 |
364,279 | 72,429,296 | How to calculate the area of the positive part of a graph in python? | <p>I have a dataframe</p>
<pre><code>>>print(df)
Power
timestamp
2019-02-16 00:00:00 -7240.2360
2019-02-16 01:00:00 -7598.0856
2019-02-16 02:00:00 -7563.9708
2019-02-16 03:00:00 -7247.5380
2019-02-16 04:00:00 -7167.5292
2019-02-16 05:00:00 -7540.6572
2019-02-1... | <pre><code>#Get area of Positive part of array graph
print(np.trapz(df[df>0],x=df[df>0]))
#Get area of negative part of array graph
print(np.trapz(df[df<0],x=df[df<0]))
</code></pre> | python|pandas|numpy | 0 |
364,280 | 72,225,625 | What are these 2 files in the CenterNet MobileNetV2 from the Tensorflow OD model zoo?, Do we need them? | <p><a href="https://i.stack.imgur.com/cOevp.png" rel="nofollow noreferrer">Do we need these files?, The Tensorflow Doc don't say anything about them</a></p> | <p>The <code>model.tflite</code> file is the pretrained model in <code>.tflite</code> format. So if you want to use the model out of the box, you can use this file.</p>
<p>The <code>label_map.txt</code> is used to map the output of your network to actual comprehensible results. I.e. both of the files are needed if you ... | tensorflow|object|deep-learning|detection | 0 |
364,281 | 72,394,438 | Can I modify pd.Series.value_counts so that by default `dropna=False`? | <p>When using <code>pd.Series.value_counts</code> I almost always add the parameter <code>dropna=False</code>. Is there a simple way to set this as the default value without creating a separate function?</p>
<p>I (<a href="https://github.com/pandas-dev/pandas/issues/21890" rel="nofollow noreferrer">among others</a>) am... | <p>You can check the parameters of <code>pd.Series.value_counts</code>:</p>
<pre class="lang-py prettyprint-override"><code>print(pd.Series.value_counts.__annotations__)
# Ouput
{'normalize': 'bool', 'sort': 'bool', 'ascending': 'bool', 'dropna': 'bool'}
</code></pre>
<p>And the associated default values:</p>
<pre clas... | python|pandas | 1 |
364,282 | 72,273,946 | Using numpy to find area of polygon | <p>I have been reading through some python code and have come to this function for the polygon area using numpy.</p>
<pre><code>def polygon_area(self, x,y):
correction = x[-1] * y[0] - y[-1]* x[0]
main_area = np.dot(x[:-1], y[1:]) - np.dot(y[:-1], x[1:])
return 0.5*np.abs(main_area + correction)... | <p>This is a calculation of the area of a polygon using the shoelace formula. The correction is just the term not calculated in the <code>main_area</code> shortcut.</p>
<p>A lot more maths than python or numpy for that matter.</p> | python|numpy|polygon | 2 |
364,283 | 72,340,897 | When I one hot encode a column with corresponding values. It gets null values in between them | <p>I hope this finds you all well. I have been working with a steel data-set. I was trying to one_hot_encode a categorical data column with their corresponding values using mapping method. However when I do this the column gets null values in between. I am unable to understand why. The column before one_hot_encoding di... | <p>@ansev has answered your immediate question in the comments.</p>
<p>Here's another way to do what you want to do that may be easier for you:</p>
<pre><code>df["material_spec"].str.extract(r'Material_(\d+)').astype(int)
</code></pre>
<p>But what you are doing is not really one-hot encoding is it? I think o... | python|pandas|dataframe|mapping|one-hot-encoding | 0 |
364,284 | 72,276,887 | How can you use RD coordinates instead of gps coordinates to plot traffic routes in a folium plot? | <p>In want to show traffic routes on a folium map. These routes are in the Netherlands and the coordinates are in RD (EPSG:28992). I tried to map the routes using the following code:</p>
<pre><code>my_map = folium.Map(location=(52.2130,5.2794), tiles='cartodbpositron', zoom_start=7, control_scale=True)
origin = [rap.r... | <p>See this question on GIS stack exchange: <a href="https://gis.stackexchange.com/questions/198695/leaflet-changing-base-map-crs">https://gis.stackexchange.com/questions/198695/leaflet-changing-base-map-crs</a>. It references the <a href="https://leafletjs.com/examples/wms/wms.html" rel="nofollow noreferrer">Leaflet W... | python|geometry|geopandas|folium | 1 |
364,285 | 72,332,202 | AttributeError at /app/ 'numpy.ndarray' object has no attribute 'read' | <p>I am making a wep app for face recognition by django and face_recogntion api, I don't how to solve this error</p>
<pre><code>from django.http import HttpResponse
from django.shortcuts import redirect, render
from .models import *
import face_recognition
import cv2
import urllib.request
import numpy as np
import dlib... | <p>Your problem is here:</p>
<pre><code>imageURL = urllib.request.urlopen(request.POST["imageURL"])
imageURL = face_recognition.load_image_file(imageURL)
image = face_recognition.load_image_file(imageURL)
</code></pre>
<p>First</p>
<pre><code> imageURL = face_recognition.load_image_file(imageURL)
</code></pre... | python|django|numpy-ndarray|face-recognition|web-development-server | 0 |
364,286 | 72,189,254 | Modifying JSON colums in Python | <p>I have data in the following format in my dataframe</p>
<pre><code>>>> Surveyresp['Warehouse.Response.jud_3_3_q']
1 ['item3', 'item4', 'item2', 'item1']
Name: Warehouse.Response.jud_3_3_q, dtype: object
</code></pre>
<p>This snipped of data shows the way user responses are formatted in my data to a s... | <p>You can try combine the <code>q.1</code> to <code>q.4</code> to list</p>
<pre class="lang-py prettyprint-override"><code>d = {'Warehouse.Response.jud_3_3_q.1': ['item1'], 'Warehouse.Response.jud_3_3_q.2': ['item2'], 'Warehouse.Response.jud_3_3_q.3': ['item3'], 'Warehouse.Response.jud_3_3_q.4': ['item4']}
answer = p... | python|json|pandas | 0 |
364,287 | 72,185,142 | Remove expression from pandas dataframe and replace it with NAN values | <p>I want to remove some pattern, particularly '--', '-', '- -', '- -' from my dataframe columns and replace it with NaN values.</p>
<p>Help me find solution for the same. Dataframe is given below:</p>
<p><a href="https://i.stack.imgur.com/oWC3j.png" rel="nofollow noreferrer">Data frame image</a></p> | <p>Well I quickly found out a way to replace this pattern:</p>
<pre><code>for i in range(len(df)):
for j in range(len(df.columns)):
if df.iloc[i][j] == '--':
print(df.iloc[i][j])
df.iloc[i,j] = np.nan
</code></pre>
<p>I hope this helps.</p> | python-3.x|pandas | 0 |
364,288 | 72,334,213 | merge two dataframe with unequal and duplicate index | <p>I have a empty dataframe with a datetime index like this:</p>
<pre><code>>>> idx_df
Empty DataFrame
Columns: []
Index: [2020/1/1, 2020/1/1, 2020/1/2, 2020/1/2, 2020/1/3, 2020/1/3, 2020/1/3, 2020/1/3, 2020/1/3, 2020/1/4, 2020/1/4, 2020/1/4, 2020/1/5, 2020/1/5, 2020/1/5, 2020/1/5]
</code></pre>
<p>I want merg... | <p>You can just do <code>reindex</code></p>
<pre><code>out = df2.reindex(idx_df.index)
</code></pre> | python|pandas | 0 |
364,289 | 72,414,861 | Groupby year dropping some variables | <p>This is the original data and I need the mean of each year of all the variables.</p>
<p><img src="https://i.stack.imgur.com/sf4ye.png" alt="Original data" /></p>
<p>But when I am using <code>groupby('year')</code> command, it is dropping all variables except 'lnmcap' and 'epu'.</p>
<p><img src="https://i.stack.imgur... | <p>You might want to convert all numerical columns to float before getting their mean, for example</p>
<pre><code>cols = list(ds.columns)
#remove irrelevant columns
cols.pop(cols.index('company'))
cols.pop(cols.index('year'))
#convert remaining relevant columns to float
for col in cols:
ds[col] = pd.to_numeric(ds... | python|pandas|dataframe|group-by | 1 |
364,290 | 72,363,816 | Pandas: Create table from data frame matching columns to a list | <p>I am trying to create a matrix from a data frame and a list. The list and column 1 of the data frame contain the same strings, however, not all of the strings in the list are in the column 1 and are not in the same order (see example below). I would like to search through the data frame, and print the data in the se... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a>:</p>
<pre><code>Occurences.set_index('sequence').reindex(seqList).reset_index()
</code></pre>
<pre><code> sequence hits
0 ... | python|pandas | 1 |
364,291 | 72,415,001 | How to sort pandas dataframe by month name | <p>I have the following data frame:</p>
<p><a href="https://i.stack.imgur.com/b5CMd.png" rel="nofollow noreferrer">https://i.stack.imgur.com/b5CMd.png</a>
(44 rows)</p>
<p>I tried sorting it by using CategoricalIndex() but found out it can only be done if there are no repeat in month values. Any one know how to sort it... | <p>You can also try:</p>
<pre><code>df['date']=(df['month']+' '+df['year'])
df['date']=pd.to_datetime(df['date'])
df=df.sort_values('date')
</code></pre> | python|pandas|database|dataframe | 0 |
364,292 | 72,230,049 | Most efficient way to search over a DataFrame in Python | <p>I have a DataFrame having these kind of data :</p>
<pre><code>df = pd.DataFrame({
'id' : ['a', 'a', 'b', 'b', 'c', 'c'],
'alias' : ['value'+str(i) for i in range(6)],
'source' : ['src1', 'src2', 'src1', 'src2', 'src1', 'src3']
})
print(df)
</code></pre>
<p>output :</p>
<pre><code> id alias source
0 ... | <p>I believe you want to <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'id' : ['a', 'a', 'b', 'b', 'c', 'c'],
'alias' : ['value'+str(i) for i in range(6)],
'source' ... | python|pandas|dataframe|performance | 1 |
364,293 | 72,163,736 | Save the Output of for loop of a DataFrame to a DataFrame that is declared outside | <p>Is there any way to save the output of a dataframe that is evaluated inside a for loop to a data frame that is empty and is declared outside the for loop?
Can we save the output of for loop separately for every iteration?</p>
<pre><code>new_dict1 = {'ABW':{'ABR':1,'BPR':1,'CBR':1,'DBR':0},'BCW':{'ABR':0,'BPR':0,'CBR... | <p>you can <code>concat</code> the dataframes:</p>
<pre><code>import pandas as pd
new_dict1 = {'ABW':{'ABR':1,'BPR':1,'CBR':1,'DBR':0},'BCW':{'ABR':0,'BPR':0,'CBR':1,'DBR':0},
'CBW':{'ABR':1,'BPR':1,'CBR':0,'DBR':0},'MCW':{'ABR':1,'BPR':1,'CBR':0,'DBR':1}}
df = pd.DataFrame.from_dict(new_dict1,orient="index&qu... | python|pandas|dataframe|dictionary | 0 |
364,294 | 72,142,853 | Assigning to a double-indexed numpy array | <p>I know that when assigning to a double indexed-array gives bad results because you're assigning to a view rather then to an array directly, but I cannot figure out how to properly assign to double-indexed array:</p>
<pre><code>import numpy as np
foo = np.array([1, 2, 3, 4, 5])
bar = np.array([False, True, True, True... | <p>Assuming you want to index using both a boolean array and a slice of the True values in this array, you would need to compute another boolean array that summarizes those conditions.</p>
<p>Here is a possible approach based on the indices of the boolean array:</p>
<pre><code>idx = np.arange(len(bar))
foo[idx[bar][1:3... | python|arrays|numpy|indexing | 1 |
364,295 | 72,429,640 | Numpy function that returns the minimum dtype to hold the objects in the sequence? | <p>As stated, is there a numpy function that can return the minimum dtype required when creating an array? For example, if the input is a list <code>[3., 4.]</code> and dtype is not specified, then <code>np.array</code> will choose <code>numpy.float64</code> as dtype; if the input is <code>[3, 4]</code> then <code>np.a... | <p>To answer my own question, I do find the desired function when searching the numpy doc. It is called <a href="https://numpy.org/doc/stable/reference/generated/numpy.min_scalar_type.html#numpy.min_scalar_type" rel="nofollow noreferrer">numpy.min_scalar_type</a> which is new in version 1.6.0.</p>
<p>What I want is to ... | python|numpy | 1 |
364,296 | 72,297,756 | Pandas groupby: coordinates of current group | <p>Suppose I have a data frame</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'group':['A','A','B','B','C','C'],'score':[1,2,3,4,5,6]})
</code></pre>
<p>At first, say, I want to compute the groups' sums of scores. I usually do</p>
<pre><code>def group_func(x):
d = {}
d['sum_scores'] = x['score'].sum()
... | <p>Just add <code>.name</code></p>
<pre><code>def group_func(x):
d = {}
d['sum_scores'] = x['score'].sum()
d['group_name'] = x.name # d['group_name'] = x['group'].iloc[0]
return pd.Series(d)
df.groupby('group').apply(group_func)
Out[63]:
sum_scores group_name
group ... | python-3.x|pandas|dataframe|pandas-groupby | 1 |
364,297 | 72,291,893 | Python save CSV without changing ID to an integer | <p>I have a df <em>in Python</em> with an ID column - those IDs can be a mix of numbers and letters, or solely numbers. Eg:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>00028D9D1</td>
</tr>
<tr>
<td>00027B98F</td>
</tr>
<tr>
<td>000275457</td>
</tr... | <p>According to <a href="https://datatracker.ietf.org/doc/html/rfc4180" rel="nofollow noreferrer">RFC 4180</a>, CSV files do not contain any type information, so it is solely the responsibility of the application to correctly interpret the contents of the file. From what I read in your question,</p>
<blockquote>
<p>I h... | python|pandas|csv | 0 |
364,298 | 72,274,153 | Run Different Scikit-learn Clustering Algorithms on Dataset | <p>I have a dataframe like below. The shape is (24,7)</p>
<pre><code>Name x1 x2 x3 x4 x5 x6
Harry 102 204 0.43 0.21 1.02 0.39
James 242 500 0.31 0.11 0.03 0.73
.
.
.
Mike 3555 4002 0.12 0.03 0.52. 0.11
Henry 532 643 0.01 0.02 0.33 0.10
</code></pre>
<p>I want to run Scikit-learn's D... | <p>PS : please replace : data = X_data.iloc[:20000] by your X</p>
<pre><code>import numpy as np
import matplotlib as plt
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import decomposition
from sklearn import preprocessing
from sklearn import cl... | python|pandas|machine-learning|scikit-learn|cluster-analysis | 1 |
364,299 | 72,368,294 | How to not break differentiability with a model's output? | <p>I have an autoregressive language model in Pytorch that generates text, which is a collection of sentences, given one input:</p>
<pre><code>output_text = ["sentence_1. sentence_2. sentence_3. sentence_4."]
</code></pre>
<p>Note that the output of the language model is in the form of logits (probability ove... | <p>Okay solved it. Posting answer for completion.</p>
<p>Since the output is in the form of logits, I can take the <code>argmax</code> to get the indices of each token. This should allow me to know where each <code>period</code> is (to know where the end of the sentence is). I can then split the sentences in the follow... | python|machine-learning|split|pytorch|language-model | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.