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
371,100
55,815,191
how can I suppress the "dtype" line when printing a pandas dataframe?
<p>I have a dataframe and need to print the output of some aggregations and such. </p> <p>For example, a line in my script has:</p> <pre><code>pd.f_type = inventory['fruit'].value_counts() print(f_type) </code></pre> <p>And its output like this: </p> <pre><code>apple 2 watermelon 1 pineapple 1 grapef...
<p>If the removal of the last line is just for the sake of output, you can do like this:</p> <pre><code>f_type.to_string() </code></pre> <p>However, be careful with using <code>.to_string()</code> on large dataframes, because it will convert and print the entire dataframe, not just the amount of rows specified in <co...
python-3.x|pandas|dataframe
5
371,101
55,852,727
TypeError when adding cuda device
<p>I'm running a simple demo of Pytorch 1.0, and get stuck when trying cuda settings.(vscode 1.33.1, Python 3.6)</p> <p>My pytorch code is as followed.</p> <pre><code>import torch from torch import cuda if cuda.is_available(): devic=cuda.device(0) layer=torch.rand([5,3,2],requires_grad=True) </code></pre> <p...
<p>Just exchange <code>devic=cuda.device(0)</code> to <code>devic=torch.device('cuda:0')</code>. </p> <p>The - confusing - reason that <code>torch.device</code> is what's used to allocate a tensor to a physical device, while <code>torch.cuda.device</code> is a context manager to tell torch on which gpu to compute stuf...
python-3.x|pytorch
0
371,102
55,988,298
How do I convert 1D data into a 2D array?
<p>I have downloaded some aeromagnetic data and am trying to plot it using <code>pcolor</code> or <code>pcolormesh</code>. This data came in a format where each column had a type of data. I read the file and took out the longitude, latitude and background magnetic columns. So I have 3 1D arrays with these values. To pl...
<p>You can try something like vstack (or a related method).</p> <p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html</a></p>
python|arrays|numpy
0
371,103
55,915,230
Looping to create a new column based on other column values in Python Dataframe
<p>I want to create a new column in python dataframe based on other column values in multiple rows. For example, my python dataframe df:</p> <pre><code>A | B ------------ 10 | 1 20 | 1 30 | 1 10 | 1 10 | 2 15 | 3 10 | 3 </code></pre> <p>I want to create variable C that is base...
<p>recreate the data:</p> <pre><code>import pandas as pd A = [10,20,30,10,10,15,10] B = [1,1,1,1,2,3,3] df = pd.DataFrame({'A':A, 'B':B}) df A B 0 10 1 1 20 1 2 30 1 3 10 1 4 10 2 5 15 3 6 10 3 </code></pre> <p>and then i'll create a lookup Series from the df:</p> <pre><code>l...
python-3.x|pandas|jupyter-notebook
1
371,104
55,995,914
Conditionally overwrite values in series using a for loop and if statement
<p>I ran a Logit model using <code>stats.models</code> and declared a series with predicted values:</p> <pre><code>M1 = sm.Logit(y_train, X_train) M1_results = M1.fit() y_pred = M1_results.predict(X_train) # This returns a series </code></pre> <p><code>y_pred</code> is a series with values between 0 and 1. I want to...
<p>If <code>y_pred</code> is an instance of list you can use <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow noreferrer">enumerate</a> function to iterate over list with indexes. This will give you a possibility to set value of item by it's index in list.</p> <p><strong>Code:</strong...
python|pandas|for-loop|if-statement
1
371,105
55,747,348
Pandas subplot layout not working in this case
<p>I was plotting some scatter plot of mpg dataset from the seaborn library. I was wondering if it is possible to plot the odd number of subplots in python?</p> <pre><code>import pandas as pd import seaborn as sns df = sns.load_dataset('mpg') df.groupby('origin').plot.scatter(x='cylinders',y='mpg',subplots=True,layout...
<p>Try <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.delaxes.html" rel="nofollow noreferrer"><code>delaxes</code></a>:</p> <pre><code>fig.delaxes(axes[1][1]) </code></pre>
python|pandas|matplotlib|plot|seaborn
2
371,106
55,964,427
tf.keras HDF5 Model and Keras HDF5 Model
<p>I want to convert a Keras model to Tensorflow Lite model. When I examined the documentation, it is stated that we can use tf.keras HDF5 models as input. Does it mean I can use my saved HDF5 Keras model as input to it or tf.keras HDF5 model and Keras HDF5 models are different things?</p> <p>Documentation: <a href="h...
<p>tf.keras HDF5 model and Keras HDF5 models are not different things, except for inevitable software version update synchronicity. <a href="https://www.tensorflow.org/guide/keras" rel="nofollow noreferrer">This is what the official docs say</a>:</p> <blockquote> <p>tf.keras is TensorFlow's implementation of the Ker...
keras|tensorflow-lite|tf.keras
2
371,107
55,673,347
Python Pandas Regex: Search for strings with a wildcard in a column and return matches
<p>I have a search list in a column which may contain a key: <code>'keyword1*keyword2'</code> to try to find the match in a separate dataframe column. How can I include the regex wildcard type <code>'keyword1.*keyword2'</code> <code>#using str.extract, extractall or findall?</code></p> <p>Using <code>.str.extract</cod...
<h3>Solution</h3> <p>You are close to the solution, just change <code>*</code> to <code>.*</code>. Reading the <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>. (Dot.) In the default mode, this matches any character except a...
python|regex|pandas|wildcard-expansion
1
371,108
55,869,497
How can I reshape usage data into minute-by-minute format?
<p>How can I re-shape the following raw usage data into a “minute-by-minute dataframe”. Is there a special pandas feature for such an operation that can divide the raw data into the minute slots?</p> <p><strong>Example of raw usage data:</strong></p> <pre><code>**Video-ID | UsageStart** | **Duration in sec** ...
<pre><code># convert UsageStart to datetime column df['UsageStart']= pd.to_datetime(df['UsageStart']) # reindex and sum df = df.set_index('UsageStart').resample('1T').sum() </code></pre>
python|pandas
1
371,109
55,959,848
Cannot serialize protocol buffer when using MobileNet with Tensorflow Federated
<p>I'm using the pre-trained MobileNet from Keras and want to train it using TensorFlows federated learning, but I'm always getting an error that the protocol buffer cannot be serialized since the 2GB limit is exceeded. My inputs are 224x224 RGB images.</p> <p>Edit: I have a dataset of 1000 Images (500 Images per Clie...
<p>In version <code>0.12.0</code> TensorFlow Federated started using a new eager-mode executor by default which may improve this significantly; there are reports of rounds completing for training a ResNet model.</p>
python|tensorflow|keras|tensorflow-federated|mobilenet
1
371,110
55,868,622
Efficient way to calculate matrix cell distance from arbitrary coordinate in numpy
<p>I am looking for an efficient numpy solution to the following problem:</p> <p>I have a N by N numpy matrix. Given an arbitrary i,j coordinate (can be decimal) of the matrix and an arbitrary range, I need to calculate the value of each cell of the matrix divided by its euclidian distance to the coordinate within the...
<p>We can vectorize your code to be more efficient by removing the two for loops and replace them with numpy operations and slicing. Additionally, removing the standard python <code>math.sqrt</code> and replacing it with <code>np.sqrt</code> should give a performance boost, more particularly noticeable with larger matr...
python|numpy|numpy-ndarray
0
371,111
55,692,307
How to rename a pandas DataFrame index label based on other column value
<p>I Have a df and I am trying to update the value of some labels in the multiIndex based on the value of the columns on the same row.</p> <p>At the moment, I drop the index level and use some masking as if it was a value column, but I feel there must be a much cleaner way of doing this</p> <pre class="lang-py pretty...
<p>I finally got around it with DataFrame.rename() function</p>
python|pandas
0
371,112
55,950,909
Convert Keras model output into sparse matrix without forloop
<p>I have a pretrained <code>keras</code> model that has output with dimesion of <code>[n, 4000]</code> (It makes the classification on 4000 classes).</p> <p>I need to make a prediction on the test data (300K observations).</p> <p>But when I call method <code>model.predict(X_train)</code>, I get an <code>run-out memo...
<p>Isn't there a <code>batch_size</code> parameter in the <code>predict()</code>?</p> <p>If I get it correct the <code>n</code> means number of sample right?</p> <p>Assume that you system ram is enough to hold the entire data but the VRAM is not.</p>
python|tensorflow|machine-learning|keras
0
371,113
55,617,449
ValueError (string to float), Conditional For Loop
<p>I have my data in a <code>pandas.groupby</code> object and am attempting iterate through the groups based on a conditional in column titled "Amount". However, the error message I'm getting is trying to convert a "Reference" code from a string to a float, but I'm unsure where I'm giving this directive. </p> <pre><co...
<p>I'm not entirely sure what you are trying to do. Did you know that you can check multiple columns values in one go using <code>masks</code> in pandas? Here's some sample code that maybe useful to you:</p> <pre><code>import pandas as pd import numpy as np df2 = pd.read_excel('sample.xlsx') df2['Amount'] = df2['Amou...
python|pandas|for-loop
1
371,114
55,620,696
Additional calculations after creating a pivot table on select columns
<p>I have created a pivot table using this code:</p> <pre><code>q2=q1.pivot(index='state', columns='year', values='wtrate') </code></pre> <p>where I reshape a dataset that was long (each state had 10 observations for each year) and I save the values from the variable wtrate. Now, I want to calculate a CAGR for diffe...
<p>How about this?</p> <pre><code>cagr = lambda df, start, end: (df[end]/df[start])**(1/((end-start)+1))-1 q2['CAGR_08'] = cagr(q2, 2008, 2019) q2['CAGR_14'] = cagr(q2, 2014, 2019) </code></pre>
python|pandas|pivot-table
3
371,115
55,900,754
Why am I getting different results after saving and loading model weights in pytorch?
<p>I have written a model, the architecture is follows:</p> <pre class="lang-py prettyprint-override"><code>CNNLSTM( (cnn): CNNText( ...
<p>After loading the model, you need to write <code>model.eval()</code>.</p> <pre><code>state_dict = torch.load(MODEL_PATH) model.load_state_dict(state_dict) model.eval() </code></pre> <p>Reference : <a href="https://pytorch.org/tutorials/beginner/saving_loading_models.html#save-load-state-dict-recommended" rel="nofoll...
python|python-3.x|pytorch
1
371,116
55,919,995
Minimize function with Pandas dataframe
<p>I have to find the 2 input values for which the output value is minimized:</p> <pre><code>import pandas as pd def calc_func(x1, x2): var1 = pd.DataFrame([x1]).loc[0] var2 = pd.DataFrame([x2]).loc[0] y = var1-var2 return(y) from scipy.optimize import minimize x0 = [1,2,3] res = minimize(calc_fun...
<p>The function <code>minimize</code> minimizes a function from R^n to R. The simplest thing to do, is to have <code>x,y</code> both concatenated in a single vector <code>z</code>, then optimize the function with respect to <code>z</code>. The following code works: </p> <pre><code>import pandas as pd from scipy.optimi...
python-3.x|pandas|scipy|minimize
1
371,117
55,694,403
Append column and default data into new Pandas DataFrame
<p>I want to append data from column and a default phrase at the same time into a Pandas DataFrame, <code>db</code> has many columns, not only id_sin &amp; extra...</p> <p>I tried this:</p> <pre><code>import pandas as pd db = pd.DataFrame({'id_sin':['s123','s124','s125','s126'], 'extra':['abc','def...
<p>You can create a copy of existing DataFrame and then add new column to it.</p> <pre><code>import pandas as pd db = pd.DataFrame({'id_sin':['s123','s124','s125','s126'], 'extra':['abc','def','ghi','jkl'], ... }) df = pd.DataFrame() df['id_sin'] = db[['id_sin']] df['Phrase'] = 'Default ...
python|pandas|dataframe
1
371,118
55,981,622
re-numbering list members in python
<p>How can re-numbering list members respectively from zero to n in Python ?</p> <p>for example :</p> <pre><code>In : [4, 10, 12, 40, 4, 12, 20, 21] Out : [0, 1, 2, 3, 0, 2, 4, 5] </code></pre>
<p>Here you go, the solution for your problem</p> <pre><code>x=[4, 10, 12, 40, 4, 12, 20, 21] y=[0] nextIndex=1; for i in (range(1,len(x))): for j in range(i): if(x[i]==x[j]): y.append(y[j]) break if(j==i-1): y.append(nextIndex) nextIndex+=1 print(y) ...
python|python-3.x|list|numpy
-1
371,119
55,765,443
shortcut to split "complex array" into "real" and "imaginary" arrays
<p>let's say I have a numpy array:</p> <pre><code>import numpy as np x = np.array((1 + 2j, 2 + 4j, 5 + 10j)) </code></pre> <p>and I want to create two separate arrays, one of the real component, and one with the complex number component without the j. Is there a shortcut to perform this operation in python? the on...
<pre><code>In [145]: x = np.array((1 + 2j, 2 + 4j, 5 + 10j)) In [146]: x Out[146]: array([1. +2.j, 2. +4.j, 5.+10.j]) </code></pre> <p>The <code>real</code> and <code>imag</code> attributes work for the whole ...
python|numpy
2
371,120
55,796,877
numpy sum slower than string count
<p>I was comparing the performance of counting how many letters 'C' are in a very long string, using a <code>numpy array</code> of characters and the string method <code>count</code>.<br> <strong>genome</strong> is a very long string. </p> <pre><code>g1 = genome g2 = np.array([i for i in genome]) %timeit np.sum(g2=...
<p>Let's explore some variations on the problem. I won't try to make as large a string as yours.</p> <pre><code>In [393]: astr = 'ABCDEF'*10000 </code></pre> <p>First the string count:</p> <pre><code>In [394]: astr.count('C') ...
python|string|numpy|count
2
371,121
55,928,968
Problem with New Column in Pandas Dataframe
<p>I have a dataframe and I'm trying to create a new column of values that is one column divided by the other. This should be obvious but I'm only getting 0's and 1's as my output. </p> <p>I also tried converting the output to float in case the output was somehow being rounded off but that didn't change anything.</p> ...
<p>Without having the exact dataframe it is difficult to say. But it is most likely a casting problem.</p> <p>Lets build a MCVE:</p> <pre><code>import io import pandas as pd s = io.StringIO("""Country;Self_cite;Citations Aus.;15606;90765 Brazil;14396;60702 Canada;40930;215003 China;411683;597237 France;28601;130632 ...
python|pandas|dataframe
0
371,122
64,902,097
How to drop a row in pandas dataframe if there is only word in a pandas column
<p>How do we drop an entire row on pandas dataframe if there is an item in a column that only has one word</p> <p>Example:</p> <pre><code>'the cat likes mice', 'the dog likes the cat', 'dog' </code></pre> <p>Return</p> <pre><code>'the cat likes mice', 'the dog likes the cat' </code></pre>
<p>How about using the <code>pd.Series.str.contains</code> method to look for spaces:</p> <pre><code>df = pd.DataFrame({'items': ['the cat likes mice', 'the dog likes the cat', 'dog']}) df = df[df['items'].str.contains(' ')] </code></pre>
python|pandas
1
371,123
64,892,612
Tensorflow quantum requires Manylinux2010. Is there a workaround to get Tensorflow quantum working on a Windows OS?
<p>I have been having issue with installing tensorflow quantum on a windows operating system and am currently having it run on a Linux subsystem. Are there any workarounds to get it running on Windows? Protobuf version cannot simultaneously be version 3.8 and 3.12 to satisfy the installation requirements.</p> <p><a hre...
<p>I'm the engineer who looks after TFQ. From the image you linked I see a couple of things going on:</p> <ol> <li><p>You are using annaconda. TFQ only supports the official pip builds of TF. Long story short they build TF with different compiler flags for the C++ code that break compatability with TFQ: <a href="https:...
windows|tensorflow|quantum-computing|python-manylinux|tensorflow-quantum
0
371,124
64,840,798
Plot categorical scatterplot in seaborn or matplotlib
<p>I have the following dataframe</p> <pre><code> it, A B C D 0 10, aa mn cd kk 1 100, ab cd wc ll 2 1000, wc cd mn sf 3 10000, ll ll kk mn 4 100000, wc kk mn cd 5 1000000, aa ll we sf 6 10000000, ss aa ss kk </code></pre> <p>created as</p> <pre><code>options = [&quot;ab&quot;, &quot...
<p>Let's try stack the data, convert to categorical with given order, sort and plot:</p> <pre><code>s = df.stack() s = pd.Series(pd.Categorical(s, categories=options, ordered=True), index=s.index) sns.scatterplot(data=s.sort_values().reset_index(name='value'), x='level_0', y='value', hu...
python|pandas|matplotlib|seaborn
1
371,125
64,882,837
data manipulation with na values
<p>My code are like that df2 DataFrame (toy data) :</p> <pre><code>import pandas as pd import numpy as np end = '20201117' np.random.seed(107) df = pd.DataFrame() for i in range(10): start = np.random.choice(['20000101', '20100101', '20160101', '20121010']) df_tempo = pd.DataFrame({'product': 'p'+str(i), ...
<p>Since <code>date</code> is already the index of <code>df2</code>, <code>pd.Grouper(freq=&quot;Y&quot;).last()</code> can be used to retrieve the value on the last date. Is this what you are expecting?</p> <p><strong>Note</strong>: <code>df2 = df2.groupby(pd.Grouper(freq=&quot;Y&quot;)).ffill()</code> will fill the l...
pandas|dataframe|apply
0
371,126
65,025,236
How to get the difference between rows
<p>This is my DataFrame:</p> <pre><code>utc_timestamp data 2015-10-13 11:00:00+00:00 1 2015-10-13 12:00:00+00:00 5 2015-10-13 13:00:00+00:00 6 2015-10-13 14:00:00+00:00 10 2015-10-13 15:00:00+00:00 11 </code></pre> <p>The values of <code>data</code> are cumulative.</p> <p>How can I get this resu...
<p>Try assign it back</p> <pre><code>df['data'] = df['data'].diff() </code></pre>
python|pandas
1
371,127
64,773,766
Creating subplots using matplotlib using ordered data
<p>I have a data frame that looks like</p> <pre><code>d = {'First': ['A','A','A','B','B','C'], 'Second': ['B', 'C', 'B', 'B', 'B', 'A'] df = pd.DataFrame(data = d) </code></pre> <p>I want to be able to create bar graphs for each value in First, preferably using subplots, that shows the number of values in secon...
<p>Try this:</p> <pre><code>df.groupby('First')['Second']\ .agg('value_counts')\ .unstack('First')\ .plot.bar(subplots=True, figsize=(10,8)) </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/wSA4m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wSA4m.png" alt="enter image descr...
python|pandas|matplotlib|subplot
2
371,128
64,964,460
Pandas Filter DF Column if Values are NaN or Anything else
<p>Let's say I have a dataframe that looks like this:</p> <pre><code> a b c 0 dave blue NaN 1 bill red NaN 2 sally green Member 3 Ian Org Paid </code></pre> <p>How can I filter for rows that are EITHER <code>NaN</code> or have a value of &quot;Member&quot;?</p>
<p>Yopu can chain 2 masks by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isna.html" rel="nofollow noreferrer"><code>DataFrame.isna</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame...
python-3.x|pandas
2
371,129
64,665,064
Replace duplicates on axis 0 with 0
<p>The ID represents levels of the same thing. This means that the dataset has many duplicates in each sample. I want to keep the longest ID value as this contains the most information.</p> <pre><code>df_test=pd.DataFrame({'ID':[ &quot;k__&quot;, &quot;k__|p__|c__|...
<p>I used <code>df.duplicated</code>: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer">documentation on pandas duplicated</a>:</p> <p>First Removing the duplicates and keeping the last line (works the same as in your code, just a one-liner):...
pandas|numpy
0
371,130
64,698,954
Counting different number of combinations that exists in a column
<p>I have DNA sequences of different bacterias with different lengths that are in string format. Example:</p> <pre><code>DNA xx345- b324- c82- d13- c14 xx345- a22- c14- d13 a34- f12 - r27- fg98 - tr12 z23 xx345 </code></pre> <p>I would like to count co-occurrences of each DNA piece in my data set. I need two outputs. F...
<p>I believe you need split values by <code>\s*-\s*</code> - here <code>\s*</code> means zero or more spaces, then flatten in list comprehension all combinations:</p> <pre><code>from itertools import combinations L = ['-'.join(y) for x in df['DNA'].str.split('\s*-\s*') for y in combinations(x, 2)] </code></pre> <p>If...
pandas|combinations
1
371,131
64,770,682
Odd pandas date slicing behavior (doesn't slice day)
<p>I could be missing something here but I believe that there is something odd going on with pandas datetime slicing. Here is a reproducible example:</p> <pre><code>import pandas as pd import pandas_datareader as pdr testdf = pdr.DataReader('SPY', 'yahoo') testdf.index = pd.to_datetime(testdf.index) testdf['2020-11']...
<p><code>testdf['2020-11-09']</code> slice <strong>column-wise</strong>, i.e. looking in columns for <code>'2020-11-09'</code>. Do you mean:</p> <pre><code>testdf.loc['2020-11-09'] </code></pre>
python-3.x|pandas|datetime
2
371,132
64,766,707
TypeError: only size-1 arrays can be converted to Python scalars Popping despite np.vectorize
<p>While I was plotting logarithms on a graph using Matplotlib <code>TypeError: only size-1 arrays can be converted to Python scalars</code> popped up. I searched Stack for this and there was an answer which suggested using <code>numpy.vectorize()</code> but when I tried it, it didn't work and outputted the exact same ...
<p>Nothing to do with <code>vectorize</code>. The problem is that you can't do log2 of negative numbers. If you change the starting range as follows, it works:</p> <pre class="lang-py prettyprint-override"><code>x = np.linspace(3, 100, num = 10) plt.plot(x, x, label = &quot;x&quot;) plt.plot(x, np.log2(64*x - 160), lab...
python|numpy|matplotlib
0
371,133
65,017,826
Clustering data by averaging where the gradient is small
<p>My data that is fairly continuous but has different regions. I'm trying to detect the center of each such cluster (approximately).</p> <p>Basically, the data is a list of 2D vectors, in a (N,2) numpy array. The data has a characteristic structure that looks like this:</p> <p><a href="https://i.stack.imgur.com/7cyl4....
<p>I found a way that uses a for loop, but it iterates over the clusters rather than over the values so you still have the benefits of vectorized operations.</p> <p>I set up my test case in accordance to your problem description like so:</p> <pre><code>data = np.ndarray((30,2)) data[:10] = np.random.random((10,2)) * 4 ...
python|numpy
1
371,134
65,019,151
Groupby matching pattern of different groups
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame({'ID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 'Info': ['info1', 'info2', 'info3', 'info4', 'info5', 'info6', 'info7', 'info8', 'info9', 'info10', 'info11', 'info12'], 'Category': ['1...
<p>You can try this with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.get_group.html#pandas.core.groupby.GroupBy.get_group" rel="nofollow noreferrer"><code>GroupBy.get_group</code></a> here.</p> <pre><code>g = df['Category'].str.extract(&quot;/*(\w+)$&quot;).squeeze() ...
python|pandas|dataframe|regular-language
3
371,135
64,697,812
Replacing a string with list of them in a dataframe in pandas seperated by a capital letter
<p><strong>DATA</strong></p> <pre><code> Metropolitan area Population (2016 est.)[8] NHL 0 New York 20153634 RangersIslandersDevils 1 Los Angeles 13310447 KingsDucks 2 San Jose 6657982 Sharks ...
<p>You can <code>split</code> using a regex with positive lookahead:</p> <pre><code>df['NHL'].str.split('[a-z](?=[A-Z])') </code></pre> <p>Output:</p> <pre><code>0 [Ranger, Islander, Devils] 1 [King, Ducks] 2 [Sharks] 3 [Blackhawks] </code></pre> <p>The pattern <...
python|pandas
2
371,136
64,939,849
Element-wise matrix-vector product with NumPy
<p>I have an MxN RGB image, represented as a <code>(M, N, 3)</code> array <code>A</code>. And I have another <code>(3, 3)</code> matrix <code>B</code>. I want to left-multiply each pixel (a 3-vector) in <code>A</code> by <code>B</code> to obtain a <code>(M, N, 3)</code> output matrix <code>C</code>, so that <code>C[i][...
<p>You can simply do this</p> <pre><code>C = (B @ A[...,None]).reshape(A.shape) </code></pre>
numpy
1
371,137
64,959,759
What's the difference between changing datetime string to datetime by pd.to_datetime & datetime.strptime()
<p>I have a df that looks similar to this (shortened version, with less rows):</p> <pre><code> Time (EDT) Open High Low Close 0 02.01.2006 19:00:00 0.85224 0.85498 0.85224 0.85498 1 02.01.2006 20:00:00 0.85498 0.85577 0.85423 0.85481 2 02.01.2006 21:00:00 0.85481 0.85646 0.85434 0.85646 3 ...
<p>It's surprising that a vectorized method (<code>pd.to_datetime</code>), written in Cython is slower than a pure Python method (<code>datetime.strptime</code>).</p> <p>You can specify the format to <code>pd.to_datetime</code> whicch speeds it up a lot:</p> <pre><code>pd.to_datetime(df['Time (EDT)'], format='%d.%m.%Y ...
pandas|datetime|datetimeindex|string-to-datetime
1
371,138
64,703,065
How to check if a column contains list
<pre><code>import pandas as pd df = pd.DataFrame({&quot;col1&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, [&quot;a&quot;, &quot;b&quot;]]}) </code></pre> <p>I have a dataframe like this, and I want to find the rows that contains list in that column. I tried value_counts() but it tooks so long and throws error ...
<p>Iterate on rows and check type of <code>obj</code> in column by this condition: <code>type(obj) == list</code></p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;col1&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, [&quot;a&quot;, &quot;b&quot;]]}) for ind in df.index: print (type(df['col1'][ind])...
python|pandas
3
371,139
64,733,485
How can I shift the probability of a random number generator as it moves through a list?
<p>I'm working on a side project which involves randomly generating neural networks using PyTorch. Issue is it's inefficient to randomly generate the sizes of the hidden layers if the input and output layers vary too much. So I have to kind of &quot;scale&quot; the sizes of the hidden layers as they reach the output la...
<p>You want to use a <a href="https://en.wikipedia.org/wiki/Triangular_distribution" rel="nofollow noreferrer">triangular distribution</a> where the mode is the highest bound, that will be a linear distribution where N has the highest probability and 0 has lowest:</p> <pre class="lang-py prettyprint-override"><code>imp...
python|python-3.x|numpy|random
4
371,140
65,029,817
Looping through Jupyter directory and adding file names to a list
<p>I have a simple file set up (about 15 .xlsx files in a larger file named FILE that is sitting on the home directory in Jupyter). I would like to loop through all the files that start with a certain combination of letters and then add those file names to a list. This is what I have so far. I would like to know: 1. Wh...
<p>Use the glob module <a href="https://docs.python.org/3/library/glob.html" rel="nofollow noreferrer">https://docs.python.org/3/library/glob.html</a></p> <p>From the docs:</p> <blockquote> <p>The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although re...
python|pandas|for-loop|directory|jupyter
1
371,141
65,040,144
TensorFlow 2.3.0 cannot define a complex64 type complex number
<p>I run the following code in Google Colab (TensorFlow version: 2.3.0, Python version: 3.6.9) and got an error:</p> <pre><code>import tensorflow as tf s = tf.constant(3*tf.math.exp(1j*4),dtype = tf.complex64) print(s) </code></pre> <p>error:</p> <pre><code>TypeError Traceback (most rece...
<p>I gave it more try and found the reason: If we run the following code, there is no problem:</p> <pre><code>import tensorflow as tf import numpy as np a = 3*np.exp(1j*4) print('data type of a:',a.dtype) s = tf.constant(a,dtype = tf.complex64) print(s) </code></pre> <p>results:</p> <pre><code>data type of a: complex1...
python|tensorflow
0
371,142
65,040,249
How can I get treeinterpreter's Tree Contributions, if we are using a Pipeline?
<p>I am using <code>sklearns' pipeline</code> function, to <code>one hot encode</code>, and to <code>model</code>. Almost exactly as in <a href="https://stackoverflow.com/questions/64910582/can-we-make-the-ml-model-pickle-file-more-robust-by-accepting-or-ignoring-n">this</a> post.</p> <p>After using a <code>Pipeline</c...
<p>you can get the final estimator by indexing the pipeline object <code>model[-1]</code>. similarly, we to get a new pipeline (to capture all the transformation steps) excluding the classifier by <code>model[:-1]</code>.</p> <p>Hence, this is what you need to do!</p> <pre class="lang-py prettyprint-override"><code>pre...
python|numpy|scikit-learn|random-forest
3
371,143
64,808,532
tensorflow_hub not working on google app engine
<p>The following python code is throwing an error on Google App Engine:</p> <pre><code>import tensorflow_hub as hub embed = hub.Module(&quot;https://tfhub.dev/google/universal-sentence-encoder/4&quot;) </code></pre> <p>Error:</p> <pre><code>RuntimeError: Missing implementation that supports: loader(*('/tmp/tfhub_module...
<p>Seems like similar issue to the one posted <a href="https://stackoverflow.com/questions/54029556/how-to-fix-runtimeerror-missing-implementation-that-supports-loader-when-cal#answer-54074674:%7E:text=I%20walked%20through%20the%20same%20error%20and%20this%20is%20how%20I%20solved%20it%3B">here</a>. Would you be able to...
python-3.x|google-app-engine|tensorflow-hub
0
371,144
64,710,596
Custom LearningRateScheduler in Keras
<p>I am implementing a decaying learning rate based on accuracy from the previous epoch.</p> <p>Capturing Metrics:</p> <pre><code>class CustomMetrics(tf.keras.callbacks.Callback): def on_train_begin(self, logs={}): self.metrics={'loss': [],'accuracy': [],'val_loss': [],'val_accuracy': []} self.lr=[] def ...
<p>The signature of the scheduler function is <code>def scheduler(epoch, lr):</code> which means you should take the lr from that parameter. You shouldn't write the <code>initial_learningrate = 0.1</code>, if you do that your lr will not decay, you will always return the same when the accuracy decrease. For the out of...
python|tensorflow|keras|deep-learning
1
371,145
64,840,056
How To Create a Loop With Pandas and PyAutoGui.Write
<p>I am using pyautogui to create a simple bot. However, in that bot, there is a point where I need to input information from a csv file individually and click &quot;go&quot;. I have figured out how to do this indivudally with each row/column.</p> <p>This is basically what I am using:</p> <pre><code>def function1(): ...
<p>I think you can do it by just adding a for loop in the beginning:</p> <pre><code>def function1(): for i in range(1, len(df)): # This will get executed for every row df = pd.read_csv('dbc.csv', header=None) doThisFirst() pyautogui.write(df.iloc[i, 0]) thenDoThis() pyautogui...
python|pandas
0
371,146
64,907,915
Delete rows with a certain value in Python and Pandas
<p>I want to delete rows who have certain values. The values that I want to delete have a <strong>&quot;+&quot;</strong> and are as follows:</p> <p><strong>cooperative+parallel</strong><br /> <strong>passive+prosocial</strong></p> <p>My dataset consists of 900000 rows, and about 2000 values contain the problem I mentio...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> with invert mask by <code>~</code> and escape <code>+</code>, because special regex character with <a href="http://pandas.pydata.org/pandas-docs/stabl...
python|pandas
3
371,147
65,031,956
BERT NER: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first
<p>I want to train my BERT NER model on colab. But following error occurs</p> <p>Code:</p> <pre><code>tr_logits = tr_logits.detach().cpu().numpy() tr_label_ids = torch.masked_select(b_labels, (preds_mask == 1)) tr_batch_preds = np.argmax(tr_logits[preds_mask.squeeze()], axis=1) tr_batch_labels = tr_label_ids.to(device)...
<p>In the first line of your code, <code>tr_logits = tr_logits.detach().cpu().numpy()</code> already turns <code>tr_logits</code> into a numpy array. In the line that raises the error:</p> <pre><code>tr_batch_preds = torch.max(tr_logits[preds_mask.squeeze()], axis=1) </code></pre> <p>the first thing for the program to ...
nlp|pytorch|bert-language-model|named-entity-recognition
0
371,148
64,706,722
Pandas UDF with PySpark 2.4
<p>I'm trying to execute <code>pandas_udf</code> based on the below spark documentation using PySpark 2.4, pyarrow version 0.15.0 and pandas version 0.24.2, having issues while calling <code>pandas_udf</code> function.</p> <p><a href="https://spark.apache.org/docs/2.4.0/sql-pyspark-pandas-with-arrow.html" rel="nofollow...
<p>You can set <code>ARROW_PRE_0_15_IPC_FORMAT=1</code> in <code>$SPARK_HOME/conf/spark-env.sh</code>. This issue has been documented in <a href="https://spark.apache.org/docs/3.0.0-preview/sql-pyspark-pandas-with-arrow.html#compatibiliy-setting-for-pyarrow--0150-and-spark-23x-24x" rel="nofollow noreferrer">https://spa...
pandas|apache-spark|pyspark|apache-spark-sql
1
371,149
64,925,988
Merge countries using Cartopy
<p>I am using the following code to make a map for Sweden, Norway and Finland together as one area. however, I am struggling with it. I'm following this example, Python Mapping in Matplotlib Cartopy Color One Country.</p> <pre><code>from shapely.geometry import Polygon from cartopy.io import shapereader import cartopy....
<p>The code <a href="https://stackoverflow.com/questions/62448828/python-cartopy-map-clip-area-outside-country-polygon/62502422#62502422">here</a> that you adapted to your work is good for a single country. If multiple contiguous countries are new target, one need to select all of them and dissolve into a single geomet...
matplotlib|geopandas|cartopy
2
371,150
64,878,854
Pandas: Custom fillna() function?
<p>Lets say I have data like this:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'values': [5, np.nan, 2, 2, 2, 5, np.nan, 4, 5]}) &gt;&gt;&gt; print(df) values 0 5.0 1 NaN 2 2.0 3 2.0 4 2.0 5 5.0 6 NaN 7 4.0 8 5.0 </code></pre> <p>I know that I can use <code>fillna()</code>, wit...
<p>You can use <code>ffill</code> and <code>bfill</code> together as follows :</p> <pre><code>df['values'] = df['values'].ffill().add(df['values'].bfill()).div(2) print(df) values 0 5.0 1 3.0 2 2.0 3 2.0 4 2.0 5 5.0 6 4.0 7 4.0 8 5.0 </code></pre> <p>Just change the <code>df['va...
python|pandas|data-processing|data-wrangling
2
371,151
64,843,347
Calculating rolling beta in Pandas
<p>I am trying to calculating a rolling beta between two Series in Pandas.</p> <p>My understanding is that to get the beta, I need to get the covariance matrix and then divide the cells (0, 1) by (1, 1)</p> <p>So I created a function:</p> <pre><code>def calc_beta (A, B) : covariance = np.cov (A, B) beta =...
<p>It might not be the best answer (read, the most compact) but Ithink this could do the trick. You were actually on the right track to begin with. So, assume you have the two series you gave and make them into a df</p> <pre><code>A = pd.Series(np.random.randint(1,101,50)) B = pd.Series(np.random.randint(1,101,50)) df ...
python|pandas|statistics
0
371,152
64,962,066
Validate the merge keys error when using trying to merge two csv columns?
<p>I am incredibly new to coding. I am trying to merge two .csv files on the column 'FIPS' which holds a four or five digit number (Example 1001 or 54780) and keep getting a lengthy error I can't make sense of?</p> <p>Here is the code</p> <pre><code>import pandas as pd a = pd.read_csv(r&quot;C:\Users\RSHAR\Documents\...
<p>One or both of your dataframes do not have a column FIPS. Before you merge:</p> <pre><code>print(a.columns) print(b.columns) </code></pre> <p>will show 'col' as your column name in both dataframes because of:</p> <pre><code>names=['col'] </code></pre>
python|pandas|dataframe
2
371,153
64,988,345
Python and Snowflake error on appending into existing table on the cloud
<p>I am trying to upload a dataframe into an existing table in snowflake cloud. Here is the dataframe:</p> <pre><code>columns_df.head() </code></pre> <p><a href="https://i.stack.imgur.com/c1q10.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c1q10.png" alt="enter image description here" /></a></p> <p...
<p>From the <a href="https://docs.snowflake.com/en/user-guide/python-connector-pandas.html#writing-data-from-a-pandas-dataframe-to-a-snowflake-database" rel="nofollow noreferrer">snowflake documentation</a>.</p> <blockquote> <p>To write data from a Pandas DataFrame to a Snowflake database, do one of the following:</p> ...
python|snowflake-cloud-data-platform|pandas-to-sql
2
371,154
64,779,768
How to divide one data frame to another completely
<p>Consider two dataframes like:</p> <p><code>df1</code>:</p> <pre><code> A B C D x 1 2 3 4 y 5 6 7 8 </code></pre> <p><code>df2</code>:</p> <pre><code> A B C D x 2 4 2 5 y 3 2 4 8 </code></pre> <p>How do I divide <code>df1</code> with <code>df2</code> and get a result like t...
<p>Then just try</p> <pre><code>out = df1.div(df2) </code></pre> <p>For more information about how to divide two dataframes, please refer to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.div.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api...
python|pandas
1
371,155
64,957,737
reshape imagen dividing the size
<p>I have an image with the following dimensions: (339,339,3) and i need to convert to (113,113,3).</p> <p>I tried the following:</p> <pre><code>new_image = process_img.reshape(process_img.shape[0]/3*process_img.shape[1]/3*process_img.shape[2]/3) </code></pre> <p>the error is the following: could not broadcast input ar...
<p>you cannot use <code>reshape</code> when the total sum of elements is different.</p> <p>a good usage of <code>reshape</code> might be:</p> <pre><code>a = np.array([1,2,3,4]) a.reshape((2,2)) </code></pre> <p>in total there are still 4 elements.</p> <p>in order to remove elements, there must be some logic as to how e...
python|numpy|reshape
0
371,156
64,774,857
Bind one row cell with multiple rows cell for excle sheet in panda jupyter notebook
<p>I have an excel sheet like this.</p> <p><a href="https://i.stack.imgur.com/KNgEf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KNgEf.png" alt="excelsheet" /></a></p> <p>If I search using the below method I got only 1 row.</p> <pre><code>df4 = df.loc[(df['NAME '] == 'HIR')] df4 </code></pre> <p><...
<p>First you need to remove those blank rows in your excel. then fill values by the previous value</p> <pre><code>import pandas as pd df = pd.read_excel('so.xlsx') df = df[~df['HOBBY'].isna()] df[['SNO','NAME']] = df[['SNO','NAME']].ffill() df SNO NAME HOBBY COURSE BIRTHDATE PLACE 0 1.0 HIR DANCING BTEC...
python|excel|pandas
1
371,157
65,055,836
CASE statement in Python based on Regex
<p>So I have a data frame like this:</p> <pre><code>FileName 01011RT0TU7 11041NT4TU8 51391RST0U2 01011645RT0TU9 11311455TX0TU8 51041545ST3TU9 </code></pre> <p>What I want is another column in the DataFrame like this:</p> <pre><code>FileName |RdwyId 01011RT0TU7 |01011000 11041NT4TU8 |11041000 ...
<pre><code>def filt(list1): for i in list1: if i[:8].isdigit(): print(i[:8]) else: print(i[:5]+&quot;000&quot;) # output 01011000 11041000 51391000 01011645 11311455 51041545 </code></pre> <p>I mean, if your case is very specific, you can tweak it and apply it to your datafr...
python|regex|pandas|numpy|dataframe
1
371,158
65,037,237
ValueError: could not broadcast input array from shape (7,1) into shape (7)
<p>I have a output called <code>summation</code> of the following form :</p> <pre><code>[[0.02719706] [0.02851958] [0.03727741] [0.03857162] [0.02222067] [0.06348368] [0.0179843 ]] </code></pre> <p>The output <code>summation</code> changes with loop <code>j</code>. At each loop <code>j</code>, I am looking to sto...
<p>Check whether <em>summation</em> is a <strong>1-D</strong> array.</p> <p>In this case the following code:</p> <pre><code>country = 4 MatrixDimension = np.zeros((7, country)) summation = np.array([1, 3, 5, 7, 9, 11, 13]) j = 0 MatrixDimension[:, j] = summation print(MatrixDimension) </code></pre> <p>runs without any ...
arrays|python-3.x|numpy|for-loop
1
371,159
65,032,859
Plotting as a group using Panda and Matplotlib
<p>I want to plot as a group using Panda and Matplotlib. THe plot would look like this kind of grouping:</p> <p><a href="https://i.stack.imgur.com/ydHYd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ydHYd.png" alt="enter image description here" /></a></p> <p>Now let's assume I have a data file exa...
<p>Try this. You can play around but this gives you the stacked bars in groups.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np first = [-42, -42, -42, -42] #Use your column df['first'] second = [11, 21, 31, 122] #Use your column df['second'] third = [3, 2, 2, 3] x = np.arange(len...
python|pandas|dataframe|matplotlib
1
371,160
64,758,342
Is there an elegant solution to concatenating Dataframes as fixed element in a list?
<p>Arguably I can improve on function design choices in the first place, but currently I am in a situation where a function returns a tuple, or list, of dataframes pertaining to different data streams. The idea is that each data stream separately needs to be concatenated at the end. For now limited to three, but scalab...
<p>If I had understood it well, you want to concatenate data coming from different streams, that are initially stored in a structure such as:</p> <pre class="lang-py prettyprint-override"><code>[ (df_stm0_0, df_stm1_0, ...), (df_stm0_1, df_stm1_1, ...), ...] </code></pre> <p>If that's the case. I believe you're applyin...
python-3.x|pandas
1
371,161
64,700,236
Optimizing Applying User Defined Function that Reference Multiple DF's
<h1>Have</h1> <pre><code>import pandas as pd afltv = pd.DataFrame({'FICO': [0, 0, 700, 700], 'LTV': [0, 70, 0, 70], 'Adj': [10, 11, 12, 13]}) gfltv = pd.DataFrame({'FICO': [0, 0, 700, 700], 'LTV': [0, 70, 0, 70], 'Adj': [1, 2, 3, 4]...
<h1>Keys</h1> <ol> <li>The key among the keys is <a href="https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html" rel="nofollow noreferrer">np.searchsorted()</a>, which addresses the logic of &quot;maximum le (less than or equal to)&quot; perfectly. The function is also vectorized according to the doc...
python|pandas|optimization|apply
0
371,162
65,026,864
Numpy value assignment by indexing or slicing, duplicate memory allocation?
<pre><code>import numpy as np a = np.array([0.,0.,0.,0.]) b = a c = a d = a.copy() a[0] = 2. print(a) print(b) print(c) print(d) </code></pre> <p>The result is <code>[2. 0. 0. 0.]</code> for ALL a,b and c, which is very weird. d still correctly retains the values as zeros though.</p> <p>Is it an intended behavior?</p>
<p>Yes it is an intended behaviour as all of <code>a</code>, <code>b</code> and <code>c</code> are essentially the same python object in memory and can be easily verified by simply checking <code>a is b</code> etc.</p> <p>Only <code>d</code> is assigned a separate copy of <code>a</code> in memory.</p> <pre><code>&gt;&g...
python-3.x|numpy|numpy-slicing
0
371,163
64,824,426
Why does training one model in my script train all others?
<p>I am running a script where I am training several different models one at a time. They all have the same architecture but are trained on different datasets. The models are stored in a list. I call the models iteratively and train each one like so:</p> <pre><code>for i in range(len(model_list)): model=model_list[...
<p>Looks like functional API doesn't create layer every time you call tf.keras.models.Model(). I think you have to create your models in the loop, not just calling tf.keras.models.Model() on the same input and output</p>
python|tensorflow|keras
0
371,164
39,877,184
Insert missing weekdays in pandas dataframe and fill them with NaN
<p>I am trying to insert missing weekdays in a time series dataframe such has </p> <pre><code>import pandas as pd from pandas.tseries.offsets import * df = pd.DataFrame([['2016-09-30', 10, 2020], ['2016-10-03', 20, 2424], ['2016-10-05', 5, 232]], columns=['date', 'price', 'vol']).set_index('date') df['date'] = pd.to_d...
<p>Alternatively, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow">pandas.DataFrame.resample()</a>, specifying 'B' for <em>Business Day</em> with no need to specify beginning or end date sequence as along as the dataframe maintains a datetime inde...
python|python-2.7|pandas|datetimeindex
3
371,165
40,037,053
Cannot load customized op shared lib in tensorflow
<p>I tried to add a customized op to tensorflow, but I cannot load it from python. The question is similar to the closed <a href="https://github.com/tensorflow/tensorflow/issues/2455" rel="nofollow">issue</a> in github, but the solution there did not solve my problem.</p> <p>Operating System: macOS 10.12</p> <p>Insta...
<p>Well, I found a solution. Instead of building user op by bazel, use g++.</p> <pre><code>g++ -v -std=c++11 -shared zero_out.cc -o zero_out.so -fPIC -I $TF_INC -O2 -undefined dynamic_lookup -D_GLIBCXX_USE_CXX11_ABI=0 </code></pre> <p>It will work. The reason seems like that my gcc version is too high (v6.2.0).</p> ...
python|tensorflow
0
371,166
39,907,981
Restructuring Pandas DataFrame
<p>I have been suggested to move from the class structure, defining my own class, to the pandas DataFrame realm as I envision to have many operations with my data.</p> <p>At this point I have a dataframe that looks like this:</p> <pre><code> ID Name Recording Direction Duration Distance Path Raw ...
<p>I think I have a partial answer! I got a little confused about what you wanted with regard to the FFT (fast fourier transform?) and where the data were coming from. </p> <p>HOWEVER, I got everything else. </p> <p>First, I'm gonna make some sample data. </p> <pre><code>import pandas as pd df = pd.DataFrame({"ID":...
python|pandas|dataframe
1
371,167
39,903,986
How can I convert a categorical index to a float?
<p>I have a categorical index of wind directions in a pandas dataframe.</p> <pre><code>print (self.Groups.index) CategoricalIndex([22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5], categories=[22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5], ordered=True, name='Dir', dtype='category') </code></pre> <p>I a...
<p>Use <code>astype</code> to perform the conversion:</p> <pre><code>self.Groups.index = self.Groups.index.astype('float') </code></pre>
python|pandas
5
371,168
40,155,051
Pandas Plot with Index causes 'KeyError [] not in index'
<p>I am very new to the Pandas concept in Python. Usually plots are not a problem. However, I am now confronted with a dataframe that contains an index. Somehow nothing is working anymore. </p> <p>What I want to achieve: Create a subplot for every column [Plant1,Plant2,Plant3] against one specific colum [Trafo1]. </p>...
<p>According to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="noreferrer">docs</a> you are supposed to give the column names, not the columns themselves when plotting this way. So replacing:</p> <pre><code>test.plot(x=test[column], y=test['Trafo1'], title=column) <...
python|pandas|plot
14
371,169
40,009,591
Pandas Dataframe VWAP calculation for custom duration
<p>I have a slightly unique problem to solve using Pandas Dataframe. I have following two dataframes:</p> <pre><code>df1 time, Date, Stock, StartTime, EndTime 2016-10-11 12:00:00 2016-10-11 ABC 12:00:00.243 13:06:34.232 2016-10-11 12:01:00 2016-10-11 ABC 12:02:00.24...
<p>A merge, groupby, and apply weighted average function.</p> <p>Migrated your data to code so easy for people to load.</p> <pre><code>df1 = pd.DataFrame({'Date': {0: '2016-10-11', 1: '2016-10-11', 2: '2016-10-11'}, 'Stock': {0: 'ABC', 1: 'ABC', 2: 'XYZ'}, 'EndTime': {0: '13:06:34.232', 1: '13:04:34.232', 2: '11:24:2...
python|pandas
0
371,170
40,220,857
Most efficient way to save best performing TensorFlow model on validation set while training with thread for data loading
<p>OK, it's so easy in Torch ML ;) and I am following indico example for threading to load the data- <a href="https://indico.io/blog/tensorflow-data-input-part2-extensions/" rel="nofollow">https://indico.io/blog/tensorflow-data-input-part2-extensions/</a></p> <p>So, for I found three ways, which I don't like and I am ...
<p>The variable-sharing approach is probably the easiest way to do what you want.</p> <p>Take a look at the <a href="https://www.tensorflow.org/versions/r0.11/how_tos/variable_scope/index.html" rel="nofollow">"Sharing Variables" tutorial</a>; by using tf.variable_scope() and tf.get_variable() you can reuse variables w...
python|multithreading|tensorflow
1
371,171
40,164,506
Python pandas: store Series subclass as a DataFrame column
<p>I want to create a <code>DataFrame</code> that contains a number of <em>different</em> <code>Series</code> subclasses I've defined. It seems that the subclass is stripped from the <code>Series</code> when assigned to a <code>DataFrame</code>, however.</p> <p>Here's a toy example to illustrate the problem:</p> <pre...
<p>I think you're out of luck unless you also define your own <code>pd.DataFrame</code> subclass. And that would be an even more daunting task.</p> <p>consider this example</p> <pre><code>df = pd.DataFrame() s = pd.Series([1, 2, 3]) s.random_attribute = 'hello!' print(s.random_attribute) df['A'] = s print(df.A.rand...
python|pandas
0
371,172
39,943,547
python, dictionary in a data frame, sorting
<p>I have a python data frame called wiki, with the wikipedia information for some people. Each row is a different person, and the columns are : 'name', 'text' and 'word_count'. The information in 'text' has been put in dictionary form (keys,values), to create the information in the column 'word_count'.</p> <p>If I w...
<p>If the name column is unique, then you can change the column to the index of the <code>DataFrame</code> object:<code>wiki.set_index("name", inplace=True)</code>. Then you can get the value by: <code>wiki.at['Barack Obama', 'word_count']</code>.</p> <p>With your code:</p> <pre><code>row = wiki[wiki['name'] == 'Bara...
python|sorting|pandas|dictionary|dataframe
1
371,173
39,902,562
GridSearch with SVM producing IndexError
<p>I'm building a classifier using an SVM and want to perform a Grid Search to help automate finding the optimal model. Here's the code:</p> <pre><code>from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.multiclass import OneVsR...
<p>It seems that there is no error in your implementation.</p> <p>However, as it's mentioned in the <code>sklearn</code>documentation, the "fit time complexity is more than quadratic with the number of samples which makes it hard to scale to dataset with more than a couple of <code>10000</code> samples". <a href="http...
python|pandas|machine-learning|scikit-learn|svm
4
371,174
40,130,126
Labels show up interactively on click in python matplotlib
<p>I am plotting the following numpy array (plotDataFirst), which has 40 x 160 dimensions (and contains double values).</p> <p>I would like to be able to hover over a plot (one of the 40 that are drawn) and see the label of that particular plot. </p> <p>I have an array (1x40) that contains all of the labels. Is there...
<p>I'm not sure exactly how you want to show the label (tooltip, legend, title, label, ...), but something like this might be a first step:</p> <pre><code>import numpy as np import matplotlib.pylab as pl pl.close('all') def line_hover(event): ax = pl.gca() for line in ax.get_lines(): if line.contains...
python|numpy|matplotlib
3
371,175
39,966,149
How to directly set the gradient of a layer before backpropagation?
<p>Imagine a tiny network defined as follows, where linear is a typical helper function defining TensorFlow variables for a weight matrix and activation function:</p> <p><code>final_layer = linear(linear(_input,10,tf.nn.tanh),20)</code></p> <p>Normally this would be optimized via gradient descent on a loss:</p> <p><...
<p><code>tf.gradients</code> provides this functionality via its <code>grad_ys</code> argument, see <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/train.html#gradients" rel="nofollow">here</a>. In your case, <code>tf.gradients([final_layer], list_of_variables, grad_ys=[_deriv])</code> would compute ...
python|tensorflow|backpropagation|gradient-descent
2
371,176
40,208,088
How to join dummy columns to main table?
<p>I am trying to create dummy variables for the categorical variables. However when I create them , I am getting 'ValueError: columns overlap but no suffix specified '. Here is the code:</p> <pre><code>dummy2 = pd.get_dummies(data['Teaching'], prefix='Teach') dummy2.head () dummy2.columns = ['Small/Rural','Teaching'...
<p>There is a good explanation of how to do this using pd.concat found at <a href="https://towardsdatascience.com/the-dummys-guide-to-creating-dummy-variables-f21faddb1d40" rel="nofollow noreferrer">https://towardsdatascience.com/the-dummys-guide-to-creating-dummy-variables-f21faddb1d40</a>. Modifying it for this examp...
python|pandas|dummy-variable
4
371,177
40,074,739
How to get mean of rows selected with another column's values in pandas
<p>I am trying to get calculate the mean for Score 1 only if column <code>Dates</code> is equal to <code>Oct-16</code>:</p> <p><a href="https://i.stack.imgur.com/PR8jf.png" rel="nofollow"><img src="https://i.stack.imgur.com/PR8jf.png" alt="enter image description here"></a></p> <p>What I originally tried was:</p> <p...
<p>Iterating through the rows doesn't take advantage of Pandas' strengths. If you want to do something with a column based on values of another column, you can use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.loc.html" rel="noreferrer"><code>.loc[]</code></a>:</p> <pre><code...
python|pandas|numpy
6
371,178
40,119,907
Cutting up the x-axis to produce multiple graphs with seaborn?
<p>The following code when graphed looks really messy at the moment. The reason is I have too many values for 'fare'. 'Fare' ranges from [0-500] with most of the values within the first 100. </p> <pre><code>import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt titanic = sns.lo...
<p>Actually I wrote a little <a href="http://themrmax.github.io/2015/11/13/grouped-histograms-for-categorical-data-in-pandas.html" rel="nofollow">blog post about this a while ago</a>. If you are plotting histograms you can use the <code>by</code> keyword:</p> <pre><code>import matplotlib.pyplot as plt import seaborn.a...
pandas|matplotlib|seaborn
2
371,179
40,324,983
Mac Python IDLE import tensorflow error (but tensorflow works fine in command line)
<p>I have a Macbook laptop running MacOS Sierra 10.12.</p> <p>So I followed "Pip Installation" instructions here: <a href="https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#test-the-tensorflow-installation" rel="nofollow">https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#test-the-te...
<p>Download and install PyCharm (IDE), import tensorflow directly from their plugin.</p> <p>To install a package</p> <ol> <li>In the Project Interpreter page of the project settings, select the desired Python interpreter or virtual environment. </li> <li>Click . </li> <li>In the Available Packages dialog box that ope...
macos|python-2.7|python-3.x|tensorflow|python-idle
0
371,180
39,968,211
What is the meaning of "//" in fully_connected_feed.py
<p>I am studying TensorFlow with Python 2.7.6. <a href="https://www.tensorflow.org/versions/master/tutorials/mnist/tf/index.html#tensorflow-mechanics-101" rel="nofollow">https://www.tensorflow.org/versions/master/tutorials/mnist/tf/index.html#tensorflow-mechanics-101</a></p> <p>From above page, I can obtain fully_conn...
<p>For compatibility with Python 2 and Python 3, TensorFlow consistently uses Python 3 division operators, using a <a href="https://github.com/tensorflow/tensorflow/blob/8915f0f8072c406ae3fe0dff888f51b4cad02d7d/tensorflow/examples/tutorials/mnist/fully_connected_feed.py#L19" rel="nofollow noreferrer"><code>from __futur...
tensorflow
1
371,181
40,066,648
Boxplot for list in pandas dataframe
<p>I have the foll. dataframe:</p> <pre><code> Month(s) Vals 0 Mar [3.691756, 3.59027575] 1 Mar - Apr [4.75706325, 3.138456625, 1.90741175, 3.019323] 2 Mar - May [4.698454875, 3.317812375, 2.512695375, 2.8096] 3 Mar - Jun [4.701111...
<p>Preparing your DataFrame by setting "Month(s)" as index</p> <pre><code>df = pd.DataFrame([(' Mar',[3.691756, 3.59027575]), ('Mar - Apr', [4.75706325, 3.138456625, 1.90741175, 3.019323]), ('Mar - May',[4.698454875, 3.317812375, 2.512695375, 2.8096]), ('Mar - Jun', [4...
python|pandas
2
371,182
40,158,633
How to solve nan loss?
<h1>Problem</h1> <p>I'm running a Deep Neural Network on the MNIST where the loss defined as follow:</p> <p><code>cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, label))</code></p> <p>The program seems to run correctly until I get a nan loss in the 10000+ th minibatch. Sometimes, the program runs...
<p>I find a similar problem here <a href="https://stackoverflow.com/questions/33712178/tensorflow-nan-bug/33713196#33713196">TensorFlow cross_entropy NaN problem</a></p> <p>Thanks to the author user1111929</p> <pre><code>tf.nn.softmax_cross_entropy_with_logits =&gt; -tf.reduce_sum(y_*tf.log(y_conv)) </code></pre> <p...
python|tensorflow|nan
9
371,183
39,995,839
gis calculate distance between point and polygon / border
<p>I want to calculate the distance between a point and the border of a country using python / <code>shapely</code>. It should work just fine point.distance(poly) e.g. demonstrated here <a href="https://stackoverflow.com/questions/33311616/find-coordinate-of-closest-point-on-polygon-shapely">Find Coordinate of Closest ...
<p>According to <a href="http://geopandas.org/reference.html" rel="noreferrer">geopandas</a> documentation, a GeoSeries is a vector of geometries (in your case, <code>0 (POLYGON...</code> tells that you have just one object, but it is still a vector). There should be a way of getting the first geometry element. GeoSeri...
python|gis|distance|shapely|geopandas
5
371,184
39,986,386
What function and parameters are available in Pandas in order to open a tab delimited text file?
<p>I have a text file as follows:</p> <pre><code> Movie_names Rating "A" 10 "B" 6.5 </code></pre> <p>The text file is tab delimited. Some movie titles are enclosed in a double quote. How to read it into a pandas dataframe with the quotes removed from the movie names?</p> <p>I tried usin...
<p>First you can read tab delimited files using either <code>read_table</code> or <code>read_csv</code>. The former uses tab delimiter by default, for the latter you need to specify it:</p> <pre><code>import pandas as pd df = pd.read_csv('yourfile.txt', sep='\t') </code></pre> <p>Or:</p> <pre><code>import pandas as ...
python|pandas|python-unicode|csv
1
371,185
39,697,349
Count how many attributes have a word as a substring of longer text value
<p>For example, if I have a data frame that looks like this:</p> <pre><code>id title 1 assistant 2 chief executive officer 3 director 4 chief operations officer 5 assistant manager 6 producer </code></pre> <p>If I wanted to find how many <code>title</code> have the word <strong>assistan...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.count.html" rel="nofollow"><code>str.count</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html" rel="nofollow"><code>sum</code></a>:</p> <pre><code>print (df.title.str.count('chief'...
python|string|pandas|dataframe|count
1
371,186
39,540,806
Tensorflow - Any input gives me same output
<p>I am facing a very strange problem where I am building an RNN model using tensorflow and then storing the model variables (all) using tf.Saver after I finish training.</p> <p>During testing, I just build the inference part again and restore the variables to the graph. The restoration part does not give any error.</...
<p>I have been able to resolve this issue. This seemed to be happening as one of my input feature was very dominant in its original values due to which after some operations all values were converging to single number. Scaling that feature has helped to resolve this.</p> <p>Thanks</p>
tensorflow|recurrent-neural-network
2
371,187
39,761,366
Transpose the data in a column every nth rows in PANDAS
<p>For a research project, I need to process every individual's information from the website into an excel file. I have copied and pasted everything I need from the website onto a single column in an excel file, and I loaded that file using PANDAS. However, I need to present each individual's information horizontally i...
<p>If no data are missing, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="noreferrer"><code>numpy.reshape</code></a>:</p> <pre><code>print (np.reshape(df.values,(2,5))) [['Andrew' 'School of Music' 'Music: Sound of the wind' 'Dr. Seuss' 'Dr.Sass'] ['Michelle' 'Scho...
python|pandas|dataframe|reshape|transpose
12
371,188
39,859,392
Get grouped Dictionary list from a file that has a time and errors then plot the time differences in python
<p>I have this file as below:</p> <pre><code>Date;Time;Task;Error_Line;Error_Message 03-13-15;08:2123:10;C:LOGINMAN;01073;Web Login Successful from IP Address xxx.xxx.x.xx 03-13-15;05:23:1235;B:VDOM;0906123;Port 123 Device 1012300 Remote 1 1012301 Link Up RP2009 03-13-15;05:23:123123;A:VCOM;0906123;Port 123 Device 101...
<p>As far as grouping by line number, this should do the trick:</p> <pre><code>import csv D = {} with open('logfile') as f: reader = csv.DictReader(f, delimiter=';') for row in reader: el = row['Error_Line'] if el not in D: D[el] = [] # Initiate an empty list D[el].append(r...
python|numpy|matplotlib|plot
1
371,189
39,726,953
change data structure of pandas dataframe
<p>I have this sample data...</p> <pre><code>import pandas as pd from StringIO import StringIO stock_list="""EAN code, name, stock , MONIN Syrups, 12345, Monin Mojito Mint Syrup 250 ml, 100 , BONNE MAMAN, 7890. Bonne Maman Strawberry Preserve 370g, 200 6543, Bonne Maman Raspberry 370g, 150""" audit = pd.read_csv(St...
<p>Copy <code>name</code> column to <code>type</code> column, clear elements to NaN and <code>ffill()</code> it:</p> <pre><code>import pandas as pd from io import StringIO stock_list="""EAN code, name, stock , MONIN Syrups, 12345, Monin Mojito Mint Syrup 250 ml, 100 , BONNE MAMAN, 7890, Bonne Maman Strawberry Preser...
pandas
3
371,190
39,544,926
CancelledError: RunManyGraphs while running distributed tensorflow
<p>I am trying to distribute TensorBox ReInspect implementation (<a href="https://github.com/Russell91/TensorBox" rel="nofollow">https://github.com/Russell91/TensorBox</a>) over one ps and two workers. I have added the training code in a <code>sv.managed_session</code>.</p> <pre><code>def train(H, test_images, server)...
<p>The <code>CancelledError</code> is relatively benign: I suspect that your main thread exits the <code>with sv.managed_session() as sess:</code> block, which closes the session and cancels all pending requests, including those made by your two pre-fetching threads.</p> <p>To avoid seeing this error, I'd recommend th...
python|tensorflow
2
371,191
39,489,089
Interpolating elements of a color matrix on the basis of some given reference elements
<p>This is more or less a follow up question to <a href="https://stackoverflow.com/questions/39485178/two-dimensional-color-ramp-256x256-matrix-interpolated-from-4-corner-colors?noredirect=1#comment66289716_39485178">Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors</a> that was profoundly a...
<p>First some questions to better clarify your problem:</p> <ul> <li>what kind of interpolation you want: linear/cubic/other ?</li> <li>What are the points constrains? for example will there be alway just single region encapsulated by these control points or there could be also points inside? </li> </ul> <p>For the ...
python|numpy|image-processing|matrix|scipy
5
371,192
39,771,934
How to extract arrays from an arranged numpy array?
<p>This is a relative question of the post <a href="https://stackoverflow.com/questions/39673377/how-to-extract-rows-from-an-numpy-array-based-on-the-content/39674145?noredirect=1#comment66837793_39674145">How to extract rows from an numpy array based on the content?</a>, and I used the following code to split rows bas...
<p>Here's an approach considering pair of elements from each row as indexing tuples -</p> <pre><code># Convert to linear index equivalents lidx = np.ravel_multi_index(arr[:,:2].T,arr[:,:2].max(0)+1) # Get sorted indices of lidx. Using those get shifting indices. # Split along sorted input array along axis=0 using tho...
python|arrays|numpy
1
371,193
39,677,168
Tensorflow documentation's example code on "Logging Device Placement" doesn't print out anything
<p><a href="https://www.tensorflow.org/versions/r0.10/how_tos/using_gpu/index.html" rel="noreferrer">Tensorflow documentation</a> has the following example code on finding out the device placement of nodes. That is, on which device a particular computation takes place.</p> <pre><code># Creates a graph. a = tf.constant...
<p>For Jupyter (and other) users, there is a recently-added feature that makes it possible to read back the device placement when you make a <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/client.html#Session.run" rel="noreferrer"><code>Session.run()</code></a> call and print it in your notebook.</p>...
tensorflow
12
371,194
39,797,393
Pandas doesn't seem to "see" my index
<p>I'm a long time user of Python, but am just starting Pandas. I'm using the latest anaconda download of Pandas 0.18 and Python 3.5 in IPython 4.2.0 on a Mac running OS-X 10.11.6. I have a data frame whose first few column names are: Date, Time, H2O16c_ppm, H2O_16cppm_se... It happens that the dates in the Date colum...
<p>The <code>drop</code> method works on the index by default. Use <code>axis=1</code> to drop a column</p> <pre><code> redu1 = test_data.drop(['Date'], axis=1) </code></pre>
pandas
0
371,195
39,424,776
Python/Numpy array dimension confusion
<p>Suppose <code>batch_size = 64</code>. I created a batch : <code>batch = np.zeros((self._batch_size,), dtype=np.int64)</code>. Suppose I have batch of chars such that <code>batch = ['o', 'w', ....'s']</code> of 64 size and <code>'o'</code> will be represented as <code>[0,0, .... 0]</code> 1-hot vector of size 27. So,...
<p>In the 1st block the initialization of <code>batch</code> to <code>zeros</code> does nothing for you, because <code>batch</code> is replaced with the <code>asarray(temp1)</code> later. (Note my correction). <code>temp1</code> is a list of 1d arrays (<code>temp</code>), and produces a 2d arrray.</p> <p>In the 2nd i...
python|numpy
1
371,196
39,592,117
Python MemoryError when 'stacking' arrays
<p>I am writing code to add data along the length of a numpy array (for combining satellite data records). In order to do this my code reads two arrays and then uses the function </p> <pre><code>def swath_stack(array1, array2): """Takes two arrays of swath data and compares their dimensions. The arrays should ...
<p>I changed your last line to <code>np.ma.vstack</code>, and got</p> <pre><code>In [474]: swath_stack(np.ones((3,4)),np.zeros((3,6))) Out[474]: masked_array(data = [[1.0 1.0 1.0 1.0 -- --] [1.0 1.0 1.0 1.0 -- --] [1.0 1.0 1.0 1.0 -- --] [0.0 0.0 0.0 0.0 0.0 0.0] [0.0 0.0 0.0 0.0 0.0 0.0] [0.0 0.0 0.0 0.0 0.0 0...
python|arrays|numpy|memory|satellite-image
1
371,197
39,821,470
Numpy not found in Python3
<p>I am trying to run numpy in Python 3, using the WinPy distribution. I put #!python3 at the top of the script, because I was told that is something that Winpy has that allows you to make it run in a certain version. If I run the script in the shell(Eclipse) it works fine, but when I try to run it from the console, I ...
<p>The "#!python3" is to help the console determine the right version of python. However you need to make sure the path is correct. Instead of putting "#!python3", put "#!/usr/bin/" and then your python version, so "python" or "python3". </p> <p>Check this article for more information on this. <a href="https://stackov...
python|numpy
0
371,198
39,467,341
How to count concurrent events in a dataframe in one line?
<p>I have a dataset with phone calls. I want to count how many active calls there are for each record. I found this <a href="https://stackoverflow.com/questions/24745882/pandas-cumulative-sum-using-current-row-as-condition">question</a> but I'd like to avoid loops and functions.</p> <p>Each call has a <code>date</code...
<p>You can use:</p> <pre><code>#convert time and date to datetime df['date_start'] = pd.to_datetime(df.start + ' ' + df.date) df['date_end'] = pd.to_datetime(df.end + ' ' + df.date) #remove columns df = df.drop(['start','end','date'], axis=1) </code></pre> <p>Solution with loop:</p> <pre><code>active_events= [] for ...
python|python-3.x|datetime|pandas|conditional-statements
4
371,199
39,755,131
List in column Python + Pandas
<p>I'm new to pandas and would like to analyse some data arranged like this:</p> <pre><code>label aa bb index 0 [2, 5, 1, 4] [x1, x2, y1, z1] 1 [3, 3, 19] [x3, x4, y2] 2 [6, 4, 2, 8, 9, 10] [y1, y2, z3, z4, x1, w] <...
<p>Pandas works best when your data are in a table format and individual cells contain values, not collections. To use pandas effectively for your problem, you need to change the way you create your data table. </p> <p>Ultimately, it looks like you want to generate a table with columns representing object "id", "amoun...
python|pandas
2