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 |
|---|---|---|---|---|---|---|
360,200 | 52,711,790 | DataFrame column compare | <p>I'm a beginner to python and am having a hard time finding documentation on how to fix a problem I've come across.</p>
<p>I need to know if the values in df1['id'] are in df2['id_list'] but hit a snag when I saw how the values were stored in df2</p>
<p>when I export the values which creates my "id_list" series, it... | <p>For this kind of string problem, often list comprehensions are faster than built-in <code>pandas</code> string methods. You can do something like this:</p>
<pre><code>desired_df = df1.join(df2)
desired_df['located'] = [i1 if i1 in i2 else False for i1, i2 in zip(df1['id'], df2['id_list']) ]
>>> desired_d... | python|regex|pandas|merge | 2 |
360,201 | 52,765,320 | Pandas Datetime conversion | <p>I have the following dataframe;</p>
<pre><code>Date = ['01-Jan','01-Jan','01-Jan','01-Jan']
Heure = ['00:00','01:00','02:00','03:00']
value =[1,2,3,4]
df = pd.DataFrame({'value':value,'Date':Date,'Hour':Heure})
print(df)
Date Hour value
0 01-Jan 00:00... | <p>You need to explicitely add <code>2015</code> somehow, and include the <code>Hour</code> column as well. I would do something like this:</p>
<pre><code>df.index = pd.to_datetime(df.Date + '-2015 ' + df.Hour, format='%d-%b-%Y %H:%M')
>>> df
Date Hour value
2015-01-01 00:00:00 01-... | pandas|datetime | 1 |
360,202 | 52,623,197 | How to modify the values in a dataframe based on the values from another dataframe in an efficient way? | <p>I have 2 dataframes like so:</p>
<pre><code>import pandas as pd
data1 = {'Col1':['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
'Col2':[3.409836, 2.930693, 2.75, 3.140845, 2.971429, 2.592593, 2.6, 3.1875, 2.857143, 0.714286]}
df1 = pd.DataFrame(data1, columns=['Col1', 'Col2'])
data2 = {'Col1':['B', 'F'... | <p>If working only with one column use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a>:</p>
<pre><code>df1['Col2'] = df1['Col1'].map(df2.set_index('Col1')['Col2']).fillna(df1['Col2'])
print (df1)
Col1 Col2
0 A 3.409836
1... | python|pandas|dataframe|join|merge | 1 |
360,203 | 52,775,450 | Converting Values of series with dictionary values to DataFrame. Not the Series itself | <p>I have series which looks like this:</p>
<pre><code>d1 = {'Class': 'A', 'age':35, 'Name': 'Manoj'}
d2 = {'Class': 'B', 'age':15, 'Name': 'Mot'}
d3 = {'Class': 'B', 'age':25, 'Name': 'Vittoo'}
ser = [d1, d2, d3]
dummy = pd.Series(ser)
dummy
0 {'Class': 'A', 'age': 35, 'Name': 'Manoj'}
1 {'Class': 'B', 'ag... | <p>Use <code>DataFrame</code> constructor instead <code>Series</code> constructor:</p>
<pre><code>d1 = {'Class': 'A', 'age':35, 'Name': 'Manoj'}
d2 = {'Class': 'B', 'age':15, 'Name': 'Mot'}
d3 = {'Class': 'B', 'age':25, 'Name': 'Vittoo'}
ser = [d1, d2, d3]
df = pd.DataFrame(ser)
print (df)
Class Name age
0 ... | python|python-3.x|pandas | 2 |
360,204 | 52,575,354 | How can I get a frequency count of values delimited by comma in a pandas dataframe column? | <p>Let's say I'm trying to create a count vector of a some stackoverflow metadata (not actually what I'm doing but similar). So the DataFrame could look something like this:</p>
<pre><code>question: description: tags:
Q1 desc1 java, android
Q2 desc2 python, machine l... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="noreferrer"><code>str.split</code></a> by regex <code>,s\+</code> for comma with one or more whitespaces, then create <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pan... | python|pandas|dataframe | 5 |
360,205 | 52,897,985 | Extract data from pandas data frame | <p>I want to create a list of data frames from a bigger data frame based on column value. The column <code>"ID"</code> can repeat for example <code>1,2,3,1,2,3,4,5,1,2</code>. </p>
<p>I want to create a list of data frames by extracting the rows until when the ID repeats over again back to 1. In this case the list sho... | <p>No need for loops.</p>
<pre><code>>>> list(zip(*df.groupby(df.ID.diff().ne(1).cumsum())))[1]
</code></pre> | python-3.x|pandas|pandas-groupby | 4 |
360,206 | 52,787,372 | TensorFlow: Add dimension (column) with constant value | <p>I have a Tensor of shape <code>(-1,)</code> which represents a list of indices. I want to create a Tensor of shape <code>(-1,2)</code>. The first column should be the same as the list of indices, while the second column should be filled with a constant.</p>
<p>Eg (let's say the constant is 6):</p>
<pre><code>indices... | <p>You can use <code>tensorflow.pad</code>. But first you have to make it a two dimensional tensor.</p>
<pre><code>indices = tf.constant([1,2,3,4])
indices = tf.expand_dims(tf, 1) # now you have a (4,1) tensor
padding = [[0,0],[0,1]] # no padding before or after the first dimension
# no paddin... | python|tensorflow | 3 |
360,207 | 52,666,677 | Python date time formatting - String to a specified format | <p>I am looking to convert raw string to a specified data time format. </p>
<p>Here's the sample data: </p>
<pre><code>0 47 mins
1 1 hour 25 mins
2 1 hour 27 mins
3 6 mins
</code></pre>
<p>Is the above one of the supported date time formats in python that can be transformed usi... | <p>You have 2 potential formats, so you can try them each:</p>
<pre><code>s = pd.Series(['47 mins', '1 hour 25 mins', '1 hour 27 mins', '6 mins'])
dt1 = pd.to_datetime(s, format='%H hour %M mins', errors='coerce')
dt2 = pd.to_datetime(s, format='%M mins', errors='coerce')
res = dt1.fillna(dt2).dt.strftime('%H:%M')
... | python|pandas|datetime | 3 |
360,208 | 52,475,010 | How to create a group by spliting the dataframe using python | <p>My dataframe:</p>
<pre><code> df:
order quantity
A 1
B 1
C 2
D 3
E 3
F 4
</code></pre>
<p>My goal is to create a group from this Dataframe based on the Quantity value.
My desired res... | <p>@AnnaIliukovich-Strakovskaia solution is awesome. I re-wrote it using pure pandas.</p>
<pre><code>#Generate input dataframe from @AnnaIliukovich-Strakovskaia
df = pd.DataFrame({'order':['A', 'B', 'C', 'D', 'E', 'F'],'quantity':[1,1,2,3,3,4]})
#Expand dataframe
df_out = df.order.repeat(df.quantity).reset_index(dro... | python|pandas | 2 |
360,209 | 52,538,405 | simple usecase if numpy.delete() is not working | <p>here is some code:</p>
<pre><code>c = np.delete(a,b)
print(len(a))
print(a)
print(len(b))
print(b)
print(len(c))
print(c)
</code></pre>
<p>it gives back:</p>
<pre><code>24
[32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55]
20
[46, 35, 37, 54, 40, 49, 34, 48, 50, 38, 42, 47, 33, 52, 41, 36, ... | <p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html" rel="nofollow noreferrer"><code>numpy.delete</code></a> does not remove the elements contained in <code>b</code>, it deletes <code>a[b]</code>, in other words, <code>b</code> needs to contain the indices to remove. Since your <code>b</... | python|numpy | 1 |
360,210 | 52,859,688 | Data is a column containing titles and subsections, how to split it? | <p>I have a list of strings that looks like this:</p>
<pre><code>'A[title]'
'a'
'b'
'c'
'B[title]'
'd'
'C[title]'
'e'
'f'
...
</code></pre>
<p>Where each block is separated by a title marked with 'title'.
I need to separate these blocks and format it like this:</p>
<pre><code>'A[title]' ,'a'
'A[title]' ,'b'
'A[title... | <p>You can do it with <code>str.contains</code> and <code>ffill</code></p>
<pre><code>data=data.to_frame('ori')
data['title']=data.ori[data.ori.str.contains('title')]
data=data.ffill().loc[lambda x : x.ori!=x.title]
data
Out[499]:
ori title
1 a A[title]
2 b A[title]
3 c A[title]
5 d B[title]
7 e ... | python|pandas | 4 |
360,211 | 52,831,934 | Categorical and continuous cross feature column in Tensorflow | <p>In using Tensorflow's estimators and <code>feature_column</code> it is possible to cross a categorical column and a bucketed continuous column <a href="https://www.tensorflow.org/guide/feature_columns#crossed_column" rel="nofollow noreferrer">crossed column</a> but not a categorical and numeric cross. Could it be po... | <p>To answer my own question here. The steps involved are: </p>
<ol>
<li>Numerically encoding the categorical feature
<ul>
<li>Within the graph so it's possible within train and serve</li>
</ul></li>
<li>One hot encoding the numerical result</li>
<li>Multiplying this with the continuous variable</li>
</ol>
<p>Code:... | python|python-3.x|tensorflow | 1 |
360,212 | 52,883,177 | GPU compatibility with tensorflow installation | <p>New in the field of Deep Learning.</p>
<p>I need to install Tensorflow with GPU support. Before I purchase GPU I need to know like GPU is compatible with Tensorflow or not. In the Tensorflow installation page, with option Tensorflow with GPU below are the software requirements.</p>
<p>The following NVIDIA® softwar... | <p>For compatibility with Nvidia drivers
Visit website: <a href="https://www.nvidia.com/object/unix.html" rel="nofollow noreferrer">https://www.nvidia.com/object/unix.html</a>
Click on driver, which you are interested in. In your case it is 390.87 and 410.73 click on SUPPORTED PRODUCTS. If there is your GPU you are ok.... | tensorflow|gpu | 0 |
360,213 | 52,771,198 | Multiply DataFrame by Different shape DataFrame (or series) | <p>I have this DataFrame like this:</p>
<pre><code>1 2 1 3 1 4
2 4 5 1 1 4
1 3 5 3 1 4
1 3 1 3 1 4
</code></pre>
<p>Another like this</p>
<pre><code>1 1 0 0 0 0
</code></pre>
<p>I want to multiply them such as that I get</p>
<pre><code>1 2 0 0 0 0
2 4 0 0 0 0
1 3 0 0 0 0
1 ... | <p>It's probably easiest to use the underlying arrays, and let <code>numpy</code> do it's broadcasting magic:</p>
<pre><code>>>> df1.values * df2.values
array([[1, 2, 0, 0, 0, 0],
[2, 4, 0, 0, 0, 0],
[1, 3, 0, 0, 0, 0],
[1, 3, 0, 0, 0, 0]])
</code></pre>
<p>You can put it back into a dat... | python|pandas|numpy|array-broadcasting | 5 |
360,214 | 52,874,647 | Tensorflow v1.10+ why is an input serving receiver function needed when checkpoints are made without it? | <p>I'm in the process of adapting my model to TensorFlow's estimator API. </p>
<p>I recently asked a question regarding <a href="https://stackoverflow.com/questions/52641737/tensorflow-1-10-custom-estimator-early-stopping-with-train-and-evaluate/52642619#52642619">early stopping based on validation data</a> where in a... | <h2>What is the difference between a checkpoint and an exported best model?</h2>
<p>A checkpoint is, at its minimum, a file containing the values of all the variables <em>of a specific graph</em> taken at a <em>specific time point</em>.
By specific graph I mean that when loading back your checkpoint, what TensorFlow d... | python|tensorflow | 16 |
360,215 | 52,596,891 | How to score model saved using Tensorflow estimator? | <p>All,</p>
<p>I built a customized model for binary image classification. I managed to successfully save model using tf estimator to .pb format. My jpg image files have images in various sizes, so I have a image transformation step to transform the images to 224x224. Here is how I define serving_input_fn():</p>
<pre... | <p>I figured it out... </p>
<p>All the image transformation inside the map function were built to the output graph already. In the scoring script, just need to encode image name string to bytes, then use this as input. </p>
<pre><code>model_input=tf.train.Example(features=tf.train.Features(feature={'image/encoded':_b... | python|tensorflow | 0 |
360,216 | 52,786,431 | DecodeJpeg / Content: 0 'refers to a tensor that does not exist | <p>After retraining my model on tensorflow by following method in the tutorial video by Siraj Raval
<a href="https://www.youtube.com/watch?v=QfNvhPx5Px8" rel="nofollow noreferrer">https://www.youtube.com/watch?v=QfNvhPx5Px8</a></p>
<p>I encountered the below error when i finally tested my test image but it generated ... | <p>DecodeJpeg/Contents:0 is supposed to be a tensor, and you want to feed data to it, so you consider it as an input. Problem is that it doesn't exist, this probably means that you made a small mistake in the naming.
run this before the sess.run(something, {"DecodeJpeg/Contents:0": something})</p>
<pre><code>tf.summar... | python|docker|tensorflow|machine-learning|classification | 1 |
360,217 | 52,584,378 | How to execute inference of tensorflow model in Android | <p>I tried use Tensorflow Lite, but it has lots of limitations, it doesn't have batch normalization operation, and even with simple operations it gave a very strange result to the same data tested with Keras. It means with keras everything works, with tensorflow lite, the result is completely wrong. So I need something... | <p>You can use the <code>TensorFlowInferenceInterface</code> to make predictions using a .pb file. First, place the .pb file in your app's assets folder.</p>
<ol>
<li>In your build.gradle(Module: app) file, add the following dependency,
<code>implementation 'org.tensorflow:tensorflow-android:1.11.0'</code></li>
<li>Th... | android|tensorflow|neural-network|tensorflow-lite | 2 |
360,218 | 52,467,838 | Pandas add new column and fill it with item from list when tuple of other 2 columns is unique | <p>I am currently trying to add some values of a list to a new column in my pandas table.
First value of <code>col3</code>is the first of the list. Second value is the same in case the tuple of <code>col1</code>and <code>col2</code>is still the same.
Condition to start adding the next item of the list is that it is a n... | <p>Here's an alternative method. You can use Pandas to create a new dataframe of unique rows (maintaining order) and assign a new column. Then merge this with your original dataframe:</p>
<pre><code>res = df.merge(df.drop_duplicates().assign(col3=list1))
print(res)
col1 col2 col3
0 1 1 5
1 1 ... | python|pandas|list|multiple-columns | 3 |
360,219 | 52,799,088 | Python - How to generate a Gaussian Random Vector using Scipy.Stats.Multivariate_Normal | <p>I want to do the same thing as </p>
<pre><code>x = np.random.multivariate_normal(mean, cov, (n, 1))
</code></pre>
<p>where mean is a vector with length n and cov is a square nxn matrix, but with scipy.stats.multivariate_normal instead</p> | <p>To sample from a distribution in <code>scipy.stats</code> use the <code>.rvs</code> method.</p>
<p>Example:</p>
<pre><code>>>> from scipy import stats
>>>
>>> n = 3
>>> mn = np.random.random(n)
>>> cov = np.random.random((2*n, n)) - 0.5
>>> cov = cov.T@cov
>... | python|numpy|scipy|gaussian | 0 |
360,220 | 52,762,825 | How to train model created with tf.Keras model using tf.train? | <p>I am creating a GAN using Tensorflow. I decided to make Generator and Discriminator using Keras as layers became complex (since defining layers in Keras is easier). I have loss and training code for GAN in Tensorflow but I don't know how to train Keras model using that.</p>
<pre><code>D_loss_real = tf.reduce_mean(t... | <p><a href="https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html" rel="nofollow noreferrer">This article will help.</a> Basically, you just need to set your Keras session same as your Tensorflow.</p> | python|tensorflow|machine-learning|keras|deep-learning | 0 |
360,221 | 52,807,958 | Creating Dataframe from Dictionary of Lists, ignoring keys | <p>i have dictionary of lists that looks like this</p>
<pre><code>d = {'key1':['banana','apple','mango'],
'key2':['banana','orange'],
'key3':['apple','melon','orange','mango']}
</code></pre>
<p>Now, I want to create Dataframe from it. The dataframe must look like this</p>
<pre><code> 'banana' | 'apple' | ... | <p>You're looking for <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html" rel="nofollow noreferrer"><code>from_dict</code></a> with <code>orient='index'</code>:</p>
<pre><code>pd.DataFrame.from_dict(d, orient='index')
</code></pre>
<p></p>
<pre><code> 0 1 ... | python|pandas|dictionary|dataframe | 1 |
360,222 | 52,743,774 | Python code has no error but it does not run or output anything | <p>I copied a piece of code online. When I run it, it shows no error, but it did not output anything. Can anyone help me with this? I am new to python. I was running it in Spyder. Is there any way to see where the problems are? ... I tried some other script in this environment and they work fine.
Here is the script:</p... | <p>Code works well with python2.7 and changing your code with (removed extra whitespace):</p>
<pre><code>if __name__ == '__main__':
print('hello')
main()
</code></pre>
<p>For these kind of problems don't hesitate to use a debugger. PyCharm for example <a href="https://www.jetbrains.com/pycharm/" rel="nofollow... | python|python-3.x|numpy | 1 |
360,223 | 52,602,775 | Convert data frame to array with column header | <p>I want to convert a dataframe:</p>
<p><a href="https://i.stack.imgur.com/KdBMV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KdBMV.png" alt="enter image description here"></a></p>
<p>to array without losing the header column like this:</p>
<p><a href="https://i.stack.imgur.com/mKIRX.png" rel=... | <p>What you're looking for is a way to turn the DataFrame into a structured array, you can find the instructions to do this in the question here <a href="https://stackoverflow.com/questions/46837472/converting-pandas-dataframe-to-structured-arrays">Converting pandas dataframe to structured arrays</a></p> | python|arrays|pandas|numpy | 0 |
360,224 | 52,594,544 | Pandas: Replacing '-' when used as a zero but not when used as a negative | <p>I am reading a csv file into a pandas dataframe.</p>
<pre><code>df= pd.read_csv("table.csv", encoding = 'ISO-8859-1')
</code></pre>
<p>I have a column named 'value' which contains '-' when the value is nil. My aim is to filter out all rows where the value in this column is nil.</p>
<p>However the sign is also co... | <p>As pointed out by @Allolz, to get rid of your <code>,</code> thousands separator, use the <code>thousands</code> argument in <code>pd.read_csv()</code>:</p>
<pre><code>df= pd.read_csv("table.csv", thousands=',', encoding = 'ISO-8859-1')
</code></pre>
<p>If I understand correctly, the easiest thing to do is to use ... | python|pandas|dataframe | 5 |
360,225 | 52,673,708 | Pandas Timestamp(year=2011, month=8, day=1) returns last day of month | <p>Wanted to create a time range from August 1, 2011 dynamically to the last month of the existing data. Don't know why I'm returning time series with the last day of the month instead of the first. </p>
<p>Any suggestions? Please ignore my petty comments to my coworkers. </p>
<pre><code># Our Formatting System i... | <p>By using the freq <code>M</code>, you are telling it to use month's end. See <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases" rel="nofollow noreferrer">this link</a> for a description of datetime offsets in pandas, but in short <code>M</code> is </p>
<blockquote>
<p>month end f... | python|pandas | 2 |
360,226 | 52,640,065 | Remove numpy rows contained in a list? | <p>I have a numpy array and a list. I want to remove the rows contained in the list.</p>
<pre><code>a = np.zeros((3, 2))
a[0, :] = [1, 2]
l = [(1, 2), (3, 4)]
</code></pre>
<p>Currently I try to do this by making a set of <code>a</code>'s rows, then exclude the <code>set</code> created from <code>l</code>, something ... | <p><strong>Approach #1 :</strong> Here's one with <code>views</code> (viewing each row as an element each with extended dtype) -</p>
<pre><code># https://stackoverflow.com/a/45313353/ @Divakar
def view1D(a, b): # a, b are arrays
a = np.ascontiguousarray(a)
b = np.ascontiguousarray(b)
void_dt = np.dtype((np... | python|arrays|performance|numpy|set | 1 |
360,227 | 52,770,164 | how to flatten (n, ) shape numpy array | <p>I have a variable called data, and i want to flatten it. </p>
<p>Right now <code>data.shape = (10, )</code>. Each element in data has a shape (5000, 64). I want to make my <code>data.shape = (10, 5000, 64)</code>. </p>
<p>How can I do that? I've tried many below, but none of them work:</p>
<pre><code>b = np.conca... | <pre><code>In [50]: t = np.zeros(3,object)
In [51]: t[0]=np.ones((3,2),int)
In [52]: t[1]=np.ones((3,2),int)
In [53]: t[2]=np.ones((3,2),int)
In [54]: t
Out[54]:
array([array([[1, 1],
[1, 1],
[1, 1]]),
array([[1, 1],
[1, 1],
[1, 1]]),
array([[1, 1],
[1, 1],
[1, 1... | python|numpy | 0 |
360,228 | 52,762,791 | Group by 3 columns and find max/min according to 4th? | <p>I want to group by <code>col1</code> , <code>col2</code> and <code>col4</code> and find the max and min of each group according to <code>col3</code></p>
<pre><code>import pandas as pd
d = {'col1': [1,1,2,3,3,4,4,4,5,5,5,6,6,6,7,7],
'col2': ['w', 'w','w','w','w','e','e','e','e','e','e','t','t','t','t','t'],
... | <p>You have to pass a list of columns on which you want to process group by and define a name to new column</p>
<pre><code>df.groupby(['col1','col2','col4'])['col3'].max().reset_index(name ='Max')
</code></pre>
<p>Output</p>
<pre><code>col1 col2 col4 Max
1 w 5 4
2 w 6 1
3... | python|pandas|group-by | 0 |
360,229 | 52,688,897 | how to guess file encoding | <p>I have a file (an author list from the Library of Congress) with lines like:</p>
<pre><code>Arteaga, Ana Mar�ia
Corval�an-V�asquez, Oscar E.
</code></pre>
<p>(when printed to linux console) </p>
<p>I'd like to read those (either into a pandas dataframe or a set of lines)</p>
<pre><code> df = pd.read_csv(fname,... | <p>Ok this seems to be the '<a href="https://en.wikipedia.org/wiki/MARC-8" rel="nofollow noreferrer" title="marc-8">marc-8</a>' format .</p>
<pre><code>yaz-iconv -f marc8 -t utf8 infile.txt > outfile.txt
</code></pre>
<p>took care of the conversion to utf8 , with the sole hiccup being that yaz killed all the line... | pandas|utf-8|iso-8859-1 | 0 |
360,230 | 52,732,364 | Pandas any() returning false with true values present | <p>I have a largely empty dataframe of poorly formatted dates that I converted into DateTime format.</p>
<pre><code>from io import StringIO
data = StringIO("""issue_date,issue_date_dt
,
,
19600215.0,1960-02-15
,
,""")
df = pd.read_csv(data, parse_dates=[1])
</code></pre>
<p>Which produces</p>
<pre><code> issue_... | <p>I'm not entirely sure <em>why</em> this is occuring<sup>[1]</sup>, my best guess is that the differing datatypes along the first axis cause this unexpected result, as <code>any</code> works as expected along axis <code>0</code>. <em>However</em>, I would argue that the workaround to this is actually a better approa... | python|pandas|datetime | 7 |
360,231 | 52,870,891 | return a dataframe but got difference when using it in another function | <p>I'd like to use a dataframe in <code>function_B</code>which is produced by function_A</p>
<pre><code>def function_A():
df = pandas.DataFrame(data,columns=['A'])
return df
def function_B():
df1 = function_A()
if __name__ == '__main__':
function_A()
function_B()
</code></pre>
<p>However, <code>df1</... | <p>It is not empty. Just fix <code>function_B</code>:</p>
<pre><code>def function_B():
df1 = function_A()
return df1
</code></pre>
<p>And of course <code>id(function_A())</code> and <code>id(function_B())</code> are not equal (e.g. dataframes are not the same object because you create a new <code>Dataframe</c... | python|pandas|dataframe | 0 |
360,232 | 52,735,334 | Python - Pandas, Resample dataset to have balanced classes | <p>With the following data frame, with only 2 possible lables:</p>
<pre><code> name f1 f2 label
0 A 8 9 1
1 A 5 3 1
2 B 8 9 0
3 C 9 2 0
4 C 8 1 0
5 C 9 1 0
6 D 2 1 0
7 D 9 7 0
8 D 3 1 0
9 E 5... | <p>A very simple approach. Taken from sklearn documentation and Kaggle.</p>
<pre><code>from sklearn.utils import resample
df_majority = df[df.label==0]
df_minority = df[df.label==1]
# Upsample minority class
df_minority_upsampled = resample(df_minority,
replace=True, # sample wi... | python|pandas|numpy|machine-learning|dataset | 9 |
360,233 | 52,578,576 | Cannot import tensorflow-gpu | <p>I have tried to import tensorflow-gpu and I'm getting the same error with different versions of CUDA and cuDNN.
My GPU is compatible with CUDA and I have no problems installing but when I try to import tensorflow-gpu I got this:</p>
<p>ImportError: DLL load failed: No se puede encontrar el módulo especificado.</p>
... | <p>Try running these commands in your cmd window</p>
<pre><code>SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;%PATH%
SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\extras\CUPTI\lib64;%PATH%
SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\include;%PATH%
SET... | python|windows|tensorflow | 0 |
360,234 | 52,901,160 | How do I loop through an array python with apply? | <h2>My question is, how can I do it without using more than one for-loop?</h2>
<hr>
<pre><code>#Example:
#samples : [0.1, -0.3]
#return : [0.5, -0.5]
import numpy as np
vq = np.array([-1.5,-0.5,0.5,1.5])
vd = np.array([-1,0,1,2])
samples = [0.1,-0.3]
k = []
g = []
for t in range(len(vq)):
if(i[t] ... | <p>Are you looking for something like (1 for-loop in a list comprehension):</p>
<pre><code>In []:
[vq[np.where(vd > x)][0] for x in samples]
Out[]:
[0.5, -0.5]
</code></pre>
<p>No <code>for</code> loops (not recommended!!!):</p>
<pre><code>In []:
np.vectorize(lambda x: vq[np.where(vd > x)][0])(samples)
Out[]... | python|arrays|loops|numpy|for-loop | 2 |
360,235 | 52,728,752 | Python Moving Averages for Time Series Data with Inconsistent Data Points | <p>I have found plenty of information related to moving averages when the data is sampled to regular intervals (ie 1 min, 5 mins, etc). However, I need a solution for a time series dataset that has irregular time intervals.</p>
<p>The dataset contains two columns, Timestamp and Price. Timestamp goes down to the millis... | <p>The following works, except for the NaNs - I don't know how attached you are to those:</p>
<pre><code>foo = df.apply(lambda x: df[(df['Timestamp'] <= x['Timestamp']) & (df['timestamp']> x['timestamp'] - pd.Timedelta('5 min'))]['Price'].mean(), axis=1)
</code></pre> | python|pandas|numpy|dataframe|time-series | 1 |
360,236 | 52,866,467 | How can i make computer read a python file instead of py? | <p>I have a problem with installing numpy with python 3.6 and i have windows 10 64 bit
Python 3.6.6
But when i typed python on cmd this appears
Python is not recognized as an internal or external command
I typed py it solves problem but how can i install numpy
I tried to type commant set path =c:/python36
And cop... | <p>Try <code>pip3 install numpy</code>. To install python 3 packages you should use pip3</p> | python|numpy|scipy|installation | 0 |
360,237 | 46,391,291 | How to convert JSON data inside a pandas column into new columns | <p>I have this short version of ADSB json data and would like to convert it into dataFrame columns as Icao, Alt, Lat, Long, Spd, Cou.....</p>
<p>After Alperen told me to do this</p>
<pre><code>df = pd.read_json('2016-06-20-2359Z.json', lines=True),
</code></pre>
<p>I can load it into a DataFrame. However, <code>df.acL... | <p>If you already have your data in <code>acList</code> column in a pandas DataFrame, simply do:</p>
<pre><code>import pandas as pd
pd.io.json.json_normalize(df.acList[0])
Alt AltT Bad CMsgs CNum Call CallSus Cou EngMount EngType ... Sqk TSecs TT Tisb TrkH Trt Type VsiT WTC Year
0 NaN 0 ... | python|json|pandas | 35 |
360,238 | 46,355,445 | Dynamic matrix in Python | <p>I'm new to Python and I need a dynamic matrix that I can manipulate adding more columns and rows to it. I read about numpy.matrix, but I can't find a method in there that does what I mentioned above. It occurred to me to use lists but I want to know if there is a simpler way to do it or a better implementation.</p>
... | <p>You can do all of that in numpy (<code>np.concatenate</code> for example) or native python (<code>my_list.append()</code>). Which one is more efficient will depend on what else your program will do: numpy will be probably less efficient if all you are doing is adding / changing values one at a time, or do a lot of c... | python|numpy|matrix|dynamic | 1 |
360,239 | 46,556,169 | Finding common elements between multiple dataframe columns | <p>Hope you could help me. I am new to python and pandas, so please bear with me. I am trying to find the common word between three data frames and I am using Jupiter Notebook.</p>
<p>Just for example:</p>
<pre><code>df1=
A
dog
cat
cow
duck
snake
df2=
A
pig
snail
bird
dog
df3=
A
eagle
dog
snail
monkey
</code></pr... | <p>Simplest way is to use <code>set</code> intersection</p>
<pre><code>list(set(df1.A) & set(df2.A) & set(df3.A))
['dog']
</code></pre>
<hr>
<p>However if you have a long list of these things, I'd use <code>reduce</code> from <code>functools</code>. This same technique can be used with @cᴏʟᴅsᴘᴇᴇᴅ's use of ... | python|string|pandas|intersection|series | 19 |
360,240 | 46,367,159 | Where in tenserflow to show elements | <p>This code shows only indexes of array, where it used</p>
<pre><code>tensor1 = tf.convert_to_tensor(np.array([1536, 2, 5], dtype='float32'))
tf.where(tensor1 > 3).eval().reshape(1, 2)[0]
</code></pre>
<p>Output is:</p>
<blockquote>
<p>array([0, 2], dtype=int64)</p>
</blockquote>
<p>I did for loop to print us... | <p>tf.gather can also be used to index into arrays, so</p>
<pre><code>indices = tf.where(tensor1 > 3)
tf.gather(tensor1, indices)
</code></pre>
<p>should do the right thing</p> | python|tensorflow | 0 |
360,241 | 46,629,518 | Find indices of duplicate rows in pandas DataFrame | <p>What is the pandas way of finding the indices of identical rows within a given DataFrame without iterating over individual rows?</p>
<p>While it is possible to find all unique rows with <code>unique = df[df.duplicated()]</code> and then iterating over the unique entries with <code>unique.iterrows()</code> and extra... | <p>Use parameter <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="noreferrer"><code>duplicated</code></a> with <code>keep=False</code> for all dupe rows and then <code>groupby</code> by all columns and convert index values to tuples, last convert output <code>Series<... | python|pandas|dataframe | 22 |
360,242 | 46,359,843 | Parameters in tf.contrib.seq2seq.sequence_loss | <p>I'm trying to use the tf.contrib.seq2seq.sequence_loss function in a RNN model to calculate the loss.
According to the API document, this function requires at least three parameters: logits, targets and weights</p>
<pre><code>sequence_loss(
logits,
targets,
weights,
average_across_timesteps=True,
... | <p>Your <code>targets</code>(labels) don't need to be the same shape with <code>logits</code>.<br>
If we ignore batch_size(which is not relevant to your question) for a moment, this API simply calculates loss between two sequences through weighed sum loss of each word.Suppose vocab_size is 5, and we get a target word 3... | tensorflow | 2 |
360,243 | 46,395,181 | Making subsets of DataFrame | <p>To build an algorithm I want to make python script to work in such a way that it doesn't needs to make use of Panda's read_csv function again and again.</p>
<p>Following is the code that I am using.</p>
<pre><code>start_date = '2016-06-01'
end_date = '2017-09-22'
#Pool of symbols that I want to use
usesymbols = [... | <pre><code>powerset = [('GLAXO'), ('AVN'), ('GLAXO', 'AVN')]
j = 1
print(df.loc[:,powerset[j]])
2016-06-01 31.42
2016-06-02 32.62
2016-06-03 31.65
2016-06-04 31.65
2016-06-05 31.65
Name: AVN, dtype: float64
j=2
print(df.loc[:,powerset[j]])
GLAXO AVN
2016-06-01 205.93 31.42
2016-06-02 206.22 32... | python|pandas|dataframe | 1 |
360,244 | 46,478,518 | groupby DataFrame by N columns or N rows | <p>I'd like to find a general solution to groupby a DataFrame by a specified amount of rows or columns. Example DataFrame:</p>
<pre><code>df = pd.DataFrame(0, index=['a', 'b', 'c', 'd', 'e', 'f'], columns=['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7'])
c1 c2 c3 c4 c5 c6 c7
a 0 0 0 0 0 0 0
b 0 0... | <p>This groups by N rows</p>
<pre><code>>>> N=2
>>> df.reset_index(drop=True).groupby(by=lambda x: x/N, axis=0).mean()
c1 c2 c3 c4 c5 c6 c7
0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0
</code></pre>
<p>Or this:</p>
<pre><code>>>> df.gr... | python|pandas|pandas-groupby | 9 |
360,245 | 46,271,560 | Applying a function on a pandas dataframe column using map | <p>I am doing sentiment analysis for the first time. I am analyzing yelp reviews. I have converted the reviews into a list before writing them into a csv file. I am having some coding issues with these reviews so I am running this code.</p>
<pre><code>df['newtext'] = map(lambda x: x.decode('latin-1').encode('ascii','i... | <p><code>map</code> will slow things down, especially for large dataframes. You should know string columns offer vectorized methods which are much faster than maps and loops.</p>
<p>The pandaic way would be to call the <code>str</code> accessor methods - <code>encode</code> and <code>decode</code>, which do the exact s... | python|pandas|lambda | 2 |
360,246 | 46,592,910 | Why number below maximum for float128 in numpy is treated as inf? | <p>I'm using <code>numpy</code> under <code>python 2.7</code> and thought of using <code>np.float128</code> in order to represent a big number like 2e315. However it´s being treated as <code>inf</code> although it´s smaller than the maximum representation allowed which is near to 1e4932.</p>
<pre><code>In [1]: import ... | <p>That's because <code>2E315</code> get's evaluated <em>before</em> it is passed to <code>np.float128</code> and 2E315 evaluates to float('inf'):</p>
<pre><code>>>> 2E315
inf
</code></pre>
<p>By then it is too late. Thankfully, the constructor accepts a string:</p>
<pre><code>>>> import numpy as n... | python|python-2.7|numpy|precision | 3 |
360,247 | 46,216,095 | Using gcloud ml serving for large images | <p>I have a trained net in tensorflow that i wish to use in gcloud ml-engine serving for prediction.</p>
<p>Predict gcloud ml serving should accept numpy array float32 type images with size of 320x240x3 and return 2 tiny matrices as an output.</p>
<p>Does anyone knows how should i create the input layers that would a... | <p>I would recommended not using <code>parse_example</code> to start with. There are several options for sending image data, each with tradeoffs in complexity and payload size:</p>
<ol>
<li>Raw Tensor Encoded as JSON</li>
<li>Tensors Packed as Byte Strings</li>
<li>Compressed Image Data</li>
</ol>
<p>In each case, it... | numpy|tensorflow|google-cloud-ml-engine | 8 |
360,248 | 46,257,103 | How to Remove Rows from Pandas Data Frame that Contains any String in a Particular Column | <p>I have CSV data in the following format:</p>
<pre><code>+-------------+-------------+-------+
| Location | Num of Reps | Sales |
+-------------+-------------+-------+
| 75894 | 3 | 12 |
| Burkbank | 2 | 19 |
| 75286 | 7 | 24 |
| Carson City | 4 | ... | <p>Or you could do </p>
<pre><code>df[df['Location'].str.isnumeric()]
</code></pre>
<pre>
Location Num of Reps Sales
0 75894 3 12
2 75286 7 24
4 27659 3 17
</pre> | python|python-3.x|pandas|numpy|machine-learning | 5 |
360,249 | 46,516,823 | Function not being applied properly on a pandas dataframe | <p>I am very new to the whole pandas and numpy world. I have experience with python but not on this side. I was trying to work with a data set and I found a issue that I am not able to explain. It will be great if someone with experience helps me to understand what is going wrong in it. </p>
<p>I have a CSV file with ... | <p><strong>Option 1</strong><br>
<code>astype</code></p>
<pre><code>df['income'] = df['income'].eq("<=50K").astype(int)
</code></pre>
<hr>
<p><strong>Option 2</strong><br>
<code>np.where</code></p>
<pre><code>df['income'] = np.where(df.income == "<=50K", 1, 0)
</code></pre> | python|pandas|dataframe | 3 |
360,250 | 46,191,946 | Count and remove elements by conditions from dataframe columns of lists | <p>Suppose I have a Pandas df</p>
<pre><code> col_name
1 [16, 4, 30]
2 [5, 1, 2]
3 [4, 5, 52, 888]
4 [1, 2, 4]
5 [5, 99, 4, 75, 1, 2]
</code></pre>
<p>I would like to remove all the elements in the whole column that appears <code>less than x</code> times, for example let's take <code>x = 3</... | <p><strong>Option 1</strong><br>
Somewhat plain vanilla approach </p>
<pre><code>s = pd.Series({(i, j): x for (i, r) in df.col_name.items() for j, x in enumerate(r)})
f, u = pd.factorize(s.values)
s[(np.bincount(f) >= 3)[f]].groupby(level=0).apply(list).to_frame('col_name')
col_name
0 [4]
1 ... | python|string|list|pandas|dataframe | 3 |
360,251 | 46,375,766 | Tensorflow tf.Variable not able to perform addition | <p>I am able to perform addition using constant but not able to perform through tf.Variable </p>
<p>Below code is working fine when I am using constant for addition.</p>
<pre><code>import tensorflow as tf
a = tf.constant(5)
b = tf.constant(6)
sess = tf.Session()
result = sess.run(a + b)
print(result)
</code></pre>
... | <p>You need to initialize the variables firstly:</p>
<pre><code>import tensorflow as tf
a = tf.Variable(5)
b = tf.Variable(6)
sess = tf.Session()
</code></pre>
<p>Initialize variables:</p>
<pre><code>sess.run(tf.global_variables_initializer())
result = sess.run(a + b)
print(result)
11
</code></pre>
... | tensorflow | 2 |
360,252 | 46,241,806 | Estimator.predict in a loop cause memory leak in tensorflow | <p>When I use tensorflow <code>estimator.predict</code>, this happened to me.
Say, I have an estimator load from the saved model by this:</p>
<pre><code>estimator = tf.contrib.learn.Estimator(
model_fn=model_fn, model_dir=FLAGS.model_dir, config=run_cfg)
</code></pre>
<p>a <code>get_input_fn()</code> that will re... | <p>Finally, i found this is caused by call too many <code>tf.convert_to_tensor</code> , each time calling that function will generate a new node in tensorflow graph, which needs some memory.</p>
<p>To solve this problem, just use <code>tf.placeholder</code> to feed data.
Also, tensorflow v1.3 add a new method <code>tf... | tensorflow|memory-leaks | 1 |
360,253 | 46,527,272 | Compute dot product of numpy arrays (3,) and (1,) | <p>I want to compute the dot product between two numpy arrays.
For example, my arrays have shape of (3,) and (1,), so from basic math understanding I should an vector of shape (3,1). However using numpy dot would not get the result like that. In general, my input would have the size of (x,n) and (n,x) and I would like ... | <p>The only real issue here is that you're using arrays of size <code>(3,)</code> and <code>(1,)</code> but you should be using <code>(3,1)</code> and <code>(1,1)</code>. With that it behaves exactly as you want/expect:</p>
<pre><code>>>> np.dot([3, 2, 1], [1])
Traceback (most recent call last):
File "<s... | numpy|dot-product | 0 |
360,254 | 46,624,247 | Jupyter Kernel crash/dies when use large Neural Network layer, any idea pls? | <p>I am experimenting Autoencoder with Pytorch. It seems when I use relatively larger neural network for instance nn.Linear(250*250, 40*40) as the first layer, the Jupyter kernel keep crashing. when I use smaller layer size e.g. nn.Linear(250*250, 20*20). the Jupyter kernel is ok. Any idea how to fix this? So I can run... | <p>I have found the root cause. I am running a docker ubuntu image/package on windows. the memory setting is set too low, when I increase the memory setting on docker. my ubuntu environment got more memory, then I can larger matrix operations.</p> | python|neural-network|jupyter-notebook|pytorch | 1 |
360,255 | 46,204,605 | Array length does not match index length | <p>I'm looking to combine a few time series with varying dates into a single dataframe.</p>
<p>Each time series' column names are <code>date</code> and <code>px</code></p>
<p>I've created a date index <code>dates</code> and tried to combine all the time series by doing:</p>
<p><code>dates = pd.date_range('01/01/2017... | <p>IIUC:</p>
<pre><code>dfs = [df1,df2,df3]
pd.concat([df.set_index('date') for df in dfs], axis=1).reset_index()
</code></pre> | pandas|date|time-series | 2 |
360,256 | 46,535,113 | Convert int to list in a Pandas DataFrame | <p>I would like to convert a data frame:</p>
<pre><code>import pandas as pd
d = pd.DataFrame({id:[1, 2, 3]})
</code></pre>
<p>to </p>
<pre><code>res = pd.DataFrame({id:[[1], [2], [3]]})
</code></pre>
<p>i.e convert each element in the cell to a Python list.</p>
<p>However I tried </p>
<pre><code>res = d.apply(lam... | <p>If you have a large dataframe, it might be wise to avoid an <code>apply</code>. Try:</p>
<pre><code>pd.Series(d.values.reshape(-1, 1).tolist()).to_frame(name=d.columns[0])
id
0 [1]
1 [2]
2 [3]
</code></pre>
<hr>
<p><strong>Performance</strong></p>
<pre><code>d.shape
(1000000, 1)
</code></pre>
<pre><code>... | python|list|pandas|dataframe | 2 |
360,257 | 46,517,118 | Loss layer on Keras using two input layers and numpy operations | <p>I have a loss function implemented that uses numpy and opencv methods. This function also uses the input image and the output of the network.</p>
<p>Is it possible to convert the input and the output layers to numpy arrays, compute the loss and use it to optimize the network?</p> | <p>No, gradients are needed to perform gradient descent, so if you only have a numerical loss, it cannot be differentiated, in contrast to a symbolic loss that is required by Keras.</p>
<p>Your only chance is to implement your loss using <code>keras.backend</code> functions or to use another Deep Learning framework th... | python|numpy|keras|loss | 3 |
360,258 | 46,572,061 | How to sort a batch of 2D tensors in tensorflow? | <p>I have a tensor <code>A</code> with the shape of <code>[#batch, #MaxSequence, #Features]</code>, where the actual lengths of the 2nd dimension (may be less than <code>#MaxSequence</code>) are stored in a tensor <code>L</code>. I want to sort <code>A</code> by the 2nd feature in the 3rd dimension on the sequence in e... | <p>I have something working but it might exist better solutions. I guess my code is probably over-complicated for this simple problem.</p>
<p>The idea is that, we have to convert the return indices of <code>tf.nn.top_k(a[:,:,1].indices</code> (order by the second feature in the third dimension) to something <a href="h... | sorting|multidimensional-array|tensorflow | 4 |
360,259 | 46,189,035 | Creating a list of sliced dataframes | <p>I am trying to create a list of dataframes where each dataframe is 3 rows of a larger dataframe.</p>
<pre><code> dframes = [df[0:3], df[3:6],...,df[2000:2003]]
</code></pre>
<p>I am still fairly new to programming, why does: </p>
<pre><code> x = 3
dframes = []
for i in range(0, len(df)):
df... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow noreferrer"><strong><code>np.split</code></strong></a> </p>
<p><strong>Setup</strong><br>
Consider the dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(dict(A=range(15), B=list('abcdefghijklmno')))
</code><... | python|python-3.x|pandas | 4 |
360,260 | 46,285,149 | Python 3: RuntimeWarning with numpy.power | <p>When using <code>numpy.power(2,N)</code>, where <code>N</code> is an integer, I encounter the following issue:</p>
<pre><code>In[1] np.power(2,63)
Out[1] -9223372036854775808
RuntimeWarning: invalid value encountered in power
</code></pre>
<p>and even more strangely,</p>
<pre><code>In[2] np.power(2,63)*2
Out[2] 0... | <p>Large integers are not a problem with Python because Python only has one integer type and that is of arbitrary precision. But <a href="https://docs.scipy.org/doc/numpy/user/basics.types.html" rel="nofollow noreferrer">NumPy uses normal "C" data types</a> and these have limited precision:</p>
<pre><code>>>>... | python|python-3.x|numpy|integer|pow | 2 |
360,261 | 46,299,666 | Dummy variables in SKLearn | <p>General question. When creating a data set, thusfar I always changed categorical feautures to numbers myself.</p>
<p>For example: 5 categories for a single feature result in 1 feature with numbers 1,2,3,4,5.</p>
<p>Creating dummy variables in Pandas results in several features with 0 or 1 values. Is the latter a b... | <p>It depends on the data that you are trying to convert. If it is oridinal data like say <code>slow</code>,<code>medium</code> and <code>fast</code>, then it makes sense sense to convert them to numbers like <code>1,2 and 3</code>. This is because they seem to have some sort of order and sequence. However, if you have... | python|python-3.x|pandas|scikit-learn | 0 |
360,262 | 46,531,347 | Implementation of multiple feature linear regression | <p>I have a train_data which holds information about Stores and their sales. Which looks like this
<a href="https://i.stack.imgur.com/oXoad.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oXoad.png" alt="enter image description here"></a></p>
<p>I want to build a multiple feature linear regression t... | <p>You aren't actually importing the <code>LinearRegression</code> class. If you want to import everything in the <code>linear_model</code> module (which is generally frowned upon) you could do:</p>
<pre><code>from sklearn.linear_model import *
lr = LinearRegression()
...
</code></pre>
<p>A better practice is to impo... | python|pandas|scikit-learn | 1 |
360,263 | 46,611,869 | Cannot find modules after installing Anaconda | <p>I have installed Anaconda but still unable to use packages such as pandas and requests when running code on python.</p>
<p>When I input python on Terminal, it shows:</p>
<pre><code>Python 3.6.1 |Anaconda 4.4.0 (x86_64)| (default, May 11 2017, 13:04:09)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darw... | <p>Probably Anaconda became the default Python installation on your system. Specially when you are using a new environment, you have to install the modules you want in this new environment.</p>
<p>Try <code>conda install pandas</code> and, after that, <code>import pandas</code></p> | python|pandas|python-requests|anaconda | 0 |
360,264 | 46,373,794 | PANDAS: How to access keys of groupby object when attempting to apply multiple functions | <pre><code>data = {"index":{"0":1692,"1":1771,"2":1007,"3":2915,"4":1416},
"item_number":{"0":"123","1":"123","2":"124","3":"124","4":"125"},
"brand":{"0":"brand1","1":"brand1","2":"brand2","3":"brand2","4":"brand3"},
"price":{"0":20.00,"1":20.00,"2":25.00,"3":25.00,"4":30.00},
"comp_id":{"0":1,"1":2,"2":1,"3":3,"4":2}... | <p>Try this </p>
<pre><code>f1 = lambda x: len(x.unique())
f = {'item_number':f1, 'comp_id':f1}
df1.groupby('brand').agg(f)
Out[881]:
item_number comp_id
brand
brand1 1 2
brand2 1 2
brand3 1 1
</code></pre> | python|pandas | 2 |
360,265 | 46,416,383 | How to elegantly "reframe" a numpy array | <p>I'm using a <code>numpy.array</code> as a data buffer, and I'm looking for an elegant way to <code>reframe</code> it so that it keeps a portion of the initial data, depending on new framing conditions (the buffer may have <code>shrunk</code>, <code>expanded</code>, <code>shifted</code> or a combination of <code>shif... | <pre><code>import numpy as np
def reframe(x, start, end, default=0):
shape = list(x.shape)
orig_length = shape[0]
shape[0] = length = end - start
old_start = max(0, start)
old_end = min(end, length + 1, orig_length)
new_start = -start if start < 0 else 0
new_end = new_start + old_end - ... | python|arrays|numpy|scipy | 2 |
360,266 | 46,185,283 | Error while reading imported csv file from url with pandas | <p>I'm a beginner trying to advance on a project that I learned with a tutorial. The project consists on importing a csv file from the United States Geological Survey and plotting its data on a map.</p>
<p>I managed to make it while using a file that's located in my computer. However, I cannot get around on getting th... | <p>I believe the filename should just be the name.</p>
<pre><code>filename = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_hour.csv'
</code></pre>
<p>This should get it into a dataframe:</p>
<pre><code>import io
import requests
content = requests.get(filename).content
df = pd.read_csv(io.StringIO(c... | python|pandas|csv | 2 |
360,267 | 46,608,204 | Using datetime.time for comparison and column creation | <p>I've been using Pandas for a while and I'm sure it's a dumb question.</p>
<p>I need to create a column in a data frame which is conditional to the datetime.time. If datetime.time < 12, fill column with 'morning', then the same process to 'afternoon' and 'night'. </p>
<pre><code>import datetime
b['time'] = ['01... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a> or <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow noreferrer"><code>numpy.searchsorted</code></a> for labels by bins... | python|pandas|datetime | 1 |
360,268 | 46,579,490 | how to create a list with random round values with a given max value | <p>I want to create a list with a length of 4</p>
<p>I have a df,</p>
<pre><code> contents values
0 A 484
1 B 429
2 C 130
3 D 108
4 E 77
5 F 2
</code></pre>
<p>I want to define a bin range for these values.
I am... | <p>Use <code>np.linspace</code></p>
<pre><code>In [1212]: np.linspace(0, round(df['values'].max(), -2), len(df))
Out[1212]: array([ 0., 100., 200., 300., 400., 500.])
</code></pre> | python|pandas|numpy|dataframe|random | 1 |
360,269 | 46,284,226 | Selecting columns from a data-frame based on contents of a list | <p>I have a dataframe <code>df</code> that looks like:</p>
<pre><code> record_id month day year plot species sex wgt
0 False False False False False True False True
1 False False False False False True False True
2 False False False False False False... | <p>By using <code>isin</code></p>
<pre><code>df.loc[:,df.columns.isin(['month','plot','sex'])]
Out[165]:
month plot sex
0 False False False
1 False False False
2 False False False
3 False False False
4 False False False
5 False False False
6 False False False
7 False False Fal... | python|pandas | 3 |
360,270 | 46,416,235 | Use Keras (Tensorflow backend) with mobile GPU (laptop) | <p>If I only use the Tensorflow code, the GPU usage rate is more than 80% and temperature rises very much. But if I use Kers, the usage rate drops to 15%. Also, using Keras does not reach the maximum clock of the GPU.</p>
<p>I tried with 980m, 1070 (laptop) and 960m, but the same result was obtained. ANN and CNN all h... | <p>Maybe upgrade to Tensorflow 1.3. In TF 1.3 Keras is already included and there is no need to additionaly install keras. </p>
<p>In order to use the keras version included in TF do the following:
Use for example</p>
<pre><code>from tensorflow.contrib.keras.python.keras.models import Model
</code></pre>
<p>or</p>
... | python|keras|tensorflow | 0 |
360,271 | 46,336,049 | Selecting non 1. values in iteration of a data-set while calculating coefficient correlation? | <p>I'm iterating through the result set of the calculation of correlation values.</p>
<p>The output of this loop:</p>
<pre><code>for x in range(DT.shape[1]):
print np.corrcoef(DT[:, x], YDT, rowvar=False)
</code></pre>
<p>Is the following:</p>
<pre><code>[[ 1. ,0.58889117],
[ 0.58889117 ,1. ]]... | <p>The comment by Divakar above provided the solution.</p>
<pre><code>np.corrcoef(DT[:, x], YDT, rowvar=False)[0,1]
</code></pre> | python|numpy | 0 |
360,272 | 58,279,057 | Transfer Learning with MobileV2Net | <p>I am trying to implement transfer learning with MobileV2Net following from <a href="https://www.tensorflow.org/tutorials/images/transfer_learning" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/images/transfer_learning</a> .</p>
<p>The above tutorial uses the MobileV2Net model as the base model and... | <p><code>Padded batch</code> vs <code>batch</code>: <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#padded_batch" rel="nofollow noreferrer">padded batch</a> is used if the elements inside your dataset are of different shapes whereas <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset... | tensorflow|deep-learning|conv-neural-network|tensorflow-datasets|transfer-learning | 0 |
360,273 | 58,323,568 | Is it possible to merge two detect.tflite files into one detect.tflite File? | <p>I have trained Two models and generated their detect.tflite files successfully, I need to know that , Is there any way to merge both detect.tflite file so that resulting one detect file can be used in android/ios application?</p> | <p>I did quiet decent research on this and came to conclusion that two .tflite file cannot be merged, however one can combine datasets and retrain model and generate new .tflite file which can do job of both previous .tflite files</p> | tensorflow | 0 |
360,274 | 58,573,577 | For loop to calc desc stats for each distinct value in a subcategory column in Pandas | <p>I'd like to calculate the descriptive statistics of the 'Variance' column for each distinct value in the Subcategory column of my dataset. Rather than do it manually, I'd like to use a for loop. I'm getting a value error, but not sure what I might be missing. Thank you!</p>
<pre><code>subcategories = ['abc', 'cab',... | <p><code>df.Subcategory == i</code> returns a boolean series. The if condition doesn't know how to return on a series. You need this:</p>
<pre><code>for i in subcategories:
print(df.loc[df.Subcategory == i, 'Variance'].describe())
</code></pre> | python-3.x|pandas | 2 |
360,275 | 58,416,423 | Filter points between polygons | <p>I have polygon like this:</p>
<pre><code>MULTIPOLYGON(((3.6531688909 22.2345676543....)))
MULTIPOLYGON(((3.7531688909 22.6543234523....)))
…
</code></pre>
<p><a href="https://i.stack.imgur.com/RvOeO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RvOeO.png" alt="enter image description here"></a... | <p>What does your polygon data look like? Do you have geometry fields? If so, you could use <a href="http://geopandas.org/reference.html#geopandas.GeoSeries.contains" rel="nofollow noreferrer">geopandas <code>contains</code></a> to check if your blue polygons contain your points.</p> | python|pandas|geolocation|filtering | 1 |
360,276 | 58,591,348 | How to iterate over rows from different dataframe and to use it as a value in other? | <p>I am trying to iterate over the "df_sum" dataframe's 'contract' column by its unique values.
Then create dataframe for each "contract" value for further calculation.</p>
<p>Following is how it goes for a single unique value. I need to iterate over many thousands of unique values.</p>
<p>Here is what the df_sum loo... | <p>What about this.</p>
<pre class="lang-py prettyprint-override"><code>df_sum = pd.read_csv(r'path_to_sum.csv', sep=",", low_memory=False, index_col=False)
grouped = df_sum.groupby("contract")["power_pos"].sum()
print(grouped)
</code></pre> | python|pandas|loops|dataframe | 1 |
360,277 | 58,186,764 | How to join several data frames containing different pieces of one data into one? | <p>I have several - let's say three - data frames that contain different rows (sometimes they can overlap) of another data frame. The columns are the same for all three dfs. I want now to create final data frame that will contain all the rows from three mentioned data frames. Moreover I need to generate a column for th... | <p><a href="https://stackoverflow.com/q/49620538/2336654">See this related post</a></p>
<p>IIUC, you can use <code>pd.concat</code> with the <code>keys</code> and <code>names</code> arguments</p>
<pre><code>pd.concat(
[a, b, c], keys=['a', 'b', 'c'],
names=['from which df this row']
).reset_index(0)
from w... | python-3.x|pandas|numpy|dataframe | 1 |
360,278 | 58,236,274 | Changing excel pivot lay-out to one-dimensional dataset, using python | <p>My dataset looks like this:</p>
<pre><code> Item Type Price 1 Price 2 Price 3
1 A 400 200 -46
1 B 500 250 -62
1 C 600 300 0
</code></pre>
<p>I manage to concat the first 2 columns, but want the dataset to look like this:</p>
<pre><code... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.cat.html" rel="nofollow noreferrer">pandas.Series.str.cat</a>
to join the <code>Item</code> and <code>Type</code> columns .</p>
<pre><code>df['Unique_Items']=df['Item'].astype(str).str.cat(df['Type'],sep=' ')
</code><... | python|excel|pandas|transpose | 1 |
360,279 | 58,559,008 | How to slice ndarray after hstacking , back to original pieces | <p>Hi i would like to recover two pieces of a composite numpy array that was made by stacking two smaller arrays. i need the slicing for each peice, iyou could help me.</p>
<p>i have two ndarrays that i hastacked on to each other</p>
<pre><code>frame = np.hstack([thought1,pix])
</code></pre>
<p>shape for pix and tho... | <p>The 'inverse' of np.hstack would be <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.hsplit.html" rel="nofollow noreferrer">np.hsplit</a></p>
<pre class="lang-py prettyprint-override"><code>thought1, pix = np.hsplit(np.hstack([thought1,pix]), [thought1.shape[1]])
</code></pre> | python|numpy|slice | 0 |
360,280 | 58,320,390 | Multiple chain draws for simple Multivariate Bernouilli inference | <p>I want to perform a simple inference of a Multivariate Bernouilli (dimension D) with multiple chains. The code below works and correctly infers the parameters value for an unique chain.
I suspect that I incorrectly defined my model. I didn't find any simple example of simple bernouilli inference.</p>
<p>The error r... | <p>First of all, I am clearly not an expert in tensorflow probability, so this answer will most probably not be best practices, I just made it work with the limited knowledge I have on the library while trying to learn more of tensorflow probability myself. </p>
<p>Secondly, I am only aiming to answer the part of the ... | python|tensorflow|bayesian|tensorflow-probability | 0 |
360,281 | 58,357,118 | Filling the diagonals of square matrices inside a 3D ndarray with values given by a 2D ndarray | <p>Given a 3D ndarray <code>z</code> with shape <code>(k,n,n)</code>, is it possbile without using iteration to fill the diagonals of the k nxn matrices with values given by a 2D ndarray <code>v</code> with shape <code>(k,n)</code>?</p>
<p>For example, the result of the operation should be the same as looping over k m... | <p>Here's for generic n-dim arrays -</p>
<pre><code>diag_view = np.einsum('...ii->...i',z)
diag_view[:] = v
</code></pre>
<p>Another with reshaping -</p>
<pre><code>n = v.shape[-1]
z.reshape(-1,n**2)[:,::n+1] = v.reshape(-1,n)
# or z.reshape(z.shape[:-2]+(-1,))[...,::n+1] = v
</code></pre>
<p>Another with <code>mas... | python|numpy | 1 |
360,282 | 58,286,019 | Webots displaying processed numpy image (OpenCV Python) | <p>I am trying to simulate a line follower with Pioneer 3AT in Webots. This is the first step towards my application involving swarm robotics. I have placed camera. However, I am not able to display image processed with OpenCV in the simulation display (in realtime). For now, I am planning to just threshold the lane an... | <p>I figured out an "official way" to get this up and running. However, I do not like this solution as it is not integrated directly into the simulator (and the simulations become too slow when used with this method). For now, I am accepting this answer. However, I will accept any other answer that integrates neatly in... | python|numpy|opencv|swig|webots | 2 |
360,283 | 58,586,561 | Faster way to do t-1 calculations in pandas | <p>I have a df with 250,000+ rows. I have a few fields which are dependent on t-1 values. This is a breeze to do in excel, but not sure what the most efficient way to do it in pandas is. Currently I set the t[0] value, then use a for loop to do the rest, but this is incredibly slow. Is there a faster way to do this?</p... | <p><code>pandas</code> Dataframes are not meant for looping over the rows. I suggest you take the take to learn thoroughly the uses and functions of it. In the mean while, this should help you with what you need (I did it on the fly, so let me know if there is a compiling error):</p>
<pre><code>df['Qty'] = df['Qty'].s... | python|python-3.x|pandas|numpy | 2 |
360,284 | 58,190,176 | groupby date using other start time than midnight | <p>I am aggregating some data by date.</p>
<pre><code>for dt,group in df.groupby(df.timestamp.dt.date):
# do stuff
</code></pre>
<p>Now, I would like to do the same, but without using midnight as time offset.
Still, I would like to use groupby, but e.g. in 6AM-6AM bins.
Is there any better solution than a dummy... | <p>You can, for example, subtract the offset before grouping:</p>
<pre><code>for dt, group in df.groupby(df.timestamp.sub(pd.to_timedelta('6H')).dt.date):
# do stuff
</code></pre> | pandas|group-by|timestamp|resampling | 4 |
360,285 | 58,561,532 | Why is numpy.argsort() shuffeling the indices for ties? | <p>I am using python 3. The problem is with numpy.argsort().</p>
<p>I have two arrays (say A and B). I want to order values in array A by values in array B. I use this code.</p>
<pre class="lang-py prettyprint-override"><code>A_ordered = A[B.argsort()]
</code></pre>
<p>In array B, there are good chances that ties oc... | <p>You need to tell <code>argsort</code> to use a <em>stable</em> sorting method.</p>
<pre><code>>>> print(B.argsort(kind='stable')) #trying to sort
[ 0 1 2 ... 22997 22998 22999]
</code></pre> | python|arrays|numpy | 2 |
360,286 | 58,519,048 | Is there a way to vectorize counting items' co-occurences in pandas/numpy? | <p>I frequently need to generate network graphs based on the co-occurences of items in a column. I start of with something like this:</p>
<pre><code> letters
0 [b, a, e, f, c]
1 [a, c, d]
2 [c, b, j]
</code></pre>
<p>In the following example, I want a to make a table of all pairs of letters, ... | <h2>Notes:</h2>
<p>As suggested in the other answers, make use of <code>collections.Counter</code> for the counting. Since it behaves like a <code>dict</code> though, it needs hashable types. <code>{a,b}</code> is not hashable, because it's a set. Replacing it with a tuple fixes the hashability problem, but introduces ... | python|pandas|numpy|vectorization | 2 |
360,287 | 58,414,786 | Stacked histogram by decade from dataframe | <p>I have a dataframe that contains the date of a snowstorm and also a ranking of said snowstorm ranging from 1950-2019. I want to create a stacked histogram where the x-axis is decade and the y-axis is counts of snowstorm by category. </p>
<p>An example of what I am trying to create is listed below. <a href="https://... | <p>Aggregate you data first, then plot with the argument <code>stacked=True</code></p>
<h3><code>pivot_table</code></h3>
<pre><code>df.pivot_table('count', 'Year', 'Category', 'sum').plot.bar(stacked=True)
</code></pre>
<h3><code>groupby</code></h3>
<pre><code>df.groupby(['Year', 'Category'])['count'].sum().unstack... | python|pandas|dataframe|matplotlib | 3 |
360,288 | 58,241,656 | Neural Network (operands could not be broadcast together with shapes (1,713) (713,18) ) | <p>I am currently taking the Deep Learning specialization by Deeplearning.ai on Coursera and am on the first assignment that requires implementing Neural Network with Logistic Regression mindset. The problem is that the assignment is implementation of Neural Network as Logistic Regression function for <strong>UNSTRUCTU... | <p>The <code>*</code> operator is elementwise multiplication, and your arrays have incompatible shapes. You want matrix multiplication, which you can do with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul.html" rel="nofollow noreferrer"><code>np.matmul()</code></a> or with the <code>@</code>... | python|numpy|neural-network|logistic-regression|broadcast | 1 |
360,289 | 58,276,088 | create column by combining index #, string | <p>I have a dataframe containing a column of strings. I want to create a new column that combines the index number and the string column together in a list comprehension. The following code does this operation iterating in a loop:</p>
<pre><code>df=pd.DataFrame({'strings': ['string1','string2','string3']})
new_col=[]... | <p>You can convert the index to string and add as usual (arrays of) strings:</p>
<pre><code>df['new_col'] = df['strings'].index.astype(str) + ',' + df['strings']
</code></pre>
<p>Output:</p>
<pre><code> strings new_col
0 string1 0,string1
1 string2 1,string2
2 string3 2,string3
</code></pre> | python|pandas | 2 |
360,290 | 58,460,139 | Why is subtraction faster when doing arithmetic with a Numpy array and a int compared to using vectorization with two Numpy arrays? | <p>I am confused as to why this code:</p>
<pre><code>start = time.time()
for i in range(1000000):
_ = 1 - np.log(X)
print(time.time()-start)
</code></pre>
<p>Executes faster than this implementation:</p>
<pre><code>start = time.time()
for i in range(1000000):
_ = np.subtract(np.ones_like(X), np.log(X))
print... | <p>Both versions of your code are equally vectorized. The array you created to try to vectorize the second version is just overhead.</p>
<hr>
<p>NumPy vectorization doesn't refer to hardware vectorization. If the compiler is smart enough, it might end up using hardware vectorization, but NumPy doesn't explicitly use ... | python|arrays|numpy|matrix|linear-algebra | 7 |
360,291 | 58,474,576 | Python Pandas Syntax Error (Invalid) - Probability | <p>I have a data file IGN.csv. I have to determine:</p>
<p>If a game is selected from data: </p>
<p>Probability of it being "awful" give it was released in year 2015 or 2016. Basically, the sample space n is now games in 2015 or 2016. This is my attempt:</p>
<pre><code>#import csv file
data = pd.read_csv('IGN.csv')
... | <pre><code>len(data[(data['score_phrase' == 'Awful')
</code></pre>
<p>Should be</p>
<pre><code>len(data[(data['score_phrase'] == 'Awful')
</code></pre> | python|pandas | -1 |
360,292 | 58,468,588 | How to optimize multiple operations on python dataframe that are currently done with columns and row iterations? | <p>I currently have a process that is working with multiple iterations over rows and columns. I believe there should be a more efficient way to compute the output using some sort of vectorized functions on the dataframe in combination with group by; however, I dont know how to do it.</p>
<p><strong>This code works pre... | <p>I've refactored your solution using multi-processing. If you have a lot metrics and dimensions then it should scale well. <code>run_test_details</code> could be optimized more with some caching, but I don't know how big is your data so it could be problematic.. Also if it some standard statistical procdure, I'd chec... | python|pandas|scipy|vectorization|pandas-groupby | 0 |
360,293 | 58,466,562 | Given a batch of n images, how to scalar multiply each image by a different scalar in tensorflow? | <p>Assume we have two TensorFlow tensors:
<code>input</code> and <code>weights</code>.</p>
<p><code>input</code> is a tensor of n images, say. So its shape is [n, H, W, C].
<code>weights</code> is a simple list of n scalar weights: <code>[w1 w2 ... wn]</code></p>
<p>The aim is to scalar-multiply each image by its c... | <p>Thanks to user zihaozhihao:</p>
<p>The answer is to change the shape of <code>weights</code> to (-1, 1, 1, 1) and then multiply it with <code>input</code>.</p>
<pre><code>weights = tf.reshape(weights, (-1, 1, 1, 1))
weighted_input = input * weights
</code></pre> | tensorflow | 1 |
360,294 | 58,326,591 | Insert label column into column content in data frame | <p>I have a data frame with different columns and I need to insert the label of each column into the content of the column. </p>
<pre><code>df['colour','season','food']
colour season food
white winter meat
yellow summer fruit
red fall soup
</code></pre>
<p>I need to do an operation like this <code>df.c... | <p>No loop needed due to pandas intrinsic data alignment:</p>
<pre><code>df.columns + ' ' + df
</code></pre>
<p>Output:</p>
<pre><code> colour season food
0 colour white season winter food meat
1 colour yellow season summer food fruit
2 colour red season fall food soup
</code... | python|pandas | 3 |
360,295 | 58,353,757 | How do I reference a sub-column from a pivoted table inside a method such as sort_values? | <p><a href="https://i.stack.imgur.com/3TcX6.jpg" rel="nofollow noreferrer">This table</a> has 2 level of columns after pivotting col2. I want to sort the table with df['col3']['A'], but in <code>.sort_values()</code> you can only use a string or a list of strings to reference column(s). </p>
<p>I know for this specifi... | <p>Found the answer here: <a href="https://stackoverflow.com/questions/35652270/sort-pandas-pivot-table-by-the-margin-all-values-column?rq=1">Sort Pandas Pivot Table by the margin ('All') values column</a></p>
<p>Basically just put the column and sub column(s) in a tuple. i.e. for my case, it is just <code>.so... | python|pandas | 1 |
360,296 | 58,485,131 | 'numpy.ndarray' object has no attribute 'concatenate' error | <p>I have written some simple code to iterate through a group of lists I am analyzing (from b1 to b20). To these lists, I want to check first which of them are empty. To those that are empty, I want to add the value 0. I want to add 0 to the empty lists, because I will later sum the values from different lists altogeth... | <p>To concatenate two numpy arrays, you have to write <code>rate = np.concatenate((rate,r),axis=0/1)</code>, depending upon how you want to concatenate the two arrays.</p> | python|numpy|eval | 1 |
360,297 | 58,562,212 | Selecting items in an array by using 2 coordinates and fill it | <p>I'm making a Battleship game bot for a Discord server. I haven't implemented the Discord part yet and I'm still at making the game's logic.</p>
<p>This is the code:</p>
<pre><code>import numpy as np
import re
waters = np.zeros((10,10),'U2')
headers = ['A','B','C','D','E','F','G','H','I','J']
#PRINTS THE BOARD
f... | <p>I did the first case and few minor changes:</p>
<ul>
<li>improved regex</li>
<li>use '##' as default value for board cell</li>
<li>print board changed into function</li>
</ul>
<pre><code>import numpy as np
import re
waters = np.full((10,10), '##','U2')
headers = ['A','B','C','D','E','F','G','H','I','J']
#PRINTS ... | python|numpy | 1 |
360,298 | 58,402,219 | How to shift some values from one column to another in python / pandas? | <p>Some values are placed under wrong column in the dataset, which needs to be copied to some other column, so how to shift the values from one column to another. Images of the defected dataset and the expected output is given in the link below
Link to the images are given as
Dataset problem
<a href="https://imgur.co... | <p>The problem comes from the fact that pandas considers ; as a column separator. You should modify your data set.</p>
<p>If you can't do this here an example of what you're trying to do :</p>
<pre><code>df = pd.DataFrame({'Genres' : ['Art & Design', 'Art & Design'],'Last updated' : ['January 16', 'Pretend Pl... | python|pandas|dataframe | 0 |
360,299 | 58,226,856 | How to fill NaN will last value? | <p>For example:</p>
<pre><code>arr = ['a', np.nan, np.nan, 'b', np.nan, 'a', np.nan, np.nan]
</code></pre>
<p>let's say i want to forward fill so i get <code>['a', 'a', 'a', 'b', 'b', 'a', 'a', 'a']</code></p>
<p>I have tried using <code>fillna(method='ffill)</code>, but this just fills with a static value ie. 0. I ... | <p><a href="https://i.stack.imgur.com/wGSt9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wGSt9.png" alt="enter image description here"></a></p>
<p><code>ffill</code> is the function you need, maybe you just forget to specify inplace=True</p> | pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.