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 |
|---|---|---|---|---|---|---|
353,700 | 54,928,271 | Delete a string phrase from a data frame column and replace it python | <p>So, I have two dataframes. the first dataframe is <strong>dataset</strong> conatians several columns, what i will use in this dataframe is the <strong>dataset['text_msg']</strong>, this columns contains text data.</p>
<p>The second Dataframe <strong>sentences_to_exclude</strong> contains the data which type is text... | <p>Still don't understand your question correctly, I will try to help you, but please next time you have to include example data.</p>
<p>To answer your question I will give example dataset and explain how to remove words or sentences from other text:</p>
<pre><code># This is our example data
sentences = ['code transa... | python|string|pandas|replace | 1 |
353,701 | 54,839,315 | Making lists based on values in column | <p>I have an interesting case. In column <code>FID2</code> I have some values, based on each i'd like to create a list. The column <code>Ncircles</code> determines the list.
For example: </p>
<ul>
<li>If there's a value <code>0</code> in <code>Ncircles</code>, i'd like to create a list based on the value in <code>FID2... | <p>Use <code>range</code> in list comprehension with flattening:</p>
<pre><code>Newlist = [c for a, b in zip(df['FID2'], df['Ncircles']) for c in range(a-b, a+b+1)]
print (Newlist)
[50141, 56187, 56188, 56189, 75035, 94934, 94935, 94936, 94937, 94938, 94939, 94940]
</code></pre> | python|pandas|list | 4 |
353,702 | 54,798,588 | Converting a Dict of List with Different Size to a df | <p>I've been struggling to convert a dict to df using <code>pd.DataFrame(Dict)</code>, however, I'm getting an error saying <code>ValueError: arrays must all be same length</code>. Could anybody shed some light on this. Is there any way to go about converting a Dict with different size in 'Value' ? </p>
<p><code>Dict=... | <p>If you want to keep the first 3 columns as blank , you need either a space or <code>np.nan</code> not a blank list:</p>
<pre><code>Dict= {'Country': [np.nan],
'Organization ': [np.nan],
'Education ': [np.nan],
'City ': ['Toronto']}
print(pd.DataFrame(Dict))
Country Organization Education City
0 ... | python|pandas|dataframe|dictionary | 2 |
353,703 | 55,014,239 | How to do 100000 times 2d fft in a faster way using python? | <p>I have a 3d numpy array with a shape of (100000, 256, 256), and I'd like to do FFT on every stack of the 2d array, which means 100000 times of FFT.</p>
<p>I have tested the speed of single and the stacked data with minimum code below.</p>
<pre><code>import numpy as np
a = np.random.random((256, 256))
b = np.random... | <p><strong><a href="https://pyfftw.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">pyfftw</a>, wrapping the <a href="http://www.fftw.org/" rel="nofollow noreferrer">FFTW</a> library</strong>, is likely faster than the <a href="https://www.netlib.org/fftpack/" rel="nofollow noreferrer">FFTPACK</a> library... | python|numpy|parallel-processing|fft | 2 |
353,704 | 54,757,196 | Text encoding and column arranging give UnicodeEncodeError in 2.x | <p><strong><em>SOLVED</em></strong>
this was a Unicode issue in 2.x and a non-issue when you upgrade to 3.x</p>
<p>I am trying to learn webscraping with Python and BeautifulSoup to export data into readable spreadsheets. I have two questions:</p>
<p><strong>Problem 1:</strong> I have hit a snag multiple times while t... | <p>Using <code>read_html</code> function in <code>pandas</code> would be easier and will encounter less problems. Simply install <code>lxml</code> library if you encounter an error, pandas uses this library for HTML processing.</p>
<pre><code>import csv
import requests
from bs4 import BeautifulSoup
import pandas as p... | python|pandas|csv|web-scraping|beautifulsoup | 0 |
353,705 | 54,734,556 | Pytorch: How to create an update rule that doesn't come from derivatives? | <p>I want to implement the following algorithm, taken from <a href="http://incompleteideas.net/book/bookdraft2017nov5.pdf" rel="nofollow noreferrer">this book, section 13.6</a>:</p>
<p><a href="https://i.stack.imgur.com/YxBlr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YxBlr.png" alt="enter imag... | <p>I am gonna give this a try.</p>
<p><code>.backward()</code> does not need a loss function, it just needs a differentiable scalar output. It approximates a gradient with respect to the model parameters. Let's just look at the first case the update for the value function. </p>
<p>We have one gradient appearing for v... | python|machine-learning|pytorch|reinforcement-learning|backpropagation | 5 |
353,706 | 49,593,919 | How to get tensorflow 1.7 with colaboratory? | <p>I am getting </p>
<p>AttributeError: module 'tensorflow.contrib.rnn' has no attribute 'LayerRNNCell'</p>
<p>which is a change from tensorflow 1.6 to 1.7 and i have created custom cells based upon 1.7 api but google-colab itself does not seem to be in line with the latest release.</p>
<p>How do i upgrade 1.6.0 ver... | <p>Have you tried just using</p>
<pre><code>!pip install --upgrade tensorflow==1.7.0
</code></pre>
<p>at the beginning of your notebook?</p> | tensorflow|google-colaboratory | 3 |
353,707 | 49,739,183 | Python Pandas Dataframe: length of index does not match - df['column'] = ndarray | <p>I have a pandas Dataframe containing EOD financial data (OHLC) for analysis.</p>
<p>I'm using <a href="https://github.com/cirla/tulipy" rel="nofollow noreferrer">https://github.com/cirla/tulipy</a> library to generate technical indicator values, that have a certain timeperiod as option. For Example. ADX with timepe... | <p>Full MCVE</p>
<pre><code>df = pd.DataFrame(1, range(10), list('ABC'))
a = np.full((len(df) - 6, df.shape[1]), 2)
b = np.full((6, df.shape[1]), np.nan)
c = np.row_stack([b, a])
d = pd.DataFrame(c, df.index, df.columns)
d
A B C
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN
4 NaN ... | python|pandas|dataframe|time-series|valueerror | 0 |
353,708 | 49,647,452 | How to deal w/ Tensorflow multiple versions/installations [Ubuntu, Anaconda, VirtualEnv] | <p>I installed Tensorflow on my Ubuntu on a VirtualEnv. Soon I realized I can import Tensorflow on Anaconda (Jupyter notebook & command line Python), without even activating the VirtualEnv. Then I checked the TF versions <code>print(tf.__version__)</code>. For Anaconda I got <code>v1.1.0</code>, for VirtualEnv <cod... | <blockquote>
<p>So how can I identify and uninstall the TF v1.1.0?</p>
</blockquote>
<p>Run <code>pip show tensorflow</code> without activating virtual environment. If it shows TF v1.1.0 uninstall it:</p>
<pre><code>pip uninstall tensorflow
</code></pre>
<p>If <code>pip</code> doesn't know about TF find it manuall... | python|tensorflow|anaconda|virtualenv|ubuntu-17.10 | 1 |
353,709 | 49,576,582 | How to solve ValueError when testing truth value of Dataframe contents? Python | <p>I have a Dataframe that looks like this.</p>
<pre><code> done sentence 3_tags
0 0 ['What', 'were', 'the', '...] ['WP', 'VBD', 'DT']
1 0 ['What', 'was', 'the', '...] ['WP', 'VBD', 'DT']
2 0 ['Why', 'did', 'John', '...] ['WP', 'VBD', 'NN']
...
</code></pre>
<p... | <p>You want those lists to be tuples instead.<br>
Then use <code>pd.Series.isin</code> </p>
<pre><code>*temp1, = map(tuple, temp1)
q = a['3_tags'].apply(tuple)
q.isin(temp1)
0 True
1 True
2 False
Name: 3_tags, dtype: bool
</code></pre>
<hr>
<p>However, it appears that the <code>'3_tags'</code> column ... | python-3.x|pandas|valueerror | 1 |
353,710 | 49,724,413 | Place Variable into a Specific Location [row,column] Pandas Python | <p>I've been working to place a string variable "revenue" into a pandas dataframe <code>df1</code>. As you can see, I used df.ait.</p>
<p>More details about the code: It's about finding the specific date row, by m counting loop.</p>
<p>My issue occurs at the <code>.iat</code>.</p>
<pre><code>if info[1] == "1": #Get ... | <p>One of the main benefits of using a package like pandas is to avoid this kind of manual looping, which is very difficult to follow and modify.</p>
<p>I think you can do what you need to in one line. Something like:</p>
<pre><code>df1.loc[date, 9] = 'revenue'
</code></pre>
<p>If that doesn't work, could you edit i... | python|pandas|index-error | 1 |
353,711 | 49,434,247 | How can I load data from txt using pandas? | <p>I've read this question <a href="https://stackoverflow.com/questions/21546739/load-data-from-txt-with-pandas">Load data from txt with pandas</a>. However, my data format is a little bit different. Here is the example of the data:</p>
<pre><code>product/productId: B003AI2VGA
review/userId: A141HP4LYPWMSR
review/prof... | <p>This is one way:</p>
<pre><code>import pandas as pd
from io import StringIO
mystr = StringIO("""product/productId: B003AI2VGA
review/userId: A141HP4LYPWMSR
review/profileName: Brian E. Erland "Rainbow Sphinx"
review/helpfulness: 7/7
review/score: 3.0
review/time: 1182729600
review/summary: "There Is So Much Darkne... | python|pandas|dataframe|loaddata | 0 |
353,712 | 49,604,442 | Build c++ project of tensorflow with scons error | <p>I installed libtensorflow_cc.so with bazel. But when I build a test project include example of tensorflow from <a href="https://tensorflow.google.cn/versions/r1.2/api_guides/cc/guide" rel="nofollow noreferrer">code</a> with scons, following error occured.</p>
<pre><code>g++ -o bin/tftest test/test.o -L/usr/local/li... | <p><strong>Creating a binary compiled against Tensorflow with bazel</strong></p>
<ol>
<li>Clone the tensorflow repository.</li>
<li>Inside tensorflow/tensorflow, create a working directory, let it be <code>tftest</code>.</li>
<li>Add your C++ code that uses tensorflow, lets put that in <code>test.cpp</code>.</li>
<li>... | c++|tensorflow | 0 |
353,713 | 49,618,782 | Get external coordinates of a polygon from a numpy boolean grid | <p>I am trying to get the external coordinates of a polygon from a numpy boolean grid. For example, from a (16, 16) ndarray such as the following one</p>
<pre><code>[
[False False False False False False True True True True False False False False False False],
[False False False False False True True T... | <p>Perhaps you can move the question to <a href="https://gis.stackexchange.com/">GIS stack exchange site</a>. There you will probably get more help on this. </p>
<p>Anyway, a quick search shows <a href="https://gis.stackexchange.com/questions/187877/how-to-polygonize-raster-to-shapely-polygons">this anwer</a>, where i... | python|numpy|shapely | 3 |
353,714 | 49,666,426 | How to compare 2 different excel files of same name in 2 different folder? | <p>I have a set of excel sheet in one folder and another set in folder 2. If the same file name in both folders matches I need to take the difference in the cell.</p>
<p>The difference in column I have a script below. How to pass for loop for this?</p>
<pre><code>import pandas as pd
df1 = pd.read_excel('firstfolder/0... | <p>Assuming your folders contain the same xls files, and the file all have the same structure, then you can use <code>glob</code> and iterate -</p>
<pre><code>import glob
diffs = []
for i, j in zip(*map(glob.glob, ['firstfolder/*.xls', 'secondfolder/*.xls'])):
i, j = map(pd.read_excel, [i, j])
diffs.append(i[... | python|pandas | 2 |
353,715 | 49,592,859 | Why not allocating memory not an error in TensorFlow? | <p>Sometimes one will see warnings in the following spirit in TensorFlow :</p>
<pre><code>W tensorflow/core/common_runtime/bfc_allocator.cc:219] Allocator (GPU_0_bfc) ran out of memory trying to allocate 3.38GiB. The caller indicates that this
is not a failure, but may mean that there could be performance gains if mo... | <p>The <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/common_runtime/bfc_allocator.cc" rel="nofollow noreferrer">TensorFlow code from where the error originates</a>, looks like this from line 206:</p>
<pre class="lang-cpp prettyprint-override"><code>void* BFCAllocator::AllocateRaw(size_t... | tensorflow | 3 |
353,716 | 49,416,931 | What does the tensorflow.python.eager.tape do in the implementation of tf.contrib.eager.custom_gradient? | <p>I am going through TensorFlow Eager Execution from <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/g3doc/guide.md" rel="nofollow noreferrer">here</a> and find it difficult to understand the customizing gradients part. </p>
<pre><code>@tfe.custom_gradient
def logexp(x):
... | <p>I will answer each sub-question separately:</p>
<p><strong>Re: what is <code>dy</code></strong>: Primary use case for gradient functions is during back propagation. During back propagation, the gradient for each op, must take the gradient(s) of its output(s) and produce the gradient(s) of its input(s). This is effe... | tensorflow | 0 |
353,717 | 49,709,405 | Combine certain rows values of duplicate rows Pandas | <p>I have a dataframe based on football players. I am finding duplicate rows for when a player has transferred mid-season. My aim is to add the points the accumalted in both leagues and add them together to make just one row. </p>
<p>Here is a sample of the data:</p>
<pre><code>name full_name club Points Sta... | <p>You need:</p>
<pre><code>df[['name','full_name','club']] = df[['name','full_name','club']].fillna('')
d = {'Points':'sum', 'Start':'sum', 'Sub':'sum', 'club':'first'}
df = (df.groupby(['name','full_name'], sort=False, as_index=False)
.agg(d)
.reindex(columns=df.columns))
with pd.option_context('dis... | python|pandas|dataframe|jupyter-notebook | 3 |
353,718 | 49,777,178 | Pandas timestamp and python datetime interpret timezone differently | <p>I don't understand why <code>a</code> isn't the same as <code>b</code>:</p>
<pre><code>import pandas as pd
from datetime import datetime
import pytz
here = pytz.timezone('Europe/Amsterdam')
a = pd.Timestamp('2018-4-9', tz=here).to_pydatetime()
# datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo'Europe/Ams... | <p>From this <a href="https://stackoverflow.com/questions/45755336/why-does-creating-a-datetime-with-a-tzinfo-from-pytz-show-a-weird-time-offset">stackoverflow post</a> I learned that <code>tzinfo</code> doesn't work well for some timezones and that could be the reason for the wrong result.
<a href="http://pytz.sourcef... | pandas|datetime | 3 |
353,719 | 49,575,897 | Can't replace 0 to nan in Python using Pandas | <p>I have dataframe with only 1 column. I want to replace all '0' to np.nan but I can't achieve that.</p>
<p>dataframe is called area.
I tried:</p>
<pre><code>area.replace(0,np.nan)
area.replace(to_replace=0,np.nan)
area.replace(to_replace=0,value=np.nan)
area.replace('0',np.nan)
</code></pre>
<p>What should I do?<... | <p>You can set <code>inplace</code> to <code>True</code> (default is <code>False</code>):</p>
<pre><code>area.replace(0, np.nan, inplace=True)
</code></pre>
<p>See examples in <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html#pandas-dataframe-replace" rel="noreferrer">docs<... | python|pandas|dataframe | 61 |
353,720 | 49,718,863 | How to combine multiple columns in a Data Frame to Pandas datetime format | <p>I have a pandas data frame with values as below</p>
<p><code>ProcessID1 UserID Date Month Year Time
248 Tony 29 4 2017 23:30:56
436 Jeff 28 4 2017 20:02:19
500 Greg 4 5 2017 11:48:29
</code>
I would like to know is there any way I... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a> with automatic convert column <code>Day,Month,Year</code> with add <code>time</code>s converted <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.... | python-3.x|pandas | 13 |
353,721 | 49,608,962 | pandas questions about argmin and timestamp | <pre><code>final_month = pd.Timestamp('2018-02-01')
df_final_month = df[df['week'] >= final_month]
df_final_month.iloc[:, 1:].sum().argmax()
index = df.set_index('week')
index['storeC'].argmin()
</code></pre>
<p>the code above is correct, i just don't exactly understand how does it work inside. i have some quest... | <blockquote>
<ol>
<li>Is Timestamp almost as same as datetime?</li>
</ol>
</blockquote>
<p>Here is quote from <code>pandas</code> documentation itself:</p>
<blockquote>
<p>TimeStamp is the pandas equivalent of python’s Datetime and is interchangable with it in most cases</p>
</blockquote>
<p>In fact, if you ... | pandas | 1 |
353,722 | 49,487,158 | Tensorflow Dataset structure | <p>I'm trying to figure out how can I use the Dataset module of Tensorflow by studying an official example about cifar10 on <a href="https://github.com/tensorflow/models/blob/master/official/resnet/cifar10_main.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/official/resnet/cifar10_main.p... | <p>This problem is fixed by simply change the expression <code>record_vector = tf.decode_raw(raw_record, tf.uint8)</code> to <code>record_vector = raw_record</code>, it seems the items in the dataset of cifar are not tensors.</p> | python|tensorflow|tensorflow-datasets | 0 |
353,723 | 49,656,386 | I have a ValueError while using Jupyter Notebook and need help to find out why I get this error and how to fix it | <p>When I run this code:</p>
<pre><code>from sklearn.tree import DecisionTreeRegressor
melbourne_model = DecisionTreeRegressor()
melbourne_model.fit(X, y)
</code></pre>
<p>I get this output:</p>
<p><code>ValueError: Input contains NaN, infinity or a value too large for dtype('float32').</code></p>
<p>This error p... | <p>The error you're getting is fairly clear: <code>Input contains NaN, infinity or a value too large</code>. The problem is not that your inputs are pandas Series, but that your data is missing values! A quick glance at your CSV on Kaggle shows that rows 15 and 16 are missing quite a few fields, for example.</p>
<p>It... | python|python-3.x|pandas|machine-learning|data-science | 0 |
353,724 | 49,675,587 | Error when trying to apply lambda function using pandas Dataframe | <p>I have a dataframe with a datetime index, which looks like this:</p>
<pre><code> ModelRun Tmp_2m_C DSWRF TCDC Obs_kW n beta \
2016-01-01 06:30:00 2.016010e+09 7.962387 0.00000 100.0 0.0 1 0.0
2016-01-01 07:30:00 2.016010e+09 8.077713 9.00000 100.0 0.0 1 ... | <p>Using <code>apply()</code> for this is not efficient at all. You should almost never use <code>apply()</code> except as a last resort. You can solve your problem much more simply:</p>
<pre><code>df["sunset_deg"] = df[["earth_sunset_deg", "surface_sunset_deg"]].min(1)
</code></pre>
<p>Here's an alternative which ... | python|python-3.x|pandas|dataframe | 2 |
353,725 | 49,784,269 | numba: How to delete an existing array and assign a new array to the old array's name? | <p>Considering the following minimal not working example:</p>
<pre><code>import numba as nb
import numpy as np
@nb.jit(nopython=True)
def resize_np_array(np_array, new_size, fill_value):
if new_size <= np_array.shape[0]:
return np_array
else:
new_shape = np_array.shape
new_shape[0] ... | <p>Your error is coming from trying to assign a new value to the <code>shape</code> attribute of the existing numpy array; that's a fixed thing, you can't just reshape an array by redefining its <code>shape</code> attr (in numpy or in numba). (In fact, <code>shape</code> is a tuple, which is immutable in any context.) ... | python|numpy|numba | 2 |
353,726 | 49,638,201 | numpy version creating issue. python 2.7 already installed | <p>Getting few "package missing" errors while installing ipython on High Sierra.</p>
<p>matplotlib 1.3.1 has requirement numpy>=1.5, but you'll have numpy 1.8.0rc1 which is incompatible.</p> | <p>I just met the same problem. It's a issue about numpy preinstall in Python has a version number issue(required >=1.5, but found 1.8.0rc1).</p>
<p>Try running <code>brew install python2</code> to upgrade your python which may solve this issue.</p> | macos|numpy|matplotlib|ipython|homebrew | 3 |
353,727 | 49,709,237 | Trying to truncate decimal values in all the cells of dataframe, but not working | <p>The Dataframe consists of table, the format of which is shown in the <a href="https://i.stack.imgur.com/4khi4.png" rel="nofollow noreferrer">Attached image</a>. I apologize for not being able to type the format here as while trying to type the format of the Dataframe, it was getting messed up due to long decimal val... | <p>Problem is need <code>axis=1</code> for count <code>mean</code> per rows and change function to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.nanmean.html" rel="nofollow noreferrer"><code>numpy.nanmean</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame... | python|pandas|numpy | 0 |
353,728 | 49,510,935 | How to remove Non English words in Python? | <p>I am doing a sentiment analysis project in Python (using Natural Language Processing). I already collected the data from twitter and saved it as a CSV file. The file contains tweets, which are mostly about cryptocurrency. I cleaned the data but there is one more thing before I apply sentiment analysis using classfic... | <p><a href="https://stackoverflow.com/questions/41290028/removing-non-english-words-from-text-using-python">There has been a similar question here.</a></p>
<p>You could try <a href="https://pypi.python.org/pypi/pyenchant/1.6.6" rel="nofollow noreferrer">enchant</a>:</p>
<pre><code>import enchant
d = enchant.Dict("en_... | python|pandas|twitter|nlp|sentiment-analysis | 0 |
353,729 | 49,721,539 | normalize input data based on a normalized dataset | <p>I have this code that normalizes a pandas dataframe. </p>
<pre><code>import numpy as np; import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
from sklearn import preprocessing
df = pd.read_csv('DS/RS_DS/final_dataset.csv')
rec_df = df.drop(['person_id','encounter_id','birthdate','CN','HN','D... | <p>I think you should do <code>fit</code> and <code>transform</code> separately. This is done to ensure that the distribution of data using in fitting is maintained.</p>
<pre><code># initialise scaler
min_max_scaler = preprocessing.MinMaxScaler()
# fit here
min_max_scaler.fit(rec_df.values)
# apply transformation
df... | python|pandas | 0 |
353,730 | 49,362,591 | "NaN" is not extracting in .csv | <p>My objective is to pass the .xlsx file and convert it into .csv, and parse to remove special character from .csv and "NaN" should display in empty cell. To do so i am using below code.</p>
<p>If I ran below command on the console followed by #df it shows the NaN in the output. On other side If I run the code, does... | <p>Yes you can convert np.nan to string "NaN" in the data frame. But a better and faster way is to give pandas a proper parameter when reading in the excel file, specifying what value should be mapped to nan and what should not.</p>
<p>When you are calling read_excel function, you are using the default value of <code>... | python|python-2.7|pandas|nan | 0 |
353,731 | 28,277,248 | Numpy vectorisation of python object array | <p>Just a short question that I can't find the answer to before i head off for the day,</p>
<p>When i do something like this:</p>
<pre><code>v1 = float_list_python = ... # <some list of floats>
v2 = float_array_NumPy = ... # <some numpy.ndarray of floats>
# I guess they don't ... | <p><code>numpy</code> is fast because it performs numeric operations like this in fast compiled <code>C</code> code. In contrast the list operation operates at the interpreted Python level (streamlined as much as possible with Python bytecodes etc).</p>
<p>A <code>numpy</code> array of numeric type stores those numb... | python|numpy|scipy | 1 |
353,732 | 28,225,440 | pandas display results grouped by column | <p>I'm trying to essentially do the same as a pivot table in Excel would do but using pandas. Here is some of my data:</p>
<pre><code> First_Name Last_Name Country Prize_Money
Roger Federer SUI 88691538
Novak Djokovic SRB 72444493
Rafael ... | <p>You can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a>:</p>
<pre><code>>>> df.groupby("Country")["Prize_Money"].sum()
Country
ESP 96349620
GBR 34190085
SRB 72444493
SUI 88691538
Name: Pri... | python-3.x|pandas | 0 |
353,733 | 28,319,530 | Flatten image background using OpenCV/Numpy | <p>I am creating an image analysis tool (using Python).
I already have segmented images resulting from Otsu thresholding.
Using the OpenCv kmeans function I reduced the amount of colors in my image to 4.
One of the K-means clusters is supposed to be black background (BGR values [0,0,0] ). </p>
<p>Due to the algorithm... | <p>You could vectorize this operation like this:</p>
<pre><code>In [29]: A = np.random.random_integers(0,10,(2,4,3))
In [30]: A
Out[30]:
array([[[ 5, 9, 1],
[ 4, 0, 2],
[ 0, 5, 9],
[ 8, 7, 8]],
[[ 1, 6, 7],
[ 8, 10, 9],
[ 2, 10, 1],
[ 9, 2, 3]]])
... | python|image|opencv|numpy | 2 |
353,734 | 28,268,851 | splitting an array into predictor matrix and response vector | <p>I think this is very trivial question but hopefully someone can help me out. What's the best way to split an array that contains both predictors (inputs) and the response variable (output)?</p>
<p>I imported a csv file with both predictors and the response, but I'd like to split it so that the predictors are in a n... | <p>Simply use the shape property of the imported numpy array to determine m and the extract the subarrays using slicing:</p>
<pre><code>import numpy as np
# load csv data
data = np.loadtxt('data.txt', delimiter=',')
# m is the number of columns minus one
m = data.shape[1]-1
# use slicing to extract subarrays
pred = d... | python|arrays|numpy|split | 2 |
353,735 | 27,980,843 | python pandas functions with and without parentheses | <p>I notice that many DataFrame functions if used without parentheses seem to behave like 'properties' e.g.</p>
<pre><code>In [200]: df = DataFrame (np.random.randn (7,2))
In [201]: df.head ()
Out[201]:
0 1
0 -1.325883 0.878198
1 0.588264 -2.033421
2 -0.554993 -0.217938
3 -0.777936 2.21... | <p>They are different and not recommended, one clearly shows that it's a method and happens to output the results whilst the other shows the expected output.</p>
<p>Here's why you should not do this:</p>
<pre><code>In [23]:
t = df.head
In [24]:
t.iloc[0]
-------------------------------------------------------------... | python|pandas | 4 |
353,736 | 28,017,807 | Performing calculations on subset of data frame subset in Python | <pre><code>user_id char_id rating
100 33 3
100 44 2
100 33 1
100 44 4
111 55 5
111 44 4
111 55 5
</code></pre>
<p>I have a data frame formatted similarly to this one and am trying to perfor... | <p>There's no need to do this manually, creating and summarizing subsets like this is exactly what <code>DataFrame.groupby()</code> is for. Create your groupby:</p>
<pre><code>grouped = df.groupby(['user_id', 'char_id'])
</code></pre>
<p>Then you can apply a function to each subset. It sounds like you want either <co... | python|pandas|dataframe | 2 |
353,737 | 28,148,425 | Extremely puzzling behavior when evaluating a tuple object that holds multiple DataFrames | <p>I have some statements where I invoke a function that I defined myself:</p>
<pre><code>sim_extracted_dfs = extract_dataframes(sim_queue_total_df_sim)
print (sim_extracted_dfs is tuple)
</code></pre>
<p>where <code>extract_dataframes()</code> is a function that accepts a large DataFrame as an argument and processes... | <p>Don't use the <code>is</code> operator for comparing types. From the <a href="https://docs.python.org/2/reference/expressions.html#not-in" rel="nofollow">docs</a>:</p>
<blockquote>
<p>The operators <code>is</code> and <code>is not</code> test for object identity: <code>x is y</code> is true if and only if <code>x... | python|if-statement|pandas|tuples|conditional-statements | 2 |
353,738 | 28,278,358 | Speed up function evaluation for integration in scipy | <p>I am trying to port code from Matlab to SciPy. Here is the simplified version of the code I have written so far: <a href="https://gist.github.com/atmo/01b6e007be9ef90e402c" rel="nofollow">https://gist.github.com/atmo/01b6e007be9ef90e402c</a> . However, Python version is considerably slower then Matlab. I've included... | <p>Your <code>numpy</code> version probably is comparable in to speed to older MATLAB runs. But new MATLAB versions do various forms of just-in-time compilation that speed up repeated calculations considerably.</p>
<p>My guess is that you can nibble away at the <code>lambda</code> and <code>f</code> code, and maybe c... | python|numpy|scipy | 1 |
353,739 | 28,155,535 | Numpy-style error tracebacks? | <p>In numpy, when you make a mistake, the error doesn't tell you about all the numpy internals, just the user-level error made. For example:</p>
<pre><code>import numpy as np
A = np.ones([1,2])
B = np.ones([2,3])
A+B
</code></pre>
<p>spits back</p>
<pre><code>Traceback (most recent call last):
File "/home/roderic/... | <p>The only reason that <code>A+B</code> doesn't show any internal stack frames is that <code>numpy.ndarray.__add__()</code> happens to be implemented in C, so there are no Python stack frames after the one containing the <code>A+B</code> to show. numpy is not doing anything special to clean up the stack trace.</p> | python|numpy|traceback | 1 |
353,740 | 28,337,117 | How to pivot a dataframe in Pandas? | <p>I have a table in csv format that looks like this. I would like to transpose the table so that the values in the indicator name column are the new columns,</p>
<pre><code>Indicator Country Year Value
1 Angola 2005 6
2 Angola 2005 13
3 ... | <p>You can use <code>pivot_table</code>:</p>
<pre><code>pd.pivot_table(df, values = 'Value', index=['Country','Year'], columns = 'Indicator').reset_index()
</code></pre>
<p>this outputs:</p>
<pre><code> Indicator Country Year 1 2 3 4 5
0 Angola 2005 6 13 10 11 5
1 Ang... | python|pandas|dataframe|transpose | 83 |
353,741 | 28,228,090 | 'module' object has no attribute 'date_range' in python | <p>I am learning pandas in Python.Below is my code in Terimal:</p>
<pre><code>import pandas as pd
dates = pd.date_range('20130101', periods=6)
</code></pre>
<p>Then I get this message:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object ... | <p>You can't find <code>date_range</code> because you're using pandas version 0.7.0, which is very old (~9 Feb 2012) in pandas time-- the current stable version (29 Jan 2015) is 0.15.2. </p>
<p>You're going to want to upgrade, not only because of bug fixes and new features, but because many of the examples you're goi... | python|pandas | 1 |
353,742 | 28,251,314 | Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script | <p>Im trying to install numpy with PyCharm but i keep getting this error: </p>
<blockquote>
<p>error: Microsoft Visual C++ 10.0 is required (Unable to find
vcvarsall.bat).</p>
</blockquote>
<p>Can someone please explain to me exactly what i have to do to fix this error(and as simple and detailed as possible)? im ... | <p>I was able to fix this on Windows 7 64-bit running Python 3.4.3 by running the <code>set</code> command at a command prompt to determine the existing Visual Studio tools environment variable; in my case it was <code>VS140COMNTOOLS</code> for Visual Studio Community 2015.</p>
<p>Then run the following (substituting ... | python|numpy|pycharm | 57 |
353,743 | 28,143,288 | How can I compile astropy (which uses numpy) for a kivy android installation? | <p>I'm trying to use kivy to create an android app that makes use of astropy. The difficulty is that astropy makes use of numpy during its installation, and I haven't been able to get it to successfully load the numpy libraries. I believe the problem is that it's finding the libraries compiled for ARM architecture - ho... | <p>The backtrace for the failing import contains <code>get_numpy_include_path()</code> in it, which is from <code>astropy_helpers/astropy_helpers/setup_helpers.py</code>. Looking at the source code for numpy's <code>get_include()</code>, it won't work on a system when cross compiling, so even if you managed to build nu... | android|python|numpy|kivy|astropy | 1 |
353,744 | 28,142,839 | pip install numpy (python 2.7) fails with errorcode 1 | <p>I'm installing numpy through pip on python 2.7.9... I checked <code>pip list</code>, and it returns <code>pip (1.5.6), setuptools (12.0.4)</code>. I'm running on Windows 7 64-bit, and I've tried both Python 32 and 64-bit versions.</p>
<p><code>pip install numpy</code> ends with:</p>
<pre><code>Command C:\Python27\... | <p>Download the wheel (.whl file) file from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy" rel="noreferrer">here</a> and install with pip:</p>
<ol>
<li><code>pip install wheel</code> to install support for wheel files.</li>
<li><code>pip install numpy‑1.9.1+mkl‑cp27‑none‑win32.whl</code> to install the whe... | python|numpy|pip | 32 |
353,745 | 28,238,294 | How to modify Datetime index format (UTC) in Pandas? | <p>I have a df that looks like this:</p>
<pre><code>2015-01-29 08:30:00-05:00 199425 199950 199375 199825
2015-01-29 08:45:00-05:00 199825 199850 199650 199800
2015-01-29 09:00:00-05:00 199825 199900 199450 199625
</code></pre>
<p>How can I remove the -05:00 so It look... | <p>This is an old question from Jan 2015. But since there is no answer yet (although lots of comments), here is an answer in Oct 2019. The original questioner probably found an answer already but just as a reference for the future.</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_... | python|datetime|pandas|time-series | 2 |
353,746 | 73,355,820 | Python Pandas CVS File: Slicing Values and Removing Lines with Missing Values | <p>I read "data.csv" file and has 2 columns.</p>
<p>For "code" columns, I would like to slice the value string and put back only last 2 digit(alphabet) of code into columns.</p>
<p>For each rows, if either "username" and "code" value is missing, I would like to remove the row fro... | <p>I'm assuming the empty cells are <code>""</code> strings:</p>
<pre class="lang-py prettyprint-override"><code>df = df[~df.eq("").any(axis=1)]
df["code"] = df["code"].str.rsplit("-", n=1).str[-1]
print(df)
</code></pre>
<p>Prints:</p>
<pre class="lang-none prettyprint... | python|pandas|csv|jupyter-notebook | 1 |
353,747 | 73,321,853 | How to get number of rows since last peak Pandas | <p>I would like to get a rolling count of how many rows have been between the current row and the last peak. Example code:</p>
<pre><code>Value | Rows since Peak
-----------------------
1 0
3 0
1 1
2 2
1 3
4 0
6 0
5 1
</code></pre> | <p>You can compare the values to the <code>cummax</code> and use it for a <code>groupby.cumcount</code>:</p>
<pre><code>df['Rows since Peak'] = (df.groupby(df['Value'].eq(df['Value'].cummax())
.cumsum())
.cumcount()
)
</code></pre>... | python|pandas|dataframe | 0 |
353,748 | 73,225,536 | Estimate future values following sklearn linear regression of accumulate data over time | <p>I have 10 days worth of data for the number of burpees completed, and based on this information I want to extrapolate to estimate the total number of burpees that will be completed after 20 days.</p>
<pre><code>data={'Day':[1,2,3,4,5,6,7,8,9,10],'burpees':[12,20,28,32,52,59,71,85,94,112]}
df=pd.DataFrame(data)
</cod... | <p>As per the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html" rel="nofollow noreferrer">documentation</a>, input for <code>.fit()</code> method should be a Numpy array with <code>(n_samples, n_features)</code> shape.</p>
<p>Below should work:</p>
<pre class="lang-p... | python|pandas|scikit-learn|linear-regression | 0 |
353,749 | 73,279,368 | Pandas replace Na using merge or join | <p>I want to replace Na in column A with based on shared values of column B so column rows with x in column B have 1 in column A and rows with y in column B have 2 in column A</p>
<pre><code>A B C D E
1 x d e q
Na x v s f
Na x v e j
2 y w e v
Na y b d g
'''
</code></pre> | <p>Use <code>groupby.transform('first')</code>, eventually combined with <code>convert_dtypes</code>:</p>
<pre><code>df['A'] = df.groupby('B')['A'].transform('first').convert_dtypes()
</code></pre>
<p>output:</p>
<pre><code> A B C D E
0 1 x d e q
1 1 x v s f
2 1 x v e j
3 2 y w e v
4 2 y b ... | python|pandas | 3 |
353,750 | 73,345,431 | datetime subtraction in dict for loop - python | <p>I have multiple data-frames where I need to loop start and end dates. The end dates are fixed; however, the start dates would varies between 1 to 10 years. For the sample below, all start dates are 6 years prior to the end dates. Therefore, is there a way to coding it where all k[i] are 6 years prior to l[i] instead... | <p>Let's say you first have a dataframe only with end dates</p>
<pre><code>df = pd.DataFrame({'end date': [val for key, val in l.items()]})
</code></pre>
<p>Then, define start dates by using <code>pd.offsets.DateOffset</code>:</p>
<pre><code>df['end date'] = pd.to_datetime(df['end date'], format='%Y-%m-%d')
df['start d... | python|pandas|dataframe|loops | 1 |
353,751 | 73,344,251 | Numpy matrix complex operation optimization | <p>I have a function that I am trying to optimize.</p>
<pre><code>def mul_spectrums_with_conj(x: ndarray, y: ndarray) -> ndarray:
lst = np.empty((x.shape[0], x.shape[1]), dtype=np.complex64)
for kx in range(x.shape[0]):
for ky in range(x.shape[1]):
acc0 = x.real[kx, ky] * y.real[kx, ky] +... | <p>What you have there is a very manual, lengthy way of multiplying each element of <code>x</code> by the complex conjugate of the corresponding element of <code>y</code>. You don't need to write it out like that. NumPy can already take complex conjugates and multiply complex numbers on its own.</p>
<p>NumPy supports t... | python|numpy|optimization | 2 |
353,752 | 73,363,025 | How to map nested dictionaries to dataframe columns in python? | <p>I have nested dictionaries like this:</p>
<pre><code>X = {A:{col1:12,col-2:13},B:{col1:12,col-2:13},C:{col1:12,col-2:13},D:{col1:12,col-2:13}}
Y = {A:{col1:3,col-2:5},B:{col1:1,col-2:2},C:{col1:4,col-2:7},D:{col1:8,col-2:7}}
Z = {A:{col1:6,col-2:7},B:{col1:4,col-2:7},C:{col1:5,col-2:7},D:{col1:4,col-2:9}}
</code></p... | <p>Transpose and concat them:</p>
<pre><code>dfX = pd.DataFrame(X).T.add_suffix('_X')
dfY = pd.DataFrame(Y).T.add_suffix('_Y')
dfZ = pd.DataFrame(Z).T.add_suffix('_Z')
output = pd.concat([dfX, dfY,dfZ], axis=1))
</code></pre>
<p>output :</p>
<pre><code> col1_X col-2_X col1_Y col-2_Y col1_Z col-2_Z
A 12 ... | python|python-3.x|pandas|dataframe|dictionary | 1 |
353,753 | 73,303,113 | Extracting specific blocks from a module list | <p>I'm using a <a href="https://github.com/facebookresearch/TimeSformer/blob/main/timesformer/models/vit.py#L291" rel="nofollow noreferrer">pretrained model</a> in which there are several self_attentions sequentially stacked each one after another and the number of them is 12. I need to extract the output of the fourth... | <p>To extract the output of a layer, you'll need to use <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html" rel="nofollow noreferrer">hooks</a>. A forward hook is a function that is called after the <code>forward</code> method of the module was executed.</p>
<p>Here's an example of how to do it:</p... | python|pytorch|transformer-model | 2 |
353,754 | 73,187,872 | Splitting Dataset over Multiple GPUs | <p>I'm training a large network that inputs and outputs 512x512 images. At the moment, I have 2 Tesla A100 GPUs with 40 GB of memory each, and a dataset comprising 10,000 input and outputs pairs. This adds up to roughly 38 GB of training data, which leads me to run out of memory when sending this data to the "cuda... | <p>Here is my solution. Open to others, especially more memory-efficient options!</p>
<pre><code>to_t = lambda array: torch.tensor(array, device=device)
class CustomDataset(Dataset):
def __init__(self, image, label):
self.image = image
self.label = label
def __len__(self):
return len(self.label)
def __ge... | deep-learning|pytorch | 0 |
353,755 | 73,476,668 | Setting the last n non NaN vale per group with nan | <p>I have a DataFrame with (several) grouping variables and (several) value variables. My goal is to set the last n non nan values to nan. So let's take a simple example:</p>
<pre><code>df = pd.DataFrame({'id':[1,1,1,2,2,],
'value':[1,2,np.nan, 9,8]})
df
</code></pre>
<pre class="lang-none prettyprint... | <p>You can check <code>cumsum</code> after <code>groupby</code> get how many <code>notna</code> value per-row</p>
<pre><code>df['value'].where(df['value'].notna().iloc[::-1].groupby(df['id']).cumsum()>1,inplace=True)
df
Out[86]:
id value
0 1 1.0
1 1 NaN
2 1 NaN
3 2 9.0
4 2 NaN
</code></... | python|pandas|group-by|running-count | 2 |
353,756 | 73,313,927 | Merge DF on conditions to return specific rows | <p><strong>Problem Statment</strong>:</p>
<p>I have two tables with sample inputs below:</p>
<p><em>Baseline_Cars</em>:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Name</th>
<th style="text-align: center;">Fname</th>
<th style="text-align: right;">FW_Base</th>
... | <p>If I understand what you are asking, there is no need to try and complete this in a one-liner. This gives you a lot more control over what happens and how to modify specific changes in the future.</p>
<p>You can start by just merging the baseline cars to the proposed cars.</p>
<pre class="lang-py prettyprint-overrid... | python|python-3.x|pandas|dataframe|numpy | 1 |
353,757 | 73,365,138 | Python: Adding values to empty dictionary | <p>I have scraped a data from website and I would like to save all of data. However, it only saves the last value of the data. I have made an empty dictionary but i'm struggling with adding element in empty dictionary</p>
<p>Here's my code</p>
<pre><code>from bs4 import BeautifulSoup
import requests
import pandas as pd... | <p>Close to your goal, simply add the information to your dict and append it with each iteration to a list. So you are able to create a dataframe:</p>
<pre><code>for movie in movies:
data.append({
'name': movie.find('td', class_='titleColumn').a.text,
'rank': movie.find('td', class_="titleColu... | python|pandas|dictionary|web-scraping|beautifulsoup | 2 |
353,758 | 73,200,927 | pandas: how to properly apply text based condition | <p>I have a pandas dataframe which has a 'source' column as shown in the table below. I want to normalize its values and create a new column called 'derived'.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>source</th>
<th>value</th>
<th>derived</th>
</tr>
</thead>
<tbody>
<tr>
<td>google</... | <p>You are trying to apply a function which, as coded, takes a whole DataFrame.</p>
<p>Here is a fix:</p>
<pre class="lang-py prettyprint-override"><code>def normalize_source(x):
x = x.lower()
if 'facebook' in x:
return 'facebook'
elif 'google' in x:
return 'google'
return 'other'
data ... | python|pandas | 1 |
353,759 | 73,368,405 | Display data side by side | <p>By using pandas.dataframe, extracting data using df.iloc, and applying some operations, I defined X, and Y as:</p>
<pre><code>df.iloc[:,1] = XX[df.iloc[:,1],df.iloc[:,2],def.iloc[:,3]]
</code></pre>
<p>and</p>
<pre><code>df.iloc[:,2] = ZZ[df.iloc[:,1],df.iloc[:,2],def.iloc[:,3]]
</code></pre>
<p>I defin... | <p>Here the DataFrame will be join based on the index -</p>
<p><code>pd.merge(x, y, left_index=True, right_index=True)</code></p>
<p>or</p>
<p>we can use a common column for joining (It is similar to SQL join)</p>
<p><code>pd.merge(x, y, on = 'give_common_col_name')</code></p> | python|pandas|dataframe | 0 |
353,760 | 73,397,802 | comparison of values in a column of Dataframe | <p>CODE:-</p>
<pre><code>from datetime import date
from datetime import timedelta
from nsepy import get_history
import pandas as pd
import datetime
end1 = date.today()
start1 = end1 - timedelta(days=180)
stock = ['RELIANCE']#,'HDFCBANK','INFY','ICICIBANK','HDFC'] ,'TCS','KOTAKBANK','LT','SBIN','HINDUNILVR','AXISBANK... | <p>You can use a condition like this:</p>
<pre><code>result = list()
if df['D_vol'].iloc[-1] > max(df['D_vol'].iloc[-91:-1]):
result.append(df)
</code></pre>
<p>Thus you get datasets where the last value is bigger than 90 previous ones.</p> | python|pandas|numpy | 1 |
353,761 | 73,499,369 | The model is taking too much time to train on a large news dataset | <p>I have a large news dataset containing approximately 300k news descriptions. I am applying dynamic topic modeling using gensim lda sequential model with 11 yearly time slices. The average length of each news article is around 3200 words.</p>
<p>I applied the model to a reduced dataset of 1500 messages and also divid... | <p>Most probably the library does not support TPUs. <br />
A little Google search showed me lack of GPU support also.<br />
Try the same on CPUs. I think you will get a similar result.</p> | python|pandas|gensim|lda|topic-modeling | 0 |
353,762 | 73,183,689 | Loss key needs to be present Pytorch | <p>I am following this repo:
<a href="https://github.com/NVIDIA/NeMo/tree/main/examples/nlp/entity_linking" rel="nofollow noreferrer">https://github.com/NVIDIA/NeMo/tree/main/examples/nlp/entity_linking</a></p>
<p>Here is a small tutorial:
<a href="https://colab.research.google.com/github/NVIDIA/NeMo/blob/v1.0.2/tutori... | <p>You get this error message about "loss key needs to be present" because in some training steps you return the dict <code>{"loss": None}</code>. This happens in your code here</p>
<pre><code>if train_loss == 0:
train_loss = None
lr = None
</code></pre>
<p>where you set <code>train_loss = N... | python|pytorch|pytorch-lightning | 0 |
353,763 | 73,339,341 | Adding values to a columns based on other columns in the same dataframe | <p>My aim is to put values in column D based on columns A to C. I want to go through each of the columns A, B and C and add 1 to column D if the value is greater than 20.</p>
<pre><code>import pandas as pd
data={'A':[5,2,25,4],"B":[15,22,100,24], "C":[4, 100, 0, 19], "D" : [0,0,0,0]}
df= p... | <p>What is wrong is that you can't use <code>if Series > value</code> in a vectorial way. <code>if</code> expects a single boolean value and <code>df.iloc[:, x] > 20</code> returns a Series of booleans.</p>
<p>In your case use:</p>
<pre><code>df['D'] = df.drop(columns='D').gt(20).sum(1)
</code></pre>
<p><em>NB. ... | python|pandas|dataframe | 2 |
353,764 | 73,511,306 | Make soccer prediction from sample data | <p>I have this code on a <a href="https://runkit.com/embed/d49t0inpy048" rel="nofollow noreferrer">node.js playground</a>. I'm experimenting with brain.js and I want to predict the probability that a team will win a match.</p>
<p>NB: <a href="https://stackoverflow.com/questions/24432687/soccer-score-prediction-using-br... | <p>WE are together. Use this to get some ideas <a href="https://github.com/lukewduncan/brain-js-predictor/blob/master/routes/index.js" rel="nofollow noreferrer">https://github.com/lukewduncan/brain-js-predictor/blob/master/routes/index.js</a></p>
<p>and</p>
<pre><code>const teams = {
Sofapaka: 0,
Tusker: 1,
Posta... | node.js|machine-learning|neural-network|tensorflow.js|brain.js | 1 |
353,765 | 73,258,494 | First appearance of a condition in a dataframe | <p>I have a pandas dataframe like this:</p>
<pre class="lang-py prettyprint-override"><code> col
0 3
1 5
2 9
3 5
4 6
5 6
6 11
7 6
8 2
9 10
</code></pre>
<p>that could be created in Python with the code:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame(
... | <p>Boolean indexing to the rescue:</p>
<pre><code># value > 8
m1 = df['col'].gt(8)
# get previous value <4
# check if any occurred previously
m2 = df['col'].shift().lt(4).groupby(m1[::-1].cumsum()).cummax()
df[m1&m2]
</code></pre>
<p>Output:</p>
<pre><code> col
2 9
9 10
</code></pre> | python|pandas|dataframe | 2 |
353,766 | 73,287,093 | Even-Odd Train-Test Split with 2D array input and return two tuples of the form (X_train, y_train), (X_test, y_test) | <p>trying to complete this function. Any help would be appreciated. This is my work so far:</p>
<p>Should take a 2-d numpy array as input:</p>
<pre><code>array([[ 1.961e+03, 2.263e-02],
[ 1.962e+03, 1.420e-02],
[ 1.963e+03, 8.360e-03],
[ 1.964e+03, 5.940e-03],
[ 1.965e+03, 5.750e-03],
... | <p>Given your example data</p>
<pre><code>data = np.array([[ 1.961e+03, 2.263e-02],
[ 1.962e+03, 1.420e-02],
[ 1.963e+03, 8.360e-03],
[ 1.964e+03, 5.940e-03],
[ 1.965e+03, 5.750e-03],
[ 1.966e+03, 6.190e-03],
[ 1... | python|numpy|train-test-split | 1 |
353,767 | 73,279,649 | Learning multivariate normal covariance matrix using pytorch | <p>I am trying to learn a multivariate normal covariance matrix (Sigma, ∑) using some observations.</p>
<p>The way I went at it is by using pytorch.distributions.MultivariateNormal:</p>
<pre><code>import torch
from torch.distributions import MultivariateNormal
# I tried both the scale_tril parameter and the covariance... | <p>You are not calling .grad on your leaf nodes (on <code>.view</code> rather than tensor itself), also you have <code>requires_grad=False</code> on a mean, lets make things more explicit</p>
<pre><code>import torch
from torch.distributions import MultivariateNormal
mean = torch.tensor([0.0, 0.0], requires_grad=True)
... | deep-learning|pytorch|gaussian-process|bayesian-deep-learning|pytorch-distributions | 1 |
353,768 | 73,253,254 | pyspark conditional cumulative sum | <p>I have a pyspark dataframe with two dates - bill and payment date. I want to create a column that has the sum of amounts of bills billed and paid before the bill date of that row. Also, this needs to be done for every buyer ID individually. Example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>... | <p>You can use <code>pandas_udf()</code> and do conditional processing there:</p>
<pre><code>import pandas as pd
import pyspark.sql.functions as F
from pyspark.sql import SparkSession, Window
from pyspark.sql.types import IntegerType
def conditional_sum(data: pd.DataFrame) -> int:
df = data.apply(pd.Series) # ... | python|pandas|pyspark | 0 |
353,769 | 73,488,634 | De-duplication with merge of data | <p>I have a dataset with duplicates, triplicates and more and I want to keep only one record of each unique with merge of data, for example:</p>
<pre><code>id name address age city
1 Alex 123,blv
1 Alex 13
3 Alex 24 Florida
1 Alex ... | <p>I've changed a bit the code from <a href="https://stackoverflow.com/a/47376393/14774959">this</a> answer.</p>
<p>Code to create the initial dataframe:</p>
<pre><code>import pandas as pd
import numpy as np
d = {'id': [1,1,3,1],
'name': ["Alex", "Alex", "Alex", "Alex"],
... | python-3.x|pandas|dataframe | 2 |
353,770 | 73,392,167 | Python - Convert 5 digit date to datetime from SAS date | <p>I have a 5 digit date variable that was exported from SAS. I am having trouble converting it into a datetime format in Python. The variable is currently stored as an object.</p>
<p>Here is a background on SAS dates:</p>
<p><em>"The SAS System represents dates as the number of days since a reference date. The re... | <p>Let's try <code>pd.to_datetime</code> with specified <code>origin</code> and <code>unit</code></p>
<pre class="lang-py prettyprint-override"><code>df['out'] = pd.to_datetime(df['Date'], unit='D', origin='1960-01-01')
</code></pre>
<pre><code>print(df)
Date out
0 21032 2017-08-01
1 16387 2004-11-12
2 ... | python|pandas|date|python-datetime | 3 |
353,771 | 73,304,319 | How to map multiple nested dictionaries to Pandas DataFrame | <p>I have a Pandas DataFrame that looks something like this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
"class":["a","b","c","b","a","b","c","c","a","c","b","c","c"... | <p><code>df.apply</code> to the rescue:</p>
<pre><code>numbers = {
'a': class_a_numbers,
'b': class_b_numbers,
'c': class_c_numbers,
}
df["number"] = df.apply(lambda row: numbers[row["class"]][row["country"]][row["category"]], axis=1)
</code></pre> | python|pandas|dataframe|dictionary | 2 |
353,772 | 73,426,118 | setting -t, +t around the event date, NaN giving a headache | <p>I have a df</p>
<pre><code>id date eventdate
A 2020Q1 2020Q3
A 2020Q2 2020Q3
A 2020Q3 2020Q3
A 2020Q4 2020Q3
B 2019Q1 2019Q2
B 2019Q2 2019Q2
B 2019Q3 2019Q2
B 2019Q4 2019Q2
C 2020Q1 NaN
C 2020Q2 NaN
C 2020Q3 NaN
C 2020Q4 NaN
D 2019Q2 NaN
D 2019Q3 NaN
D 2019Q4 NaN
...
... | <p>Problem is that <code>pd.PeriodIndex</code> converts <code>NaN</code> value to <code>NaT</code>. When you convert a <code>NaT</code> value to int with <code>.astype('int')</code>, it gives <code>-9223372036854775808</code>.</p>
<p>You can check the data is <code>NaT</code> when accessing the <code>n</code> attribute... | python|pandas | 1 |
353,773 | 73,253,492 | Unable to read multiple sheets of excel files in a folder in python | <p>I am trying to read multiple worksheets from 7 different excel files in a folder in python. This is what I have tried -</p>
<pre><code>import pandas as pd
import glob
# getting excel files from Directory Desktop
path = "Desktop/my_path"
# read all the files with extension
filenames = glob.glob(path + &qu... | <p>Can you try it this way?</p>
<pre><code>import os
import pandas as pd
import glob
glob.glob("C:\\your_path\\*.xlsx")
all_sheets = []
all_data = pd.DataFrame()
for f in glob.glob("C:\\your_path\\*.xlsx"):
sheets_dict = pd.read_excel(f, sheet_name=None)
for name, sheet in sheets_dict... | python-3.x|excel|pandas|dataframe|jupyter-notebook | 0 |
353,774 | 73,228,427 | Why doesn't TensorFlow learn from my numpy array but works with other numpy arrays? (Cubic regression) | <p>This is the code for my data generation:</p>
<pre><code>x = []
for i in range(-500, 500):
x.append(i)
y = []
for i in range(-500, 500):
y.append(i**3)
x = np.array(x)
y = np.array(y)
</code></pre>
<p>And I can plot it and everything's fine, but when I use this dataset in my model:</p>
<pre><code>#Build model
m... | <p>You can change the compile parameters as per dataset type and values range to get the required output.</p>
<p>For this, Please change the 'Adam' optimizer to either 'SGD' or 'RMSprop' which are good optimzers for linear values. Also change the loss function to <code>MeanSquaredLogarithmicError()</code> as your data ... | python|numpy|tensorflow | 0 |
353,775 | 73,479,834 | Input array must have a shape == (..., 3)), got (299, 299, 4) | <p>I am using a pretrained resnet50 model to validate some classes. I am using LIME to test how the model is testing this data as well. However, some of the images are not RGB and may be different formats, and I noticed that RGB arrays are value 3 instead of other numbers (like 4). I am using skimage to preprocess the ... | <p>Your model expects RGB images and your url may point to non-RGB images.</p>
<p>In this situation the best is to make sure images are read in RGB. For instance, <a href="https://docs.opencv.org/3.4/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56" rel="nofollow noreferrer"><code>OpenCV</code> reads ima... | tensorflow|scikit-image|lime | 0 |
353,776 | 73,247,678 | Changing dataframe values after regex function problem | <p>I try to make a pipeline voor Twitter sentiment analysis. As usual data preprocessing is a thing...</p>
<p>Based on real tweets I made a dataframe with only 3 rows/tweets, for experiment goal.</p>
<p>What I try to do:
1: clear al @, ', http etc. from the tweet.
2: after that is done I want the cleaned tweet to repla... | <p>try:</p>
<pre class="lang-py prettyprint-override"><code>df.Tweet = df.Tweet\
.str.replace(r'[@#]\w*\b', '', regex=True)\
.str.replace(r'https?://\S+', '', regex=True)\
.str.replace(r'\s[#@%/;$()~_?\+-=\\\.&\']+', '', regex=True)\
.str.strip()
</code></pre>
<p>Output:</p>
<pre class="lang-py pret... | python|pandas|regex | 1 |
353,777 | 73,183,551 | How does loss of information lead to better accuracy? | <p>So, I’ve been looking into the following code</p>
<pre><code># Define the model
model = tf.keras.models.Sequential([
# Add convolutions and max pooling
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPoo... | <p>The loss of information is a by-product of mapping the image onto a lower dimensional target (compressing the representation in a lossy fashion), which is actually what you want. The relevant information content however is preserved as much as possible, while reducing the irrelevant or redundant information. The ini... | tensorflow|machine-learning|deep-learning|neural-network|conv-neural-network | 1 |
353,778 | 73,427,954 | Fastest way to compute a rolling distance between high-dimensional vectors in numpy? | <p>I have a time series of vectors: <code>Y = [v1, v2, ..., vn</code>]. At each time <code>t</code>, I want to compute the distance between vector <code>t</code> and the average of the vectors before <code>t</code>. So for example, at <code>t=3</code> I want to compute the cosine distance between <code>v3</code> and <c... | <p><a href="https://numpy.org/doc/stable/reference/generated/numpy.cumsum.html#numpy.cumsum" rel="nofollow noreferrer"><code>ndarray.cumsum</code></a> or <code>np.add.accumulate</code> can be used to calculate the cumulative sum:</p>
<pre><code>>>> y
array([[0.77132064, 0.02075195],
[0.63364823, 0.74880... | python|numpy|vector|distance | 3 |
353,779 | 73,302,479 | Numpy way to temporarily remove NaN values from array, with ability to place them back later | <p>I am trying to get a version of an array without the NaN values, with the ability to place them back later. Example:</p>
<pre class="lang-py prettyprint-override"><code>Array = [1,2,nan,4,5,2,5,6,nan,1,nan,nan,nan,nan,8,7,5,2]
Array_non_nan = [1,2,4,5,2,5,6,1,8,7,5,2]
</code></pre>
<p>This can be achieved with array... | <p>You can save the indices where the <code>nan</code> values existed via as a boolean mask. Then use that mask to fill in the the value you want.</p>
<pre><code>a = np.array([nan, 1., 2., 3., 4., 5., nan, 6., 7., 8., 9.])
nan_mask = np.isnan(a)
a_no_nan = a[~nan_mask]
</code></pre>
<p>So far it is basicall... | python|numpy | 2 |
353,780 | 73,429,297 | plotting percentage of occurrence in a group in data frame python | <p>I have a data frame with two columns, age group and gender.
I want to plot the percentage of females and males in every age group.</p>
<p>this is what i did</p>
<pre><code>df.groupby('AGE_B_M0')['Gender_Type_Cd_M0'].value_counts(normalize=True)
</code></pre>
<p>how do i plot this as pie chart ?</p>
<p>I got the perc... | <p><code>df.groupby('Gender_Type_Cd_M0').count() / len(df)</code> should return the percentage of observations for each gender.</p> | python|pandas|data-analysis|exploratory-data-analysis | 1 |
353,781 | 73,514,510 | Apply strip() to all cells in dataframe with multiple data types | <p>I have a dataframe that has multiple data types. Part of my processing code is to apply the <code>strip()</code> function before I work on the df.</p>
<p>My example df:</p>
<pre><code>Unnamed: 1 Unnamed: 2 Unnamed: 3 Unamed: 4
Protocol Number NaN NaN 5
xyz-4134 NaN 3... | <p>Incorporating the suggestions by both IgnatiusReilly & Rabinzel, this worked for me:</p>
<pre><code>df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
</code></pre>
<p>Also worth noting, the reason the <code># of Units</code> was keeping the trailing space was because I used used <code>applymap</... | python|pandas | 1 |
353,782 | 73,375,199 | List creation from dataframe using for loop | <p>having a dataframe as below:</p>
<pre><code>data={'column1':[1,1,1,1,1,1,1,1,2,2,2,2],'person':['A','A','A','A','B','B','B','B','C','C','C','C'],'location1':['GOA','BANGLORE','GOA','BANGLORE','BANGLORE','DELHI','BANGLORE','DELHII','KOCHI','DELHI','DELHI','KOCHI'],'location2':['BANGLORE','GOA','GOA','BANGLORE','DELHI... | <p>You can start off by grouping the dataframe based on the columns 'column1', <code>person</code> and <code>location1</code>. After that, you use <code>apply</code> to make a list of the results in every group.</p>
<pre><code>grouped_df = df.groupby(['column1','person','location1'])['time'].apply(lambda x:list(x))
co... | python|pandas|dataframe | 3 |
353,783 | 35,028,248 | Want to write csv after concatenating | <pre><code>import glob
import os
import pandas as pd
os.chdir('E:\in\extracted')
file_list = glob.glob('*.csv')
df_list = []
col_names = ['Year', 'Month', 'Day', 'Hour', 'Temp', 'DewTemp', 'Pressure', 'WinDir', 'WindSpeed',
'Sky', 'Precip1', 'Precip6', 'ID']
def outfile():
new_path = r'E:\out\Conc... | <p>You call <code>to_csv</code> as a method on the dataframe itself:</p>
<pre><code>concat_d.to_csv(outfile()) #Says I need 'Self'
</code></pre> | python-3.x|pandas | 1 |
353,784 | 35,239,461 | LSTM implementation with peephole | <p>I have been reading papers about LSTM and checking its implementations. There is one point that is not clear to me.<br>
In most of the papers it is mentioned that the weight matrices from the cell to gate vectors should be diagonal(ex: <a href="http://arxiv.org/pdf/1308.0850v5.pdf" rel="nofollow noreferrer">Alex</a>... | <p>The TensorFlow implementation does use a diagonal matrix, see <a href="https://github.com/tensorflow/tensorflow/blob/97f585d506cccc57dc98f234f4d5fcd824dd3c03/tensorflow/python/ops/rnn_cell.py#L353" rel="noreferrer">here</a>. Note that what this means in practice is that the peepholes only go from the cell to itself,... | tensorflow|neural-network|deep-learning|theano|lstm | 5 |
353,785 | 35,268,925 | How to exclude first word in Pandas header? | <p>I'm importing text files to Pandas data frames. Number of columns can vary and also the names varies. </p>
<p>However, the header line always starts with <code>~A</code> and read_csv interprets this a s the name of the first column, subsequently all the column names are shifted on step to the right. </p>
<p>Earlie... | <p>Why not just post-process?</p>
<pre><code>df = ...
df_modified = df[df.columns[:-1]]
df_modified.columns = df.columns[1:]
</code></pre> | python|csv|pandas | 6 |
353,786 | 34,890,899 | How to add dynamically created input images to a RandomShuffleQueue using a QueueRunner in tensor flow | <p>I am trying to train a CNN with images created during program execution. I have a game environment (not created by me) that generates screen images that depend on actions taken in the game. The actions are controlled by the learnt CNN. </p>
<p>These images are then pushed into a RandomShuffleQueue, from which mini ... | <p>The problem can be traced to this line, which defines the <a href="https://www.tensorflow.org/versions/master/api_docs/python/train.html#QueueRunner" rel="noreferrer"><code>tf.train.QueueRunner</code></a>:</p>
<pre><code>experience_runner = tf.train.QueueRunner(
experience, [perceive(game()) for num in range(av... | python|numpy|neural-network|tensorflow|conv-neural-network | 5 |
353,787 | 34,983,826 | Pandas to_dict group all non index columns into a list of tuples | <p>Example dataframe</p>
<pre><code>patient_id, value_id, value
1 10 20
1 30 5
2 40 8
</code></pre>
<p>From this dataframe, i'd like to transform it to something like this in a dictionary form.</p>
<pre><code>{ 1: [(10, 20), (30, 5)], 2: [(40, 8)] }
</code></pre>
... | <p>I do not see any way that <code>to_dict()</code> can create what you want here. The following solution is not the most Pythonic (or Pandanic), but it is a way to get what you want: </p>
<pre><code>d={}
for pid,vid,v in df.itertuples(index=False):
d.setdefault(pid,[])
d[pid].append((vid,v))
</code></pre>
<p... | python|pandas | 0 |
353,788 | 35,005,017 | How to fix the TypeError Corresponding to the Conversion between Types in Python3? | <p>I am running the following code. Since I am new to python, I am trying to understand why I am getting TypeError and how to fix it. Your help is greatly appreciated.</p>
<pre><code>import matplotlib
matplotlib.use('SVG')
import matplotlib.pyplot as pyplot
import random
from numpy import array as ar
import math
N ... | <p>Your error occurs because <code>math.log()</code> expects a scalar, or scalar-like arrays.</p>
<pre><code>import math
import numpy as np
math.log(np.array([3, 4])) # will fail
math.log(np.array([3])) # same as math.log(3)
</code></pre>
<p>If you want to calculate the log of all elements, use <code>np.log()</co... | python|numpy|matplotlib | 2 |
353,789 | 35,163,371 | Tensorflow: Extracting the features of a trained model | <p>I have an implementation of the AlexNet. I'm interested in extracting the vector of features of a trained model <em>before the fully-connected classification layers</em></p>
<ol>
<li><p>I want to first train the model (below I included the evaluation methods for training and testing).</p></li>
<li><p>How do I get a... | <p>It sounds like you want the value of dense2 from alex_net()? If so, you will need to return that from alex_net() in addition to out, so</p>
<pre><code>return out
</code></pre>
<p>becomes</p>
<pre><code>return dense2, out
</code></pre>
<p>and</p>
<pre><code>pred = alex_net(x, weights, biases, keep_prob)
</code>... | python|machine-learning|computer-vision|tensorflow | 3 |
353,790 | 35,158,954 | Read data from text format into Python Pandas dataframe | <p>I am running Python 2.7 on Windows.</p>
<p>I have a large text file (2 GB) that refers to 500K+ emails. The file has no explicit file type and is in the format:</p>
<pre><code>email_message#: 1
email_message_sent: 10/10/1991 02:31:01
From: tomf@abc.com| Tom Foo |abc company|
To: adee@abc.com| Alex Dee |abc company... | <p>I could not resist the itch so here is my approach.</p>
<pre><code>from __future__ import unicode_literals
import io
import pandas as pd
from pandas.compat import string_types
def iter_fields(buf):
for l in buf:
yield l.rstrip('\n\r').split(':', 1)
def iter_messages(buf):
it = iter_fields(buf)... | python|python-2.7|pandas|dataframe|datasource | 1 |
353,791 | 35,096,783 | Interface Error importing pandas dataframe to sqlite: Unsupported parameter | <p>I have an excel workbook which has two worksheets. I want to import these two worksheets data in two different pandas data frame and then write it to sqlite database.</p>
<p>Here is the code for the same. </p>
<pre><code>leads_dim = pd.read_excel('client_data.xlsx',sheetname='Lead_Dimension')
leads_dim.to_sql('lea... | <p>The reason for the error message is probably that you have a column with times (<code>datetime.time</code> objects). These are not supported using the sqlite3 connection fallback (but will be in the upcoming pandas release, see <a href="https://github.com/pydata/pandas/pull/11547" rel="nofollow">PR</a>).</p>
<p>If ... | python|sql|pandas | 0 |
353,792 | 30,759,033 | Numpy - Difference between two floats vs float type's precision | <p>I was looking at <code>numpy.finfo</code> and did the following:</p>
<pre><code>In [14]: np.finfo(np.float16).resolution
Out[14]: 0.0010004
In [16]: np.array([0., 0.0001], dtype=np.float16)
Out[16]: array([ 0. , 0.00010002], dtype=float16)
</code></pre>
<p>It seems that the vector is able to store two numb... | <p>From what I understand, the precision is the amount of decimals you can have. But since floats are stored whith exponants, you can have a number smaller than the resolution. try <code>np.finfo(np.float16).tiny</code>, it should give you <code>6.1035e-05</code>, which is way smaller than the resolution. But the base ... | python|numpy|floating-accuracy | 2 |
353,793 | 30,942,224 | When I run this Python 2.7 code I get the output "k" immediately . Shouldn't "k" be printed after 5 seconds? | <pre><code>import numpy
import cv2
vid=cv2.VideoCapture("katy.avi")
cv2.waitKey(5000)
if vid.isOpened():
print "k"
</code></pre>
<p>I am running this code on windows 8.1, Python 2.7 and numpy 1.9.1.</p> | <p>I think I remember that pressing a key will trigger the end of waitKey(), thus skipping the 5s</p> | numpy|opencv3.0 | 0 |
353,794 | 30,755,719 | Pandas guess delimiter with sep=None | <p><a href="http://pandas.pydata.org/pandas-docs/version/0.15.2/io.html#io-read-csv-table" rel="noreferrer">Pandas documentation</a> has this:</p>
<blockquote>
<p>With sep=None, read_csv will try to infer the delimiter automatically
in some cases by “sniffing”.</p>
</blockquote>
<p>How can I access pandas' guess ... | <p>Looking at the source code, I doubt that it's possible to get the delimiter out of <code>read_csv</code>. But <code>pandas</code> internally uses the <code>Sniffer</code> class from the <code>csv</code> module. Here's an example that should get you going:</p>
<pre><code>import csv
s = csv.Sniffer()
print s.sniff("a... | python|csv|pandas | 13 |
353,795 | 31,160,675 | Pandas add two column values to new data frame | <p>Why can I do this:</p>
<pre><code>df[df['location'] == '170079']
</code></pre>
<p>(which then yields some information on the location that I am interested in)</p>
<p>But not this (or at least, it yields an error):</p>
<pre><code>df_target = df[(df['location'] == '170079'), (df['location'] == '170078')]
</code></... | <p>If you want to create a new dataframe with multiple conditions on locations, this is a way to do it :</p>
<pre><code>df_target = df[df['location'].isin(['170079','170078'])]
</code></pre>
<p>I invite you to refer to the pandas' documentation about <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html"... | python|pandas | 1 |
353,796 | 30,815,420 | Finding All Values in Pandas DataFrame Not of Certain Type | <p>To avoid the following error, I would like to replace any integer in my DataFrame with <a href="https://en.wikipedia.org/wiki/Unix_time" rel="nofollow">Unix Time</a>:</p>
<blockquote>
<p>ValueError: mixed datetimes and integers in passed array</p>
</blockquote>
<p>In a small subset of the Excel files I'm reading... | <p>Use Python's <a href="https://docs.python.org/2/library/functions.html#isinstance" rel="nofollow">isinstance()</a> or <a href="https://docs.python.org/2/library/functions.html#issubclass" rel="nofollow">issubclass()</a></p> | python|datetime|pandas | 1 |
353,797 | 31,077,140 | Pandas count results per unique server | <p>I am very new to both pandas and python. I did find this </p>
<p><a href="https://stackoverflow.com/questions/23765397/pandas-count-unique-occurances-by-month">Pandas Count Unique Occurances by Month</a></p>
<p>on stackoverflow that is similar to my question, but I can't seem to manipulate the answer to address my... | <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow"><code>groupby</code></a> 'Server Name', call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.count.html#pandas.core.groupby.GroupBy.count" rel="nofollow"><code>count</code></a> and the... | python|pandas|group-by|dataframe | 1 |
353,798 | 31,030,834 | Connecting Python/pandas to Redshift when SSL is required | <p>My company recently changed our Redshift cluster and now they require an SSL connection. In the past I've connected Python/pandas to Redshift via the method I've detailed here: <a href="http://measureallthethin.gs/blog/connect-python-and-pandas-to-redshift/" rel="noreferrer">http://measureallthethin.gs/blog/connect-... | <p>AWS has developed an Amazon Redshift connector for Python (<a href="https://github.com/aws/amazon-redshift-python-driver" rel="nofollow noreferrer">here is the GitHub repo</a>) that helps in the process.</p>
<p>In order to install it on may install from the source</p>
<pre><code>git clone https://github.com/aws/amaz... | python|ssl|pandas|psycopg2|amazon-redshift | 1 |
353,799 | 30,892,269 | Improve performance on processing a big pandas dataframe | <p>I have a big pandas dataframe (1 million rows), and I need better performance in my code to process this data.</p>
<p>My code is below, and a profiling analysis is also provided.</p>
<p>Header of the dataset:</p>
<pre><code>key_id, date, par1, par2, par3, par4, pop, price, value
</code></pre>
<p>For each key, we... | <p>The way to make this significantly faster is like this.</p>
<p>Create some sample data</p>
<pre><code>In [148]: df = DataFrame({'A' : range(5), 'B' : [1,1,1,2,2] })
</code></pre>
<p>Define the <code>compute_val_column</code> like you have</p>
<pre><code>In [149]: def f(p):
return DataFrame({ 'A' : df['A']*p,... | python|performance|pandas|profiling|dataframe | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.