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 |
|---|---|---|---|---|---|---|
356,900 | 50,663,803 | Training on minibatches of varying size | <p>I'm trying to train a deep learning model in PyTorch on images that have been bucketed to particular dimensions. I'd like to train my model using mini-batches, but the mini-batch size does not neatly divide the number of examples in each bucket.</p>
<p>One solution I saw in <a href="https://stackoverflow.com/questi... | <p>Hi since every batch should contain images of the same dimension, your <code>CustomSampler</code> works just fine, it needs to be passed as an argument to <code>mx.gluon.data.DataLoader</code>, with the keyword, <code>batch_sampler</code>. However, as stated in the docs, do remember this:</p>
<blockquote>
<p>"Do ... | python|deep-learning|pytorch|mini-batch | 0 |
356,901 | 50,337,526 | Setting varying columns for a subset of rows in a pandas multiindex dataframe | <p>I want to re-assign values in specific rows and varying multi-index columns of a large pandas dataframe, df, to non NaN values that have been calculated and stored in a slightly smaller masked subset of the dataframe, df_sub.</p>
<pre><code>df =
A B ... | <p>You should add <code>values</code> at the end of <code>df_sub</code> after <code>.iloc</code></p>
<pre><code>df.loc[1, pd.IndexSlice['B', 5:7]] = df_sub.loc[1, 5:7].values
df.loc[3, pd.IndexSlice['B', 3:5]] = df_sub.loc[3, 3:5].values
</code></pre> | python|pandas|dataframe|assign | 2 |
356,902 | 50,249,653 | Pandas merging 2 dataframes on their similar columns(which is the index) | <p>I have two dataframes, which in both I happened to set 'timeStamp' as the index. <code>df_1.set_index('timeStamp', inplace=True)</code>. </p>
<p><strong>df_1</strong></p>
<pre><code> value
timeStamp
2016-11-23 20:00:00 37.21
2016-11-23 21:00:00 37.79
2016-11-23 22:00:00 33.9... | <p>I believe that you CAN merge on an index. You just seem to have used the wrong syntax. Instead of specifying <code>on</code> you should try using <code>left_index</code> and <code>right_index</code>. </p>
<p>See the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="no... | python|pandas|dataframe | 1 |
356,903 | 50,438,071 | Cost function convergence in Tensorflow using softmax_cross_entropy_with_logits and "soft" labels/targets | <p>I've found what is probably a rare case in Tensorflow, but I'm trying to train a classifier (linear or nonlinear) using KL divergence (cross entropy) as the cost function in Tensorflow, with soft targets/labels (labels that form a valid probability distribution but are not "hard" 1 or 0). </p>
<p>However it is cle... | <p>Ahh my friend, you're problem is that with soft targets, especially ones that aren't close to 1 or zero, cross entropy loss doesn't change significantly as the algorithm improves. One thing that will help you understand this problem is to take an example from your training data and compute the entropy....then you w... | tensorflow|classification | 1 |
356,904 | 50,378,153 | pandas faster way than argsort to rank in dataframe subset | <p>I have this dataframe:</p>
<pre><code>user1 user2 quantity
--------------------------
Alice Carol 10
Alice Bob 5
Bob Dan 2
Carol Eve 7
Carol Dan 100
</code></pre>
<p>I want to rank the each row in descending order, using the quantity, BUT by user 1. Example:</p>
<p... | <p>Use:</p>
<pre><code>df['order'] = df.groupby('user1')['quantity'].rank(ascending=False).astype(int)
</code></pre>
<p>Output:</p>
<pre><code> user1 user2 quantity order
0 Alice Carol 10 1
1 Alice Bob 5 2
2 Bob Dan 2 1
3 Carol Eve 7 2
4 Carol ... | python|pandas|sorting | 6 |
356,905 | 50,351,264 | Pandas: Recommendation on how to handle missing decimal | <p>I have a scenario where the one of the record in the dataset contains empty value (simplified below for ease of understanding). there are two records in data, one with 0.1 and other with None. When I serialize <code>df1</code>, I get the response I want i.e null for second record. </p>
<pre><code>import pandas as p... | <pre><code>df3['A'] = df2['A'].apply(lambda x: (decimal.Decimal(x) if not pd.isnull(x) else None))
</code></pre> | python|json|python-3.x|pandas|numpy | 0 |
356,906 | 50,479,406 | Run tensorflow on ios with Xcode | <p>I have searched some related questions here, but I can't find the way to solve my problem.</p>
<p>I would like to ask how to run my python script(which includes tensorflow modules) on ios app. Are there any websites that I can follow the steps and install sucessfully? or some useful documents?</p>
<p>Thanks for th... | <p>I think this will be hard to do:</p>
<p>Although there are several apps in the app store available, in which you can run python scripts, I think you cannot add external modules there (but I not that sure about that). You could check <a href="https://itunes.apple.com/de/app/pythonista-3/id1085978097?mt=8" rel="nofol... | ios|xcode|tensorflow | 0 |
356,907 | 50,490,494 | Select a column in a multiple headers dataframe | <p>I have a df with multiple headers :</p>
<pre><code>multicol = pd.MultiIndex.from_tuples([('France', '2017'), ('France', '2018'),('UK', '2017'), ('UK', '2018')], names = ("Country", "Year"))
df = pd.DataFrame([[1, 2, 5, 8], [2, 4, 2, 9]], index=['Number', 'Volume'], columns=multicol)
</code></pre>
<p>I want to prin... | <p>Use tuple for select columns in <code>MultiIndex</code>:</p>
<pre><code>df = df[('France','2018')]
print (df)
Number 2
Volume 4
Name: (France, 2018), dtype: int64
</code></pre>
<p>For more complicated selects use <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="nofollow ... | python|pandas | 1 |
356,908 | 50,354,158 | TensorFlow TypeError: 'BatchDataset' object is not iterable / TypeError: 'CacheDataset' object is not subscriptable | <p>I'm following the <a href="https://www.tensorflow.org/get_started/eager" rel="nofollow noreferrer">TensorFlow starter guide</a>. It specifically said to enable eager execution on the sample project for iris (flower) classification.</p>
<blockquote>
<p>Import the required Python modules, including TensorFlow, and ... | <p>It turns out that I actually failed to do certain steps in the project that caused this problem.</p>
<h3>Upgrade TensorFlow from 1.7 to 1.8:</h3>
<p><code>!pip install --upgrade tensorflow</code></p>
<h3>Checking if your TensorFlow is updated</h3>
<p>This code cell:</p>
<pre><code>from __future__ import absolut... | python|python-3.x|tensorflow|google-colaboratory | 4 |
356,909 | 50,618,565 | Find repeated words in a column and sort it according to number of occurence using pandas | <pre><code> A B
1) Italy Transport for London.....
2) Italy Roseanne Barr Actor leavin.....
3) America Americas Transport for London........
4) America Transport for London.....
5) America Rosea... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> with <a href="https://stackoverflow.com/q/16486252"><code>argsort in descending order</code></a> for positions and select by <code>iloc</code>:</p>
<pre... | python|python-3.x|pandas|dataframe | 1 |
356,910 | 50,619,237 | How to explicitly set database engine when using to_sql() in pandas | <p>How could I possibly patch the sql statement in the pandas to_sql() function, so the newly created table uses the MYISAM storage engine?</p>
<p>I need MYISAM because of a very large amount of columns. This currently causes issues with the standard database engine INNODB (Row size too large (> 8126).</p>
<p>I am aw... | <p>As per my knowledge, <em>storage engine</em> of <em>MySQL</em> can't be set using <code>df.to_sql</code> or <code>engine = create_engine('mysql+pymy....://x@y/z')</code>. </p>
<p>MySQL storage engine can be added to table structure once it is created.<br>
<code>executing</code> an <code>alter table</code> command ... | python|mysql|pandas | 1 |
356,911 | 50,455,551 | Why is numpy.ravel() required in this code that produces small multiples? | <p>I found some code to generate a set of <a href="https://en.wikipedia.org/wiki/Small_multiple" rel="nofollow noreferrer">small multiples</a> and it is working perfectly.</p>
<pre><code>fig, axes = plt.subplots(6,3, figsize=(21,21))
fig.subplots_adjust(hspace=.3, wspace=.175)
for ax, data in zip(axes.ravel(), clean_se... | <p>Your guess is correct. <code>plt.subplots()</code> returns either an <code>Axes</code> or a <code>numpy</code> array of several axes, depending on the input. In case a 2D grid is defined by the arguments <code>nrows</code> and <code>ncols</code>, the returned <code>numpy</code> array will be a 2D array as well.</p>
... | python|numpy|matplotlib | 5 |
356,912 | 50,619,380 | Marked in Scatter plots, if Unexpected Values shows | <p>I have a <code>dataframe</code>, like this. I want to do <code>scatter plots</code> of it.</p>
<p><a href="https://i.stack.imgur.com/6zTDd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6zTDd.png" alt="enter image description here" /></a></p>
<p>I want to do <code>scatter plots</code> of <code>Va... | <p>Add another column with color information:</p>
<pre><code>import matplotlib.cm as cm
df['color'] = [int(value < 0.6) for value in df.Value2]
df.plot.scatter(x=df.index, y='Value1',c='color',cmap=cm.jet)
</code></pre> | python|pandas|matplotlib|scatter-plot | 1 |
356,913 | 50,612,031 | New column with in a Pandas Dataframe with respect to duplicates in given column | <p>Hi i have a dataframe with a column "id" like below</p>
<pre><code>
id
abc
def
ghi
abc
abc
xyz
def
</code></pre>
<p>I need a new column "id1" with a number 1 appended to it and number should be incremented for every duplicate. output should be like below.</p>
<pre><code>
id id1
abc abc1
def def1
ghi... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>groupby.cumcount</code></a> for count <code>id</code>s, add <code>1</code> and convert to <code>string</code>s:</p>
<pre><code>df['id1'] = df['id'] + df.groupby('id').cumcoun... | python-3.x|pandas|dataframe | 1 |
356,914 | 50,322,378 | Append pd.value_counts() and defined variable to a row of dataframe | <p>Had a bit of difficulty coming up with a simple example, but I hope this makes sense: I have a loop that generates me a variable <code>name</code> and a dataframe like so</p>
<pre><code>name = 'store1'
exampledf = pd.DataFrame({'animal': ['bird', 'bird', 'dog', 'cat', 'cat', 'cat']})
</code></pre>
<p>I can use <co... | <p>Let's try vectorizing this. Concatenate your DataFrames, call <code>str.get_dummies</code> and then sum along the index. </p>
<pre><code>df_list = [exampledf1, exampledf2]
names = [name1, name2]
(pd.concat(df_list, axis=0, keys=names)
.animal
.str.get_dummies()
.sum(level=0)
)
bird cat dog
stor... | python|pandas|dataframe | 3 |
356,915 | 50,479,582 | Python: How do I ensure the function is loaded once the first time it is called? | <p>I am currently reading the tensorflow tutorial given by Stanford <a href="https://docs.google.com/presentation/d/1iO_bBL_5REuDQ7RJ2F35vH2BxAiGMocLC6t_N-6eXaE/edit#slide=id.g1bfea8a10f_0_101" rel="nofollow noreferrer">lecture</a>. It is teaching about a concept call "lazy loading". And in the slide, it explains that ... | <p>There's a pretty good description of the use of the <em>@property</em> decorator for lazy evaluation <a href="https://stevenloria.com/lazy-properties/" rel="nofollow noreferrer">here</a>. Basically, the <em>@property</em> decorator allows you to define an instance variable that will:</p>
<ol>
<li>Be evaluated upon ... | python|tensorflow | 1 |
356,916 | 50,653,035 | shift numpy array column and row? | <p>I have numpy array like this, where I have one column and one row of ZEROS :</p>
<pre><code> ([[0. , 2.8, 3.5, 0. , 2.5, 1. , 0.8],
[0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[3.5, 2.5, 0. , 0. , 2.8, 1.3, 1.1],
[3.6, 3.8, 3.3, 0. , 2.5, 0.6, 0.4],
[2.5, 1.5, 2.8, 0. , 0. , 3.1, 1.9],
[1. , 0.8, 1.3, 0. , ... | <p>Use advanced indexing together with <code>np.ix_</code>:</p>
<pre><code>>>> import numpy as np
>>>
>>> X = np.array( ([[0. , 2.8, 3.5, 0. , 2.5, 1. , 0.8],
... [0. , 0. , 0. , 0. , 0. , 0. , 0. ],
... [3.5, 2.5, 0. , 0. , 2.8, 1.3, 1.1],
... [3.6, 3.8, 3.3, 0. , 2.5, 0.6, 0.4],
... | python|numpy|row | 2 |
356,917 | 50,554,600 | How to correctly compare elements of 3 different numpy arrays? | <p>I'm trying to compare elements at the same index from 3 different arrays. When I try <code>if arr1[i] == arr2[i]</code> I get the <code>The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</code>. Here's the whole function:</p>
<pre><code>def tmr(arr1, arr2, arr3):
arr4 = arr1... | <p>Interpreting this as for the intended result in your last example using <code>zip</code>, try:</p>
<pre><code>arr4 = arr1[np.equal(arr1, arr2) & np.equal(arr2, arr3)]
</code></pre>
<p>For the interpretation in your first code block you can use list comprehension:</p>
<pre><code>list4 = [arr1[i] if arr1[i] == ... | python|python-3.x|numpy|comparison | 0 |
356,918 | 50,298,705 | pandas DataFrame to list of dicts using to_json() | <p>So, i'm reading a xlsx file with pandas, then parsing the datetime (excel's a float)</p>
<p>Then I need to parse it into Json, and I'm running into some problems.</p>
<p>STEP 1 (Before parsing with to_json())</p>
<pre><code>df = pandas.read_excel('test.xlsx', names=['date', 'value', 'source'])
df['date'] = pandas... | <p>You'll need a couple of fixes—</p>
<ol>
<li>Convert your date column to string, because as it currently is, your datetime column is being coerced to Unix integer timestamps. Alternatively, use the <code>date_format</code> argument with <code>to_json</code> as the other answer suggests.</li>
<li>Change the orient wh... | python|json|string|pandas|datetime | 2 |
356,919 | 50,393,860 | How to start from beginning of the script after an exit? | <p>I have lots of xml files and I want to extract some information from them, but some file doesn’t contain any information. So when I run my script on an empty file then I stop my script. But I don’t know to take next file in my directory if the current file is empty.
Below a small part of my script. </p>
<pre><code... | <p>I would use the sentence "try". If you have a loop which opens the xml files, with this order it tries open the file and if it does not exit, pass and it does not raise the error.</p>
<pre><code>for ...
try:
(action)
except:
pass #(or another action)
</code></pre> | python|xml|pandas | 0 |
356,920 | 50,535,073 | Pandas - Merge rows in a DataFrame | <p>I'm trying to cleanup some data</p>
<p>The dataframe currently look something like this:</p>
<pre><code> id data data2
0 12 NaN 50.0
1 12 a 50.0
2 12 a NaN
3 52 b NaN
4 52 NaN 20.0
5 52 NaN 20.0
</code></pre>
<p>I'd like to collapse the rows to remove duplicate entries and keep o... | <p>You need:</p>
<pre><code>df.groupby('id', as_index=False).first()
</code></pre>
<p>Output:</p>
<pre><code> id data data2
0 12 a 50.0
1 52 b 20.0
</code></pre> | python|pandas|dataframe | 2 |
356,921 | 50,558,077 | Convert JSON to CSV with pandas | <p>I have a JSON file which contains 46k+ tweets in english and other languages as well which I want to save as csv file. Below is a part of json file.</p>
<pre><code> [{"user_id": 938118866135343104, "date_time": "03/20/2018 18:38:35", "tweet_content": "RT @PTISPOfficial: پاکستان تحریک انصاف کے وائس چیئرمین شاہ مح... | <p>You should just be able to use Pandas as follows:</p>
<pre><code>import pandas as pd
with open('PeshVsQuetta.json', encoding='utf-8-sig') as f_input:
df = pd.read_json(f_input)
df.to_csv('PeshVsQuetta.csv', encoding='utf-8', index=False)
</code></pre>
<p>This assumes that your JSON file contains a BOM at the... | python|json|python-3.x|pandas|csv | 5 |
356,922 | 50,319,733 | Combine rows to remove duplicates in CSV Python and Pandas | <p>I'm trying to combine multiple sets of rows together to remove duplicates in a CSV, using python and pandas. Based on a common value, the 'ID', Where there are duplicate rows the values from another column 'HostAffected' should be combined with a line break. Similar to this post: <a href="https://stackoverflow.com/q... | <p>After comments we get it <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow noreferrer"><code>strip</code></a> if traling wthitespaces with <code>apply</code> and <code>join</code> by <code>line break</code>:</p>
<pre><code>df['Description'] = df['Description'... | python|pandas|csv|dataframe|pandas-groupby | 0 |
356,923 | 45,293,759 | pip installation error for tensorflow | <p>I was trying to install tensorflow from source on ubuntu 14.04, python 2.7.
I followed the steps from "tensorflow.org" for source installation.
I had completed all the steps, such as bazel installation, python dependencies installation.
In the final step for sudo pip installation; the command was as follows:-</p>
<... | <p>I didn't figure out the root of the problem, but for what its worth I skipped the tensorboard issue by installing an older version (1.2.0 worked for me)</p>
<pre><code>pip install https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.2.0-cp27-none-linux_x86_64.whl
</code></pre> | python-2.7|ubuntu|tensorflow | 1 |
356,924 | 45,685,676 | Gpu util is 0 when run tensorflow training job, and context switch is very high | <pre><code>tensorflow: 1.2.0
gpu: TITAN X (Pascal)
driver: 370.28
</code></pre>
<p>I run distrubuted tensorflow to train image classify model, but see no gpu usage(actually,gpu util of mnist or other training job are also 0). </p>
<p>there's many poll system call when straced the training process(poll fd is /dev/nvid... | <p>I've had the same problem before, but it's because my gpu is not set to run -- I ran tensorflow on my CPU, but I thought it was run on GPU. If you do everything right, it won't be like this.</p>
<p>1) You could check this by use nvidia-smi to check: Despite that the gpu util is 0%, is the gpu memory util also 0% ? ... | tensorflow|gpu|nvidia | 1 |
356,925 | 45,687,917 | Kernel dead running a simple average operation using Python | <p>I am running a simple average operation over three columns. I am transforming the monthly data into a quarterly average. The data looks like this: </p>
<pre><code>2000.1 2000.2 2000.3....
18 15 27
</code></pre>
<p>I want to transform it into </p>
<pre><code>2000.q1
20
</code></pre>
<p>Here is what I h... | <p>I think you need convert columns names <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> and then to <code>month period</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.to_p... | python|pandas|ipython-notebook | 0 |
356,926 | 45,302,781 | How to reshape my data for the convolution neural network model? | <p>I need to let input in my convolution neural network model a reshaping data,
But my problem is with line of code: </p>
<pre><code>model = Sequential()
input_traces = Input(shape=(3253,))
model.add(Convolution1D(nb_filter=32, filter_length=3,
activation='relu',input_shape = input_traces))
</code></pre>
<p>... | <p>I assume you are using the old version of Keras (since the <a href="https://github.com/fchollet/keras/releases/tag/2.0.0" rel="nofollow noreferrer">release 2.0</a>, <code>nb_filter</code> has changed to <code>filters</code>, therefore, you should follow the old documentation (e.g. <a href="https://faroit.github.io/k... | python|tensorflow|keras|deep-learning | 0 |
356,927 | 45,337,155 | Concatenate Data -Python | <p>I am working with data formatted in a .txt file in the format below:</p>
<pre><code>family1 1 0 0 2 0 2 2 0 0 0 1 0 1 1 0 0 0 0 1 NA NA 4
family1 2 0 0 2 2 1 4 0 0 0 0 0 0 0 0 0 0 0 0 NA NA 4
family1 3 0 0 2 5 1 2 0 0 0 1 1 0 1 1 1 0 0 0 NA NA 2
family2 1 0 0 2 5 2 1 1 1 1 0 0 0 0 0 0 0 0 0 NA NA 3
etc.
</code></p... | <p>You might find <code>combinations</code> from <code>itertools</code> to be helpful.</p>
<pre><code>from itertools import combinations
print([thing for thing in combinations((1,2,3), 2)])
</code></pre>
<p>Yields</p>
<pre><code>[(1, 2), (1, 3), (2, 3)]
</code></pre> | python|pandas | 1 |
356,928 | 45,599,279 | Adding series to Pandas dataframe yields column of NaN | <p>Using this data set (some cols and hundreds of rows omitted for brevity) . . . </p>
<pre><code> Year Ceremony Award Winner Name
0 1927/1928 1 Best Actress 0.0 Louise Dresser
1 1927/1928 1 Best Actress 1.0 Janet Gaynor
2 1937 10 Best Actress ... | <p>You can join your result on the initial data frame</p>
<pre><code>New_col = df.loc[df.Winner == 0.0, :].groupby('Name').Winner.count().rename('New_col')
df = df.join(New_col, on='Name')
</code></pre>
<p>Output :</p>
<pre><code> Award Ceremony Name Winner Year New_col
0 Best Actress ... | python|pandas | 2 |
356,929 | 45,329,840 | Python merging mostly duplicated rows, split column to other column | <p>input data is dataframe</p>
<pre><code>[
name1 name2 data1 data2
a x 1 ""
a y 2 ""
b x 3 ""
b y 4 ""
a x 5 ""
a y 6 ""
b x 7 ""
b y 8 ""
]
</code></pre>
<p>what I want is </p>
<pre><code>[
name1 name... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> with columns <code>name1</code> and <code>Series</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupB... | python|pandas | 2 |
356,930 | 45,424,010 | How can the name of the index column of a pandas DataFrame be changed? | <p>I've got a DataFrame that gets set up such that a column of country names is set as the index column. I want to change the title of that index column. This seems like a simple thing to do, but I can't find how to actually do it. How can it be done? How can the index "foods" column here be changed to "countries"?</p>... | <p>Try this:</p>
<pre><code>df = df.rename_axis("countries", axis=0).rename_axis(None, axis=1)
</code></pre>
<p>Demo:</p>
<pre><code>In [10]: df
Out[10]:
alcoholic drinks beverages carcase meat ...
countries
England 375 57 245
Northern Ireland ... | pandas | 2 |
356,931 | 45,439,662 | Building numpy from source in docker | <p>Hi everyone I am trying to build numpy from source in docker container.
This is my Dockerfile:</p>
<pre><code>FROM debian:testing
MAINTAINER Dr Suman Khanal <suman81765@gmail.com>
LABEL updated_at '2017-07-26'
WORKDIR /
RUN apt-get update \
&& apt-get install -y gnupg git wget build-essential python3 ... | <p>Here is working <code>Dockerfile</code>.</p>
<pre><code>FROM debian:testing
MAINTAINER Dr Suman Khanal <suman81765@gmail.com>
LABEL updated_at '2017-07-26'
WORKDIR /
RUN apt-get update \
&& apt-get install -y gnupg git wget build-essential python3 python3-dev \
&& apt-get install -y python... | python-3.x|numpy|docker | 0 |
356,932 | 45,361,340 | How do I create the counts of the column values, grouped by values in the other column in Pandas? | <p>I have a dataframe df that has values: </p>
<pre><code>ID Status
1 A
2 B
5 A
1 A
3 B
4 B
5 B
</code></pre>
<p>I need to group column ID by the column Status. The issue is that ID can have duplicates, that can have the same or different codes. </p>
<p>The code I have is... | <p>You need to <code>groupby</code> and <code>count</code>:</p>
<pre><code>df.groupby('Status')['Status'].count()
</code></pre>
<p>Output:</p>
<pre><code>Status
A 3
B 4
Name: Status, dtype: int64
</code></pre> | python|pandas|group-by|unique | 3 |
356,933 | 45,410,300 | tensorflow/ improved wgan-gp code that i writed diverged very quickly, | <p>Here is my code :</p>
<pre><code>DEPTH = 64
OUTPUT_SIZE = 28
batch_size = 16:
def Discriminator(name,inputs):
with tf.variable_scope(name):
output = tf.reshape(inputs, [-1, 28, 28, 1])
output1 = conv2d('d_conv_1', output, ksize=5, out_dim=DEPTH)
output2 = lrelu('d_lrelu_1', output1)
... | <p>Are you sure you enforce a Lipschitz constraint as done in the WGAN paper?</p>
<p>It is done in their paper by having a strong limit one the weights of the discriminator.</p>
<p><a href="https://arxiv.org/pdf/1701.07875.pdf" rel="nofollow noreferrer">Original WGAN paper</a></p> | tensorflow | 0 |
356,934 | 45,467,758 | How to do elementwise multiplication between a sparse and a dense tensors in tensorflow? | <p>Tensorflow has the implementation <code>tf.sparse_tensor_dense_matmul</code> of sparse to dense matrix multiplication, but does it have sparse to dense elementwise multiplication (the two tensors having the same shape)? I would like to avoid converting my sparse tensor to a dense one as it wouldn't fit in memory.... | <p>I don't believe there is a built-in function, but you can do this by hand relatively easily, at least if you don't intend to support broadcasting. If <code>x</code> and <code>y</code> are resp. your sparse and dense tensor,</p>
<pre><code>res = tf.SparseTensor(x.indices, tf.gather_nd(y, x.indices) * x.values, x.den... | python|tensorflow|sparse-matrix | 1 |
356,935 | 45,685,254 | How to efficiently assign unique ID to individuals with multiple entries based on name in very large df | <p>I'd like to take a dataset with a bunch of different unique individuals, each with multiple entries, and assign each individual a unique id for all of their entries. Here's an example of the df:</p>
<pre><code> FirstName LastName id
0 Tom Jones 1
1 Tom Jones 1
2 David Smith ... | <p>This approach uses <code>.groupby()</code> and <code>.ngroup()</code> (new in Pandas 0.20.2) to create the <code>id</code> column:</p>
<pre><code>df['id'] = df.groupby(['LastName','FirstName']).ngroup()
>>> df
First Second id
0 Tom Jones 0
1 Tom Jones 0
2 David Smith 1
3 ... | python|pandas|dataframe|indexing | 42 |
356,936 | 45,400,713 | PIL image _crop to tensor, in tensorflow | <p>I am a student studying about deeplearning.
I'm using tensroflow framework and make a code.
So i have a question.
I make a crop image using Pil.image.crop
but when I training the Pil.image.crop can't assign to tensor.
so How can i assign cropped image to tensor.
Plz give me a advice.
Thank you.
here is my github add... | <p>You can do it with <code>tf.image.crop_and_resize</code>. Here is an example:</p>
<pre><code>from scipy.misc import imread
img = imread('flower.jpg')
# image placeholder
X = tf.placeholder(dtype=tf.uint8, shape=(1, 300,300,3))
# You need to set the area to crop in boxes and resize it to in crop_size
Y = tf.image... | image|tensorflow | 0 |
356,937 | 45,382,843 | Merge Pandas Dataframe using "to_frame" without duplicates | <p>I am merging one column from DataFrame (df1) with another DataFrame (df2 where both have the same index. The result of this operation gives me a lot more rows that I started with (duplicates). Is there a way to avoid duplicates? Please see the example codes below to replicate my issue.</p>
<pre><code>df1 = pd.DataF... | <p>What you want to do is concatenate as follows:</p>
<pre><code>pd.concat([df1, df2['Flow'].to_frame()], axis=1)
</code></pre>
<p>...which returns your desired output. The <code>axis=1</code> argument let's you "glue on" extra columns.</p>
<p>As to why your join is returning twice as many entries for <code>Sample_... | python|pandas|numpy | 1 |
356,938 | 45,458,719 | Using the value of of a Tensor as the shape of another? | <p>I have the following two lines in my code:</p>
<pre><code>numSequences = tf.placeholder(tf.float32, shape=())
...
prediction = tf.reshape(predictionFlat, [numSequences, sequenceLength, vocabSize])
</code></pre>
<p>Is it possible to extract the scalar value out of the <code>numSequences</code> tensor to use it as a... | <p>Yes, tensor shapes can usually be tensors themselves, however they need to be of integer type.</p>
<pre><code>import tensorflow as tf
x = tf.constant([2, 3], dtype=tf.int32)
y = tf.zeros((x[0], x[1], 5))
sess = tf.InteractiveSession()
print(y.eval().shape)
# (2, 3, 5)
</code></pre>
<p><strong>EDIT</strong></p>
... | python|tensorflow | 2 |
356,939 | 45,492,220 | using a regex pattern to filter rows from a pandas dataframe | <p>Suppose I have a pandas dataframe like this:</p>
<pre><code> Word Ratings
0 TLYSFFPK 1
1 SVLENFVGR 2
2 SVFNHAIRK 3
3 KAGEVFIHK 4
</code></pre>
<p>How can I use regex in pandas to filter out the rows that have the word that match the following regex pattern but keep the dat... | <p>Demo:</p>
<pre><code>In [2]: df
Out[2]:
Word Ratings
0 TLYSFFPK 1
1 SVLENFVGR 2
2 SVFNHAIRH 3
3 KAGEVFIHK 4
In [3]: pat = r'\b.[VIFY][MLFYIA]\w+[LIYVF].[KR]\b'
In [4]: df.Word.str.contains(pat)
Out[4]:
0 False
1 True
2 False
3 False
Name: Word, dtype: bool
I... | regex|python-3.x|pandas | 9 |
356,940 | 45,721,207 | Don't understand: ValueError: Can only tuple-index with a MultiIndex | <p>I know this question already exists, but the answers havent helped me. </p>
<pre><code>def function(T,theta,A):
x=(T-theta)/A
return(x)
filen=pd.read_csv('filename')
filelist=[file,file2,...,filen)
labels=['name1','name2',...]
colors=['red','blue','green',...]
for i in range(len(filelist)):
x=filelist[i]... | <p>Try to change:</p>
<pre><code>w=np.where(x>170)
</code></pre>
<p>to:</p>
<pre><code>w = x[x>170]
</code></pre>
<p><code>np.where</code> returns a tuple in your case:</p>
<blockquote>
<h2>Returns</h2>
<pre><code>If only `condition` is given, return the tuple
``condition.nonzero()``, the indices where `c... | python|pandas | 3 |
356,941 | 45,535,251 | Tensorflow Convolutional Network that returns an image (no logits) | <p>I have undertaken a project in which I must use a convolutional network which will output an image instead of logit class predictors. For this purpose I've adapter the CNN code I downloaded from <a href="https://github.com/aymericdamien/TensorFlow-Examples" rel="nofollow noreferrer">https://github.com/aymericdamien/... | <p>you need to start the queue runner to get the data for optimizing from the queue. </p>
<pre><code>....
coord = tf.train.Coordinator()
with tf.Session() as sess:
sess.run(init)
tf.train.start_queue_runners(sess=sess, coord=coord)
....
# also use tf.nn.sparse_softmax_cross_entropy_with_logits for cost
</c... | python|tensorflow|deep-learning | 0 |
356,942 | 45,313,681 | Serving the inception model v3 in Java using SavedModelBundle | <p>Using org.tensorflow:tensorflow:1.3.0-rc0.</p>
<p>I have generated the inception model from the checkpoints as per the tutorial <a href="https://tensorflow.github.io/serving/serving_inception" rel="nofollow noreferrer">https://tensorflow.github.io/serving/serving_inception</a>:</p>
<pre><code>inception_saved_model... | <p>You need to feed your input (here your tensor image) associated to the name of its node in the graph, from the link you posted it seems that the tutorial uses "images" (see here <a href="https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/inception_client.py#L49" rel="nofollow noreferrer">ht... | java|tensorflow|tensorflow-serving | 0 |
356,943 | 45,613,391 | How to properly plot dataframe with matplotlib | <p><a href="https://i.stack.imgur.com/C4iNQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C4iNQ.png" alt="enter image description here"></a>I'm trying to plot a dataframe with two columns:</p>
<pre><code> Compound_ID,Averages
0 M0001,0.75
1 M0002,0.87
2 M003,0.45
</code></pre>
<p>Inst... | <p>You can do this:</p>
<pre><code>plt.plot(df['Averages'])
plt.xticks(range(len(df['Compound_ID'])) , df['Compound_ID'])
</code></pre>
<p>This way you plot xticks separately. The first element is numerical indexes, second - names.</p> | python|pandas|matplotlib|dataframe | 3 |
356,944 | 45,287,145 | Most efficient way to convert empty(ish) strings to null | <p>I have a pandas series that contains both empty strings and strings with nothing but whitespace. I want to convert these to a 'null' value (e.g. None).</p>
<pre><code>def empty_str_to_null(s):
"""Convert empty strings to None (null)"""
s.loc[s.str.strip().str.len() == 0] = None
return s
foo = pd.Series... | <p>Here's one approach -</p>
<pre><code>def empty_str_to_null_slicer(s):
a = s.values.astype(str)
# slicer_vectorized from https://stackoverflow.com/a/39045337/
mask = (slicer_vectorized(a,0,1)==' ') | (a=='')
s[mask] = None
return s
</code></pre>
<p>Sample run -</p>
<pre><code>In [245]: s = pd.S... | python|pandas | 0 |
356,945 | 45,281,557 | Simple/Beginner Excel Transformation in Pandas | <p>I'm have an excel document formatted like so (Columns are datasets, Rows are cell types, values are comma-delineated gene names)
<img src="https://i.stack.imgur.com/prRrt.png" alt="Input Excel Format"></p>
<p>I would like to reformat the sheet like so (Columns are still datasets, but Rows are now gene names, and va... | <p>There are duplicates in <code>gene</code>s, so need:</p>
<p>You need create <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a>,
then is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/... | python|excel|pandas|data-science | 2 |
356,946 | 45,494,649 | Return dataframe subset based on a list of boolean values | <p>I'm trying to slice a dataframe based on list of values, how would I go about this?</p>
<p>Say I have an expression or a list <code>l = [0,1,0,0,1,1,0,0,0,1]</code></p>
<p>How to return those rows in a dataframe, <code>df</code>, when the corresponding value in the expression/list is 1? In this example, I would in... | <p>You can use masking here:</p>
<pre><code>df[np.array([0,1,0,0,1,1,0,0,0,1],dtype=bool)]
</code></pre>
<p>So we construct a boolean array with true and false. Every place where the array is True is a row we select.</p>
<p>Mind that we do <em>not</em> filter inplace. In order to retrieve the result, you have to ass... | python|pandas|dataframe | 22 |
356,947 | 45,447,848 | Check for words from list and remove those words in pandas dataframe column | <p>I have a list as follows,</p>
<pre><code>remove_words = ['abc', 'deff', 'pls']
</code></pre>
<p>The following is the data frame which I am having with column name 'string'</p>
<pre><code> data['string']
0 abc stack overflow
1 abc123
2 deff comedy
3 definitely
4 pls lkjh
5 pls1234
</code></p... | <p>Try this:</p>
<pre><code>In [98]: pat = r'\b(?:{})\b'.format('|'.join(remove_words))
In [99]: pat
Out[99]: '\\b(?:abc|def|pls)\\b'
In [100]: df['new'] = df['string'].str.replace(pat, '')
In [101]: df
Out[101]:
string new
0 abc stack overflow stack overflow
1 abc123 ... | python|regex|python-2.7|pandas|replace | 24 |
356,948 | 45,448,434 | How do I apply css formatting to a pd.DataFrame and not display index column | <p>Put simply, my goal is to display a table in my html page that looks 'normal' (aka all headers are on a single line, there are no line numbers) and each cell is color-coded according to a rule lookup (need flexibility to look up a different rule for each cell.) My data is being stored in a pd.DataFrame object. Somet... | <p>You can use <a href="https://i.stack.imgur.com/djEfC.png" rel="nofollow noreferrer"><strong><code>pd.DataFrame.style.set_table_styles</code></strong></a> </p>
<p>We can keep using the same styler object and updating it.</p>
<pre><code>dfs = df.style
for col in df.columns:
dfs.applymap(basic_limits[col], subse... | python|css|pandas|dataframe|pandas-styles | 2 |
356,949 | 45,316,906 | Working with large (+15 gb) CSV datasets and Pandas/XGBoost | <p>I am trying to find a means of starting to work with very large CSV files in Pandas, ultimately to be able to do some machine learning with XGBoost. </p>
<p>I am torn between using mySQL or some sqllite framework to manage chunks of my data; my issue is in the machine learning aspect of it later on, and in loading ... | <p><a href="http://matthewrocklin.com/blog/work/2017/03/28/dask-xgboost" rel="noreferrer">This blogpost</a> goes through an example using XGBoost on a large CSV dataset. However it did so by using a distributed cluster with enough RAM to fit the entire dataset in memory at once. While many dask.dataframe operations c... | python|pandas|machine-learning|xgboost|dask | 5 |
356,950 | 45,581,197 | Trying to install OpenCV with Matplotlab | <p>I am attempting to install OpenCV on my linux computerI followed this installation guide:</p>
<p><strong>Linux / Mac Users:</strong></p>
<p>pip3 install numpy or apt-get install python3-numpy. You may need to apt-get install python3-pip.</p>
<p>pip3 install matplotlib or apt-get install python3-matplotlib.</p>
<... | <p>Use <a href="https://www.continuum.io/downloads" rel="nofollow noreferrer">Anaconda</a>, there are download for Windows, Linux and Mac. Installation is easy.</p>
<p>I would suggest you download Anaconda2.
Then install with command (on Linux) (more <a href="https://docs.continuum.io/anaconda/install/linux" rel="no... | python|opencv|numpy | 0 |
356,951 | 45,672,933 | Avoid for loop using numpy vectors | <p>I am creating x and y coordinates of a line at many different angles. How can I vectorise the following code, and avoid the need for a for loop?</p>
<pre><code># set up vector line equation that goes through 180 deg
v_1 = np.array([0,0]) #step on vector
mu = np.linspace(0, 2.5, 1000)
angle_step = 100
theta = np.lin... | <p>I think this is what you need:</p>
<pre><code>x1, y1 = np.rint(v_1[0] + mu[:,None] * v_2[0]).astype(int), np.rint(v_1[1] + mu[:,None] * v_2[:, i][1]).astype(int)
x2, y2 = np.rint(v_1[0] - mu[:,None] * v_2[:, i][0]).astype(int), np.rint(v_1[1] - mu[:,None] * v_2[:, i][1]).astype(int)
</code></pre>
<p><code>mu[:,Non... | python|numpy|vectorization | 0 |
356,952 | 45,698,673 | Vectorizing Numpy for loops | <p>I'm currently trying to vectorize a few operations in NumPy. s is a very large number (10000) and X represents a numpy array with around 1200000</p>
<pre><code>for element1 in range(1,s+1):
d = np.zeros(s)
for element2 in range(1,s+1):
d[element2-1] = norm(np.subtract(X[0:n,element1],X[0:n,element2... | <p>Those are basically euclidean distances on a slice off the input array -</p>
<pre><code>from scipy.spatial.distance import cdist, pdist, squareform
X_slice = X[0:n,1:s+1]
d_all = squareform(pdist(X_slice.T))
</code></pre>
<p>Thus, inside the first loop, it would be just a slice from the output <code>d_all</code> ... | python|arrays|numpy | 0 |
356,953 | 45,378,307 | Matrix Inversion in CBLAS/LAPACK vs Python | <p>The matrix I am trying to invert is:</p>
<pre><code> [ 1 0 1]
A = [ 2 0 1]
[-1 1 1]
</code></pre>
<p>The true inverse is:</p>
<pre><code> [-1 1 0]
A^-1 = [-3 2 1]
[ 2 -1 0]
</code></pre>
<p>Using Python's numpy.linalg.inv, I get the correct answer. One of my routines for matrix in... | <p>It seems that <a href="https://github.com/numpy/numpy/blob/v1.15.1/numpy/linalg/linalg.py#L468-L533" rel="nofollow noreferrer"><code>numpy.linalg.inv</code></a> is a lite version of the <a href="https://github.com/scipy/scipy/blob/v1.1.0/scipy/linalg/basic.py#L907-L979" rel="nofollow noreferrer">scipy.linalg.inv</a>... | numpy|matrix|lapack|matrix-inverse|cblas | 1 |
356,954 | 45,521,025 | The loss function decreases, but accuracy on train set does not change in tensorflow | <p>I am trying to implement a simple gender classifier using deep convolutional neural networks using tensorflow. I have found this <a href="http://www.cv-foundation.org/openaccess/content_cvpr_workshops_2015/W08/papers/Levi_Age_and_Gender_2015_CVPR_paper.pdf" rel="noreferrer">model</a> and implemented it.</p>
<pre><co... | <p>Proper initialisation of weights is often crucial to getting deeper neural nets to train.</p>
<p>Xavier initialisation is derived with the goal of ensuring that the variance of the output at each neuron is expected to be 1.0 (see <a href="http://andyljones.tumblr.com/post/110998971763/an-explanation-of-xavier-initi... | tensorflow|neural-network|deep-learning|conv-neural-network|loss | 3 |
356,955 | 45,418,953 | Vertical lines do not appear in matplotlib plot | <p>I have a code which allows me to plot two timeseries of data. I also have a number of events which I plot as a series of vertical lines within the timeseries. I have this timeseries for three years: 2015, 2016, and 2017. My code works well for 2015 and 2016, and I produce a graph like so (this is for 2016):<a href="... | <p>In a comment, you say you got the idea for your values for <code>ymin</code> and <code>ymax</code> from <a href="https://stackoverflow.com/questions/21488085/pandas-graphing-a-timeseries-with-vertical-lines-at-selected-dates">Pandas graphing a timeseries, with vertical lines at selected dates</a>, but the example th... | python|numpy|matplotlib|plot | 5 |
356,956 | 62,776,280 | Pandas read csv with repeating header rows | <p>I have a csv file where the data is as follows:</p>
<pre><code> Col1 Col2 Col3
v1 5 9 5
v2 6 10 6
Col1 Col2 Col3
x1 2 4 6
x2 1 2 10
x3 10 2 1
Col1 Col2 Col3
y1 9 2 7
</code></pre>
<p>i.e. there are 3 different ta... | <p>You can read the data and remove the rows that are identical to the columns:</p>
<pre><code>df = pd.read_csv('file.csv')
df = df[df.ne(df.columns).any(1)]
</code></pre>
<p>Output:</p>
<pre><code> Col1 Col2 Col3
v1 5 9 5
v2 6 10 6
x1 2 4 6
x2 1 2 10
x3 10 2 1
y1 9 2 ... | pandas|python-3.8 | 4 |
356,957 | 62,781,587 | error : module 'tensorflow._api.v2.train' has no attribute 'GradientDescentOptimizer' what is the solution | <pre><code>import tensorflow as tf
# the equation is : 4x+2 = 0
unknownvalue = tf.Variable(0.0)
a = tf.constant(4.0)
b = tf.constant(2.0)
c = tf.multiply(unknownvalue,a) # 4x
equation = tf.add(c,b) # 4x+2
zerovalue = tf.constant(0.0)
diff = tf.square(equation-zerovalue) # differnce is : 4x+2 - 0
solving = tf.tra... | <p>tensorflow 2 has the gradient descent located in keras.optimizers, change it to this: <code>tf.keras.optimizers.SGD().minimize(var_list=diff)</code></p>
<p>Packages have been moved around and reorganized.</p>
<p>Here is a link that will show you the changes that you need to make in order to transition your code from... | python|tensorflow|tensorflow2.0 | 0 |
356,958 | 62,894,729 | Averaging untill an index value that corresponds with the value of another array in Numpy | <p>I have one array in which the values should be averaged until the day that is given as a value in another array. The first array has 365 days as the first axis, and the second array corresponds to specific julian dates, ranging from 0 to 365, from which the value from the first array should be averaged.</p>
<pre><co... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.cumsum.html?highlight=cumsum#numpy.cumsum" rel="nofollow noreferrer">numpy.cumsum</a> to calculate the cumulative sum along <code>axis=0</code> then taking some index and dividing by this index give the average till this index.</p>
<pre><cod... | numpy|multidimensional-array|vectorization|array-broadcasting|numpy-slicing | 1 |
356,959 | 62,857,026 | Pandas merger multiple rows and columns | <p>Hi I have a data frame which goes like this:</p>
<pre><code>index event action date
0 event1 action1 date1
1 event2 action2 date1
2 event3 action3 date2
3 event4 action4 date2
</code></pre>
<p>I want to merge both columns and row. I have already merged the rows using <code>groupby</code> and <... | <p>try this, <code>groupby</code> + <code>zip</code></p>
<pre><code>(
df.groupby('date')['event', 'action']
.apply(lambda x:
" and ".join([f"for {x} do {y}"
for x, y in zip(x['event'], x['action'])]))
)
</code></pre> | python|pandas|pandas-groupby | 0 |
356,960 | 62,536,722 | create new column Pandas df with str.contains gives: Length of values does not match length of index | <p>I've seen many almost similar questions, but I still didn't find the right answer.</p>
<p>My df has a column ['Name'], containing names of all kind of stores. I want to categorize these by giving, for example, a grocery store the label 'Supermarket' in a new column df['Type'].</p>
<p>I first did this:</p>
<pre><code... | <pre><code># create a selection
boolean_indexer = df['Naam'].str.contains('Albert')
# create your new column
df.loc[boolean_indexer, 'Type'] = 'Supermarkt'
</code></pre> | python|pandas | 1 |
356,961 | 62,583,781 | Add rows for missing data grouped by another column in Pandas DataFrame | <p>I have a Pandas dataframe where for certain <code>dates</code> certain <code>products</code> are missing. I want to add those rows to the dataframe and assign them a <code>sales</code> value of 0. How can I do that?</p>
<pre><code># Sample dataframe
import pandas as pd
df = pd.DataFrame({
'date': ['2020-01-01', ... | <p>Try with <code>pivot</code></p>
<pre><code>df=df.pivot(*df.columns).fillna(0).stack().to_frame('sales').reset_index()
df
Out[120]:
date product sales
0 2020-01-01 clothes 120.0
1 2020-01-01 food 50.0
2 2020-01-01 glass 100.0
3 2020-01-02 clothes 0.0
4 2020-01-02 food 60.0
5 20... | python|pandas | 2 |
356,962 | 62,638,048 | Facing Index out of bounds Error when replacing NaNs in a column using a function in Pandas | <p>I am trying to replace NAN values using below function,but i am getting Index out of Bound Error.<a href="https://i.stack.imgur.com/sZh05.png" rel="nofollow noreferrer">This</a> is my sample Dataframe. It has columns(Date,Centre_Name,Commodity_Name,Price,Year).I am trying to replace Price column missing values using... | <p>in the second script replace <code>data.iloc</code> with <code>data.loc</code></p> | python|pandas|machine-learning|data-analysis|missing-data | 0 |
356,963 | 62,589,270 | Filter sub-dataframe in nested for-loop | <p>I'd like to filter a dataframe to get sub-datasets in a nested for-loop, then apply <code>some_function</code> to each sub-datasets, pick one row from each sub-dataset based on time duration column called <code>TimeDiff</code>, then concatenate all the individual rows into one dataframe.</p>
<p>Here's the code:</p>
... | <p>IIUC you want to return a <code>pd.DataFrame</code> containing, for each <code>YearMonth</code> and for each <code>Id</code>, the maximum <code>TimeDiff</code> under 5 minutes. Is that right ?</p>
<p>A few comment on your code first:</p>
<ul>
<li>At the first iteration of <code>total_t.append(pd.Series(long_event))<... | python|pandas|dataframe|for-loop|nested | 0 |
356,964 | 62,826,054 | How to reduce a pandas Series by performing an operation on every set of N sequential elements | <p>Say I have a pandas series, and I want to take the mean of every set of 8 rows. I don't have prior knowledge of the size of the series, and the index may not be 0-based. I currently have the following</p>
<pre class="lang-py prettyprint-override"><code>N = 8
s = pd.Series(np.random.random(50 * N))
n_sets = s.shape... | <p>You could try with <code>groupby</code>, by slicing the index in <code>N</code> (you can see <a href="https://stackoverflow.com/a/54358895/13676202">here</a> an explanation of the slicing), and then use <code>pd.Series.mean()</code>:</p>
<pre><code>newout_array=s.groupby(s.index//N).mean().to_list()
</code></pre>
<p... | python|pandas|space-efficiency | 1 |
356,965 | 62,535,082 | Sort DataFrame by a datetime object from Jan to dec | <p>I have a dataframe. Aggregating the datframe using the pandas groupby:</p>
<pre><code>df.groupby(["Date", "company"]).producttyp.size().reset_index()
</code></pre>
<p>Results are displayed in the table below</p>
<pre><code> Date company producttyp
0 Apr-2020 proA1 1... | <p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_datetime</code></a> to convert the <code>Date</code> column to the pandas datetime series and assign this to a temporary column in a grouped df, then use <a href="https://pandas.pyd... | python|python-3.x|pandas|dataframe|pandas-groupby | 2 |
356,966 | 62,524,725 | Creating multiple subsets of a timeseries pandas dataframe by weekly intervals | <p>New to python. I have a dataframe with a date time column (essentially a huge time series data). I basically want to divide this into multiple subsets where each subset data frame contains one week worth of data (starting from the first timestamp). I have been trying this with groupBy and Grouper but it returns tupl... | <p>If your dataset is really big, it could be worth externalising this work to a time-series database and then query it to get each week you are interested in. These results can then be loaded into pandas, but the database handles the heavy lifting. For example in QuestDB you could get the current week as follows</p>
<... | python|pandas|time-series|pandas-groupby | 1 |
356,967 | 62,875,960 | Pytorch: multiply two high dimensions tensor, (2, 5, 3) * (2, 5) into (2, 5, 3) | <p>I want to multiply two high dimensions tensor, (2, 5, 3) * (2, 5) into (2, 5, 3), which multiply each row vector by a scalar.</p>
<p>E.g.</p>
<pre><code>emb = nn.Embedding(6, 3)
input = torch.tensor([[1, 2, 3, 4, 5,],
[2, 3, 1, 4, 5,]])
input_emb = emb(input)
print(input.shape)
> torch.Si... | <p>You can by correctly aligning the dimensions of both tensors:</p>
<pre><code>import torch
from torch.nn import Embedding
emb = Embedding(6, 3)
inp = torch.tensor([[1, 2, 3, 4, 5,],
[2, 3, 1, 4, 5,]])
input_emb = emb(inp)
inp[...,None] * input_emb
tensor([[[-0.3069, -0.7727, -0.3772],
... | python|pytorch|tensor | 1 |
356,968 | 62,819,482 | Efficient way of row-based calculation in Pandas | <p>I have a dataframe with 2 columns: class (0/1) and time (integer). I need to append a third column which will be the remaining time to get a class 1 row.</p>
<pre><code>df = pd.DataFrame([
[1,101], [1,104],
[0,107], [0,110], [0,123],
[1,156],
[0,167]],
columns=['class', 'time'])
</code></pre>
<ul>
... | <p>Not too much different from @Datanovice.</p>
<p>Use <code>where</code> to <code>NaN</code> the time for <code>df['class'] == 1</code>, then <code>bfill</code> to get the first <code>df['class'] == 0</code> value. This Series gets the correct 'time' to subtract regardless of class so we can do a normal subtraction.<... | python|pandas|lambda|pandas-apply | 4 |
356,969 | 62,622,455 | Tensorflow.js: dtype of the feed (int32) is incompatible with that of the key 'input_1' (float32) | <p>I did a transfer learning from Mobilenet to my model, and trying to do the prediction:</p>
<pre class="lang-js prettyprint-override"><code>const img = document.querySelector("img");
const image = tf.reshape(tf.fromPixels(img), [1, 224, 224, 3]);
const pretrainedModelPrediction = pretrainedModel.predict(ima... | <p><code>image</code> is of type <code>int32</code>. You can cast it to <code>float32</code>.</p>
<pre><code> pretrainedModel.predict(image.cast('float32'));
</code></pre> | javascript|tensorflow|tensorflow.js | 1 |
356,970 | 62,806,681 | pytorch KLDivLoss loss is negative | <p>my target is training a span prediction model</p>
<p>which can predict the position in the BERT output sequence</p>
<p>my input's shape is (batch_size, max_sequence_len(512),embedding_size(768))</p>
<p>output's shape will be (batch_size , max_sequence_len , 1) and the third dim is stand for kind a probability , then... | <p><a href="https://pytorch.org/docs/stable/nn.html#torch.nn.KLDivLoss" rel="noreferrer"><code>nn.KLDivLoss</code></a> expects the input to be log-probabilties.</p>
<p>From the documentation:</p>
<blockquote>
<p>As with <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.NLLLoss" rel="noreferrer"><code>NLLLoss</c... | python|machine-learning|nlp|pytorch|loss-function | 6 |
356,971 | 62,756,540 | Django serve zipped GeoDataFrame shapefile from memeory as download | <p>I have a Django GIS-related application where users can download shp files. I have the geopandas GeoDataFrame object. I can easily convert it to a zipfile and then read the zipfile to the user when they want to download it:</p>
<pre><code>
from django.http import HttpResponse
import geopandas as gpd
import shapely
i... | <p>It would be possible to create the file and delete it instantly after serving by using <a href="https://docs.python.org/3/library/tempfile.html" rel="nofollow noreferrer">tempfile</a>. So not the answer you were looking for but maybe still of help. According to <a href="https://stackoverflow.com/a/34250008/15353043"... | python|django|zip|geopandas | 5 |
356,972 | 62,496,343 | Pandas Merge with interpolation | <p>I have two dataframes df1 and df2</p>
<p><strong>df1</strong></p>
<p><a href="https://i.stack.imgur.com/Wo11B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wo11B.png" alt="Date/Time S
1/1/2012 0:00 7.51
1/1/2012 1:00 7.28
1/1/2012 2:00 6.75
1/1/2012 3:00 7.80
1/1/2012 4:00 8.18
1/1/... | <p>Assuming <code>df2</code> is sorted by column <code>S</code>, you can do:</p>
<pre><code>tmp = df1.assign(tmp=df1.S.apply(np.floor)).merge(df2.assign(tmp2=(df2.Val.shift(-1) - df2.Val)), how='outer', left_on='tmp', right_on='S')
tmp.loc[tmp.Val.isna(), 'S_x'] = 0
tmp['Val'] = (tmp['S_x'] - tmp['S_y'].fillna(0)) * tm... | python-3.x|pandas|dataframe|merge | 2 |
356,973 | 62,803,839 | Filling missing date (day) values with 0 | <p>I have a dataframe:</p>
<pre><code> day Datavalue
2020-06-01 3.179695
2020-06-02 0.132487
2020-06-08 3.179695
2020-06-09 3.179695
2020-06-10 3.179695
</code></pre>
<p>I would like to set a date range and add any dates that aren't in the dataframe as 0 for example:</p>
<pre><code> ... | <p>Assuming this is to be done for the entire DataFrame, use <code>asfreq</code>:</p>
<pre><code>df.set_index('day').asfreq('1D', fill_value=0)
Datavalue
day
2020-06-01 3.179695
2020-06-02 0.132487
2020-06-03 0.000000
2020-06-04 0.000000
2020-06-05 0.000000
2020-06-06 0.000000... | python|pandas|indexing | 3 |
356,974 | 62,673,073 | Exporting TFRecords training patches with Google Earth Engine (kernelSize issues) | <p>I've been using GEE to export some training patches from Sentinel-2 to be used in Python.
I could make it work, by following the GEE guide <a href="https://developers.google.com/earth-engine/tfrecord" rel="nofollow noreferrer">https://developers.google.com/earth-engine/tfrecord</a>, and using the <code>Export.image.... | <p>After some time trying to overcome this issue, I realized a not well documented behavior when one uses the kernel size to export patches from GEE.
Bundled with the exported TFRecord, there exists one <code>xml</code> file called <code>mixer</code>.
It doesn't matter if we use:</p>
<pre><code>'patchDimensions': [184,... | tensorflow|training-data|google-earth-engine|tfrecord | 0 |
356,975 | 62,660,270 | How to solve Key Error while XML File Parsing in Python | <p>I have the following XML file which I want to convert as a Pandas DataFrame.</p>
<pre><code>row {'Id': '-1', 'Reputation': '1', 'CreationDate': '2009-09-28T00:00:00.000', 'DisplayName': 'Community', 'LastAccessDate': '2010-11-10T17:25:34.627', 'WebsiteUrl': 'http://meta.stackexchange.com/', 'Location': 'on the serve... | <p>Error appears to be due to missing attributes in one or more of the <code><row></code> tags. Instead of explicitly assigning dictionary keys/values by each attribute consider retrieving <em>all</em> attributes. Doing so, the final <code>DataFrame</code> constructor will input <code>NAs</code> to rows with miss... | python-3.x|xml|pandas|dataframe|xml-parsing | 1 |
356,976 | 62,649,019 | How to create a new column in pandas iterating existing columns without getting this next error? | <p>i'm trying to create a new column, iterating existing ones, but I keep getting the same error,don't know what I'm doing wrong.</p>
<pre><code> import pandas as pd
data = pd.read_excel('AAPL.xlsx', sheet_name='Hoja1')
data.set_index('timestamp', inplace=True)
data1 = data.loc['2011-08-20':'2008-05-15'... | <p>I believe your loop can be done in pandas</p>
<pre><code>df['Upside 7%'] = 'Not OK'
df.loc[((df['high'] / df['open']) - 1) * 100 >= 0.07, 'Upside 7%'] = 'OK'
</code></pre> | python|pandas|loops|dataframe | 0 |
356,977 | 62,709,332 | Panda Slicing Notation whats better | <p>Basically I want to know what the difference between:</p>
<pre><code>data.iloc[0:2]
</code></pre>
<p>and</p>
<pre><code>data[0:2]
</code></pre>
<p>Wouldn't both of these pandas dataframes. return the same information? Does it matter with one I use?</p> | <p>They can be different when your DataFrame's indexes are different from the position.
<code>iloc</code> is based on the absolute position like a <code>list</code> in Python.
<code>loc</code> is based on the index of the DataFrame.</p>
<p>For example, if we have this DataFrame:</p>
<pre><code>df = pd.DataFrame([['a'],... | python|pandas|numpy | 0 |
356,978 | 62,536,131 | Is there explanation for mentioned code are available? | <p>Could you please share me the explanation for below mentioned codes. As I'm not able to understand these code by my own. I'm assumimg that this is defnine function for column but not sure about.</p>
<pre><code>def remove_common_text(lst):
if len(lst) > 4:
for itm in lst:
if len(itm... | <p>I am going to write what <code>remove_common_text(lst)</code> does. The stuff below is pandas, so perhaps someone else can answer it better than I can.</p>
<p>The parameter lst is supposed to be something like this: <code>[['a','b','c','d','e'],['a','b','1','d','e'],['a','b','2','d','e'],['a','b','3','d','e'],['a','... | python-3.x|pandas | 0 |
356,979 | 62,564,322 | Doing a pandas left merge with duplicate column names (want to delete left and keep right) | <p>So let's say I have df_1</p>
<pre><code> Day Month Amt
--------------- --------- ---------
Monday Jan 10
Tuesday Feb 20
Wednesday Feb 30
Thursday April 40
Friday April 50
</code></pre>... | <p>This answer is purely supplemental to the duplicate target. That is a much more comprehensive answer than this.</p>
<h2>Strategy #1</h2>
<p>there are two components to this problem.</p>
<h3>Use <code>df_2</code> to create a mapping.</h3>
<p>The intuitive way to do this is</p>
<pre><code>mapping = df_2.set_index('Mo... | python|pandas|join|merge | 3 |
356,980 | 62,492,707 | "ERROR: Invalid requirement: pip3 install torch==1.5.0+cpu torchvision==0.6.0+cpu -f", while deployment | <p>I'm deploying a application on Heroku and that application needs Torch module to install on the server and I'm unable to push the app using git because of this error....
I tried many methods but unable to push it...
Tell me what should I write in the requirements.txt in order to install torch</p> | <p>You need to write the url of wheel file (from <a href="https://download.pytorch.org/whl/torch_stable.html" rel="nofollow noreferrer">torch_stable.html</a>) of torch (and torchvision, if required) corresponding to the required version in your <code>requirements.txt</code> file. Then, <code>pip</code> will install the... | python|heroku|deployment|pytorch|torch | 0 |
356,981 | 62,702,548 | How to create a new column of NaN when adding a series to a DataFrame? | <p>This question might be confusing but I'm trying to add a series as a row to an already created DataFrame. Though if there's a column that's not already been created in the DataFrame I want to add one will NaN and the value from the series.</p>
<p>Here's my series:</p>
<pre><code>w1 0.195870
w3 0.072609
w4 0... | <p>How about <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> first with a union of <code>df.columns</code> and <code>series.index</code>:</p>
<pre><code>df = df.reindex(columns = (df.columns | series.index))
df.loc[3]... | pandas|numpy | 2 |
356,982 | 62,561,286 | Python - How to end routine by probability which updates itself with every 'iteration'? | <p>So I've been working on an adaptation of the Balloon Analogous Risk Task. The gist of it is that the participant gets 30 trials (3 condition, 10 trials per condition) and in each of these trials they can fill a balloon with air by pressing the space bar as often as they want. The larger the balloon, the larger the a... | <p>To test something with a certain probablity, you can in general do:</p>
<pre class="lang-py prettyprint-override"><code>import random
rnd_val = random.random() # Generates a pseudorandom value between 0 and 1
prob = 0.05
print(rnd_val < prob) # Prints True 5% of times, otherwise False
</code></pre>
<p>Knowing t... | python|python-3.x|python-2.7|numpy | 0 |
356,983 | 62,615,758 | How to get all possible array attributions of numpy arrays? | <ul>
<li>Python: get all possible array attributions of nd arrays. Use <code>itertools.product</code>?
<ul>
<li>If so, how?</li>
</ul>
</li>
<li>In Python, I have two n dimensions numpy arrays <code>A</code> and <code>B</code> (<code>B</code> is a zero array).</li>
<li>Such way <code>A.shape[i]<=B.shape[i]</code>, f... | <p>itertools product should work.</p>
<pre><code>import numpy as np
from itertools import product
A = np.ones((2,3))
B = np.zeros((3,4))
r_rng = range(B.shape[0]-A.shape[0]+1)
c_rng = range(B.shape[1]-A.shape[1]+1)
for i,j in product(r_rng, c_rng):
C = B.copy()
C[i:i+A.shape[0],j:j+A.shape[1]]=A
print(C,... | python|arrays|numpy | 2 |
356,984 | 62,563,923 | Pyspark EMR Notebook - Unable to save file to EMR environment | <p>This seems really basic but I can't seem to figure it out. I am working in a Pyspark Notebook on EMR and have taken a pyspark dataframe and converted it to a pandas dataframe using <code>toPandas()</code>.</p>
<p>Now, I would like to save this dataframe to the local environment using the following code:</p>
<pre><co... | <p>When you are running PySpark in EMR Notebook you are connecting to EMR cluster via Apache Livy. Therefore all your variables and dataframes are stored on the cluster and when you run <code>df.to_csv('file.csv')</code> you are trying to save CSV on the cluster and not in your local enviroment. I've struggled a bit, b... | pandas|pyspark|amazon-emr | 0 |
356,985 | 62,603,377 | Fastest Way to Find the Dot Product of a Large Matrix of Vectors | <p>I am looking for suggestions on the most efficient way to solve the following problem:</p>
<p>I have two arrays called A and B. They are both of shape NxNx3. They represent two 2D matrix of positions, where each position is a vector of x, y, and z coordinates.</p>
<p>I want to create a new array, called C, of shape ... | <p>With a bit of reshaping, we can use <code>matmul</code>. The idea is to treat the first 2 dimensions as the 'batch' dimensions, and to the <code>dot</code> on the last:</p>
<pre><code>In [278]: E = A[...,None,:]@B[...,:,None]
In [279]: E.shape ... | python|numpy|tensordot | 1 |
356,986 | 62,641,506 | In numpy, how to compare all values in an axis | <p>For a numpy array, how can I change the value only if all elements along an axis are equal to another array? For example...</p>
<pre><code>array = np.array([[1, 0, 1],
[0, 0, 1],
[1, 1, 0],
[0, 0, 0],
[1, 0, 1]])
</code></pre>
<p>I want to repla... | <p>Try with:</p>
<pre><code>array[(array == [1, 0, 1]).all(axis=1)] = [1, 1, 1]
</code></pre> | python|numpy | 5 |
356,987 | 62,687,886 | Duration of multiple events from a datetime column in Python | <p>I have the below sample data (<strong>multiple_sensors.csv</strong>) from multiple motion sensors:</p>
<pre><code>sensorid,date_time,value
303,2012-06-25 11:15:35,0
404,2012-06-25 11:15:35,0
101,2012-06-25 11:15:35,0
202,2012-06-25 11:15:35,0
303,2012-06-25 11:15:36,0
404,2012-06-25 11:15:36,0
101,2012-06-25 11:15:3... | <p>IIUC,</p>
<p>Let's try this:</p>
<pre><code>def f(df):
a = (df['value'] != 1).cumsum().mask(df['value'] == 1)
df['value group'] = a.bfill()
df_final = df.groupby('value group').filter(lambda x: set(x['value']) == set([1,0]))\
.groupby('value group')['date_time'].agg(['first','last'])\
... | python|pandas|dataframe|csv|time-series | 0 |
356,988 | 62,552,382 | DQN Atari with tensorflow: Training seems to stuck | <p>I'm trying to learn a DQ-Learning Network to play Breakout Atari in Tensorflow. The code runs without problems, but always after 1000-1200 episodes, the time for executing one step explodes to over 100s.
Here is my <strong>DQN</strong>:</p>
<pre><code>class DQNetwork():
def __init__(self, scope, state_size=(84, ... | <p>I had the same experience whilst using an RL algorithm and training on the Atari Breakout environment from openAI gym. It happened after my exploration rate dropped to a very low value. I found the solution from this post: <a href="https://stackoverflow.com/questions/44777068/openai-gyms-breakout-v0-pauses">OpenAI g... | python|tensorflow|deep-learning|reinforcement-learning | 0 |
356,989 | 62,572,663 | looping through a pandas dataframe and applying an if esle function | <p>I am trying to build a simple backtester using python, the backtester works by comparing 2 values in a certain time, as (at time x check if indicator_value > ohlc_value: order_type = 1; else order type will be = 0)</p>
<pre><code>data = {'time':[0, 1, 2, 3, 4, 5], 'ohlc':[1.1, 1.2, 1.3, 1.4, 1.5,1.66], 'indicator... | <p>Here you go:</p>
<pre class="lang-py prettyprint-override"><code>df['order_type'] = (df['ohlc'] > df['indicator']).astype(int)
print(df)
</code></pre>
<p>Output:</p>
<pre><code> time ohlc indicator order_type
0 0 1.10 1.05 1
1 1 1.20 1.22 0
2 2 1.30 1.40 ... | python|pandas|quantitative-finance | 1 |
356,990 | 62,601,935 | plotting the data from csv file in python | <p>5.30-420462 | 100 | SAT-Synergy-gen2 |
| 5.30-42 | 92 | Scale |
| 5.30-423 | 90 | Scale |
| 5.30-420 | 76 | Scale |
| 5.30-420462 | 85 | Scale |
| 5.30-4205 | 88 | Scale |
| 5.30-420664 | 88 | ... | <p>Try using <code>matplotlib</code> for plotting data. And reading the data in with <code>pandas</code>. Then you could try set label and other stuff.<br />
Reading in the data from your file -> <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">https... | python|pandas|plot | 0 |
356,991 | 62,504,640 | Is there a way to convert numerical month/day/year to letter form month/day/year in pandas? | <p>Currently, I have a column in the form month/day/year like <strong>2/11/2020</strong>. I am trying to get it into the form of <strong>February Eleven 2020</strong>.</p>
<p>So far I've tried looking into dt.time to split into date and month but it looks like I need it in yy-mm-dd. I was thinking I can maybe split it ... | <p>The following are the three I have come across.</p>
<pre><code>df=pd.DataFrame({'Date':['2/11/2020']})
df['Date']=pd.to_datetime(df['Date']).dt.strftime('%d %B %Y')# day/Month/Year
df['Date']=pd.to_datetime(df['Date']).dt.strftime('%A %B %Y')#day of the week/month/Year
df['Date']=pd.to_datetime(df['Date']).dt.strf... | python-3.x|pandas|csv | 0 |
356,992 | 62,842,321 | pandas: iterate with conditionals within group | <p>I have a dataframe which looks similar to this (note this is an example, my actual dataframe has thousands of rows with hundreds of groups)</p>
<pre><code>pd.DataFrame({'a':['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'],
'year':[2018, 2019, 2020, 2018, 2020, 2018, 2019, 2020],
'c':[1, 2, 4, 2... | <p>We can do condition with <code>apply</code> + <code>reindex</code></p>
<pre><code>df['cond']=df.groupby('a').apply(lambda x : pd.Series([2018,2019,2020]).isin(x['year']).all() & x['c'].diff().fillna(1).gt(0).all()).reindex(df.a).values
df
a year c cond
0 A 2018 1 True
1 A 2019 2 True
2 A 2020 ... | python|pandas|pandas-groupby | 1 |
356,993 | 62,595,768 | How to fix underfitting using a CNN/ why can't my code identify images correctly? | <p>I'm quite new to neural nets and tried writing my own code to classify images. I've been using the Concrete Crack Images for Classification (<a href="https://data.mendeley.com/datasets/5y9wdsg2zt/2" rel="nofollow noreferrer">https://data.mendeley.com/datasets/5y9wdsg2zt/2</a>) to classify whether an image has a crac... | <p>There are a couple of issues you can check.</p>
<ol>
<li><p>since you are using VGG and ImageDataGenerator, you gotta make sure the image data generator do the same preprocessing as the VGG pretrained model required. VGG is trained using the imagenet_utils.preprocessing_input with mode set to "caffe". Ther... | python|tensorflow|keras|classification|conv-neural-network | 1 |
356,994 | 62,518,389 | how to convert a dataframe of counts to a probability density function | <p>Suppose that I have the following observations of integers:</p>
<pre><code>df = pd.DataFrame({'observed_scores': [100, 100, 90, 85, 100, ...]})
</code></pre>
<p>I know that this can be used as an input to make a density plot:</p>
<pre><code>df['observed_scores'].plot.density()
</code></pre>
<p>but suppose that what ... | <p>IIUC, <code>statsmodels</code> lets you fit a weighted KDE:</p>
<pre><code>from statsmodels.nonparametric.kde import KDEUnivariate
df = pd.DataFrame({'observed_scores': [100, 95, 90, 85],
'counts': [1534, 1399, 3421, 8764]})
kde1= KDEUnivariate(df.observed_scores)
kde_noweight = KDEUnivariate(df... | python|pandas|scikit-learn | 3 |
356,995 | 62,543,350 | pandas: force 'minute' and 'seconds' to be zero | <p>I have one column: line1 [ 'daytime' ]</p>
<p>the format of this column looks like:</p>
<pre><code>2018-02-07 17:40:29
2018-02-07 17:41:15
2018-02-07 17:41:55
2018-02-07 17:42:54
2018-02-07 17:43:44
2018-02-07 18:02:54
2018-02-07 18:03:44
Name: daytime, Length: 174859, dtype: datetime64[ns]
</code></pre>
<p>I want t... | <p>Use <code>astype</code> to cast to a numpy with unit as hour</p>
<pre><code>df.daytime.astype('datetime64[h]')
# dates
# 0 2018-02-07 17:00:00
# 1 2018-02-07 17:00:00
# 2 2018-02-07 17:00:00
# 3 2018-02-07 17:00:00
# 4 2018-02-07 17:00:00
# 5 2018-02-07 18:00:00
# 6 2018-02-07 18:00:00
</code></pre>... | python|pandas|dataframe | 6 |
356,996 | 62,535,289 | Pandas function to_numpy | <p>From pandas documentation, I found the function <code>to_numpy</code>
<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html</a>
But when I tried it(the sam... | <p>The attribute <code>to_numpy()</code> was released with pandas version <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html" rel="nofollow noreferrer"><code>0.24.0</code></a>. Please upgrade your pandas package to use this attribute.</p>
<p>To check the version of pandas... | python|pandas|numpy|dataframe|numpy-ndarray | 2 |
356,997 | 62,666,072 | How to groupby and create a multiindex dataframe | <p>I have a dataframe which looks like this:</p>
<pre><code> 0 1 2
0 April 0.002745 ADANIPORTS.NS
1 July 0.005239 ASIANPAINT.NS
2 April 0.003347 AXISBANK.NS
3 April 0.004469 BAJAJ-AUTO.NS
4 June 0.006045 BAJFINANCE.NS
5 June 0.005176 B... | <p>Based on your info, I'd suggest the following:</p>
<pre><code>#rename columns to make useful
new = new.rename(columns={0:'Month',1:'Price', 2:'Ticker'})
new.groupby(['Month','Ticker'])['Price'].sum()
</code></pre>
<p>To note - you should change change the 'Month' to a datetime or else the order will be illogical.... | python|pandas|group-by | 1 |
356,998 | 62,880,264 | Numpy mask by rows | <p>I have 2D array:</p>
<pre><code>matrix =np.array([[95,90,-1,55],[100,90,-1,80],[0,90,85,100]])
</code></pre>
<p>I try to choose 2 random rows, and ignore -1.</p>
<p>I tried:</p>
<pre><code>random_ints = np.random.choice(len(matrix), size=2, replace=False)
students = matrix[random_ints, :]
ignored = students[students... | <p>If you had <strong>equal</strong> number of elements to be left (<em>!= -1</em>) in
each row, you could run:</p>
<pre><code>np.apply_along_axis(lambda row: row[row != -1], 1, students)
</code></pre>
<p>To check this variant, set <code>random_ints = np.array([0,1])</code>, select just
the above rows to <em>students</... | python|numpy | 0 |
356,999 | 62,805,371 | group by a string column and datetime64[ns] column | <p>I have the following data and I would like to know: <strong>Who was the first and last customer that each Driver pick-up for each day?</strong></p>
<p><a href="https://drive.google.com/file/d/194byxNkgr2e9r-IOEmSuu9gpZyw27G7j/view?usp=sharing" rel="nofollow noreferrer">Data</a></p>
<p>This is how far I just got:</p>... | <p>You can first sort by the column <code>Start</code> which includes the hour and minutes, ensuring that
multiple same day events are sorted correctly for the next step. Group the frame by <code>Driver</code> to find
the drivers pick up for each day.</p>
<p>Using <code>drop_duplicates</code> drop repeated values using... | python|pandas|datetime | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.