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 |
|---|---|---|---|---|---|---|
352,100 | 64,272,148 | replace dataframe values from another list with specific indexes | <p>I have a dataframe which has a column date and I'm trying to replace with another list based on index, for example:
wrong_dates_indexes has list of indexes where date is in wrong format in original dataframe df:</p>
<pre><code>dirty_dates_indexes=[4,33,48,54,59,91,95,132,160,175,180,197,203,206,229,237,266,271,278,2... | <p>You are trying to get the value from <code>dirty_dates_indexes</code> and use that to lookup the position in <code>formatted_dates</code>. It may be messing you up.</p>
<p>You are using loc instead of iloc to reach the specific row.</p>
<p>Here's what I did.</p>
<pre><code>dirty_dates_indexes=[4,33,48,54,
... | python|python-3.x|pandas|dataframe|data-science | 0 |
352,101 | 64,341,359 | Scalar Multipliction Numpy | <p>I need to multiply a scalar value to a numpy array starting from a specific element.</p>
<p>eg) 3 * [1,1,1,1,1,1] = [1,3,3,3,3,3]</p>
<p>I have tried to do <code>np.dot(value, arr[1:])</code>, but this removes the first element. How would I do this?</p> | <p>Is your data a numpy array or a python array? For numpy array:</p>
<pre><code>a[1:] *= 3
</code></pre>
<p>For python array:</p>
<pre><code>for i in range(1,len(a)): a[i] *= 3
</code></pre>
<p><strong>Note</strong>: Of course the python approach works for numpy arrays as well, but it wouldn't take advantage of numpy'... | python|numpy | 4 |
352,102 | 64,423,245 | dataframe Sort_values giving improper results | <p><a href="https://i.stack.imgur.com/cwzhx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cwzhx.png" alt="enter image description here" /></a></p>
<p>Hi I am trying to get the top 10 values.
I would like to get the top 10 attendance and punctuality by staff.
here's my code for sorting:
newData =dat... | <p>Because values in column <code>Attendance</code> are strings, so sorted in lexicographic order.</p>
<p>So need convert them to numeric:</p>
<pre><code>data['Attendance'] = data['Attendance'].astype(float)
#if possible some non numeric values convert them to NaNs
#data['Attendance'] = pd.to_numeric(data['Attendance']... | pandas|sorting|plotly | 0 |
352,103 | 64,539,460 | If one dataframe value exists in another dataframe, then get a value from the dataframe | <p>I am a beginner in Python and this is my first time using pandas. I would like to create a code to analyze my data but it's not working.</p>
<p>I have 2 dataframes: first one has the information about how user rated a movie ('user id', 'movie id', 'rating') and second one had the information about the users ('user i... | <p><code>for</code> loops are slower. You can avoid it by using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>df.merge</code></a></p>
<pre><code>In [2142]: df1.merge(df2, on='user id')
Out[2142]:
user id gender
0 4 F
1 ... | python|pandas|dataframe | 1 |
352,104 | 64,186,435 | Dataframe Resample with GroupBy on time data | <p>Traffic data per second shows the number of cars in and out. I want to aggregate them into 2-minute by In/Out and show their totals, like:</p>
<p><a href="https://i.stack.imgur.com/C4TeK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C4TeK.png" alt="enter image description here" /></a></p>
<pre><... | <p>I believe you should resample on index. Can you try:</p>
<pre><code>df.time = pd.to_datetime(df.time)
df.set_index("time").groupby('flow').resample('2T')['cars'].sum()
flow time
In 2020-01-23 13:34:00 59
2020-01-23 13:36:00 298
Out 2020-01-23 13:34:00 431
... | python|pandas|dataframe|group-by|resampling | 1 |
352,105 | 64,330,249 | Pandas - Plot the timely distributed usage of two types in one plot | <p>I have the dataframe as the following:</p>
<pre><code>payment time of
the day
credit card 23
cash 1
cash 2
credit card 5
cash 2
credit card 8
credit card 22
credit card 23
credit card 22
cash 22
</code></pre>
<p>Expected Output:</p>
<p>x-axis is the time of the day, and ... | <p>The solution uses a trick: sum the uniform dummy weight <code>1</code>. The idea is in fact a special case of dealing with non-equal sample weight. After counting is completed, just populate the sum of count into the correct indexes of the required arrays.</p>
<h2>Code</h2>
<pre><code># 1. accumulate
# dummy equal w... | python|pandas | 0 |
352,106 | 64,451,449 | Print column with a specific value in python | <p>I am using Colab.I am trying to print data form only NY,NC, SC State</p>
<pre><code>confirmed_cases_USA, deaths_USA = get_confirmed_deaths_tuple_df (USA_covid_data)
# selecting rows based on condition PA, IL,OH,GA ,NC
options = ['NC',"PA"]
#options = ['NC',"PA","IL","OH",&... | <p>I'm not sure what <code>get_confirmed_deaths_tuple_df</code> does but it doesn't look like a DataFrame.</p>
<p><code>USA_covid_data['State'].isin(options)</code> should return a boolean mask containing <code>True</code> and <code>False</code>. Return the values that satisfy the <code>True</code> condition with <code... | python|pandas|google-colaboratory | 0 |
352,107 | 64,521,320 | Python pandas dataframe: Count number of elements a in column greater or smaller than a threshold | <p>This code will count the number of elements in column <code>c2</code> that have value greater than or equal 3</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'c1': ['A', 'B','C','D','E'], 'c2': [3, 1, 0,2,5]})
count=df.loc[:,'c2']
count=count[~ (count<3)]
count=count.shape[0]
</code></pre>
<p>Is there a di... | <p>You can update your code to add the condition and do the count in one single line as below</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'c1': ['A', 'B','C','D','E'], 'c2': [3, 1, 0,2,5]})
count=df[df['c2'] >= 3].count().shape[0]
print(count) # prints 2
</code></pre> | python|pandas|dataframe | 2 |
352,108 | 64,311,469 | Replace DataFrame values within matching column names with Series' keys | <p>I have a data frame:</p>
<pre class="lang-python prettyprint-override"><code>df = pd.DataFrame(
[[1, 2, 3, 0, 0], [4, 5, 6, 0, 0]],
columns=['a', 'b', 'c', 'd', 'e'])
</code></pre>
<p>and a data series:</p>
<pre class="lang-python prettyprint-override"><code>s = pd.Series({'d': 7, 'e': 8})
</code></pre>
<p... | <p>Lets use <code>DataFrame.assign</code>:</p>
<pre><code>df.assign(**s)
</code></pre>
<hr />
<pre><code> a b c d e
0 1 2 3 7 8
1 4 5 6 7 8
</code></pre> | python|pandas|dataframe | 6 |
352,109 | 64,362,032 | How to melt a dataframe while doing some operation? | <p>Let's say that I have the following dataframe:</p>
<pre><code>index K1 K2 D1 D2 D3
N1 0 1 12 4 6
N2 1 1 10 2 7
N3 0 0 3 5 8
</code></pre>
<p>Basically, I want to transform this dataframe into the following:</p>
<pre><code>index COL1 ... | <p>This is matrix multiplication:</p>
<pre><code>(df[['D1','D2','D3']].T@df[['K1','K2']]).unstack().reset_index()
</code></pre>
<p>Output:</p>
<pre><code> level_0 level_1 0
0 K1 D1 10
1 K1 D2 2
2 K1 D3 7
3 K2 D1 22
4 K2 D2 6
5 K2 D3 13
</code></pre... | python|pandas | 7 |
352,110 | 64,278,565 | How do I join two tables even if some rows are missing from each other | <pre><code>**Table 1** **Table2**
Column_name Value Column_name Value
K1 13 K1 65
K2 25 K2 31
K4 46 K3 71
H1 56 H2 56
H3 26
H4 ... | <p>Use <code>outer</code> join from the <code>pandas</code>.</p>
<pre><code>>>> df1 = pd.DataFrame({"Column_name":["K1","K2","K4","H1","H3","H4","H6"],"col2":[13,25,46,56,26,46,56]})
>>> df2 = pd.DataFrame({"... | python|python-3.x|pandas | 3 |
352,111 | 64,556,182 | Pandas get column name of max of several column sums in groupby to new column | <p>I have a dataframe on this form:</p>
<pre><code>
value1 value2 value3 value4 random string column group
index1 10 2 3 4 stuff group 2
index2 5 4 3 2 other stuff group 1
index3 6 7 8 9 other stuff ... | <p>Let's extract the columns by group then map:</p>
<pre><code>max_cols = (df.filter(like='value') # choose the value columns, also df.iloc[:, :4]
.groupby(df['group']).sum() # calculate sum per group
.idxmax(axis=1) # find col with max value
)
df['Column'] = df... | python|pandas|pandas-groupby | 2 |
352,112 | 64,342,732 | Python: Pandas how to highlight the Header Row | <p>Here is the function that highlights all the rows in my table:</p>
<pre><code>def highlight(s):
if s.Points == 10 or s.Points == 15:
return ['background-color : #d9ead3']*3
elif s.Points == 8 or s.Points == 6:
return ['background-color : #cfe2f3']*3
elif s.Points == 5:
return ['background-color : #f4ccc... | <p>Have you tried this?</p>
<pre><code>col_loc_1 = df.columns.get_loc('Rank') + 2
col_loc_1 = df.columns.get_loc('GolferName') + 2
df.style.apply(highlight, axis = 1).set_table_styles(
[{'selector': f'th:nth-child({col_loc_1})',
'props': [('background-color', '#ff0')]},
{'selector': f'th:nth-child({co... | python|pandas|formatting|highlight | 2 |
352,113 | 64,433,889 | DataFrame New Column to split sessions by time difference - pandas | <p>I have following sorted DataFrame:</p>
<pre><code>import pandas as pd
hits = {'id': ['A','A','A','A','B','B','C','C'],
'datetime': ['2010-01-02 03:00:00','2010-01-02 03:05:10','2010-01-02 03:51:35','2010-01-02 04:40:20',
'2010-01-02 03:29:10','2010-01-02 03:29:15','2010-01-02 03:45:20','... | <p>It's a common technique to use <code>cumsum</code> on <code>diff</code> compared with the threshold to identify blocks separated by threshold. Something like:</p>
<pre><code>series.diff().gt('30Min').cumsum()
</code></pre>
<p>Since you want to find the blocks by id, you just need to wrap that in <code>groupby()</cod... | python|pandas|partition | 3 |
352,114 | 64,230,842 | Validation accuracy when training and testing within same loop | <p>Since I am training and testing within same loop (for each epoch on <code>training set</code>, network is applied on entire <code>validation set</code>).</p>
<p>Now does it make sense that the highest validation accuracy I get at some instant (nth epoch) be my network's highest accuracy or should I only use the vali... | <p>I think you are confusing <code>testing</code> with <code>validation</code>. If possible you should keep a separate test set of your dataset for testing only AFTER the training and validation are done.</p>
<p>Although you can use that test set for your validation, it's the best practice to do inference on a separate... | deep-learning|pytorch | 0 |
352,115 | 64,215,879 | Create new Pandas boolean df based on values from list | <p>Suppose I have this df:</p>
<pre><code>col1 col2 col3 col4
A B B A
B C C D
D null D null
</code></pre>
<p>And a list</p>
<pre><code>list1 = ["A","B","C","D"]
</code></pre>
<p>How do I create a new df with the boolean representation of the values of... | <p>This is essentially crosstab:</p>
<pre><code>df.melt().groupby('value')['variable'].value_counts().unstack(fill_value=0)
</code></pre>
<p>Output:</p>
<pre><code>variable col1 col2 col3 col4
value
A 1 0 0 1
B 1 1 1 0
C 0 1 ... | python|pandas | 1 |
352,116 | 64,513,991 | how to convert outlogits to tokens? | <p>i have a forward function in allenNlp given by :</p>
<pre><code> def forward(self, input_tokens, output_tokens):
'''
This is the main process of the Model where the actual computation happens.
Each Instance is fed to the forward method.
It takes dicts of tensors as input, with same keys as the fie... | <p>In allennlp you have access to the <code>self.vocab</code> attribute with <a href="https://docs.allennlp.org/master/api/data/vocabulary/#get_token_from_index" rel="nofollow noreferrer">Vocabulary. get_token_from_index</a>.</p>
<p>Usually to select a token from the logits one would apply a softmax (in order to have a... | nlp|pytorch|allennlp | 1 |
352,117 | 64,284,804 | Inaccesable first column in pandas dataframe? | <p>I have a dataframe with multiple columns. When I execute the following code it assigns the header for the first column to the second column thereby making the first column inaccessible.</p>
<pre><code>COLUMN_NAMES = ['id', 'diagnosis', 'radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean',
'smoothness_mean... | <p><code>pd.read_csv</code> is going to make your first column the index rather than a column like the rest of what is on your list.</p>
<p>You could update it to be:</p>
<pre><code>path_to_file = list(files.upload().keys())[0]
data = pd.read_csv(path_to_file, names=COLUMN_NAMES, header=0,index_col = False)
</code></pr... | python|pandas|dataframe | 1 |
352,118 | 64,592,950 | Pandas - shifting a rolling sum after grouping spills over to following groups | <p>I might be doing something wrong, but I was trying to calculate a rolling average (let's use sum instead in this example for simplicity) after grouping the dataframe. Until here it all works well, but when I apply a shift I'm finding the values spill over to the group below. See example below:</p>
<pre><code>import ... | <p>The problem is that</p>
<pre><code>df.groupby(by='X')['Y'].rolling(window=2, min_periods=2).sum()
</code></pre>
<p>returns a new series, then when you chain with <code>shift()</code>, you shift the series as a whole, not within the group.</p>
<p>You need another <code>groupby</code> to shift within the group:</p>
<p... | python|pandas|dataframe | 2 |
352,119 | 64,253,973 | How to display Polygon List into one Graph with For Loops | <p>so I'm working on a Line of Sight script where the Polygons act as buildings and return a boolean value based on whether a line intersects with a Polygon.</p>
<p>The logic behind it works, but when I try to integrate more Polygons from a list called <em>polycoords</em> and use a For Loop so it can instantiate it on ... | <p>Resolved meshgrid creation in the loop has been moved out and done once as given below:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import shapely.geometry
from shapely.geometry import LineString
from shapely.geometry import Point, Polygon
import descartes
origin = [-1.0, 0.0] # Set a point to... | python|numpy|matplotlib|shapely|descartes | 0 |
352,120 | 64,223,751 | Concurrent Caching Iterator Error when using tf.data.cache(file) | <p>I am getting the following errors when using tf.data.cache(file) followed by <code>model.fit()</code>, I am not sure why this is happening. There are no <code>lockfile</code> in the directory.</p>
<pre><code>tensorflow.python.framework.errors_impl.AlreadyExistsError: There appears to be a concurrent caching iterato... | <p>The problem was due to the creation of an iterator before the <code>model.fit()</code> on the dataset.</p>
<pre><code>ds_iter = iter(ds)
x, y = ds_iter.next()
</code></pre>
<p>The problem is resolved after removing this code.</p> | python|tensorflow | 0 |
352,121 | 64,446,787 | Plot multiple lines with Python Bokeh fom the same dataset | <p>Is there a possibility to achive plots like sample1 with Bokeh? Sample1 was created with Matplotlib. My goal is to plot multiple short lines which are separated from each other on the map. But the lines share the same source and are just different parts from the source within.</p>
<p>I already wrote a small script b... | <p>Anything that can be plotted with Matplotlib, can be plotted with Bokeh. Sometimes with a bit more code, sometimes with a bit less.</p>
<p>There are too many things going on in your code, so I'll answer in plain text:</p>
<ul>
<li>Use <code>multi_line</code> instead of <code>line</code>: <a href="https://docs.bokeh.... | python|matplotlib|bokeh|bokehjs|pandas-bokeh | 2 |
352,122 | 64,380,223 | Pandas : XLSX to CSV : extra comma generated as a first character | <p>I wrote a basic function to convert a xlsx file to a csv file. I am getting an extra <code>,</code> at the beginning of every CSV generated files. Do you know why and how to fix this issue?</p>
<p>Here is one example of a csv file generated with the code i wrote:</p>
<pre><code>,0,First Name,Last Name,Gender,Country... | <p>The code is working great. It seems that your first row (that corresponds to the headers) have the first column empty and that is why the ´,´ is added at the beginning.
Maybe you need to use ´data_xls.to_csv(csv_file_name,header=True, encoding = 'utf8', index=False´) parameter to ignore the row numbers.</p> | python|pandas|csv | 1 |
352,123 | 64,452,644 | How to extract the uppercase as well as some substring from pandas dataframe using extract? | <p>This question is the follow up question to previous question <a href="https://stackoverflow.com/questions/64452218/how-to-extract-only-uppercase-substring-from-pandas-series?noredirect=1#64452218">How to extract only uppercase substring from pandas series?</a>.</p>
<p>Instead of changing the old question, I decided ... | <p>For <code>feat</code>, since you already got the answer to <code>agg</code> in your other StackOverflow question, I think you can use the following to extract two different series based off two different patterns that are separated with <code>|</code> and then <code>fillna()</code> one series with another.</p>
<ol>
... | python|pandas|python-re | 1 |
352,124 | 64,564,125 | Building an older Tensorflow 2.x | <p>I have been trying to do this for a while now. I wasn't able to get a build on my local machine so I went the Docker route. I was able to successfully the use docker image devel-gpu to build Tensorflow. The problem is that it built the latest and greatest (2.5). I have searched and searched for a way to build an old... | <p>If you are fine with using already built images there are older versions available on Docker Hub. Here is a link for 2.1: <a href="https://hub.docker.com/r/tensorflow/tensorflow/tags?page=1&name=2.1" rel="nofollow noreferrer">https://hub.docker.com/r/tensorflow/tensorflow/tags?page=1&name=2.1</a> This is the... | docker|tensorflow|tensorflow2.0 | 0 |
352,125 | 64,306,068 | Python Initialize multidimensional numpy array of random value | <p>If I want to bulid a 3-dimensional array
And I can write something like this (x is the 3-dimensional array)</p>
<pre><code>for i in range(pN):
for j in range(C):
for k in range(K+1):
X[i][j][k] = random.uniform(0,1) #random initialize
</code></pre>
<p>But how can I make this code to be more... | <p>Just use numpy random function:</p>
<p><a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.rand.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.rand.html</a></p>
<p>It will generate random array of a shape you want (like 3x2x3)</p... | python|numpy | 2 |
352,126 | 64,476,745 | Tensorflow-Lite unresolved reference for tfLite!!.setUseNNAPI in kotlin Android App | <p>I am trying to run <a href="https://github.com/lmoroney/dlaicourse/tree/master/TensorFlow%20Deployment/Course%202%20-%20TensorFlow%20Lite/Week%202/Examples/Android%20Apps/object_detection" rel="nofollow noreferrer">this app</a> which is an object detection application. The app uses Tensorflow-Lite.</p>
<p>When tryin... | <p>Please check the build.gradle file for app.
If you see the below line or if the version is less than 2.3.0 update it to the latest version</p>
<p><strong>implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly'</strong></p>
<p>change it to</p>
<p><strong>implementation 'org.tensorflow:tensorflow-lite:2.3.0'</st... | android|android-studio|tensorflow|kotlin|tensorflow-lite | 6 |
352,127 | 64,547,862 | Keyerror on dataframe scatterplot | <p>I am trying to print a scatterplot of latitude and longitude values from a df. When running this:</p>
<pre><code>info.plot.scatter(x=info['latitude'], y=info['longitude'])
</code></pre>
<p>I get the following key error</p>
<pre><code>KeyError: "None of [Float64Index([ 34.6951242, 34.6951242, ... | <p>Forgo the <code>info</code> inside <code>scatter</code>:</p>
<pre><code>info.plot.scatter(x='latitude', y='longitude')
</code></pre>
<p>Or use <code>plt.scatter</code>:</p>
<pre><code>plt.scatter(x=info['latitude'], y=info['longitude'])
</code></pre> | python|pandas|dataframe|jupyter-notebook | 1 |
352,128 | 64,291,796 | subset a python dataframe by conditions | <p>I trying to select the name row with count>250, which is called effective here. So we will try to find the mean of its rate</p>
<pre><code>t3=dfnew.groupby('name')['ratings']
t4=t3.count()
t5=t4[t4.values>250]
t6=t3.mean()
t6[(t6.index==t5.index)]
</code></pre>
<p>Obviously the problem is in last row of my cod... | <pre><code>t3=dfnew.groupby('name')['ratings'].agg(['count','mean'])
t5=t3[t3['count']>250]
t5
</code></pre>
<p>It works fine when I aggregate two functions at the same time.</p> | python|pandas|numpy | 0 |
352,129 | 64,458,352 | Difference between installing pandas with python and python3 | <p>I have to install pandas but nothing I am trying seems to be working. I have tried to run this in cmd</p>
<pre><code>pip install wheel
pip install pandas
pip3 install pandas
python -m pip install pandas
python3 -m pip install pandas
</code></pre>
<p>And even updated setuptools. When I run <code>python -m pip install... | <p>Assuming that you are on Linux or Mac, <code>python</code> stands for <strong>Python Version 2</strong> and <code>python3</code> of course stands for <strong>Python Version 3</strong>. You should not use python 2 because it is no longer being actively developed and it's support has also been dropped more than a year... | python|pandas|installation|module | 0 |
352,130 | 64,591,952 | How to mask an image in a square shape? | <p>I am trying to mask a square shape out of a rectangular image. Those area out of square shape will be painted white. I write code as below.</p>
<pre><code>photo_data = imageio.imread('./demo/dog.jpg')
total_rows,total_columns,layer=photo_data.shape
X,Y=np.ogrid[:total_rows,:total_columns]
center_rows=total_rows/2
ce... | <p>Instead of</p>
<pre><code>np.logical_and(upper_mask,low_mask,left_mask,right_mask)
</code></pre>
<p>you can use</p>
<pre><code>upper_mask & low_mask & left_mask & right_mask
</code></pre>
<p>but actually you need <code>OR</code> for your task, so correct way is to use:</p>
<pre><code>upper_mask | low_mas... | python|image|numpy | 0 |
352,131 | 64,462,917 | "view_as_windows" from skimage but in Pytorch | <p>Is there any Pytorch version of <code>view_as_windows</code> from skimage? I want to create the view while the tensor is on the GPU.</p> | <p>I needed the same functionality from Pytorch and ended up implementing it myself:</p>
<pre class="lang-py prettyprint-override"><code>def view_as_windows_torch(image, shape, stride=None):
"""View tensor as overlapping rectangular windows, with a given stride.
Parameters
----------
ima... | python|pytorch|scikit-image | 1 |
352,132 | 64,525,370 | How to use lists of strings in a column of pandas dataframe | <p>I have a pandas DataFrame which includes a feature, named B here, that has list of values:</p>
<p>df</p>
<pre><code>A B
t8 ab1r,tvc3b,cdv5s,tad7
t9 trg1br
t2 trg6b,t9try,ab1r,t8sf,t10hg
t2 t20hj,tad7'
... ...
</code></pre>
<p>What is a good way to normalize feature B in this dataf... | <p>You can do this:</p>
<pre><code>df = df.apply(lambda x: x.str.split(',').explode())
print(df)
A B
0 t8 ab1r
0 t8 tvc3b
0 t8 cdv5s
0 t8 tad7
1 t9 trg1br
2 t2 trg6b
2 t2 t9try
2 t2 ab1r
2 t2 t8sf
2 t2 t10hg
3 t2 t20hj
3 t2 tad7'
</code></pre> | pandas|dataframe | 1 |
352,133 | 64,216,491 | How can I verify my google account to use TensorBoard.dev during sbatch? | <p>I want to run a tenosorboard.dev using the following bash file.</p>
<pre><code>#!/bin/bash
#SBATCH -c 1
#SBATCH -N 1
#SBATCH -t 50:00:00
#SBATCH -p medium
#SBATCH --mem=4G
#SBATCH -o hostname_tensorboard_%j.out
#SBATCH -e hostname_tensorboard_%j.err
module load python/3.7.4 conda2/4.2.13
source activate env_tf
ec... | <p>Not familiar with sbatch, but when you authorize tensorboard, it creates a file so that you can upload afterwards without re-authorizing. You should be able to manually copy that file into the environment in which you will be uploading in the future.</p>
<p>On my workstation, the credentials file is</p>
<p><code>~/... | tensorflow|tensorboard|slurm|sbatch | 2 |
352,134 | 64,484,146 | Pandas way to create new dataframe from rows which contain list of dictionaries | <p>I have the following <code>dataFrame</code>.</p>
<pre><code> ID APs
0 1 [{'ID': -1, 'Name': 'Merkmal nicht erhoben'}, {'ID': 0, 'Name': 'Nicht bekannt'}, {'ID': 1, 'Name': 'Werbung bekannt'}, {'ID': 2, 'Name': 'Werbung unbekannt, aber Marke/Modell bekannt'}]
1 2 [{'ID': -1, 'Name': 'Merkmal nicht erhoben... | <p>Let us try <code>explode</code> both on row and columns then <code>join</code></p>
<pre><code>s = df.pop('APs').explode()
out = pd.DataFrame(s.tolist(),index=s.index).join(df.rename(columns={'ID':'df_id'}))
out
Out[342]:
ID Name df_id
0 -1 Merkma... | python|pandas | 1 |
352,135 | 64,433,110 | I have two arrays and I need to do a simple operation in one array depending on conditions of the other array | <p>I have two arrays <code>R</code> and <code>M</code>. In the first array, <code>R.shape = (10,7)</code>, each row corresponds to the state of an object and each column is the evolution of the object in time (10 objects in 7 time periods each). The second array <code>M</code> is a characteristic of each object <strong... | <p>I created a dictionary mapping each string to the value to add, then looped through <code>M</code> to add the values to <code>R</code>:</p>
<pre><code>d = {'C':.5, 'SC':.7, 'HS':.5, 'HSDO':.3}
for i, val in enumerate(M):
R[i] += d[val]
</code></pre>
<p>Result:</p>
<pre><code>array([[1.5, 1.5, 1.5, 1.5, 1.5, 1.5... | python|arrays|numpy|indexing | 1 |
352,136 | 64,570,366 | how to invert pandas data into text data | <p>I want to make a simple spell corrector system and I have a datafarme like this:</p>
<pre><code>incorrect_word, correct_word
scoohl,school
watn,want
frienf,friend
</code></pre>
<p>"I watn to go scoohl"<br />
I want to correct this sentence by replacing the incorrect sample in "incorrect_word&qu... | <p>I would do like this :</p>
<pre><code>df = pd.DataFrame([['scoohl','school'], ['watn','want'], ['frienf','friend']], columns=['incorrect_word', 'correct_word'])
df.index = df['incorrect_word']
df.drop(columns=['incorrect_word'], inplace=True)
text_to_correct = "I watn to go scoohl"
words = text_to_correc... | python|pandas|nlp | 1 |
352,137 | 64,177,572 | Loop for column names in python | <p>I would like to write mean values from one dataframe (df1) to another (dfmaster ).
Manually i can manage it, but i would like to automate the process in that way, that it will be read all the columns names from the df1 (as variable) and those variable will be used in the code below, to calculate mean of all columns ... | <p>You can use agg to get specific aggregations for each column:</p>
<pre><code>df1_summary = (df1.agg(["mean", "std", "max"])
.rename(index={"mean": "Mean", "std": "St.Dev", "max": "Max"}))
print(df1_summary)
... | python|pandas|dataframe|loops|automation | 3 |
352,138 | 64,364,503 | I am having issue installing numpy in windows | <p>I had Python 3.9.0 32 bit installed in my windows system and successfully installed numpy using the command: <code>pip install numpy</code> in the command Prompt.</p>
<p>I then had to switch to Python 3.9.0 64 bit and I was unable to use numpy from here on so I tried to install it again but I got the following error... | <p>i think Windows has both Python versions mixed up, or there are traces of both 32 bit and 64 bit, have a look at the <code>PATH</code> environment variables, and other variables relating to Python are using the right file path.</p>
<p>If this does not resolve the issue remove both versions of Python and use a CClean... | python-3.x|numpy | 0 |
352,139 | 64,507,089 | Approximate an array efficiently | <p>I have an array of the form</p>
<pre><code>[-0.87336,0.18776,1.00000,0.56449,-0.27645]
</code></pre>
<p>I would like to convert it to an array of the form</p>
<pre><code>[-1.0,0.0,1.0,1.0,0.0]
</code></pre>
<p>following the rule that if the element i of the initial array is less or equal to -0.5, then it is assigned... | <p>In numpy you could use <code>np.round</code>:</p>
<pre><code>x = np.array([-0.87336,0.18776,1.00000,0.56449,-0.27645])
x.round()
</code></pre>
<p>which gives:</p>
<pre><code>array([-1., 0., 1., 1., -0.])
</code></pre>
<p>If you don't like the <code>-0.</code>, you can add <code>0.</code>:</p>
<pre><code>x.round(... | python|numpy | 1 |
352,140 | 64,303,655 | Input z must be 2D, not 0D in python | <p>so i am trying to plot a contour of this function. Code follows:</p>
<pre><code>#base packages
#import sympy as sp
#from sympy import *
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
x = np.reshape(np.array([0,0,0,0.1,0.1,0.3,0.3,0.9,0.9,0.9]),(-1,1))
y = np... | <p>You function <code>f</code> is returning a number (0D - 0-dimensional), which you are using as the third argument of a function expecting a 2D array instead at that position (probably <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.contour.html" rel="nofollow noreferrer"><code>plt.contour</code><... | python|numpy|matplotlib|plot|contour | 0 |
352,141 | 64,583,159 | Consider two consecutive words as one in Word Frequency | <p>I have this sentence:</p>
<pre><code>Sentence
Who the president of Kuala Lumpur is?
</code></pre>
<p>I am trying to extract all the words (tokenization)</p>
<pre><code>low_case = df['Sentence'].str.lower().str.cat(sep=' ')
words = nltk.tokenize.word_tokenize(low_case)
word_dist = nltk.FreqDist(words)
example = ... | <p>You could do some pre-processing and separate the bi-grams from the rest of the sentence using <a href="https://docs.python.org/3/library/re.html#match-objects" rel="nofollow noreferrer">re Match Objects</a>. For example:</p>
<pre><code>import re
# initialize sentence text
sentence_without_bigrams = 'Who the presid... | python|pandas|nltk | 0 |
352,142 | 64,599,130 | How to split one column into multiple columns with pipes acting as a separator | <p>I'm trying to split the content below into multiple columns, separated by | or multiple pipes. For example, what you see below should have split into 8 columns.</p>
<blockquote>
<p>By the end of the week, you will have the opportunity to: | | Explain
the accrual basis of accounting and the reasons for adjusting entr... | <p>You can use regular expression pattern:</p>
<pre><code>df['col'].str.split('( ?\| ?)+')
</code></pre> | python|pandas|dataframe|strsplit | 0 |
352,143 | 64,352,830 | Python pandas trying to make word count | <p>Hi I just noticed the tweepy api, I can create dataframe with pandas using tweets object which fetched from tweepy. I want to make a word count df to my tweets. here's my code</p>
<pre><code>freq_df = hastag_tweets_df["Tweet"].apply(lambda x: pd.value_counts(x.split(" "))).sum(axis =0).sort_value... | <p>Use can use spaCy library to do it. With this library you can easily remove words like "the","a" known as stop words:</p>
<p>its easy to install : <code>pip install spacy</code></p>
<pre><code>import spacy
from spacy.lang.en.stop_words import STOP_WORDS
nlp = spacy.load("en_core_web_sm"... | python|pandas | 0 |
352,144 | 64,582,124 | Appending only rows that are not yet in a pandas dataframe | <p>I have the same dataset but over different weeks (so later weeks contain new rows). I want to append the new rows to the original dataframe to create one big dataframe with all unique rows and no duplicates. I can't just take the last week because some get deleted over the weeks.</p>
<p>I tried to use the following ... | <p>if I understand your question, you are just trying to add the unique rows from one dataframe to another dataframe. I don't think there is any need to iterate through the keys like you are doing. There is an example on this question that I think can help you and i think it is conceptually easier to follow <a href="ht... | python|pandas|dataframe | 1 |
352,145 | 64,362,969 | Tensorflow 2.3.x cudnn failure Windows 10 CUDA 10.1 CUDNN 7.6.5 Anaconda3 | <p>Running TensorFlow 2.3.x and then stopping and then running it again seems to cause Tensorflow to fail to initialize cudnn. This stopping and starting is unavoidable when fine tuning and debugging pre and post processing. Every time cudnn fails I have to restart my computer. This failure seems to have a 50% probabil... | <p>After days of debugging I have found that the issue isn't with CUDA, CUDNN, TensorFlow, Python, Anaconda but is actually Windows 10.</p>
<p>I had mistakenly joined the Windows Insider program in order to get a Linux Virtual machine working in Windows. That worked but then TensorFlow stopped working properly in Windo... | windows|tensorflow|installation|gpu | 0 |
352,146 | 64,344,245 | Fast way to remove array of specific row values from 2D numpy array | <p>I have a 2D array like this:</p>
<pre><code>a = np.array([[25, 83, 18, 71],
[75, 7, 0, 85],
[25, 83, 18, 71],
[25, 83, 18, 71],
[75, 48, 8, 43],
[ 7, 47, 96, 94],
[ 7, 47, 96, 94],
[56, 75, 50, 0],
[19, 49, 92, 57],
[52, 93, 58, 9]])
</code></pre>
<... | <p>Here's a <strong>pandas</strong> approach doing a "anti join" using <code>merge</code> and <code>query</code>.</p>
<pre><code>dfa = pd.DataFrame(a)
dfb = pd.DataFrame(b)
df = (
dfa.merge(dfb, how='left', indicator=True)
.query('_merge == "left_only"')
.drop(columns='_merge')
)
0... | python|arrays|pandas|numpy | 7 |
352,147 | 64,611,957 | AssertionError: would build wheel with unsupported tag ('cp310', 'cp310', 'linux_x86_64') | <p>I've got this message when I try to install numpy using Python 3.10.</p>
<p>How to fix this?</p>
<pre><code> Copying numpy.egg-info to build/bdist.linux-x86_64/wheel/numpy-1.19.3-py3.10.egg-info
running install_scripts
Traceback (most recent call last):
File "/home/walenty/.local/lib/python3.10/site-pa... | <p>It's a bug in python 3.10, a workaround is installing numpy with the <code>--no-use-pep517</code> flag. E.g.: <code>pip3.10 install numpy --no-use-pep517</code></p>
<p>There's a fix for this on the way though, so just waiting is an option as well.</p> | python|numpy | 3 |
352,148 | 64,179,262 | Can't eliminate pandas SettingWithCopyWarning | <p>I tried many times, but I couldn´t avoid this warning in my code, when inserting the 'multiplier' column on 'ipcaMomSlice'. Any idea?</p>
<pre><code>import pandas as pd
ipcaMom = bcbQuery(433)
ipcaMom['valor'] /= 100
initDate = "1995-01-01"
ipcaMomSlice = ipcaMom[initDate:]
ipcaMomSlice.loc[:,'multipli... | <p>If you want this <code>ipcaMomSlice</code> to be it's own entity, and not refer back to <code>ipcaMom</code> (e.g. you don't want to assign a "multiplier" column to <code>ipcaMom</code> at all, and only want the "multiplier" on <code>ipcaMomSlice</code>) you'll need to tell pandas that <code>ipca... | python|pandas | 1 |
352,149 | 64,509,717 | Neural Network doesn't work for multiple data samples | <p>When I train my neural network on only one training sample my code works just fine but when I train on any more it doesn't work at all. Does anyone have a clue as to why? I'm pretty sure somethings wrong with the update_mini_batch function but I have no idea. By the way, this is my first neural network and I'm doing... | <p>so I've found the problem but I don't know how to fix it. apparently, my neural network can eventually get it right but it takes a couple thousand epochs of training. this is because the return backpropagation gradient always has zeros in the first bias and weight layer. I believe this is an error in the indexing bu... | python|numpy|neural-network|gradient-descent | 0 |
352,150 | 64,605,596 | Simple way of performing Matrix Factorization with tensorflow 2 | <p>I've been searching on how to perform matrix factorization for this very simple and basic case that I will show, but didn't find anything. I only found complex and long solutions, so I will present what I want to solve:</p>
<pre><code>U x V = A
</code></pre>
<p>I would just like to know how to solve this equation in... | <p>A naive and straightforward approach using TensorFlow 2:</p>
<p>Note that rating was converted to float32. TensorFlow cannot calculate gradients over integer, see <a href="https://github.com/tensorflow/tensorflow/issues/20524" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/20524</a>.</p>
<... | python|tensorflow|tensorflow2.0|recommendation-engine|matrix-factorization | 2 |
352,151 | 64,539,158 | OSError: Traceback (most recent call last) | <p>I'm getting this error as an <strong>UnknownError</strong> with the data augmentation function for a CNN I developed using Keras and Tensorflow as mentioned below.</p>
<pre><code>testGenerator = ImageDataGenerator(
rescale = 1./255.0,
rotation_range = 45,
horizontal_flip = True,
vertical_flip = True,... | <p>Looks like batch_size hasn't been defined yet. Try defining batch size, or using a #.</p> | python|tensorflow|keras|tensorflow2.0|tf.keras | 0 |
352,152 | 64,519,741 | Pandas - convert value as type string to float | <p>In my df I have some values set up as <code>dtype(str)</code></p>
<pre><code> x
27:47
13:45
10:45
</code></pre>
<p>And I would like to convert them to <code>float</code>, ending up with:</p>
<pre><code> x
27.47
13.45
10.45
</code></pre>
<hr />
<p>How do I do this?</p> | <p>In your case, you can do:</p>
<pre><code>df['x'] = df['x'].str.replace(':','.').astype(float)
</code></pre>
<p>Output:</p>
<pre><code> x
0 27.47
1 13.45
2 10.45
</code></pre> | python|pandas|string|datetime | 1 |
352,153 | 64,529,174 | Create a column removing unwanted parts of strings based on condition | <p>I'm new to python and I'm stuck here. I have a dataframe like the one below and I'm trying to create a new column with only the macro genres of the Genres column.</p>
<p>Dataframe:</p>
<pre><code>import pandas as pd
d = {'Genres': ['Finance', 'Arcade', 'Business', 'Photography', 'Entertainment;Brain Games', 'Medical... | <p>You can just use <code>str.split(';')</code>. If <code>;</code> is not present in string, nothing happens -> the list with original string is returned (so you can always use <code>[0]</code>):</p>
<pre><code>df['macro_genres'] = df['Genres'].apply(lambda x: x.split(';')[0])
print(df)
</code></pre>
<p>Prints:</p>
... | python|pandas|loops|split | 1 |
352,154 | 64,440,961 | Python, Indexing and assigning to Np Array | <p>To improve the speed I would like to avoid forloops.
I have a image array looking like :
<code>image = np.zeros_like(np.zeros(shape=(480,640,1)),dtype=np.uint8)</code>
and a typed np array <code>Events</code> with the following types
<code>dtype = [('x', '<f8'),('y', '<f8'),('grayVal','<u2')</code>
where 'x... | <p>Let's work with a small example, one we can actually examine and play with!</p>
<p>Make a structured array:</p>
<pre><code>In [32]: dt = np.dtype([('x', int),('y', int) ,('grayVal','u2')])
In [33]: events = np.zeros(5, dt)
In [34]: events['x'] = np.arange(5)
In [35]: events['y'] = np.array([3,4,0,2,1])
In [36]: even... | python|arrays|numpy | 1 |
352,155 | 64,549,386 | Question about deserializing some numbers (bug??) | <p>In order to deserialize bytes object, we use pickle.loads()</p>
<pre><code>import pickle
import numpy as np
pickle.loads(np.float64(0.34103))
</code></pre>
<p>and the expected result is like below (because np.float64(0.34103) is not bytes objects, appropriate errors are expected)</p>
<pre><code>---------------------... | <p><code>pickle.loads</code>'s input isn't quite restricted to be a <code>bytes</code> object. Quoting the <a href="https://docs.python.org/3/library/pickle.html#pickle.loads" rel="nofollow noreferrer">docs</a>,</p>
<blockquote>
<p>Return the reconstituted object hierarchy of the pickled representation <em>data</em> of... | python|numpy|pickle | 2 |
352,156 | 64,464,482 | How groupby unique value ? Python Pandas | <p>I would like to groupby this dataframe with unique values for priority and Alias column to create a latex report:</p>
<pre><code>Alias Number Duration(h) priority
A 23834 8111.130497 120
B 16453 6773.243598 120
C 15988 8347.042753 120
A 1... | <p>Your data are already grouped by priority and alias because every combination of values for this 2 columns is unique at your dataset. It's just a matter of visualize it better and i think the <code>set_index()</code> above recommended is the correct answer.
You can also bring priority column in front of alias.</p> | python|pandas|pandas-groupby | 0 |
352,157 | 64,469,257 | How to turn ordinal rankings to integer score? | <p>I am new to code and this may be a straightforward fix –</p>
<p>I have 3 columns in a dataset:</p>
<pre><code>age_bridges.Deck_rating
age_bridges.Supstr_rating
age_bridges.Substr_rating
</code></pre>
<p>and the ratings are ordinal from failed, failing, ... good, excellent</p>
<p>I want to assign an integer of 1-6 fr... | <p>There's 2 large approaches you can take for this:</p>
<ul>
<li>Use <code>.map</code> to transform your column values into a numerical representation</li>
<li>Change your columns into a pd.Categorical Series</li>
</ul>
<p>Set up data:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(0)
ordered_ra... | pandas|dataframe | 0 |
352,158 | 64,357,491 | load txt with datetime | <p>Good morning,
I'm really new to python, I'm trying to load datatime into python. I have found various options but none correctly respond to the problem.
I see this code but it's not workin obviously, "since strptime () takes exactly 2 arguments (1 given)"</p>
<pre><code>from datetime import datetime
data20... | <p>Try:</p>
<pre><code>from datetime import datetime
data2012 = np.loadtxt("try.txt", converters={0:lambda t: datetime.strptime(t.decode(), '%m-%d-%Y %H:%M')}, delimiter=','
, dtype={
'names': ('time', 'col1', 'col2', 'col3',),
'for... | python|numpy|datetime | 0 |
352,159 | 64,524,251 | 'wrap around' when slicing in python/numpy | <p>I have a NumPy array</p>
<pre><code>import numpy as np
a = np.array([10, 20, 30, 40])
</code></pre>
<p>and I'd like to slice it in such a way, that the entire array is returned, with the first element appended to the end, so <code>array([10, 20, 30, 40, 10])</code>, or (as a normal list) <code>[10, 20, 30, 40, 10]</... | <pre><code>>>> a = np.array([10, 20, 30, 40])
>>> np.take(a, np.arange(5), mode='wrap')
array([10, 20, 30, 40, 10])
</code></pre> | python|arrays|numpy | 2 |
352,160 | 64,444,906 | Numpy array - stack multiple columns at the end of an array as rows using reshape | <p>I want to stack <code>n</code> number of columns as new rows at the end of the array. I was trying to do it with reshape but I couldn't make it. For example given the table</p>
<pre><code>table = np.array([[11,12,13,14,15,16],
[21,22,23,24,25,26],
[31,32,33,34,35,36],
... | <p>OP offers a solution:</p>
<pre><code>np.concatenate(np.split(table, table.shape[1]/n, axis=1), axis=0)
</code></pre>
<p>It appears to be inefficient because <code>np.split</code> forces to change data to list of arrays and then iterate it within outer argument. More over <code>np.concatenate</code> is not that effic... | python|numpy|reshape | 1 |
352,161 | 64,239,416 | IndexError: index 6842 is out of bounds for axis 0 with size 6842 | <p>I know this probably is a pretty dumb error but I'm stuck with this. I need to 1-hot encode an array with numpy:</p>
<p>numpy.<strong>version</strong> ==> 1.18.5</p>
<pre><code>print(array)
[[ 3 1275 10 ... 1 2235 1]
[ 0 0 0 ... 2 139 151]
[1277 1278 1 ... 2239 831 1]
...
[ 2 6... | <p>For me this was the solution:</p>
<pre><code>np.eye(array_classes + 1)[array]
</code></pre>
<p>Because I need the last index of my array to be the number of classes so I have to add +1 to <code>np.eye()</code></p> | python|arrays|numpy|encoding | 0 |
352,162 | 47,544,804 | Pandas dtypes dictionary from yaml | <p>I am having an issue where I want to load a section from a YAML file to populate the pandas.read_csv dtypes parameter. My problem is that the value in the dictionary has ' ' around it and pandas is not recognizing it as a datatype.</p>
<pre><code>Yaml:
dict: {ITEM_GROUP: object, ITEM: object}
import pandas as p... | <p>This works for me. Your problem seems to be the parameter <code>dtypes</code> in <code>pd.read_csv</code> which should be <code>dtype</code>:</p>
<hr>
<pre><code>import yaml
from io import StringIO
config = yaml.load(StringIO("""
Yaml:
dict: {ITEM_GROUP: object, ITEM: object}
"""))
config['Yaml']['dict']
# {'I... | python|pandas|dictionary|yaml | 1 |
352,163 | 47,694,542 | Building my own tf.Estimator, how did model_params overwrite model_dir? RuntimeWarning? | <p>Recently I built a customized deep neural net model using TFLearn, which claims to bring deep learning to the scikit-learn estimator API. I could train models and make predictions, but I couldn't get the scoring (evaluate) function to work, so I couldn't do cross-validation. I tried to ask questions about TFLearn ... | <p>Simply because you're feeding your <code>model_param</code> as a <code>model_dir</code> when you construct your <code>Estimator</code>.</p>
<p>From the <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator" rel="nofollow noreferrer">tensorflow documentation</a> : </p>
<p><strong>Estimator <cod... | python-3.x|tensorflow|tensorflow-estimator | 2 |
352,164 | 47,876,663 | pandas divide two multi index series | <p>I have a multi-index series that looks like</p>
<pre><code> value
foo bar baz
1 A C 6
D 2
B D 6
F 4
2 B C 5
F 7
</code></pre>
<p>I would like to sum on foo and bar, to get the sum of values for each foo, bar, regardless of baz, which I c... | <p>You could do it like this using <code>transform</code> to get sum with like indexes of oringal dataframe then use <code>div</code> with Pandas intrinsic data alignment:</p>
<pre><code>df.div(df.groupby(['foo','bar']).transform('sum'))
</code></pre>
<p>Output:</p>
<pre><code> value
foo bar baz ... | python|pandas|group-by | 12 |
352,165 | 47,837,733 | splitting text into many columns | <p>I have the following dataframe, and i want to split the column <code>activities</code> into other columns spliting the text by "," into my dataframe</p>
<pre><code>id activities
1 541,589,235,45
2 213,213
3 458,88,999,150,360
</code></pre>
<p>I am using <code>df= df['activities'].str.split(',',5,expand=True... | <p>You're on the right track. Once you split, you can either </p>
<ul>
<li>assign <code>id</code> back, or</li>
<li><code>concat</code> the two pieces</li>
</ul>
<pre><code>i = df.activities.str.split(',', expand=True).add_prefix('activity_')
i
activity_0 activity_1 activity_2 activity_3 activity_4
0 541 ... | python|string|pandas|split | 4 |
352,166 | 47,702,750 | MemoryError from sklearn.metrics.silhouette_samples | <p>I get a memory error when trying to call <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.silhouette_samples.html" rel="nofollow noreferrer">sklearn.metrics.silhouette_samples</a>. My use case is identical to this <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silh... | <p>Update: <a href="https://github.com/scikit-learn/scikit-learn/pull/11135" rel="nofollow noreferrer">PR 11135</a> should resolve this issue within scikit-learn, making the rest of the post obsolete. </p>
<hr>
<p>You have about 100000 = 1e5 samples, which are points in 12-dimensional space. The <code>pairwise_distan... | python|numpy|scikit-learn|out-of-memory|cluster-analysis | 7 |
352,167 | 47,703,250 | Remove rows having same value in all columns | <p>I have a pandas dataframe that I'm trying to drop rows based on all columns having exact same value. Here's an example to help understand the idea.</p>
<p>Input: </p>
<pre><code>index A B C D E F ....
0 1 2 3 1 3 4
1 2 2 2 2 2 2
2 5 5 5 5 5 5
3 7 7 6 7 7 7
</code></pr... | <p>An efficient way of doing this with numeric DataFrames is to use the standard deviation (which will be 0 only if all values are the same):</p>
<pre><code>df[df.std(axis=1) > 0]
Out:
A B C D E F
0 1 2 3 1 3 4
3 7 7 6 7 7 7
</code></pre>
<p>Timings with 40k rows:</p>
<pre><code>%timeit df[df... | python|pandas|dataframe | 8 |
352,168 | 47,779,130 | ValueError for tf.contrib.learn.KMeansClustering with predefined inital_clusters | <p>I tried to use predefined inital_centers for tensorflow's KMeansClustering. (In sklearn, it is very simple with "KMeans(n_clusters=K, init=init)")</p>
<pre><code>import tensorflow as tf
import numpy as np
K=5
X = np.random.random((100,1))
m1 = min(X)
m2 = max(X)
init_c = np.linspace(m1[0], m2[0], num=K).reshape(... | <p>Make sure that the <code>numpy</code> array uses the same data type <code>float32</code> as expected from tensorflow</p>
<p><code>init_c = np.asarray(init_c, dtype=np.float32)</code></p>
<p>and for some reason you need to set</p>
<p><code>use_mini_batch=False</code></p> | python|tensorflow|k-means | 0 |
352,169 | 47,625,257 | Key error when trying to vlookup pandas | <p>I am trying to vlookup values of EW against AD. </p>
<p>Dataframe 1</p>
<pre><code> EW
0 A
1 BC
</code></pre>
<p>Dataframe 2</p>
<pre><code> AD
0 A
1 B
2 BC
</code></pre>
<p>Then I run:</p>
<pre><code>df3 = df1.insert(0, 'AD', df1['EW'].map(df2.set_index('EW')['AD... | <p>Your code error, come from the df2 do not have the columns name 'EW'</p>
<p>I will recommend using <code>isin</code> + <code>np.where</code></p>
<pre><code>df2.AD=np.where(df2.AD.isin(df1.EW),df2.AD,np.nan)
df2
Out[193]:
AD
0 A
1 NaN
2 BC
</code></pre> | python|python-3.x|pandas | 1 |
352,170 | 47,906,209 | Merge two plots into one with logarithmic scale - different data frames pandas | <p>I would like to combine next two plots into one plot on a logarithmic scale. </p>
<pre><code>df1.plot(x = 'Interval', y = 'Trend')
plt.yscale("log")
plt.show()
df2.plot(x = 'Value', y = 'Reliability')
plt.yscale("log")
plt.show()
</code></pre>
<p>How to merge these two plots? </p> | <p>According to the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow noreferrer">documentation</a> you can pass in the axes you want to plot to. Therefore, your code would become:</p>
<pre><code>fig, ax = plt.subplots()
df1.plot(x = 'Interval', y = 'Trend', ax=... | python|pandas|dataframe|matplotlib|subplot | 0 |
352,171 | 47,562,634 | Converting numpy datetime64 to long integer and back | <p>How to convert NumPy datetime64 to a long ineteger and back?</p>
<pre><code>import numpy as np
import datetime
np.datetime64(datetime.datetime.now()).astype(long)
</code></pre>
<p>Gives a value of 1511975032478959</p>
<pre><code>np.datetime64(np.datetime64(datetime.datetime.now()).astype(long))
</code></pre>
<p... | <p>You need to specify the units of the long int (in this case, microseconds).</p>
<pre><code> np.datetime64(np.datetime64(datetime.datetime.now()).astype(long), 'us')
</code></pre>
<p>returns</p>
<pre><code> numpy.datetime64('2017-11-29T17:11:44.638713')
</code></pre> | python|numpy|datetime | 7 |
352,172 | 47,804,792 | Distributed Tensorflow: ps/workers hosts on aws ? | <p>I am using distributed Tensorflow on aws using gpus. When I train the model on my local machine, I indicate ps_host/workers_host as something like 'localhost:2225'. What are the ps/workers host I need to use in case of aws? </p> | <p>here's a good github project showing how to use Distributed TensorFlow on AWS with Kubernetes or the new AWS SageMaker: <a href="https://github.com/pipelineai/pipeline" rel="nofollow noreferrer">https://github.com/pipelineai/pipeline</a></p>
<p>at minimum, you should be using the TensorFlow Estimator API. there a... | python|tensorflow | 2 |
352,173 | 47,921,268 | How to add layers before the input layer of model restored from a .pb file? | <p>I have a .pb model file and I can get the input tensor and output tensor by get_tensor_by_name and then use the input and output tensor to create a saved model which can then be served in tensorflow model server. But currently, the input tensor is images in 3D array format, and I want to add one more layer to decode... | <p>You can add those layers by editing the file export_inference_graph here <em><a href="https://github.com/tensorflow/models/blob/master/research/slim/export_inference_graph.py#L114-L116" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/slim/export_inference_graph.py#L114-L116</a>.</... | tensorflow|tensorflow-serving | 1 |
352,174 | 47,949,244 | Keras - throwing error that my input shape is 3 dimensional, when it is not | <p>My program takes in a CSV file where the first 6 rows are the inputs.</p>
<p>When defining the input I am using:</p>
<pre><code>inputs = Input(shape=(2697, 6))
</code></pre>
<p>Where 2697 is the batch size and 6 is the input size. I know that <code>Input(shape=(batch-size, input-size))</code> is correct.</p>
<p>... | <p>From <code>Input</code> documentation:</p>
<blockquote>
<p><strong>Arguments</strong> </p>
<ul>
<li><p>shape: A shape tuple (integer), <strong>not including the batch size</strong>.
For instance, <code>shape=(32,)</code> indicates that the expected input
will be batches of 32-dimensional vectors. </p><... | tensorflow|machine-learning|neural-network|keras|theano | 3 |
352,175 | 47,762,055 | Tensorflow: how should I reshape a row placeholder to a column placeholder | <p>I want to convert a row placeholder, e.g., <code>[1, 2]</code>, to a column placeholder, e.g., <code>[[1], [2]]</code></p>
<pre><code>y = tf.placeholder(tf.int32, shape=[None], name='target')
y = tf.reshape(y, (y.shape[0], 1))
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
p... | <p>I'm not sure if you meant it, but you <em>can't</em> change the shape of a node in tensorflow in runtime. So as <code>target</code> is defined as <code>[?]</code> placeholder, it'll remain so.</p>
<p>What you can do instead is convert it to a new tensor (which won't be a placeholder!) using <code>tf.expand_dims</co... | python|multidimensional-array|tensorflow | 0 |
352,176 | 47,679,870 | How to Use vectorize or Apply instead of iterrows on pandas dataframe in python | <p>I have 2000+ dataframes with two columns. I want to ngrams for on the columns and then create a new dataframe with ngrams. Here is my code. Its working fine. Just taking a lot of time. </p>
<p>I am currently using itterows to iterate through each row of each dataframe in each file. Is there an easier way to do this... | <pre><code># pylint: disable=I0011
# pylint: disable=C0111
# pylint: disable=C0301
# pylint: disable=C0103
# pylint: disable=W0612
# pylint: disable=W0611
import logging
import os
from os import listdir
from os.path import isfile, join
import math
import pickle
import itertools
import multiprocessing
import time
import... | python|pandas|dataframe|vectorization|apply | -1 |
352,177 | 47,969,587 | Opencv Python open dng format | <p>I can't figure out how to open a dng file in opencv.
The file was created when using the pro options of the Samsung Galaxy S7.
The images that are created when using those options are a dng file as well as a jpg of size 3024 x 4032 (I believe that is the dimensions of the dng file as well).</p>
<p>I tried using the... | <p>As far as i know it is possible that DNG files can be compressed (even though it is lossless format), so you will need to decode your dng image first. <a href="https://www.libraw.org/" rel="noreferrer">https://www.libraw.org/</a> is capable of doing that.</p>
<p>There is python wrapper for that library (<a href="ht... | python|image|numpy|opencv|type-conversion | 6 |
352,178 | 47,921,250 | Replace selected integer value with list of values with Pandas | <p>I have a pandas dataframe that has column "Survived".<br>
That column has two possible values: 1 and 0.<br>
I want to replace 1 with [1, 0] and 0 with [0, 1].</p>
<p>These are the ways I have tried to do it:</p>
<p>First convert column data type from int to object:</p>
<pre><code>data["Survived"] = data["Survived... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with broadcasting:</p>
<pre><code>data["Survived"] = np.where((data["Survived"] == 1)[:, None], [1,0],[0,1]).tolist()
</code></pre> | python|pandas | 5 |
352,179 | 47,630,600 | DataFrame by especific columns in Python pandas to a JSON response? | <p>I can't figure out how to generate this output:</p>
<pre><code> "name" "hp" "hpperlevel"
"1" Annie 524 88
"2" Olaf 597.24 93
</code></pre>
<p>With this:</p>
<pre><code>{
"type": "champion",
"version": "7.24.1",
"data": {
"1": {
"title": "the Dark Chi... | <p>You can create a single dataframe with a couple of list comprehensions passed to the dataframe constructor:</p>
<pre><code>import pandas
def get_stats(data):
return (data['id'], data['name'], data['stats']['hp'], data['stats']['hpperlevel'])
response = {
"data": {
"1": {
"stats": {"hp"... | python|pandas | 0 |
352,180 | 47,683,705 | How to read pickle files without taking up a lot of memory | <p>Currently I have a loop that contains:</p>
<pre><code>df = pandas.read_pickle(filepath)
</code></pre>
<p>the files are ~ 100 mb. However since it is looping through these many times, it is taking up a lot of memory and then eventually I get a memory error. Is there a way to do this where I can close the file once ... | <pre><code>del df
gc.collect()
</code></pre>
<p>Erase reference, and garbage colector.</p>
<p>Edit, this erase your dataframe from memory, you can not close the file, take the info and dont use ram.</p> | python|pandas|pickle | 1 |
352,181 | 47,661,149 | ValueError: Found input variables with inconsistent numbers of samples: [100, 7] | <p>Currently trying to have the program guess the animal based on the feature that is included in the zoo database.
When I run this code it gets the error ''ValueError: Found input variables with inconsistent numbers of samples: [100, 7]''. It shows the error happens on this line ''X_train, X_validation, Y_train, Y_va... | <p>The problem is with this part:</p>
<pre><code>X = zoodatabase_v2.loc[1:101,'hair':'catsize']
Y = zoodatabase_v2.loc[0:6,'Class_Type':'Animal_Names']
</code></pre>
<p>X is a DataFrame with length 100 (1:101), and Y is a Series with length 6. To train a model (supervised learning), you need to give target labels for... | python|pandas | 1 |
352,182 | 47,793,356 | Cannot use Pandas pct_change with date | <p>I have a data frame:</p>
<pre><code> date value
0 2017-11-30 13:58:57 901
1 2017-11-30 13:59:41 905
2 2017-11-30 13:59:41 925
</code></pre>
<p>That was generated by: </p>
<pre><code>import pandas as pd
df = pd.DataFrame.from_items( [('date', ['2017-11-30 13:58:57', '2017-11-30 13:59:41',... | <blockquote>
<p>How do I make it ignore the date column?</p>
</blockquote>
<p>Here's a solution with <code>select_dtypes</code> that should generalise to any dataframe by ignoring non-numeric columns - </p>
<pre><code>df.select_dtypes(include=['number']).pct_change()
value
0 NaN
1 0.004440
2 0.022099... | python|pandas | 2 |
352,183 | 47,704,224 | download url in txt format into pandas dataframe | <p>I am having trouble trying to download the data from this particular URL and store it in a pandas data-frame. Can anyone help with this? </p>
<pre><code>url ='http://www2.conectiv.com/cpd/tps/archives/nj/2017/12/20171205NJA1.txt'
</code></pre>
<p>I need to store each <code>Segment</code> as a row with correspondi... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer">read_csv()</a> has many useful options </p>
<ul>
<li><code>header=None</code> - and first row is not treated as headers.</li>
<li><code>sep='\s+'</code> - and it uses spaces to split columns (instead of comma <cod... | python|pandas|urllib | 8 |
352,184 | 47,891,168 | Assign values to a numpy array for each row with specified columns | <p>I have a matrix <code>foo</code> with <code>n</code> rows and <code>m</code> columns. Example:</p>
<pre><code>>>> import numpy as np
>>> foo = np.arange(6).reshape(3, 2) # n=3 and m=2 in our example
>>> print(foo)
array([[0, 1],
[2, 3],
[4, 5]])
</code></pre>
<p>I have an ... | <p>Since <code>ind</code> takes care of the first axis, you just need the indexer for the zeroth axis. You can do this pretty simply with <code>np.arange</code>: </p>
<pre><code>foo[np.arange(len(foo)), ind] = bar
foo
array([[9, 1],
[8, 3],
[4, 7]])
</code></pre> | python|arrays|numpy | 6 |
352,185 | 47,725,664 | tensorflow import causing numpy calculation errors | <p>I'm learning the basics of TensorFlow thru an example of linear regression. Performing the linear regression with scikit-learn works well:</p>
<pre><code>import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
housing = fetch_california_housing()
... | <p>The Anaconda distribution uses Intel's Math Kernel Libraries (MKL) by default which seems to result in multiple issues with Numpy and SciPy when used in conjunction with TensorFlow as reported in <a href="https://github.com/tensorflow/tensorflow/issues/11724" rel="nofollow noreferrer">this issue</a> and in other ref... | python|numpy|tensorflow|scikit-learn | 1 |
352,186 | 47,829,588 | Python Pandas extra commas | <p>im making a little work with csv and pandas and I must merge two CSV lists on one and delete the duplicates but the final output add extra commas to the last column and I don´t know why</p>
<p>I have two CSV lists like this:</p>
<pre><code> DESCRIPTION EXTRAS ADDRESS AVAILABLE
1 House WiFi CP 43... | <p>First you will merge both csv file in pandas dataframe. Then drop duplicate data from dataframe.</p>
<pre><code>import pandas as pd
df1=pd.read_csv('first.csv')
df2=pd.read_csv('second.csv')
frames = [df1, df2]
result=pd.concat(frames)
df5 = pd.DataFrame(result)
df5.drop_duplicates()
print(df5)
</code></pre> | python|pandas|csv | 1 |
352,187 | 47,765,243 | Pandas - expand nested json array within column in dataframe | <p>I have a json data (coming from mongodb) containing thousands of records (so an array/list of json object) with a structure like the below one for each object:</p>
<pre><code>{
"id":1,
"first_name":"Mead",
"last_name":"Lantaph",
"email":"mlantaph0@opensource.org",
"gender":"Male",
"ip_address":"23... | <p>I propose an interesting answer I think using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="noreferrer"><code>pandas.json_normalize</code></a>.<br>
I use it to expand the nested <code>json</code> -- maybe there is a better way, but you definitively should consid... | python|json|pandas | 14 |
352,188 | 47,950,216 | Python - Numpy speedup needed | <p>I would like to know if I can speedup this code using <strong>numpy</strong>...</p>
<p>The code is actually running but I know it's possible to do better with np.where, which I've tried but without success :)</p>
<p>For each syn position I want to compare the string on first positions ('000','001'...) with the var... | <p>looks like a <code>dictionary</code> would help</p>
<pre><code>syn=dict([['000','none'],['001',6],['010',5],['011',3],['100',4],['101',0],['110',1],['111',2]])
syn
{'000': 'none',
'001': 6,
'010': 5,
'011': 3,
'100': 4,
'101': 0,
'110': 1,
'111': 2}
syn.get('011') # .get(key) will return None if the key ... | python|numpy|hamming-code | 0 |
352,189 | 47,968,757 | How to make a customized tf.nn.conv2d() of TensorFlow? | <p>Almost same as existing conv2d(), but I would like to add a special function to it.</p>
<p>Suppose that we have a shape of 5x5 filter and a shape of 100x100 input.</p>
<p>In my understanding, conv2d() internally does:</p>
<ol>
<li>choosing a 5x5 input area from the entire input. </li>
<li>calculating convolution... | <p>Since convolution itself is linear, inserting any linear operation can be done by doing convolution via <code>tf.nn.conv2d</code> first and then that operation. </p>
<p>The <code>(max(x) + min(x)) / 2</code> on each <code>5x5</code> patch can be realized by <code>(tf.nn.max_pool(x) - tf.nn.max_pool(-x)) * 0.5</code... | python|tensorflow|neural-network|conv-neural-network|convolution | 3 |
352,190 | 47,811,757 | How to load row major data from text file in numpy | <p>How can row-major text data files be loaded with numpy?</p>
<p>The <code>loadtxt(..)</code> function loads column-major, i.e. the data lies in rows below names in the first row, how can I load data where the names are in the 1st column and data in subsequent columns?</p>
<p>Row major:</p>
<pre><code>field 1: d1, ... | <p>The parameter <code>unpack=True</code> does this. </p>
<blockquote>
<p>If True, the returned array is transposed, so that arguments may be unpacked using x, y, z = loadtxt(...). When used with a structured data-type, arrays are returned for each field. Default is False.</p>
</blockquote>
<p>This does not require... | python|numpy|scipy | 2 |
352,191 | 47,810,702 | Why can't I convert floats in an array into integers? | <p>I want to convert the elements(float) into integer, but it seems not working. </p>
<pre><code>#get an array from a matrix
pre_dataY = data[:, -1]
print(pre_dataY)
# float to integer
for i in range(len(pre_dataY):
pre_dataY[i]=int(pre_dataY[i])
print(pre_dataY)
</code></pre>
<p>however, the output is :</p>
<... | <p>use mapping:</p>
<pre><code>print map(int, pre_dataY)
</code></pre>
<p>Mapping create a new list with your values</p> | python|numpy|integer | 0 |
352,192 | 47,933,019 | How to properly sample truncated distributions? | <p>I am trying to learn how to sample truncated distributions. To begin with I decided to try a simple example I found here <a href="https://darrenjw.wordpress.com/2012/06/04/metropolis-hastings-mcmc-when-the-proposal-and-target-have-differing-support/" rel="nofollow noreferrer">example</a></p>
<p>I didn't really unde... | <p>You say you want to learn the basic idea of sampling a truncated distribution, but your source is a blog post about
<a href="https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm" rel="noreferrer">Metropolis–Hastings algorithm</a>? Do you actually need this "method for obtaining a sequence of random s... | python|numpy|random|probability|mcmc | 9 |
352,193 | 47,564,821 | manipulate numpy arrays in a nested list | <p>I am trying to manipulate numpy arrays in a nested list.</p>
<p>I have a nested list, and in each inner list, there are several numpy arrays.</p>
<pre><code>a = [
[np.random.normal(0,1,[2,3]), np.random.normal(0,1,[4,5]), np.random.normal(0,1, [9, 10])],
[np.random.normal(0,1,[2,3]), np.random.normal(0,1,[4,5]), n... | <p>I'm not sure if this is what you want, but here's a potential solution:</p>
<pre><code>b = [np.mean(row, axis=0) for row in zip(*a)]
</code></pre>
<p><code>zip(*a)</code> rearranges the nested list into a sensible format, so <code>row</code> is the list of equally sized arrays, and <code>np.mean(row, axis=0)</code... | python|list|numpy | 2 |
352,194 | 49,035,156 | PyTorch - How to use "toPILImage" correctly | <p>I would like to know, whether I used <a href="http://pytorch.org/docs/master/torchvision/transforms.html#torchvision.transforms.ToPILImage" rel="nofollow noreferrer">toPILImage</a> from torchvision correctly. I want to use it, to see how the images look after initial image transformations are applied to the dataset.... | <p>You can use PIL image but you're not actually loading the data as you would normally.</p>
<p>Try something like this instead:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
for img,labels in train_data_loader:
# load a batch from train data
break
# this converts it from GPU to CPU and se... | python|pytorch | 8 |
352,195 | 49,262,132 | Numpy's logic functions and the "if cond is False" idiom | <p>When applying PEP8's "if cond is False" idiom proposed by PyCharm with <a href="https://docs.scipy.org/doc/numpy/reference/routines.logic.html" rel="nofollow noreferrer">numpy's logic functions</a> such as <code>np.isinf</code> or <code>np.isnan</code>, we get surprising behaviors.</p>
<pre><code>>>> impor... | <p>The problem is that numpy's logic functions do not return a <code>bool</code>, but an instance of <code>numpy.bool_</code>, which is a different type. Thus,</p>
<pre><code>>>> np.bool_(False) is False
False
</code></pre>
<p>One could think of using the <code>dtype</code> argument of those functions to for... | python|numpy|pycharm | 3 |
352,196 | 49,212,264 | Pandas IF test to create new column | <p>any idea how i can create a column C based on the test of 3 columns in a dataframe?</p>
<p>so far i have</p>
<pre><code>df.loc[df['Negative'] > df['Neutral'] and df['Negative'] > df['Positive'],
'C'] = 'Bad'
</code></pre>
<p>this gives me</p>
<p>ValueError: The truth value of a Series is ambiguous</p> | <p>Add <code>()</code> and instead <code>and</code> use bitwise and - <code>&</code>:</p>
<pre><code>df.loc[(df['Negative'] > df['Neutral']) & (df['Negative'] > df['Positive']), 'C'] = 'Bad'
</code></pre>
<p>Also if need <code>if-else</code> use <a href="https://docs.scipy.org/doc/numpy/reference/genera... | python-3.x|pandas | 1 |
352,197 | 48,896,964 | Select sublist where each element has a 1.5% chance to be included | <pre><code> tmp = []
while len(tmp) == 0:
for i in range(0,385):
# Multiplying by 100 in order to remove the decimal point
if randint(0,10000) < chance*100:
tmp.append(i)
return tmp
</code></pre>
<p>This is the code I'm currently using to help clear ... | <pre><code>import numpy as np
n = 385
chance = 0.015 # Chance of 1.5%
main_list = np.arange(n) # Generate initial list
rnd = np.random.uniform(size=main_list.shape) # Generate random number between 0 and 1
sublist = main_list[rnd < chance] # Select numbers
</code></pre> | python|arrays|numpy|random|sublist | 1 |
352,198 | 49,325,236 | Pandas remove/filter time series data | <p>If I have a lot of time series data, is it possible to remove any rows in the dataframe if its not on a 0, 15, 30, 45, minute time stamp? </p>
<p>For example I can make up some data on 5 minute intervals...</p>
<pre><code>import pandas as pd
import numpy as np
time = pd.date_range('6/28/2013', periods=2000, freq=... | <p>You can using <code>isin</code> </p>
<pre><code>data[data.index.minute.isin([0,15,30,45])]
</code></pre> | python|pandas|time-series | 3 |
352,199 | 49,218,349 | pandas plot distinct values of a column after groupby on another column | <p>I want to plot 2 line charts on the graph, with x-axis being month and y-axis being the count for each city for each month.</p>
<p>I do a group by on the month to get the count for each city.</p>
<p>my df:</p>
<pre><code>city month
A 1
A 2
A 2
B 2
B 3
C 3
df['city'].groupby(df['month'... | <p>I believe you need <code>groupby</code> with <code>size</code> for count and reshape by <code>unstack</code>, last filter columns (cities) by <code>subset</code>:</p>
<pre><code>df.groupby(['month', 'city']).size().unstack(fill_value=0)[['A','B']].plot()
</code></pre>
<p>Similar:</p>
<pre><code>pd.crosstab(df['mo... | python|pandas|matplotlib | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.