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 |
|---|---|---|---|---|---|---|
372,100 | 52,168,725 | pandas groupby include a column in final result | <pre><code> cast year revenue title
id
135397 Chris Pratt 2015 1.392446e+09 Jurassic World
135397 Bryce Dallas Howard 2015 1.392446e+09 Jurassic World
135397 Irrfan Khan 2015 1.392446e+09 Jurassic World
135397 Nick Robinson 2015 ... | <p>You can split your logic into 2 steps. First sum by cast and year using <code>GroupBy</code> + <code>sum</code>. Then find the maximum revenue by year using <code>GroupBy</code> + <code>idxmax</code>:</p>
<pre><code># sum by cast and year
df_summed = df.groupby(['cast', 'year'])['revenue'].sum().reset_index()
# ma... | python|pandas|dataframe|pandas-groupby | 1 |
372,101 | 52,435,537 | Select rows from a DataFrame based on a values in another dataframe and updating one of the column with values according to the second DataFrame | <p>I have two Dataframes df and df1.</p>
<p>Main DataFrame is as follows:<br>
DF:</p>
<pre><code> start end price
0 A Z 1
1 B Y 2
2 C X 3
3 A Z 4
4 D W 5
</code></pre>
<p>Second DataFrame:<br>
DF1:</p>
<pre><code>start end price
0 A Z 100
1 B Y 200
</code></p... | <p>Using <code>update</code> </p>
<pre><code>df=df.set_index(['start','end'])
df.update(df1.set_index(['start','end']))
df.reset_index()
Out[99]:
start end price
0 A Z 100.0
1 B Y 200.0
2 C X 3.0
3 A Z 100.0
4 D W 5.0
</code></pre> | python|pandas|dataframe|rows|updating | 2 |
372,102 | 52,082,853 | Convert a column to header row | <p>So I've got this dataframe/csv file:</p>
<pre><code>,stock,adj_close
0,GERN,3.59
1,GERN,3.3
2,GERN,3.34
...
4530,CMCSA,35.78
4531,CMCSA,35.46
4532,CMCSA,35.08
...
9060,AAPL,189.63
9061,AAPL,189.25
9062,AAPL,190.31
</code></pre>
<p>With a bunch more stocks and datapoints. There's an equal amount of rows per stock, ... | <p>Use <code>set_index</code> and <code>unstack</code></p>
<pre><code>In [37]: (df.set_index(['stock', df.groupby('stock').cumcount()])['adj_close']
.unstack('stock'))
Out[37]:
stock AAPL CMCSA GERN
0 189.63 35.78 3.59
1 189.25 35.46 3.30
2 190.31 35.08 3.34
</code></pre>
<p>Or, ... | python|pandas | 2 |
372,103 | 52,312,799 | Segmentation fault (core dumped) and how to setup new python environments | <p>How to manage the new environment when I run many projects? For instance, I was usually got the errors during training where I updated the libraries such as matplotlib and skimage and my system oupute the error like : Segmentation fault (core dumped). </p>
<p>It's probably to handle new environments to new project ... | <p>Have you tried using <a href="https://conda.io/docs/user-guide/getting-started.html#" rel="nofollow noreferrer">Anaconda</a> for <a href="https://conda.io/docs/user-guide/getting-started.html#managing-packages" rel="nofollow noreferrer">managing packages & versions</a>?</p> | python-3.x|tensorflow|gpu|pytorch|ubuntu-17.10 | 0 |
372,104 | 52,169,051 | Pandas Dataframe row selection combined condition index- and column values | <p>I want to select rows from a dataframe based on values in the index combined with values in a specific column:</p>
<pre><code>df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [0, 20, 30], [40, 20, 30]],
index=[4, 5, 6, 7], columns=['A', 'B', 'C'])
A B C
4 0 2 3
5 0 4 1
6 0 20 30... | <p>You can use multiple conditions in your <code>loc</code> statement:</p>
<pre><code>df.loc[(df.index < 6) & (df.A == 0), 'C'] = 99
</code></pre> | python|pandas | 27 |
372,105 | 52,261,733 | Tensorflow: multiply matrix columns by elements of vector and get matrix back | <p>Here is what I would like to accomplish in Tensorflow. </p>
<p>I have 2x2 matrix (trainable)</p>
<pre><code>x_1 x_2
x_3 x_4
</code></pre>
<p>and I have input vector </p>
<pre><code>a
b
</code></pre>
<p>I would like to multiply each column of matrix by element of vector and get back the following matrix</p>
<pr... | <p>Thanks to <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer">broadcasting</a>, you should be fine using the regular multiplication operator:</p>
<pre><code>import tensorflow as tf
x = tf.constant([[3, 5], [7, 11]], dtype=tf.int32)
a = tf.constant([4, 8], dtype=tf.int... | tensorflow|vector|matrix-multiplication | 1 |
372,106 | 52,008,259 | How to replace the values in a dataframe column based on another dataframe condition | <p>I have two dataframe, XXX and override.</p>
<pre><code>XXX = pd.DataFrame({'A':['One', 'Two', 'Three'], 'B': [6,4,3], 'C': ['red','green','blue']})
override = pd.DataFrame({'A':['One','Two'], 'C': ['apple','pie']})
</code></pre>
<p>I'm looking for the best way to replace the values of column C of the XXX datafr... | <p>You could use <code>map</code> and <code>fillna</code> over series mapper</p>
<pre><code>In [1077]: XXX.A.map(override.set_index('A')['C']).fillna(XXX.C)
Out[1077]:
0 apple
1 pie
2 blue
Name: A, dtype: object
</code></pre>
<hr>
<pre><code>In [1078]: XXX.C = XXX.A.map(override.set_index('A')['C']).fill... | python-3.x|pandas|dataframe|replace | 3 |
372,107 | 52,271,413 | can not find a version when I install tensorflow | <p>this is my symptom:</p>
<pre><code>[shankai@shankai ~]$ pip3 install tensorflow
Collecting tensorflow
Could not find a version that satisfies the requirement tensorflow (from versions: )
No matching distribution found for tensorflow
</code></pre>
<p>my python : 3.7 64bit
os : ArchLinux</p> | <p>As listed <a href="https://pypi.org/project/tensorflow/" rel="nofollow noreferrer">at the pypi tensorflow page</a> tensorflow is currently just available for Python 3.6, not for Python 3.7.</p>
<p>Either change your setup to Python 3.6 or build Tensorflow from source.</p> | python|linux|tensorflow | 1 |
372,108 | 52,244,366 | Combine dataframes result with a DatetimeIndex index | <p>i have a pandas dataframe with random values at every minute.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.random.randint(0,30,size=20), index=pd.date_range("20180101", periods=20, freq='T'))
df
0
2018-01-01 00:00:00 21
2018-01-01 00:01:00 21
2018-01-01 0... | <p>You can <code>pd.concat</code> both dataframes and <code>fillforward</code></p>
<pre><code>df3=pd.concat([df,df2],axis=1).ffill()
</code></pre> | python|python-3.x|pandas | 2 |
372,109 | 52,068,525 | Generating User / Item interactions | <p>I have a pandas dataframe (Interactions dataframe) with columns as User, Item, Rating.</p>
<pre><code>Ratings ItemID UserID
1 1172952 A74
1 1178735 176
4 341785 70C
3 136771 67E
2 1178883 383
</code></pre>
<p>Let's say I have two more dataframes with 200 users and 100... | <p>Your explanation of the problem is a little sloppy, but I have a feeling that you need this:</p>
<pre><code>interactions.set_index(['ItemID','UserID'])\
.unstack().fillna(0).astype(int).stack()\
.reset_index()
</code></pre>
<p>This code creates a rectangular table of users and items, fills ... | python|pandas|numpy|machine-learning|recommendation-engine | 2 |
372,110 | 52,301,851 | Python Pandas Dataframe - Fill Empty Columns with calculation that uses row value and column name | <p>I have a dataframe df, which can be created with this:</p>
<pre><code>import pandas as pd
import datetime
#create the dates to make into columns
datestart=datetime.date(2018,1,1)
dateend=datetime.date(2018,1,5)
newcols=pd.date_range(datestart,dateend).date
#create the test data
d={'name':['a','b','c','d'],'earlydat... | <p>IIUC:</p>
<pre><code>i = pd.to_datetime(df.earlydate.values).values
j = pd.to_datetime(df.columns[2:]).values
df.iloc[:, 2:] = (j - i[:, None]).astype('timedelta64[D]').astype(int)
df
earlydate name 2018-01-01 2018-01-02 2018-01-03 2018-01-04 2018-01-05
0 2018-01-01 a 0 1 2 ... | python|pandas|dataframe | 5 |
372,111 | 52,129,993 | Pandas stack date matirx value | <p>My data format is like:</p>
<pre><code>year month 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 .. 31
1998 1 2.5 1 - - -2.5 - - - - - - - - - - - - - - 1.5
1998 2 2.5 1 - - -4.5 - - - - - - - - - - - - - - 1.5
1998 3 2.5 1 - - -3.5 - - - - - - - - - - - - - - 1.5
1998 4 2.5 1 - - -8.5 - - - - - - - - - - - - - - 1.5
1998 5 2... | <p>Pretty much what you're asking is to "<em>un-pivot</em>", your DataFrame. The general way to approach these types of problems are using some version of <code>melt</code>, <code>stack</code>, or <code>unstack</code>. Here is an approach using <code>stack</code>.</p>
<p><strong><em>Setup</em></strong></p>
<pre><co... | python|python-3.x|pandas|datetime | 1 |
372,112 | 52,113,568 | Generate New DataFrame without NaN Values | <p>I've the following Dataframe:</p>
<pre><code> a b c d e
0 NaN 2.0 NaN 4.0 5.0
1 NaN 2.0 3.0 NaN 5.0
2 1.0 NaN 3.0 4.0 NaN
3 1.0 2.0 NaN 4.0 NaN
4 NaN 2.0 NaN 4.0 5.0
</code></pre>
<p>What I try to to is to generate a new Dataframe without the NaN values.
There are always th... | <p>Using array indexing:</p>
<pre><code>pd.DataFrame(df.values[df.notnull().values].reshape(df.shape[0],3),
columns=list('xyz'),dtype=int)
x y z
0 2 4 5
1 2 3 5
2 1 3 4
3 1 2 4
4 2 4 5
</code></pre>
<hr>
<p>If the <code>dataframe</code> has more inconsistance value... | python|pandas|dataframe | 3 |
372,113 | 52,218,277 | Why column of int and NaN has float type | <p>I have this dataframe:</p>
<pre><code>data = {'one': pd.Series([1,2,3], index=['a','c','d'], dtype='i4')
'two': pd.Series([4,7,2,2], index=['a','b','c','d'])}
pd.DataFrame(data)
</code></pre>
<p>I am getting following output</p>
<pre><code> one two
a 1.0 4
b NaN 7
c 2.0 2
d 3.0 2
</code></p... | <p>In Pandas / NumPy, <code>NaN</code> is a <code>float</code>:</p>
<pre><code>assert type(np.nan) == float
</code></pre>
<p>Pandas sets the dtype for a series to accommodate all values, as <a href="https://pandas.pydata.org/pandas-docs/stable/basics.html#attributes-and-the-raw-ndarray-s" rel="nofollow noreferrer">ex... | python|pandas|numpy|series | 2 |
372,114 | 52,072,533 | Tensorflow Estimator: Cache bottlenecks | <p>When following the tensorflow image classification tutorial, at first it caches the bottleneck of each image:</p>
<p><a href="https://github.com/tensorflow/hub/blob/a5105da43ae81267398bf0a2d12560edbced2715/examples/image_retraining/retrain.py#L433" rel="noreferrer">def: cache_bottlenecks())</a></p>
<p>I have rewri... | <p>TF cannot work as you code. You should:</p>
<ol>
<li>Export bottleneck to file from the raw net. </li>
<li>Use bottleneck result as input, use another net to train your data.</li>
</ol> | python|tensorflow|machine-learning|classification | 1 |
372,115 | 52,314,391 | Sort array values for a particular slice from 3d DataArray | <p>Summary: Given a 3D array, how I can I slice at two particular co-ordinates and then sort on the VALUES of the 3rd dimension, retaining index information</p>
<p>Preamble:</p>
<p>I am trying to compare the cost of shopping baskets for customers buying a combination of apples and bananas. I know our competitors unit... | <p>I think I found my answer.</p>
<p>1) Make my selection 1 dimensional</p>
<p><code>selection = selection[0]</code></p>
<p>2) Reindex by the argsorted variable </p>
<p><code>selection = selection[selection.variable.argsort()]</code></p>
<p>3) Now selection should be sorted and you have the indicies to look at the... | python|numpy|python-xarray | 0 |
372,116 | 52,015,282 | pandas get_level_values behaives unexpectedly | <p>I have a multi-index in my dataframe like this:</p>
<pre><code>x = pd.MultiIndex(levels=[['a', 'b', 'c'], ['2014.12.31', 'd', 'e', '2015.12.31']],
labels=[[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]],
names=['proj', 0])
x.get_level_values(0)
x.get_level_values(1)
</code></pre>
<p>I e... | <p>You have two index levels, and you can get them either by name or by integer index. The index level at integer index <code>0</code> has name <code>proj</code>, a string. The index level at integer index <code>1</code> has name <code>0</code>, an integer.</p>
<p>When you call <code>get_level_values(level)</code>, <c... | python|pandas | 3 |
372,117 | 52,005,576 | Seaborn boxplot horizontal line annotation | <p>I'm wanting to add a <strong>horizontal line</strong> i.e. a 'target' line to some plots: stripplots, boxplots, and violin plots, to show ideal values data (or ideally a range).</p>
<p>This R example (<a href="https://stackoverflow.com/questions/34366196/add-multiple-horizontal-lines-in-a-boxplot">Add multiple hori... | <p>Let's say you wan't to plot a horizontal line at height <code>y</code> and from <code>x1</code> to <code>x2</code> where <code>x1</code> and <code>x2</code> are your actual x-data values. The following are just three out of possibly several ways you can do that:</p>
<p>First:</p>
<pre><code>ax.hlines(y, x1, x2)
</... | python|pandas|seaborn|boxplot | 5 |
372,118 | 52,037,095 | Pandas DataFrame: how to get column mean valuebut taking into account only the rows that have lower index than the one I want to get the mean | <p>The problem I have is I want to predict the victory of a team over another one, to do that I want to have for each match the winrate of each team before the date of the match.</p>
<p>However using a <code>df.groupBy("teamName").agg({"isVictory":"mean"})</code> provides me the global wirate of the team that is not u... | <p>There must be a better way, but this one works:</p>
<pre><code>df = pd.DataFrame({'team': [' a', ' a', ' a', ' a', 'b', 'b', 'c'],
'IndexMatch': [1, 2, 3, 4, 5, 6, 7],
'isVictoryTeam': [1, 0, 1, 1, 0, 1, 1]})
df['winrate'] = df.groupby('team')['isVictoryTeam'].expanding().mean(... | python|pandas|group-by|aggregate|mean | 1 |
372,119 | 52,217,149 | Is Bigtable or Datastore more suited to storing and using financial data for online applications? | <p>I'm creating a stock analysis web application. I want to store financial data for multiple stocks. Then I want to use a stock screener on them. This screener involves retrieving multiple stocks from the backend and performing a technical indicator test on them. Stocks that pass the indicator test will be returned to... | <p><em>Disclosure: I am a product manager for Cloud Bigtable.</em></p>
<p>If you plan to have a large amount of financial data, covering the entire stock market, Cloud Bigtable is a good choice: it scales to terabytes and petabytes, and you can get low-latency responses to your requests, it is already in use in financ... | python|pandas|numpy|google-cloud-datastore|google-cloud-bigtable | 4 |
372,120 | 52,091,535 | Combining two conditions in numpy (column-wise) | <p>I have got the following table<br/></p>
<pre><code> A B C <br/>
1 5 True 10<br/>
2 6 False 2<br/>
3 1 True 5<br/>
</code></pre>
<p>Now I would like to create a new column <code>D</code> which is set to TRUE when column <code>A</code> is larger than 5 and <code>B</code... | <p>I think you need:</p>
<pre><code>import numpy as np
df['D'] = (df['A']>5) & (df['B']==True)
print(df)
</code></pre>
<p>Output:</p>
<pre><code> A B C D
0 5 True 10 False
1 6 False 2 False
2 1 True 5 False
</code></pre>
<p><strong>Additional</strong></p>
<p>If your de... | python|pandas|numpy | 2 |
372,121 | 52,010,073 | Setting up a CNN network with multi-label classification | <p>I have a set of 100x100 images, and an output array corresponding to the size of the input (i.e. length of 10000), where each element can be an 1 or 0.</p>
<p>I am trying to write a python program using TensorFlow/Keras to train a CNN on this data, however, I am not sure how to setup the layers to handle it, or the... | <blockquote>
<p>I am not sure how to setup the layers to handle it.</p>
</blockquote>
<p>Your code is one way to handle that but as you might read in literature, is not the best one. State-of-the-art models usually use 2D <code>Convolution Neural Networks</code>. E.g:</p>
<pre><code> img_input = keras.layers.Inp... | python|tensorflow|keras | 2 |
372,122 | 52,427,638 | Why is dtype being changed in simple pandas array function from int64 to float64? | <p>I have a pandas data frame. If I check the data-type of the date column by writing </p>
<pre class="lang-python prettyprint-override"><code>analytic_events.date.dtype
</code></pre>
<p>I get the result </p>
<p><code>dtype('int64')</code></p>
<p>And yet if I run this simple array function (which returns the value ... | <p>By shifting, you've introduced a null spot at the end of the series. That get's filled in with <code>np.nan</code>. Unfortunately, <code>np.int64</code> doesn't have an equivalent null object as does <code>np.float64</code>.</p>
<h3>Alternative 1</h3>
<p>Fill with zero</p>
<pre><code>analytic_event.date.shift(-... | pandas | 2 |
372,123 | 52,109,956 | how to apply window function in python? | <p>I have below sample dataframe as :- i.e. id, name across different year and quater with different value</p>
<pre><code>id name year quater value
1 bn 2017 2
1 bn 2017 3 4.5
1 bn 2017 4
2 an 2018 1 2.3
2 an 2018 2 3.3
2 an 2018 3 4.5
</code></pre>
<p>I have to identify if the n... | <p>You can use <code>duplicated</code> with a subset of id, name and year, then invert the result to identify the first occurrence..., eg:</p>
<pre><code>df['status'] = (~df.duplicated(subset=['id', 'name', 'year'])).astype(int)
</code></pre>
<p>Gives you:</p>
<pre><code> id name year quater value status
0 1... | pandas|window | 1 |
372,124 | 52,349,507 | How do I find: Is the first non-NaN value in each column the maximum for that column in a DataFrame? | <p>For example:</p>
<pre><code> 0 1
0 87.0 NaN
1 NaN 99.0
2 NaN NaN
3 NaN NaN
4 NaN 66.0
5 NaN NaN
6 NaN 77.0
7 NaN NaN
8 NaN NaN
9 88.0 NaN
</code></pre>
<p>My expected output is: <code>[False, True]</code> since 87 is the first !NaN value but not the maximum in column <co... | <h1><strong>Option a)</strong>: Just do <code>groupby</code> with <code>first</code></h1>
<p>(May not be 100% <a href="https://github.com/pandas-dev/pandas/issues/8427" rel="nofollow noreferrer">reliable</a> )</p>
<pre><code>df.groupby([1]*len(df)).first()==df.max()
Out[89]:
0 1
1 False True
</code></pr... | python|pandas|max|nan | 6 |
372,125 | 52,195,449 | Dictionary Comprehension to Create New Columns in Stored DataFrames | <p>I have a dictionary with values that are Pandas DataFrames. I would like to create new columns in each of the DataFrames. I could easily use a for loop, but I'd like a more pythonic way of doing it. Dictionary comprehensions seem like an ideal way to do it. How would this be done using dictionary comprehension?</p>
... | <p>You could make a small helper function that is called within the dictionary comprehension:</p>
<pre><code>def add_shifted_col(df):
df['shifted'] = df['Value'].shift(2)
return df
{k: add_shifted_col(v) for k, v in d1.items()}
</code></pre>
<p>EDIT: The dictionary comprehension creates a new dictionary. To ... | python|pandas|for-loop|dataframe|dictionary-comprehension | 2 |
372,126 | 52,096,324 | Remove unnamed and the serial number | <p>i cant seems to remove the unnamed and also the serial number from the csv file. i've look online it says using index_col = 0. but still not working.</p>
<p>Is there any other way doing it?<br>
<br>
Code is :<br>
<code> brics = pd.read_csv('brics.csv', index_col = 0) <br/></p>
<p>and the csv output is :<br/></p>
... | <p>What you call a "serial number" is the index of your dataframe (dataframe is your object type - pandas.DataFrame) so you cannot remove it.
Read more about removing the index in that SO Post:
<a href="https://stackoverflow.com/questions/20107570/removing-index-column-in-pandas">Removing index column in pandas</a></p>... | python|pandas|dataframe | 0 |
372,127 | 52,357,918 | Select subset of dataframe from intersection of two sets | <p>I've got two sets of column headers from a DataFrame. One set is a subset of the other one.</p>
<pre><code>import pandas as pd
d = {'feature1':[1,2,3], 'feature2':[3,4,5], 'feature3':[6,7,8]}
df = pd.DataFrame(data=d)
</code></pre>
<p>now I got two sets:</p>
<pre><code>set_1 = {'feature1','feature2','feature3'}
s... | <p>Sets are not hashable, so you need to convert them to a list, for example.</p>
<p>Then you can select the dataframe like this</p>
<pre><code>df[list(set_1)]
</code></pre>
<p>which returns</p>
<pre><code> feature1 feature3 feature2
0 1 6 3
1 2 7 4
2 3 8 5
</code></pre>
<p>or </p>
<pre... | python|python-3.x|pandas|set | 0 |
372,128 | 52,121,785 | How to replace NaN values where the other columns meet a certain criteria? | <p>I am working on the titanic datset from Kaggle and am trying to replace the NaN values in one column based on information from the other columns.</p>
<p>In my specific example I am trying to replace the unknown age of male, 1st class passengers with the average age of male, 1st class passengers.</p>
<p>How do I do... | <blockquote>
<p>I am trying to replace the unknown age of male, 1st class passengers
with the average age of male, 1st class passengers.</p>
</blockquote>
<p>You can split the problem into 2 steps. First calculate the average age of male, 1st class passengers:</p>
<pre><code>mask = (df['Pclass'] == 1) & (df['... | python|pandas|kaggle | 5 |
372,129 | 52,402,473 | Loop a Groupby to a Figure, then Subplot by Groupby | <p>Hi I wanna subplot a dataframe groupby. But before that I also want to loop from a major groupby. Take this for example:</p>
<pre><code>Year State Person Value
2011 California A 12879
2011 California B 10572
2011 California C 8645
2011 California D 9573
2011 Florida A ... | <pre><code>byState=df.groupby('State')
for name, df in byState:
byPerson = df.groupby('Person')
fig, axs = plt.subplots(figsize=(len(byPerson)*2,4), nrows=1, ncols=len(byPerson))
fig.suptitle(name)
subplot_targets = zip(byPerson.groups.keys(), axs.flatten())
for key, ax in subplot_targets:
a... | python|pandas|matplotlib | 2 |
372,130 | 52,014,258 | Slope or Trend calculation for series or each vector (multiple columns) | <p>We have multiple time series datasets. Some are by Month, Date and Year. </p>
<p>Here our challenge is scanning the dataset quick and tell the insights to our management instead of creating a dashboard and check by click-click. </p>
<p>Seems like Trend and Slope is interchangeable and experts are computing differe... | <p>One way is to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html" rel="nofollow noreferrer">numpy.polyfit</a> with <code>deg=1</code>, which gives you both <strong>a slope</strong> and <strong>an intercept</strong> in this order. Just take the <strong>first one (slope)</strong> by u... | python|pandas|scikit-learn | 2 |
372,131 | 52,188,764 | Sort rows of a Pandas DataFrame based on aggregated count and get one row randomly | <p>I have a Pandas DataFrame with columns like this:</p>
<p><code>col1 col2 col3 col4 col5</code></p>
<p><code>a a1 foo1 foo2 foo3</code></p>
<p><code>b b1 foo4 foo5 foo6</code></p>
<p><code>c c1 foo7 foo8 foo9</code></p>
<p><code>a ... | <p>Here is how you could do this:</p>
<p>1) Create a helper series using <code>Series.value_counts</code> to get the order</p>
<p>2) Index your original df with this helper series and drop duplicate <code>col1</code> values.</p>
<pre><code>s = df.col1.value_counts()
df.set_index('col1').loc[s.index].reset_index().dr... | python|pandas|dataframe|pandas-groupby | 3 |
372,132 | 52,236,463 | How to create dummy records based on sample from dataframe? | <p>I have a 40 record df with roughly 100 columns. </p>
<p>example: </p>
<p>df</p>
<pre><code>id email phone first_name ......
1 a@a.com 123 adam
2 b@b.com 456 bob
</code></pre>
<p>Is there any way I can take a sample of each column and have python develop sample data based on t... | <p>The Python <code>faker</code> library seems to be well received for the type of thing you are doing.</p>
<p>More information can be found here:
<a href="https://github.com/joke2k/faker" rel="nofollow noreferrer">github.com/joke2k/faker</a></p> | python|python-3.x|pandas | 1 |
372,133 | 52,229,954 | Getting column value based on other multiple conditions | <p>I have a dataframe:</p>
<pre><code> cid si
A 1
A 0
A 1
A 0
A 1
A 0
A 0
A 0
A 0
A 0
A 0
A 0
A 0
A 0
B 1
B 0
B 0
B 0
B 0
B 0
B 0
</code></pre>
<p>I need to have another column with named ide which should add the same value until next 1 in si is encountered and value in ci... | <p>First, define a mapping dictionary that maps 1...n with your desired filler values; here is a small example:</p>
<pre><code>dct = {1: 'aa', 2: 'bb', 3: 'cc'}
</code></pre>
<p>Then use <strong><code>groupby</code></strong>, <strong><code>cumsum</code></strong> and <strong><code>map</code></strong>:</p>
<pre><code>... | python|pandas | 1 |
372,134 | 52,335,967 | Is there a GUI to see contents of .npy file? | <p>I am working with Python 2.</p>
<p>I have saved a <code>dict</code> of <code>arrays</code> to a <code>.npy</code> file on my computer. If I open it as a text file, a just see a mess of ASCII characters, as one would expect since I am not <em>just</em> saving arrays.</p>
<p>I can see its contents by <code>np.load</... | <p>I think this tool can help you do what you need. It can help you edit the contents of .npy files like spreadsheets. It also has options to visualize .npy files as 2D grayscale images and 3D point clouds:</p>
<p><a href="https://github.com/csmailis/NPYViewer" rel="noreferrer">https://github.com/csmailis/NPYViewer</a>... | python|numpy|save | 5 |
372,135 | 52,374,062 | Changing the np array does not change the Torch Tensor automatically? | <p>I was going through the basic tutorials of PyTorch and came across conversion between NumPy arrays and Torch tensors. The documentation says:</p>
<blockquote>
<p>The Torch Tensor and NumPy array will share their underlying memory locations, and changing one will change the other.</p>
</blockquote>
<p>But, this d... | <p>Any time you write a <code>=</code> sign in Python you are creating a new object.</p>
<p>So the right-hand side of your expression in the <em>second case</em> uses the original a and then evaluates to a new object i.e. <code>a + 1</code>, which replaces this original a. b still points to the memory location of the ... | python|numpy|pytorch|torch|tensor | 6 |
372,136 | 52,233,046 | Parsing a JSON string enclosed with quotation marks from a CSV using Pandas | <p>Similar to <a href="https://stackoverflow.com/questions/20680272/parsing-a-json-string-which-was-loaded-from-a-csv-using-pandas/20683341">this question</a>, but my CSV has a slightly different format. Here is an example: </p>
<pre><code>id,employee,details,createdAt
1,John,"{"Country":"USA","Salary":5000,"Review... | <p>I have reproduced your file
With</p>
<pre><code> df = pd.read_csv('e1.csv', index_col=None )
print (df)
</code></pre>
<p>Output</p>
<pre><code> id emp details createdat
0 1 john "{"Country":"USA","Salary":5000,"Review":null}" "2018-09-01"
1 2 s... | python|json|pandas | 0 |
372,137 | 60,428,921 | Convert str dates to MongoDB date objects via Pymongo | <p>I am using this method to insert rows of a CSV file into MongoDB </p>
<pre class="lang-py prettyprint-override"><code>def insertData(self, path=None):
df = pd.read_csv(path)
data = df.to_dict('records')
self.collection.insert_many(data, ordered=False)
</code></pre>
<p>One of the columns if <code>df</co... | <p>Adding the line: </p>
<pre class="lang-py prettyprint-override"><code>df['Dates'] = pd.to_datetime(df['Dates'], format='%d/%m/%Y')
</code></pre>
<p>Seems to do the trick, will keep the question open for any alternatives :) </p> | python|python-3.x|pandas|mongodb | 0 |
372,138 | 60,736,743 | selecting images as per specific index values in numpy array | <p>I have an array containing images of data as follows.</p>
<pre><code>print(np.shape(input_data_transformed))
</code></pre>
<blockquote>
<p>(120, 120, 1, 589)</p>
</blockquote>
<p>Here <code>input_data_transformed</code> is NumPy array having 589 images stored in it. Each image is <code>120x120</code> in size wi... | <p>Seems like your dimensions are in the wrong order. You could <code>transpose</code> and then just index on the first axis:</p>
<pre><code>input_data_transformed.transpose(3,2,0,1)[index_array]
</code></pre>
<hr>
<p>Checking with an example:</p>
<pre><code>a = np.random.rand(120, 120, 1, 589)
index_array=np.array... | python|arrays|numpy|image-processing | 1 |
372,139 | 60,661,022 | How do I customize the dimensions for plot | <p>I have added exact numbers to my barplot and now it won't fit the space. How can I fix this?
PROBLEM:</p>
<p><a href="https://i.stack.imgur.com/lZg1k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lZg1k.png" alt="enter image description here"></a></p>
<p>Code:</p>
<pre><code> ax = df.plot.b... | <p>A hack for this is to manually set the limits:</p>
<pre><code>...
ax.invert_yaxis()
ax.set_xlim(0, 800)
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/I4rgw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I4rgw.png" alt="enter image description here"></a></p> | python|pandas|matplotlib | 2 |
372,140 | 60,713,811 | Count the values for each aggregated data time | <p>Im trying to aggregate datetime by hours and count the values. </p>
<p>Here is sample dataframe :</p>
<pre><code> date_time
1/1/10 18:28:54 +0100 #format %d/%b/%Y %H:%M:%S %z
1/1/10 18:29:12 +0100
1/1/10 19:27:50 +0100
1/2/10 20:25:06 +0100
</code></pre>
<p>I need this:</p>
<pre><code>date_time count
1/1/10 ... | <p>We can try:</p>
<pre><code>new_df = (df.assign(date_time = df['date_time'].astype(str).str[:9])
.groupby('date_time').size().reset_index(name='count'))
print(new_df)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> date_time count
0 1/1/10 18 2
1 1/1/10 19 1
2 1/2/10 20 1
... | python-3.x|pandas|datetime | 0 |
372,141 | 60,692,752 | Converting a Dataframe to Dictionary | <p>I have a Dataframe in CSV format as shown in the picture.</p>
<p><a href="https://i.stack.imgur.com/iHPW9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iHPW9.png" alt="enter image description here"></a></p>
<p>I want to convert it into a dictionary such that rows are key and values are also co... | <p>First dont use <code>dict</code> for variable name, because builten, python code word.</p>
<p>Create <code>Series</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_dict.html" rel="nofollow noreferrer"><code>Series.to_dict</code></a>:</p>
<pre><code>match_pairs ... | python|pandas|dataframe|dictionary | 2 |
372,142 | 60,372,196 | Import several sheets from the same excel into one dataframe in pandas | <p>I have <strong>one</strong> excel file with several identical structured sheets on it (same headers and number of columns) (sheetsname: 01,02,...,12).</p>
<p>How can I get this into one dataframe?</p>
<p>Right now I would load it all seperate with:</p>
<pre><code>df1 = pd.read_excel('path.xls', sheet_name='01')
d... | <p>read the file as:</p>
<pre><code>collection = pd.read_excel('path.xls', sheet_name=None)
combined = pd.concat([value.assign(sheet_source=key)
for key,value in collection.items()],
ignore_index=True)
</code></pre>
<p>sheet_name = None ensures all the sheets are read in.<... | python|excel|pandas | 3 |
372,143 | 60,720,664 | Vectorized dot product in pandas? | <p>I have two dataframes, df1 is indexed by date and contains some numeric values val1, val2 for products/entries A,B,...:</p>
<pre><code>Date entry val1 val2
2017-04-12 A 1 10
2017-04-12 B 2 10
2017-04-12 C 3 10
2017-04-13 A 1 20
2017-04-13 B 2 20
2017-04... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mul.html" rel="nofollow noreferrer"><code>DataFrame.mul</code></a> with <code>MultiIndex in df1</code> with transpose <code>df2</code>, then <code>sum</code> per rows and convert <code>MultiIndex Series</code> by <a href="http://... | python|pandas|dataframe|matrix-multiplication | 3 |
372,144 | 60,575,828 | More Pythonic way to build random clusters in Python | <p>I would like to create a function which will create a uniform distribution random cluster centered around a set of co-ordinates and with a specified radius, I have done this with the below:</p>
<pre><code>import numpy as np
# create cluster builder
def cluster(center, radius=10, n=50):
xx = np.random.uniform(c... | <p><a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.uniform.html" rel="nofollow noreferrer"><code>np.random.uniform</code></a> also accepts <code>low</code> and <code>high</code> as arrays/lists. Hence, we can simply do -</p>
<pre><code>c = np.asarray(center)
xx,yy,zz = np.random.unifo... | python|arrays|numpy | 4 |
372,145 | 60,689,872 | How to apply a function to a pandas dataframe column containing strings? | <p>I open a CSV file which has a country column.</p>
<p>I want to create a new column which has that countries ISO3 Code.</p>
<p>I can do this by installing </p>
<pre><code>import country_converter as coco
</code></pre>
<p>It works in the following way:</p>
<pre><code>coco.convert('Afghanistan')
</code></pre>
<p>... | <p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for apply function per groups by <code>Country</code>, idea is run function only once per group for improve speed:</p>
<pre><code>df... | python-3.x|pandas|dataframe | 0 |
372,146 | 60,488,863 | Understanding pandas.Series.str.replace behavior when I try to pass pat as a list? | <p>The signature of the subject method is <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace(self, pat, repl, n=-1, case=None, flags=0, regex=True)</code></a> where:</p>
<blockquote>
<p>pat:str or compiled regex</p>
<p>String can be a... | <p>You didn't state the version, but I confirm in pandas 1.3 it throws an error if you try to pass <code>pat</code> as a list:</p>
<pre><code>pd.Series(['a','b',5,np.nan]).str.replace(['a'],'999')
TypeError: unhashable type: 'list'
</code></pre>
<p>Beyond that, the place to file a bug/enhance request on pandas is <a h... | python|pandas | 0 |
372,147 | 60,425,287 | Extra tree classifier missing argument y | <p>So I was trying to implement Extra Tree Classifier in order to find the parameters importance in my data base, I wrote this simple code but for some reason I keep getting thiss Error.</p>
<p>My Code:</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from ... | <p>Usually, for fit function, we need to have both attributes(X) and labels(Y) and you need to use <code>extra_tree_forest.fit(X, Y)</code> to train this classifier.
I recommend you split labels and attributes and import them as two separate lists when you import
<code>Final After Simple Filtering.csv</code>.</p> | python|pandas|numpy|dataframe|scikit-learn | 2 |
372,148 | 60,589,633 | Why is my beautifulSoup code coming up with an empty data frame? | <p>I'm trying to scrape a table on a wikipedia page, and I can't get my BeautifulSoup code to work - it keeps coming up as an empty data frame. Any advice?</p>
<pre><code>import requests
import pandas as pd
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537... | <p>You are looking at the wrong table. Change this line:</p>
<pre><code>table = soup.find_all('table')[1]
</code></pre>
<p>to this:</p>
<pre><code>table = soup.find('table')
</code></pre> | python|pandas|beautifulsoup | 0 |
372,149 | 60,428,707 | maximum recursion depth exceeded when summarizing a categorical variable | <p>When trying to get the counts for each level of a pandas series category I get a 'maximum recursion depth exceeded' error </p>
<p>A code example that produce the error is as follows:</p>
<pre><code>vs = pd.Series([0,0,0,1,1,1,1,1]).astype('category')
tn = pd.Series.value_counts(vs)
print(tn[0])
print(tn[1])
</code... | <p>Use:</p>
<pre><code>vs = pd.Series([0,0,0,1,1,1,1,1]).astype('category')
tn = vs.value_counts()
print(tn)
1 5
0 3
dtype: int64
print(tn[pd.Categorical(0)])
1 5
dtype: int64
print(tn[pd.Categorical(1)])
0 3
dtype: int64
</code></pre>
<p>For select by positions use <a href="http://pandas.pydata.org/pan... | python|pandas|recursion|categorical-data|depth | 0 |
372,150 | 60,516,366 | Looping and concatenating in Keras Sequential API | <p>Lets say I have a model defined like this:</p>
<pre><code>from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import (BatchNormalization, concatenate,
Conv2D, Conv2DTranspose, DepthwiseConv2D,
Dropout, Input, Ma... | <p>I was able to get the functional version working by storing the downblocks in a dictionary that I reference later during concatenation. See below:</p>
<pre><code>class configurable_model():
def __init__(self, csize, channels, start_neurons, depth):
self.csize = csize
self.channels = channels
... | python|tensorflow|keras | 0 |
372,151 | 60,687,700 | How to randomly shuffle a populaiton by preserving all properites except one? | <p>A spherical region of space is filled with a specific distribution of smaller, different size spheres. Each sphere is associated with some physical properties: position, radius, mass, velocity, and ID all represented as 1d or 3d <code>numpy</code> arrays. I would like to shuffle this population of spheres in a total... | <p>You can implement a Knuth shuffle (<a href="https://en.wikipedia.org/wiki/Random_permutation" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Random_permutation</a>), its quite straight-forward.</p>
<p>You can adapt the implementation algorithm to only swap your desired properties.</p> | python-3.x|numpy|random|shuffle | 1 |
372,152 | 60,626,361 | How can I solve error of ": Incompatible shapes" in tensorflow CNN? | <p>I am beginner in Tensorflow and I try to create a CNN to classify images,this is my code for training model:</p>
<pre><code>import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Dropout,Activation,Flatten,Conv2D,MaxPooling2D
import pickle
from tensorflow.k... | <p>The problem might be that, you have not used the Flatten() between the Conv and the Dense layers. Dense layers cannot handle the direct output of the Conv layers, so they need to be flattened.</p>
<p>Example:</p>
<pre><code>model=Sequential()
model.add(Conv2D(64,(3,3),input_shape=X.shape[1:]))
model.add(Activation... | python|image|tensorflow|conv-neural-network | 0 |
372,153 | 60,552,424 | Normalize pandas dataframe column by the max observed to date | <p>I have a pandas dataframe with time index and want to normalize every row of a column by the maximum value observed to that date and time.</p>
<pre><code># an example input df
rng = pd.date_range('2020-01-01', periods=8)
a_lst = [2, 4, 3, 8, 2, 4, 10, 2]
df = pd.DataFrame({'date': rng, 'A': a_lst})
df.set_index('da... | <p>you are looking at <code>cummax</code>:</p>
<pre><code>df['A_normalized'] = df['A']/df['A'].cummax()
</code></pre>
<p>Output:</p>
<pre><code> A A_normalized
date
2020-01-01 2 1.00
2020-01-02 4 1.00
2020-01-03 3 0.75
2020-01-04 8 1.00... | python|pandas|dataframe|date|normalization | 2 |
372,154 | 60,684,938 | Remove whitespace from list of strings in a pandas series | <p>I have a dataframe in which one columns values are lists of strings.</p>
<p>I want to remove the leading and trailing white space from each of the elements in the lists.</p>
<p>I am trying this:</p>
<pre><code>interests_no_nulls = fcc['JobRoleInterest'].dropna()
splitted_interests = interests_no_nulls.str.split('... | <p>Use <code>list comprehension</code> for <code>strip</code> in lists:</p>
<pre><code>fcc = pd.DataFrame({'JobRoleInterest':['aa,ss','dd , ff','k ,dd', 'j, gg']})
interests_no_nulls = fcc['JobRoleInterest'].dropna()
splitted_interests = interests_no_nulls.str.split(',')
print (splitted_interests.apply(lambda x: [y.st... | python-3.x|pandas | 2 |
372,155 | 60,751,580 | Masking Using Pixel Statistics | <p>I'm trying to mask bad pixels in a dataset taken from a detector. In my attempt to come up with a general way to do this so I can run the same code across different images, I tried a few different methods, but none of them ended up working. I'm pretty new with coding and data analysis in Python, so I could use a han... | <p>Here is an approach that will be sligthly faster on larger images:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
# generate dummy image
a = np.random.randint(1,5, (5,5))
# generate dummy outliers
a[4,4] = 20
a[2,3] = -6
# initialise mask
mask = np.ones_like(a)
# subtract mean and normalise to... | python|numpy|image-processing|data-analysis|masking | 1 |
372,156 | 60,610,280 | BertForSequenceClassification vs. BertForMultipleChoice for sentence multi-class classification | <p>I'm working on a text classification problem (e.g. sentiment analysis), where I need to classify a text string into one of five classes.</p>
<p>I just started using the <a href="https://huggingface.co/transformers/index.html" rel="noreferrer">Huggingface Transformer</a> package and BERT with PyTorch. What I need is ... | <p>The answer to this lies in the (admittedly very brief) description of what the tasks are about:</p>
<blockquote>
<p>[<code>BertForMultipleChoice</code>] [...], e.g. for RocStories/SWAG tasks.</p>
</blockquote>
<p>When looking at the <a href="https://arxiv.org/pdf/1808.05326.pdf" rel="noreferrer">paper for SWAG</... | python|machine-learning|pytorch|bert-language-model|huggingface-transformers | 13 |
372,157 | 60,742,332 | Getting time slots from Datetime column in a dataframe | <p>I have a dataframe which reads like this:</p>
<pre><code>Datetime Transaction Item
3/16/2020 9:58 1 X
3/17/2020 10:05 2 Y
3/18/2016 14:48 3 Z
</code></pre>
<p>What I need is Datetime column to be converted to weekday and one hour ... | <p>I'm not sure what weekday is doing here. Isn't it just extract the time and add one hour?</p>
<pre><code>hours = df['Datetime'].dt.hour
df['TimeSlot'] = hours.astype(str) + "-" + hours.add(1).astype(str)
</code></pre>
<p>Output:</p>
<pre><code> Datetime Transaction Item TimeSlot
0 2016-10-30 09:58:0... | python|pandas|dataframe | 1 |
372,158 | 60,378,541 | merge pandas dataframes on value from column | <p>I have 3 pandas dataframes with a structure similar to:</p>
<pre><code>pandas1:
date star col1 col2
2019-01-30T00:32:18.128 tau_Cet 12 25
2019-01-30T00:34:05.525 tau_Cet 23 466
2019-01-03T03:54:59.886 HD_41248 344 997
2019-01-06T03:54:25.886 51_Peg 353 458
pandas2:
date star col3 col4 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> in list comprehension with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_ind... | pandas|dataframe|merge | 1 |
372,159 | 60,647,953 | Creating a bar chart | <p>I have a dataset on which I have used the describe() function.<a href="https://i.stack.imgur.com/CnaQb.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Now, I have plotted 2 bar graphs showing subject wise min and max scores in each.<a href="https://i.stack.imgur.com/ipVRP.png" rel="nofollow n... | <p><strong>sample df.describe() (just a dummy one):</strong></p>
<pre><code> Pressure(BP) Nitrogen Dioxide(NO2) PM 10(RSPM) PM.1 2.5(PM2.5)
count 7.000000 7.000000 7.000000 7.000000 7.000000 7.000000 7.000000
mean 151.0000 295.2857 110.4285 184.1428 134.2857 302.5714 303.857143
std 188.3781... | python|pandas | 0 |
372,160 | 60,332,608 | Python Compare two Excel by id value and "Filed" output in other columns difference in new excel with respect to ID column | <p>I have two excel(A.xlsx,B.xlsx with same sheet name example "testdata".
The data format looks like this.</p>
<p>A.xlsx(sheet2)
<a href="https://i.stack.imgur.com/Sb8MN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sb8MN.png" alt="enter image description here"></a></p>
<p>B.xlsx (sheet2)
<a hre... | <pre><code>id = list(range(100))
filled_items = ["ADV", "KN", "BBL", "TOOL"]
sum_items = ["a", "b", "c", "d", "e", "f", "g"]
df = pd.DataFrame(columns=["id","filled", "sum"])
df1 = pd.DataFrame(columns=["id","filled", "sum"])
df["id"] = random.sample(id,100)
df1["id"] = random.sample(id,100)
df["sum"] = random.choices(... | python-3.x|pandas|data-science | 0 |
372,161 | 60,440,396 | pandas convert a nested dictionary to mutiIndex rows and columns | <p>I have a nested dictionary and i want to make it to a multiIndex rows and colums like below. But my data is lost in table somehow. </p>
<pre><code> test= {12: {'Category 1': {'TestA': {'att_1': 1, 'att_2': 'whatever'}, 'TestB': {'att_1': 3, 'att_2': 'spring'}}, 'Category 2': {'TestA': {'att_1': 23, 'att_2': 'ano... | <p>You can get the required data frame as:</p>
<pre><code>import pandas as pd
import numpy as np
test= {12: {'Category 1': {'TestA': {'att_1': 1, 'att_2': 'whatever'}, 'TestB': {'att_1': 3, 'att_2': 'spring'}}, 'Category 2': {'TestA': {'att_1': 23, 'att_2': 'another'}, 'TestB': {'att_1': 9, 'att_2': 'summer'}}}, 15: ... | python|pandas|dataframe|dictionary|multi-index | 0 |
372,162 | 60,607,402 | Style Transfer : Save&Restore checkpoint/model in tensorflow 1.15.0 | <p>i am a bit frustrated about saving and restoring models in tensorflow 1.15.0. I want to achieve it in a jupyter notebook / google colab notebook environment. The application is style-transfer of images.</p>
<p>I simply want to save the model and restore it in order to apply the style transfer for a larger number of... | <p>I also tried saving the model via the keras - syntax.</p>
<pre><code>model.load_weights('/content/sample_data/saved_model/my_model6.h5')
</code></pre>
<p>and </p>
<pre><code>model.save_weights('/content/sample_data/saved_model/my_model6.h5', save_format='h5')
</code></pre>
<p>There was no error message, but the ... | python|tensorflow|save|checkpoint|style-transfer | 0 |
372,163 | 60,444,013 | Pandas - return all rows with identical values in one column and small differences in another column | <p>I have some DataFrame: </p>
<pre><code>df = pd.DataFrame({'fruit':['apple', 'apple', 'apple', 'pear', 'pear', 'pear', 'mango', 'mango', 'mango', 'peach', 'peach', 'peach', 'plum', 'plum', 'plum'],
'region':[5,5,5,7,7,7,2,2,2,2,2,2,2,2,2],
'location':[75000,75000,75000,250,250... | <p>I am adding this as a new answer sicne the previous answer is usefull if someone wants the whole group instead of a portion of the group like you are wanting now.</p>
<p>For your latest need, you can do as below</p>
<pre><code>def func(x):
return (x - x.iloc[0])
a = df.groupby('region')['location'].apply(func)... | python|pandas|pandas-groupby | 0 |
372,164 | 60,522,680 | How to select row information in dataframe over ID | <p>I'm new in python. I have a large dataframe as like that : </p>
<pre><code> ID x y
0 1 x1 y1
1 0 x2 y2
2 0 x3 y3
3 2 x4 y4
4 1 x5 y5
5 2 x6 y6
</code></pre>
<p>I would like to take couples of (x;y) between the IDs 1 and 2, in a dataframe like this : </p>
<pre><code> coordin... | <p>One idea is create groups by each <code>1</code> starting values and aggregate custom lambda function for tuples:</p>
<pre><code>df['new'] = (df['ID'] == 1).cumsum()
print (df)
ID x y new
0 1 x1 y1 1
1 0 x2 y2 1
2 0 x3 y3 1
3 2 x4 y4 1
4 1 x5 y5 2
5 2 x6 y6 2
df1 =... | python|pandas|dataframe|iteration|selection | 3 |
372,165 | 60,651,800 | Keras Layer unknown, try to load a model | <p>I saved a trained model with this code but cannot load it because the layer isn't in keras.layer, here's my code, thanks in advance for your precious help !</p>
<pre><code>from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import tensorflow as tf
import tensorflo... | <p>the problem here is that model save file does not contain code of that layer. you can solve this problem using custom_objects and pass dictionary to this argument.</p>
<p>The trick here is to copy the unrecognized name, put it to string in dictionary as key and provide that layer as its value</p>
<p><strong>For ex... | python|tensorflow|keras|neural-network|keras-layer | 1 |
372,166 | 60,526,641 | Pandas difference between timestamps per row on column level | <p>I have the following dataframe: df</p>
<pre><code> Date Type
0 1990-01-01 02:00:00 1
1 1990-01-01 03:00:00 1
2 1990-01-01 04:00:00 1
3 1990-01-01 05:00:00 2
4 1990-01-01 06:00:00 2
5 1990-01-01 07:00:00 2
</code></pre>
<p>How do I get the timedifference per row on a new column d... | <p>For solution with <code>shift</code> subtract values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.sub.html" rel="nofollow noreferrer"><code>Series.sub</code></a> with shifted data per groups by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.group... | pandas|datetime|pandas-groupby|timedelta | 1 |
372,167 | 60,627,591 | Count number of categories after GROUP BY in SQL or Pandas | <p>I have a dataframe df :</p>
<pre><code>ORDERID PRODUCTTYPE PRODUCTID PRODUCT
123 Fruits 2 Banana
123 Vegetables 3 Tomato
123 Vegetables 3 Onion
321 Fruits 2 Grapes
321 Fruits 2 Avocado
</code></pre>
<p>I need... | <p>In SQL, you can use conditional aggregation:</p>
<pre><code>select
orderid,
sum(case when producttype = 'Fruits' then 1 else 0 end) fruits,
sum(case when producttype = 'Vegetables' then 1 else 0 end) vegetables
from mytable
group by orderid
</code></pre>
<p>Or, if your database supports the modern <cod... | sql|pandas|oracle|group-by|pivot | 4 |
372,168 | 60,616,182 | rpy2 conversion to pandas DataFrame returns numpy recarray instead of pandas | <p>I am trying to convert an R data frame into a python using <code>rpy2</code></p>
<pre><code>with localconverter(ro.default_converter + pandas2ri.converter):
smogned = ro.conversion.rpy2py(smogned)
print('after pandas2ri')
print(type(smogned))
print(smogned.shape)
print(smogned.dtype)
</c... | <p>Thanks to @hpaulj, I fixed this by converting the 'recarray' to a pandas DataFrame explicitly:</p>
<pre><code>smogned = pd.DataFrame(smogned)
</code></pre>
<p>Although its still weird for me why is it returning a <code>recarray</code></p> | python|pandas|numpy|rpy2 | 0 |
372,169 | 60,601,769 | Converting column in Dataframe to datetime | <p>I've been trying to use the to_datetime function to convert values in my column to datetime: </p>
<pre><code>df['date'] = pd.to_datetime(df['date'],errors='coerce',format='%Y-%m-%d %H:%M:%S %z %Z')
</code></pre>
<p>After that, I received only NaT values.</p>
<p>Example: Value Format in Column: '1979-01-01 00:00:... | <p>I think you can't parse utc offset (+0000) and timeszone information at the sime time. </p>
<p>You might want to remove the UTC at the end and only parse the offset.</p>
<pre><code>df['date'] = df.date.str[:-4]
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d %H:%M:%S %z')
</code></pre> | python|pandas|datetime | 3 |
372,170 | 60,675,928 | Dataframe column names np array has \n after one of the column names | <p>I am trying to sum the values of select columns from a list of columns and store it in a new column. However, I keep getting </p>
<blockquote>
<p>raise KeyError('%s not in index' % objarr[mask])</p>
<p>KeyError: "['a' 'b' 'c' 'd' 'e'\n 'f'] not in index"</p>
</blockquote>
<p>This is the piece of code where ... | <pre><code>In [290]: np.argwhere('Person')
Out[290]: array([], shape=(1, 0), dtype=int64)
</code></pre>
<p>It doesn't make sense to use that in <code>np.delete</code>.</p>
<p>Show <code>cols</code></p>
<p>===</p>
<pre><code>In [301]: cols = np.array(['... | python|pandas|numpy|dataframe | 0 |
372,171 | 60,393,668 | Pandas - Generate Unique ID based on row values | <p>I would like to generate an integer-based unique ID for users (in my df).</p>
<p>Let's say I have:</p>
<pre><code>index first last dob
0 peter jones 20000101
1 john doe 19870105
2 adam smith 19441212
3 john doe 19870105
4 jenny fast 19640822
</code></pre>
<p>I ... | <p>You can try using hash function.</p>
<pre><code>df['id'] = df[['first', 'last']].sum(axis=1).map(hash)
</code></pre>
<p>Please note the hash id is greater than 10 digits and is a unique integer sequence.</p> | python|pandas|hash | 3 |
372,172 | 60,383,124 | How to match and extract value between two dataframes? | <p>I have two dfs:</p>
<pre><code>df1:
col1 col2
text 1
df2:
col1
text 123
</code></pre>
<p>I want to see if value in df1.col1 is in df2.col1, and if yes the value is present, I want to pull out value of df2.col1 into new column in df1. </p>
<p>updated df1:</p>
<pre><code>col1 col2 col_extr... | <p>I asked for lengths of dataframes because searching/matching multiple string patterns is generally slow. You data is pretty small, so it wouldn't be a problem. Here's a solution:</p>
<pre><code>pd.concat((df1,
df2[df2['col1'].str.contains(df1.col1.iloc[0])]
.add_suffix('_extracted')
... | python-3.x|pandas | 1 |
372,173 | 60,685,040 | I need to create a python function that makes an n-dimensional vector such that each element is a real number in [0,100) | <p>I'm not very good with python and I need to create a function, randvec(n), that will create an n-dimensional vector where each element is a random real number in [0,100). Below is what I have so far.</p>
<pre><code>def randvec(n):
vector = np.ndarray((1,n),dtype=float)
for i in range(0,n):
vector[i]... | <pre><code>def randvec(n):
return [random.random()*100 for _ in range(n)]
</code></pre>
<p>will generate <code>n</code> real random values such that each value is in interval [0, 100). See class <code>Random</code> for more information on <code>random()</code> method.</p>
<p>But that's a PRNG (pseudo random number... | python|function|vector|numerical-methods|numpy-ndarray | 0 |
372,174 | 60,748,816 | Convert Google Colab notebook to PDF / HTML? | <p>I would like to know if there is a way in Google Colab that can collate outputs nicely, just like Markdown in R and how IPython Notebook can be converted to pdf and html format? </p>
<p>My output consists of multiple tables, graphs etc. I would like to preferably pretty print them into one file, of which some part ... | <p>You can also create a pdf in colab itself using nbconvert.</p>
<pre class="lang-py prettyprint-override"><code>!apt update
!apt install texlive-xetex texlive-fonts-recommended texlive-generic-recommended
import re, pathlib, shutil
# Get a list of all your Notebooks
notebooks = [x for x in pathlib.Path("/content/d... | python|pandas|jupyter-notebook|google-colaboratory | 5 |
372,175 | 60,536,394 | Convert Julia Dataframe to Python Pandas data frame | <p>I am trying to convert a PyCall.jlwrap ('Julia') object to a Pandas dataframe. I'm using PyJulia to run an optimization algorithm in Julia, which spits out a dataframe object as a result. I would like to convert that object to a Pandas dataframe.</p>
<p>This is a similar question as posed 5 years ago <a href="https... | <p>I get an error (reading a Julia DataFrame in Python), if I use the <a href="https://github.com/JuliaData/DataFrames.jl" rel="noreferrer">DataFrames.jl</a> package. However, it seems to work nicely with the <a href="https://github.com/JuliaPy/Pandas.jl" rel="noreferrer">Pandas.jl</a> package:</p>
<pre><code>>>... | python|pandas|dataframe|julia | 6 |
372,176 | 60,737,595 | Resize all images stored in array | <p>I stored images read through <code>cv2.imread</code> in an array <code>masks</code>. The shape of the array is <code>(10, 5248, 7936, 3) (10 images, image height, image width, 3 channels)</code>.</p>
<p>I am now trying to copy this array but with every image resized to the values <code>monitor_h</code> and <code>mo... | <p>To see why your images are coming out black and white, let's step through the code.</p>
<pre><code>resized_masks = np.empty([masks.shape[0], monitor_h, monitor_w, masks.shape[3]])
</code></pre>
<p>This line creates an array of type <code>np.float</code> by default.</p>
<pre><code>resized_masks[i] = cv2.resize(np.... | python|numpy|opencv|image-processing|image-resizing | 2 |
372,177 | 60,660,812 | How can I find a combination of rows from a table where each column sums a specific number (or range)? | <p>I have a table with three columns. Let's say the first row is filled with some people names. The second and the third are numbers representing the value they spent. I want to build another table with a subset of those people where the sum from each column of this new table gives a specific value. How can I do that i... | <p>Extending on @stanna's solution: We can create all possible combinations of the rows to be dropped using <code>iterables.combinations()</code> and check if our requirements are satisfied </p>
<pre><code>def checkRequirements(sum1, sum2):
if sum1 == 20 and sum2 == 125:
return True
else:
return False
# f... | python|pandas|python-2.7|numpy | 1 |
372,178 | 60,684,868 | Docker Image using compiled TensorFlow library is not working on my CPU | <p>I'm currently trying to use <a href="https://github.com/stickeritis/sticker/blob/master/doc/PRETRAINED.md" rel="nofollow noreferrer">some pretrained models</a> that are provided as docker image to use for some NLP stuff. The problem however is, that whenever I try to run the docker image I get the following error me... | <p>I ran into the same problem while starting the official <a href="https://www.tensorflow.org/install/docker" rel="nofollow noreferrer">tensorflow docker</a> in my VM via VirtualBox. And I found maybe it's because of <a href="https://www.virtualbox.org/ticket/15471" rel="nofollow noreferrer">VirtualBox not supporting ... | docker|tensorflow | 1 |
372,179 | 60,534,921 | UnicodeEncodeError in Python | <p>I am getting an error and I don't know what exactly I should do?!
The error message:<br>
File "pandas_libs\writers.pyx", line 55, in pandas._libs.writers.write_csv_rows
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 147: ordinal not in range(128)</p>
<pre><code>import numpy as np
imp... | <p>I found a solution that works also:
adding (encoding='utf-8') to the line:
data.to_csv("Tweets.csv", encoding='utf-8')</p> | python|pandas|csv|decode|encode | 1 |
372,180 | 60,454,777 | Pull Column from DataFrame and Calculate the Standard Deviation for Each Column in Each Cluster | <p>I realize how, confusing the title sounds so let me explain my issue. I have a DataFrame separated by the Column ID. The Column ID represents the cluster. Each Cluster DataFrame has the same Column labels.</p>
<p>I'm trying to create a function, that allows me to send in each cluster DataFrame, into the function, a... | <p>IIUC, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> to filter, then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.std.html" rel="nofollow noreferrer"><code>groupby... | python|pandas|function|dataframe | 2 |
372,181 | 60,728,826 | How to split column with dictionary into 2 column | <p>What is the best way to split the following column into a data frame with column with the name of every country and the other two columns with the data from the first column (history)?</p>
<p>From this dataframe:</p>
<pre><code>+-----------------------------------------+----------------------------------+---------... | <p>IIUC,</p>
<pre><code>new_df = (pd.DataFrame(df['history'].tolist(),
index = df['country'])
.reset_index()
.melt('country',var_name = 'days')
.sort_values('country'))
</code></pre>
<p>or symply:</p>
<pre><code>#import numpy as np
pd.DataFrame(data = np.... | python-3.x|pandas|dataframe | 1 |
372,182 | 60,489,076 | Calling sort_values() on Pandas DataFrame raises ValueError: The truth value of a Series is ambiguous | <p>I have a DataFrame containing Trump's tweets. The column <code>polarity</code> contains a sentiment value for each tweet, and I am trying to sort the DataFrame <code>trump</code> based on these values by making a call to <code>sort_values()</code>. </p>
<p>If I write <code>trump.sort_values('polarity')</code> I get... | <p>I found a solution to my problem. Rather than creating the <code>'polarity'</code> column manually by assigning <code>trump['polarity']</code> to the result of nested list comprehensions, I merged the <code>tidy_format</code> and <code>sent</code> DataFrames (<code>sent</code> has column <code>polarity</code> contai... | python|pandas|dataframe|twitter|series | 0 |
372,183 | 72,776,884 | find when a value is above threshold and store the result in a list in pandas | <p>here is my problem.
I have a df like this one :</p>
<pre><code>user_id profile item level amount cumulative_amount
1 1 1 1 10 10
1 1 1 2 30 40
1 1 2 1 10 10
1 1 2 2 10 ... | <p>IIUC, you can filter for values above or equal to threshold (40), then get the first matching level per group:</p>
<pre><code>(df
.loc[df['cumulative_amount'].ge(40)]
.groupby(['user_id', 'profile', 'item'])
['level'].first()
)
</code></pre>
<p>output Series:</p>
<pre><code>user_id profile item
1 1 ... | pandas|list|group-by|aggregate-functions | 2 |
372,184 | 72,764,305 | How to make a matrix using index and the value in python? | <p>I have a dataset, which has two columns:</p>
<pre><code>index Value
0 True
1 True
2 False
3 True
</code></pre>
<p>Is it possible to obtain a matrix that looks like</p>
<pre><code>index 0 1 2 3
0 True True False True
1 True True False True
2 False False False False
3 ... | <p>A possible way:</p>
<pre><code>m = np.tile(df['Value'], len(df)).reshape(-1, len(df)) * df[['Value']].values
out = pd.DataFrame(m)
print(out)
# Output
0 1 2 3
0 True True False True
1 True True False True
2 False False False False
3 True True False True
</code></pre> | python|pandas|dataframe|matrix|crosstab | 2 |
372,185 | 72,743,211 | When testing a model written from scratch, how do you predict the new outputs? | <p>Would I use the weights and Biases that's been saved by the training model?</p>
<p>Below is the code. Do I just call in predict with the new test data?? .predict(X_test)</p>
<p>where X is the input array. I am trying to understand the math and how the testing work for neural networks instead of using TensorFlow or P... | <blockquote>
<p>Would I use the weights and Biases that's been saved by the training model?</p>
</blockquote>
<p>Yes. This happens when you call <code>.fit()</code></p>
<blockquote>
<p>Do I just call in predict with the new test data?? .predict(X_test)</p>
</blockquote>
<p>Again, yes</p>
<blockquote>
<p>I am trying to ... | python|tensorflow|machine-learning|deep-learning | 0 |
372,186 | 72,790,947 | How to combine or join unique values from different columns in DataFrame? | <p><img src="https://i.stack.imgur.com/kvj2v.png" alt="This is my Dataset and I want to combine Symptom_1, Symptom_2, Symptom_3" /></p>
<p>This is my Dataset and I want to combine Symptom_1, Symptom_2, Symptom_3.
The code that I used to combine them is</p>
<pre class="lang-py prettyprint-override"><code>df['Symptom'] =... | <pre><code>df['Symptom'] = df['Symptom_1'].str.cat(df[['Symptom_2', 'Symptom_3']], sep=', ')
</code></pre> | python|pandas|dataframe|numpy | 1 |
372,187 | 72,497,051 | VLOOKUP using pandas without repetition | <p>I have two dataframes df1 and df2. How do I obtain df3 using pd.merge or any other function?</p>
<p>What I tried?</p>
<p><code>df3=df1.merge(df2, on='A', how='left')</code></p>
<p>This gives me df3 with number of rows same as df2. But, what I want is number of rows in df1 and df3 are same. df3 should look exactly as... | <p>Use <code>drop_duplicates</code> to keep one instance of <code>(A, B)</code>:</p>
<pre><code>>>> df1.merge(df2, on='A', how='left').drop_duplicates(['A', 'B'], ignore_index=True)
A B C
0 1 1 XY
2 2 1 XY
5 3 2 XY
7 4 2 XY
9 5 3 XY
11 6 7 AB
13 7 1 AB
14 8 1 AB
15 ... | python|pandas|dataframe|vlookup | 3 |
372,188 | 72,578,189 | Pandas: Copy a value of a row and paste it to multiple rows above in another column | <p>I need to copy the strings of <code>event</code> and paste them into three rows above and five rows down of a new column named <code>epoch</code>.</p>
<pre><code> event epoch
NaN NaN
NaN NaN
NaN NaN
NaN 2_1
NaN 2_1
NaN 2_1
... | <p>Try this: <em>(considering column "epoch" doesn't exist yet)</em></p>
<pre><code>df['epoch'] = df.event.ffill(limit=5)
df['epoch'] = df['epoch'].bfill(limit=3)
df
</code></pre>
<p>Output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>event</th>
<th>epoch</th>
... | python|pandas|dataframe|copy | 1 |
372,189 | 72,539,968 | How to store tf-agents' trajectory object in big query from python and retrieve it back as the trajectory object | <p>I wanted to save the trajectories from the tf-agents into a big query table and wanted to retrieve them back as needed into python again.</p>
<p>In the python dataframe, the trajectories are saved as trajectory object. But, I am not sure how to save these trajectories object to big query and retrieve them back into ... | <p>Stored each trajectory as pickle data, using pickle.dumps(), to the big query column.
The big query data type used is 'bytes' for the trajectory object.</p>
<p>Again retrieved the pickle back using pickle.dumps()</p> | python|tensorflow|google-bigquery|tf-agent | 1 |
372,190 | 72,699,948 | Resnet50+LSTM to classify the video frames | <p>I want to implement a Resnet50+LSTM to classify the video frames into different 7 phases (classes). In my train files, I have 5 folders, each one includes a video that is captured as some frames which show one phase of a specific action(the action is identical for all the videos). Now I want to use Resnet50+LSTM to ... | <blockquote>
<p>What should I do?</p>
</blockquote>
<p>Why not using a 3D conv network? It gives the best results according to papers with code (<a href="https://paperswithcode.com/sota/action-classification-on-kinetics-400" rel="nofollow noreferrer">https://paperswithcode.com/sota/action-classification-on-kinetics-400... | python|tensorflow|keras|conv-neural-network|lstm | 0 |
372,191 | 72,704,022 | Read one cell from each sheet of an Excel workbook and compile into a list (pandas/python) | <p>I have an Excel workbook with a bunch of sheets that I want to pull the contents of cell B4 and put all of those cells into a list, not a dictionary. I'm also pulling information from other parts of each sheet but I don't think I can do both at the same time so my code looks like this:</p>
<pre><code>sheets = pd.rea... | <p>I still didn't get the whole picture of your data.</p>
<p>But here's an approach.</p>
<hr />
<p>The example of excel content I used(only one sheet).</p>
<p><a href="https://i.stack.imgur.com/fWaTV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fWaTV.png" alt="enter image description here" /></a><... | python|excel|pandas|dataframe|dictionary | 1 |
372,192 | 72,804,437 | Finding correlation in dataframe | <p>I have a pandas dataframe(df) that has columns (say x_1,x_2,....x_n as column names). I want to find a correlation (Pearson) between the ith column and the rest of the columns.</p>
<p>One way I can do this is by using the .corr() function</p>
<pre><code>correlation = df.corr(method='pearson')
corr_i = correlation['x... | <p><code>corrwith()</code> might be what are looking for.</p>
<p>Say you had a data frame with columns <code>c1,c2,c3,c4</code>.</p>
<p>Then you should be able to:</p>
<pre><code>df[['c2','c3','c4']].corrwith(df['c1'])
</code></pre> | python|pandas|dataframe|correlation|pearson-correlation | 3 |
372,193 | 72,592,043 | Pandas - How to combine multiple columns into new one with list as value? | <p>I have a dataframe that contains images:</p>
<pre><code>SOME_COL SOME_COL IMAGE_MAIN IMAGE_2 IMAGE_3 IMAGE_4 IMAGE_5 IMAGE_6
* * 0 1 2 3 NaN 5
</code></pre>
<p>I want to drop the <code>IMAGE_MAIN</code> and <code>IMAGE_[2..6]</code> columns and create a new one <code>IM... | <p>You can start by filtering the columns which start with 'IMAGE' using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>DataFrame.filter</code></a>, and then apply a function row-wise using <a href="https://pandas.pydata.org/docs/reference/api/pandas.... | python|pandas|numpy | 1 |
372,194 | 72,503,923 | The equivalent of torch.nn.Parameter for LibTorch | <p>I am trying to port a python PyTorch model to LibTorch in C++.</p>
<p>In python the line of code within a subclass of a torch.Module object
<code>self.A = nn.Parameter(A)</code> where <code>A</code> is a torch.tensor object with <code>requires_grad=True</code>.</p>
<p>What would be the equivalent of this for a torch... | <p>To register a parameter (or tensor which requires gradients) to a module, you could use:</p>
<p><code>m.register_parameter("A", torch::ones({20, 1, 5, 5}), True)</code>;
in libtorch.</p> | pytorch|libtorch | 2 |
372,195 | 72,524,884 | How to intersect boolean subarrays for True values? | <p>I know that Numpy provides <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html" rel="nofollow noreferrer"><code>logical_and()</code></a> which allows us to intersect two boolean arrays for True values only (True and True would yield True while True and False would yield False). For e... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduce.html" rel="nofollow noreferrer"><code>.reduce()</code></a> along the first axis:</p>
<pre><code>>>> a = np.array([[[ True, True], [ True, False]], [[ True, False], [False, True]]])
>>> np.logical_and.reduce(a... | python|arrays|python-3.x|numpy|boolean | 4 |
372,196 | 72,630,794 | Pandas standard deviation of column values | <p>I have 4 columns that I want the standard deviation of in a dataframe.</p>
<pre><code>Key A B C D stdDev
X 1 2 3 4 std(1,2,3,4)
y 4 5 6 7 std(4,5,6,7)
z 8 9 10 11 std(8,9,10,11)
</code></pre>
<p>I want to take the values from ABCD and use them to find the stdDev of. I need thi... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.std.html" rel="nofollow noreferrer"><code>std</code></a> by row (<code>axis=1</code>):</p>
<pre><code>df['stdDev'] = df[['A', 'B', 'C', 'D']].std(axis=1)
</code></pre>
<p>output:</p>
<pre><code> Key A B C D stdDev
0 X 1 2 3 ... | python|pandas|dataframe | 2 |
372,197 | 72,605,066 | How to check if any of the gradients in a PyTorch model is nan? | <p>I have a toy model:</p>
<pre><code>import torch
import torch.nn as nn
import torch.optim as optim
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.fc1 = nn.Linear(1, 2)
self.fc2 = nn.Linear(2, 3)
self.fc3 = nn.Linear(3, 1)
def forward(self, x):
... | <p>You can check as below. This approach only checks for the gradients with respect to the model parameters. It does not look at intermediate gradients, actually, those intermediate gradients do not exist after <code>loss.backward()</code> is called without <code>retain_graph=True</code> argument. For the demonstration... | machine-learning|pytorch | 1 |
372,198 | 72,721,658 | insert sub-id column into pandas dataframe | <p>I have the following pandas dataframe:</p>
<pre><code>ID TYPE ESC END
TRL EC1 MISL1123 36
TRL EC2 XISL1124 57
LBL EC1 CARB24 20
LBL EC1 AARB70 96
LBL EC2 MUT23 79
</code></pre>
<p>I want to insert a column of sequential sub-ids (Column "SEQUENCE") into the dataframe to account for multiple en... | <p>Does this accomplish what you needed?</p>
<pre><code>df['Sequence'] = 'seq' + df.groupby('ID').cumcount().astype(str)
</code></pre> | python|pandas | 3 |
372,199 | 72,532,120 | Pandas add minutes from other column | <p>I have a dataframe:</p>
<pre><code>data = {'time':['10:45:00', '09:30:00', '17:00:00', '15:50:00'], 'minutes_to_be_add': [10, 5, 7, 20]}
df = pd.DataFrame(data=data)
</code></pre>
<p>I want to create a new column <code>future_time</code> by adding the minutes from <code>minutes_to_be_added</code> column to the <cod... | <p>You can use Timedeltas:</p>
<pre><code>(pd.to_timedelta(df['time'])
.add(pd.to_timedelta(df['minutes_to_be_add'], unit='m'))
.astype(str).str[-9:]
)
</code></pre>
<p>output:</p>
<pre><code>0 10:55:00
1 09:35:00
2 17:07:00
3 16:10:00
dtype: object
</code></pre> | pandas|dataframe|datetime | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.