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 |
|---|---|---|---|---|---|---|
17,100 | 71,686,844 | Formatting List to Columns for CSV | <p>I am trying to a calculated list to serve as 2 additional columns in an existing csv, however I struggle with preparing them as 2 columns.</p>
<p>MWE:</p>
<pre><code>import pandas as pd
from transformers import BertTokenizer, BertForSequenceClassification, pipeline
df = pd.read_csv('original.csv')
dtype_before = ty... | <p>Please try this, if it helps:</p>
<pre><code>import pandas as pd
x = [[{'label': 'γγΈγγ£γ', 'score': 0.7804045081138611}], [{'label': 'γγΈγγ£γ', 'score': 0.9542087912559509}], [{'label': 'γγΈγγ£γ', 'score': 0.8557115793228149}],
[{'label': 'γγΈγγ£γ', 'score': 0.9135494232177734}], [{'label': 'γγΈγγ£γ', 'score': 0.862447... | python|pandas|dataframe|export-to-csv | 1 |
17,101 | 71,451,182 | Get groups where values go from 0 to 1 | <p>I want to get all the users from a dataframe where a specific column goes from <code>1</code> to <code>0</code>.</p>
<p>For example, with the following dataframe I want to keep only user 1 and 2 as their values go from <code>1</code> to <code>0</code>.</p>
<p><em>Relevant rows</em></p>
<ul>
<li>Row 6 to 7 for user 1... | <p>Let us try <code>cummax</code></p>
<pre><code>df.loc[df.user.isin(df.loc[df.value != df.groupby('user')['value'].cummax(),'user'])]
Out[769]:
user value
4 1 0
5 1 1
6 1 1
7 1 0
8 2 1
9 2 1
10 2 0
11 2 0
</code></pre> | python|pandas|dataframe|numpy | 1 |
17,102 | 42,572,744 | Combine date and time columns using datetime | <p>I am trying to combine the date to multiple time columns in my dataframe. I am able to iterate through each row, but I am confused as to how I combine the columns. For example:</p>
<pre><code> date first_time second_time ....
0 2008/09/11 12:32 17:56
1 2016/12/02 06:43 14:02
2 200... | <p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> with column <code>date</code> and then in loop of <code>time</code> columns convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.... | python|pandas|datetime|dataframe|anaconda | 1 |
17,103 | 42,236,830 | Pandas add keys while concatenating dataframes at column level | <p>As per Pandas 0.19.2 documentation, I can provide <strong>keys</strong> argument to create a resulting multi-index DataFrame. An example (from pandas documents ) is :</p>
<p><code>result = pd.concat(frames, keys=['x', 'y', 'z'])</code>
<a href="https://i.stack.imgur.com/4u0Dn.png" rel="nofollow noreferrer"><img src... | <p>This is supported by <code>keys</code> parameter of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>pd.concat</code></a> when specifying <code>axis=1</code>:</p>
<pre><code>df1 = pd.DataFrame(np.random.random((4, 4)), columns=list('ABCD'))
df2 = pd.... | python|pandas|concatenation | 3 |
17,104 | 42,317,664 | Trying to implement networkx into graphicsscene | <p>-------- companytrades.csv --------</p>
<pre><code>date,Company1,Company2
1/2/2017,1001,1111
1/3/2017,1001,1100
1/4/2017,1111,1001
1/5/2017,1100,1001
1/6/2017,1011,1001
1/7/2017,1001,1111
1/8/2017,1111,1100
1/9/2017,1100,1011
</code></pre>
<p>I found this great example of a set of classes implementing a networkx i... | <p>A more minimal question might help with obtaining an answer. (for instance, nothing from your <code>x.py</code> seems relevant to the problem at the end)</p>
<p>To get you started, you are likely suffering from some namespace overloading (renaming the same objects). In <code>netxgui.py</code> you have <code>impor... | pandas|pyqt4|networkx|qgraphicsview|qgraphicsscene | 1 |
17,105 | 42,238,099 | How to fill in values for a column in a dataframe by matching values from another dataframe pandas | <p>I'm new to python and am working with the kaggle titanic dataset to practice.</p>
<p>I'm trying to fill in a couple missing values for the cabin feature by using rows that have the same tickets. That is, I want to get a list of duplicate tickets and their corresponding cabin value and replace the null values with t... | <p>You groupby the Ticket to group together rows with matching tickets and fill null values using first_valid_index that returns the first non-null value in the group.</p>
<pre><code>df['Cabin'] = df.groupby('Ticket')['Cabin'].transform(lambda x: x.loc[x.first_valid_index()])
</code></pre> | python|pandas | 1 |
17,106 | 69,801,724 | Python Pandas Merge Two Dataframes Based on Another Correspondence Dataframe | <p>I'm working with 2 dataframes. Dataframe1 is for parking sites. Dataframe2 is for sensors. Correspondence dataframe shows which sensor is in which site.</p>
<p>Dataframe1:</p>
<pre><code> Site Time Available Capacity
0 19E 12:00 5 10
1 19E 13:00 4 10
2 44E 12:00 8 ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> to map <code>Site</code> to <code>Sensor</code> and then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html#pandas.DataFra... | python|pandas|dataframe|join|merge | 1 |
17,107 | 43,378,625 | SciPy/numpy: Only keep maximum value of a sparse matrix block | <p>I am trying to operate on a large sparse matrix (currently 12000 x 12000).
What I want to do is to set blocks of it to zero but keep the largest value within this block.
I already have a running solution for dense matrices:</p>
<pre><code>import numpy as np
from scipy.sparse import random
np.set_printoptions(prec... | <pre><code>def keep_only_max(a,b,c,d):
sub = x[a:b,c:d]
z = np.max(sub)
sub[sub < z] = 0
</code></pre>
<p>For a sparse <code>x</code>, the <code>sub</code> slicing works for <code>csr</code> format. It won't be as fast as the equivalent dense slice, but it will create a copy of that part of <code>x</code>. ... | python|numpy|scipy | 1 |
17,108 | 72,251,640 | Change values in DataFrame based on a dict | <p>I have a Pandas Dataframe, eg. like below:</p>
<pre><code> Name Age Papers
0 tom 10 12
1 nick 15 8
2 juli 14 8
</code></pre>
<p>And I have a dictionary:</p>
<pre><code>d = {10: 11, 14: 30, 20: 44}
</code></pre>
<p>I want to change values in <code>df</code>, such that where <code>Age</c... | <p>You can use:</p>
<pre><code>df['Papers'] = df['Age'].map(d).combine_first(df['Papers']).astype(int)
</code></pre>
<p><code>map</code> replaces each Age using the dictionary, which adds NaN if the values are missing so we use <code>combine_first</code> to add the old values back.</p>
<p>Output:</p>
<pre><code> Name... | python|pandas|dataframe | 2 |
17,109 | 54,301,005 | Import data from text file with multiple conditions using Pandas | <p>I'm trying to parse this text file using Pandas data frame.
The text file is in this particular format:</p>
<pre><code>Name: Tom
Gender: Male
Books:
The problem of Pain
The reason for God: belief in an age of skepticism
</code></pre>
<p>My code so far to import the data is:</p>
<pre><code>import pandas as pd
... | <p>You can do two things. You can use <code>enumerate()</code>, and use an <code>if</code> statement:, I used a text file named <code>test.txt</code> in the below code.</p>
<pre><code>import pandas as pd
d = {}
value_list = []
for index, text in enumerate(open('test.txt', "r")):
if index < 2:
d[text.spl... | python|pandas | 1 |
17,110 | 54,261,103 | convert grouped dataframe to dictionary with apply/lambda | <p>I have a df like this</p>
<pre><code> A B C
0 11 one 5
1 11 two 7
2 11 three 9
3 22 one 11
4 22 two 13
</code></pre>
<p>I'd like to convert this df to dictionary like this:</p>
<pre><code>{11: [(one, 5), (two, 7), (three, 9)]
22: [(one, 11), (two, 13)]}
df_dic... | <p>Try,</p>
<pre><code>df.groupby('A').apply(lambda x: list(zip(x.B, x.C))).to_dict()
{11: [('one', 5), ('two', 7), ('three', 9)], 22: [('one', 11), ('two', 13)]}
</code></pre> | python-3.x|pandas|dictionary | 1 |
17,111 | 73,750,972 | how to access dataframe index after concatenating 2 dataframes: one with multiindex, one without | <p>I want to access a column/index in a dataframe that is a concatenation between 2 dataframes, one that has a multiindex, and an other that doesn't. Questions are inside the code.</p>
<pre><code>import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.ones((2, 2)), columns=["a", "b"])
df2_col... | <p>Seems like a bug to me.</p>
<p>You can cheat and use 2D slicing:</p>
<pre><code>df.loc[:, [('c', 1)]]
</code></pre>
<p>Output:</p>
<pre><code> (c, 1)
0 1.0
1 1.0
</code></pre>
<p>You can assign correctly:</p>
<pre><code>df.loc[:, [('c', 1)]] = [8,9]
</code></pre>
<p>Updated DataFrame:</p>
<pre><code> a... | python|pandas|dataframe|multi-index | 1 |
17,112 | 73,647,539 | Merge groupby df with repeated index df, drop non-matching rows | <p>I want to merge the following <code>df</code> with the <code>series_object</code> below it (details below them):</p>
<p>df1</p>
<pre><code> wallet cumulative_rewards position position_rewards position_type
0 0x12345 0 LUSD 1000 LP Pair
0 0x123... | <p>Use:</p>
<pre><code>print (df1)
wallet cumulative_rewards position position_rewards position_type
0 0x12345 0 LUSD 1000 LP Pair
0 0x12345 0 TOKE 200 LP Token
1 0xabcde 0 UNI_LP 500 ... | python|pandas|dataframe|join|group-by | 1 |
17,113 | 71,138,474 | How to fix "Boolean value of Tensor with more than one value is ambiguous"? | <p>I am trying to create a Model, but i'm getting a RuntimeError "Boolean value of Tensor with more than one value is ambiguous". I've searched already on other posts about this but could find a working solution so here is my own try.</p>
<p>I am following a tutorial, which is working with the tutorial set of... | <p><strong>Short answer</strong>:<br />
Remove the <code>Variable()</code></p>
<p><strong>Explanation</strong>:<br />
I believe your answer is in you question. If you don't know what Variable is, why are you using it? But more importantly you are importing it from <code>tkinter</code> which is an interface package and ... | python|deep-learning|neural-network|pytorch|artificial-intelligence | 0 |
17,114 | 52,182,051 | How to import dats from one sheet to another sheet based on Substring using python | <p>My goal here is to import the data stored as DataFrame df1 in sheet1 based on the substring.</p>
<p>My DataFrame looks like below: </p>
<pre><code>df:[2 x 8]
ordercode quantity
PMC11-AA1L1FAVWJA 20
PMC21-AA1A1CBVXJA 10
PMP11-AA1L1FAWJJ 5
PMP21-AA1A1FBWJJ 3
PMP23-AA1A1... | <p>First read your data into a Pandas dataframe:</p>
<pre><code>df = pd.read_excel('file.xlsx')
</code></pre>
<p>Then use a dictionary comprehension with <code>pd.Series.str.contains</code>:</p>
<pre><code>substrings = ['1C', '1F']
d = {x: df[df['ordercode'].str.contains(x, na=False, regex=False)] for x in substrin... | python|excel|pandas | 1 |
17,115 | 60,579,343 | padding and attention mask does not work as intended in batch input in GPT language model | <p>The following code is without batch:</p>
<pre><code>from transformers import GPT2LMHeadModel, GPT2Tokenizer
import torch
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained('gpt2')
model.eval()
context=torch.tensor([tokenizer.encode("This is")])
output, past = model(context)
t... | <p>I'm not sure if this helps, but you don't need to implement you own attention masking and padding. The Transformers library provides the <a href="https://huggingface.co/transformers/main_classes/tokenizer.html#transformers.PreTrainedTokenizer.encode_plus" rel="nofollow noreferrer">encode_plus()</a> and <a href="http... | python|pytorch|language-model|huggingface-transformers | 1 |
17,116 | 60,729,852 | Drop a level in pandas dataframe header | <p>My dataframe looks like:</p>
<p><a href="https://i.stack.imgur.com/3nHyu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3nHyu.png" alt="enter image description here" /></a></p>
<p>Can I transform this into a simple single line header, like:</p>
<pre><code>userId (no genres listed) Action Adven... | <p>You should use df.reset_index() method available in pandas.
Refer to the link here: </p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html</... | python|pandas|dataframe | 0 |
17,117 | 60,498,031 | PyTorch: Simple feedforward neural network not running without retain_graph=True | <p>Below is my code for training a Feedforward neural network (FFNN). </p>
<p>The labels are numbers between 0 and 50. The FFNN comprises of a single hidden layer with 50 neurons and an output layer with 51 neurons. Furthermore, I have used negative log likelihood loss.</p>
<p>I am very new to PyTorch so I used a cou... | <p>You are missing <code>.zero_grad()</code> operation. Add that to the loop and your code will work fine without <code>retain_graph= True</code>. </p>
<pre><code>loss.backward()
opt.step()
opt.zero_grad()
</code></pre> | python|debugging|pytorch|backpropagation|loss-function | 1 |
17,118 | 60,652,667 | Collapse(or combine) multiple columns into two separate columns python | <p>I have a <code>dataframe</code> as shown below:</p>
<pre><code>8964_real 8964_imag 8965_real 8965_imag 8966_real 8966_imag 8967_real ... 8984_imag 8985_real 8985_imag 8986_real 8986_imag 8987_real 8987_imag
0 112.653120 0.000000 117.104887 0.000000 127.593406 0.000000 129.522106 ... ... | <p>Create <code>MultiIndex</code> by <code>split</code>, so possible reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a>:</p>
<pre><code>df.columns = df.columns.str.split('_', expand=True)
print (df.head(... | python|pandas|dataframe|multiple-columns|concat | 3 |
17,119 | 60,734,016 | Marking Duplicates while ignoring null values in pandas | <p>I have been trying to highlight duplicates values in my df by using below code.</p>
<pre><code>ncns['D-Account'] = ncns.duplicated('Account Number')
</code></pre>
<p>Although it marks the duplicates correctly, but it also marks the blank values as duplicate. </p>
<p>Please suggest something so that it should igno... | <p>If blank are missing values chain mask for test non misisng values by <code>&</code> for bitwise <code>AND</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.notna.html" rel="nofollow noreferrer"><code>Series.notna</code></a>:</p>
<pre><code>ncns['D-Account'] = ncns.dup... | python|pandas | 3 |
17,120 | 60,454,846 | BigQuery Results to Panda DataFrame in Chunks | <p>I am trying to save the results of a BigQuery query to a Panda DataFrame using <code>bigquery.Client.query.to_dataframe()</code></p>
<p>This query can return millions of rows.</p>
<p>Given that Panda to BQ (<code>Dataframe.to_gbq()</code>) has a chunk parameter, is there something similar for BQ to Pandas to incre... | <p>You can use <code>to_dataframe_iterable</code> instead to do this.</p>
<pre class="lang-py prettyprint-override"><code>job = client.query(query)
result = job.result(page_size=20)
for df in result.to_dataframe_iterable():
# df will have at most 20 rows
print(df)
</code></pre> | python|pandas|google-bigquery | 3 |
17,121 | 72,833,498 | How do i loop and collect data after closing webdrivers | <p>I am trying to be able to go to a tournament href, input that into the url then cycle through the rounds before closing that driver and opening a new one to do the same thing. For some reason i can't figure where to put the beginning url.</p>
<pre><code>from selenium import webdriver
import time
import pandas as pd
... | <p>You do not need to <code>.quit()</code> the <code>driver</code> with every iteration, cause you are changing its target url.</p>
<p>Main issue should be to construct the correct <code>url</code>, so change <code>{ytournaments}</code>:</p>
<pre><code>page = driver.get(f"https://www.europeantour.com{ytournaments}... | python|pandas|selenium|loops|beautifulsoup | 1 |
17,122 | 72,535,034 | module 'torch' has no attribute 'has_mps' | <p>I just followed a youtube video that teaches how to install PyTorch nightly for MacBook to accelerate by m1 chip. However, I came across a problem really wierd. I can see in the jupyter notebook that torch.has_mps = True. But in jupyter notebook in vscode, it shows that module 'torch' has no attribute 'has_mps'.</p... | <p>Just make sure you installed the nightly build of PyTorch.
Apple Silicon support in PyTorch is currently available only in nightly builds.</p>
<p>e.g., if you're using conda, try this:</p>
<pre><code>conda install pytorch torchvision -c pytorch-nightly
</code></pre>
<p>or with pip</p>
<pre><code>pip3 install --pre t... | pytorch | 2 |
17,123 | 59,828,981 | Find difference between two pandas Dataframes and and add all to new DF | <p>I have two <code>Guest-Lists</code>, in DataFrames, and I want know which names dropped out, which ones were added, and then get a new DF, what do I do?</p>
<p>The two DFs are:</p>
<pre><code>list1 = {'First Name': ['Adi', 'Beni', 'Dimi', 'Sergei'], 'Last Name': ['Beer', 'Wine', 'Liquor', 'Vodka'], 'Job': ['Brewe... | <p>The easiest way is to put the first and last names together, compare them and then separate them again.</p>
<p>Here is the corresponding code:</p>
<pre><code>FIRST_NAME = 'First Name'
LAST_NAME = 'Last Name'
JOB = 'Job'
KEYS = [FIRST_NAME, LAST_NAME, JOB]
def intersection(lst1, lst2):
return [value for value... | python|pandas|concat | 1 |
17,124 | 59,829,531 | How to return value_counts() when grouped by another column in pandas | <p>I'm want to return the values in a value_counts of col2 back to the original dataframe after a pandas groupby based on col1.</p>
<p>i.e. I have...</p>
<pre><code> col1 col2
0 1111 A
1 1111 B
2 1111 B
3 1111 B
4 1111 C
5 2222 A
6 2222 B
7 2222 C
8 2222 C
</code></pre>
<p>and I... | <p>you can make this with <code>groupby</code> and <code>transform</code>.</p>
<pre><code>df['col3'] = df1.groupby(['col1','col2'])['col2'].transform('count')
print(df)
col1 col2 col3
0 1111 A 1
1 1111 B 3
2 1111 B 3
3 1111 B 3
4 1111 C 1
5 2222 A 1
6 2222 B 1... | python|pandas | 3 |
17,125 | 59,747,062 | Merge multiple rows to one row in a csv file using python pandas | <p>I have a csv file with multiple rows as stated below</p>
<pre><code>Id Name Marks1 Marks2 Marks3 Marks4 Marks5
1 ABC 10 NAN NAN NAN NAN
2 BCD 15 NAN NAN NAN NAN
3 CDE 17 NAN NAN NAN NAN
1 ABC NAN 18 NAN 17 NAN
2 BCD NAN 10 NAN 15 ... | <p>IIUC, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> + <code>as_index=False</code> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.first.html" rel="nof... | python|database|pandas|pandas-groupby | 3 |
17,126 | 61,789,949 | Epoch time increasing when running Pytorch on AML docker | <p>The epoch time keeps increasing when running Pytorch training on AML and a custom docker image.
When the same code is running locally the epoch time is constant (the difference here is that there is no docker image involved and the training dataset exists locally, so not a mounted blob storage by AML and the machine... | <p>Although not a fully scripted way, I usually do this kind of debugging by running my training in <code>tmux</code> session, with an active <code>htop</code> in the second terminal, and in your case an <code>nvidia-smi -l 1</code> in a third one.</p>
<p>Are you mounting the blob-store or downloading the data to the ... | docker|machine-learning|pytorch|azure-machine-learning-service | 0 |
17,127 | 62,033,283 | Is torch.as_tensor() the same as torch.from_numpy() for a numpy array on a CPU? | <p>On a CPU, is <code>torch.as_tensor(a)</code> the same as <code>torch.from_numpy(a)</code> for a numpy array, <code>a</code>? If not, then why not?</p>
<p>From the docs for <code>torch.as_tensor</code></p>
<blockquote>
<p>if the data is an <code>ndarray</code> of the corresponding <code>dtype</code> and
th... | <p>They are basically the same, except than <code>as_tensor</code> is more generic:</p>
<ul>
<li>Contrary to <code>from_numpy</code>, it supports a wide range of datatype, including list, tuple, and native Python scalars.</li>
<li><code>as_tensor</code> supports changing dtype and device directly, which is very conveni... | pytorch | 3 |
17,128 | 57,791,287 | Segmentation Fault while reading parquet file from AWS S3 using read_parquet in Python Pandas | <p>I have a python script running on an AWS EC2 (on AWS Linux), and the scripts pulls a parquet file from S3 into Pandas dataframe. I'm now migrating to new AWS account and setting up a new EC2. This time when executing the same script on python virtual environment I get "Segmentation Fault" and the execution ends.</p>... | <p>I was able to solve this by changing the used engine parameter.
according to the official documentation of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_parquet.html" rel="nofollow noreferrer">pandas</a>, those are the engine options: </p>
<blockquote>
<p>engine : {βautoβ, βpyar... | python|pandas|amazon-web-services|fastparquet | 1 |
17,129 | 55,031,839 | Removing entries from Pandas DF beginning with letter and two numbers | <p>I am curious as to how to remove string entries from a Pandas DF beginning with a letter and two numbers and replacing with NaN.</p>
<pre><code>A B C D
Apple Pear N45 82f John
Cat P48 hH2 Mary Sponge
Hat P67 De1 Bed S90 GGGF
</code></pre>
<p>I would l... | <p>You can try this:</p>
<pre><code>df.mask(df.apply(lambda r: r.str.contains('[a-zA-Z]{1}\d{2}')))
</code></pre>
<p>Output:</p>
<pre><code> A B C D
0 Apple Pear NaN John
1 Cat NaN Mary Sponge
2 Hat NaN Bed NaN
</code></pre>
<p>I like @coldspeed's stack too:</p>
<pre><c... | python|pandas | 1 |
17,130 | 49,786,769 | Need to handle a concatenated dataframe with non-unique multi-index | <p>This works:</p>
<pre><code>import pandas as pd
raw_data = {
'type_1': [1, 1],
'id_1': ['2', '3'],
'name_1': ['Alex', 'Amy']}
df_a = pd.DataFrame(raw_data, columns = ['type_1', 'id_1', 'name_1'])
raw_datab = {
'type_2': [1, 1],
'id_2': ['4', '5'],
'name_2': ['Billy',... | <p>Change <code>axis=1</code> to <code>axis=0</code>(defualt)</p>
<pre><code>df = pd.concat(dfs)
df
Out[52]:
name_1 name_2
type_1 id_1
1 2 Alex NaN
2 Amy NaN
4 NaN Billy
5 NaN Brian
</code></pre>
<p>Base on your comment ..</p>
<pre><... | python|python-3.x|pandas|dataframe | 5 |
17,131 | 49,582,826 | InvalidArgumentError for autoencoder with keras | <p>I'm training an autoencoder (with the keras blog code), and I'm getting the fallowing error</p>
<pre><code>InvalidArgumentError (see above for traceback): Incompatible shapes: [1,420,748,3] vs. [1,422,750,3]
[[Node: loss/conv2d_7_loss/sub = Sub[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](co... | <p>The problem is your variables "blured" (420 x 748 x 3) and "img" (422 x 750 x 3) do not have the same shape. Auto-encoder expects same input and label shapes since it is trained to learn to go from inputs into a bottleneck layer and from there to labels.</p> | tensorflow|keras | 0 |
17,132 | 49,667,502 | Python/Pandas- applying label at trend shift (identifying local maxima and minima in dataset) | <p>So I have a CSV where I have stock prices and for every day (row) I have a corresponding column that shows whether the price increased or decreased over the previous day.</p>
<p>Task:I want to identify peaks and troughs (see example screenshot).
Logic: The last 'increase" cell before the trend changes should be lab... | <p>This is a vectorised solution using <code>pandas</code> and <code>numpy</code> functionality.</p>
<pre><code>import pandas as pd, numpy as np
df = pd.DataFrame({'seq': ['inc', 'dec', 'inc', 'inc', 'inc', 'dec', 'dec', 'dec', 'inc']})
df['mark'] = df['seq'].map({'inc': 1, 'dec': -1}).diff().shift(-1).map(np.sign).... | python|pandas|loops|csv | 2 |
17,133 | 49,713,384 | How do I exclude a single row from groupby().transform() in pandas? | <p>My intended goal was to perform a simple <code>groupby</code>, then store the group averages as a new column using <code>.transform('mean')</code>. Then things got complicated. The catch is that what I really want is an average of n-1 values, where 'n' is the number of rows belonging to each group. Example data, whe... | <p>Got the answer from my comment above.</p>
<pre><code>list_of_tuples = [('A', 3, 4.5),
('A', 2, 4.75),
('A', 5, 4),
('A', 4, 4.25),
('A', 7, 3.5),
('B', 6, 6.75),
('B', 9, 6),
('B', 8, 6.25),... | pandas|pandas-groupby | 1 |
17,134 | 67,441,453 | Return a unique dataframe name from function | <p>I would like to return several dataframes from def function using unique names based on variables. My code as follows:</p>
<pre><code>def plots_without_outliers(parameter):
"""
The function removes outliers from dataframe variables and plots boxplot and historams
"""
Q1 ... | <p>A common way to deal with this is by using a dictionary, which you can make a global variable outside of the function and then update with the returned dataframe and the corresponding name as dictionary key.</p>
<pre><code>dict_of_dfs = dict()
def plots_without_outliers(parameter):
# your function statements
... | python|pandas|function|dataframe | 1 |
17,135 | 60,154,818 | Multiply array indices with numbers | <p>is there any short numpy command for the following operation in the for loops?</p>
<pre><code>import numpy as np
a= np.array([1.0,2.0,3.0,4.0,5.0,6.0])
b= np.array([10.0,20.0,30.0])
c= np.array([100.0,200.0,300.0,900.0])
y=np.linspace(0,2,50)
m=np.array([0.2,0.1,0.3])
A,C,B,Y = np.meshgrid(a,c,b,y,indexing="ij")... | <p>To remove the loop, you just need <code>einsum</code> here.</p>
<pre><code>np.einsum('ijkl,k->ijkl', Y, m)
</code></pre>
<p>Or just broadcasted multiplication:</p>
<pre><code>Y * m[:, None]
</code></pre>
<hr>
<p>However, if you don't want to create the meshgrid in the first place, you can broadcast <code>Y</... | numpy|indexing|numpy-ndarray | 2 |
17,136 | 60,272,086 | After finetuning Faster RCNN object detection model, how to visualize bbox prediction? | <p>I finetuned pytorch torchvision model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) on my own custom dataset.</p>
<p>I followed this guide <a href="https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html#torchvision-object-detection-finetuning-tutorial" rel="nofollow noreferre... | <p>The prediction from <a href="https://pytorch.org/docs/stable/torchvision/models.html#torchvision.models.detection.fasterrcnn_resnet50_fpn" rel="nofollow noreferrer">FasterRCNN</a> is of the form:</p>
<pre><code>>>> predictions = model([input_img_tensor])
[{'boxes': tensor([[419.6865, 170.0683, 536.0842, 49... | deep-learning|computer-vision|pytorch|faster-rcnn|torchvision | 2 |
17,137 | 65,213,845 | How to avoid unnecessary multi-index entries in pandas dataframe concat? | <p>I have the following data:</p>
<pre><code>df1 = pd.DataFrame({'Room': [1, 2, 3, 5, 8], 'User': 'Martin', 'Task': 'Play', 1: [1, 2, 3, 4, 5]}).set_index(['Room', 'User', 'Task'])
df2 = pd.DataFrame({'Room': [1, 2, 3, 5, 8], 'User': 'Martin', 'Task': 'Play', 2: [1, 2, 3, 4, 5]}).set_index(['Room', 'User', 'Task'])
df3... | <p>If is possible sum values:</p>
<pre><code>df = df.sum(level=[0,1,2])
#alternative
#df = df.groupby(level=[0,1,2]).sum()
print (df)
1 2
Room User Task
1 Martin Clean 6.0 6.0
Play 1.0 1.0
2 Martin Clean 7.0 7.0
Play 2.0 2.0
3 M... | pandas|dataframe|multi-index | 1 |
17,138 | 65,182,638 | Calculate gap between two datasets (pandas, matplotlib, fill_between already used) | <p>I'd like to ask for suggestions how to calculate lenght of gap between two datasets in matplotlib made of pandas dataframe. Ideally, I would like to have these gap values written in the plot and also, if it is possible, include them into the dataframe.
Here is my simplified example of dataframe:</p>
<pre><code>impor... | <p>IIUC, do you want something like this:</p>
<pre><code>import matplotlib.pyplot as plt
ax = df.plot(x='Atom Number', y=['Mean-1','Mean-2'], figsize=(15,8))
y_1 = df['Mean-1']
y_2 = df['Mean-2']
x = df['Atom Number']
error_1 = df['SEM-1']
error_2 = df['SEM-1']
ax.fill_between(df['Atom Number'], y_1-error_1, y_1+er... | python|pandas|dataframe|matplotlib | 1 |
17,139 | 65,088,449 | saving RL agent by pickle, cannot save because of pickle.thread_RLock -- what is the source of this error? | <p>I am trying to save my reinforcement learning agent class after training for further training later on by pickling it.</p>
<p>The script used is:</p>
<pre><code>with open('agent.pickle','wb') as agent_file:
pickle.dump(agent,agent_file)
</code></pre>
<p>I am receiving an error:</p>
<pre><code>TypeError: can't p... | <p>I too faced the same error but found a workaround. After <code>model.fit()</code>, use <code>model.save("modelName")</code>. It will make a folder inside which the model will be saved.</p>
<p>To load the model, use <code>keras.models.load_model("modelName")</code></p> | tensorflow|pickle|openai-gym | 0 |
17,140 | 65,308,353 | Type error: Int object is not iterable error [For loop] | <p>There is an exercise I have found on Kaggle which defines my purpose as:</p>
<blockquote>
<p>We'd like to host these wine reviews on our website, but a rating
system ranging from 80 to 100 points is too hard to understand - we'd
like to translate them into simple star ratings. A score of 95 or
higher counts as 3 sta... | <p>When you use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply(axis='columns')</code></a>, the provided function will be applied to <em>each row</em> of the input DataFrame.</p>
<p>The <code>reviews</code> argument holds a <code>... | python|pandas|dataframe | 1 |
17,141 | 65,058,676 | create dataset from one column csv file where data are separated by spaces | <p>I have a csv file with one column, I want to split this column to many columns so I get a real dataset</p>
<pre><code>data
02/01/19 11 725001 ADWYA 4,7 4,7 4,8 4,8 4,8 4,8 4,8 4296 5 20620,8 ... | <p>Pandas support regex split, <code>\s+</code> will match 1 or more spaces and split on it:</p>
<pre><code>df['data'].str.split(r'\s+')
</code></pre> | python|pandas|dataframe | 2 |
17,142 | 64,145,357 | Pandas: How to filter column information in Dataframe and process it differently | <p>I have a data frame representing the schedule of some restaurants in a week.</p>
<ul>
<li><strong>What i want to do is to add a column <code>is_OpenSaturday</code> to my initial Dataframe <code>df</code> that represents If the restaurant is open on Saturdays (boolean value: 0 or 1)</strong></li>
</ul>
<p><strong>not... | <p>(One of) the (syntactically) simplest way is to apply a <code>lambda</code> function on elements of the <code>Saturday</code> column:</p>
<pre><code>df["is_OpenSaturday"] = df["Saturday"].apply(lambda el: 0 if el in ('0:0-0:0', '0') else 1)
</code></pre>
<p>Output:</p>
<pre><code>df["is_Open... | python|pandas|feature-engineering | 1 |
17,143 | 63,882,968 | Transform a specific string to pandas dataframe | <p>My string looks at follow:</p>
<pre><code>'{"book":"xrp_mxn","created_at":"2020-09-14T10:39:07+0000","minor":"-101850.00105195","major":"19705.14850000","fees_amount":"19.70514850","fees_currency":"xrp&... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html" rel="noreferrer"><code>pandas.read_json()</code></a> for the task:</p>
<pre><code>s = '{"book":"xrp_mxn","created_at":"2020-09-14T10:39:07+0000","minor":"-1018... | python|pandas | 5 |
17,144 | 46,917,696 | How to check if a series of strings is contained in a PANDAS DataFrame columns and assign that string as a new column in the row? | <p>I have a series of substrings that I want to check against a DataFrame column. For example:</p>
<pre><code>SubStr = pd.series(['dog','cat','cow','fish'])
</code></pre>
<p>The DataFrame has a column called "String" where:</p>
<pre><code>df['String'] = (['The dog went for a Walk.','The fish was in the lake.','The ... | <p>Use regex:</p>
<pre><code>import re
pattern= '|'.join(['dog','cat','cow','fish'])
df['StrLookUp'] = [re.findall(pattern, i) for i in df['String']]
</code></pre> | python|regex|pandas|substring | 2 |
17,145 | 63,076,260 | How to create a 1D sparse tensors from given list of indices and values? | <p>I have a list of indices and values. I want to create a sparse tensor of size 30000 from this indices and values as follows.</p>
<pre><code>indices = torch.LongTensor([1,3,4,6])
values = torch.FloatTensor([1,1,1,1])
</code></pre>
<p>So, I want to build a 30k dimensional sparse tensor in which the indices <code>[1,3,... | <p><a href="https://pytorch.org/docs/stable/torch.html#torch.sparse_coo_tensor" rel="nofollow noreferrer">In general</a> the <code>indices</code> tensor needs to have shape <code>(sparse_dim, nnz)</code> where <code>nnz</code> is the number of non-zero entries and <code>sparse_dim</code> is the number of dimensions for... | pytorch|sparse-matrix | 3 |
17,146 | 63,227,634 | Limit timestamp column between 2 durations in python? | <p>I have the following dataframe.</p>
<pre><code>df = {'location_id': [1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5],
'timestamp':['2020-05-26 06:00:00','2020-05-26 07:00:00','2020-05-26 08:00:00', '2020-05-26 09:00:00',
'2020-05-26 10:00:00','2020-05-26 11:00... | <p><code>set_index</code> on your time column and use <code>between_time</code>:</p>
<pre><code>df = pd.DataFrame(df)
df["timestamp"] = pd.to_datetime(df["timestamp"])
print (df.set_index("timestamp").between_time("07:00","11:00"))
location_id
ti... | python|pandas | 0 |
17,147 | 63,040,250 | How to make a graph plotting monthly data over many years in pandas | <ul>
<li>I have 11 years worth of hourly ozone concentration data.
<ul>
<li>There are 11 csv files containing ozone concentrations at every hour of every day.</li>
</ul>
</li>
<li>I was able to read all of the files in and convert the index from date to datetime.</li>
<li>For my graph:
<ul>
<li>I calculated the maximum... | <ul>
<li><code>df.index -= pd.DateOffset(hours=3)</code> has been removed for being potentially problematic
<ul>
<li>The first hours of each month would be in the previous month</li>
<li>The first hours of each day would be in the previous day</li>
</ul>
</li>
</ul>
<pre class="lang-py prettyprint-override"><code>impor... | pandas|matplotlib|timeserieschart|datetimeindex | 4 |
17,148 | 63,088,499 | Storing and reading multiple histograms in a csv file | <p>I'm working with histograms presented as pandas Series and representing the realizations of random variables from an observation set. I'm looking for an efficient way to store and read them back.</p>
<p>The histogram's bins are the index of the Series. For example :</p>
<pre><code>histogram1 :
(-1.3747106810983318, ... | <p>You are addressing two different topics here:</p>
<ol>
<li>What is an efficient way to store multiple series?</li>
<li>How to determine the bin for a <code>float</code> from an already formed <code>IntervalIndex</code>?</li>
</ol>
<hr />
<p>The first part is straightforward. I would use <a href="https://pandas.pydat... | python|pandas|csv|histogram | 0 |
17,149 | 63,165,342 | Pandas add space between characters if necessary | <p>How can I add a space so that row <strong>2</strong> has a space between the "PEO - word"? Regex always confuses me, is there a good way to learn? Many of the values look like row <strong>1</strong> with proper spacing.</p>
<pre><code>df
Name
1 'PEO - word word, LLC - Austria - 1 EE'
2 'PEO-a... | <p>We can try using <code>str.replace</code> as follows:</p>
<pre><code>df["Name"] = df["Name"].str.replace("(\w)\s*-\s*(\w)", "\\1 - \\2")
</code></pre>
<p>For the input:</p>
<pre><code>PEO-aword-9EE - RB
</code></pre>
<p>the output would be:</p>
<pre><code>PEO - aword - 9EE - R... | python|regex|pandas | 1 |
17,150 | 61,371,684 | GCP and TPU, experimental_connect_to_cluster give no response | <p>I am trying to use TPU on GCP with tensorflow 2.1 with Keras API.
Unfortunately, I am stuck after creating the tpu-node.
In fact, it seems that my VM "see" the tpu, but could not connect to it.</p>
<p>The code I am using : </p>
<pre><code>resolver = tf.distribute.cluster_resolver.TPUClusterResolver(TPU_name)
prin... | <p>Trying to reproduce, I used <code>ctpu up --zone=europe-west4-a --disk-size-gb=50 --machine-type=n1-standard-8 --tf-version=2.1</code> to create vm and tpu. Then ran your code, and it succeeded.</p>
<pre><code>taylanbil@taylanbil:~$ python3 run.py
Running on TPU grpc://10.240.1.2:8470
2020-04-28 19:18:32.597556: ... | tensorflow|google-cloud-platform|tpu|google-cloud-tpu | 2 |
17,151 | 61,414,995 | Pattern identification in a dataset using python | <p>I have a dataframe that looks something like this:</p>
<pre><code>empl_ID day_1 day_2 day_3 day_4 day_5 day_6 day_7 day_8 day_9 day_10
1 1 1 1 1 1 1 0 1 1 1
2 0 0 1 1 1 1 1 1 1 0
3 0 1 ... | <p>Check with idxmcx and for loop with shift </p>
<pre><code>s=df.set_index('empl_ID')
idx=s.columns.get_indexer(s.idxmax(1))
l=[(s.iloc[t, x :y].eq(s.iloc[t, x :y].shift())&s.iloc[t, x :y].eq(0)).any() for t , x ,y in zip(df.index,idx,idx+5)]
df['Label']=l
df
empl_ID day_1 day_2 day_3 day_4 ... day_7 da... | python-3.x|pandas|numpy|dataframe|pattern-matching | 1 |
17,152 | 61,301,617 | How can I apply calculations at row level in Dataframe? | <p>I am trying to predict a value in a dataframe based on two columns but adding the decimal residue from the previous row. This needs to happen only if store of current row it is the same as the previous one. </p>
<p>For example, I would want row 2 of this dataset to predict Forecast: 9 * Lag: 0.2 + residue(from row ... | <p>Try using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>pandas.DataFrame.shift</code></a> to create columns with shifted values.</p>
<pre><code>df['store_prev'] = df.store.shift(1)
df['lag_prev'] = df.lag.shift(1)
store forecast... | python|pandas|dataframe | 1 |
17,153 | 61,335,421 | Pandas countifs value from column and other column not null | <p>I am trying to perform the equivalent to an Excel COUNTIFS formula in pandas, where the first range is a dataframe column, and the search criteria is each value in that column. The second search range is a different column and the criteria is non null values in that column. </p>
<p>Written as an Excel formula, it w... | <p>Use <code>groupby.transform</code> with <code>np.count_nonzero</code> as:</p>
<pre><code>df['Count_of_ADJL'] = df.groupby('ADJL')['ADJL'].transform('count')
df['Count_of_ADJL & LNCEL not null'] = df.groupby('ADJL')['LNCEL'].transform(np.count_nonzero)
#or
df['Count_of_ADJL & LNCEL not null'] = df.groupby('A... | python|pandas | 2 |
17,154 | 61,347,613 | IndexError: Target -1 is out of bounds error in tabular learner fatai2 | <p>Getting the below error when trying to fit a tabular_learner from fastai2 library. </p>
<p>used data loaders</p>
<p><a href="https://i.stack.imgur.com/MvF39.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MvF39.png" alt="enter image description here"></a></p>
<p>learn = tabular_learner(dls, lay... | <p>Finally got figured this out, this happened because my validation set accidentally had more dependent variable classes than in my training set (or may be it was the other way around)......To fix this I had to ensure that my class size of training set and validation set are the same </p>
<p>i:e make sure you do this... | deep-learning|pytorch|fast-ai | 3 |
17,155 | 68,728,817 | How do I change the categorical rows to columns in python | <p>I need some help with respect to changing a dataframe in python.</p>
<pre><code> NODE SIGNAL-STRENGTH LOCATION
0 A 76 1
1 A 78 1
2 A 78 1
3 A 79 1
4 A 79 2
5 ... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html#pandas-pivot-table" rel="nofollow noreferrer"><code>.pivot_table</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>df = (
df.pivot_table(index="LOCATION", columns="NODE", valu... | python|pandas|dataframe|data-wrangling | 0 |
17,156 | 68,670,091 | Why some of my images are being ignored in Tensorflow when i have images not being ignored in the same folders? | <p>I have data inside 2 folders (Training with 10000 images and Validation with 1000 images) and in each of these folders I have 10 folders (the respective classes).
I put all this data into a dataframe to use later.
It turns out that some images in certain folders at the moment I use "flow_from_dataframe" in... | <p>Sorted out. It was due to the fact that the path to the images and the image name itself was too long.</p> | python|pandas|tensorflow|machine-learning|tf.keras | 0 |
17,157 | 68,605,583 | Tensorflow keras: creating layer from config 'Keyword argument not understood:', 'axis' | <p><strong>Code:</strong></p>
<pre class="lang-py prettyprint-override"><code>config = MCM_feature_extractor.get_layer(index=132).get_config()
x = tf.keras.layers.Layer()
x = x.from_config(config)
</code></pre>
<p><strong>config:</strong></p>
<pre><code>{'axis': ListWrapper([3]),
'beta_constraint': None,
'beta_initia... | <p><strong>Solution:</strong></p>
<pre class="lang-py prettyprint-override"><code>layer = MCM_feature_extractor.get_layer(index=132)
config = layer.get_config()
weights = layer.get_weights()
config['name'] = layer.name+'_2'
second_layer = type(layer).from_config(config)
second_layer.build(layer.input_shape)
second_lay... | tensorflow|tf.keras|keras-layer | 3 |
17,158 | 53,043,101 | Reading in excel files with wrapped headers onto pandas | <p>I want to import excel sheets as data frames and export as csv. I need to do this for quite a few files. However, the headers of all files are arranged in two rows. </p>
<p>Thus, when I read the files, I get the headers as <code>Fuel Temp \n(Deg C)</code>,<code>Air Charge Temp \n(Deg C)</code> and so on. </p>
<p>H... | <p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>str.replace</code></a>:</p>
<pre><code>df.columns = df.columns.str.replace('\n', '')
</code></pre> | python|excel|pandas | 3 |
17,159 | 53,148,901 | error with checking target: expected dense_49 to have 4 dimensions, but got array with shape (2250, 3) | <pre><code>model=models.Sequential()
model.add(layers.Dense(7, activation='relu', input_shape=(50,50,3)))
model.add(layers.Dense(7, activation='relu'))
model.add(layers.Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train,y_train,b... | <p>Let's look to the following dense layers Image from <a href="https://blog.datawow.io/interns-explain-basic-neural-network-ebc555708c9" rel="nofollow noreferrer">here</a>.
<a href="https://i.stack.imgur.com/tdblE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tdblE.png" alt="enter image descripti... | python|tensorflow|keras | 0 |
17,160 | 65,533,700 | tensorflow network didn't fit | <p>I have a pandas <code>dataset</code> where <code>col1</code> -> input text(text tokenize with pre-trained tokenizer),col2 -> binary classification [0,1].
translating it into tensorflow dataset</p>
<pre><code>dataset = tf.data.Dataset.from_generator(lambda: dataset, output_types=(tf.string, tf.int32))
</code></... | <p>I think the problem is in the way you create your Dataset. The <code>from_generator</code> function expect a <strong>generator</strong> as first argument and not a function.</p>
<p>Try accessing an element or ispecting it to see if it works. Try for example:</p>
<pre><code>next(iter(dataset))
</code></pre>
<p>and se... | python|tensorflow|nlp | 0 |
17,161 | 63,447,602 | how to retrieve matched value in a excel sheet with a user input using Python | <p><a href="https://i.stack.imgur.com/f9QiO.png" rel="nofollow noreferrer">example sheet </a>How to retrieve matched value in a excel sheet with a user input using Python.</p>
<p>Consider below data is in a text.csv fiile.
If user inputs as 9 the my code needs to match the corresponding value if it which is 10.1.12.15<... | <p>Create DataFrame by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> and set first column to <code>index</code>:</p>
<pre><code>df = pd.read_csv('text.csv', names=['col1','col2'], sep=',', index_col=[0])
print (df)
... | python|excel|pandas|numpy | 0 |
17,162 | 71,825,692 | How to use trained model in Tensorflow Serving? | <p>I have trained <code>Mask-RCNN</code> model, and want to try <code>Tensorflow Serving</code> to use it in web.<br />
So i just run <code>tensorflow/serving</code> docker container. And realised what i have no clue how to send image to <code>predict</code>. Here is <code>saved_model_cli.py</code> output:</p>
<pre><co... | <p>You need to create a Json file with signature_name(Signature) and instances(images in list) like below,</p>
<pre><code>data = json.dumps({"signature_name": "your_signature", "instances": test_data[0:n].tolist()})`
</code></pre>
<p>Then you can make a request like below,</p>
<pre><code>h... | tensorflow|tensorflow-serving | 0 |
17,163 | 55,537,173 | How to create a column with means obtained from groupby function in Python? | <p>I have a dataframe CGdf_2004 as below:</p>
<pre><code>Region, Sector, TSR_15_16
Europe Consumer 12%
Americas Telecom 15%
...so on 7000 rows
</code></pre>
<p>I have calculated the mean TSR_15_16 grouping by sector and region.</p>
<p><code>X = CGdf_2004.groupby(['Region', 'Sector']).mean()</code></p>
<p... | <p>You should use join.</p>
<pre><code>X=CGdf_2004.groupby(['Region', 'Sector']).mean()
CGdf_2004.join(X, on=['Region', 'Sector'], rsuffix='_mean')
</code></pre>
<p>In one line</p>
<pre><code>CGdf_2004.join(CGdf_2004.groupby(['Region', 'Sector']).mean(), on=['Region', 'Sector'], rsuffix='_mean')
</code></pre> | python|pandas|dataframe | 0 |
17,164 | 55,527,616 | Converting a pandas dataframe column from long to wide when there are multiple values per group | <p>I have the following dataframe with the following format: </p>
<pre><code>df = pd.DataFrame({'Date': np.repeat(['20190101', '20190102'], 8),
'Category': list(np.repeat(['A', 'B'], 4))*2,
'Sub-Category': list(np.repeat(['X', 'Y'], 2))*4,
'Samples': range... | <p>First we using <code>groupby</code> <code>cumcount</code> create the additional key, then it is more like <code>pivot</code> problem </p>
<pre><code>df['New']=df.groupby(['Date','Category','Sub-Category']).cumcount()
yourdf=df.pivot_table(values='Samples',index=['Date','Category','New'],columns='Sub-Category').rese... | python|pandas|dataframe|pivot|reshape | 5 |
17,165 | 55,506,120 | How To Locate First Element In An Array? | <p>I'm new to Python and I'm trying to fetch the first element in a row and print it. How do I do that?</p>
<p>For example, Array A has:</p>
<pre><code>([[ 0, 435, 500, 432, 658]])
</code></pre>
<p>I need to print 0. How will I be able to do that?</p> | <p>It is an example of a 2D array with only 1 row, hence you can use the following [0,0]</p>
<p>The first 0 will select the first row or the 1D array and the second 0 will select the first element in that array.
More about indexing numpy array can be found here: <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/ba... | python|arrays|numpy|scipy | 1 |
17,166 | 56,868,133 | Loss Policy Gradient - Reinforcement Learning | <p>I am training my network using policy gradient and defining the loss as:</p>
<pre><code>self.loss = -tf.reduce_mean(tf.log(OUTPUT_NN)* self.REWARDS))
self.opt = tf.train.AdamOptimizer(self.lr).minimize(self.loss)
</code></pre>
<p>What I do not understand is that the loss function is sometimes positive other times... | <p>Without going into much details, you need to calculate the gradient of an equation:</p>
<p><a href="https://i.stack.imgur.com/ssbcu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ssbcu.png" alt="enter image description here"></a></p>
<p>where <a href="https://i.stack.imgur.com/13v8y.png" rel="n... | tensorflow|reinforcement-learning|policy-gradient-descent | 1 |
17,167 | 66,770,790 | panda python groupby depending on other list | <p>I have x an y of my cars and would like to add a new column with the block of the car (1-3). The "y_block_number_ends" gives the y coordinates where a block ends.</p>
<pre><code>import pandas as pd
x_start = 1
y_start = 1
size_city = 5
y_block_number_ends = [2,4]
cars = pd.DataFrame({'x': np.repeat(np.a... | <h3><code>pd.cut</code></h3>
<pre><code>cars.assign(block=pd.cut(cars.y, [0, 2, 4, float('inf')], labels=[1, 2, 3]))
x y block
0 1 1 1
1 1 2 1
2 1 3 2
3 1 4 2
4 1 5 3
5 2 1 1
6 2 2 1
7 2 3 2
8 2 4 2
9 2 5 3
10 3 1 1
11 3 2 1
12 3 ... | python|pandas | 5 |
17,168 | 47,427,238 | Diagonal element for covariance matrix not 1 pandas/numpy | <p>I have the following dataframe: </p>
<pre><code> A B
0 1 5
1 2 6
2 3 7
3 4 8
</code></pre>
<p>I wish to calculate the covariance</p>
<pre><code>a = df.iloc[:,0].values
b = df.iloc[:,1].values
</code></pre>
<p>Using numpy for cov as : </p>
<pre><code>numpy.cov(a,b)
</code></pre>
<p>I get: </p>
<pre... | <p>No they shouldn't. I think you might be confusing it with Correlation.
Correlation and Covariance are different.</p>
<p>What you see in the diagonals is simply the variance of the variables!
Wiki screenshot for the formulas - </p>
<p><a href="https://i.stack.imgur.com/uGFyT.png" rel="nofollow noreferrer"><img src=... | python|pandas|numpy|dataframe|covariance | 3 |
17,169 | 68,043,971 | PyTorch Sampler: if specified, the next iteration samples the same subset or another subset? | <p>If I have the code like:</p>
<pre class="lang-py prettyprint-override"><code>dataset = Dataset(...)
sampler = RandomSampler(...)
dataloader = DataLoader(..., sampler=sampler)
</code></pre>
<p>Then whenever I call:</p>
<pre class="lang-py prettyprint-override"><code>for data, label in dataloader:
...
</code></pre>... | <p>It is different subset compared to the last call. I modify example <a href="https://discuss.pytorch.org/t/how-to-use-randomsampler/68376" rel="nofollow noreferrer">here</a> for your question:</p>
<pre><code>data = torch.rand(10,1)
dataset = torch.utils.data.TensorDataset(torch.arange(len(data)),data)
index,_ = datas... | python|pytorch | 1 |
17,170 | 68,232,782 | Extracting from a 2D df and adding value to 1D df in python | <p>I am trying to extract information from a 2d data frame where I have rows A through H and columns 1-12. Each cell has a different number. My second dataframe only has one column with the combined information, for example A1, A2, etc. I want to set a for loop so that I can do df1.iloc and select the coordinates. But ... | <p>One option is to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> <code>df1</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reindex.html" rel="nofollow noreferrer"><code>reind... | python|pandas|dataframe | 0 |
17,171 | 59,073,310 | How to obtain the dictionary of features and tensors of a tf.data.Dataset? | <p>Given the following dataset:</p>
<pre><code>import pandas as pd
import tensorflow as tf
df = pd.DataFrame({
'feat_binomial': [5, 1, 7, 4, 6],
'feat_normal': [5.001512, 5.346654, -0.480363,4.821558,-2.080958],
'feat_ordinal': ['low', 'low', 'low','low','low'],
'feat_string': ['a', 'b', 'b','b','b'],... | <p>You may try using iterator,</p>
<pre class="lang-py prettyprint-override"><code>iterator = dataset.make_one_shot_iterator()
feature_dict = iterator.get_next() # Returns Dictionary of features
</code></pre> | python|tensorflow|tensorflow-datasets | 0 |
17,172 | 59,101,166 | Check all row combination and find out the rows with maximum mean on a particular column of pandas data frame | <p>I have a data frame like this,</p>
<pre><code>df
col1 col2 ind
A 1 0
B 2 1
C 10 2
D 5 3
E 11 4
F 4 5
G 7 6
H 20 7
I 33 8
J 24 9
K 22 10
L 5 11
</code></pre>
<p... | <p>One idea is use
<a href="https://rigtorp.se/2011/01/01/rolling-statistics-numpy.html" rel="nofollow noreferrer">strides</a> solution:</p>
<pre><code>def rolling_window(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_trick... | python|pandas|dataframe | 0 |
17,173 | 59,263,247 | Breaking image pixels when a scalar is added to image | <p>I wanted to adjust an image's brightness, by adding a scalar</p>
<p>I wrote this code.</p>
<pre class="lang-py prettyprint-override"><code>img1 = np.uint8(np.clip(img + 45, 0, 255))
img2 = np.uint8(np.clip(img + 45., 0, 255))
plt.imshow(img1)
plt.show()
plt.imshow(img2)
plt.show()
</code></pre>
<p>Only differen... | <p>You overflow the allowed range.</p>
<p>Β»But I'm using <code>np.clip()</code> and cast it to <code>uint8</code>!Β« you want to say.</p>
<p>Right, but too late. Your <code>img</code> is probably already of type <code>uint8</code>, and as long as you add an integer to an integer, the type is not changed, so the first... | python|image|numpy|opencv | 1 |
17,174 | 57,022,633 | How to convert sRGB to NV12 format using NumPy? | <p><strong>NV12</strong> format defines specific color channels ordering of YUV color space with 420 subsampling.<br>
NV12 format is mostly used in video encoding/decoding pipeline. </p>
<p><a href="https://chromium.googlesource.com/libyuv/libyuv/+/HEAD/docs/formats.md#nv12-and-nv21" rel="nofollow noreferrer">libyuv ... | <h2>Converting sRGB to NV12 format using NumPy</h2>
<p>The purpose of the post is demonstrating the conversion process.<br />
The Python implementation below uses NumPy, and deliberately avoids using OpenCV.</p>
<p>RGB to NV12 conversion stages:</p>
<ul>
<li>Color space conversion - convert from sRGB to YUV color space... | python|numpy|image-processing|video-processing|nv12-nv21 | 5 |
17,175 | 45,868,971 | Where to perform tf.string_split() operation | <p>I am struggling with how to adapt the ML engine examples to use a long text string as an input feature. I am building a custom estimator (like this <a href="https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/census/customestimator/trainer/model.py" rel="nofollow noreferrer">example</a>) and am lookin... | <p>The division between what happens in the <code>input_fn</code> and what happens in the <code>model_fn</code> is entirely determined by what behavior you want at inference time. As a general rule of thumb:</p>
<ul>
<li>If you need to perform a transformation on both the training input and the prediction input, put i... | tensorflow|tensorflow-serving|google-cloud-ml-engine | 1 |
17,176 | 45,783,285 | Code changes needed for custom distributed ML Engine Experiment | <p>I completed this <a href="https://cloud.google.com/ml-engine/docs/tutorials/distributed-tensorflow-mnist-cloud-datalab" rel="nofollow noreferrer">tutorial</a> on distributed tensorflow experiments within an ML Engine experiment and I am looking to define my own custom tier instead of the <code>STANDARD_1</code> tier... | <blockquote>
<p>are any additional code changes needed to create a custom tier of any size?</p>
</blockquote>
<p>No; no changes are needed to the MNIST sample to get it to work with different number or type of worker. To use a <code>tf.estimator.Estimator</code> on CloudML engine, you must have your program invoke <... | google-cloud-platform|tensorflow|google-cloud-ml-engine | 1 |
17,177 | 50,922,606 | How to choose number of perceptron in fine-tuning FC layer? | <p>I use VGG-16 pre-trained model and fine-tune the last 3 FC layers.
But in my case, I only use 3 classes as my classification.
I want to ask <strong>how to choose the perceptron of FC layers</strong>.
<strong>Should I visualize the Conv5_3 layer</strong>, then making a decision?
BTW, VGG-16 official model is 4096, 4... | <p>The easiest way to adapt your network is to add another FC layer on top of the VGG (with weight kernel of size 1000x3).</p>
<p>Alternatively, replace the last FC layer (of size 4096x1000) with an FC layer of size 4096x3.</p>
<p>Don't forget to properly initialize your newly added layers.</p> | python|tensorflow | 0 |
17,178 | 66,725,721 | failed to boxplot one figure in each canvas using Seaborn for groupby data in pandas | <p>I have a dataset, which is as follows:</p>
<pre><code>funding_round_type variable value
venture raised_amount_usd 7.0000000000
seed raised_amount_usd 5.8450980400
venture raised_amount_usd 6.5323565818
venture raised_amount_usd 6.3010299957
seed raised_amount_usd 4.6370892735
venture raised_amoun... | <p>There are many ways to create a boxplot for each subplot.</p>
<p>The code below supposes that you want different x-ranges for each of the boxes (otherwise you could simply put them together into one plot). Looping through each of the axes, the example code limits the x-axis to the interval between 5% and 95%, so out... | python|pandas|seaborn|boxplot | 1 |
17,179 | 66,493,068 | ylabel axis value 1e6 change | <p>I have created a bar chart of active covid cases for my lab classes from pandas dataframe. Although I am not satisfied with the y axis and it's reference which is 1E6 How can i change that?</p>
<p>My DF</p>
<p><a href="https://i.stack.imgur.com/GQJuC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com... | <p>You can format the y-axis</p>
<ul>
<li>first graph is default formatter that gives same result as you note</li>
<li>second graph formats as millions</li>
</ul>
<pre><code>import matplotlib.pyplot as plt
import matplotlib
fig, ax = plt.subplots(2, figsize=[14,6], sharex=True)
df = pd.json_normalize(requests.get(&qu... | python|pandas | 0 |
17,180 | 66,449,599 | How to predict Faster RCNN model in batches? | <p>I have a trained RCNN (Keras-Retinanet) model and I could predict only one image at a time.</p>
<pre><code>boxes, scores, labels = model.predict_on_batch(np.expand_dims(image, axis=0))
</code></pre>
<p>Full script is <a href="https://github.com/fizyr/keras-retinanet/blob/master/examples/ResNet50RetinaNet.ipynb" rel=... | <p>The reason you expand the dims there is to artificially add a batch dimension. Simply stack a bunch of images together and pass it into this function to get a batch of results.</p>
<p>Said differently, right now you are passing in:
[image].</p>
<p>You could instead pass in:
[image_1, image_2, image_3, ...] (as a num... | tensorflow|keras|prediction|faster-rcnn | 0 |
17,181 | 57,718,548 | How to parse Cloud SQL CSV export nulls ("N) with Pandas read_csv | <p>Using Airflow, we're exporting data from Google Cloud SQL to a CSV, and eventually loading that CSV into a different SQL warehouse. However, Cloud SQL exports null values as the string <code>"N</code> (This is a known Google issue: <a href="https://issuetracker.google.com/issues/64579566" rel="nofollow noreferrer">h... | <p>Ultimately had to brute force it by replacing the text.</p>
<pre><code> with open(filepath, 'r', encoding="utf-8") as inputFile:
raw_text = inputFile.read()
edited_text = raw_text.replace('"N,', ',')
edited_text = edited_text.replace(',"N\n', ',\n')
with open(edited_filepath, 'w', newline='... | pandas|google-cloud-sql | 0 |
17,182 | 57,633,505 | NLP in Python3 - count up occurrences of specific terms in a large string | <p>I have numerous files, containing pages of text. While looping through each file, I would like to extract counts for terms that I'm specifically interested in.</p>
<p>For example, I have something like the below (simplified example - actual is 2-5 pages of text):</p>
<pre><code>to_process = 'soccer football socce... | <p>You could use a dict comprehension (using <code>collections.Counter</code> and <code>re.sub</code>):</p>
<pre><code>import re
from collections import Counter
to_process = '>>SocceR... !football! soccer *asdlkj assdasda? asdsasad ; FOOtball; soCCer'
words = ['soccer', 'football']
all_counts = Counter(re.su... | python-3.x|pandas|numpy|nlp | 2 |
17,183 | 73,029,852 | Accessing Universal-Sentence-encoder training vocabulary | <p>I'm basing this question off of <a href="https://stackoverflow.com/questions/55148713/any-way-to-extract-the-exhaustive-vocabulary-of-the-google-universal-sentence-en">this similar question</a>, but the <a href="https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/3" rel="nofollow noreferrer">multilin... | <p>Took a bit but I had to load the by</p>
<pre><code>import sentencepiece as spm
sp_model = spm.SentencePieceProcessor()
sp_model.LoadFromSerializedProto(model_string)
vocab = {sp_model.IdToPiece(i): i for i in range(sp_model.GetPieceSize())}
</code></pre> | python|tensorflow|pickle | 0 |
17,184 | 70,670,293 | Fill in Bellow a group df pandas | <p>I have a data frame that I made the transpose of it looking like this</p>
<p><a href="https://i.stack.imgur.com/axsUu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/axsUu.png" alt="enter image description here" /></a></p>
<p>I would like to know how I can transform this group into filled lines, f... | <p>In your case, repeat the indices of your data frame five times, save them in a new column, and then make the column entries original indices.</p>
<pre><code>ibov_transpose['index'] = ibov_transpose.index.repeat(5)
ibov_transpose.set_index('index')
del(ibov_transpose['index'])
</code></pre> | python|pandas|dataframe|fillna | 0 |
17,185 | 70,950,360 | Why is numpy inverse square root "x**(-1/2)" so much slower than "1/np.sqrt(x)" | <p>In numpy, the square root and power by 1/2 is almost indistinguishable in speed. However, when doing the inverse square root vs the power by -1/2, the latter is about 10x slower.</p>
<pre class="lang-py prettyprint-override"><code># Python 3.10.2; numpy 1.22.1; clang-1205.0.22.11; macOS 12.1
import numpy as np
arr ... | <p><code>numpy</code> makes special cases of exponents in <code>{-1, 0, 0.5, 1, 2}</code>, but no others. There was <a href="https://github.com/numpy/numpy/issues/9363" rel="noreferrer">an issue opened in 2017</a> to add to add -2 and -0.5 to this set, but it appears that nothing yet has been done in that direction.</p... | python|numpy|performance | 9 |
17,186 | 70,779,165 | How to replace values in Dataframe based on multiple conditions? | <p>I have one large dataframe that currently has both "?", "??", and NaN values that I'm trying to remove. I want to redefine the columns to be booleans to see whether they contained "?", "??" or NaN.</p>
<p>My current approach involves cloning different columns of the dataframe ... | <p>how about using quick-sort algorithm. And, I am not sure I got what your data looks like and what results you want to obtain. Maybe you could show us parts of your data frame.</p> | python|pandas|dataframe | 0 |
17,187 | 51,919,178 | Pandas Fill column value with next available value in the same column | <p>I am working on a data set where the values in PLU column are scattered all over the place like:
I have 4 columns out of more than 500:</p>
<pre><code>Inventory_No | Description | Group | PLU
----------------------------------------------
93120007 | Coke |Drinks | 1000
93120008 | Diet Coke |Drinks ... | <p><strong><em>Setup</em></strong></p>
<pre><code>print(df)
Inventory_No Description Group PLU
0 93120007 Coke Drinks 1000
1 93120008 Diet Coke Drinks 1003
2 93120009 Coke Zero Drinks 1104
3 93120010 Fanta Drinks 1105
4 93120011 ... | python|python-3.x|pandas | 3 |
17,188 | 51,955,386 | pandas dataframe merge based on str.contains | <p>I have two dataframe that I would like to merge based on if column value from df2 contains column value from df1. I've been trying to use str.contains and series.isin. But no luck so far. Example below.</p>
<p>df1</p>
<pre><code> Domain Visits
aaa 1
bbb ... | <p><strong><em>Setup</em></strong></p>
<p>We can start by creating a new series which is the row each domain in <code>df2</code> corresponds to in <code>df1</code>, if such a row exists:</p>
<pre><code>r = '({})'.format('|'.join(df1.Domain))
merge_df = df2.Domain.str.extract(r, expand=False).fillna(df2.Domain)
</code... | python|pandas|dataframe | 4 |
17,189 | 35,854,768 | Convert Pandas DataFrame to Dictionary using multiple columns for the key | <p>I have a pandas DataFrame as below</p>
<pre><code>From_email,To_email,email_count
110165.74@compuserve.com,klay@enron.com,1
2krayz@gte.net,klay@enron.com,1
"<""d@piassick"".@enron@enron.com>",klay@enron.com,1
</code></pre>
<p>I would like to change it to a dictionary of the following format </p>
<pre><code>... | <p>You can use a <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow"><code>dict</code> comprehension</a> to create the <code>dict</code> from your <code>DataFrame</code>.</p>
<pre><code>df = DataFrame({
'From_email': ['110165.74@compuserve.com', '2krayz@gte.net', '<"d@piassick".@enron@enron.com&g... | python|pandas | 4 |
17,190 | 35,834,746 | my jupyter notebook fails to import anaconda modules consistently | <p>I can't get my jupyter notebook properly import any modules. The weird thing is, I am able to import numpy but not pandas with Sublime. </p>
<p>I wiped out every python related content on my Mac and re-installed anaconda. Here's the import error message for numpy on jupyter:</p>
<pre><code>ImportError ... | <p>Deleting everything Python related is a <em>bad</em> idea. There are system files which require it. Hopefully you didn't delete the wrong files and won't have to reinstall your operating system.</p>
<p>Regarding your question, you need to first activate your conda environment before launching jupyter notebook.</p... | python|numpy|pandas|anaconda|importerror | 2 |
17,191 | 37,255,647 | Clean one column from long and big data set | <p>I am trying to clean only one column from the long and big data sets. The data has 18 columns, more than 10k+ rows about 100s of csv files, Of which I want to clean only one column. </p>
<p>Input fields only few from the long list</p>
<pre><code>userLocation, userTimezone, Coordinates,
India, Hawaii, ... | <p>There are many things wrong here.</p>
<ol>
<li>The file is not a simple csv and is not being appropriately parsed by your assumed <code>data = pd.read_csv('input.csv')</code>.</li>
<li>The 'Coordinates' filed seems to be a <code>json</code> string</li>
<li>There are NaN's in that same field</li>
</ol>
<p>This is w... | python|pandas|data-cleaning|bigdata | 1 |
17,192 | 37,341,229 | Discrete Weights and Activations in Tensorflow or Keras | <p>Do you know about a way to constrain <code>tensorflow</code> or <code>keras</code> to a set of discrete weights and use discrete/rigid activation functions (e.g. like <code>sign</code> or <code>hard-tanh</code>)?</p>
<p>The APIs seem to have only smooth activation functions.</p>
<p>What I also thought about is to ... | <p>In my opinion changing weights and activations from smooth to discrete ones might be a huge problem in Keras. I see at least two major difficulties in this approach:</p>
<ol>
<li><strong>Optimization framework must be completely different:</strong> the main reason why Keras / Theano does so good job in ANN is the f... | tensorflow|machine-learning|keras|neural-network|deep-learning | 1 |
17,193 | 41,761,226 | Python: Build DataFrame from parts of JSON response | <p>I am trying to develop an application to retrieve stock prices (in JSON) and then do some analysis on them. My problem is with getting the JSON response into a pandas DataFrame where I can work. Here is my code:</p>
<pre><code>'''
References
http://stackoverflow.com/questions/6862770/python-3-let-json-object- acce... | <p>To answer your first question, <code>pd.read_json</code> takes a JSON string directly, so you should be doing this:</p>
<pre><code>pd.read_json(response)
</code></pre>
<hr>
<p>But instead, considering how the data is structured, it's best to first convert the JSON string to a dictionary containing the data:</p>
... | json|python-3.x|pandas|dataframe | 5 |
17,194 | 42,010,398 | Most Effecient way to parse Evtx files for specific content | <p>I have hundreds of gigs of Evtx security event logs I want to parse for specific Event IDs (4624) and usernames (joe) based on the Event IDs. I have attempted to use Powershell cmdlet like below:</p>
<pre><code>get-winevent -filterhashtable @{Path="mypath.evtx"; providername="securitystuffprovider"; id=4624}
</cod... | <p>Use <code>-Path</code> with the <code>-FilterXPath</code> parameter, and then filter using an XPath expression like so:</p>
<pre><code>$Username = 'jdoe'
$XPathFilter = "*[System[(EventID=4624)] and EventData[Data[@Name='SubjectUserName'] and (Data='$Username')]]"
Get-WinEvent -Path C:\path\to\log\files\*.evtx -Fi... | python|windows|powershell|pandas | 1 |
17,195 | 37,946,847 | Trying to upsample Pandas to have data for every minute | <p>I have a database, with a mix of minutely,5minutely, and hourly data points:
My goal is to have 10min data averages, but hwen I plot this out there is missing datapoints and the written CSV file goes from writing every data point to every hour) </p>
<p>The output looks like</p>
<pre><code> 2005-03-01 17:00:00,... | <p>Your data is a little sparse to get points every 10min when you only get one reading per hour at the end... Since you get missing points, you either have to use the data you have (using <code>ffill</code> or <code>bfill</code>), or interpolate the missing data.</p>
<pre><code>df['Conc'].plot(label='original')
df['C... | python|pandas | 2 |
17,196 | 31,256,252 | Why does numpy.linalg.solve() offer more precise matrix inversions than numpy.linalg.inv()? | <p>I do not quite understand why <code>numpy.linalg.solve()</code> gives the more precise answer, whereas <code>numpy.linalg.inv()</code> breaks down somewhat, giving (what I believe are) estimates. </p>
<p>For a concrete example, I am solving the equation <code>C^{-1} * d</code> where <code>C</code> denotes a matrix... | <p><code>np.linalg.solve(A, b)</code> does <em>not</em> compute the inverse of <em>A</em>. Instead it calls one of the <a href="http://www.netlib.org/lapack/double/dgesv.f" rel="noreferrer"><code>gesv</code> LAPACK routines</a>, which first factorizes <em>A</em> using LU decomposition, then solves for <em>x</em> using ... | python|arrays|numpy|matrix|linear-algebra | 55 |
17,197 | 64,537,752 | Want to create a daily "open" feature derived from : MO 00:00-23:59 TU 00:00-23:59 etc in phyton | <p>I have masterdata openings hours available to me like : MO 00:00-23:59 TU 00:00-23:59 WE 00:00-23:59 TH 00:00-23:59 FR 00:00-23:59 SA 00:00-23:59 SU 00:00-23:59</p>
<p>I would like to use this to create a feature for each date individually.</p>
<p>In order to restock a store I need to plan this event. The created fe... | <p>This one is a little strange since your starting data is in a strange format, but no matter.</p>
<p>First step is to split out the days into rows and split out rows based on the day of the week:</p>
<pre><code>days = (
df1["restock_hours"]
.str.strip()
.str.replace("(\D{2})(\s)", r&qu... | pandas|dataframe|date|datetime | 0 |
17,198 | 47,865,343 | How to run official Tensorflow Docker Image as a non root user? | <p>I currently run the official Tensorflow Docker Container (GPU) with Nvidia-Docker:</p>
<ul>
<li><a href="https://hub.docker.com/r/tensorflow/tensorflow/" rel="nofollow noreferrer">https://hub.docker.com/r/tensorflow/tensorflow/</a></li>
<li><a href="https://gcr.io/tensorflow/tensorflow/" rel="nofollow noreferrer">h... | <p>Docker containers by default run as <code>root</code>. You can override the user by passing <code>--user <user></code> to docker run command. Note however this might be problematic in case the container process needs root access inside the container.</p>
<p>The security concern you mention is handled in docke... | docker|tensorflow|deep-learning|dockerfile | 2 |
17,199 | 47,609,080 | variable sharing in Tensorflow | <p>I am trying to implement a siamese network for the first time. I don't have any experience with variable sharing. I don't know why I become this Error "Variable conv2/W does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=tf.AUTO_REUSE in VarScope?" Any help is ... | <p>In <code>net1 = tower_network()</code>, the parameter <code>reuse</code> is set to its default value, which is <code>True</code>.
This leads in tensorflow trying to reuse a variable with the same name, which does not exist yet.</p>
<p>Replacing the line with <code>net1 = tower_network(reuse=False)</code> should so... | python|tensorflow|tensorboard|tflearn | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.