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
10,600
49,333,733
Python Pandas Combine two rows
<p>I have a <strong>big dataset</strong> like following:</p> <p><a href="https://i.stack.imgur.com/5BFDp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5BFDp.png" alt="enter image description here"></a></p> <p>There are so many rows like this format.</p> <p>Finding each NaN rows should base on th...
<p>I try create solution working if multiple <code>NaN</code>s consecutive rows:</p> <pre><code>df = pd.DataFrame({'Subjects':['Math','Computer','Science', 'II' , 'Computer','Science1'], 'Students':[10,np.nan, np.nan, 12, np.nan, 12], 'Class':[3, np.nan, np.nan, 5, np.nan, 5]}) ...
python|pandas
0
10,601
59,007,045
Efficient way of selectively replacing vectors from a tensor in pytorch
<p>Given a batch of text sequences, the same is converted into a tensor with each word represented using word embeddings or vectors (of 300 dimensions). I need to selectively replace vectors for certain specific words with a new set of embeddings. Further, this replacement will occur only for not all occurrences of the...
<p>It could be vectorized in a following way:</p> <pre><code>import torch import torch.nn as nn import torch.nn.functional as F batch_size, sentence_size, vocab_size, emb_size = 3, 2, 15, 1 # Make certain bias as a marker of embedding embedder_1 = nn.Linear(vocab_size, emb_size) embedder_1.weight.data.fill_(0) embe...
python|pytorch|tensor
1
10,602
58,787,234
deploying an ML model on gcloud with numpy c-extensions failed
<p>I am trying to deploy a simple Machine Learning model online, so that others can access it online easily. I have tried to to deploy it locally on LocalHost, and it works well. So now, i am trying to deploy it as a web application by using gcloud. </p> <p>I successfully followed this <a href="https://www.freecodecam...
<p>You have to specify in your app.yaml the numpy library as followed:</p> <p>app.yaml </p> <pre><code>runtime: python27 api_version: 1 threadsafe: true handlers: - url: /static static_dir: static - url: /.* script: main.app libraries: - name: ssl version: latest - name: numpy version: "1.6....
python|numpy|deployment|virtualenv|gcloud
0
10,603
58,670,207
Error: "Cannot treat the scalar component 'PVtoB'as an indexed component"
<p>Variable is not treated as an indexed component. <code>Numpy</code> overload?</p> <pre><code>model.PVtoB = Param(initialize=df.PVGeneration.tolist(), doc='PV Generation') def market_constraintx1(model, t): return (model.Charge[t]&lt;= model.PVtoB[t]) model.market_rulex1 = Constraint(model.T, rule=market_c...
<p>I think because the Pyomo Parameter PVtoB in your case is not given a Set as an index.</p> <p>Try:</p> <pre><code>model.PVtoB = Param(model.T, initialize=df.PVGeneration.tolist(), doc='PV Generation') def market_constraintx1(model, t): return (model.Charge[t]&lt;= model.PVtoB[t]) model.market_rulex1 = Cons...
numpy|optimization|solver|pyomo
1
10,604
70,255,871
Python - pandas, group by and max count
<p>I need the most similar (max count) from column cluster-1 from column cluster-2.</p> <blockquote> <p>Input - data</p> </blockquote> <p><a href="https://i.stack.imgur.com/DNURc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DNURc.png" alt="Input data" /></a></p> <blockquote> <p>Output - data</p> <...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.SeriesGroupBy.value_counts.html" rel="nofollow noreferrer"><code>SeriesGroupBy.value_counts</code></a> because by default sorted values, so possible convert <code>MultiIndex</code> to <code>DataFrame</code> by <a href="http://...
python|pandas|group-by|pandas-groupby
2
10,605
56,185,916
right way to add values in empty column in loop in dataframe , python
<pre class="lang-py prettyprint-override"><code>df=pd.DataFrame[columns='one','two','three'] for home in city: adres= home for a in abc: #abc is pd.Series od names #here i want to add values - adress and a , but my dataframe have 3 columns, i will use only 2 here df.loc[len(df)]= [adres, a, np...
<p>I think you are looking for something like:</p> <pre><code>for i in range(1): df.loc[i,['one','two']]=['adress','a'] print(df) </code></pre> <hr> <pre><code> one two three 0 adress a NaN </code></pre>
python|pandas|dataframe
1
10,606
55,911,687
how do u replace part of a each "elements" of a dataframe column with something else
<p>I want to change a columns of dates that have a defaulted value that is invalid in pandas date-time conversion. Say I have:</p> <pre><code>index Date_posted Voted_on id .... 0 2002-10-00 ... ... 1 2002-10-20 ... ... 2 2002-09-00 ... ... </code></pre> <p>There is 140,000 entries so...
<p>You can use str.replace</p> <pre><code>df['Date_posted'] = df['Date_posted'].str.replace('-00', '-01') pd.to_datetime(df['Date_posted']) 0 2002-10-01 1 2002-10-20 2 2002-09-01 </code></pre>
python-3.x|pandas|dataframe|datetime
2
10,607
55,849,086
How to groupby and then weight values according to size of each group
<p>I would like to give each employee a pro rata share after a sale has been made. Therefore I first need to sum up the number of contacts per Customer that leads to a sale and then split the reward the each employee involved in this process. </p> <pre><code>import pandas as pd df = pd.DataFrame({"Cust_ID":[1,1,1,2,3,...
<p>First let's augment the DataFrame:</p> <pre><code>df['Touch'] = df.groupby('Cust_ID').cumcount() df['Touches'] = df.groupby('Cust_ID').Employee.count()[df.Cust_ID].values df['Reward'] = 0.0 </code></pre> <p>Now we have the basic setup:</p> <pre><code> Cust_ID Employee Purchase Touch Touches Reward 0 ...
python|pandas|transform|pandas-groupby
2
10,608
64,983,567
issue with date conversion
<p>I have a dataframe with a column of date and time in the format of <code>yyyymmddhhmm</code> (example: 20200325343000 ) and I'm trying to add a column of these dates and times to one column of datetime.</p> <p>I tried the following:</p> <pre><code>df['dates'] = pd.to_datetime(df['str_full_date'], format='%Y%m%d%H%M%...
<p>20200325343000 has a problem with this format. 20200325 is a good date but the time 343000 is not, unless we have a time 34:30:00. The error appears right</p> <pre><code>data = { 'intime' : ['20200325343000']} df = pd.DataFrame(data) df['dates'] = pd.to_datetime(df['intime'], format='%Y%m%d%H%M%S') df </code></pr...
pandas|google-colaboratory
0
10,609
64,899,771
Why is my groupby returning incorrect values for the 'product' column?
<p>I am trying to get the maximum price paid by each user, as well as which product was purchased, into a dataFrame. When I run the below code, it returns exactly what I'd expect, but the 'product' column is incorrect.</p> <p>Original data:</p> <pre><code>df = pd.DataFrame([[123,'xt23',20], [123,'q45...
<p>Use this to get the desired output efficiently.</p> <pre><code>idx = df.groupby(['userid'])['price'].transform(max) == df['price'] print(df[idx]) </code></pre>
python|pandas
0
10,610
64,924,225
TypeError: unsupported operand type(s) for &: 'float' and 'bool'
<pre><code>import pandas as pd df = pd.read_csv('NISPUF17.csv') cleaned = df[['CBF_01','P_NUMFLU']] (cleaned[cleaned['CBF_01']==1]) &amp; (cleaned[cleaned['CBF_01']==2]) </code></pre>
<pre><code>cleaned[(cleaned['CBF_01']==1) &amp; (cleaned['CBF_01']==2)] </code></pre> <p>This will give you desired rows from 'cleaned' Dataframe</p>
pandas
2
10,611
43,991,965
Error make correlation and heatmap
<p>i want to see correlation for (survived, pclass, sex, age, and fare) on dataset titanic, having table :</p> <p>Index([u'survived', u'pclass', u'sex', u'age', u'sibsp', u'parch', u'fare', u'embarked'],</p> <blockquote> <p><code>correlation_matrix =np.zeros(shape=(5,5))</code> matrix 5x5</p> </blockquote> ...
<p>It's complaining that 'ret' is a string and you are trying to divide it by rcount which is presumably a float or int.</p> <p>This looks like it may be a duplicate issue.</p> <p><a href="https://stackoverflow.com/questions/32012259/issue-with-seaborn-in-sublime">Issue with seaborn in sublime</a></p>
python|pandas|jupyter-notebook
0
10,612
44,284,946
pandas groupby mean with nan
<p>I have the following dataframe:</p> <pre><code>date id cars 2012 1 4 2013 1 6 2014 1 NaN 2012 2 10 2013 2 20 2014 2 NaN </code></pre> <p>Now, I want to get the mean of cars over the years for each id ignoring the NaN's. The result should be like this:</p> <pre><code>date id cars res...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="noreferrer"><code>transform</code></a>, this returns a series the same size as the original:</p> <pre><code>df["result"]=df.groupby("id")["cars"].transform('mean') print (df) date id cars result...
python|pandas|dataframe|mean|pandas-groupby
8
10,613
69,434,720
"ValueError: numpy.ndarray size changed " while trying Intel lpot in tensorflow model
<p>While trying out the Intel Low Precision Optimization Tool in tensorflow model, getting some value error.</p> <p>Please find the command I tried below:</p> <pre><code># The cmd of running ssd_resnet50_v1 bash run_tuning.sh --config=ssd_resnet50_v1.yaml --input_model=/tmp/ssd_resnet50_v1_fpn_shared_box_predictor_640x...
<p>Please try to upgrade numpy version. Command is given below:</p> <pre><code>pip install --upgrade numpy </code></pre> <p>I had this same issue and what I did was upgrade numpy, which resolved the issue.</p> <p>Thanks</p>
intel|intel-lpot|intel-tensorflow
1
10,614
69,597,461
Is the None stride in Keras MaxPooling2D dynamically set according to filter size?
<p>I am building a CNN on 112 x 92 images using Keras. After each conv layer I insert a MaxPooling2D layer. I am a little confused on how the output matrix dimensions are being calculated. I am using a (2,2) filter in each MaxPooling2D layer with strides set as 1) None 2) (1,1) and 3) (2,2). The output matrix of 1) and...
<p>Yes, as per the <a href="https://keras.io/api/layers/pooling_layers/max_pooling2d/" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>Integer, tuple of 2 integers, or None. Strides values. Specifies how far the pooling window moves for each pooling step. If None, it will default to pool_size.</p> </bl...
tensorflow|keras
1
10,615
41,105,285
NumPy array of integers to timedelta
<p>I have a numpy array of milliseconds in integers, which I want to convert to an array of Python datetimes via a timedelta operation.</p> <p>The following MWE works, but I'm convinced there is a more elegant approach or with better performence than multiplication by 1 ms.</p> <pre><code>start = pd.Timestamp('2016-0...
<p>So your approach produces:</p> <pre><code>In [56]: start = pd.Timestamp('2016-01-02 03:04:56.789101').to_pydatetime() In [57]: start Out[57]: datetime.datetime(2016, 1, 2, 3, 4, 56, 789101) In [58]: dt = np.array([ 19, 14980, 19620, 54964615, 54964655, 86433958]) In [59]: time_arr = start + dt * timedel...
python-3.x|datetime|pandas|numpy
7
10,616
40,839,441
Filling in a pandas column based on existing number of strings
<p>I have a pandas data-frame that looks like this:</p> <pre><code>ID Hobbby Name 1 Travel Kevin 2 Photo Andrew 3 Travel Kevin 4 Cars NaN 5 Photo Andrew 6 Football NaN .............. 1303 rows. </code></pre> <p>The number of Names filled in might be large then ...
<p>It's difficult to tell but I think you need <code>ffill</code></p> <pre><code>df['Name'] = df['Name'].ffill() </code></pre>
python|sorting|pandas|filter
0
10,617
54,085,357
Expect FloatTensors but got LongTensors in MNIST-like task
<p>I am performing a MNIST-like task, the input is 10-class images, and the expected output is the predicted class of the images.</p> <p>But now the <code>output</code> is like [-2.3274, -2.2723, ...], which the length is the batch_size. And the <code>target</code> is [4., 2., 2., 8., ...] </p> <p><code>Error message...
<p>The error you got refers to the <em>second</em> (#2) argument of the loss: the <code>target</code>.<br> <a href="https://pytorch.org/docs/0.4.1/nn.html#torch.nn.NLLLoss" rel="nofollow noreferrer"><code>NLLLoss</code></a> expects (for each element) to have a <em>float</em> vector of probabilities, and a single <em>lo...
python|machine-learning|deep-learning|computer-vision|pytorch
3
10,618
54,249,661
Tracking the position of element in rows using pandas
<p>I have been working on sport analysis especially soccer, I am calculating week rank of the teams. I want to track their position changes. Here is my sample data that replicate my problem.</p> <pre><code>df = pd.DataFrame() df ['Season'] = ['1314','1314','1314','1314','1314','1314','1314','1314','1314','1415','1415'...
<p>IIUC, you need:</p> <pre><code>df['Position_Change']=df.groupby(['Season','Team'])['Position'].apply(lambda x : x.diff().fillna(0)) print(df) Season Team GW Position Position_Change 0 1314 A 1 1 0.0 3 1314 A 2 3 2.0 6 1314 A 3 2 -1.0 1 ...
python|pandas
2
10,619
66,104,921
Pandas Merge Dataframe, Keep duplicates consecutive
<p>I'd like to merge dataframes df1 and df2, and preserve the row data in the order of original index value.</p> <p>df3 is my desired output :</p> <p><a href="https://i.stack.imgur.com/CFq2S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CFq2S.png" alt="enter image description here" /></a></p>
<p>Use <code>concat</code>:</p> <pre><code>pd.concat((df1,df2)).sort_index(kind='mergesort').reset_index(drop=True) </code></pre>
pandas|merge|duplicates
1
10,620
52,548,594
What is the right way to reshape a tensor?
<p>The code below is for lungs segmentation(2D) from Chest X-ray. It is supposed to generate lung masks from Chest X-rays using the trained model 'trained_model.hdf5'. On giving a chest x-ray as input, it should be able to identify which are the lungs and create a separate mask of the lungs accordingly. The <code>trai...
<p><code>ImageDataGenerator</code> expects the shape of input to be <code>(samples, height, width, channels)</code> but in your case, there's an extra dimension. But the shape of your input <code>X</code> is <code>(samples, height, width, channels, 1)</code> so you need to drop that last dimension first.</p> <p>To ans...
python|tensorflow|keras|scikit-image
2
10,621
58,575,666
How do I represent a list within a dict as a row in a Pandas dataframe?
<p>I have a list of dict, which looks like this: </p> <pre><code>[ { 'project': 'one', 'name': 'test', 'samples': [ {'timestamp': 12, 'value': None}, {'timestamp': 23, 'value': None} ] }, { 'project': 'two', 'name': 'best', 'samples': [ {'timestamp': 12, 'valu...
<p>Check <code>json_normalize</code>, <code>l</code> is your list here</p> <pre><code>from pandas.io.json import json_normalize json_normalize(l, 'samples', ['name', 'project',['value', 'timestamp']],errors='ignore').drop('value.timestamp',1) Out[195]: timestamp value project name 0 12 None one test...
python|pandas
0
10,622
68,920,063
Changing value in dataframe with the mean value based on condition
<p>I have a dictionary that contains the mean of the price of each product:</p> <p>{&quot;Apple&quot;: 4.50, &quot;Orange&quot;: 5.00, 'Banana': 2.00}</p> <p>What I would like to do is to apply these mean values to rows in my DataFrame that contain a non valid (&lt;=0) value in the &quot;Price&quot; column.</p> <div cl...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> only for filtered rows:</p> <pre><code>d = {&quot;Apple&quot;: 4.50, &quot;Orange&quot;: 5.00, 'Banana': 2.00} mask = df[&quot;Price&quot;]&lt;=0 df.loc[mask, 'Price']...
python|pandas
0
10,623
68,891,205
Iterating over rows of a df and check if any value in a row has the type "list"
<p>Consider the following dataframe with different types of elements in its columns (int and list).</p> <pre><code>&gt;&gt;&gt; df index A B C 1 0 11 [13, 16, 18] 2 1 0 nan 3 34 1 [13, 16] 4 11 nan [1...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>x = df.apply( lambda x: &quot; and &quot;.join( [ f&quot;'{i} in {tuple(v)}'&quot; if isinstance(v, list) else f&quot;'{i} == {v}'&quot; for i, v in zip(x[x.notna()].index, x[x.notna()]) ] ), axis=1, ) print(...
python|pandas|list|dataframe
1
10,624
61,150,380
Efficiently Compute Voxel Indices for a Point Cloud
<p>Suppose I have an input point cloud <code>X</code>, represented by an array of dimensions <code>N x 3</code>. Each row in this array corresponds to a single point in XYZ space, between -1 and 1. Now, let <code>k</code> be a parameter which defines the resolution of a voxel grid (e.g. <code>k</code> = 3 corresponds t...
<p>You are, in effect, comparing your point values as float against a series of other floats between -1 and 1.</p> <p>However, what you want to do is compute (once) a function that produces the value. Perform a simple computation instead of iterating.</p> <p>Ideally, that simple function would be something that <code...
python|python-3.x|numpy
2
10,625
71,685,327
is this architecture an autoencoder
<p>I want to create an autoencodre i build this architecture it works but i want to know if it is an autoencoder architecture</p> <h1>Encoder</h1> <pre><code> layer = layers.Conv2D(16, (3, 3), activation=&quot;relu&quot;, padding=&quot;same&quot;,data_format = 'channels_first')(input) layer = layers.MaxPooling2D...
<p>There are some problems in your code:</p> <ol> <li><p>You need an input layer to your model if you are using functional:</p> <p>input = layers.Input(shape=(3, 192, 192))</p> </li> <li><p>In an autoencoder, the output of your model needs to have the same dimensions as the input. However, in your model your output is ...
tensorflow|keras|conv-neural-network
0
10,626
42,411,891
How to extract bias weights in Keras sequential model?
<p>I'm running a simple feed-forward network using <em>Keras</em> . Having just one hidden layer I would like to make some inference regarding the relevance of each input to each output and I would like to extract the weights. </p> <p>This is the model: </p> <pre><code>def build_model(input_dim, output_dim): n_o...
<p><code>get_weights()</code> for a <code>Dense</code> layer returns a list of two elements, the first element contains the weights, and the second element contains the biases. So you can simply do:</p> <pre><code>weights = model.layers[0].get_weights()[0] biases = model.layers[0].get_weights()[1] </code></pre> <p>No...
python|tensorflow|neural-network|keras
39
10,627
69,952,691
Pandas to_sql to localhost table returns 'Engine' object has no attribute 'cursor'
<p>I see lots of this question is about sqlite, but mine is to MySQL.</p> <p>my entire script is like this:</p> <pre><code>df = pd.read_csv(&quot;df.csv&quot;) engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(config.user, config.passwd, ...
<p>I have solved this, i reset my Mac, then come back to my VS Code, and start the notebook again, the problem is gone.</p> <p>But before that, i tried also using command</p> <pre><code>reset </code></pre> <p>that can't do the trick. It has to be machine hard reset.</p>
mysql|pandas|dataframe|sqlalchemy|pandas-to-sql
0
10,628
69,982,741
How to write a circulant matrix in tensorflow
<p>I want to generate a circulant matrix in tensorflow without using any for loops. For example my input is <code>[1, 2, 3]</code>, and the expected output is <code>[[1,2,3],[2,3,1],[3,1,2]]</code>. I think we can use nd convolution to do it, but tensorflow doesn't have nd convolution.</p>
<p>I think the simplest solution to this problem, without using an explicit loop, is to use <a href="https://www.tensorflow.org/api_docs/python/tf/extract_volume_patches" rel="nofollow noreferrer">tf.extract_volume_patches</a>, which can be used to creating a sliding window over a tensor. You will just have to reshape ...
python|tensorflow|matrix|convolution
2
10,629
43,051,934
sending date time stamps to elasticsearch through python
<p>I have 3 of 5 columns of my data that is in pandas to_datetime format:</p> <pre><code>col1 col2 col3 col4 a 2017-01-01 21:07:57 2017-01-01 21:07:58 2017-01-01 21:07:59 misc_text_data text 2017-01-01 21:07:42 2017-01-01 21:07:48 2017-01-01 21:07:...
<p>Not sure what is the problem in your code, it is probably to do with the timestamp format.</p> <p>Anyway panda to_json with iso format selected worked for me:</p> <pre><code>import pandas as pd from elasticsearch import Elasticsearch import json es = Elasticsearch() data = ["2017-01-01 21:07:57, 2017-01-01 21:0...
python|python-3.x|pandas|elasticsearch
2
10,630
62,896,386
Convert Flatten CSV to nested JSON
<p>I want to nest JSON from flatten CSV file, how to create a parent category using all the subcategories in flatten CSV file. Please check out the format of data in given image below.<br> <a href="https://i.stack.imgur.com/OFuY6.jpg" rel="nofollow noreferrer">Image of the formats are in here</a></p> <p>Any help would ...
<p>You can read about csv module here: <a href="https://docs.python.org/3/library/csv.html" rel="nofollow noreferrer">https://docs.python.org/3/library/csv.html</a></p> <p>There is a class there called DictReader which takes a CSV file and puts it in a dictionary, and from there the way to json is easy.</p> <p>The foll...
python|pandas
0
10,631
62,815,653
Opposite of eq function python / select rows with more then two same entries in a column
<p>this question is related to this <a href="https://stackoverflow.com/questions/62079564/select-rows-with-excat-two-same-entries-in-a-column">question</a>.</p> <p>But this time I want to filter a dataframe that I keep all the rows which have more then two same entries in a column.</p> <p>For exact two columns I use: <...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ne.html" rel="nofollow noreferrer"><code>Series.ne</code></a> for not equal:</p> <pre><code>df1 = df[df['group'].map(df['group'].value_counts()).ne(2)] </code></pre> <p>Here is list of all methods:</p> <p><a href="http://pandas.pyda...
python|pandas
3
10,632
62,861,773
Can we use multiple loss functions in same layer?
<p>Can we use mulitple loss function in this architecture: I have two different type of loss functions and want to use it on last layer [Output] loss functions :</p> <ul> <li>binary_crossentropy</li> <li>custom loss function</li> </ul> <p>Can we do that? <a href="https://i.stack.imgur.com/UwIvv.png" rel="nofollow noref...
<p>yes you can... you simply have to repeat 2 times the model output in the model definition. you can also merge your loss in a different way using loss_weights params (default is [1,1] for two losses). Below an example in a dummy regression problem. <a href="https://colab.research.google.com/drive/1SVHC6RuHgNNe5Qj6IOt...
tensorflow|machine-learning|keras|deep-learning|loss-function
3
10,633
62,808,370
Update NaN values with dictionary of values nased on condition
<p>I have data frame like this:</p> <pre><code> c1 c2 0 a 12 1 b NaN 2 a 45 3 c NaN 4 c 32 5 b NaN </code></pre> <p>and I have dictionary like this</p> <pre><code>di = { 'a': 10, 'b': 20, 'c':30 } </code></pre> <p>I want to update my data frame like this</p> <pre><code> c1 c2 0 a 12 1 b...
<p>You can use apply() method to deal with this. Create a function and then apply that function to the required features.</p> <pre><code>`def deal_na(cols): x=cols[0] y=cols[1] if pd.isnull(y): return di[x] else: return y a['c2'] = a[['c1','c2']].apply(deal_na,axis=1)` </code></pre> <p>...
python|pandas|dataframe
1
10,634
54,526,851
Python BeautifulSoup - Scrape Multiple Web Pages with Iframes from Given URLs
<p>We have this code (thanks to Cody and Alex Tereshenkov):</p> <pre><code>import pandas as pd import requests from bs4 import BeautifulSoup pd.set_option('display.width', 1000) pd.set_option('display.max_columns', 50) url = "https://www.aliexpress.com/store/feedback-score/1665279.html" s = requests.Session() r = s....
<p>Since the number of urls is ~ 50, you could just read the urls into a list and then send a request to each of the urls. I have just tested these 6 urls and the solution works for them. But you may want to add some try-except for any exceptions that may occur. </p> <pre><code>import pandas as pd import requests from...
python|pandas|web-scraping|beautifulsoup
2
10,635
73,788,209
Modify data in rows and columns with conditions in pandas
<p>I want to modify a specific data points in the pandas data frame under a condition. For example in the following table, I want to divide the data by 2 in column A where only row values of column B is greater than 1.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;...
<pre><code>df.loc[df[&quot;Column B&quot;] &gt; 1,&quot;Column A&quot;] = df[&quot;Column A&quot;]/2 </code></pre> <p>Hope it Helps...</p>
python|pandas|dataframe|conditional-statements
2
10,636
71,236,426
How to plot geographic data with customized legend?
<p>Having the geographic points with values, I would like to encode the values with colormap and customize the legend position and colormap range.</p> <p>Using geopandas, I have written the following function:</p> <pre><code>def plot_continuous(df, column_values, title): fig = plt.figure() ax = fig.add_axes([0,...
<p>This gets far simpler if you use <strong>geopandas</strong> customisation of <code>plot()</code></p> <p>This is documented: <a href="https://geopandas.org/en/stable/docs/user_guide/mapping.html" rel="nofollow noreferrer">https://geopandas.org/en/stable/docs/user_guide/mapping.html</a></p> <p>Below I show MWE using y...
python|gis|geopandas|geography
1
10,637
71,157,866
Appending powers of a row at the and of the same row in numpy matrix
<p>I have a numpy matrix in. I want to append the second power, third power, ..., nth power of the row to the end of the row. For instance,</p> <pre><code>my_array = [ [1,2,3], [2,3,4], [3,4,5], ] </code></pre> <p>If n is 3, then my_array should be the following</p> <pre><code>my_array = [ [1,2,3,1,4,9,1,8,27], [2,3,4,...
<p>Here is one option using broadcasting, there is probably a smarter way to reshape:</p> <pre><code>N = 3 (my_array[...,None]**(np.arange(N)+1)).swapaxes(1,2).reshape(my_array.shape[0],-1) </code></pre> <p>or using <code>tile</code>/<code>repeat</code>:</p> <pre><code>N = 3 np.tile(my_array, N)**np.repeat(np.arange(N)...
python|numpy
1
10,638
71,309,782
DataFrame. TypeError: 'numpy.int64' inside a FOR loop in Data
<p>Goal is to create a function able to de-cumulate the column of table. For example:</p> <pre class="lang-py prettyprint-override"><code>data_matrix = {'x0': [0, 2, 0], 'x1':[2, 3, 1], 'x3':[4, 4, 1], 'x4':[6, 5, 1]} data_mtrice = pd.DataFrame(data_matrix) data_matrice = data_mtrice.T </code></pre> <p>That produce...
<p>There are tree problems with your code.</p> <p>The first is with <code>tentative = data_matrice.apply(lambda tableau: decumule(tableau))</code>, your function <code>decumule</code> expects a dataframe as input, when you call <code>apply</code> though the function is applied one row at a time so it gets only a row as...
python|pandas
2
10,639
71,339,451
Split a pandas series into columns and rows using string delimiter
<p>I need to split dataframe column into multiple columns based on string delimiters.</p> <p>Example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>AttachedData</th> <th>Attributes</th> <th>count</th> </tr> </thead> <tbody> <tr> <td>callid='16774327';length='0';vdn='MSIS'</td> <td>[{'Type...
<p>Another option is to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extract.html?highlight=extract#pandas.Series.str.extract" rel="nofollow noreferrer"><code>str.extract</code></a>:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ 'AttachedData':[ &quot...
python|pandas
0
10,640
60,720,847
Save excel formula in the DataFrame and then write it to excel
<p>There is a small data frame df. I want to write it to Excel so that column B contains formula: B=A+C</p> <pre><code>df = pd.DataFrame(np.random.randint(0,1000,size=(3,3)), columns=list('ABC')) df['B']='=RC[-1]+RC[1]' with pd.ExcelWriter(r'C:\Users\belose\Downloads\output.xlsx', engine='openpyxl', mode='w')as writer...
<p>Try this for the formula:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,1000,size=(3,3)), columns=list('ABC')) df['B'] = '=INDIRECT("R[0]C[-1]", 0)+INDIRECT("R[0]C[1]", 0)' with pd.ExcelWriter(r'output.xlsx', engine='openpyxl', mode='w')as writer: df.to_excel(writer, sheet_name='Sheet1', index=False) <...
python|pandas|openpyxl
1
10,641
72,575,812
Mulitlevel Pandas dataframe to nested json
<p>I am trying to turn a data frame into some nested json and have been struggling a bit. Here is an example I created. The use case is to split a document for each guest at a hotel chain, with the guest at the top, the hotel details under the visit data, and the daily charges under the 'measurements' info.</p> <p>The ...
<p>I would recommend a programming approach. <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">pandas.DataFrame.groupby</a> can be useful.</p> <pre class="lang-py prettyprint-override"><code>def hotel_data_to_json(df): return [ person_data_to_json...
json|python-3.x|pandas|dataframe
1
10,642
72,643,577
Tensorflow 2.9 nvidia graphics compatibility issues
<p>I am trying to enable my <code>nvidia gtx 1050 mobile</code> gpu for <code>tensorflow v2.9</code>. Here is what I have so far:</p> <p>The proper driver for my graphics card is 470.xx as per <a href="https://askubuntu.com/questions/1377521/ubuntu-20-04-wont-suspend/1412289#1412289">this question</a>. I have installed...
<p>This error seems to arise due to improper installation of Tensorflow. A quick and recommended way to get around this would be to install Tensorflow using Conda, as follows:</p> <pre><code>conda create --name tf_gpu tensorflow-gpu conda activate tf_gpu </code></pre> <p>However, the above commands would not support T...
ubuntu|jupyter-notebook|tensorflow2.0|nvidia|cudnn
0
10,643
72,658,212
How do I reformat several columns of a DataFrame into one row?
<p>This is snippet of the dataframe I am using:</p> <pre><code> type date time open close change high low 200ema 50ema 0 sixty-min 2007-06-04 09:00:00 1536.28 1534.71 -0.102 0.000 -0.259 NaN 1522.90 1 sixty-min 2007-06-04 10:00:00 1534.87 1534.79 -0.005 0.109 -0.106...
<p>You can first extract the hour as int and group by date:</p> <pre><code>df['time'] = pd.to_datetime(df['time']).dt.hour df = df.groupby('date').agg(list) </code></pre> <p>Then for each date concatenate (along column/axis1) dataframes created from each column. Finally concatenate (along rows/axis0) the dataframes for...
python|pandas|dataframe
1
10,644
59,681,904
Negative location for TFLite detection results
<p>Using custom model, I'm trying to locate some object on a bitmap but I get negative values for location box</p> <p>e.g. my bitmap size:</p> <pre><code>myBitmap.getHeight() = 129 myBitmap.getWidth() = 202 </code></pre> <p>but the results are:</p> <pre><code>item (91,4%) RectF(-0.48639297, 5.0847816, 321.28015, 19...
<p>You're not doing anything wrong, just need to find the correct coordination: imH, imW are your image's height and width</p> <pre><code>ymin = int(max(1,(RectF[0] * imH))) xmin = int(max(1,(RectF[1] * imW))) ymax = int(min(imH,(RectF[2] * imH))) xmax = int(min(imW,(RectF[3] * imW))) </code></pre>
android|tensorflow|tensorflow-lite
2
10,645
59,896,329
Python - Get individual elements of dataframe column
<p>I have a dataframe which has a column that is a list. I want to extract the individual elements in every list in the column. So given this input dataframe:</p> <pre><code> A 0 [5, 4, 3, 6] 1 [7, 8, 9, 6] </code></pre> <p>The intended output should be a list:</p> <pre><code> [5, 4, 3, 6,7, 8,...
<p>You can use list comprehension with flatten:</p> <pre><code>a = [y for x in df.A for y in x] </code></pre> <p>Or use <a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow noreferrer"><code>itertools.chain</code></a>:</p> <pre><code>from itertools import chain a = list(chain.fr...
python|pandas|dataframe
4
10,646
61,860,017
Removing empty dataframes from nested list
<p>I have a nested list of pandas DataFrames called ob1 it contains 755 elements some are populated most are not I would like to know if there is a way to removed the empty DataFrames from the list while keeping the rest Here is an example of the content of the list. </p> <pre><code>DataFrame (18, 7) EventNumber ...
<p>First of all give a concrete example of your problem. But I think <code>df.empty</code> can do the job.</p> <pre><code>df=pd.DataFrame() if df.empty: print('df is empty') </code></pre> <p>EDIT:</p> <p>IIUC, I hope this helps: create random dataframes </p> <pre><code>df1=pd.DataFrame(columns=list('ABCD') ) df...
python|pandas
2
10,647
61,876,308
Get nth row of groups and fill with 'None' if row is missing
<p>I have a df:</p> <pre><code> a b c 1 2 3 6 2 2 5 7 3 4 6 8 </code></pre> <p>I want every nth row of groupby a:</p> <pre><code>w=df.groupby('a').nth(0) #first row x=df.groupby('a').nth(1) #second row </code></pre> <p>The second group of the df has no second row, in this case I want to have 'None' va...
<p>If you are just interested in a specific <code>nth</code> but not have enough rows in some groups, you can consider to use <code>reindex</code> with <code>unique</code> value from the column a like:</p> <pre><code>print (df.groupby('a').nth(1).reindex(df['a'].unique()).reset_index()) a b c 0 2 5.0 7.0 1...
python|pandas
1
10,648
58,049,861
How to sovle >ValueError< with pandas Series and python?
<p>I'm using <strong>python</strong> (3.7.4) together with <strong>pandas</strong> (0.25.0) and want to use <code>value_counts()</code> on a Series.</p> <p>While executing the statement i get a <strong>ValueError</strong>.</p> <p>Any suggestions to sovle this error?</p> <pre><code>import pandas as pd series = pd.Ser...
<p>The error is from applying <code>.value_counts()</code> to the empty series that is created when you resample your index using the <code>Grouper</code>. </p> <p>You can see this by viewing the groups in your example:</p> <pre class="lang-py prettyprint-override"><code>for n,g in series.groupby(pd.Grouper(freq='D')...
python|python-3.x|pandas|series
3
10,649
54,964,622
Trouble writing binary numbers in a file using Pandas
<p>My code consists of removing the redundancy from the code as a form of backup. But when writing again in the file it removes the zeroes to the left of the 1. Like in the image below</p> <p><a href="https://i.stack.imgur.com/ii869.png" rel="nofollow noreferrer">https://imgur.com/a/OU07DzX</a></p> <pre><code>mydatas...
<p>The easiest solution is probably to read the data as string. Otherwise, the data is read as numerical where leading zeros are dropped. Plus the data is interpreted using decimal numeral system by default, which is not what you'd want anyway.</p> <pre><code>pd.read(csv('fieldstatebackup.binetflow', dtype=str) </code...
python|pandas|csv|binary|one-hot-encoding
0
10,650
49,515,698
Dataframe column based in columns conditions
<pre><code> a b 0 100 90 1 30 117 2 90 99 3 200 94 </code></pre> <p>I want to create a new <code>df["c"]</code> with next conditions:</p> <ul> <li><p>If <em>b</em> is into <em>(a ± 0.5a)</em> then <em>c = a</em></p></li> <li><p>If <em>b</em> is out <em>(a ± 0.5a)</em> then <em>c = b</em></p></li> ...
<p>I think need <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with conditions created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.eval.html" rel="nofollow noreferrer"><code>eval</code></a> or ...
python|pandas
2
10,651
49,440,296
Check if Pandas DF Column1 Contains (str) Column2
<p>I'm trying to create a column in a Pandas DataFrame that shows whether a (string) 'Column1' contains the string in 'Column2'. Reproduceable example below:</p> <pre><code># Have df = pd.DataFrame({'col1': ['a', 'aa', 'b', 'bb', 'c', 'cc'], 'col2': ['a', 'b', 'c', 'd', 'e', 'c']}) # Want: Series...
<p>This is one loopy way using <code>pd.DataFrame.apply</code> and a <code>lambda</code> function.</p> <pre><code>df = pd.DataFrame({'col1': ['a', 'aa', 'b', 'bb', 'c', 'cc'], 'col2': ['a', 'b', 'c', 'd', 'e', 'c']}) df['test'] = df.apply(lambda x: x['col2'] in x['col1'], axis=1) </code></pre> ...
python|pandas|string|series
3
10,652
73,243,570
How do I slice a NumPy array to get all the values of the same index together?
<p>Say I have a NumPy array like this:</p> <pre><code>item = [[0 5] [1 6] [2 7] [3 8] [4 9]] </code></pre> <p>With three sets of the item array, I now have a NumPy array arranged as such:</p> <pre><code>arr = [[[0 5] [1 6] [2 7] [3 8] [4 9]] [[0 5] [1 6] [2 7] [3 8] [4 9]] [[0 5] [1 6] [2 7] [3 8] [4 9]]] </code></pre...
<pre><code>import numpy as np item = np.array([[0, 5], [1, 6], [2, 7], [3, 8], [4, 9]]) arr = np.tile(a, (3, 1, 1)) a = arr[:, :, 0].T b = arr[:, :, 1].T &gt;&gt;&gt; a array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]) &gt;&gt;&gt; b array([[5, 5, 5], [6, 6, 6], [...
python|arrays|numpy
0
10,653
73,385,560
How to convert pandas dataframe into a transaction matrix
<p>I want to convert my pandas dataframe into a markov chain transaction matrix</p> <pre><code>import pandas as pd dict1={'state_num_x': {0: 0, 1: 1, 2: 1,3: 1,4: 2,5: 2,6: 2,7: 3,8: 3,9: 4,10: 5,11: 5, 12: 5,13: 5,14: 5,15: 5,16: 6,17: 6,18: 6,19: 7,20: 7,21: 7}, 'state_num_y': {0: 1,1: 1,2: 2,3: 5,...
<p>It looks like you want a <code>pivot_table</code>:</p> <pre><code>df.pivot_table(index='state_num_x', columns='state_num_y', values='Sum_Prob', fill_value=0) </code></pre> <p>output:</p> <pre><code>state_num_y 1 2 3 4 5 6 7 state_num_x ...
arrays|pandas|numpy|chain|markov
-1
10,654
67,377,446
How do I get text I compiled from a txt file into its corresponding row in a dataframe?
<p>Here is part of the txt file I'm working with:</p> <pre><code>&lt;PERSON ID=&quot;S1&quot; LANG=&quot;NRN&quot; ROLE=&quot;JU, Student&quot; SEX=&quot;M&quot; RESTRICT=&quot;NONE&quot; AGE=&quot;1&quot;&gt; &lt;FIRSTLANG&gt; HIN &lt;/FIRSTLANG&gt; &lt;/PERSON&gt; &lt;PERSON ID=&quot;S2&quot; LANG=&quot;NS&quot; ROLE...
<p>You were very close but this is how you would do it using regex:</p> <pre><code>xml_file = &quot;&quot;&quot;&lt;PERSON ID=&quot;S1&quot; LANG=&quot;NRN&quot; ROLE=&quot;JU, Student&quot; SEX=&quot;M&quot; RESTRICT=&quot;NONE&quot; AGE=&quot;1&quot;&gt; &lt;FIRSTLANG&gt; HIN &lt;/FIRSTLANG&gt; &lt;/PERSON&gt; &lt;PE...
python|regex|pandas
1
10,655
67,199,791
Is there any way to speed up the predicting process for tensorflow lattice?
<p>I build my own model with Keras Premade Models in tensorflow lattice using python3.7 and save the trained model. However, when I use the trained model for predicting, the speed of predicting each data point is at millisecond level, which seems very slow. Is there any way to speed up the predicting process for tfl?</...
<p>There are multiple ways to improve speed, but they may involve a tradeoff with prediction accuracy. I think the three most promising options are:</p> <ul> <li>Reduce the number of features</li> <li>Reduce the number of lattices per feature</li> <li>Use an ensemble of lattice models where every lattice model only get...
python-3.x|performance|machine-learning|predict|tensorflow2.x
0
10,656
65,211,016
Is there any Softmax implementation with sections along the dim (blocky Softmax) in PyTorch?
<p>For example, given logits, dim, and boundary,</p> <pre><code>boundary = torch.tensor([[0, 3, 4, 8, 0] [1, 3, 5, 7, 9]] # representing sections look like: # [[00012222_] # [_00112233] # in shape: (2, 9) # (sections cannot be sliced) logits = torch.rand(2, 9, 100) result = blocky_sof...
<p>I realize that <code>scatter_add</code> and <code>gather</code> perfectly solve the problem.</p>
pytorch|customization|softmax
0
10,657
65,085,780
What is difference between "Keras backend + Tensorflow" and "Keras from Tensorflow" using CPU(in Tensorflow 2.x)
<p>I want to limit CPU cores and threads. So I found three ways to limit these.</p> <p><strong>1) &quot;Keras backend + Tensorflow&quot;</strong></p> <pre><code>from keras import backend as K import tensorflow as tf config = tf.ConfigProto(intra_op_parallelism_threads=2, \ inter_op_parallelism...
<p>Not exactly, it's not as simple as that. As per official documentation -</p> <p><strong>intra_op_parallelism_threads</strong> - Certain operations like matrix multiplication and reductions can utilize parallel threads for speedups. A value of 0 means the system picks an appropriate number. <a href="https://www.tenso...
python|keras|tensorflow2
1
10,658
65,182,467
Stripping DataFrame column from text to make integer
<p>I couldn't find an easy way to do this and none of the complex ways worked. Can you help?</p> <p>I have a dataframe resulting from a web-scrape. In there I have a data['Milage'] column that has the following result: '80,000 miles'. Obviously that's a string, so I'm looking for a way to erase all content that isnt nu...
<p>After some test problem was <code>data</code> is dictionary, you need processing <code>df</code> for <code>DataFrame</code>.</p> <p>I think you need remove non numeric values and convert to integers:</p> <pre><code>df['Milage'] = df['Milage'].str.replace('\D','').astype(int) print(df['Milage']) 0 70000 1 6...
python|pandas|selenium
2
10,659
65,338,087
Apply style to specific columns in dataframe
<p>I want to format only specific columns of the dataframe. Right now styling gets applied to every column, this can be done using subset parameter in <code>df.style.background_gradient()</code> as per documentation. I tried to do <code>subset = df.iloc[:, 3:]</code> as I want to apply styling to column 3 onwards but ...
<p>To remove 'Unnamed 0' you can use :</p> <pre><code>df.set_index('Ticker') del df['Unnamed: 0'] </code></pre> <p>To use subset :</p> <pre><code>select_col = df.columns[3:] s = df.style.background_gradient(cmap=cm, axis = 1,subset=select_col) </code></pre>
python|pandas
2
10,660
50,021,368
Addition-merging dataframes
<p>What is the best way to add the contents of two dataframes, which have mostly equivalent indices:</p> <p>df1: </p> <pre><code> A B C A 0 3 1 B 3 0 2 C 1 2 0 </code></pre> <p>df2:</p> <pre><code> A B C D A 0 1 1 0 B 1 0 3 2 C 1 3 0 0 D 0 ...
<p>You can also <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> both the dataframes since concatenation (by default) happens by index.</p> <pre><code># sample dataframe df1 = pd.DataFrame({'a': [1,2,3], 'b':[2,3,4]}, index=['a','c','...
python|pandas|dataframe|merge
1
10,661
49,883,175
Python SettingWithCopyWarning, but I'm trying to set the value using .ix
<p>I have a pandas dataframe in python and I'm trying to modify a specific value in a particular row. I found a solution to this problem <a href="https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe-using-index">Set value for particular cell in pandas DataFrame using index</a>...
<p>Note that <a href="https://pandas.pydata.org/pandas-docs/stable/whatsnew.html#deprecate-ix" rel="nofollow noreferrer"><code>.ix</code> is deprecated</a> because it indexes by position <em>or</em> by label, depending on the data type of the index. Use <code>.loc</code> or <code>.iloc</code> instead.</p> <p>This <cod...
pandas|dataframe
1
10,662
63,821,290
ValueError: Value tf.Tensor.. shape=(), dtype=float64) has insufficient rank for batching.?
<p>I'm trying to take a dataframe and convert them to tensors to train a model in keras.</p> <p>I think it's being triggered when I am converting my Y label to a tensor:</p> <pre><code> X_train = df_train1.drop(variableToPredict, axis=1) y_train = df_train1[variableToPredict].copy() X_train=tf.data.Dataset.from_te...
<p>Either use:</p> <pre><code>y = tf.data.Dataset.from_tensors(dict(y_train)) </code></pre> <p>Or this:</p> <pre><code>y = tf.data.Dataset.from_tensor_slices(y_train) </code></pre> <p>Or just use double brackets so your dataframe remains a dataframe, then you won't need to change anything:</p> <pre><code>y_train = df[[...
python|tensorflow|keras
1
10,663
63,016,076
Adding columns in panda with and without filter
<p>I'm new to pandas. I'm trying to add columns to my <code>df</code>. There are multiple columns in the <code>csv</code>. The names of the columns include, &quot;Name&quot;, &quot;Date&quot;, ..., &quot;Problem&quot;, &quot;Problem.1&quot;, &quot;Problem.2&quot; etc. The user is going to be downloading the files at d...
<p>Use this:</p> <pre class="lang-py prettyprint-override"><code>df [ ['Name', 'Date'] + [col for col in df.columns if 'Problem' in col] ] </code></pre>
pandas|filtering
1
10,664
67,961,701
Tensorflow to categorical problem, i want map my masks for segmentation?
<p>I have a problem with labels for segmentation, the label can have this value: 0, 200, 210, 220, 230, 240. I use this code:</p> <pre><code>mask = tf.keras.utils.to_categorical(y, 241) </code></pre> <p>The code work, but i want map the mask with only 6 classes, is this possible?</p> <pre><code>mask = tf.keras.utils.to...
<p>On solution is that first replace your list with ordered indexes and then make it categorical. Because <code>to_categorical</code> expects indices for your list.</p> <p>Here is the example code if you have limited categories:</p> <pre><code>y = [0, 200,210,0,240,230,200,0,210,220,240,0] replacements = { 0: 0, ...
python|tensorflow|keras
0
10,665
67,807,132
Best Deep-DQN implementation that works with (state,action) pairs
<p>I'm moderately new to RL(Reinforcement learning) and trying to solve a problem by using a deep Q learning agent (trying a bunch of algorithms) and I don't want to implement my own agent (I would probably do a worse job than anyone writing an RL library).</p> <p>My problem is that the way I'm able to view my state sp...
<p>There is some reward &quot;function&quot; <code>R(s,a)</code> (or perhaps <code>R(s')</code> where <code>s'</code> is determined by the state-action pair) that gives the reward necessary for training a deep Q learner in this method. The reason why there aren't really out-of -box solutions is that the reward function...
python|deep-learning|pytorch|reinforcement-learning
0
10,666
61,297,650
I have to split the following date in separate columns using python
<p>2019-05-03 13:08:33.000 America/Los_Angeles</p> <p>I am having trouble splitting the above mentioned timestamp in different columns.</p>
<p>One way of doing would be to make the date a string and split by the whitespace</p> <p>Data</p> <pre><code>df=pd.DataFrame({'date':['2019-05-03 13:08:33.000 America/Los_Angeles']}) df </code></pre> <p>Split</p> <pre><code> df2=df.date.str.split(('\s+'), expand=True) df2.columns=['DATE','Time','Region'] df2 </co...
python|pandas|datetime-format|python-datetime
0
10,667
61,318,948
Change all characters in a string to unicode applied to whole column pandas
<p>I have a string:</p> <pre><code>fruit1 = 'apple' </code></pre> <p>and to change it to unicode code point:</p> <pre><code>fruit 1 = int(''.join(str(ord(char)) for char in fruit1)) print(fruit1) 97112112108101 </code></pre> <p>Is it possible apply the same concept over a whole column without running a for loop on...
<p>Unfortunately <code>map</code> and <code>apply</code> are loops under the hood, but working here:</p> <pre><code>df['new'] = df['Fruit'].map(lambda x: int(''.join(str(ord(char)) for char in x))) #alternative #df['new'] = df['Fruit'].apply(lambda x: int(''.join(str(ord(char)) for char in x))) print (df) Fruit ...
python|string|pandas|dataframe|unicode
1
10,668
61,472,179
How to create a skewed column in pandas dataframe?
<p>I would like to create a new column in a dataframe with a skewed distribution. I would like it to have 64000 data points, with a minimum of 0 (no negative values), and some sort of skewed shape where most people are closer to 0 and then it levels off to the right with higher values.</p> <p>I have tried this but I a...
<p>You can use an <a href="https://en.wikipedia.org/wiki/Exponential_distribution" rel="nofollow noreferrer">exponential</a> or <a href="https://en.wikipedia.org/wiki/Poisson_distribution" rel="nofollow noreferrer">poisson</a> distribution depending on what you are after exactly. <strong>The exponential distribution wi...
python|pandas|numpy|statistics|distribution
3
10,669
68,733,960
Show the group name for boxplots in pandas
<p>I have the following dataset:</p> <pre><code>df_plots = pd.DataFrame({'Group':['A','A','A','A','B','B','B','B','C','C','C','C','D','D','D','D'],\ 'Value':[1,1.2,1.4,1.3,16,18,16,19,43,47,42,55,0.2,0.4,0.3,0.6], 'Hit':[1,1,1,1,2,2,2,2,2,3,4,4,5,5,1,0]}) </code></pre> ...
<p>Given your code snippet, here's what I would do:</p> <pre><code>fig, axs = plt.subplots(2,2,figsize=(8,6), sharey=False) axs = axs.flatten() for i, g in enumerate(df_plots[['Group','Value']].groupby('Group')): g[1].boxplot(ax=axs[i]) # g is a Tuple[&lt;Group Name:str&gt;, &lt;Group Data:pd.DataFrame&gt;] ...
python|pandas
2
10,670
68,464,059
A tested means of combining Excel (*.xls) files into a single (*.xlsx) file
<p>I'd been having a bit of trouble finding meaningful info on how to open multiple Excel (<em>.xls) files in Python and combine them into a single dataframe and then save them out again as a single Excel (</em>.xlsx) file.</p> <p>I found a way that works for me, and I thought i'd share with all the helpful people on S...
<p>The solution I found is as follows:</p> <p>Be sure to install all appropriate packages in Anaconda for library imports to work</p> <pre><code>import numpy as np import pandas as pd import os import xlrd import glob2 </code></pre> <p>*** is the directory where your files are located</p> <pre><code>os.chdir(&quot;/***...
python|excel|pandas|glob
0
10,671
68,751,933
Mixing .loc and .iloc slicing to select first n rows of index sublevels
<p><a href="https://i.stack.imgur.com/ToTra.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ToTra.png" alt="enter image description here" /></a></p> <p>I have a multilevel index. I'd like to select the first two rows of each style (example highlighted in yellow). Sort of an <code>.iloc[:, :2]</code...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.head.html" rel="nofollow noreferrer"><code>.GroupBy.head</code></a>:</p> <pre><code>df.groupby(level='style').head(2) </code></pre> <p>Here is another way:</p> <pre><code>df.groupby(level='style').apply(lambda...
pandas
1
10,672
68,514,513
Remove repeating data in pandas
<p>I have 4 columns of data <code>A</code>, <code>B</code>, <code>C</code>, <code>D</code>. Some data are repeating such as row 1: <code>P2 XX P6 XX</code> is repeating in row 5: <code>P6 XX P2 XX</code>. Can anyone help me to remove the repeating units from Pandas dataframe?</p> <pre><code>A B C D P2 XX ...
<p>Assuming it's okay to swap columns <code>A</code> and <code>C</code>, you can use <code>np.minimum</code> and <code>np.maximum</code> to swap the two columns and then drop duplicates:</p> <pre><code>import numpy as np df.A, df.C = np.minimum(df.A, df.C), np.maximum(df.A, df.C) df.drop_duplicates() A B C D...
python|pandas|dataframe
1
10,673
53,147,002
pandas summation per year
<p>python3, pandas version 0.23.4</p> <p>Let's say we have a pandas DataFrame as follows</p> <pre><code>np.random.seed(45) df = pd.DataFrame({'A': np.random.randint(0, 10, 20)}, index = pd.to_datetime(dd).sort_values(ascending=False)) </code></pre> <p>Now, I would like to total the data in column A with respect to e...
<p>You can using <code>transform</code></p> <pre><code>gf_perYear = gf.groupby(by= gf.index.year) gf['new'] = gf_perYear.transform('sum') </code></pre>
python-3.x|pandas
1
10,674
52,942,860
Accumulate partial reductions into array in numpy
<h2>Problem description</h2> <p>How do I accumulate into <code>a</code> the values in <code>c</code> using <code>b</code> to index into <code>a</code>? That is, given</p> <pre><code>import numpy as np a = np.zeros(3) b = np.array([2, 1, 0, 1]) c = np.arange(0.1, 0.5, 0.1) print ('a=%s b=%s c=%s'.replace(' ', '\n') % ...
<p><code>np.bincount</code> does exactly what you want:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; b = [2, 1, 0, 1] &gt;&gt;&gt; c = np.arange(0.1, 0.5, 0.1) &gt;&gt;&gt; c array([0.1, 0.2, 0.3, 0.4]) &gt;&gt;&gt; np.bincount(b, c) array([0.3, 0.6, 0.1]) </code></pre> <p>There is also <...
python|numpy
1
10,675
53,182,452
Python Create Bar Chart Comparing 2 sets of data
<p>I have a notebook with 2* bar charts, one is winter data &amp; one is summer data. I have counted the total of all the crimes and plotted them in a bar chart, using code:</p> <pre><code>ax = summer["crime_type"].value_counts().plot(kind='bar') plt.show() </code></pre> <p>Which shows a graph like:</p> <p><a href="...
<p>The following generates dummies of your data and does the grouped bar chart you wanted:</p> <pre><code>import random import pandas as pd import numpy as np import matplotlib.pyplot as plt s = "Crime Type Summer|Crime Type Winter".split("|") # Generate dummy data into a dataframe j = {x: [random.choice(["ASB", "Vi...
python|pandas|bar-chart
10
10,676
65,499,407
Calculating number of intersecting columns for each row with each other row from boolean numpy array
<p>I have written a short program to extract association rules from a database. However, now I want to compare the extracted rules and calculate the number of intersecting attributes from each rule with each other. The rule-conditions are represented in a boolean numpy array, where each row can be considered as the ant...
<p>You can achieve this with simple linear algebra.</p> <p>Imagine that every <code>True</code> is <code>1</code> and every <code>False</code> is <code>0</code></p> <p>So multiply this integers matrix <code>a</code> by its transpose <code>a.T</code> will give you what you want.</p> <p>Of course the <em>numpy</em> is ve...
python|arrays|numpy|vectorization
2
10,677
63,725,876
How to calculate cumulative sum over days in a month? using pandas for time series analysis
<p>I Have following dataframe df:</p> <p><a href="https://i.stack.imgur.com/5LCEJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5LCEJ.png" alt="enter image description here" /></a></p> <p>I want a cumulative sum of <code>Volume</code> by <code>PROD Cluster</code> which start doing fresh sum after e...
<p>Use <code>groupby</code> and <code>cumsum</code>:</p> <pre><code># sample data d1 = pd.DataFrame({'PROD Cluster': ['A']*3, 'Date': pd.date_range('2020-01-01', '2020-01-03'), 'Volume': [1,2,3]}) d2 = pd.DataFrame({'PROD Cluster': ['A']*3, 'Date': pd.date_range(...
python|pandas|dataframe|time-series
2
10,678
63,508,796
tf.compat.v1.train.exponential_decay: global step = 0
<p>To find out how to implement both a ANN with exponential decay as well as a with a constant learning rate I looked it up here: <a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/exponential_decay" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/exponential_...
<p>I hope this example clears your doubt.</p> <pre><code>epochs = 10 global_step = tf.Variable(0, trainable=False, dtype= tf.int32) starter_learning_rate = 1.0 for epoch in range(epochs): print(&quot;Starting Epoch {}/{}&quot;.format(epoch+1,epochs)) for step, (x_batch_train, y_batch_train) in enumerate(train_...
python|tensorflow|deep-learning|learning-rate
0
10,679
63,699,379
Creating meshgrids with combinations of rows between two arrays
<p>Given the two 2d arrays <code>x</code> and <code>y</code> of the same shape but with different values.</p> <p>I want to create an array of <code>meshgrids</code> between each row in x and y like so:</p> <pre><code>import numpy as np x = np. array([[ 0. , 2.5, 5. ], [ 0. , 5. , 10. ]]) y = np....
<p>Here's one way -</p> <pre><code>m1,n1 = x.shape m2,n2 = y.shape out = np.empty((m1,n2,n1,2), dtype=np.result_type(x.dtype, y.dtype)) out[:,:,:,0] = y[:,:,None] out[:,:,:,1] = x[:,None,:] meshgrids = out.reshape(m1,-1,2) </code></pre>
python|numpy
1
10,680
53,439,070
Understanding Keras LSTM NN input & output for binary classification
<p>I am trying to create a simple LSTM network that would - based on the last 16 time frames - provide some output. Let's say I have a dataset with 112000 rows (measurements) and 7 columns (6 features + class). What I understand is that I have to "pack" the dataset into X number of 16 elements long batches. With 112000...
<p>You are close with the last comments of the question. Since it's a binary classification problem, you should have <code>1</code> output per input, so you need to get rid of the <code>16</code> in you <code>y</code>s and replace it for a <code>1</code>.</p> <p>Besides, you need to be able to divide the train set by ...
python|tensorflow|keras|lstm
1
10,681
71,915,671
comparing numpy arrays such that they equal each other if they both fall within the same range of values
<p>Suppose that I have a 3d numpy array where at each canvas[row, col], there is another numpy array in the format of [R, G, B, A].I want to check if the numpy array at canvas[row, col] is equal to another numpy array [0, 0, 0, 240~255], where the last element is a range of values that will be accepted as &quot;equal&q...
<p>You can compare slices:</p> <pre class="lang-py prettyprint-override"><code>( (canvas[row, col, :3] == 0).all() # checking that color is [0, 0, 0] and (canvas[row, col, 3] &gt;= 240) # checking that alpha &gt;= 240 ) </code></pre> <p>Also, if you need to check this on a lot of values, you can optimize i...
python|arrays|numpy
0
10,682
71,906,218
`join` method importing `other` dataframe values as `NaN`
<p><em>Editing this to reflect addition work:</em></p> <p><strong>Situation</strong></p> <p>I have 2 pandas dataframes of Twitter search tweets API data in which I have a common data key, <code>author_id</code>.</p> <p>I'm using the <code>join</code> method.</p> <p>Code is:</p> <p><code>dfTW08 = dfTW07.join(dfTW04uf, o...
<p>Couldn't figure out the <code>NaN</code> issue using <code>join</code>, but was able to <code>merge</code> the databases with this:</p> <p><code>callingdf.merge(otherdf, on='author_id', how='left', indicator=True)</code></p> <p>Then did <code>sort_values</code> and <code>drop_duplicates</code> to get the final list ...
python|pandas|dataframe|join
0
10,683
55,333,191
Does get_dummies() function change the dtype of a column?
<p>I have a data frame column <code>['Cause']</code> with dtype as <code>object</code> having the below values :</p> <p><code>Cause Water Fire Earthquake Flood</code></p> <p>Now when I am using get_dummies() function on this column, I got 4 additional column as below with binary values:</p> <p><code>Water | Fire | E...
<p>Yes, by default if you don't mention dtype it will be converted to uint8. </p> <p>You can do something like this</p> <pre><code>pd.get_dummies(..., dtype=int64) </code></pre>
python|pandas
3
10,684
56,518,581
How to convert batches of images with [H,W,C] shape into a dictionary of size [N,H,W,C]?
<p>Preprocessed image shape and dtype</p> <pre><code>(240, 320, 3) &lt;dtype: 'float32'&gt; </code></pre> <p>image_list = np.concatenate(image_list, axis=0) It doesent work.</p> <pre><code>ValueError: zero-dimensional arrays cannot be concatenated </code></pre> <p>my aforementioned code as follows</p> <pre class="...
<p>You need to create the extra dimension first.</p> <pre class="lang-py prettyprint-override"><code>image_list = np.zeros([240, 320, 3]) print(image_list.shape) # (240, 320, 3) image_list = np.expand_dims(image_list, axis=0) print(image_list.shape) # (1, 240, 320, 3) image_list = np.concatenate([image_list, image_l...
tensorflow|tensorflow-datasets
0
10,685
66,969,259
CNN in pytorch "Expected 4-dimensional input for 4-dimensional weight [32, 1, 5, 5], but got 3-dimensional input of size [16, 64, 64] instead"
<p>I am new to pytorch. I am trying to use chinese mnist dataset to train the neural network that shows in below code. Is that a problem of the neural network input or something else goes wrong in my code. I have tried many ways to fix it but instead it shows me other errors</p> <pre><code>train_df = chin_mnist_df.grou...
<p>Your training images are greyscale images. That is, they only have one channel (as opposed to the three RGB color channels in color images).<br /> It seems like your <code>Dataset</code> (implicitly) <a href="https://pytorch.org/docs/stable/generated/torch.squeeze.html#torch.squeeze" rel="nofollow noreferrer">&quot;...
python|pytorch|conv-neural-network
0
10,686
68,110,416
Check for existence of data from two Dataframe's columns in List
<p>I'm searching for <code>difference</code> between columns in <code>DataFrame</code> and a data in <code>List</code>.</p> <p>I'm doing it this way:</p> <pre class="lang-py prettyprint-override"><code> # pickled_data =&gt; list of dics pickled_names = [d['company'] for d in pickled_data] # get values from dictionary ...
<p>You can form a set of tuples from your <code>pickled_data</code> for faster lookup later, then using a list comprehension over <code>company_name</code> and <code>place</code> columns of the frame, we get a boolean list of whether they are in the frame or not. Then we use this to index into the frame:</p> <pre><code...
python|pandas|dataframe
1
10,687
68,120,496
how to put numbers into categories in python
<p>i am new to the community and recently starting my project using 'python'</p> <p>i have looked up the internet, but couldn't find quite the answer i want</p> <pre><code>duration_ms 3203 4583 7789 189654 512300 6523 42358 ... </code></pre> <p>the list ranging from 5k~550k, and spread randomly i tried to put these int...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html" rel="nofollow noreferrer"><code>Series.between()</code></a> to simplify the syntax:</p> <pre><code>time_dura= { '550k~600k':df[df['duration_ms'].between(550000, 60000-1)], '500k~550k':df[df['duration_m...
python|pandas
1
10,688
59,446,681
How to classify image using custom model in tensorflow.js?
<p>The script that builds and trains the model looks like this:</p> <pre><code>const model = tf.sequential(); model.add(tf.layers.conv2d({ inputShape: [160, 200, 3], filters: 32, kernelSize: 3, activation: 'relu', })); model.add(tf.layers.flatten()); model.add(tf.layers.dense({units: labels.length, activati...
<p>After training your model, to classify a new image, the <code>predict</code> method will be used. It will return the probability of each label given your input image(s).</p> <pre><code>output = model.predict(image) // It can be a tensor of one image or a batch of many // output is a tensor that contain the probabi...
javascript|node.js|tensorflow|tensorflow.js
1
10,689
45,726,522
What's the best way to tell the missing row in pandas DataFrame?
<p>I'm new to Python - pandas, currently trying to use it to check whether the data in DataFrame is continuous. For example:</p> <pre><code> thread sequence start end 14 1 114 1647143 1672244 15 1 115 1672244 1689707 16 1 116 1689707 1713090 17 1 ...
<p>A faster method using <code>RangeIndex</code>:</p> <pre><code>seq = pd.RangeIndex(df.sequence.min(), df.sequence.max()) seq[~seq.isin(df.sequence)].values # array([117]) </code></pre>
python|pandas
7
10,690
50,734,036
merging pandas DataFrames after resampling
<p>I have a DataFramewith with a datetime index.</p> <pre><code>df1=pd.DataFrame(index=pd.date_range('20100201', periods=24, freq='8h3min'), data=np.random.rand(24),columns=['Rubbish']) df1.index=df1.index.to_datetime() </code></pre> <p>I want to resample this DataFrame, as in :</p> <pre><code>df1=df...
<p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a>:</p> <pre><code>print(pd.merge_asof(df1,df2,right_index=True,left_index=True)) Rubbish_x Rubbish_y 2010-02-01 0.446505 NaN 2010-02-08 0....
python|pandas|datetime|dataframe|merge
3
10,691
51,070,904
Matplotlib 3D plot colors from different classes from Dataframe
<p>I am trying to plot a 3D plot in Matplotlib from a Pointcloud data which is essentially extracted from two different classes. </p> <p>However, I cannot differentiate the classes into different colors. My code is below.</p> <pre><code>x=pd.DataFrame(np.array(x).reshape(-1,1)) y=pd.DataFrame( np.array(y).reshape( -1...
<p>I found the answer myself- Mapped the Dataframe to the arguments of Color using below <code>col=new_data['target'].map({'Variable1':'r','Variable2 ':'g','Variable3':'b'})</code></p>
python|pandas|matplotlib|data-visualization
3
10,692
66,529,238
How to add date automatically based on the other column in python?
<p>I am pretty new to Datetime and pandas. So, I created a code that generates new data(extra rows) to a column, whereas my index is the date. Now depending on the new rows which got created in a column, the date also should get automatically added depending on the above. Is there any way to do it?</p> <p>My input:</p>...
<p>You can create <code>DatetimeIndex</code> by maximal datetime from original <code>DatetimeIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>:</p> <pre><code>max1 = df.index.max() df1.index = pd.to_datetime...
python|pandas|datetime|indexing|dataset
1
10,693
66,563,463
How to treat '<attribute 'dtype' of 'numpy.generic' objects>' error?
<p>After installing pypfopt and u-numpy, <code>dataframe.info()</code> command shows this error.</p> <pre class="lang-none prettyprint-override"><code>TypeError: Cannot interpret '&lt;attribute 'dtype' of 'numpy.generic' objects&gt;' as a data type </code></pre>
<p>I happened to mix my versions and I encountered the problem today. I managed to fix it. Both codes in jupyter gave me an error: TypeError: Cannot interpret '&lt;attribute 'dtype' of 'numpy.generic' objects&gt;' as a data type</p> <pre><code>df.info() df.categorical_column_name.value_counts().plot.bar() </code></pre...
python-3.x|pandas|dataframe|typeerror
14
10,694
57,437,923
How to remove duplicate values in dataframe while preserving the rest of the row in Pandas?
<p>I am working on some gross profit reports in a jupyter notebook. I have exported the data out of our CRM as a csv and am using Pandas to with with the data. Some of the data is being duplicated in a couple of columns. I need to remove those duplicate values in those columns, but preserve the rest of the row. </p...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/version/0.24.2/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>DataFrame.duplicated</code></a> to check which rows contain duplicates based on <code>PO Number</code> &amp; <code>PO Subtotal</code>. Then conditionally replace the value...
python-3.x|pandas|duplicates|jupyter-notebook
0
10,695
57,392,480
Extract bucket size from binned column using Pandas' cut function
<p>I would like to be able to read from a column which is transformed from a continuous/integer to a categorical column using Pandas' cut what the bin size is. Why? Because I have a case where I can't access the code which cuts the column but I can access the resulting column itself and I want to log the binsize that i...
<p>One way can be using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ediff1d.html" rel="nofollow noreferrer">np.ediff1d()</a> - </p> <pre><code>out, bins = pd.cut(np.array([1, 7, 5, 4, 6, 3]), bins=np.arange(0, 10, 2), retbins=True) bins[1] - bins[0] # np.ediff1d(bins)[0] OR np.diff(bins)[0] </c...
python|pandas|extract|cut|binning
0
10,696
57,685,558
Merge dataframe rows when values are NaN
<p>I want to flatten a dataframe as in the example below.</p> <p>I have the next dataframe:</p> <pre><code> file name format location 0 movie1.mp4 NaN NaN 1 NaN NaN D:/mymovies 2 NaN mp4 NaN </code></pre> <p>and I want to convert it to:</p> <pre><code> file name format ...
<p>I believe you can use forward filling for first column, if first non missing value is first value of group and then aggregate with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.first.html" rel="nofollow noreferrer"><code>GroupBy.first</code></a> for first non missing ...
python-3.x|pandas
1
10,697
57,506,792
pandas random shuffling dataframe with constraints
<p>I have a dataframe that I need to randomise in a very specific way with a particular rule, and I'm a bit lost. A simplified version is here:</p> <pre><code>idx type time 1 a 1 2 a 1 3 a 1 4 b 2 5 b 2 6 b 2 7 a 3 8 a 3 9 a 3 10 b 4 11 b 4 12 b 4 13 a 5 14 a 5 15 ...
<p>See if this works.</p> <pre><code>import pandas as pd import numpy as np n = [['a',1],['a',1],['a',1], ['b',2],['b',2],['b',2], ['a',3],['a',3],['a',3]] df = pd.DataFrame(n) df.columns = ['type','time'] print(df) order = np.unique(np.array(df['time'])) print("Before Shuffling",order) np.random.shuffle...
python-3.x|pandas
0
10,698
70,705,403
Pandas read nested JSON to data frame
<p>Below is a snippet of my JSON file. There is 1 play, multiple playId's, and with numerous timestamps. I am trying to get a data frame of: 'timeStamp', 'playID', 'x', 'y', 'typ', 'id'. The majority of those fields would come from the mergedPositionalData key.</p> <p>Currently I am stuck here:</p> <pre><code>mergedPos...
<p>You can select the value of <code>mergedPositionalData</code> first, then make use of <code>meta</code> argument of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer">pandas.json_normalize()</a>.</p> <pre class="lang-py prettyprint-override"><cod...
python|pandas
0
10,699
51,357,485
Combine multi columns to one column Pandas
<p>Hi I have the following dataframe</p> <pre><code> z a b c a 1 NaN NaN ss NaN 2 NaN cc 3 NaN NaN aa NaN 4 NaN ww NaN 5 NaN ss NaN NaN 6 aa NaN NaN 7 g NaN NaN 8 j 9 NaN NaN </code></pre> <p>I would like to create a new column d to do something like this</p> <pre><c...
<p>In fact, it's not nessary to use <code>fillna</code>, <code>sum</code> can transform the <code>NAN</code> elements to zeros automatically. </p> <p>I'm a python newcomer as well,and I suggest maybe you should read the pandas cookbook first.</p> <p>The code is:</p> <pre><code>df['Total']=df[['a','b','c']].sum(axis=...
python|python-3.x|pandas|dataframe
1