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,400 | 52,865,504 | remove extra characters in all data points in a dataframe | <p>I have a dataframe that has field names placed in every field:</p>
<pre><code> index name ngram field slop
0 index=1 name=unknown ngram=00 field=body slop=0
1 index=2 name=unknown ngram=01 field=body slop=0
2 index=3 name=unknown ngram=02 field=body slop=0
... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>pd.DataFrame.apply</code></a>:</p>
<pre><code>df = df.apply(lambda x: x.str.split('=').str[-1])
print(df)
index name ngram field slop
0 1 unknown 00 body 0
1 ... | python|pandas|performance|dataframe | 3 |
371,401 | 52,524,590 | Appending Rows to a data frame | <p>I am stuck on a simple task. I want to create an empty DataFrame and append rows to it based on a query of another dataset. I have tried the answers here but I am missing something ..beginner Pythoner. Any help would be appreciated. I want to take the top 3 rows of each state and add them into a new dataframe for p... | <p>I think I know what course you're doing, I had a great time with that a year ago, keep it up! </p>
<p>The simplest/fastest way I've found to concatenate a bunch of sliced dataframes is to append each df to a list, then at the end just concatenate that list. See the working code below (it does what I interpret you m... | python|pandas | 1 |
371,402 | 52,735,231 | How to select all non-black pixels in a NumPy array? | <p>I am trying to get a list of an image's pixels that are different from a specific color using NumPy.</p>
<p>For example, while processig the following image: </p>
<p><a href="https://i.stack.imgur.com/08gNN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/08gNN.png" alt="enter image description here"></a>... | <p>You should use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html" rel="noreferrer"><code>np.any</code></a> instead of <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html" rel="noreferrer"><code>np.all</code></a> for the second case of selecting all but black pixels... | python|image|numpy|image-processing | 33 |
371,403 | 52,486,670 | group by a topic and collapse a column of strings into respective categories | <p>Given:</p>
<pre><code>import pandas as pd
lis1= ('baseball', 'basketball', 'baseball', 'hockey', 'hockey', 'basketball')
lis2= ('I had lots of fun', 'This was the most boring sport', "I hit the ball hard", 'the puck went too fast', 'I scored a goal', 'the basket was broken')
pd.DataFrame({'topic':lis1, 'review':l... | <p>Use <code>groupby</code> and aggregate the strings via <code>str.join</code>:</p>
<pre><code>df.groupby('topic', as_index=False).agg({'review' : ', '.join})
topic review
0 baseball I had lots of fun, I hit the ball hard
1 basketball This was the ... | python|pandas|dataframe|nlp | 2 |
371,404 | 52,792,550 | Calculating 5 year rolling returns | <p>I have the below code which has returns for U.S. stocks over the period Jan 1995 to Dec 2000. I wish to calculate the return for Jan 2001 using a 60-month rolling return in Python. As there is 5 years of returns, how is this possible?</p>
<p>I would like to calculate this for each stock over the time period Jan 200... | <p>You can use <code>.rolling()</code> to create the subset for the 60 month rolling return</p>
<pre><code>returns_5year=table.rolling(250*6).pct_change()
</code></pre>
<p>And if you want yearly returns, use 'asfreq('BA')`</p>
<pre><code>returns_yearly = table.asfreq('BA').pct_change()
</code></pre> | python|pandas|finance|quandl|economics | 2 |
371,405 | 52,792,232 | Dataframe multiplication with multiple index | <p>Data: <a href="https://www.dropbox.com/s/5h03ibrju3ilbig/01EconMod_EU1.xlsx?dl=0" rel="nofollow noreferrer">Here</a></p>
<p>Question:
I have several data sheets which I export to Python as dataframes. I want to perform multiplications across these dataframes, which will generate another dataframe that takes the sam... | <p>pardon me if I misunderstood you because I am unable to comment before posting answer: </p>
<p>Well, if they are all the same length, and have the same index, you can start off by first concatenation them along the 0 axis. This will create a larger dataframe. Next, you can assert a conditional column or columns tha... | python|pandas|numpy|dataframe | 0 |
371,406 | 52,712,578 | pandas isin based on a single row | <p>Now I have:</p>
<pre><code>ss dd list
A B [B,E,F]
C E [C,H,E]
A C [A,D,E]
</code></pre>
<p>I want to rule out rows that both ss and dd are in list. So we rule out row 2. Function isin() checks if ss and dd are in all rows of list each time, which is not giving me the result.</p>
<p>P... | <p>First we flatten your <code>list</code> column to a dataframe and using <code>isin</code>(here <code>index</code> is do matter , that is why I using original dataframe <code>index</code> to create the <code>cdf</code>)</p>
<pre><code>cdf=pd.DataFrame(df['list'].tolist(),index=df.index)
mask=(cdf.isin(df.ss).any(1))... | pandas | 1 |
371,407 | 52,896,868 | Python / Pandas parse string to date and time | <p>I have a dataframe with a column containing strings that represent date and time like this:</p>
<pre><code>0 Fri Oct 19 17:42:31 2018
1 Fri Oct 19 17:42:31 2018
2 Fri Oct 19 17:42:31 2018
3 Fri Oct 19 17:42:31 2018
4 Fri Oct 19 17:42:31 2018
</code></pre>
<p>How can I parse the strings to get the ti... | <p>Just use <code>pd.to_datetime()</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018']],
columns=['Date'])
df['Date'] = pd.to_datetime(df['Date'])
</code></p... | python-3.x|pandas|datetime | 4 |
371,408 | 52,602,335 | Pandas count specific values in groupby results | <p>I just learned how to group a Pandas DataFrame with datetime index by dates. How can I count the number of specific values ('Passed' or 'Failed') on each day that is returned by the groupby?</p>
<p>My goal is to calculate daily yield: yield = passed_count/(passed_count + failed_count).</p>
<pre><code>import pandas... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.value_counts.html" rel="nofollow noreferre... | python|pandas | 1 |
371,409 | 52,640,007 | Conditional String Split based on another column str Python | <p>Hi guys is there a clean way to organize this data into its correct columns to geolocate it later?</p>
<pre><code> import pandas as pd
coordinates = {'event': ['1', '2', '3', '4'],
'direction': ['E', 'E,N', 'N,E', 'N'],
'location': ['316904', '314798,5812040', '5811316,314766', '5811309']}
df = pd.Data... | <p>Solution 1:</p>
<p>First <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> columns to new ones and then swap values by boolean mask created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.... | python|regex|string|pandas | 3 |
371,410 | 52,676,813 | Groupby greater than in Pandas very slow | <p>I have the table below as a pandas dataframe. I need count of all <code>Part Number</code> where <code>Net Sales</code> is greater than <code>Recommended Price</code> for a given part.</p>
<p><strong>Input: above_master</strong></p>
<pre><code> Short Number Net Sales Part Number Recommended Price
0 MU... | <p>Using <code>loc</code> with <code>size</code>:</p>
<pre><code>df.loc[df['Recommended Price'].lt(df['Net Sales'])].groupby('Part Number').size()
</code></pre>
<p></p>
<pre><code>Part Number
MU1609 1
MU2146 3
dtype: int64
</code></pre> | python|pandas | 4 |
371,411 | 52,510,737 | Online LSTM classification model giving very high number of wrong predictions | <p>I am trying to implement an online classification model using the 20 news groups data-set to classify the posts into relevant groups.</p>
<p><strong>pre-processing</strong>: I am going through all the posts and making a dictionary with the words.Then I am indexing the words starting from 1. I then iterate through a... | <p>Few things to consider -:</p>
<ol>
<li>Plot <strong>loss vs iterations</strong> graph. It should be downwards to know that your network is learning.You can use <strong>tensorboard</strong> for producing these graphs. Also produce accuracy vs iterations.</li>
<li><strong>Increase batch size</strong> from 1 to mini b... | python|tensorflow|machine-learning|lstm|text-classification | 0 |
371,412 | 52,467,033 | Conditionnally assign pixel values of one image to another | <p>I have two images ( of the same size): A and B</p>
<p><strong>A is the mask</strong>, it contains regions that have zero value and others that have RGB values. </p>
<p><strong>B is the RGB image</strong> that i want to change the values of some of its pixels to their correspondent A's pixels (pixels that have the ... | <p>If you read the images with <code>opencv</code>:</p>
<pre><code>h = b.shape[0]
w = b.shape[1]
for y in range(0, h):
for x in range(0, w):
if a[y,x] > 0:
b[y,x] = a[y,x]
</code></pre>
<p>Or better, as points @Dan Mašek in the comment</p>
<pre><code>import numpy as np
def app... | python|numpy|opencv|pixel|assign | 1 |
371,413 | 52,479,397 | ValueError: setting an array element with a sequence. on DBSCAN, no missing dimensionality | <p>I am using DBSCAN.fit() on a dataset that is actually a pandas single column with vectorized words, all the same # of dimensions, 30. It looks like this:</p>
<pre><code>df['column']
2 [-0.003417029886667123, -0.0016105849274073794...
3 [-0.24330333298729837, 0.48110865717035506, 0....
4 [-0.001701... | <p>The way you are converting your feature to array, does not convert it to an array, but to an array of lists, that is why you are seeing this error.<a href="https://i.stack.imgur.com/HksU9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HksU9.png" alt="depicted in below image"></a></p>
<p>What you... | python|pandas|valueerror|dbscan | 1 |
371,414 | 52,602,703 | Creating a new column in a data frame by mapping multiple columns in pandas | <p>I want to map one column of dataframe to another dataframe by using multiple columns.
The sample dataframes are as follow:</p>
<pre><code>df1 = pd.DataFrame()
df1['Date'] = ['2018-08-10','2018-08-10','2018-08-10','2018-08-10','2018-08-10',
'2018-08-11','2018-08-11','2018-08-11','2018-08-12','2018-08-... | <p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with left join and then set <code>0</code> by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code... | python|pandas|mapping | 1 |
371,415 | 52,769,259 | keeping null values as they are in panda dataframe columns while assigning type to them | <p>I have a panda data frame and want to import it to bigquery using to_gbq(). Some of the columns have null value and I want to keep them as they are without replacing null value to nan, None or other string. for example if I use the below line if replace null values to 0. Is there any way to keep null values while ch... | <p>Using <code>loc</code>, to only replace where <code>ViewersStart</code> is not null:</p>
<pre><code>df.loc[df.ViewersStart.notnull(),'ViewersStart'] = df.loc[df.ViewersStart.notnull(),'ViewersStart'].astype('int64')
</code></pre>
<p><strong>Example</strong>:</p>
<pre><code>df = pd.DataFrame({'ViewersStart':['1','... | python|pandas | 0 |
371,416 | 52,793,025 | Alternative to Pandas OLS | <p>I want to make trend-lines in Pandas Series.
I liked the way it was done using <code>pandas.ols</code>
What is the current best alternative for <code>pandas.ols</code> </p> | <p>Below is an example using the Linear Regression package from <a href="https://www.statsmodels.org/stable/regression.html" rel="nofollow noreferrer">StatsModels</a></p>
<p>This shows 1st, 2nd, and 3rd order polynomial fits for a randomly-generated dataset (using Ordinary Least Squares). </p>
<pre><code>import numpy... | python|pandas | 2 |
371,417 | 52,702,411 | How to set the minima and maxima in a pandas dataframe? | <p>I have the following code:</p>
<pre><code>from scipy.signal import argrelextrema
test = pd.DataFrame()
test['price'] = perf.price
test = test.dropna()
# reindex so index is int count
test.reset_index(inplace=True)
# get the peaks and valleys for the data set
peaks = argrelextrema(test.price.values, np.greater)
va... | <p>Try this:</p>
<p><strong>Example data:</strong> <code>perf = pd.DataFrame({'price':[100.1, 1.1, 3.5, 400, 3.1, 651, 39]})</code></p>
<p><strong>Added code:</strong></p>
<pre><code>test['peaks'] = False
test['valleys'] = False
test['peaks'].loc[peaks] = True
test['valleys'].loc[valleys] = True
</code></pre>
<p><s... | python|pandas | 0 |
371,418 | 52,491,442 | Pandas: drop duplicated rows with same "rounded" values without creating new columns | <p>I want to remove duplicated rows that values in column <code>B</code> and <code>C</code> after rounding them to 2 decimal places are equal</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"A":["f1", "f2", "f3", "f4"], "B":[1.2579,1.2586,1.7223,1], "C":[8.2579,8.2586,12.7223,14.0]})
A B C
0 f1... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>DataFrame.duplicated</code></a> with inverting boolean mask by <code>~</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow nor... | python|python-2.7|pandas | 0 |
371,419 | 52,820,615 | Tensorflow object detection api. Detecting 90 default classes + n new classes at a time | <p>I am using tensorflow object detection api. I was able to detect default 90 classes using pre-trained models.
I was also able to detect only custom objects (Ex: <code>macncheese</code>) by training on new dataset that has only <code>macncheese</code>. <br/>
I am having a hard time trying to combine 90 (default)+ 1(... | <p>If you want all 91 classes to be recognized, you would have to retrain on training date set which has all 91 classes. Like you did for the one macncheese. Is there any specific question beyond this you are struggling with?</p> | tensorflow|neural-network|computer-vision|conv-neural-network|object-detection-api | 0 |
371,420 | 52,672,653 | Einsum for high dimensions | <p>Considering the 3 arrays below:</p>
<pre><code>np.random.seed(0)
X = np.random.randint(10, size=(4,5))
W = np.random.randint(10, size=(3,4))
y = np.random.randint(3, size=(5,1))
</code></pre>
<p>i want to add and sum each column of the matrix X to the row of W ,given by y as index. So ,for example, if the first e... | <p>Let's simplify the problem by dropping one dimension and using values that are easy to verify manually:</p>
<pre><code>W = np.zeros(3, np.int)
y = np.array([0, 1, 1, 2, 2])
X = np.array([1, 2, 3, 4, 5])
</code></pre>
<p>Values in the vector <code>W</code> get added values from <code>X</code> by looking up with <co... | python|linear-algebra|numpy-einsum | 2 |
371,421 | 52,770,780 | Why is my Deep Q Net and Double Deep Q Net unstable? | <p>I am trying to implement DQN and DDQN(both with experience reply) to solve OpenAI AI-Gym Cartpole Environment. Both of the approaches are able to learn and solve this problem sometimes, but not always.</p>
<p>My network is simply a feed forward network(I've tried using 1 and 2 hidden layers). In DDQN I created one ... | <p>These kind of problems happen pretty often and you shouldn't give up. First, of course, you should do another one or two checks if the code is all right - try to compare your code to other implementations, see how the loss function behave etc. If you are pretty sure your code is all fine - and, as you say that model... | python|tensorflow|reinforcement-learning|q-learning | 7 |
371,422 | 52,520,812 | Pandas - replace % signs in data and put them back | <p>I have the following df: </p>
<pre><code>Name Jan_2018 Feb_2018 Mar_2018
A 33% 40% 42%
B 20% 35% 50%
C 21% 31% 12%
</code></pre>
<p>I'm doing some operations with the numeric data (sums, averages, etc) so I need to remove the % sign so pandas can stop trea... | <p>Replace:</p>
<pre><code>df = df.replace({'%':''}, regex=True)
Name Jan_2018 Feb_2018 Mar_2018
0 A 33 40 42
1 B 20 35 50
2 C 21 31 12
</code></pre>
<p>Convert to numbers</p>
<pre><code>df = df.apply(lambda s: pd.to_numeric(... | python|pandas|dataframe | 1 |
371,423 | 52,729,179 | filter rows on column values with string methods | <p>Input df:</p>
<pre><code>title desc
movie A It is a awesome movie with action
movie B Slow but intense movie.
</code></pre>
<p>I want to filter rows which contains the following keywords:</p>
<pre><code>keys = ["awesome", "action"]
</code></pre>
<p>Output... | <p>Why yes, there is - <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer">pandas.Series.str.contains</a></p>
<pre><code>idx = df['column_name'].str.contains("|".join(keys), regex=True)
df[idx]
</code></pre> | python|pandas | 3 |
371,424 | 52,884,048 | How to create this matrix in Python? | <p>I am new in python and was struggling on how to code this matrix for a while. </p>
<pre><code>x'=[x1,x2,x3,x4,...,xN]
</code></pre>
<p>x is the transpose of the above matrix.</p>
<p>I'd like to create a matrix y with values</p>
<p><img src="https://i.stack.imgur.com/YQTni.png" alt="shown here"></p>
<p>x needs t... | <p>You can use broadcasting to avoid explicit tiling.
Let <code>base_vector</code> (your x) be a numpy array, and let <code>max_power</code> (your k) be an integer as in @Eric Miller's answer.</p>
<pre><code>import numpy as np
powers = np.range(max_power+1)
result = base_vector[:, np.newaxis] ** powers[np.newaxis, :]
... | python|arrays|numpy|matrix | 0 |
371,425 | 52,551,997 | Assigning integers to dataframe fields ` OverflowError: Python int too large to convert to C unsigned long` | <p>I have a dataframe <code>df</code> that looks like this:</p>
<pre><code> var val
0 clump_thickness 5
1 unif_cell_size 1
2 unif_cell_shape 1
3 marg_adhesion 1
4 single_epith_cell_size ... | <p>I dont know the why. Maybe lamda use by default int in front of int64?
I have a workaround that maybe is useful for you.</p>
<p>Convert the result to string (<em>object</em>):<code>df['id'] = df.apply(lambda row: str(int.from_bytes('{}{}'.format(row["var"], row["val"]).encode(), 'little')), axis = 1)
</code></p>
<... | python-3.x|pandas | 2 |
371,426 | 52,661,463 | gRPC for kotlin android: Import "google/protobuf/wrappers.proto" does not work | <p>I created a gRPC project very similar to the example gRPC for kotlin android project at
<a href="https://github.com/grpc/grpc-java/tree/master/examples/example-kotlin/android/helloworld" rel="nofollow noreferrer">https://github.com/grpc/grpc-java/tree/master/examples/example-kotlin/android/helloworld</a></p>
<p>Th... | <p>The "well-known" protos that are shipped with the normal protobuf jar are not included in the protobuf-lite jar, which the kotlin Android example is using. The issue is tracked in <a href="https://github.com/protocolbuffers/protobuf/issues/1889" rel="nofollow noreferrer">https://github.com/protocolbuffers/protobuf/i... | android|kotlin|protocol-buffers|grpc|tensorflow-serving | 1 |
371,427 | 52,857,501 | Errors during group by on pandas dataframe | <p>Can you please advise on the below, I'm a bit stuck.</p>
<p>So, dataframe3 has the columns, 'domain' and 'size'. My script cleans up the domain and adds a new column called 'newdomain2'</p>
<p>I add the column below & view the dataframe & it looks correct.</p>
<p>So then, df4 needs to be an aggregated ver... | <p>You can't directly put a list into a dataframe column,</p>
<pre><code>df3['your_col'] = pd.Series(your_list).values
</code></pre> | python|python-3.x|pandas|pandas-groupby | 0 |
371,428 | 52,465,370 | Accuray error due to Index column in dataframe | <p>I hope you guys are in good health. I am working on keras library python 3 for solving a regression problem. When i load my dataset into a panads dataframe it adds index column automatically which can be reset but cannot be removed when I train my model on that dataset it gives very low accuracy (0.002) Will you guy... | <p>i suggest use, </p>
<p><code>df = df.values</code></p>
<p>df now becomes the numpy ndarray:
this will effectively remove the index column and the column names, so what you would do is as follows</p>
<pre><code>y_train=train[['csMPa']].values
x_train=train.drop(["csMPa"],axis=1).values
</code></pre>
<p>now i am n... | python|tensorflow|keras | 1 |
371,429 | 52,546,068 | Pandas how to convert a timestamp column (EST) to local TimeZone info available in other column | <p>From</p>
<pre><code>colA (EST) colB (local tz)
2016-09-19 01:29:13 US/Central
2016-09-19 02:16:04 Etc/GMT+2
2016-09-19 01:57:54 Europe/London
</code></pre>
<p>To</p>
<pre><code>colA (EST) colB (local tz) colC (timestamp in local tz)
2016-09-19 01:29:1... | <p>Read the datetime column as timestamp and localize to US/Eastern time and then apply tz_convert</p>
<pre><code>df['colA (EST)'] = pd.to_datetime(df['colA (EST)']).dt.tz_localize('US/Eastern')
df['colC (timestamp in local tz) '] = df.apply(lambda x: x['colA (EST)']\
.tz_convert(x['colB (local tz)']), axis = 1)
... | python|pandas|timestamp-with-timezone | 3 |
371,430 | 52,595,395 | Simple Python xlsx File Compare Without Metadata | <p>Is there an easy way to compare two xlsx files in python that ignores metadata? Trying to test that the output of a script matches an expected xlsx file.</p>
<p>I'm looking for something like filecmp.cmp() which doesn't work because the metadata for the files differs (I think the only difference is that they were w... | <p>Xlsx files are a collection of XML files in a Zip container. For two xlsx files to be binary equivalent the:</p>
<ol>
<li>XML files must be exactly the same.</li>
<li>The zip must be done in the same way.</li>
</ol>
<p>For XlsxWriter files, and probably for most software, the zip will be the same. However, it may ... | python|pandas | 0 |
371,431 | 52,709,073 | How to vectorize indexing operation in tensorflow | <p>I have a tensor A of shape (2, 4, 2), and a tensor B of shape (4, 4), all the values are int. Entries in A are from 0 to 3.</p>
<p>I want to create a tensor C of shape(2, 4, 2). </p>
<p>The for loop code is like:</p>
<pre><code>
for i in range(2):
for j in range(2):
for k in range(4):
C[i... | <p>Here is how you can do it with <a href="https://www.tensorflow.org/api_docs/python/tf/gather_nd" rel="nofollow noreferrer"><code>tf.gather_nd</code></a>:</p>
<pre><code>import tensorflow as tf
# Input values
A = tf.placeholder(tf.int32, [None, None, None])
B = tf.placeholder(tf.int32, [None, None])
# Make indices ... | python|tensorflow | 0 |
371,432 | 52,598,012 | Slicing, indexing and iterating over 2D numpy arrays | <p>I am enrolled in a beginners class Python at my university. We've got a programming assignment which I'm stuck on.</p>
<p>We got an assignment to find a route between two point in a map, the map is an 2D numpy array.
One of the first tasks is to convert the array consisting of free road(1) and buildings(0) to an a... | <p>Here is one simple way using standard numpy techniques:</p>
<p>1) Make a map consisting of 3x3 blocks with 80% road</p>
<pre><code>>>> map_ = np.kron(np.random.random((6, 5)) < 0.8, np.ones((3, 3), int))
>>> map_
array([[1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 0... | python|arrays|numpy | 2 |
371,433 | 52,631,878 | Using ndimage.interpolation.affine_transform for matrix translation | <p>I'm trying to translate a simple matrix using <code>ndi.interpolation.affine_transform</code>, but the result I get is reversed. For instance:</p>
<pre class="lang-py prettyprint-override"><code>import scipy.ndimage as ndi
m = [[1, 1, 11], [2, 2, 22], [3, 3, 33]]
final_affine_matrix = [[1, 0], [0, 1]]
final_offset ... | <p>As stated in the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html" rel="nofollow noreferrer">documentation</a>, <code>scipy.ndimage.affine_transform()</code> computes the new position by doing: <code>np.dot(matrix, o) + offset</code> (where <code>o</code> is the outpu... | python|numpy|scipy | 0 |
371,434 | 52,459,285 | How to make multiple if statements run faster in python | <p>I have following pandas dataframe</p>
<pre><code> Code Sum Quantity
0 -12 0
1 23 0
2 -10 0
3 -12 0
4 100 0
5 102 201
6 34 0
7 -34 0
8 -23 0
9 100 0
10 100 ... | <p>Let's look at three solutions and provide performance comparisons at the end.</p>
<p>One approach that tries to stay close to pandas would be the following:</p>
<pre><code>def f1(df):
# Group together the elements of df.Sum that might have to be added
pos_groups = (df.Sum <= 0).cumsum()
pos_groups[d... | python|pandas|dataframe | 2 |
371,435 | 52,651,074 | Python Pandas equivalent to the excel fill handle? | <p>Is there a Pandas function equivalent to the MS Excel fill handle? </p>
<p><a href="https://i.stack.imgur.com/0Q7rb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Q7rb.png" alt="Fill Handle from MS Excel"></a></p>
<p>It fills data down or extends a series if more than one cell is selected. My... | <p>This simple function essentially does what I want. I think it would be nice if ffill could be modified to fill in this way...</p>
<pre><code>def fill_down(df, col, val, start, end = 0, interval = 1):
if not end:
end = len(df)
for i in range(start,end,interval):
df[col].iloc[i] += val
re... | python|pandas|autofill | 2 |
371,436 | 52,727,099 | Generation of combination of matrix rows | <p>For example I am having matrix with 64 rows. I want to get all the combinations looks like we can take 1 element from rows 0 to 3, 1 element from 4 to 7 etc.
So I need 16 rows from matrix.
My idea is making 16 matrix with 4 rows and try to choose one from each. But my code doesn't work. Task is getting all the combi... | <p>For something as large as what you have, its very difficult to print the results, so i will give you a working example for something smaller-</p>
<pre><code>import numpy as np
from itertools import permutations
matrix = np.random.randint(0, 5, (4,2))
print(matrix)
</code></pre>
<p>Output:</p>
<pre><code>[[4 3]
[... | python|python-3.x|numpy|combinations|itertools | 0 |
371,437 | 52,582,275 | tf.data with multiple inputs / outputs in Keras | <p>For the application, such as <strong>pair text similarity</strong>, the input data is similar to: <code>pair_1, pair_2</code>. In these problems, we usually have multiple input data. Previously, I implemented my models successfully:</p>
<pre><code>model.fit([pair_1, pair_2], labels, epochs=50)
</code></pre>
<p>I d... | <p>I'm not using Keras but I would go with an tf.data.Dataset.from_generator() - like:</p>
<pre><code>def _input_fn():
sent1 = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.int64)
sent2 = np.array([20, 25, 35, 40, 600, 30, 20, 30], dtype=np.int64)
sent1 = np.reshape(sent1, (8, 1, 1))
sent2 = np.reshape(sent2, (8... | tensorflow|keras|tensorflow-datasets | 68 |
371,438 | 52,633,819 | Removing duplicate records from CSV file using Python Pandas | <p>I would like to remove duplicate records from a csv file using Python Pandas
The CSV contains records with three attributes scale, minzoom, maxzoom. I want to have a resulting dataframe with minzoom and maxzoom and the records left being unique</p>
<p>i.e</p>
<p>Input CSV file (lookup_scales.csv)</p>
<pre><code> ... | <p>You don't need numpy or anything you can just do the unique-ify in one line, while importing the csv using pandas:</p>
<pre><code>import pandas as pd
df = pd.read_csv('lookup_scales.csv', usecols=['minzoom', 'maxzoom']).drop_duplicates(keep='first').reset_index()
</code></pre>
<p>output:</p>
<pre><code> minzoom... | python|pandas|csv|grouping|distinct-values | 4 |
371,439 | 52,832,567 | Regex in python / pandas causing strange end of line characters | <p>I'm just getting started with Pandas and am working on a domain cleanup tool. Essentially, I want to remove all subdomains & just retain the main domain + the tld.</p>
<p>The below works in ipython against a single domain, but I am struggling against a dataframe of multiple domains.</p>
<p>The script seems to ... | <p>Here is the working code:</p>
<pre><code>In [5]: import pandas as pd
In [6]: import re
#Define the path of the file & generate the dataframe from it
In [7]: path = "Desktop/domains.csv"
In [8]: df = pd.read_csv(path, delimiter=',', header='infer')
#Show the dataframe to validate input is correct
In [9]: df
Out[... | python|python-3.x|pandas | 0 |
371,440 | 46,614,843 | How to set cells of matrix from matrix of columns indexes | <p>I'd like to build a kernel from a list of positions and list of kernel centers. The kernel should be an indicator of the TWO closest centers to each position.</p>
<pre><code>> x = np.array([0.1, .49, 1.9, ]).reshape((3,1)) # Positions
> c = np.array([-2., 0.1, 0.2, 0.4, 0.5, 2.]) # centers
print x
print ... | <p>One way would be to initialize zeros array and then index with <a href="https://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer"><code>advanced-indexing</code></a> -</p>
<pre><code>out = np.zeros(dist.shape,dtype=int)
out[np.arange(idx.shape[0])[:,None],idx... | numpy | 1 |
371,441 | 46,511,328 | Tensorflow Dataset.from_generator fails with pyfunc exception | <p>I am trying tensorflow's nightly 1.4 as I need <a href="https://www.tensorflow.org/versions/master/api_docs/python/tf/contrib/data/Dataset#from_generator" rel="noreferrer"><code>Dataset.from_generator</code></a> to stich together some variable length datasets. This simple code (idea from <a href="https://stackoverfl... | <p>The <a href="https://www.tensorflow.org/versions/master/api_docs/python/tf/contrib/data/Dataset#from_generator" rel="noreferrer"><code>Dataset.from_generator()</code></a> method is designed to connect non-TensorFlow Python code to a <code>tf.data</code> input pipeline. For example, you can yield simple Python object... | python|tensorflow|generator|yield|tensorflow-datasets | 13 |
371,442 | 46,574,336 | How would tensorflow handle back propagation when you reorganized your outputs in the middle layers | <p>
I have a neural network with a hidden layer that outputs a number A, then I used a function which uses A to generate a vector. The question is can TF deal with this properly when doing back propagation? I did try it in TF and it can outputs something but I'm still not sure if the bp works correctly. </p>
<p>BTW, t... | <p>Yes, tensorflow can backpropagate through almost any differentiable transformation expressed in the tensorflow graph, and you'll get a visible error when the backpropagation cannot happen.</p> | tensorflow|backpropagation | 1 |
371,443 | 46,429,925 | Display datraframe into django template | <p>I'm currently working on a stadistics portal with <code>Django</code> and i'm trying to display a <code>Dataframe</code> in my template with the next code:</p>
<p>View.py:</p>
<pre><code>def tabla(request):
engine = create_engine('postgresql://postgres:alphabeta@localhost:5432/escaladas')
t='escalado 08/20... | <p>Try <code>{{table|safe}}</code> instead, so the HTML doesn't get <a href="https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#safe" rel="nofollow noreferrer">escaped</a>.</p> | python|django|pandas|templates|bootstrap-4 | 0 |
371,444 | 46,175,459 | pandas select FROM .... TO | <p>I have a dataframe </p>
<pre><code>C V S D LOC
1 2 3 4 X
5 6 7 8
1 2 3 4
5 6 7 8 Y
9 10 11 12
</code></pre>
<p>how can i select rows from loc X to Y and inport them in another csv </p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.idxmax.html" rel="nofollow noreferrer"><code>idxmax</code></a> for first values of index where <code>True</code> in condition:</p>
<pre><code>df = df.loc[(df['LOC'] == 'X').idxmax():(df['LOC'] == 'Y').idxmax()]
print (df)
C V S D... | python|pandas | 3 |
371,445 | 46,607,246 | How can I compile correctly and execute the example of TensorFlow C++ API? | <p>I tried the example of TensorFlow C++ API (<a href="https://www.tensorflow.org/api_guides/cc/guide" rel="nofollow noreferrer">https://www.tensorflow.org/api_guides/cc/guide</a>) on macOS.</p>
<p>What I did is:</p>
<ol>
<li>Install bazel</li>
<li>git clone --recursive <a href="https://github.com/tensorflow/tensorfl... | <p>I finally found the solution.</p>
<p>BUILD below in the guide might not be suitable for the latest tensorflow.</p>
<pre><code>cc_binary(
name = "example",
srcs = ["example.cc"],
deps = [
"//tensorflow/cc:cc_ops",
"//tensorflow/cc:client_session",
"//tensorflow/core:tensorflow",
... | c++|tensorflow|bazel | 2 |
371,446 | 46,344,549 | How to specify dtype correctly in python when dealing with complex numbers and numpy? | <p>I need to check whether a matrix is unitary in python, for that I use this function: </p>
<pre><code>def is_unitary(m):
return np.allclose(np.eye(m.shape[0]), m.H * m)
</code></pre>
<p>but when I'm trying to specify a matrix by:</p>
<pre><code>m1=np.matrix([complex(1/math.sqrt(2)),cmath.exp(1j)],[-cmath.exp(-... | <p><a href="https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html#array-or-matrix-which-should-i-use" rel="nofollow noreferrer">Don't use <code>np.matrix</code></a>, it's almost always the wrong choice, especially if you use Python 3.5+. You should rather use <code>np.array</code>.</p>
<p>Besides, you ... | python|python-3.x|numpy|linear-algebra|complex-numbers | 0 |
371,447 | 46,228,705 | python pandas DataFrame iterate through rows and compare two columns and apply function | <p>I have a DataFrame with two columns:</p>
<pre><code>df:
ix Col1 Col2
1 11.0 'JPY'
2 51.0 'EUR'
..
1000,000 27.0 'CAD'
</code></pre>
<p>I have a list of currencies <code>l1 = ['JPY','EUR',...,'CAD']</code>
I have a list of conversions <code>l2 = [5.0, 1.0, ..., 0... | <p>IIUC you can use the following vectorized approach:</p>
<p>Source data sets:</p>
<pre><code>In [108]: d1
Out[108]:
ix Col1 Col2
0 1 11.0 JPY
1 2 51.0 EUR
2 3 27.0 CAD
In [109]: l1 = ['JPY','EUR','CAD']
In [110]: l2 = [5.0, 1.0, 0.5]
</code></pre>
<p>Helper "exchange rate" Series:</p>
<pre><code... | python|function|pandas|dataframe|apply | 0 |
371,448 | 46,429,766 | Distributed Tensorflow: CreateSession still waiting | <p>Simple script below is launched with args shown in it's header. It behaves differently, but often one of the workers hangs and prints these "CreateSession still waiting for some other task" messages. Why does a new MonitoredTrainingSession need others? And why don't the others wait for it to start? </p>
<pre><code... | <p>By default, a distributed TensorFlow session will attempt to connect to <strong>all servers</strong> named in the <code>tf.train.ClusterSpec</code>, and will block until they respond. This provides a useful barrier that ensures that all workers have become ready to receive computation requests before returning contr... | python|tensorflow|distributed-computing|distributed | 1 |
371,449 | 46,345,565 | How to initialize a two dimensional string DataFrame array in python | <p>I want to initialize a 31756x2 data frame of strings.
I want it to look like this:</p>
<pre><code>index column1 column2
0 A B
1 A B
.
.
31756 A B
</code></pre>
<p>I wrote:</p>
<pre><code>content_split = [["A", "B"] for x in range(31756)]
</code... | <p>Use <code>DataFrame</code> constructor only:</p>
<pre><code>df = pd.DataFrame([["A", "B"] for x in range(31756)], columns=['col1','col2'])
print (df.head())
col1 col2
0 A B
1 A B
2 A B
3 A B
4 A B
</code></pre>
<p>Or:</p>
<pre><code>N = 31756
df = pd.DataFrame({'col1':['A'] * N, '... | python|arrays|pandas|spyder | 2 |
371,450 | 46,384,890 | Use pandas to read in text file with row as column names | <p>I'm working on a project to read in a text file of variable length which will be generated by a user. There are several comments at the beginning of the text file, one of which needs to be used as the column name. I know it is possible to do this with genfromtxt(), but I am required to use pandas. Here is the beginn... | <p>One way may be to try following:</p>
<pre><code>df = pd.read_csv('example.txt', sep='\s+', engine='python', header=2)
# the first column name become #a so, replacing the column name
df.rename(columns={'#a':'a'}, inplace=True)
# alternatively, other way is to replace # from all the column names
#df.columns = [colu... | python|python-3.x|pandas|dataframe | 0 |
371,451 | 46,625,844 | Convert pandas data frame with mapping | <p>I have a pandas data frame. Df1 which has the customer information:</p>
<pre><code>Customer_Name Demand
John 100
Mike 200
...
</code></pre>
<p>There is also a dictionary which has the map between customer name and customer code</p>
<pre><code>Customer_Name Customer_Code
John ... | <p>A <code>merge</code> should do just fine.</p>
<pre><code>df = df1.merge(df2)
df
Customer_Name Demand Customer_Code
0 John 100 1
1 Mike 200 2
</code></pre>
<p>If you'd like to get rid of the first column, call <code>df.drop('Customer_Name', 1)</code>:</p>
<pr... | python|pandas|dataframe | 5 |
371,452 | 46,305,796 | Pandas .loc without KeyError | <pre><code>>>> pd.DataFrame([1], index=['1']).loc['2'] # KeyError
>>> pd.DataFrame([1], index=['1']).loc[['2']] # KeyError
>>> pd.DataFrame([1], index=['1']).loc[['1','2']] # Succeeds, as in the answer below.
</code></pre>
<p>I'd like something that doesn't fail in either of</p>
<pre><c... | <p><strong>Update for @AlexLenail comment</strong><br>
It's a fair point that this will be slow for large lists. I did a little bit of more digging and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html?highlight=intersection#pandas.Index.intersection" rel="noreferrer">found<... | pandas | 17 |
371,453 | 46,576,831 | Get TypeError: Index must be DatetimeIndex when filtering dataframe | <p>I want to filter the dataframe by a certain datatime period like the following code.</p>
<pre><code>df2 = df2['Dates'].between_time(pandas.to_datetime('5/13/2015 8:41'), pandas.to_datetime('5/13/2015 8:55'))[['Dates','Category']]
</code></pre>
<p>but got an error 'TypeError: Index must be DatetimeIndex'
This is t... | <p>If you want to filter <code>df</code> by a certain datetime period, you can try with:</p>
<pre><code>start_date = pandas.to_datetime('5/13/2015 8:41')
end_date = pandas.to_datetime('5/13/2015 8:55')
df2.loc[(df2['Dates'] > start_date) & (df2['Dates'] < end_date)]
</code></pre> | python|pandas|python-datetime | 3 |
371,454 | 46,629,694 | Matplotlib graph displaying aggregate functions in a strange manner | <p>I've faced with the following problem while trying to display data from a DataFrame with Matplotlib. The idea is to build a linear graph where Y-axis is the mean of score for each gamer and the X-axis is the number of shots performed. I have applied aggregate functions to the data in my DataFrame but the resulting g... | <p>IIUC, you need something like this:</p>
<pre><code>In [52]: df.groupby('Gamer').agg({'Score':'mean','Shots':'count'}).plot()
Out[52]: <matplotlib.axes._subplots.AxesSubplot at 0xb41e710>
</code></pre>
<p><a href="https://i.stack.imgur.com/pkBh2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.c... | python|pandas|matplotlib|dataframe | 2 |
371,455 | 46,429,997 | Convert Timestamp to str value python pandas dataframe | <p>I have dataframe
which looks like this</p>
<pre><code> Date Player Fee
0 2017-01-08 Steven Berghuis 6500000
1 2017-07-18 Jerry St. Juste 4500000
2 2017-07-18 Ridgeciano Haps 600000
3 2017-01-07 Sofyan Amrabat 400000
</code></pre>
<p>I want to change every date value to str if they m... | <p>By using <code>pd.cut</code></p>
<pre><code>ses1 = pd.to_datetime('2013-02-01')
ses2 = pd.to_datetime('2014-02-01')
ses3 = pd.to_datetime('2015-02-01')
ses4 = pd.to_datetime('2016-02-01')
ses5 = pd.to_datetime('2017-02-01')
ses6 = pd.to_datetime('2018-02-01')
pd.cut(df.Date,[ses1,ses2,ses3,ses4,ses5,ses6],labels=[... | python|pandas|datetime|dataframe | 1 |
371,456 | 46,232,537 | Adding a column to large dataframe retreived in chunks | <p>I have sample code as below:</p>
<pre><code>def return_table_df(table_name, chunksize,conn):
try:
df = pandas.read_sql_table(table_name,conn, chunksize=chunksize)
return df
except Exception as e:
logging.error(e)
data_fram... | <p><strong>Scenario 1</strong><br>
Creating a blank column. This is simple, just assign a new column to the dataframe. You'll need to iterate over the the return value of <a href="http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.read_sql_table.html" rel="nofollow noreferrer"><code>read_sql_table</code... | python|pandas|dataframe | 1 |
371,457 | 46,400,617 | Return rows that match certain Japanese characters in a Series | <p>I have a pandas dataframe with several columns in Japanese.
I would like to run a search that returns rows that contain certain Japanese characters. </p>
<p>ex.</p>
<pre><code>find_str = 'バッグ'
</code></pre>
<p>I know I can't just use things like:</p>
<pre><code>df[df.col1.str.contains(find_str)] or df[df.col1 =... | <p>For me working:</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
df = pd.read_csv('file.csv', encoding='utf-8')
find_str = u'バッグ'
m = df['name'].str.contains(find_str)
print (m)
0 False
1 True
2 False
3 False
4 False
5 False
Name: name, dtype: bool
</code></pre> | python|pandas|character-encoding | 0 |
371,458 | 46,372,238 | Can I use "from __future__ import" to overcome API changes for "sort" in pandas? | <p>The pandas API on the sort function has changed from pandas version 17 on, so that now you need to use <code>df.sort_values</code> instead of <code>df.sort</code>:</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/whatsnew.html#whatsnew-0170-api-breaking" rel="nofollow noreferrer">https://pandas.pydata.o... | <p>similar to bphi 's comment, you could try using if/else:</p>
<pre><code>#print(pd.__version__.split('.'))
#output: ['0', '20', '2']
# using an or statement here just in case you need to ultra-future-proof
# will check if version is above 0.x.x or greater than 0.17.0
if int(pd.__version__.split('.')[1]) > 17 or ... | python|pandas|sorting | 1 |
371,459 | 46,315,202 | How to get the inner module of Unet? | <p>I created a <code>UNet</code> with the the <a href="https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py#L235-L314" rel="nofollow noreferrer">UnetGenerator</a>. You can find the resulting structure <a href="https://gist.github.com/anonymous/078ee01f43a13524f634eff1d87fe191" rel="nof... | <p>All the subclasses of nn.Module has an attribute called children. Which you will be able to access using the code below.</p>
<pre><code>unet = UnetGenerator(512,512,4)
layers = list(unet.children())
len(layers)
</code></pre>
<p>For the network I created using the above code , I can access one of the layers inside ... | pytorch | 2 |
371,460 | 46,541,543 | How to plot pandas.crosstab() columns | <p>I am trying to plot in the same figure the first <em>n</em> values which are the results of <code>pd.crosstab()</code>, I have tried:</p>
<pre><code>tab = pd.crosstab(df['genre_ids'], df['target'],margins=True).sort_values('All',ascending=False)
tab = tab.drop('All',axis=1)
tab = tab.drop('All',axis=0)
tab[:top_n].... | <p>Solved simply set <code>stacked = False</code> as has suggested @Nipun Batra in the comments.</p> | python|pandas|matplotlib | 0 |
371,461 | 46,404,523 | Error with pandas: pandas.io.common.CParserError: Error tokenizing data | <p>when I run this script it does not work and I don't know why. Can you help me?</p>
<pre><code>import pandas as pd
data1 = pd.read_csv(url)
print(data1)
</code></pre>
<p>Errors:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\abc\Desktop\script.py", line 4, in <module>
data1 = pd.read_... | <p>in pandas handle, you should pass in the location of the csv. </p>
<p>Example:
pd.read_csv(location.of.archive)
Like:
pd.read_csv(myfile.csv)</p>
<p>That's all! </p> | python|python-3.x|pandas | 1 |
371,462 | 46,473,554 | Numpy Basics - How to Interpret [:,] in array access | <p>I have an nd-array A</p>
<pre><code>A.shape
(2, 500, 3)
</code></pre>
<p>What's the difference between <code>A[:]</code> and <code>A[:,2]</code></p>
<p>Coming from Python, the ',' in the array access is confusing me a lot.</p> | <p>The commas separate the subscripts for each dimension. So, for example, if the matrix <code>M</code> is defined as</p>
<pre><code>M = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
</code></pre>
<p>then <code>M[2, 1]</code> would be 8 (third row, second column).</p>
<p>The subscript for e... | python|arrays|numpy | 3 |
371,463 | 46,473,356 | Set opencv images/numpy array values using an array of pixels | <p>Attempting to do forward warping of a homography matrix in OpenCV. You don't have to know what that means to understand the issue though.</p>
<p>Assume there are 2 images (an image is a 2D Numpy array of pixel values), A and B, and an array <code>match</code> that looks like </p>
<pre><code>[[ 6.96122642e+01 -1.... | <p>The fastest way would be to not reinvent the wheel and use <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html#cv2.warpPerspective" rel="nofollow noreferrer">cv.WarpPerspective</a> function.</p>
<p>Alternatively, you can use Pillow <a href="http://pillow.readthedocs.io/en/4.1.x/re... | python|arrays|opencv|numpy|array-broadcasting | 1 |
371,464 | 58,384,390 | Training Data for Spacy from Pandas Dataframe | <p>I am new to Python and I am currently strugglint with converting a dataframe into a the followinf format.</p>
<p>As an example, I have the following dataframe (df1):</p>
<pre><code> fulltext text start end text1 start1 end1
0 Android Pay expands to Canada ... | <p>try this</p>
<pre><code>df['fulltext'].apply(lambda x: (x,{'entities':[(0,len(x),'entity')]})).tolist()
</code></pre>
<p>This is a partial solution.
You can expand same to your entities</p> | python|pandas | 0 |
371,465 | 58,553,289 | How can I reference particular cells in a dataframe? | <p>I am a beginner and this is my first project.. I searched for the answer but it still isn't clear.
I have imported a worksheet from excel using Pandas..</p>
<p>**Rabbit Class:</p>
<pre><code> Num Behavior Speaking Listening
0 1 3 1 1
1 2 1 ... | <p>What you want is to find rows where <code>df.Behavior</code> is equal to 1. Use any of the following three methods. </p>
<pre class="lang-py prettyprint-override"><code># Method-1
df[df["Behavior"]==1]
# Method-2
df.loc[df["Behavior"]==1]
# Method-3
df.query("Behavior==1")
</code></pre>
<p>Output: </p>
<pre><c... | python|excel|pandas|dataframe | 0 |
371,466 | 58,470,377 | copy and paste each column from an existing csv file into a new csv file | <p>So I have an existing csv file with multiple columns. I am trying to copy each column (one by one) and paste it into a new csv file. The name of the new csv file will be the header of the column. </p>
<p>I am trying to tweak a code that picks specific columns but no luck so far for multiple columns.</p>
<pre><code... | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>my_file = r"D:/Excel/new_csv_3.csv"
df = pd.read_csv(my_file)
for col in df.columns:
df[col].to_csv(f'D:/Excel/new{col}.csv')
</code></pre>
<p>if you need specific columns, just change the for loop:</p>
<pre class="lang-py prettyprint-override"><co... | python|pandas|csv | 0 |
371,467 | 58,342,418 | TF2.0 lite for Android : Converting Keras (LSTM) models to tflite | <p>I am using the following code with LSTM (Keras Sequential Model)</p>
<pre><code>def MyModel_keras():
model = tf.keras.models.Sequential([
tf.keras.layers.LSTM(conf.n_hidden_lstm, activation='tanh', return_sequences=False, name='lstm1'),
tf.keras.layers.Dense(conf.n_dense_1, activation='relu', na... | <p>Maybe you can convert specific RNN ops to TFLite in TensorFlow. See this <a href="https://www.tensorflow.org/lite/convert/rnn" rel="nofollow noreferrer">doc</a>. We can use <code>tf.compat.v1.nn.rnn_cell</code> and others mentioned in this <a href="https://www.tensorflow.org/lite/convert/rnn#currently_supported" rel... | android|tensorflow|keras|lstm|tensorflow2.0 | 1 |
371,468 | 58,193,395 | PIL.Image.verify() breaks ability to convert PIL image to Numpy | <p>This code works as expected:</p>
<pre><code>import numpy as np
import PIL.Image
img = PIL.Image.open('test.png')
img_np = np.array(img)
print(img_np.dtype, img_np.shape)
> uint8 (192, 256)
</code></pre>
<p>When I add <code>verify()</code>, <code>img_np</code> becomes an object, not the image data:</p>
<pre>... | <p>This is <a href="https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.verify" rel="nofollow noreferrer">documented behaviour</a>:</p>
<blockquote>
<p><code>Image.verify()</code></p>
<p>Verifies the contents of a file. For data read from a file, this method attempts to determine if the ... | python|numpy|python-imaging-library | 3 |
371,469 | 58,397,678 | fast pytables pandas data slicing | <p>I am suffering from slow running speed.
my data is </p>
<pre><code> <class 'pandas.io.pytables.HDFStore'>
File path: c:/data/bed_1/acc_ohlc.hdf
/000020 frame (shape->[7721,5])
/000030 frame (shape->[1037,5])
/000040 frame (shape->[7723,5])
/... | <p>Something like this might speed up the process drastically.
.iterrows may not be the best option out there. </p>
<pre><code>def fun(c):
code = c[:-3]
p_data[code] = store[code].ix[begin:end].astype (float)
code_list.Code.apply(fun)
</code></pre> | python|pandas|pytables | 0 |
371,470 | 58,573,113 | How do I iterate over an ndarray without using for/while loops? | <p>For two given 1-d arrays or lists I can calculate the squared Euclidean distance via the function</p>
<pre><code>import numpy as np
def npdistance(x1, x2):
return sum((np.array(x1)-np.array(x2))**2)
</code></pre>
<p>Now for a given vector v and 2d-array X I would like to find the shortest squared Euclidean d... | <p>In case of numpy, prefer <code>np.sum</code> and <code>np.min</code>, rather than Python buildins <code>sum</code> and <code>min</code>.</p>
<p>We can adapt <code>npdistance</code> for 2D numpy vectors:</p>
<pre><code>def npdistance(x1, x2):
return np.sum((np.array(x1)-np.array(x2))**2, axis=1)
</code></pre>
... | python|numpy|numpy-ndarray | 1 |
371,471 | 58,450,965 | List of lists conversion to pandas DataFrame | <p>I have a list of lists that looks like this:</p>
<pre><code>[[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '1'), ('type', 'good')],
[('category', 'intensifier'), ('type', 'shifter')],
[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '2'), ('type', 'good')],
</code></pre>
<p>Note that... | <p>You could transform each list into a dictionary:</p>
<pre><code>import pandas as pd
data = [[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '1'), ('type', 'good')],
[('category', 'intensifier'), ('type', 'shifter')],
[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '2'), ('type', 'good... | python|pandas|list|dataframe | 4 |
371,472 | 58,403,985 | How to compare two columns for a string and replace the string case in one column to other? | <p>I have two columns Sentences and Updates. I want to match each words in Updates Column at the end of a Url with corresponding Sentences word case and replace it with the case of the word in Sentences.</p>
<p>I have no clue how to go about this comparison any help is appreciated.
The actual data has 43k rows with d... | <p>Use <code>re</code></p>
<p>Code:</p>
<pre><code>import re
dict1 = {
'Sentences': [
'The new line',
'Its a bright and sunny day',
'Smartphone have taken our the World',
'GLOBAL Warming is reaching its Peak '
],
'Updates': [
'The new abc.com/Line',
'Its a ... | python|regex|pandas|pattern-matching | 0 |
371,473 | 58,530,446 | RuntimeError when importing keras? | <p>I'm trying to do some newb-level tutorial stuff with Keras and Python but I can't get past the keras module import. I'm working in Python 3.7.3 (on a Mac/no GPU) using a fresh virtualenv. Here's my <code>pip list</code>:</p>
<pre><code>Package Version
-------------------- -------
absl-py 0... | <p>Found the problem. Apparently tensorflow doesn't yet support Python 3.7. I tried with Python 3.6.4 and everything works fine.</p> | python|tensorflow|keras | 0 |
371,474 | 58,366,134 | Split rows into multiple rows based on column value | <p><strong>Input DF</strong>:</p>
<pre><code>Index Parameters A B C
1 Apple 1 2 3
2 Banana 2 4 5
3 Potato 3 5 2
4 Tomato 1 x 4 1 x 6 2 x 12
</code></pre>
<p><strong>Output DF</strong></p>
<pre><code>Index Para... | <p>Solution if always only one <code>x</code> values in data - first <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a> by columns in list, then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pa... | python|pandas | 1 |
371,475 | 58,232,001 | convert data from JSON to pandas dataframe | <p>I would like to extract some data from the following line of text. The data of interest are:<code>'exchange_symbol</code> under both <code>market_pair_base</code> and <code>'market_pair_quote</code>, all the data under <code>exchange_reported</code>.
Any help would be great.</p>
<pre><code>{'status': {'timestamp':... | <p>Assumed JSON as given in <code>d</code> variable</p>
<p>Try below snippet:</p>
<pre><code>target_df=pd.DataFrame(columns=['market_pair_base','market_pair_quote','price','last_updated'])
target=dict()
usedlist=d['data']['market_pairs']
for i in range(len(usedlist)):
target['market_pair_base']=[usedlist[i]['ma... | python|pandas | 1 |
371,476 | 58,255,200 | Using Wide_to_Long on 3 Columns | <p>How to split a dataframe using pandas wide_to_long keeping first column as index and balance columns (in group of 3) into single dataframe. </p>
<p>I have sample dataframe like below:</p>
<pre><code>columns = [timestamp, BQ_0, BP_0, BO_0, BQ_1, BP_2, BO_2, BQ_3, BP_3,BO_3, BQ_4, BP_4, BO_4, BQ_4, BP_4, BO_4]
09:1... | <p>Source : <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html</a></p>
<p>pandas.wide_to_long(df, stubnames, i, j, sep='', suffix='\d+')</p>
<pre>df : DataFrame
The ... | python|python-3.x|pandas | 2 |
371,477 | 58,543,235 | Swapping values in columns depending on value type in one of the columns | <p>Suppose I have the following pandas dataframe:</p>
<pre><code>df = pd.DataFrame([['A','B'],[8,'s'],[5,'w'],['e',1],['n',3]])
print(df)
0 1
0 A B
1 8 s
2 5 w
3 e 1
4 n 3
</code></pre>
<p>If there is an integer in column 1, then I want to swap the value with the value from column 0, so in other words ... | <p>Replace numbers from second column with mask by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="noreferrer"><code>to_numeric</code></a> with <code>errors='coerce'</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.notna.html" re... | python|pandas|dataframe | 4 |
371,478 | 58,568,159 | Dataframe: compare column value and one row below | <p>I have a dataframe with directions: </p>
<pre><code> Direction:
2/01/19 None
1/31/19 Upward
1/30/19 None
1/29/19 None
1/28/19 Downward
1/27/19 None
1/26/19 None
1/25/19 Upward
</code></pre>
<p>I want to create a "Momentum" column based on the following conditions (starting at 1/25/19): <br> 1. If the Dire... | <p>Here is one way. I'll try to improve upon it after some coffee...</p>
<pre><code>df['Momentum:'] = None # Base case.
df.loc[df['Direction:'].eq('Upward'), 'Momentum:'] = 'Upward'
df.loc[df['Direction:'].eq('Downward'), 'Momentum:'] = 1 # Temporary value.
df.loc[:, 'Momentum:'] = df['Momentum:'].bfill()
df.loc[df... | python|pandas|dataframe|np | 2 |
371,479 | 58,557,961 | "Unknown graph" error when using keras application model with tf.functions | <p>This is my code:</p>
<pre><code>import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow.keras.applications.vgg16 as vgg16
tf.enable_eager_execution()
def resize_image(image, shape = (224,224)):
target_width = shape[0]
target_height = shape[1]
initial_width = tf.shape(image)[0]
initial... | <p>Facing the same issue. I've reported it here: <a href="https://github.com/tensorflow/tensorflow/issues/33997" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/33997</a></p> | tensorflow|machine-learning|deep-learning|google-colaboratory|tf.keras | 0 |
371,480 | 58,271,866 | Aggregate the data of multiple numpy files into one | <p>I have a list which contains 6 different sub-dataset of a dataset. I would like to perform 6 fold cross-validation. Therefore, in a for-loop of 6 steps each time to split my dataset into 2 groups (training that will contain the 5 sub-datasets and test set - contain the leave one sub-dataset). My code looks like:</p>... | <p>Alternatively to <a href="https://stackoverflow.com/a/58272174/2740563">Mason's</a> answer, you can use np.concatenate inside your crossValidFiles function so that whatever code in there is run on the aggregated test data.</p>
<pre><code>import numpy as np
def crossValidFiles(input_file):
data, labels = some_l... | python|numpy | 1 |
371,481 | 58,352,948 | Numpy: np.finfo does not fail as one would expect | <p>I am using numpy.iinfo and np.finfo to test whether a given type or value is corresponds to an integer or a float. There is a weird behaviour when dealing with <strong>None</strong>.</p>
<p>The following fails, as expected:</p>
<pre><code> np.iinfo(None)
</code></pre>
<p>Nevertheless</p>
<pre><code> np.finfo(Non... | <p>On a purely technical level we can explain what you are seeing by looking at the <a href="https://github.com/numpy/numpy/blob/9ae4f9bae9344ee0f1ca4d5767e49c196d534efc/numpy/core/getlimits.py" rel="nofollow noreferrer">source</a></p>
<p>The relevant snippet would be</p>
<pre><code>@set_module('numpy')
class finfo(o... | python|numpy|floating-point | 2 |
371,482 | 58,596,568 | replace Column with maximum string length based on frequency count in dataframe | <p>I have two columns: <code>freq</code> and <code>newname</code>. I want to replace newname with maximum string length word based on freq.
Code Which I tried :</p>
<pre><code> k = df['Newname'].to_list()
j = list(set(k))
for row in df.iterrows():
print(row)
if row==j[0]:
df.at[... | <p>Hope it helps!</p>
<pre><code>#Get name lengths
df['name_len'] = df['name'].apply(lambda x : len(x))
#Get variables
max_freq = df['freq'].max()
max_len = df['name_len'].max()
#Apply Filters
filter1 = df[df['name_len'] == max_len].reset_index(drop=True)
filter2 = filter1[filter1['freq'] == max_freq].reset_index(dr... | python|pandas|dataframe | 0 |
371,483 | 58,339,044 | Find the most relevant columns for each single class in pandas | <p>The following question (<a href="https://stackoverflow.com/questions/37055978/how-to-find-most-relevant-dimensions-columns-to-separate-known-classes">this one</a>) did not help me.</p>
<p>I have a big dataset, and I want to know which Columns are the most relevant for the Target Variable. I know that, in my case, f... | <p>You could train a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html" rel="nofollow noreferrer">RandomForest classifier</a> for each of your target variables (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html" r... | python|pandas|data-science | 0 |
371,484 | 58,440,980 | Using Pandas Style I get KeyError: "None of .... are in the [columns] | <p>I build a dataframe using </p>
<pre><code> result = pd.concat([dmicao,dms,dmtime,dmdt,dmwd,dmws,dmwg,dmfc,dmvis,dmch,dmcl,dmwx,dmov], axis=1)#, sort=False)
headers = ['icao','msg_type','time','dt','ddd','ff','gg','flt_cat','vis','cld_hgt','cld_type','present_wx','vis_obc']
result.columns = headers
... | <p>You should pass only the column name in your subset variable. Also, your function should return a list with the same length as your column. </p>
<pre class="lang-py prettyprint-override"><code>def _color_red_or_green(val):
conditions = val > 2500
results = []
for v in conditions:
if v:
... | python|html|pandas|styles|keyerror | 1 |
371,485 | 58,464,636 | How to create Date and Hour columns from Seconds column using SQL | <p>I have a column called <code>Time</code> with float values giving time in seconds after the first event occurred. I was wondering how to create columns called <code>Date</code> and <code>Hour</code> using this column in SQL.</p>
<p>My dataset is big, I can not use Pandas.</p>
<h1>Setup</h1>
<pre><code>import nump... | <p>You can use functions: <a href="https://spark.apache.org/docs/2.4.0/api/sql/index.html#timestamp" rel="nofollow noreferrer">timestamp</a>, <a href="https://spark.apache.org/docs/2.4.0/api/sql/index.html#unix_timestamp" rel="nofollow noreferrer">unix_timestamp</a> and <a href="https://spark.apache.org/docs/2.4.0/api/... | python|sql|pandas|apache-spark|pyspark | 5 |
371,486 | 58,417,771 | Read multiple CSV files then rename files based on the filenames | <p>Currently the below code reads all the csv files in the path, then saved in a list.</p>
<p>I want to save each dataframe with the name of the filename e.g. echo.csv</p>
<pre><code>path = r'M:\Work\Experimental_datasets\device_ID\IoT_device_captures\packet_header_features' # use your path
all_files = glob.glob(os.p... | <p>As you mentioned a dictionary would be useful for this task. For example:</p>
<pre><code>import os
all_files = glob.glob(os.path.join(path, "*.csv"))
df_dict = {}
for filename in all_files:
df = pd.read_csv(filename, skiprows=15, sep='[|]',
skipfooter=2, engine='python', header=None,
names=["... | python|pandas|dataframe | 2 |
371,487 | 58,527,815 | How to preprocess and feed data to keras model? | <p>I have a dataset with two columns, path and class. I'd like to fine tune VGGface with it. </p>
<pre><code>dataset.head(5):
path class
0 /f3_224x224.jpg red
1 /bc_224x224.jpg orange
2 /1c_224x224.jpg brown
3 /4b_224x224.jpg red
4 /0c_224x224.jpg yellow
</code></pre>
<p>I'd like to use the... | <p>X_train, X_test are basically just path names it seems. In your data preparation step you just need to modify your code like that adding those last two lines.</p>
<pre><code>from sklearn.model_selection import train_test_split
path = list(dataset.columns.values)
path.remove('class')
X = dataset[path]
y = dataset['... | python-3.x|tensorflow|machine-learning|keras|computer-vision | 3 |
371,488 | 58,201,084 | How to transform multiple dataframe columns into one numpy array column | <p>I have a dataframe like below </p>
<pre><code>from pyspark import SparkContext, SparkConf,SQLContext
import numpy as np
config = SparkConf("local")
sc = SparkContext(conf=config)
sqlContext=SQLContext(sc)
df = sqlContext.createDataFrame([("doc_3",1,3,9), ("doc_1",9,6,0), ("doc_2",9,9,3) ]).withColumnRenamed("_1",... | <p>Unfortunately you cannot make <code>numpy.array</code> column in pyspark dataframe, but you can use regular <code>python</code> list instead, and convert it while reading:</p>
<pre class="lang-py prettyprint-override"><code>>>> df = sqlContext.createDataFrame([("doc_3",[1,3,9]), ("doc_1",[9,6,0]), ("doc_2"... | numpy|pyspark|pyspark-dataframes | 1 |
371,489 | 58,313,139 | Trying to read a .tsv file where the first few lines contain an amount of fields different to the rest of the file | <p>I am currently trying to read a tsv file containing a large amount of data to process later using python. Problem is, the first few lines of these tsv files follow a format (I'm not sure how to phrase it) that is different from the actual data. </p>
<p>Here is an example of what I mean:</p>
<pre class="lang-none p... | <p>As mentioned in the comments there is a skiprows option in read_csv:</p>
<pre><code>raw_data = pd.read_csv(r'filename.tsv', skiprows = 4)
</code></pre>
<p>This will skip the first 4 lines in the file</p>
<p>EDIT to read the first 3 lines, you can do this in 2 separate reads:</p>
<pre><code>df1 = pd.read_csv(r'fi... | python|pandas|dataframe | 2 |
371,490 | 58,328,075 | Add column for squares/cubes/etc for each column in numpy/pandas | <p>I’m trying to take a set of data that consists of N rows, and expand each row to include the squares/cube/etc of each column in that row (what power to go up to is determined by a variable j). The data starts out as a pandas DataFrame but can be turned into a numpy array.</p>
<p>For example:
If the row is [3,2] and... | <p>Use NumPy broadcasting for a vectorized solution -</p>
<pre><code>In [66]: a = np.array([3,2])
In [67]: j = 3
In [68]: a**np.arange(1,j+1)[:,None]
Out[68]:
array([[ 3, 2],
[ 9, 4],
[27, 8]])
</code></pre>
<p>And there's a NumPy builtin : <a href="https://docs.scipy.org/doc/numpy/reference/gener... | python|pandas|numpy|dataframe|regression | 2 |
371,491 | 58,262,052 | Drop pandas rows for entire group based on condition | <pre><code>import seaborn
df = seaborn.load_dataset('flights')
</code></pre>
<p>I want to drop the years where the number of average passengers per year is less than 200. I tried this</p>
<pre><code>df[df.groupby(['year'])['passengers'].mean() > 200]
</code></pre>
<p>but get this error:</p>
<pre><code>*** panda... | <p>I think, you need to:</p>
<ul>
<li><strong>group</strong> by <em>year</em>,</li>
<li><strong>filter</strong> groups, checking whether the mean of <em>passengers</em> in the
current group is > 300.</li>
</ul>
<p>So the code should be:</p>
<pre><code>df.groupby(['year']).filter(lambda x: x.passengers.mean() > 30... | python|pandas | 1 |
371,492 | 58,345,641 | pandas to_datetime convert 6PM to 18 | <p>is there a nice way to convert Series data, represented like 1PM or 11AM to 13 and 11 accordingly with <code>to_datetime</code> or similar (other, than <code>re</code>)</p>
<p>data:</p>
<pre><code>series
1PM
11AM
2PM
6PM
6AM
</code></pre>
<p>desired output:</p>
<pre><code>series
13
11
14
18
6
</code></pre>
<p>... | <p>You can provide the format you want to use, with as format <code>%I%p</code>:</p>
<pre><code>pd.to_datetime(df['series']<b>, format='%I%p'</b>)<b>.dt.hour</b></code></pre>
<p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.hour.html" rel="nofollow noreferrer"><strong><code>... | pandas | 2 |
371,493 | 58,455,206 | Cannot find the variable that is input to the ReadVariableOp | <p>Trying to save a Keras .h5 file containing weights to Tensorflow .pb file</p>
<pre><code># I keep getting the error: ValueError: Cannot find the variable that is an input to the ReadVariableOp.
frozen_graph = freeze_session(K.get_session(),
output_names=[out.op.name for out in model.k... | <p>I just ran into this same issue, adding </p>
<pre class="lang-python prettyprint-override"><code>import keras.backend as K
k.set_learning_phase(0)
</code></pre>
<p>which sets the learning phase to testing mode, was the solution. </p> | python|tensorflow|keras|protocol-buffers | 3 |
371,494 | 58,561,265 | can pandas autocorr handle irregularly sample timeseries data? | <p>I have a dataframe with datetime index, where the data was sampled irregularly (the datetime index has gaps, and even where there aren't gaps the spacing between samples varies).</p>
<p>If I do:</p>
<p>df['my column'].autocorr(my_lag)</p>
<p>will this work? Does autocorr know how to handle irregularly sampled da... | <p>This is not quite a programming question.</p>
<p>Ideally, your measure of autocorrelation would use data measured at the same frequency/same time interval between observations. Any autocorr function in any programming package will simply measure the correlation between the series and whatever lag you want. It wil... | python|pandas|autocorrelation | 0 |
371,495 | 58,562,582 | Default MaxPoolingOp only supports NHWC on device type CPU | <p>I tried to run a prediction on a SegNet model, but when the predict function its call I received an error.</p>
<p>I tried also to run the prediction with the <code>with tf.device('/cpu:0'):</code>, but I received the same error</p>
<pre class="lang-py prettyprint-override"><code>if __name__ == '__main__':
# pa... | <p>Without <code>test4.jpg</code> it's difficult to test solutions. However, the error <code>Default MaxPoolingOp only supports NHWC on device type CPU</code>
means that the model only can accept inputs of the form n_examples x height x width x channels.
I think your <code>cv2.resize</code> and subsequent <code>np.resh... | python|tensorflow|keras | 7 |
371,496 | 58,368,591 | Cannot read an Excel file in pandas | <p>I am using Juypter which I launch from the same directory which contains the notebook and Excel file. I use the following commands:</p>
<pre><code>import pandas as pd
!ls # Returns the contents of the working directory. Use "dir" in a Windows.
</code></pre>
<p>Which returns:</p>
<p>Book1.xlsx<br>
common... | <p>You should install <code>xlrd</code> dependence.</p>
<p><code>pip install xlrd</code> should do the trick for you.</p>
<p>Hope this helps!</p> | python|pandas|jupyter-notebook | 6 |
371,497 | 58,490,878 | pandas.to_datetime() automatically converting to <M8[ns] and unable to use numpy.isnat() | <p>I have a dataframe that was read as a string containing a date in the format "YYYY-MM-DD". I had converted the column to datetime using pd.to_datetime (with coerce) and I'm intending to search the column for NaTs using numpy.isnat(). </p>
<pre><code>defaultDate = datetime.datetime(2020, 12, 31)
df['dates'] = pd.to_... | <p><code><M8[ns]</code> is a synonym for <code>datetime64[ns]</code>. Also, you don't need <code>np.isnat</code> if you are dealing with pandas <code>datetime</code>:</p>
<pre><code>defaultDate = pd.to_datetime('2020-12-31')
df['newDates'] = [x if ~np.isnat(x) else defaultDate for x in df['dates']]
df['newDates'] =... | python|pandas|numpy|dataframe | 3 |
371,498 | 58,459,065 | if list contains any of list return matching string | <p>I'm trying to create a new column that compares two lists and returns the matching string. </p>
<p>I keep getting the error "'list' object has no attribute 'find'". </p>
<p>I'm still a novice at this so any help would be really appreciated!</p>
<p>I'm trying to use python and pandas for this</p>
<p>What I have s... | <p>There is no "find" method or property in the list type (brandnames), so Python is throwing an error. For a quick check of the available properties and methods in a type, you can use <code>dir()</code>, e.g.:</p>
<pre><code>>>> x = ['abc', 'def']
>>> dir(x)
['__add__', '__class__', '__contains__', ... | python|pandas | 0 |
371,499 | 58,463,867 | Function not returning the correct amount of observations | <p>I am trying to create a function to show the <code>n</code> number of movies most rated by a user in a given dataframe. I have been able to extract the movies the user provided rating for but I cannot return the correct amount of rows - instead it prints all the movies with rating from the user.</p>
<p>I have tried... | <p>I'm not sure what exactly, you want to achieve, but check this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
{
'user_id': [1, 1, 1, 2, 2, ],
'title': ['t1', 't2', 't3', 't1', 't5'],
'rating': [25, 25, 35, 25, 30,],
})
df.sort_values(by='rating', ascending=Fals... | python|pandas | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.