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 |
|---|---|---|---|---|---|---|
13,300 | 66,300,513 | Matplotlib - Horizontal Bar Chart Timeline With Dates - Xticks not showing date | <p>Trying to make a graph that looks like the first image here.</p>
<p>However when I try and implement it, I can't work out how to get the dates to print on the X axis, the scale seems about right, just the xticks seem not to be dates, but some basically random number. The typical output is visible in figure 2.</p>
<p... | <p>You can plot each bar as line, choosing the width of the line (<code>lw</code>) you prefer:</p>
<pre class="lang-py prettyprint-override"><code># Set the color of the grid lines
mpl.rcParams['grid.color'] = "w"
fig, ax = plt.subplots(1, 1)
# Plot eac item as a line
for i, (b, e, l) in enumerate(zip(beg_so... | python-3.x|numpy|datetime|matplotlib|bar-chart | 2 |
13,301 | 46,246,987 | tensorflow InvalidArgumentError: "You must feed a value for placeholder tensor" | <p>This is a simple tensorflow code that creates 2 models with shared parameters but different inputs (placeholders).</p>
<pre><code>import tensorflow as tf
import numpy as np
class Test:
def __init__(self):
self.x = tf.placeholder(tf.float32, [None] + [64], name='states')
self.y = tf.placeholde... | <p>The problem lies in the use of batch norm, namely these lines:</p>
<pre><code>extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(extra_update_ops):
self.train_step = tf.train.RMSPropOptimizer(.00002).minimize(self.loss)
</code></pre>
<p>Note, that you have two gr... | machine-learning|tensorflow|deep-learning | 2 |
13,302 | 58,551,938 | Select rows from dataframe by group by and select max in given column | <p>I have a data set structured as follow. This a sample so please imagine a dataframe which contain many sequences. Few things to precise:
<code>time</code> are in descending order.
<code>created_at</code> is also in descending order.
Both <code>time</code> and <code>created_at</code> reset when a new <code>source</co... | <p>You can call <code>last</code> which computes the last values for each group and use <code>iloc</code> to get the row values:</p>
<pre><code>df.groupby(["source", "currency", "app_v"]).last().iloc[-1]
</code></pre>
<p>You can access the index group values using the name attribute like:
<code>df.get_group(df.groupb... | python|pandas | 0 |
13,303 | 58,216,315 | pandas how to get values from df2 for df1 while df1 and df2 have values overlapped on column(s) | <p>I have two <code>df</code>s, the <code>df1</code> looks like,</p>
<pre><code>df1
id
1
2
3
4
5
df2
doc_no c_id
2 22
3 33
4 44
6 66
7 77
</code></pre>
<p>values of <code>id</code> in <code>df1</code> overlaps some values of <code>doc_no</code> in <code>df2</code>; I want t... | <p>You could use <code>df1.merge(df2)</code> (which is basically a left/right/inner join more described). Anyway, are you having any performance problem on your program due to the left join? This should be done quick.</p>
<p>Regards!</p> | python|python-3.x|pandas|dataframe | 1 |
13,304 | 58,319,088 | How to change color of line plot based on date column? | <p>I am trying to change color of my line chart based on 'date column'. But I am getting an error</p>
<p>I have tried the code:</p>
<pre><code>fig = px.line(df_1, x='Time_ist', y='AccelerationG', color = 'Date')
# # fig.update_layout(title_text='Acceleration on ' + str(i))
fig.show()
The error i am getting is:
Key... | <p><code>color</code> in <code>px.line</code> does not not take a <code>Timestamp</code> as an argument. If it somehow did, I'm not sure what to expect the result to be. Perhaps a color that indicates the passage of time? I'm not sure, really. But what I'm guessing your're looking for here, is to discern the data point... | python|pandas|plotly | 2 |
13,305 | 58,526,255 | Resizing an array to another shape in Python | <p>I have the following array:</p>
<pre><code>a = np.random.rand(5,2)
a
array([[0.98736372, 0.07639041],
[0.45342928, 0.4932295 ],
[0.75789786, 0.48546238],
[0.85854235, 0.74868237],
[0.13534155, 0.79317482]])
</code></pre>
<p>and I want to resize it so that it is divided into 2 batches w... | <p>Using numpy.resize, you have to use like this:</p>
<pre><code>import numpy as np
a = np.random.rand(5,2)
b = np.resize(a, (2,3,2))
</code></pre>
<p>otherwise you can use the object method to get the same result, like this:</p>
<pre><code>import numpy as np
a = np.random.rand(5,2)
a.np.resize(2,3,2)
b = a.copy()
<... | python|arrays|numpy|resize|reshape | 5 |
13,306 | 68,926,755 | pandas return auxilliary column from groupby and max | <p>I have a pandas DataFrame with 3 columns, A, B, and V.</p>
<p>I want a DataFrame with A as the index and one column, which contains the B for the maximum V</p>
<p>I can easily create a df with A and the maximum V using groupby, and then perform some machinations to extract the corresponding B, but that seems like th... | <pre><code>A = [1,1,1,2,2,2,3,3,3,4,4,4]
B = [1,2,3,4,5,6,7,8,9,10,11,12]
V = [21,22,23,24,25,26,27,28,29,30,31,32]
df = pd.DataFrame({'A': A, 'B': B, 'V': V})
res = df.groupby('A').apply(
lambda x: x[x['V']==x['V'].max()]).set_index('A')['B'].to_frame()
res
B
A
1 3
2 6
3 9
4 12
</code></pre> | pandas|pandas-groupby|aggregate | 0 |
13,307 | 69,059,980 | Update an existing column in one dataframe based on the value of a column in another dataframe | <p>I have two csv files as my raw data to read into different dataframes. One is called 'employee' and another is called 'origin'. However, I cannot upload the files here so I hardcoded the data into the dataframes below. The task I'm trying to solve is to update the 'Eligible' column in employee_details with 'Yes' or ... | <p>You can merge the 2 dataframes on Personal ID and then use np.where</p>
<p>Merge with <code>how='outer'</code> to keep all personal IDs</p>
<pre><code>df_merge = pd.merge(employee_details, origin_details, on='Personal_ID', how='outer')
df_merge['Eligible'] = np.where(df_merge['Country']=='UK', 'Yes', 'No')
Pe... | python|pandas|dataframe|numpy | 1 |
13,308 | 69,258,366 | Is there a way to mass edit user permissions / interact with hundreds of Google Sheets via Python? | <p>I have around 600 google sheets that are all very similar where I need to get values from one specific column. I've authenticated an app in the Google Developer console so I have access to one sheet. However to do so I had to give access to the Service Account from inside the sheet itself. That service account does ... | <p>You can use <a href="https://developers.google.com/drive/api/v3/reference/permissions/create" rel="nofollow noreferrer">Permissions: create</a> in Drive API to create a new permission to a specific file based on your preferred role.</p>
<h2>Sample Request via API explorer:</h2>
<p><strong>FileId:</strong> Sheet file... | python|pandas|google-sheets|google-sheets-api | 0 |
13,309 | 69,169,595 | Should feature embeddings be taken before or after dropout layer in neural network? | <p>I am training a binary text classification model using BERT as follows:</p>
<pre><code>def create_model():
text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name='text')
preprocessed_text = bert_preprocess(text_input)
outputs = bert_encoder(preprocessed_text)
# Neural network layers
l1 = ... | <p>In order to answer your question let's recall how a Dropout layer works:</p>
<p>The Dropout layer is usually used as a means to mitigate overfitting. Suppose two layers, A and B, are connected through a Dropout layer. Then during the training phase, neurons in layer A are being randomly dropped. That prevents layer ... | tensorflow|neural-network|embedding|bert-language-model|dropout | 1 |
13,310 | 68,880,631 | How to match return of tomorrow with factor of today more efficiently in Dataframe? | <p>I'm handling financial data, and want to match the return of the future to the factor of today. My data table consists of 13 columns as follows.
<a href="https://i.stack.imgur.com/dP98p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dP98p.png" alt="enter image description here" /></a></p>
<p>In t... | <p>you can use a vectorized operation</p>
<pre><code>double_sorted['ret+1'] = double_sorted.sort_values(['permno', 'year', 'month'])\
.groupby('permno').ret.shift(-1)
</code></pre> | python|pandas|dataframe | 1 |
13,311 | 44,512,270 | building TensorFlow: bazel cannot find libstdc++ in non-standard directory | <p>I am trying to build MKL-accelerated version of TensorFlow using bazel 0.5.1, gcc 6.2, binutils 2.28, Anaconda2 python on Scientific Linux 7.2.
Apparently the system /lib64/libstdc++.so.6 is too old, so I am trying to use gcc installed in another directory. PATH, LD_LIBRARY_PATH are modified to prepend the correspon... | <p>sorry for the slow reply. Bazel by design ignores LD_LIBRARY_PATH when running actions. It doesn't have to ignore them during C++ toolchain detection, but at the moment, it does :/ To help you forward, I would try adding --sysroot= as linkopt or using bazel grte_top flag. Depending on where your libstdc++.so lives, ... | tensorflow|bazel | 0 |
13,312 | 44,734,539 | Could someone explain me the basic tutorial of TensorFlow? | <p>I am trying to get through the second section of the first tutorial of TensorFlow:
<a href="https://www.tensorflow.org/get_started/get_started" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/get_started</a></p>
<p>"Basic Usage":</p>
<pre><code>import tensorflow as tf
# NumPy is often used to load... | <ol>
<li>Where is the tf.Graph() ot tf.Session()?</li>
</ol>
<blockquote>
<p>Tensorflow creates a default computational graphs for you. So all the
variables and operations you have defined above will be on the default
graph. Sessions are defined inside the estimator functions. For
example estimator.fit() creat... | machine-learning|tensorflow|deep-learning | 0 |
13,313 | 61,069,717 | Count a certain value for each country | <p>I am attempting to do a Excel <code>countif</code> function with <code>pandas</code> but hitting a roadblock in doing so.</p>
<p>I have this <code>dataframe</code>. I need to count the <code>YES</code> for each country quarter-wise. I have posted the requested answers below.</p>
<pre><code>result.head(3)
Country ... | <p>We can use the length of your column and take the floor division to create your quarters. Then we groupby on these and take the sum.</p>
<p>Finally to we add the prefix <code>Quarter</code>:</p>
<pre><code>df = df.set_index('Country')
grps = np.arange(len(df.columns)) // 3
dfn = (
df.join(df.eq('Yes')
... | python|pandas | 3 |
13,314 | 71,473,523 | Aggregating Values using Date Ranges in Another Dataframe | <p>I need to sum all values from <code>maindata</code> using <code>master_records</code>. Many values for <code>ids</code> will not get summed even if there are <code>timestamp</code>s and values for these columns.</p>
<pre><code>import pandas as pd
#Proxy reference dataframe
master_records = [['site a', '2021-03-05 ... | <p>The "id"s don't match; so first we create a column in both DataFrames to get a matching ID; then <code>merge</code> on the matching "id"s; then filter the merged DataFrame on the rows where the timestamps are between "start" and "end". Finally <code>groupby</code> + <code>sum<... | python|pandas|dataframe|pandas-groupby|pandas-merge | 3 |
13,315 | 71,658,101 | How to reshape a Pivot Table? | <p>I am trying to "reshape" a pivot table:</p>
<p><a href="https://i.stack.imgur.com/kgL6G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kgL6G.png" alt="enter image description here" /></a></p>
<p>I would like to remove those MultiIndex:</p>
<p><a href="https://i.stack.imgur.com/5bCQc.png... | <p>Try:</p>
<pre><code>brincando3 = df4.pivot_table('OCCUPANCY %', 'NAME', 'NEW_TIME', aggfunc='median') \
.rename_axis(columns=None)
</code></pre>
<ol>
<li><p>Don't use <code>['OCCUPANCY %']</code> if you don't want an outer level, prefer <code>'OCCUPANCY %'</code> if you have only one variable to pivo... | pandas|pivot-table|reshape | 1 |
13,316 | 71,550,448 | convert an horizental dataframe to vertical one | <pre><code>i have a dataframe looks like this :
Time A B C D
01-05-2021 00:00:00 11 10 5 5
01-05-2021 00:15:00 5 3 4 5
01-05-2021 00:30:00 8 3 3 7
01-05-2021 00:45:00 6 4 4 5
</code></pre>
<p>and i want to convert it to something like that :</p>
<pre><code> Time ... | <p>This should work, supposing that 'Time' is your index:</p>
<pre><code>df = pd.melt(df)
</code></pre> | python|pandas|dataframe | 0 |
13,317 | 42,196,007 | error happened during using TensorArray and while_loop to do dynamic rnn | <p>My intention is to do CNN (VGG16) and then push the output of it to two-layer lstm for every frame. However, error happens when I try to use sess.run(). That suggests the graph is constructed correctly. So where's my bug?
Here's the error info.</p>
<pre><code>tensorflow.python.framework.errors_impl.InvalidArgumentE... | <p>Problem solved. It seems if the VggNet is defined in the while loop, the loss has to be computed inside the loop.
Here's the changed code:</p>
<pre><code>lstm=tf.nn.rnn_cell.BasicLSTMCell(128)
cell=tf.nn.rnn_cell.MultiRNNCell([lstm]*2)
state=cell.zero_state(1, tf.float32)
inputImgA=tf.TensorArray(tf.string, length... | python|tensorflow | 1 |
13,318 | 42,465,726 | How can I calculate days between two dates separated into days per month in pandas | <p>I want to subtract dates in 'A' from dates in 'B' and get the difference of days per each month between the dates:</p>
<pre><code>df
A B
2014-01-01 2014-02-28
2014-02-03 2014-03-01
df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])
#df['A'] - df['B']
Desired Output:
============... | <p>Interesting problem, thanks for sharing. Basic idea presented here is to build a function that can iterate between the start and end dates, and return a dict with keys for year/month, and values of the number of days in that month.</p>
<p><strong>Code:</strong></p>
<pre><code>import calendar
import datetime as dt... | python|pandas|datetime | 2 |
13,319 | 69,917,781 | Python: how to vectorized insertions of values into list/np.array (with given probability)? | <p>I have very long numpy array:</p>
<pre><code>v = np.array([10, 15, 15, 15, 10, 30, 30, 10, 10])
</code></pre>
<p>And I want to insert 0s after each element with probability</p>
<pre><code>stop_prob = 0.5
</code></pre>
<p>So result could look like:</p>
<pre><code>[ 0 10 0 0 15 0 0 15 15 10 0 0 30 30 10 10 0 0... | <p>If you prepend <code>0s</code> to each element of <code>v</code> with probability <code>p = stop_prob</code> until you insert the element, then this is a sequence of <strong>independent Bernoulli trials</strong>.</p>
<p>You can model the random variable "number of 0's before each element" as a <a href="htt... | python|arrays|numpy|insert|vectorization | 2 |
13,320 | 69,822,128 | Group by year in NetworkX to calculate annual number of connections | <p>I have a dataframe of two IDs and year. IDs in the same row mean there is a connection. I want to group by year to calculate total connections for each year for an ID.</p>
<p>I used NetworkX for counting the connections to count considering only ID1 and ID2, but can't figure out how to group by year.</p>
<pre><code>... | <p>2 suggestions to modify your approach:</p>
<pre><code>def count_connects(sdf):
G = nx.from_pandas_edgelist(sdf, "ID1", "ID2")
return pd.DataFrame.from_dict(
{n: len(G[n]) for n in G.nodes}, orient="index"
)
# Version 1
df_connects = (
df.groupby("year"... | python|pandas|pandas-groupby|grouping|networkx | 1 |
13,321 | 70,014,001 | Make elements with value division by zero equal to zero in a 2D numpy array | <p>I have a code snippet:</p>
<pre><code>import numpy as np
x1 = [[1,4,2,1],
[1,1,4,5],
[0.5,0.3, 1,6],
[0.8,0.2,0.7,1]]
x2 = [[7,0,2,3],
[8,0,4,5],
[0.1,0, 2,6],
[0.1,0,0.16666667,6]]
np.true_divide(x1, x2)
</code></pre>
<p>The output is:</p>
<pre><code>array([[0.142... | <p>You can use <code>numpy.where</code> to select the values for which the division result or the original values be retained:</p>
<pre><code>import numpy as np
x1 = np.array([[1,4,2,1],
[1,1,4,5],
[0.5,0.3, 1,6],
[0.8,0.2,0.7,1]])
x2 = np.array([[7,0,2,3],
... | python|numpy|multidimensional-array|division|divide-by-zero | 2 |
13,322 | 69,785,932 | Rounding errors: deal with operation on vectors with very small components | <p>Imagine to have some vectors (could be a <code>torch</code> tensor or a <code>numpy</code> array) with a huge number of components, each one very small (~ 1e-10).</p>
<p>Let's say that we want to calculate the norm of one of these vectors (or the dot product between two of them). Also using a <code>float64</code> da... | <p>You are dealing with two different issues here:</p>
<h2>Underflow / Overflow</h2>
<p>Calculating the norm of very small values may underflow to zero when you calculate the square. Large values may overflow to infinity. This can be solved by using a stable norm algorithm.
A simple way to deal with this is to scale th... | python|arrays|numpy|torch|arbitrary-precision | 2 |
13,323 | 72,423,063 | how to create basic level DataFrame by using dictionary | <p>I have a DataFrame like this</p>
<p><a href="https://i.stack.imgur.com/Y5smP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y5smP.png" alt="enter image description here" /></a></p>
<p>but I want to create DataFrame like this ;</p>
<p><a href="https://i.stack.imgur.com/4aXuv.png" rel="nofollow nor... | <p>Try this</p>
<pre class="lang-py prettyprint-override"><code>df = df.set_index('department_name')
# add salary as level=0 column name
df.columns = pd.MultiIndex.from_product([['salary'], df.columns])
</code></pre> | pandas|dataframe | 0 |
13,324 | 50,359,442 | Apply a method from a list of methods to pandas dataframe | <p>this is my first question here so please be patient with me.</p>
<p>My problem is as follows:</p>
<p>Assume we have a pandas Dataframe and we want to apply dynamically some pd.Series methods to a set of columns of this Dataframe. Why the following example doesn't work?</p>
<pre><code>testframe=pd.DataFrame.from_d... | <p>Your syntax for calling a method is incorrect. There are 2 ways you can call a method in Python.</p>
<p><strong>Direct</strong></p>
<p>As you found, this will work. Note that <code>astype</code> isn't referencing some other object, it's the <em>actual name</em> of the method belonging to <code>pd.Series</code>.</p... | python|python-3.x|pandas|functional-programming|series | 4 |
13,325 | 50,269,445 | Units and inputShape in TensorFlowJS | <p>I'm new to TensorflowJS and ML. In the API Reference, the following code is <a href="https://js.tensorflow.org/api/0.10.0/#sequential" rel="nofollow noreferrer">there</a>.</p>
<pre><code>const model = tf.sequential();
// First layer must have an input shape defined.
model.add(tf.layers.dense({units: 32, inputShape... | <blockquote>
<p>What is <code>inputShape</code> ?</p>
</blockquote>
<p>It's an array which contains the dimensions of the tensor, which is used as input when running the neural net.</p>
<blockquote>
<p>What is the automatic shape?</p>
</blockquote>
<p>It just uses the output shape of the layer before. In this ca... | javascript|tensorflow|tensorflow.js | 2 |
13,326 | 45,653,910 | Sum of frequency of words in a dataframe derived from a list | <p>I have column of data that contains text and a list of individual words that I want to match with the text column and sum the number of times the words appear in each row of the column. </p>
<p>Here's an example:</p>
<pre><code>wordlist = ['alaska', 'france', 'italy']
test = pd.read_csv('vacation text.csv')
test.... | <p>One way would be using <code>str.count</code></p>
<pre><code>In [792]: test['Text'].str.count('|'.join(wordlist))
Out[792]:
0 2
1 1
2 0
3 3
Name: Text, dtype: int64
</code></pre>
<p>Another way, <code>sum</code> of individual word counts</p>
<pre><code>In [802]: pd.DataFrame({w:test['Text'].str.count(... | python|pandas | 2 |
13,327 | 45,360,476 | How can I merge two dataframes of dissimilar size and preserve their column order? | <p>Consider the dataframes</p>
<p>A:</p>
<pre><code>g N a
1 3 5
2 4 6
</code></pre>
<p>and B:</p>
<pre><code>g N a e
3 3 4 7
4 9 1 8
</code></pre>
<p>Is there some way to merge these such that the resultant dataframe is:</p>
<pre><code>g N a e
1 3 5 NaN
2 ... | <p>Use <code>reindex_axis</code>:</p>
<pre><code>pd.concat([A,B]).reindex_axis(B.columns, axis=1)
</code></pre>
<p>Output:</p>
<pre><code> g N a e
0 1 3 5 NaN
1 2 4 6 NaN
0 3 3 4 7.0
1 4 9 1 8.0
</code></pre> | python|pandas|dataframe | 5 |
13,328 | 45,581,400 | Tensorflow A3C implementation with shared statistics optimizer | <p>Is there opensource <code>Tensorflow</code>-based implementation of A3C reinforcement learning algorithm that utilizes optimizer with shared statistics, as in original paper?</p>
<p>*I'm aware of <code>PyTorch</code> and <code>Chainer</code> versions of A3C with shared RMSProp stats. but failed to find TF one. </p>... | <p>Miyosuda's A3C implementation (found at <a href="https://github.com/miyosuda/async_deep_reinforce" rel="nofollow noreferrer">https://github.com/miyosuda/async_deep_reinforce</a>) utilizes shared RMSProp stats over the training threads.</p>
<p>Further reference at <a href="https://github.com/miyosuda/async_deep_rein... | asynchronous|tensorflow|reinforcement-learning | 0 |
13,329 | 45,620,903 | Grouping by each value in a column of a dataframe in python | <p>I have a dataframe with 7 columns, as follows:</p>
<pre><code>Bank Name | Number | Firstname | Lastname | ID | Date1 | Date2
B1 | 1 | ABC | EFG | 12 | Somedate | Somedate
B2 | 2 | ABC | EFG | 12 | Somedate | Somedate
B1 | 1 | DEF | EFG | 12 | S... | <p>Using <code>apply</code> you could do</p>
<pre><code>In [117]: cols = ['BankName', 'Number', 'Firstname', 'Lastname']
In [126]: df.groupby('ID')[cols].nunique().apply(tuple, axis=1)
Out[126]:
ID
12 (2, 2, 2, 1)
13 (3, 3, 2, 3)
dtype: object
</code></pre>
<p>or, </p>
<pre><code>In [127]: df.groupby('ID').a... | python|pandas|dataframe|pandas-loc | 2 |
13,330 | 45,363,586 | Pandas: change values in group to minimum | <p>What I have:</p>
<pre><code>df = pd.DataFrame({'SERIES1':['A','A','A','A','A','A','B','B','B','B','B','B','B','B','C','C','C','C','C'],
'SERIES2':[1,1,1,1,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1],
'SERIES3':[10,12,20,10,12,4,8,8,1,10,12,12,13,13,9,8,7,7,7]})
SERIES1 SERIES2 SERIES3... | <p>You can use <code>groupby.transform</code>, which gives back a same length series that you can assign back to the data frame:</p>
<pre><code>df['SERIES3'] = df.groupby(['SERIES1', 'SERIES2']).SERIES3.transform('min')
df
</code></pre>
<p><a href="https://i.stack.imgur.com/R8XWB.png" rel="nofollow noreferrer"><img s... | python|pandas|dataframe|group-by | 1 |
13,331 | 45,310,816 | Numpy match indexing dimensions | <h1>Problem</h1>
<p>I have two numpy arrays, <code>A</code> and <code>indices</code>. </p>
<p><code>A</code> has dimensions m x n x 10000.
<code>indices</code> has dimensions m x n x 5 (output from <code>argpartition(A, 5)[:,:,:5]</code>).
I would like to get a m x n x 5 array containing the elements of <code>A</co... | <p>You can use <a href="https://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer"><code>advanced-indexing</code></a> -</p>
<pre><code>m,n = A.shape[:2]
out = A[np.arange(m)[:,None,None],np.arange(n)[:,None],indices]
</code></pre>
<p>Sample run -</p>
<pre><cod... | python|arrays|numpy|indexing | 5 |
13,332 | 62,721,271 | IF Statement in Pandas: Using values from one column (A) to select values from different columns (B or C) an store it in one separate column (D) | <p>My question is: How can I simplify my table with Pandas, to get only one column with the selected values (the three columns should be one).</p>
<pre><code>Name Selection Active Inactive
A active 0 0.9
B active 1 0.8
C inactive 2 0.7
D inactive 3 0... | <p>The code below should provide you with what you are looking for.</p>
<pre><code>df.loc[df['Selection'] == 'active','Selected_Value'] = df['Active']
df.loc[df['Selection'] == 'unactive','Selected_Value'] = df['Unactive']
</code></pre> | python|pandas|if-statement|selection | 1 |
13,333 | 62,684,750 | Importing whatsapp text file within a new dataframe | <p>I am trying to import and analyse a whatsapp chat (only one file/conversation). I am following this article to do it:</p>
<p>My data looks like as follows:</p>
<pre><code>[28/07/2018, 01:39:21] User1: \u200eMessages to this chat and calls are now secured with end-to-end encryption.\n\u200e[28/07/2018, 01:39:21] Mart... | <p>So it looks like you have a specific issue in your pattern, I'm not seeing the date format accounted for anywhere in there.</p>
<p>For simplicity, since each message is a line, start with splitting by line.
Then apply your regex there, or even more simply, you could <code>partition</code> on <code>]</code>, that'd g... | python|regex|pandas | 0 |
13,334 | 62,569,117 | Finding the mean of consecutive columns | <p>I have a very large data file (tens of thousands of rows and columns) formatted similarly to this.</p>
<pre><code>name x y gh_00hr_bio_rep1 gh_00hr_bio_rep2 gh_00hr_bio_rep3 gh_06hr_bio_rep1
gene1 x y 2 3 2 1
gene2 x y 5 7 6... | <p>I would first build a Series of final names indexed by the original columns:</p>
<pre><code>names = pd.Series(['_'.join(i.split('_')[:-1]) for i in df.columns[3:]],
index = df.columns[3:])
</code></pre>
<p>I would then use it to ask a mean of a groupby on axis 1:</p>
<pre><code>tmp = df.iloc[:, 3:]... | python|pandas|mean|rolling-computation | 1 |
13,335 | 62,589,257 | How to implement mode-k product Python for Tacker decomposition? | <p>I am trying to do Tacker decomposition in python.
I refer <a href="https://www.alexejgossmann.com/tensor_decomposition_tucker/" rel="nofollow noreferrer">this page</a>.</p>
<p>I would like to implement mode-k product in Python using NumPy. According to the above web page, I have to do mode-k product.</p>
<p>I write ... | <p>This is the answer.</p>
<pre><code>def mode_n_product(x, m, mode):
x = np.asarray(x)
m = np.asarray(m)
if mode <= 0 or mode % 1 != 0:
raise ValueError('`mode` must be a positive interger')
if x.ndim < mode:
raise ValueError('Invalid shape of X for mode = {}: {}'.format(mode, x.shape))... | python|numpy|tensor | 0 |
13,336 | 62,550,011 | Python: Counting Zeros in multiple array columns and store them efficently | <p>I create an array:</p>
<pre><code>import numpy as np
arr = [[0, 2, 3], [0, 1, 0], [0, 0, 1]]
arr = np.array(arr)
</code></pre>
<p>Now I count every zero per column and store it in a variable:</p>
<pre><code>a = np.count_nonzero(arr[:,0]==0)
b = np.count_nonzero(arr[:,1]==0)
c = np.count_nonzero(arr[:,2]==0)
</code><... | <p>You can construct a boolean array <code>arr == 0</code> and then take its sum along the rows.</p>
<pre><code>>>> (arr == 0).sum(0)
array([3, 1, 1])
</code></pre> | python|arrays|numpy|dictionary|counting | 5 |
13,337 | 62,839,226 | pandas: create a column of comma separated value based on the len of strings in another cloumn | <p>I have a dataframe like the following:</p>
<pre><code>df = {"text":["see you in five minutes", "she is my friend", "she goes to school in five minutes","he is my friend"]}
</code></pre>
<p>and I would like to create another column of comma separated repeated value ba... | <p>try this,</p>
<pre><code>df['new_text'] = (
df.text.str.split().str.len()
.apply(lambda x: x * ['s']).str.join(',')
)
</code></pre>
<hr>
<pre><code> text new_text
0 see you in five minutes s,s,s,s,s
1 she is my friend s,s,s,... | python|pandas|list | 3 |
13,338 | 54,664,217 | Hourly time series data in data frame: calculate total data per day | <p>I have hourly time series data in data frame I want to calculate total data per day in python.</p>
<p>I have tried resampling the data by mean on daily basis. But the problem is, it gives the mean data on daily basis but not the total count of the data on particular day</p>
<pre><code>df2=df.reset_index().set_inde... | <pre><code>df2=df.reset_index().set_index('date').resample('1D').sum()
</code></pre>
<p>Instead of using mean(), you can use sum() as the agg function.</p> | python|pandas|dataframe | 0 |
13,339 | 73,840,203 | How to calculate f1 score during evaluation on test set? | <p>I am trying to calculate the f1 score during evaluation of my own test set but i'm not able to solve as I am very unexperienced. I've tried to use both f1 score from Scikit-Learn and from torchmetrics but they give me everytime different errors.
This is my code:</p>
<pre><code># Function to test the model
from skle... | <p>The error trace should be available in order to spot the problem but I guess the problem is due to passing a nested list to <code>f1_score</code> instead of a single list. It must be fixed by changing the collecting strategy of the final lists.</p>
<pre><code># Iterate over data.
y_true, y_pred = [], []
with torch.n... | python|pytorch|metrics | 0 |
13,340 | 73,837,017 | Convert column data to row wise data | <p>I have a dataframe as shown below,</p>
<p><a href="https://i.stack.imgur.com/6GemN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6GemN.png" alt="dataframe" /></a></p>
<p>data_dict =
{'CustCode': {0: 64, 1: 64, 2: 97, 3: 97, 4: 97, 5: 97, 6: 97, 7: 97, 8: 97, 9: 110},
'InvoiceMonth': {0: 'Aug', 1... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>df = df.pivot(index="CustCode", columns="InvoiceMonth", values="TotalAmount")
months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul&... | python|pandas|dataframe|group-by | 1 |
13,341 | 71,374,710 | Python pandas - define and apply a function inline | <p>Let say I have below code</p>
<pre><code>import pandas as pd
def calc(df, var1, var2) :
return (df[var1] * df[var2]).sum()
Dat = pd.DataFrame({'product_name': ['laptop', 'printer', 'printer', 'printer', 'laptop', 'printer'], 'price': [1200, 150, 1200, 150, 1200, 150], 'price1': [1200, 150, 1200, 150, 1200, 15... | <p>You can use <code>lambda</code> function: <a href="https://www.w3schools.com/python/python_lambda.asp" rel="nofollow noreferrer">https://www.w3schools.com/python/python_lambda.asp</a></p>
<pre class="lang-py prettyprint-override"><code>Dat.groupby(['product_name']).apply(lambda df: (df['price'] * df['price1']).sum()... | python-3.x|pandas | 0 |
13,342 | 71,243,552 | How can I change my plot so that my major axis is every 12 months rather than every 20 months? | <p>I am trying to plot temperatures from January 2010 to December 2019. I am using the Pandas dataframe. I've been able to plot my data fine, it looks like this:</p>
<p><a href="https://i.stack.imgur.com/54ycy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/54ycy.png" alt="Line plot showing monthly t... | <p>The trick is to suppress default x-axis behavior of <code>pandas</code> with <code>x_compat=True</code></p>
<pre><code>import math
import pandas as pd
from matplotlib.dates import MonthLocator, DateFormatter
# Data
df = pd.DataFrame({"datetime": pd.date_range("2010-01-01", "2018-08-31"... | python|pandas|plot|xticks | 1 |
13,343 | 71,373,425 | Change the column name index with pandas | <p>I have a df, and when I run df.columns, I get the result in the screenshot I am attaching. I do not understand what is the result in red referring to. Furthermore, I would like to have no "name".</p>
<p><a href="https://i.stack.imgur.com/QHHcW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rename_axis.html" rel="nofollow noreferrer"><code>rename_axis</code></a>:</p>
<pre><code>ri_2 = ri_2.rename_axis(None, axis=1)
</code></pre> | python|pandas | 3 |
13,344 | 52,176,385 | Why is the behavior different for count and unique different for GroupBy objects? | <p>I have the following csv file:</p>
<pre><code>col_1,col_2
foo,1
foo,1
bar,1
bar,2
baz,1
baz,1
baz,2
baz,2
qux,1
qux,2
qux,3
</code></pre>
<p>And the following code (together with the outputs)</p>
<pre><code>print(df.groupby('col_1').count())
# col_2
# col_1
# bar 2
# baz 4
# foo 2
# qu... | <p><code>count</code> & <code>nunique</code> are different functions and do different things.</p>
<p>Documentation links for further reading:</p>
<ul>
<li><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.count.html" rel="nofollow noreferrer">count</a></li>
<li><a href="https://pand... | pandas | 1 |
13,345 | 60,651,882 | error regarding change in datatype in jupyter | <p>I have a dataframe which contains a string instead of nan values and whenever i try to drop rows containing it, it gives an error with the label:</p>
<pre><code>KeyError: 'SALE PRICE'
</code></pre>
<p>where, "SALE PRICE" is the column containing those values, I am trying to create a decision tree for the data plea... | <p>The approach that you're trying to use won't work, I'll explain what your code is doing:</p>
<pre><code>y = df["SALE PRICE"]
</code></pre>
<p>This line uses the selects the column <code>"SALE PRICE"</code> from your dataframe called <code>df</code> and sets it to the variable <code>y</code>. Note that the object r... | python-3.x|pandas|dataframe | 0 |
13,346 | 60,426,639 | Unable convert the data time of this column (object to time) | <p>I have a data frame data types like below</p>
<pre><code> usr_id year
0 t961 00:50:03.158000
1 t964 03:25:57
2 t335 00:55:00
3 t829 00:04:25.714000
usr_id object
year object
dtype: object
</code></pre>
<p>I want to convert the year column data type to a datetime. I used the below ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>Series.dt.strftime</code></a>:... | python|pandas|dataframe|datetime|python-datetime | 3 |
13,347 | 60,666,925 | pandas.errors.ParserError: Error tokenizing data. C error: Calling read(nbytes) on source failed. Try engine='python' | <p>I was trying to generate tf record from csv file for doing object detection using tensorflow object detection API. Below is the code that I used:</p>
<pre><code>from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import io
import pandas as pd
from P... | <p>I got the same error when I accidentally switch the arguments like below</p>
<pre><code>python generate_tfrecord.py --image_dir=CrowdHumanTrain --csv_input=crowd_human_train_anno.csv --output_path=ch_train.record --label "head"
</code></pre>
<p>I have provided the directory path to CSV path and wise versa.</p>
<p... | python-3.x|pandas|tensorflow | 0 |
13,348 | 60,527,036 | Pytorch - select region of a tensor using torch function | <p>I am looking for a way to select a region of a PyTorch tensor using a torch function (without using numpy). Do you have suggestions on how to proceed? </p>
<p>In other words, I'm looking for a way to crop a region of a matrix. Using numpy, it would be something like</p>
<pre><code>import numpy as np
A = np.random.... | <p>What's wrong with regular slicing?</p>
<pre class="lang-py prettyprint-override"><code>import torch
A = torch.randn([1,3,64,64])
B = A[..., 16:32, 16:32]
</code></pre> | python|pytorch | 1 |
13,349 | 72,713,816 | Is it against privacy of clients if I have a global tokenizer in Federated Learning (TFF)? | <p>I am currently stuck in a dead end. I am trying to make an image caption generator from a federated approach. My initial idea was to have a different tokenizer for each client. That poses these issues however:</p>
<ol>
<li><p>Every client will have a different sized vocabulary, and thus a
different shape of y, which... | <p>It depends. In Federated Learning if everyone has the same of some value it could be thought of as <em>public</em> information. Global vocabulary definitions could fit this criteria.</p>
<p>For example we can take the <a href="https://www.tensorflow.org/federated/api_docs/python/tff/federated_broadcast" rel="nofollo... | tensorflow|nlp|tensorflow-federated|federated-learning | 1 |
13,350 | 72,522,908 | DCN recommender system recommend function | <p>I am working on a recommender system using DCN, following this tutorial <a href="https://www.tensorflow.org/recommenders/examples/dcn" rel="nofollow noreferrer">https://www.tensorflow.org/recommenders/examples/dcn</a></p>
<p>But his tutorial lacks the recommend function, which I can pass the user_id and command, it ... | <p>I have used the dcn model for a custom dataset but followed the tutorial.</p>
<p>Following is the model training code (<em>copy pasted from the dcn tutorial</em>):</p>
<pre><code>dcn_result = run_models(use_cross_layer=True,
deep_layer_sizes=[192, 192])
def run_models(use_cross_layer, deep_... | tensorflow|recommendation-system | 0 |
13,351 | 72,622,273 | Filtering a numpy array with np.where and a condition containing another numpy array of different shape | <p>I have two ndarrays of different shape.
X.shape = (112800, 28, 28)
Y.shape = (112800,)</p>
<p>X is an array of 28x28 grayscale pictures of handwritten numbers and letters (from the enmist balanced dataset)
Y is the array which holds the corresponding labels / classifications for all those pictures in X (values rangi... | <p>This can be easily done without <code>np.where</code> and simply using a boolean array, that I call <code>idx_hex</code>. This array contains True and False, it contains True where Y < 16 and False where Y >= 16.</p>
<pre class="lang-py prettyprint-override"><code>idx_hex = Y < 16
Y_hex = Y[idx_hex]
X_hex =... | python|arrays|numpy | 0 |
13,352 | 72,812,755 | How to unstack unique column values to columns and set another column as row index in Python Pandas | <p>I have a table as given below.</p>
<p><a href="https://i.stack.imgur.com/5CM7B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5CM7B.png" alt="enter image description here" /></a></p>
<p>I am trying to rearrange the table in a certain manner so that I have the unique values of the column 'Metric C... | <p>Add column <code>Participant</code> to <code>MultiIndex</code>:</p>
<pre><code>df2.set_index(['Participant',df2.groupby(['Metric_Category'])['Metric_Category'].cumcount(), 'Metric_Category'])['Response'].unstack()
</code></pre> | python|pandas|dataframe|pivot|pandas-groupby | 1 |
13,353 | 59,864,775 | Convert Columns to row values where column+row is True | <p>I have a dataset that appears as follows:</p>
<pre><code> key f1 f2 f3 f4 f5
0 001 A B True False False
1 002 C D False True False
2 003 A D False True False
3 004 C B False False True
</code></pre>
<p>And I'd like to use pandas to convert the above to:</p>... | <p>One way is to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dot.html" rel="nofollow noreferrer"><code>Dataframe.dot</code></a>:</p>
<pre><code>t = df.loc[:,'f3':]
df['state'] = t.dot(t.columns)
</code></pre>
<hr>
<pre><code>print(df.drop(t.columns, axis=1))
key f1 f2... | python|python-3.x|pandas|numpy | 3 |
13,354 | 59,631,507 | Is there a way to add condition to cumsum without "cutting" my table? | <p>I found the code to calculate a YTD (year to date) value (basically a <strong>cumulative sum</strong> applied to a <strong>group by</strong> function passed on "year").
But now, I want this cumulative sum only for when the "<strong>Type</strong>" column is "Actual" and not "Budget". I'd like to have either empty spa... | <p>With <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> we select only the rows where <code>Type = Actual</code> and we assign our <code>cumsum</code> to our new column <code>YTD</code>.</p>
<p>Then we fill our gaps of ... | python|pandas | 0 |
13,355 | 59,707,946 | Merging Latitude and Longitude from separate columns in a Dataframe then use haversine for distance | <p>I'm doing the New York taxi problem from Kaggle for practice. The taxi pickup and dropoff points are given as four columns in the dataframe: pickup_latitude, pickup_longitude, dropoff_latitude, dropoff_longitude. I want to make the pickup lat and long into one and the same for dropoff, so that I can use them in a ha... | <p>Something like that:</p>
<pre><code>df["long_lat"] = list(zip(df["pickup_longitude"], df["pickup_latitude"]))
</code></pre>
<p>Also you could use geopandas:</p>
<pre><code>from shapely.geometry import Point
from geopandas import GeoDataFrame
geometry = [Point(xy) for xy in zip(df["pickup_longitude"], df["pickup_... | python|pandas|dataframe|merge|haversine | 1 |
13,356 | 61,880,247 | Does Huggingface's T5 Model Vocabulary include English-only version? | <p>Does anyone know if HuggingFace's T5 model (small) comes with mono-language vocabulary? The T5 paper by Google indicates that their vocabulary is trained on English and 3 other languages. Is there a version of this vocabulary that contains English only vocabulary? </p> | <p>When looking at the publicly available <a href="https://s3.amazonaws.com/models.huggingface.co/bert/t5-small-config.json" rel="nofollow noreferrer">model card definition</a>, the HuggingFace T5-small also seems to contain the necessary translation tasks, which makes it a multi-lingual model. Note that the summarizat... | huggingface-transformers | 0 |
13,357 | 62,000,679 | python panda count occurence in matrice column | <p>I wouldike to display at the end with the number of value "Présent". Here an image to describe what I want : <a href="https://i.stack.imgur.com/lhwbz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lhwbz.png" alt="Example"></a></p>
<p>I use panda to display this matrice and this structure :</p>
... | <p>Compare values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a>, count <code>True</code>s by <code>sum</code> and last convert to integers with assign to new row by <a href="http://pandas.pydata.org/pandas-docs/sta... | python|pandas | 1 |
13,358 | 58,007,782 | Measuring performance for keras model being trained in batches | <p>I have a keras model which i am trying to train with a large dataset in chunks</p>
<pre class="lang-py prettyprint-override"><code>for chunk in pd.read_csv(input_file, chunksize=chunk_size, usecols = FEATURE_COLUMNS, low_memory = False):
(X_train, y_train, X_val, y_val,full_pipeline) = dataPrep.get_data(dat... | <p>Hi there writing my suggestion here because I'm not able to comment...</p>
<p>correct me if I'm wrong but you could just get the f1-score after every chunk and then after the training is done you could get the mean of the gathered f1-scores.</p>
<p>Alernatively you also could get the recall and precision for every c... | python|pandas|validation|keras|deep-learning | -1 |
13,359 | 54,799,650 | Selecting second dim of tensor using an index tensor | <p>I have a 2D tensor and an index tensor. The 2D tensor has a batch dimension, and a dimension with 3 values. I have an index tensor that selects exactly 1 element of the 3 values. What is the "best" way to product a slice containing just the elements in the index tensor?</p>
<pre><code>t = torch.tensor([[1,2,3], ... | <p>An example of the answer is as follows.</p>
<pre class="lang-python prettyprint-override"><code>import torch
t = torch.tensor([[1,2,3], [4,5,6], [7,8,9]])
col_i = [0, 0, 1]
row_i = range(3)
print(t[row_i, col_i])
# tensor([1, 4, 8])
</code></pre> | pytorch | 2 |
13,360 | 55,062,886 | convert cv2.umat to numpy array | <p>Processed_image() function returns a cv2.Umat type value which is to be reshaped from
3 dimensions<code>(h, ch, w)</code> to 4 dimensions<code>(h, ch, w, 1)</code> so <code>i</code> need it to be converted
to numpy array or also if possible help me to directally rehshape <code>cv2.umat</code>
type variable to be ... | <p>I didn't quite catch your question, but you can get numpy data of an opencv's umat with "get()" like <a href="https://github.com/opencv/opencv/blob/fecebea2e38a97a15219219e3e1ad8cf680e9e2b/modules/python/test/test_umat.py#L36" rel="nofollow noreferrer">this</a></p>
<p>and you should probably <a href="https://pytorc... | python|numpy|opencv|computer-vision|pytorch | 5 |
13,361 | 55,060,196 | Handle UL Tags in Web Scraping, Python 3.6 | <p>I want to scrpe "Table:" & "Release date: " from the URL: <a href="https://www150.statcan.gc.ca/n1/en/type/data?geoname=A0002&p=0#" rel="nofollow noreferrer">https://www150.statcan.gc.ca/n1/en/type/data?geoname=A0002&p=0#</a></p>
<p>I am using salenium web driver to scrape</p>
<p>Below is the tags pres... | <p>You can use an nth-of-type selector. This is based on:</p>
<blockquote>
<p>I want to scrape "Table:" & "Release date: " from the URL</p>
</blockquote>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.we... | python-3.x|pandas|web-scraping|beautifulsoup | 1 |
13,362 | 49,416,430 | Tensorflow gather_nd over input with varied shape | <p>I need to extract the the sub tensors along <code>axis=1</code> based on the value from another tensor.</p>
<pre class="lang-py prettyprint-override"><code>state = tf.placeholder(shape=[None, None, 10], dtype=tf.float32)
length = tf.placeholder(shape=[None], dtype=tf.int32)
# this won't work, just be put here to d... | <p>I realized this is actually solved by Tensorflow's higher order function.</p>
<pre><code>tf.map_fn(lambda x: x[0][x[1], :], (state, length), dtype=tf.float32)
</code></pre> | python|tensorflow|tensor | 0 |
13,363 | 49,493,911 | Combining two lists of identifiers into a single column with Pandas | <p>I'm new to using Pandas and I'm currently trying to clean up one of my dataframes so I can merge/join with another dataframe based on a shared ID. The problem is that one of my dataframes has multiple ID columns that may both include lists of IDs, all of which are valid.</p>
<p>I am trying to put each ID on a uniqu... | <p>IIUC, string unnesting</p>
<pre><code>data=data.fillna('')
data['ID']=data.ID1.str.split(',')+data.ID2.str.split(',')
data.set_index(['Age','Name']).ID.apply(pd.Series).replace('',np.nan).stack().drop_duplicates().reset_index().drop('level_2',1)
Out[560]:
Age Name 0
0 50 Bob 1
1 50 Bob 2
2 50 Bo... | python|pandas | 0 |
13,364 | 49,428,015 | Keeping rows based on conditions(Pandas) | <p>I have a dataFrame:</p>
<pre><code>df.head()
Out[374]:
ID Time op1
0 1 1 -0.0007
1 1 2 0.0019
2 1 3 -0.0043
3 1 4 0.0007
4 1 5 -0.0019
</code></pre>
<p>ID runs from 1 to 100.
I have a list difference:</p>
<pre><code>difference
Out[375]:
[161,
... | <p>I believe you need create dictionary for <code>map</code> with <code>enumerate</code>, compare with <code>Time</code> column and filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>print (df)
ID... | python|pandas|loops | 2 |
13,365 | 49,781,923 | Right way to normalize multiple input and output data | <p>I want to predict temperature with a LSTM using the following inputs:</p>
<blockquote>
<p>Temperature,
Pressure,
Windspeed</p>
</blockquote>
<p>My output is:</p>
<blockquote>
<p>Temperature</p>
</blockquote>
<p>What is the best way to normalize the input data?
Should i just min max scale all of the 3 inp... | <p>Each input separately to zero-mean, unit-norm and same for the output.
The effects of normalization and its importance are argued in section 4.3 of the now-famous <a href="http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf" rel="nofollow noreferrer">Efficient Backpropagation</a>.</p> | python|tensorflow|machine-learning|neural-network | 0 |
13,366 | 49,764,019 | Can't import meta graph with op for MaxBytesInUse | <p>When I try to import a meta graph using <code>saver = tf.train.import_meta_graph(meta_graph_path, clear_devices=True)</code> I get KeyError: 'MaxBytesInUse' from within the importer. </p>
<p>Tensorflow version: 1.7-gpu-python3
OS: Ubuntu 16.04</p>
<p>Here is the stack trace of the error:</p>
<pre><code>/usr/local... | <p>Add <code>dir(tf.contrib)</code></p>
<p>See the link: <a href="https://github.com/tensorflow/tensorflow/issues/10130" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/10130</a></p> | tensorflow | 1 |
13,367 | 73,448,001 | merging data frames without deleting unique values (Python) | <p>I have what seems like a simple problem but I can figure out how to do it...</p>
<p>I have 3 Dataframes.</p>
<pre><code>df1 : 1 column, Product SKU
df2 : 2 Columns, Product SKU, Price(supplier 1)
df3 : 2 Columns, Product SKU, Price( Supplier 2)
</code></pre>
<p>I need to create a df4.</p>
<pre><code>df4 : 3 Column... | <p>USE - <code>df4 = df2.merge(df3, on="Product_SKU", how = 'outer')</code></p>
<p>Code-</p>
<p>I Created random dataframe <code>df4</code> it contains all unique <code>Product_SKU</code> and some rows will contain <code>NaN</code> values as it's price is not present in <code>df2</code> or <code>df3</code>.</... | python|pandas|dataframe | 0 |
13,368 | 73,226,480 | Tensorflow: How to load an object detection model and viewing the model's architecture? | <p>I am trying to load a object detection model and viewing the architecture because I need to know what my input and output layers are in order to convert the model format to a different format.</p>
<p>Right now, I am trying to do:</p>
<pre><code>model = tf.saved_model.load('/content/drive/MyDrive/my_ssd_mobnet_640x64... | <p>According to the <a href="https://www.tensorflow.org/guide/keras/save_and_serialize#savedmodel_format" rel="nofollow noreferrer">documentation</a>, you should load the model as keras model, like this:</p>
<pre><code>model = keras.models.load_model("my/path/saved_model")
</code></pre>
<p>The <code>.pb</code... | tensorflow|object-detection | 0 |
13,369 | 73,274,060 | Hooking setting of a value on a numpy array | <p>It is straight forward to hook direct setting of an attribute on a class.</p>
<pre><code>class A(object):
def __setattr__(self, key, value):
print(f'__setattr__: {key} = {value}')
super(A, self).__setattr__(key, value)
def __getattribute__(self, key):
pr... | <p>What class <code>A</code> stores is not the object itself, but a reference to the array. As such, when you set the index 2 of <code>attribute</code> to 5, you're not actually editing <code>a.attribute</code>, so that no call to <code>__setattribute__</code> is performed. What <code>A</code> objects does in this case... | python|python-3.x|numpy | 0 |
13,370 | 73,407,428 | How to select the first valid rows in a pandas dataframe? | <p>I have <code>pd.DataFrame</code> with time series as index:</p>
<pre><code> a b
2018-01-02 12:30:00+00:00 NaN NaN
2018-01-02 13:45:00+00:00 NaN 232.0
2018-01-02 14:00:00+00:00 133.0 133.0
2018-01-02 14:15:00+00:00 134.0 134.0
</code></pre>
<p>I am interested in preser... | <p>You can try <code>apply</code> <code>Series.first_valid_index</code> per column and mask the other rows with nan</p>
<pre class="lang-py prettyprint-override"><code>df[df.apply(lambda col: col.index != col.first_valid_index())] = np.nan
</code></pre>
<pre><code>print(df)
a b
2018... | python|pandas|dataframe | 3 |
13,371 | 67,414,377 | Does dissecting a Pytorch model lower memory usage? | <p>Suppose I have a Pytorch autoencoder model defined as:</p>
<pre><code>class ae(torch.nn.Module):
def __init__(self, z_dim, n_channel=3, size_=8):
super(ae, self).__init__()
self.encoder = Encoder()
self.decoder = Decoder()
def forward(self, x):
z = self.encoder(x)
x_reconstr... | <blockquote>
<p>is it possible that the code can run on lower ram/gpu-memory?</p>
</blockquote>
<p>The way you created it right now no, it isn't. If you instantiate it and move to device, something along those lines:</p>
<pre><code>encoder = ...
decoder = ...
autoencoder = ae(encoder, decoder).to("cuda")
</co... | machine-learning|pytorch | 1 |
13,372 | 60,301,705 | python: subsetting and renaming columns by name in list of dataframes | <p>I have a list of dataframes, all with the same columns. I wish to first select a subset of the columns and then rename the columns.</p>
<p>I have a list of columns on which to subset</p>
<pre><code>rename_cols_list = ['Portfolio', 'CalendarYear', 'Count']
</code></pre>
<p>and apply a dictionary to change the col... | <p>You are juut resetting the loop variable in your loop to a new dataframe, not actually updating the list (think references/pointers). The easiest solution is to use the <code>inplace</code> flag:</p>
<pre><code>for df in base_df:
df[rename_cols_list].rename(rename_cols_dict, axis='columns', inplace=True)
</code... | python|pandas|list|dataframe | 3 |
13,373 | 65,129,696 | Pandas add new column with groupby based on values in 3 different columns | <p>I have the following df:</p>
<pre><code> Document Date Schedule Quantity Key
0 123 2020-12-02 1 20 1
1 123 2020-12-02 2 10 0
2 123 2020-12-02 3 5 0
3 456 2020-12-02 4 10 0
</code></pre>
<p>I wa... | <p>Define the following function:</p>
<pre><code>def getNewCol(grp):
rv = pd.Series(0, index=grp.index)
# Quantity from row with Key == 1 (a Series)
qn = grp.query('Key == 1').Quantity
if qn.size == 0: # Nothing found
return rv
qnK1 = qn.iloc[0] # The Quantity itself
# Min Schedule fr... | python|pandas | 1 |
13,374 | 65,314,755 | numpy-thonic way to store data on already-allocated data | <p>I have a code where I have to iterate creation of several <code>GB</code> of data with <code>np.tile</code> and <code>np.repeat</code>.
After few iterations the code goes out of memory. Since each tile and repeat is used only within inside an iteration, I am thinking on how to save memory.</p>
<p>Ideally, in order t... | <ol>
<li><p>Numpy's in-place assignment is <code>large_matrix[:]=np.repeat(data,M)</code></p>
</li>
<li><p>better - encapsulate the inside of your for-loop as a function (e.g. <code>def process(data):</code>). This way, all matrices except for the returned outputs are freed when the iteration is done. If the outputs ar... | numpy|numpy-ndarray | 0 |
13,375 | 65,426,568 | Seaborn: How to temporarily replace none-numeric values in a column with a numeric values for distribution? | <p>This may sound like a strange question, but I was wondering if it's possible to temporarily replace none-numeric values in a column with numeric values, so that we can see the distribution.</p>
<p>Only because, if we use the <code>distplot</code> function, it only works for numerical values only, not none-numeric va... | <p>Consider the sample data:</p>
<pre><code>>>> import pandas as pd
>>> data = ({"Colour": [Red, Red, Blue, Red, Blue]})
>>> df = pd.DataFrame(data)
>>> df
Colour
0 Red
1 Red
2 Blue
3 Red
4 Blue
</code></pre>
<p>You can then create a <code>colour_map</code> f... | python|pandas|numpy|seaborn | 0 |
13,376 | 65,137,299 | Why I can't create two columns with different moving average windows on Pandas? | <p>I'm sincerely out of clue with this one. I've been trying to create a couple of columns from a dataframe but I get the <code>ValueError: Wrong number of items passed 2, placement implies 1 </code>. Somehow I can create one, doesn't matter if it is the window=7 or the window=14 but only allowed to create one. Here's ... | <p>When you first run <code>suspects['suspects_ma_7'] = suspects.rolling(window=7).mean()</code> you automatically transform your Series into a DataFrame.</p>
<p>So, for running the second <code>rolling</code> approach, use:</p>
<pre><code>suspects['suspects_ma_7'] = suspects.Colima.rolling(window=7).mean()
</code></pr... | python|pandas | 1 |
13,377 | 65,261,908 | Find whether an event (with a start & end time) goes beyond a certain time (e.g. 6pm) in dataframe using Python (pandas, datetime) | <p>I'm creating a Python program using pandas and datetime libraries that will calculate the pay from my casual job each week, so I can cross reference my bank statement instead of looking through payslips.
The data that I am analysing is from the Google Calendar API that is synced with my work schedule. It prints the ... | <p><strong>UPDATE: (2020-12-19)</strong></p>
<p>I have simply filtered out the <code>Start</code> rows, as you were correct an extra row wa being calculated. Also, I passed <code>dayfirst=True</code> to <code>pd.to_datetime()</code> to convert the date correctly. I have also made the output clean with some extra column... | python|pandas|datetime|time-series|google-calendar-api | 1 |
13,378 | 65,330,093 | How to change values in a column to fake values | <p>I want to change values from one column in a dataframe to fake data.</p>
<p>Here is the original table looking sample:</p>
<pre><code>df = {'Name':['David', 'David', 'David', 'Kevin', 'Kevin', 'Ann', 'Joan']
'Age':[10,10,10,12,12,15,13]}
df = pd.DataFrame(df)
df
</code></pre>
<p>Now what I want to do is to change th... | <p>Here is my suggestion. List 'fake' below has more than 23000 items, if your df has more unique values, just increase the end of the loop (currently 5) and the fake list will increase exponentially:</p>
<pre><code>import string
from itertools import combinations_with_replacement
names=df['Name'].unique()
letters=li... | python|pandas|dataframe | 1 |
13,379 | 65,102,972 | update a column and save it back to dataset in pandas | <p>I m working on a football dataset which has a few columns. There is one column called TimeUnder and the datatype of the column is int64. I want to append the unit 's' to all the values in the column and save it back to the dataset.</p>
<p>I converted the column to a string datatype and modified appending a 's' to ea... | <p>Currently, you are modifying the column and creating a separate dataframe from it and writing that to csv.</p>
<p>Instead, you need to modify the column in the original df and write it to df.</p>
<p><strong>Change this <code>football1=football['TimeUnder'].astype(str) + 's'</code> to:</strong></p>
<pre><code>footbal... | python|pandas|csv | 1 |
13,380 | 65,320,835 | Tensorflow 2.4.0 import error cannot import name 'multi_worker_mirrored_2x1_cpu' | <p>I'm getting an error upon loading tensorflow==2.4.0 in Python. I've tried uninstall and reverting to an earlier version (but still 2), but can't seem to be able to solve it. Anyone any idea? The full error is:</p>
<pre><code> File "<stdin>", line 1, in <module>
File "C:\Users\CX667CJ\Ap... | <p>0</p>
<p>I don't know but I opened the adminstrator cmd if don't know just hover over command promp and right click and you'll see the option of open in admistrator mode click over it just uninstall using pip uninstall package_name and don't close because the package_will be cached down and when you again command pi... | python-3.x|tensorflow|tensorflow2.0|importerror | 0 |
13,381 | 64,020,604 | transfer dictionary with key to df to one dataframe | <p>I have a dictionary that I am trying to transform into a single dataframe.</p>
<p>Currently is has key:dataframe system, as below.</p>
<pre><code>{'lab_location-one': water_quality titration
DateTimeStamp
2020-01-13 08:20:00 53.340000 50
2020-01-13 08:2... | <p>I think you want <code>concat</code>:</p>
<pre><code>pd.concat(df_by_intervaled_group).reset_index()
</code></pre> | python|pandas | 1 |
13,382 | 63,892,433 | (Python) Grouping intervals in pandas dataframe | <p>The dataframe consists of a lot of columns with the column 'sec_time' in seconds (type = float).
I'm trying to group the intervals and count, so I used this code:</p>
<pre><code>data.groupby(pd.cut(user_data['sec_time'],[0,60,120,180,240,300,360,420])).count()
</code></pre>
<p>The output looks something like</p>
<pr... | <p>You can add <code>inf</code> in your last bucket:</p>
<pre><code>data = pd.DataFrame({'sec_time': np.random.randint(0, 1000, 30)})
data.groupby(pd.cut(data['sec_time'],[0,60,120,180,240,300,360,420, float('inf')])).count()
</code></pre>
<pre><code> sec_time
sec_time
(0.0, 60.0] ... | python|pandas|dataframe | 1 |
13,383 | 63,770,607 | How to merge columns from multiple sheets in one excel file by pandas | <p>How to combine the columns from every sheet, using pandas?</p>
<p>I need to iterate through each sheet in one Excel file, and merge every sheet separately, like the following images.</p>
<p>I have around 1000 sheets in one file, and sheets names are not same.</p>
<p>How to do the iteration and merging?</p>
<p><img s... | <ul>
<li>It seems easiest to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html" rel="nofollow noreferrer"><code>pandas.read_excel</code></a> with <code>sheet_name=None</code>.
<ul>
<li>Specify <code>None</code> to get all sheets.</li>
<li>This will create a <code>dict</code>... | python|excel|pandas | 1 |
13,384 | 63,150,264 | Is there a way to cut only the first gap from histogram and take all the remain values in Python? | <p>I have a data frame with fields: <strong>'unique years', 'counts'</strong>. I plotted this data frame and i am getting the following histogram: <a href="https://i.stack.imgur.com/YrlRy.png" rel="nofollow noreferrer">histogram - example</a>. I need to define a <strong>start year</strong> variable but if i have empty ... | <p>The issue with your question is that 'continuous' is not really well defined here. Do you mean that every <em>year</em> should have a non-empty count (that is fairly easy to do as you can filter your data for that prior to building your histogram), or should every consecutive <em>bucket</em> be non empty? If the lat... | python|python-3.x|pandas|dataframe|histogram | 2 |
13,385 | 63,053,949 | Scipy convolve2d different from tensorflow conv2d | <p>Here is my code:</p>
<pre><code>import tensorflow as tf
import numpy as np
from scipy import signal
img2 = np.array([
[10, 10, 10, 0, 0, 0],
[10, 10, 10, 0, 0, 0],
[10, 10, 10, 0, 0, 0],
[10, 10, 10, 0, 0, 0],
[10, 10, 10, 0, 0, 0],
[10, 10, 10, 0, 0, 0]
]).astype(np.float32)
k = np.array([
... | <p>In the end, I found the response.</p>
<p>The issue is <code>scipy</code> does the mathematically 'correct' convolution, whereas <code>tensorflow</code> does the convolution oriented to a Convolutional Neural Network (CNN) application.</p>
<p>Therefore, <code>scipy</code> inverts the kernel before applying the convol... | python|tensorflow|scipy | 2 |
13,386 | 63,047,707 | How do I convert a numpy array to a gif? | <p>Suppose I have a 4D <code>numpy</code> array where the 3D subarrays are RGB images. How do I convert this to a gif? I would prefer to only depend on well-known Python image processing libraries.</p>
<p>Sample data:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
imgs = np.random.randint(0, 255... | <p>This is straightforward using <code>PIL</code>:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from PIL import Image
imgs = np.random.randint(0, 255, (100, 50, 50, 3), dtype=np.uint8)
imgs = [Image.fromarray(img) for img in imgs]
# duration is the number of milliseconds between frames; this ... | python|numpy | 4 |
13,387 | 67,968,321 | Extracting data from one dataframe in accordance to another dataframe | <p>I have a dataframe that contains point name, time of passing, which group it is in, and the path it took. A sample dataframe, showing only one object using the one path and going to several points, is as follows:</p>
<pre><code>df = pd.DataFrame({'Point': ['tefe','fesa','lksa','sado','kalo'],
'Tim... | <p>I actually have found one solution but it is quite long.</p>
<p>I first add a jump column in the <code>df</code></p>
<pre><code>df['Jump'] = df['Group']+'-'+df['Group'].shift(-1)
</code></pre>
<p>I then create a mask to filter the <code>df</code> to show only the rows that are in the <code>idDF</code> and from there... | python|pandas|dataframe | 0 |
13,388 | 67,633,740 | Select rows where Col1 "isnull" & Col2 "notnull" | <p>I would like to select rows where value in col1 is null and value in col2 is not null
DF</p>
<pre><code>col1 col2
423 NaN
NaN 291
391 102
</code></pre>
<p>Desired output</p>
<pre><code>col1 col2
NaN 291
</code></pre> | <p>Use <code>pandas loc</code>:</p>
<pre><code>df.loc[(df['col1'].isna()) & (~df['col2'].isna())]
</code></pre> | python|pandas | 2 |
13,389 | 61,306,552 | I am trying to use Neural Networks for regression on boston dataset using tensorflow. Somehow I am getting all predictions as wrong | <p>I am getting correct_eval as 0. I have used boston dataset. Splitted into training and testing. Used tensorflow for training the model. (Not keras). The neural networks consists of 2 hidden layers of size 13 each and input size is also 13.</p>
<pre><code>import pandas as pd
import numpy as np
data=pd.read_csv("Bo... | <p>Take a look at this line of code:</p>
<pre><code>correct_pred=tf.equal(pred,y_train)
</code></pre>
<p>You are evaluating outputs from an untrained regression model using equality. There are a couple problems with this.</p>
<ol>
<li><p>The values in <code>y_train</code> are produced by 3 layers that have random we... | python|tensorflow | 0 |
13,390 | 68,865,360 | Stripping and dropping columns from pandas dataframe | <p>I have the following columns in a pandas df:</p>
<pre><code>Index(['Commodity Derivative Name\n(including associated contracts)',
'Venue MIC ', 'Name of Trading Venue ', 'Venue Product Codes ',
'Principal Venue Product Code', 'Spot month single limit#',
'Other month limit#', 'Conversion Factor',... | <p>To remove the trailing spaces:</p>
<pre><code>df.columns = [c.strip() for c in df.columns]
</code></pre>
<p>and to drop the "Unnamed" columns:</p>
<pre><code>df.drop(columns=df.filter(like='Unnamed').columns)
</code></pre>
<p>Here is an example for the <code>drop</code> part:</p>
<p>input:</p>
<pre><code>&... | python-3.x|pandas|dataframe | 2 |
13,391 | 68,868,341 | Extract value from a list of lists and add to new column | <p>I have a data frame with one column that is a list of lists containing address information.</p>
<p>My data:</p>
<pre><code>import pandas as pd
data = [['location1', [(123, 'Number'),('Main', 'Street'),('New York', 'City')]], ['location2', [('Broadway', 'Street'),('New York', 'City'),(11111, 'ZIP')]], ['location3', ... | <p>You can use a list comprehension and the <code>str</code> accessor:</p>
<pre><code>df['Address_Info'].apply(lambda l: [i[0] for i in l if i[1] == 'Number']).str[0]
</code></pre>
<p>output:</p>
<pre><code>0 123.0
1 NaN
2 987.0
</code></pre>
<p>To save it in a new column:</p>
<pre><code>df['Number'] = (df['... | python|pandas|nested-lists | 1 |
13,392 | 53,066,627 | groupby to return nth group - NOT row | <p>I'm attempting to group by two factors in a long (>2M) rows.</p>
<h3>Background to the data</h3>
<p>The second factor is effectively a test date - for a given sample (the first group) a sample can be retested.
However the test can change the sample, so it useful to be able to selectively pull out the batch of tes... | <p>You can <code>reset_index</code>, then use <code>GroupBy</code> + <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.nth.html" rel="nofollow noreferrer"><code>nth</code></a>:</p>
<pre><code>res = df.reset_index().groupby('id').nth(1)
print(res)
date ... | python|pandas|group-by|pandas-groupby|rank | 3 |
13,393 | 53,052,761 | Connecting two numpy array channels | <p>I have two numpy arrays, for example:</p>
<pre><code>a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[11,12,13],[14,15,16],[17,18,19]]
</code></pre>
<p>Which are channels of the same image. I would like to get the "connected" channels array in a as pythonic way as possible. wanted outcome:</p>
<pre><code>c = [[[1,11],[2,12],[... | <p>You can use <code>np.stack</code> on the second axis:</p>
<pre><code>>>> np.stack((a,b),axis=2)
array([[[ 1, 11],
[ 2, 12],
[ 3, 13]],
[[ 4, 14],
[ 5, 15],
[ 6, 16]],
[[ 7, 17],
[ 8, 18],
[ 9, 19]]])
</code></pre>
<p>Checking that it's the sa... | python|numpy | 4 |
13,394 | 65,699,504 | Will dtype affect Pandas calculation performance? | <p>Aside from memory usage and disk usage, will float16 computation <strong>faster</strong> than float32 computation in Pandas dataframe? If so, how much more performance should I expect?</p> | <p>float16 computation <em><strong>MUCH SLOWER</strong></em> than float32, it is happening because there is no equivalent of float16 in c.</p>
<p>since python is based on c, as there is no equivalent of that in c, numpy created a method to perform for float16.</p>
<p>( float is a 32 bit IEEE 754 single precision Floati... | python|pandas|performance|dataframe|optimization | 0 |
13,395 | 65,621,208 | Pandas to_excel not working when trying to write a dataframe on an empty xlsx file | <p>Having this code:</p>
<pre><code>tlfx = pandas.DataFrame()
writer = pandas.ExcelWriter(file)
writer.book = load_workbook(file)
writer.sheets = dict((register.title, register) for register in writer.book.worksheets)
tlfx = tlfx.append({'Name': person, 'Telephone': telephone}, ignore_index=True)
reader = pandas.rea... | <p>The error was here:
pandas.to_excel function was creating a new sheet with the default name "Sheet_1", and all the data went there.
To fix it, I used writer.book.active.title as the value for the sheet_name parameter in the to_excel() function.</p> | python|excel|pandas | 0 |
13,396 | 63,344,215 | How to impute values before merging two dataframes in python pandas to avoid loss of data | <p>I have two dataframes, <code>df1</code> and <code>df2</code> which can be seen below:</p>
<pre><code>df1
name posteam down rush
0 A.Ekeler LAC 1.0 35.7
1 A.Ekeler LAC 2.0 15.1
2 A.Ekeler LAC 3.0 15.9
3 A.Ekeler LAC 4.0 0.4
4 A.Jones GB 1.0 ... | <p>you should try this</p>
<pre><code>merged_df = pd.merge(df1, df2,
how='outer',
on=['name', 'posteam', 'down']).fillna(value=0.0)
</code></pre> | python|pandas|dataframe|merge | 1 |
13,397 | 63,501,505 | TensorFlow - ValueError: Shapes (3, 1) and (4, 3) are incompatible | <p>I'm completely new to DL and I'm stuck with this error when I fit my model</p>
<p><code>ValueError: Shapes (3, 1) and (4, 3) are incompatible</code></p>
<p>Dataset:</p>
<pre><code>Features: [0.22222222 0.625 0.06779661 0.04166667], Target: [1 0 0]
Features: [0.16666667 0.41666667 0.06779661 0.04166667], Target:... | <p>In your code <strong>InputLayer</strong> is missing in <strong>build_fc_model</strong> so check this out:</p>
<pre><code>import tensorflow as tf
import numpy as np
def build_fc_model():
fc_model = tf.keras.Sequential([
tf.keras.layers.InputLayer((4,)),
tf.keras.layers.Dense(4, activation=tf.nn.softmax... | python|tensorflow|model | -1 |
13,398 | 63,411,077 | Function on column from dictionary | <p>I have a df like this:</p>
<pre><code>df = pd.DataFrame({'A': [3, 1, 2, 3],
'B': [5, 6, 7, 8]})
A B
0 3 5
1 1 6
2 2 7
3 3 8
</code></pre>
<p>And I have a dictionary like this:</p>
<pre><code>{'A': 1, 'B': 2}
</code></pre>
<p>Is there a simple way to performa function (eg. d... | <p>For me working division by dictionary, because keys of dict matching columns names:</p>
<pre><code>d = {'A': 1, 'B': 2}
df1 = df.div(d)
</code></pre>
<p>Or:</p>
<pre><code>df1 = df / d
print(df1)
A B
0 3.0 2.5
1 1.0 3.0
2 2.0 3.5
3 3.0 4.0
</code></pre> | python-3.x|pandas | 1 |
13,399 | 53,490,588 | Arrange long column into multiple shorter ones in pandas | <p>I have a long data column that I would like to organize by groups.</p>
<pre><code>np.random.seed(0)
data = {'unit':['a']*5+['b']*5,\
'day':list(range(5))+list(range(5)),\
'data':np.random.random(10)*10}
df = pd.DataFrame.from_dict(data)
</code></pre>
<p>The dataframe looks like this:</p>
<pre><code> unit... | <h3><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a></h3>
<p>Pandas has a method for this:</p>
<pre><code>res = df.pivot(index='day', columns='unit')
print(res)
data
unit a b
day ... | python|pandas | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.