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 |
|---|---|---|---|---|---|---|
8,300 | 52,685,466 | Sliced column of Pandas dataframe keep mentioning original column name in new objects created from the column | <p>I sliced from a pandas dataframe to create object label. The name of the column in the original dataframe was <code>y</code>. </p>
<p>Now when I take sum of <code>label</code> and assign it to <code>m</code>, while printing it keeps showing <code>y</code>. Why is it doing so and what is it trying to mean by writing... | <p>Your <code>label</code> DataFrame contains only 1 column named <code>y</code> with 50 rows of <code>1.0</code>, so it returned <code>sum of y</code>. In your code the name became the index name (a sum of a single column) since all index in DataFrame <em>needs</em> a name, you can rename that using <code>m.index = &l... | python|pandas|slice | 0 |
8,301 | 52,633,472 | Index labels are not displaying - Pandas(Series) | <p>I am using pandas and matplotlib and I am trying to set the label on x axis by the <strong>index in Series of panda</strong></p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
index = ['apples','oranges','cherries','bananas']
quantity = [20,30,40,50]
s = pd.Series(quantity, index = index)
s.plot()... | <p>There seems to be some problem with pandas (currently?) as also seen from <a href="https://stackoverflow.com/questions/52631031/make-pandas-plot-show-xlabel-and-xvalues">Make pandas plot() show xlabel and xvalues</a>.</p>
<p>Here using matplotlib directly is a good option as well. Just replace <code>s.plot()</code>... | pandas|matplotlib | 1 |
8,302 | 52,628,672 | numpy rfftn changes input dimensions | <p>I want to compute the discrete Fourier Transform of a 3D numpy array. I'm using the <code>numpy.fft.rfftn</code> function but its output has different dimensions of the input, how can I fix this?
Here it is my code:</p>
<pre><code>np.shape(img_coll)
>>> (9997, 50, 50)
img_spectrum = np.fft.rfftn(img_coll,... | <p>There is nothing to fix in your code.
If your signal is <em>real</em>, then its Fourier transform is <em>conjugate symmetric</em>.
In other words, the frequency-domain signal <code>img_spectrum</code> (along the first axis <code>axes=[0]</code>) has <em>even magnitude</em> and <em>odd phase</em>, so the user is resp... | python|numpy|fft | 1 |
8,303 | 46,510,422 | Append npy file to another npy file with same number of columns in both files | <p>npy files size are around 5 gb and RAM is around 5gb so cannot load both numpy arrays. How to load one npy file and append its rows to other npy file without loading it </p> | <p>An npy file is a header containing the data type (metadata) and shape, followed by the data itself.</p>
<p>The header ends with a <code>'\n'</code> (newline) character. So, open your first file in append mode, then open the second file in read mode, skip the header by <code>readline()</code>, then copy chunks (usi... | python|python-2.7|numpy|numpy-ufunc|numpy-memmap | 0 |
8,304 | 58,557,552 | Custom mean implementation is slower than pandas default mean. How to optimize? | <p>I want to find the mean of the pandas <code>Dataframe</code>. So I was using the following mean function which pandas provide by default. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mean.html" rel="nofollow noreferrer">Link to its doc</a></p>
<pre><code>df.mean()
</code></pr... | <p>Found the solution by my self. The logic is to first normalize all the values by dividing it by length of Series (# of records) and then use default <code>df.mean()</code> and then multiply the normalized mean with # of records: This is an improvement from 1min 37 seconds to 3.13 seconds. But I still don't understan... | python|python-3.x|pandas|optimization|mean | 1 |
8,305 | 58,385,916 | Selecting Cells in Pandas MultiIndex DataFrames Using a List | <p>I am trying to set the values of certain cells in a Pandas MultiIndex DataFrame by selecting these cells using a list. </p>
<p><em>Note the sequence of both lists.</em></p>
<pre><code>df.loc[(['Peter','John','Tom'],'AAPL'),1] = ['Peter', 'John', 'Tom']
</code></pre>
<p><strong>Problem:</strong> However, the value... | <p>Like this, by giving the entire index for each elements.</p>
<pre class="lang-py prettyprint-override"><code>df.loc[[('Peter', 'AAPL'), ('John', 'AAPL'),('Tom','AAPL')],1] = ['Peter', 'John', 'Tom']
print(df)
</code></pre>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced-i... | python|python-3.x|pandas|dataframe|multi-index | 2 |
8,306 | 68,945,022 | Fuzzy-compare two dataframes of addresses and copy info from 1 to another | <p>I have this data set. df1 = 70,000 rows and df2 = ~30 rows. I want to match the address to see if df2 appears in df1 and if it does than I want to show the match and also pull info from df1 to create a new df3. Sometimes the address info is off by a bit..for example (road = rd, street = st, etc )Here's an example:<... | <p>My answer is similar to <a href="https://stackoverflow.com/a/68324933/15239951">one</a> of your old questions that I answered.</p>
<p>I slightly modified your dataframe:</p>
<pre><code>>>> df1
address unique key
0 123 nice road Uniquekey1
1 150 spring drive Uniquekey2
2 240 happy ... | python|pandas|dataframe|fuzzywuzzy|difflib | 1 |
8,307 | 69,253,057 | Apply multiple criteria to select current and prior row - Pandas | <p>I have a dataframe like as shown below</p>
<pre><code>person_id source_system r_diff
1 O NULL
1 O 0
1 O 9
1 O NULL
2 O 574
2 I 20
2 O 135
... | <p>I prefer not one line solution, because hard readable if more complicated code, so better is use:</p>
<pre><code>m1 = df['visit_source_value'] == 'I'
m2 = df['r_diff'] <= 0
m3 = df.groupby('person_id')['visit_source_value'].shift(-1) == 'I'
df = df[m1 | (m2 & m3)]
print (df)
person_id visit_source_value... | python|pandas|dataframe|pandas-groupby|series | 1 |
8,308 | 69,159,550 | Keras - Is there a way to manage the filenames generated by the flow_from_directory function of ImageDataGenerator? | <p>As the title is self-descriptive, I need to keep the original filenames of my images after the data augmentation, which is handled by the <code>flow_from_directory</code> function of the <code>ImageDataGenerator</code> class of <code>Keras</code>. The reason behind this requirement is that the filenames actually rep... | <p>Unfortunately, there is not an easy way to access to the filenames from the <code>ImageDataGenerator.flow_from_directory</code> iterator. Instead, you can use <code>ImageDataGenerator.flow</code> to apply your augmentations to an image, then save the augmented image manually using another image processing library, e... | keras|tensorflow2.0|tf.keras|data-augmentation|data-generation | 0 |
8,309 | 68,957,453 | Get unique count of items of a column in pandas pivot table | <p>Here is my code:</p>
<p><code>df1.pivot_table(index=["Unit", "Grade"],values = ["Unit", "QTY","ORDER_NUM", "ORDER ID"], aggfunc={'Cost': 'sum' ,'QTY':'sum', "ORDER_NUM":'count',"ORDER ID":'count'})</code></p>
<p>I want to get a count of ... | <p>You can use <code>'nunique'</code>:</p>
<p>example input:</p>
<pre><code>df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
"bar", "bar", "bar", "bar"],
"B&quo... | python|pandas | 1 |
8,310 | 61,108,469 | How to randomly pick and mask a portion of a Tensor in Tensorflow (python) | <p>I'm training a denoising autoencoder in Tensorflow 2, one part of the run time is spent on CPU doing masking of a portion of the input data, randomly selecting the indices to be masked, then setting their values to zero. This is my masking function, this masking is repeated on the beginning of each epoch, at differe... | <p>I think I finally figured it out, it was easy to debug this problem with Tensorflow 2, so I was able to solve this when I changed from TF1 to TF2:</p>
<pre><code>def mask_data(y_true, mask_ratio, verbose=0):
nf = tf.cast(tf.shape(y_true)[1], tf.float32)
mask_portion = tf.math.round( tf.math.multiply(nf,(1-... | python|numpy|tensorflow|tensorflow2.0|masking | 5 |
8,311 | 60,980,181 | How can I get one array to return only the masked values define by another array with Numpy / PyTorch? | <p>I have a <code>mask</code>, which has a shape of: <code>[64, 2895]</code> and an array <code>pred</code> which has a shape of <code>[64, 2895, 161]</code>.</p>
<p><code>mask</code> is binary with only <code>0</code>s and <code>1</code>s. What I want to do is reduce <code>pred</code> so that it maintains <code>64</c... | <p>If you want a vectorized computation then different dimension seems not possible, but this would give you the one with masked entry filled with 0:</p>
<pre><code># pred: torch.size([64, 2895, 161])
# mask: torch.size([64, 2895])
result = pred * mask[:, :, None]
# extend mask with another dimension so now it can d... | python|numpy|pytorch | 1 |
8,312 | 60,942,519 | Can't download c4 dataset with Dataflow in colab | <p>I want to download the c4 dataset. As per the instructions page: <a href="https://www.tensorflow.org/datasets/catalog/c4" rel="nofollow noreferrer">https://www.tensorflow.org/datasets/catalog/c4</a>, it's recommended to use dataflow. I followed the steps described here: <a href="https://www.tensorflow.org/datasets/b... | <p>As of today, you don't have to do the processing yourself. We uploaded the dataset to a bucket in the Google Cloud, and also created a JSON version. More details at <a href="https://github.com/allenai/allennlp/discussions/5056" rel="nofollow noreferrer">https://github.com/allenai/allennlp/discussions/5056</a>.</p> | google-colaboratory|apache-beam|tensorflow-datasets|dataflow | 0 |
8,313 | 71,470,699 | Embedding multiple real-time graphs in one Python Tkinter GUI | <p>I am new with Tkinter. I am trying to plot two real-time animated graphs in a window, but two realtime data overlaps onto the same graph after a while. I want them to be displayed on separate graphs. <a href="https://i.stack.imgur.com/PlXNC.gif" rel="nofollow noreferrer">I put a gif to show my output</a>.
I want to ... | <p>If You don't specifically need canvas1 and 2, You can create two subplots for one figure / canvas.<br />
Then You will get 2 axes: <code>ax1</code> and <code>ax2</code>.</p>
<p>You can use just one <code>FuncAnimation</code> with same <code>x</code>.
If You need separate animations for <code>ax1</code> and <code>ax2... | python|pandas|matplotlib|tkinter | 1 |
8,314 | 42,324,119 | Converting column into proper timestamp using pandas read_csv | <p>I have a time series csv file that consists of timestamps and financial data, like this:</p>
<pre><code>20140804:10:00:13.281486,782.83,443355
20140804:10:00:13.400113,955.71,348603
</code></pre>
<p>Now, I would like to put this into a <code>pandas.DataFrame</code>, and parse the dates to <code>yyyymmddhhmmss</cod... | <p>You need:</p>
<p><strong>no header of csv</strong>:</p>
<pre><code>import pandas as pd
from pandas.compat import StringIO
temp=u"""
20140804:10:00:13.281486,782.83,443355
20140804:10:00:13.400113,955.71,348603"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp),
... | python|pandas|datetime | 1 |
8,315 | 42,569,432 | How to copy every row of one matrix into every other row of another matrix using broadcasting? | <p>if I have the following matrices:</p>
<pre><code>a = np.array([['A'], ['B'], ['C']])
b = np.array([['0'], ['0'], ['0'], ['0'], ['0'], ['0']])
</code></pre>
<p>and I want to get the following:</p>
<pre><code>c = np.array([['A'], ['0'], ['B'], ['0'], ['C'], ['0']])
</code></pre>
<p>Is there a way to get c using so... | <p>For in-situ edit in <code>b</code> -</p>
<pre><code>b[::2] = a
</code></pre>
<p>To make those changes in a new array, make a copy and edit -</p>
<pre><code>c = b.copy()
c[::2] = a
</code></pre> | python-2.7|numpy|array-broadcasting | 1 |
8,316 | 42,451,011 | How is the numpy way to binarize arrays with a threshold value? | <p>How to binarize an numpy array to its corresponding maximum value in a row above a threshold value. if the arrays row maximum value is lesser than the threshold value then column 1 should be equal to one.</p>
<pre><code>a=np.array([[ 0.01, 0.3 , 0.6 ], ... | <p>One solution: use <code>argmax</code> and advanced indexing</p>
<pre><code>am = a.argmax(axis=-1)
am[a[np.arange(len(a)), am] < 0.6] = 1
out = np.zeros_like(a)
out[np.arange(len(a)), am] = 1
out
array([[ 0., 0., 1.],
[ 0., 1., 0.],
[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 1., 0.]... | python|arrays|numpy | 1 |
8,317 | 69,699,821 | Creating a dataframe from list and existing dataframe | <p>I have a dataframe in the form of</p>
<pre><code>column 1 column 2 column 3
</code></pre>
<p>And I would like to add values to it.
I have a list which I would like to add which is in the form of:</p>
<pre><code>a= [['Master Vithal', ' Vithal Zubeida'], ['Firozshah Mistry', ' B Irani'], ['Grigor']]
</code></pre>
<p>H... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>.loc</code></a> to add elements of list <code>a</code> at the end of the dataframe, as follows:</p>
<pre><code>import numpy as np
cols = ['column 1', 'column 2', 'column 3'] ... | python|pandas|web-scraping | 0 |
8,318 | 69,900,878 | How do I create a contourplot with a custom function? | <p>I have seen many examples online of create a contourplot as follows</p>
<pre><code>import numpy as np
xlist = np.linspace(-3.0, 3.0, 3)
ylist = np.linspace(-3.0, 3.0, 4)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)
cp = plt.contourf(X, Y, Z)
plt.colorbar(cp)
ax.set_title('Contour Plot')
ax.set_xlabel('... | <p>Answered by Tadhg McDonald-Jensen in a comment. Create a new function with <code>np.vectorize(nllh)</code></p> | python|numpy|contour | 0 |
8,319 | 43,086,123 | plot a graph with its x-label is month and date | <p>I have a dataframe like this</p>
<pre><code> 2015max 2015min idxmax idxmin
01-05 242.0 -54.0 241.0 -127.0
01-26 245.0 -45.0 238.0 -134.0
04-02 298.0 -23.0 280.0 -59.0
04-04 288.0 72.0 283.0 -86.0
04-17 281.0 29.0 278.0 -47.0
</code></pre>
<p>I want to overlay... | <p>It seems in your data are some bad values, so need parameter <code>error='coerce'</code> for replace them to <code>NaT</code> and then replace <code>NaT</code> to some value:</p>
<pre><code>print (idxmin)
2015max 2015min idxmax idxmin
01-05 242.0 -54.0 241.0 -127.0
01-26 245.0 -45.0 238.0... | python|pandas|matplotlib | 3 |
8,320 | 43,110,684 | How to plot values of pandas dataframe with reference to a list (problems with indexing)? | <p>I am looking for a clever way to produce a plot styled like this rather childish example:
<a href="https://i.stack.imgur.com/6HeqV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6HeqV.png" alt="enter image description here"></a></p>
<p>with source data like this:</p>
<pre><code>days = ['Monday'... | <p>One possible solution is flatenning values from <code>lists</code>, <code>pivot</code> and then plot:</p>
<pre><code>from itertools import chain
df2 = pd.DataFrame({
"Feature": np.repeat(df.Feature.values, df.Values.str.len()),
"Values": list(chain.from_iterable(df.Values)),
"observed on":... | python|pandas|matplotlib | 1 |
8,321 | 43,464,410 | Pandas drop group column after groupby.apply(..) | <pre><code> uid iid val
uid
1 1 1 5 5.5
2 3 1 4 3.5
2 2 1 4 3.5
2 7 1 4 3.5
2 9 1 4 3.5
2 11 1 4 3.5
</code></pre>
<p>From the dataframe above, I want to remove the first column, which is:</p>
<pre><code>uid
1
2
2
2
2
2
</code></pre>... | <p>You can avoid including the <code>uid</code> in the index in the first place by passing <code>group_keys=False</code> to the <code>groupby</code></p>
<pre><code>df.groupby('uid', group_keys=False).apply(lambda x: x.tail(len(x) // 5))
uid iid val
4 1 5 5.5
</code></pre> | python|pandas|dataframe|group-by|pandas-groupby | 15 |
8,322 | 72,346,587 | How to convert tf.estimator.DNNClassifier() to tflite | <p>code:</p>
<pre><code>classifier1 = tf.estimator.DNNClassifier(
feature_columns=my_feature_columns,
hidden_units=[128,64,32,10],
n_classes=10)
</code></pre>
<p>#Save model</p>
<pre><code>feature_spec = tf.feature_column.make_parse_example_spec(my_feature_columns)
export_input_fn = tf.estimator.export.build_parsing_se... | <p>You need to specify the directory that has the saved model, not the .pb file in the saved model directory.
So if you saved the mdoel in "/content/DNN_model" then pass the same path "/content/DNN_model" to the converter.</p>
<pre><code>converter=tf.lite.TFLiteConverter.from_saved_model(servable_mo... | tensorflow|deep-learning|tensorflow2.0|tensorflow-lite | 0 |
8,323 | 50,535,067 | Need to know when, and how many times a variable gets updated in Tensorflow | <p>In my Tensorflow project, I need to know whether <code>train_op</code> as defined below, updates a certain variable or not, and if it does then, how many times it gets updated. </p>
<p>For a feed-forward network this is trivial, one <code>train_op</code> call results in one time update of the variable, but in case ... | <p>I'm pretty sure that the recurrent weights are just updated once. The weights are reused multiple times in the forward pass. Multiple gradients are calculated in the backward pass. Those gradients are added together and then a single update is made.</p> | python|tensorflow | 0 |
8,324 | 45,437,458 | Combine row data from multiple txt files to a single data frame in column format | <p>I have row data in each text file in the following format</p>
<p>File 1</p>
<pre><code> Sample 1, 24/07/2017 13:26:08
0 Peak at 1219 , 1.864
1 Peak at 1092 , 0.412
2 Peak at 1358 , 1.661
</code></pre>
<p>File 2</p>
<pre><code> Sample 2, 24/07/2017 14:28:15
0 Peak at 1219 , 1.544
1 Peak at 1092 , 0.315
2... | <p>There is main function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>, which create big <code>df</code>. But need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow norefer... | python|pandas|numpy | 1 |
8,325 | 45,603,672 | Can the date format of dataframe and csv file be the same? | <p>The two photos that I've attached below show a dataframe table and a table that was exported out to csv file. I'm wondering if there is any command that can modify the date so that the dates shown on both files would be the same. </p>
<p>On the dataframe: 2017-08-01 -> but after exporting out it becomes 2017/8/1(<s... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer">pandas.DataFrame.to_csv</a></p>
<p>When you make the call to the <code>to_csv</code> function, you can supply it the parameter <code>date_format='%Y-%m-%d'</code>.</p> | python|pandas|csv|date|dataframe | 2 |
8,326 | 45,699,653 | Using column name as a new attribute in pandas | <p>I have the following data structure</p>
<pre><code>Date Agric Food
01/01/1990 1.3 0.9
01/02/1990 1.2 0.9
</code></pre>
<p>I would like to covert it into the format</p>
<pre><code>Date Sector Beta
01/01/1990 Agric 1.3
01/02/1990 Agric 1.2
01/01/1990 Food 0.9
01/02/1990 Foo... | <p>Use <code>set_index</code> and <code>stack</code>:</p>
<pre><code>df.set_index('Date').rename_axis('Sector',axis=1).stack()\
.reset_index(name='Beta')
</code></pre>
<p>Output:</p>
<pre><code> Date Sector Beta
0 01/01/1990 Agric 1.3
1 01/01/1990 Food 0.9
2 01/02/1990 Agric 1.2
3 01/02/1990... | python|pandas|reshape | 5 |
8,327 | 45,515,031 | How to remove columns with too many missing values in Python | <p>I'm working on a machine learning problem in which there are many missing values in the features. There are 100's of features and I would like to remove those features that have too many missing values (it can be features with more than 80% missing values). How can I do that in Python?</p>
<p>My data is a Pandas dat... | <p>Demo:</p>
<p><strong>Setup:</strong></p>
<pre class="lang-none prettyprint-override"><code>In [105]: df = pd.DataFrame(np.random.choice([2,np.nan], (20, 5), p=[0.2, 0.8]), columns=list('abcde'))
In [106]: df
Out[106]:
a b c d e
0 NaN 2.0 NaN NaN NaN
1 NaN NaN 2.0 NaN 2.0
2 NaN 2.0 ... | python|pandas|dataframe|scikit-learn|missing-data | 27 |
8,328 | 62,707,855 | apache arrow - adequacy for parallel processing | <p>I have a huge dataset and am using Apache Spark for data processing.</p>
<p>Using Apache Arrow, we can convert Spark-compatible data-frame to Pandas-compatible data-frame and run operations on it.</p>
<p>By converting the data-frame, will it achieve the performance of parallel processing seen in Spark or will it beh... | <p>As you can see on the documentation <a href="http://spark.apache.org/docs/latest/sql-pyspark-pandas-with-arrow.html#apache-arrow-in-spark" rel="nofollow noreferrer">here</a></p>
<blockquote>
<p>Note that even with Arrow, toPandas() results in the collection of all records in the DataFrame to the driver program and s... | pandas|apache-spark|apache-arrow | 3 |
8,329 | 62,817,874 | Is there a way to check a dataframe against a single value? | <p>I have a dataframe like this.</p>
<pre><code>import pandas as pd
import numpy as np
# Creating a dict of lists
data = {'Name':["Akash", "Geeku", "Pankaj", "Sumitra","Ramlal"],
'Branch':["B.Tech", np.nan, "BCA", "B.Tech", &q... | <p>This will do it in one go:</p>
<p><code>(df == "B.Tech").sum(axis=1).astype(bool)</code></p>
<p>To explain:</p>
<p><code>df == "B.Tech"</code> returns a DataFrame the same shape as your original but just containing True/False values as to whether the value is equal to "B.Tech"</p>
<p><c... | python|pandas | 2 |
8,330 | 54,336,065 | How to reduce command with .replace and problems in create function | <p>I have a dataframe in which I would like to replace the 0, 1 encoding with 'yes' and 'no' in some columns that I've selected. Some df columns have this encoding and so I wrote the following command:</p>
<pre><code>dados_trabalho = dados_trabalho.replace({"ASSINTOM": {0: "Sim", 1 : "Não"}}).replace({"DOR ATIPICA": {... | <p>The function you created (<code>change_columns(df)</code>), looks like it is trying to perform the replace on all the columns. If this was your intention, you don't need any special function or chained method calls. All you need is:</p>
<pre><code>dados_trabalho = dados_trabalho.replace({0: "Sim", 1 : "Não"})
</c... | python|pandas|dataframe | 1 |
8,331 | 54,279,454 | saving the bounding box image | <p>Instead of trying to draw the bounding box over the image, i am trying to save it as a new image. </p>
<p>When i was getting [ymin, xmax, ymax, xmin] points, i was doing this.</p>
<pre><code>import cv2
import numpy as np
image = cv2.imread('ballet_106_0.jpg')
image = np.array(image)
boxes = [21, 511, 41, 420 ]
... | <p>Your code looks ok, though this line:</p>
<pre><code>image = np.array(image)
</code></pre>
<p>is not required, as if everything goes well <code>cv2.imread</code> produce <code>np.array</code>, however if <code>cv2.imread</code> fails it returns <code>None</code>, which might be source of your problem, please add f... | python|numpy|opencv|image-processing | 1 |
8,332 | 54,308,172 | Adding a trend line to a matplotlib line plot python | <p>Apologies if this has already been asked but I can't find the answer anywhere. I want to add an overall trend line to a plt plot. Sample data:</p>
<pre><code>import pandas as pd
data = pd.DataFrame({'year': [2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
2019],
'... | <p>If you are looking for a simple linear regression fit, you can use directly either <a href="http://seaborn.pydata.org/generated/seaborn.lmplot.html#seaborn.lmplot" rel="noreferrer"><code>lmplot</code></a> or <a href="http://seaborn.pydata.org/generated/seaborn.regplot.html#seaborn.regplot" rel="noreferrer"><code>reg... | python|pandas|matplotlib | 13 |
8,333 | 73,805,959 | Create Pandas DataFrame column which joins column names for any non na values | <p>How do I create a new column which joins the column names for any non na values on a per row basis.</p>
<ul>
<li>Please note the duplicate index.</li>
</ul>
<p><strong>Code</strong></p>
<pre><code>so_df = pd.DataFrame({"ma_1":[10,np.nan,13,15],
"ma_2":[10,11,np.nan,15],
... | <p>Try with <code>dot</code></p>
<pre><code>df['new'] = df.notna().dot(df.columns+',').str[:-1]
df
Out[77]:
ma_1 ma_2 ma_3 new
0 10.0 10.0 NaN ma_1,ma_2
1 NaN 11.0 11.0 ma_2,ma_3
1 13.0 NaN NaN ma_1
2 15.0 15.0 15.0 ma_1,ma_2,ma_3
</code></pre> | python|pandas | 2 |
8,334 | 73,630,099 | Docker run failing when mounting host dir inside a container | <p>I am trying to mount a directory from host to container and at the same time running jupyter from that directory. What am I doing wrong here that docker is complaining as file now found please?</p>
<p>docker run -it --rm -p 8888:8888 tensorflow/tensorflow:nightly-jupyter -v $HOME/mytensor:/tensor --name TensorFlow p... | <p>Docker run command syntax is</p>
<pre><code>docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
</code></pre>
<p>image name <code>tensorflow/tensorflow:nightly-jupyter</code> should be after options (<code>-v</code>, <code>-p</code> <code>--name</code> et.al.) and before the command.</p>
<pre><code>docker run -it --rm -p ... | python|docker|tensorflow|jupyter-notebook|mount | 0 |
8,335 | 73,633,844 | Model calculating accurcy of only class 0 in class-wise accuracy evaluation | <p>My code is given below, I am only getting the accuracy of the class 0 instead of all the classes.
The output is
Epoch 1/2
58/58 [==============================] - 424s 7s/step - loss: 4.7356 - accuracy: 0.5317 - acc_1_0: 0.9655 - acc_1_1: 0.0000e+00 - acc_1_2: 0.0000e+00 - acc_1_3: 0.0000e+00 - acc_1_4: 0.0000e+00 -... | <p><em>My code is given below, I am only getting the accuracy of the class 0 instead of all the classes</em>... probably because accuracy is meant to do exactly that... what you probably are looking for, are precision and recall</p> | python|tensorflow|keras | 1 |
8,336 | 73,702,175 | How to save multiple dataframe using one variable in a for loop | <pre><code>import numpy as np
count = np.arange(0,1849)
for i in range(0,6):
for j in range (0,6):
for k in range (0,4):
for l in range (0,10):
for m in count:
case = data[(data["CURRENT_ENERGY_RATING_Code"] == i)&(data["PROPERTY_TYPE"] == j)&(data... | <p>You could create a dictionary with keys in the format <code>i-j-k-l-m</code> iterating through 0,1,2,etc; and values as the relevant dataframes. For example:</p>
<pre><code>dic = {}
count = np.arange(0,1849)
for i in range(0,6):
for j in range (0,6):
for k in range (0,4):
for l in range (0... | python|pandas|analysis | 0 |
8,337 | 71,346,565 | pandas to_json exclude the groupby keys | <p>How do we exclude the grouped by key from the <code>to_json</code> method ?</p>
<pre><code>import pandas as pd
students_df = pd.DataFrame(
[
["Jay", 16, "Soccer"],
["Jack", 19, "FootBall"],
["Dorsey", 19, "Dining"],
[&qu... | <p>You could <code>drop</code> it:</p>
<pre><code>out = students_df.groupby('Name').apply(lambda x: x.drop(columns='Name').to_json(orient="records"))
</code></pre>
<p>Output:</p>
<pre><code>Name
Dorsey [{"Age":19,"Sport":"Dining"}]
Jack [{"Age":19,"Sport&... | python|pandas|dataframe|pandas-groupby | 2 |
8,338 | 71,227,514 | Skipping empty values python apply | <p>I need to apply the right function to a column ('Example') in a dataframe. The following code works perfectly if the column has no empty "cells". However, when it comes to columns with some empty cells I get "TypeError: 'float' object is not subscriptable".</p>
<pre><code>def right(x):
return... | <p>I'd modify your function to skip the floats (which are actually NaNs):</p>
<pre><code>def right(x):
if np.isnan(x):
return np.nan
return x[-70:]
</code></pre> | python|pandas|dataframe | 0 |
8,339 | 52,284,482 | How can I divide sub-selections of a data frame by another data frame using minimal memory usage in python? | <p>I have a dataframe with many columns and I want to divide it by another data frame at regular column intervals with minimal memory usage. </p>
<p>For example: </p>
<pre><code>df1 = pd.DataFrame([[1,2,3,4,5,6,7,8,9,10], [10,9,8,7,6,5,4,3,2,1], [2,4,3,1,6,5,7,8,9,4]])
df2 = pd.DataFrame([[1,3],[7,6],[9,3]])
</code><... | <h3>Using <code>pd.concat</code>:</h3>
<pre><code>res = pd.concat([df2]*5, 1)
res.columns = df1.columns
df1/res
</code></pre>
<p></p>
<pre><code> 0 1 2 3 ... 6 7 8 9
0 1.000000 0.666667 3.000000 1.333333 ... 7.000000 2.666667 9.0000... | python|pandas|dataframe | 2 |
8,340 | 52,009,579 | qr decomposition of a matrix | <p>I want to compute the qr decomposition of a matrix
Here is my code</p>
<pre><code>const a = tf.tensor([1, 2, 3, 4], [2, 2]);
a.print()
const [b, c] = tf.qr(a)
b.print()
</code></pre>
<p>But it is throwing the following error</p>
<blockquote>
<p>tf.qr is not a function or its return value is not iterable</p>
</b... | <p>The documentation is not clear about <a href="https://js.tensorflow.org/api/0.12.5/#qr" rel="nofollow noreferrer">tf.qr</a> and <a href="https://js.tensorflow.org/api/0.12.5/#gramSchmidt" rel="nofollow noreferrer">tf.gramSchmidt</a>. You need to use <code>tf.linalg.qr</code> and <code>tf.linalg.gramSchmidt</code> in... | tensorflow.js | 1 |
8,341 | 52,095,303 | Length of a datetimeindex in python | <p>I just cant find the answer and I know pandas eats problems like this for desert.</p>
<p>I have a <code>datetime index</code> and want to know its length, in years:</p>
<pre><code>idx=pd.date_range('2011-07-03', '2015-07-10')
</code></pre>
<p>expected output:</p>
<pre><code>4.0191 years (4 years and 7 days)
</... | <p>You can convert timedelta to days and then divide by <code>365.25</code> if is not necessary <code>100%</code> accuracy:</p>
<pre><code>idx=pd.date_range('2011-07-03', '2015-07-10')
print ((idx[-1]-idx[0]).days / 365.25)
4.0191649555099245
</code></pre>
<p>But if need <code>year</code>s with <code>day</code>s:</... | python|pandas|datetime|timedelta|datetimeindex | 4 |
8,342 | 72,623,188 | I want to split a single dataframe column into multiple oclumns | <p>I have a dataframe with 1 column and 5776 rows. I want to move every 76 rows into a new column so I am left with 76 columns and 76 rows. How do I do this?<a href="https://i.stack.imgur.com/RpWAa.png" rel="nofollow noreferrer">enter image description here</a></p> | <p>This might be the transpose of the matrix you want, and if so you can do wide_df = wide_df.T</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'column1':np.random.rand(5776)})
wide_df = pd.DataFrame(df['column1'].values.reshape((76,76)))
print(wide_df)
</code></pre> | pandas|dataframe | 3 |
8,343 | 72,621,164 | Tkinter Pandas Python App - Not Getting Value and Performing Calculation | <p>I'm fairly new to Python/Pandas/Tkinter and I'm attempting to build a tkinter application that can receive numerical inputs and then perform a WAC (weighted average coupon rate) calculation based on the given input.</p>
<p><a href="https://i.stack.imgur.com/zHt87.png" rel="nofollow noreferrer"><img src="https://i.st... | <ol>
<li><p>In the c3231_wac() function you are comparing an int value with the string <code>'SPECIAL_PROJ_CD'] == '3231'</code>, change: 3231.</p>
</li>
<li><p>After the replacement, you must recalculate the value of the "Rate_WT" column and only then calculate the WAC.</p>
</li>
</ol> | python|pandas|tkinter | 1 |
8,344 | 59,568,216 | Keras Add_loss throwing Operator Not allowed in Graph error | <p>I created a basic loss function that takes the CDF (cumsum of pdf) and does a mean_squared error between the two.</p>
<p>Here is the code:</p>
<pre><code>def tuner_loss(y_true, y_pred):
y_actual=K.cumsum(y_true)
y_pred=K.cumsum(y_pred)
return K.mean(K.square(y_actual-y_pred))
</code></pre>
<p>I tried ... | <p>Why not use the standard?</p>
<pre><code>model = Model(input_layer, output_layer)
model.compile(loss = tuner_loss, ...)
model.fit(input_data, output_data, ...)
</code></pre> | python|tensorflow|keras|neural-network | 0 |
8,345 | 59,877,664 | Return column names for 3 highest values in rows | <p>I'm trying to come up with a way to return the column names for the 3 highest values in each row of the table below. So far I've been able to return the highest value using idxmax but I haven't been able to figure out how to get the 2nd and 3rd highest. </p>
<pre><code> Clust Stat1 Stat2 Stat3 Stat4 ... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow noreferrer"><code>numpy.argsort</code></a> for positions of sorted values and filter all columns without first:</p>
<pre><code>a = df.iloc[:, 1:].to_numpy()
df['TopThree'] = df.columns[1:].to_numpy()[np.argsort(-a, a... | python|pandas | 4 |
8,346 | 59,805,592 | Why does renewing an optimizer give a bad result? | <p>I tried to change my optimizer, but first of all, I want to check whether the following two codes give the same results:</p>
<pre><code>optimizer = optim.Adam(params, lr)
for epoch in range(500):
....
optimizer.zero_grad()
loss.backward()
optimizer.step()
for epoch in range(500):
....
optimi... | <p>Different optimizers may have some "memory".<br>
For instance, <a href="https://pytorch.org/docs/stable/optim.html#torch.optim.Adam" rel="nofollow noreferrer"><code>Adam</code></a> updates rule tracks the first and second moments of the gradients of each parameter and uses them to calculate the step size for each pa... | python|optimization|pytorch | 3 |
8,347 | 59,732,495 | running keras in jupyter notebook, windows 10,64 bit system | <p>running keras gives me following error:</p>
<pre><code>Using TensorFlow backend.
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
Traceback (most recent ca... | <p>Try uninstall and install <code>TensorFlow</code>. If you use conda:</p>
<pre><code>conda uninstall tensorflow
conda uninstall keras
conda install tensorflow
conda install keras
</code></pre>
<p>Next time, it is better to provide the code you run, not just error. In that case, people can better help you. </p> | python-3.x|tensorflow|keras|jupyter-notebook|command-prompt | 1 |
8,348 | 61,711,534 | Do operation and add it to new column depending on pattern in pandas | <p>I have a dataframe such as </p>
<pre><code>COL1 COL2 COL3 COL4
SEQ_1:HDHD_DIDH(-):DUUD_37 1 40 80000
SEQ_2:HDHD_DIDH(-):DUUD_35 90 456 766
QTTSS:XGGGD(+)JJDDH_0 4 990 3556
QTTSS:XGGGD(-)JJDDH_099 6 7789 90000
HYYH:LHGGH(+)FTT_H 667 88990 1... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a>:</p>
<pre><code>In [56]: import numpy as np ... | python|pandas | 2 |
8,349 | 61,849,079 | Pandas: how to drop rows if contains more that 2 entries? | <p>I have a dataframe like the following</p>
<pre><code>df
entry
0 (5, 4)
1 (4, 2, 1)
2 (0, 1)
3 (2, 7)
4 (9, 4, 3)
</code></pre>
<p>I would like to keep only the <code>entry</code> that contains two values</p>
<pre><code>df
entry
0 (5, 4)
1 (0, 1)
2 (1, 7)
</code>... | <p>If there are tuples use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>Series.str.len</code></a> for lengths and compare by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.le.html" rel="nofollow noreferre... | python|pandas | 2 |
8,350 | 58,125,373 | Converting Data Types in Multiple Columns to Date | <p>I'm new to Python3 and I've been searching for a way to convert multiple string columns to dates using the to_datetime function but haven't had any luck. Currently, I have 4 columns that need to be converted from their originating data type to a date ("yyyy-mm-dd"). Below is a sample of the code I've written, while ... | <p>Maybe use loop? </p>
<pre><code>date_cols = ['Dob','Appt_Date','Payment_Date','Collection_Date']
for col_name in date_cols:
df[col_name] = pd.to_datetime(df[col_name], format='%Y%m%d', errors='coerce')
</code></pre> | python-3.x|pandas | 1 |
8,351 | 58,117,576 | How can I loop through a DataFrame and build a new one (with conditions)? | <p>So I created a DataFrame for my question:</p>
<pre class="lang-py prettyprint-override"><code>
import pandas as pd
import random
median = random.uniform(0, 1)
data = [[random.uniform(0, 1), random.uniform(0, 1)], [random.uniform(0, 1), random.uniform(0, 1)], [random.uniform(0, 1), random.uniform(0, 1)]]
df= pd.Data... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">np.where</a>:</p>
<pre><code>new_dataframe=pd.DataFrame(np.where(df['A']>median,df['B']-0.1,df['B']+0.1),columns=['new_dataframe'])
print(new_dataframe)
new_dataframe
0 0.463859
1 0.86878... | python-3.x|pandas|function|loops|dataframe | 0 |
8,352 | 54,993,345 | datetime instead of str in read_excell with pandas | <p>I have a dataset saved in an xls file.<br>
In this dataset there are 4 columns that represent dates, in the format dd/mm/yyyy.<br>
My problem is that when I read it in python using pandas and the function read_excel all the columns are read as string, except one, read as datetime64[ns], also if I specify dtypes={col... | <p>Dates in Excel are frequently stored as numbers, which allows you to do things like subtract them, even though they might be displayed as human-readable dates like dd/mm/yyyy. Pandas is handily taking those numbers and interpreting them as dates, which lets you deal with them more flexibly.</p>
<p>To turn them into... | string|pandas|datetime | 1 |
8,353 | 54,854,821 | Concatenate two data-frames (dask) with the same number of partitions but different number of columns | <p>I have two data-frames with the same number of partitions. I want to concatenate these data-frames (first partition with first partition, the second one with the second one, etc.) Therefore, the final data-frame has the initial number of partitions (<code>V</code>), the same number of rows in every partition (<code>... | <p>This is not too hard:</p>
<pre><code>C = dd.from_delayed([dask.delayed(pd.concat)([a, b])
for a, b in zip(A.to_delayed(), B.to_delayed())],
meta=A._meta)
</code></pre>
<p>explanation</p>
<ul>
<li>get the partitions of each dataframe as delayed objects</li>
<li>pass pairs of these to <code>concat</code></l... | python|pandas|dataframe|dask | 2 |
8,354 | 54,991,008 | AttributeError: 'Series' object has no attribute 'iterrows' | <pre><code>accounts = pd.read_csv('C:/*******/New_export.txt', sep=",", dtype={'number': object})
accounts.columns = ["Number", "F"]
for i, j in accounts["Number"].iterrows(): #i represents the row(index number), j is the number
if (str(j) == "27*******5"):
print(accounts["F"][i], accounts["Number"][i])
</... | <p><code>accounts["Number"]</code> is a <em>Series</em> object, not a DataFrame. Either iterate over <code>accounts.iterrows()</code> and take the <code>Number</code> column from each row, or use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.iteritems.html" rel="noreferrer"><code... | python-3.x|pandas|loops | 36 |
8,355 | 73,331,494 | What is the difference betweend pandas.Series.items() and pandas.Series.iteritems()? | <p>As you can see the documentation pages for <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.items.html" rel="nofollow noreferrer">Series.items()</a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.iteritems.html" rel="nofollow noreferrer">Series.iteritems()</a> are identica... | <p><code>Series.iteritems()</code> just calls <code>Series.items()</code> under the hood, see source code below:</p>
<pre class="lang-py prettyprint-override"><code>def iteritems(self) -> Iterable[tuple[Hashable, Any]]:
return self.items()
</code></pre>
<p><a href="https://github.com/pandas-dev/pandas/blob/v1.4.... | python|pandas|documentation | 1 |
8,356 | 73,520,608 | assign a time period to each value of a column in a Pandas dataframe | <p>I have a pandas dataframe with one of the columns being a date. I need to create another column which would be a start (or end, doesn't matter) of a 2W period containing this date. Ideally this would be generalizable to any offset used by <code>pd.Grouper</code>.</p>
<p>Knowing <code>pd.Grouper</code> I can come up ... | <p>Try to use the following:</p>
<pre><code>pd.Timedelta(days=14)
df[‘date’] = df[‘2A_date_grouper’] + pd.Timedelta(days=14)
</code></pre>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/timedeltas.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/timedeltas.html</a></p> | python|pandas|dataframe|group-by | -2 |
8,357 | 67,507,052 | Pandas: sort according to a row | <p>I have a Dataframe like this (with labels on rows and columns):</p>
<pre><code> 0 1 2 3
0 1 1 0 0
1 0 1 1 0
2 1 0 1 0
-1 5 6 3 2
</code></pre>
<p>I would like to order the columns according to the last row (and then drop the row):</p>
<pre><code> 0 1 2 3
0 1 1 0 0
1 1 0 1 0
2 0 1 1 0
</code></pr... | <p>Try <code>np.argsort</code> to get the order, then <code>iloc</code> to rearrange columns and drop rows:</p>
<pre><code>df.iloc[:-1, np.argsort(-df.iloc[-1])]
</code></pre>
<p>Output:</p>
<pre><code> 1 0 2 3
0 1 1 0 0
1 1 0 1 0
2 0 1 1 0
</code></pre> | python|pandas | 1 |
8,358 | 67,246,703 | Tensorflow running on terminal but not with my code editor | <p>I have created a venv and installed the tenserflow via pip, checked the versions and everything seems fine. However, when I want to run my code (simply <strong>import <strong>tensor</strong>flow</strong>) it pops the following error.</p>
<pre><code>**ModuleNotFoundError: No module named 'tensorflow'**
</code></pre>
... | <p>According to your description, please refer to the following:</p>
<ol>
<li><p>The location where the module is installed is not the python environment currently used by VS Code.</p>
<p>Please use "<code>pip --version</code>" in the VS Code terminal to check whether the source of the module installation too... | python|macos|tensorflow|keras|visual-studio-code | 1 |
8,359 | 60,261,393 | Mapping values from series over a column to replace nan values pandas | <p>I have a DataFrame which has job numbers and the customer names associated with that job. There are instances where the job numbers have no customer name and therefore is null.
I have a separate series which has these job numbers as index and the missing customer names to replace the null values, based on the job nu... | <p>You could use <code>reset_index</code> with <code>combine_first</code>:</p>
<pre><code>(df.set_index('JobNumber').squeeze()
.combine_first(customers.set_index('Job').squeeze())
.reset_index())
index Customer
0 2123 Paul F
1 46456 Kara L
2 56823 Kevin T
3 62948 Sabrina... | python|pandas|dataframe|series | 1 |
8,360 | 60,332,169 | How can I output some data during a model.fit() run in tensorflow? | <p>I would like to print the value and/or the shape of a tensor during a <code>model.fit()</code> run and not before.
In PyTorch I can just put a print(input.shape) statement into the <code>model.forward()</code> function.</p>
<p>Is there something similar in TensorFlow?</p> | <p>You can pass a <em>callback</em> object to the <code>model.fit()</code> method and then perform actions at different stages during fitting.</p>
<p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/Callback" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/... | python|tensorflow|neural-network|pytorch | 2 |
8,361 | 65,067,042 | pandas frequency of a specific value per group | <p>Suppose I have data for 50K shoppers and the products they bought. I want to count the number of times each user purchased product "a". <code>value_counts</code> seems to be the fastest way to calculate these types of numbers for a grouped pandas data frame. However, I was surprised at how much slower it w... | <p>Filter before <code>value_counts</code></p>
<pre><code>df.loc[df.col2=='a','col1'].value_counts()['c0']
</code></pre>
<p>Also I think <code>crosstab</code> is 'faster' than <code>groupby</code> + <code>value_counts</code></p>
<pre><code>pd.crosstab(df.col1, df.col2)
</code></pre> | python|pandas|dataframe|pandas-groupby | 2 |
8,362 | 65,227,589 | Sort Pandas Dataframe based on previous row value | <p>I have a dataframe that looks like:</p>
<pre><code>Name Previous Name
Alice NaN
Charlie Bob
Bob Alice
Fred Eddy
Danny Charlie
Eddy Dan
</code></pre>
<p>I would like to sort the dataframe so that is looks like:</p>
<pre><code>Name Previous Name
Alice NaN
Bob Alice
Charlie ... | <p>Sort of values, then shift:</p>
<pre><code>df = df.sort_values('Value')
df['Previous Value'] = df['Value'].shift()
</code></pre>
<p>Output:</p>
<pre><code> Value Previous Value
0 A NaN
2 B A
1 C B
4 D C
5 E D
3 F E
<... | python|pandas|dataframe|sorting | 0 |
8,363 | 65,358,010 | AttributeError: module 'tensorflow' has no attribute 'string_join' | <p>I'm reading an introductory book to tensorflow and encountered an error with the first code snippet.</p>
<pre><code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
msg = tf.string_join(["Hello ", "TensorFlow"])... | <p><code>string_join</code> seems to be from <a href="https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/strings/join" rel="nofollow noreferrer">Tensorflow 1</a>. Notice the alias of <code>string_join</code> for <code>tf.strings.join</code>.</p>
<p>However in <a href="https://www.tensorflow.org/api_docs/pyth... | python|tensorflow | 1 |
8,364 | 65,468,026 | norm.ppf vs norm.cdf in python's scipy.stats | <p>so i have pasted my complete code for your reference, i want to know what's the use of ppf and cdf here? can you explain it? i did some research and found out that ppf(percent point function) is an inverse of CDF(comulative distribution function)
if they really are, shouldn't this code work if i replaced ppf and cdf... | <p>The <code>.cdf()</code> function calculates the probability for a given normal distribution value, while the <code>.ppf()</code> function calculates the normal distribution value for which a given probability is the required value. These are inverse of each other in this particular sense.</p>
<p>To illustrate this c... | python|numpy|data-science|hypothesis-test|scipy.stats | 11 |
8,365 | 49,912,441 | How to get batch size back from a tensorflow dataset? | <p>It is recommended to use tensorflow dataset as the input pipeline which can be set up as follows:</p>
<pre><code># Specify dataset
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
# Suffle
dataset = dataset.shuffle(buffer_size=1e5)
# Specify batch size
dataset = dataset.batch(128)
# Create an ite... | <p>In TF2 at least, the type of a dataset is statically defined and accessible via <code>tf.data.Dataset.element_spec</code>.</p>
<p>This is a somewhat complex return type because it has tuple nesting that matches your Dataset.</p>
<pre class="lang-py prettyprint-override"><code>>>> tf.data.Dataset.from_tensor... | tensorflow|issue-tracking|tensorflow-datasets | 1 |
8,366 | 63,850,929 | Building forecast Pandas DataFrame | <p>I have a DataFrame in Pandas that contains forecasted sales data that looks like this:</p>
<pre><code> | Date | ProductID | Forecasted_Date | Sales |
---|-------|-----------|-----------------|-------|
0 | 1_Jan | 1 | 2_Jan | 10 |
1 | 1_Jan | 2 | 3_Jan | 3 |
2 | 1_Jan ... | <p>I figured it out.</p>
<p>If <code>df</code> is my base dataframe...</p>
<ol>
<li>Find difference in days, assuming Date and Forecasted_Date are in Datetime format:</li>
</ol>
<pre><code>df['difference'] = (df['Forecasted_Date'] - df['Date']) / pd.Timedelta(1,'D'))
</code></pre>
<ol start="2">
<li>Convert to required... | python|pandas | 1 |
8,367 | 46,900,915 | Object detection: Error with Export/Import for inference | <p>I am a beginner in machine learning and currently trying to follow the tutorial given in the following link <a href="https://github.com/tensorflow/models/blob/master/object_detection/g3doc/exporting_models.md" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/object_detection/g3doc/exporting... | <p>I have try print all argument and see:</p>
<blockquote>
<p>trained_checkpoint_prefix = "{Your path}\models\train\" \ --output_directory=output_inference_graph.pb \</p>
</blockquote>
<p>Its seem to be missing "\" in "{Your path}\models\train\"</p>
<p>Try with add more "\" after "train\" --> "train\\"</p>
<pre><... | python|tensorflow|object-detection | 0 |
8,368 | 46,972,640 | Find rows whose values are less/greater than rows of another dataFrame | <p>I have 2 dataframes:</p>
<pre><code>df = pd.DataFrame({'begin': [10, 20, 30, 40, 50],
'end': [15, 23, 36, 48, 56]})
begin end
0 10 15
1 20 23
2 30 36
3 40 48
4 50 56
df2 = pd.DataFrame({'begin2': [12, 13, 22, 40],
'end2': [14, 13, 26, 48]... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>... | python|pandas | 1 |
8,369 | 46,993,291 | Python: Plot histogram of dataframe with one column as the labels, and the other as the values | <p>I have a dataframe with two columns. I want to plot a histogram with the 'Word_Length' column as the x-axis labels and the y-axis values as the 'Count'</p>
<p>Here's a short example of what the data looks like. Both Columns values are integers.</p>
<pre><code>Word_Length Count
1 265
9 6... | <p>I guess you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html" rel="nofollow noreferrer"><code>DataFrame.plot.bar</code></a>, because <a href="https://en.wikipedia.org/wiki/Histogram" rel="nofollow noreferrer"><code>histogram</code></a> is an accurate graphical repres... | python|pandas | 0 |
8,370 | 63,023,793 | How to prevent the initial pytorch variable from changing using a function? | <p>I want to apply a function to the variable <code>x</code> and saved as <code>y</code>. But why the <code>x</code> is also changed? How to prevent it?</p>
<pre><code>import torch
def minus_min(raw):
for col_i in range(len(raw[0])):
new=raw
new[:,col_i] = (raw[:,col_i] - raw[:,col_i].min())
return new
x=t... | <p>Because this assignment:</p>
<pre class="lang-py prettyprint-override"><code>new[:,col_i] = (raw[:,col_i] - raw[:,col_i].min())
</code></pre>
<p>is an in-place operation. Therefore, <code>x</code> and <code>y</code> will share the underlying <code>.data</code>.</p>
<p>The smallest change that would solve this issue ... | function|pytorch|tensor | 2 |
8,371 | 63,041,257 | Merge Excel files with pandas in python | <p>I'm almost done with merging excel files with pandas in python but when I give the path it wont work. I get the error ''No such file or directory: 'file1.xlsx'''. When I leave the path empty it work but I want to decide from what folder it should take files from. AND I saved the file the folder 'excel'</p>
<pre><cod... | <p>pd.read_excel(file) looks for the file relative to the path where the script is executed. If you execute in '/Users/Viktor/' try with:</p>
<pre><code>import os
import pandas as pd
cwd = os.path.abspath('/Users/Viktor/downloads/excel') #If i leave it empty and have files in /Viktor it works but I have the desired ex... | python|excel|pandas | 2 |
8,372 | 63,105,754 | How do I calculate lambda to use scipy.special.boxcox1p function for my entire dataframe of 500 columns? | <p>I have a dataframe with total sales of around 500 product categories in each row. So there are 500 columns in my dataframe. I am trying to find the highest correlated category with my another dataframe columns.
So I will use Pearson correlation method for this.
But the Total sales for all the categories are highly s... | <p>Assume <code>df</code> is Your dataframe with many columns containing numeric values, and lambda parameter of box-cox transformation equals 0.25, then:</p>
<pre><code>from scipy.special import boxcox1p
df_boxcox = df.apply(lambda x: boxcox1p(x,0.25))
</code></pre>
<p>Now transformed values are in <code>df_boxcox</c... | python|pandas|logging|transformation|pearson-correlation | 5 |
8,373 | 67,639,478 | Is there a significant speed improvement when using transformers tokenizer over batch compared to per item? | <p>is calling tokenizer on a batch significantly faster than on calling it on each item in a batch? e.g.</p>
<pre class="lang-py prettyprint-override"><code>encodings = tokenizer(sentences)
# vs
encodings = [tokenizer(x) for x in sentences]
</code></pre> | <p>i ended up just timing both in case it's interesting for someone else</p>
<pre><code>%%timeit
for _ in range(10**4): tokenizer("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
785 ms ± 24.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
tokenizer(["Lorem ipsum dolor sit amet... | pytorch|huggingface-transformers | 2 |
8,374 | 61,553,229 | Pandas: How to find the average length of days for a local outbreak to peak in a COVID-19 dataframe? | <p>Let's say I have this dataframe containing the difference in number of active cases from previous value in each country:</p>
<pre><code>[in]
import pandas as pd
import numpy as np
active_cases = {'Day(s) since outbreak':['0', '1', '2', '3', '4', '5'], 'Australia':[np.NaN, 10, 10, -10, -20, -20], 'Albania':[np.NaN, ... | <p>you can <code>set_index</code> the column <code>Day(s) since outbreak</code>, then use <code>iloc</code> to select all rows except the first one, then check where the values are less than (<code>lt</code>) 0. Use <code>idxmax</code> to get the first row where the value is less than 0 and take the <code>mean</code>. ... | python|pandas|numpy|dataframe | 1 |
8,375 | 61,217,403 | How to convert XLA_GPU into GPU | <p>My OS is Ubuntu 18.04 and my GPU is GTX850M. I'm using nvidia drivers 430.50, <code>CUDA 10.1</code> ,<code>CuDNN 9.0</code> and <code>tensorflow-gpu 1.14.0</code>. When I try getting available devices in tensorflow with</p>
<pre><code>from tensorflow.python.client import device_lib
device_lib.list_local_devices()... | <p>Your output says that, there was issue with <code>Tensorflow GPU</code> installation.</p>
<blockquote>
<p>I'm using nvidia drivers 430.50, CUDA 10.1 ,CuDNN 9.0 and
tensorflow-gpu 1.14.0.</p>
</blockquote>
<p>According to <a href="https://www.tensorflow.org/install/source#gpu" rel="nofollow noreferrer">Tensorflow tes... | python|tensorflow|gpu | 0 |
8,376 | 61,205,873 | Group values in NxN matrix into a N/2 x N/2 matrix | <p>Let's assume I have the following 4x4 matrix:</p>
<pre><code>import numpy as np
np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12],
[13,14,15,16]])
</code></pre>
<p>I wish to group the values in 2x2 submatrices, sum them and gather the result in a 2x2 matrix, so that the result in thi... | <p>You can use <code>.reshape</code> method and then sum along axis:</p>
<pre><code>import numpy as np
data = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12],
[13,14,15,16]])
bs = 2 #block size
data_r = data.reshape(bs,bs,bs,bs)
data_r
array([[[[ 1, 2],
... | python|numpy | 1 |
8,377 | 68,455,178 | read txt file with multiple tab & space separated values in pandas | <p>I want to read a fixed width <strong>file.txt</strong> using pandas like this :</p>
<pre><code>option19971675181 ACHILLE BLA BLA BLA1 blabla 88 498
option19971675182 ACHILLE BLA BLA BLA1 blabla 176 498
option19971675183 ACHIL... | <p>Assuming your text file is spaced exactly as in your question, try with the following:</p>
<pre><code>df = pd.read_csv("test.txt", delimiter ="\s\s+")
df[df.columns[0]] = df[df.columns[0]].str.replace("option199716","")
>>> df
0 1 2 3 4
0 ... | python|pandas | 1 |
8,378 | 52,939,042 | Tensorflowsharp and Retinanet -- How to determine what to Fetch when graph is run? | <p>I've been using TensorflowSharp with Faster RCNN successfully for a while now; however, I recently trained a Retinanet model, verified it works in python, and have created a frozen pb file for use with Tensorflow. For FRCNN, there is an example in the TensorflowSharp GitHub repo that shows how to run/fetch this mod... | <p>I am not sure exactly the problem you are facing; You can get the ouputs from TF Serving output, Actually in retinanet Ipython/Jupyter notebook they have mentioned the output format as well</p>
<p>Querying the save model gives</p>
<pre><code> """ The given SavedModel SignatureDef contains the following output(s)... | tensorflow|tensorflowsharp | 0 |
8,379 | 65,801,868 | Cold start recommender system implementation | <p>I have to implement a recommender system model.
The data I have been provided is unique ID and ICD codes of the patients.
How am I supposed to build the system when every new case has a unique id and there seems to be no relationship between the data?</p> | <h1>Two ways:</h1>
<h2>1. regard it as a unk id and train your model every day .</h2>
<h2>2. online learning for every new id .</h2> | python-3.x|machine-learning|tensorflow2.0|recommendation-system | 0 |
8,380 | 65,805,813 | Create line plot from dataframe with two columns index | <p>I have the following dataframe:</p>
<pre><code>>>> mean_traf_tie
a d c
0.22 0.99 0.11 22
0.23 21
0.34 34
0.46 45
0.44 0.99 0.11 45
0.23 6... | <p>Update:
I Have managed to go over it by concatinating the two index columns to one before plotting like this:</p>
<pre><code>df['a,d'] = list(zip(df.a, df.d))
df=df.groupby(['a,d','C']).mean()
df.unstack(level=0).plot(figsize=(10,6))
</code></pre>
<p><a href="https://i.stack.imgur.com/J2gwa.png" rel="nofollow nore... | python|pandas|matplotlib|multi-index|line-plot | 0 |
8,381 | 63,643,708 | Sum values in a list contained in every row of a column pandas dataframe | <p>I have a df where every row in the column <code>"numbers"</code> is a list of floats. I want to add a column to the df with the sum of those floats.</p>
<pre><code>#current output
letter numbers
a [0.0, 0.1, 2.3]
b [5, 6.7, 11.21]
#desired output
letter numbers sum_result
a ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="noreferrer"><code>Series.apply</code></a> with <code>sum</code>:</p>
<pre><code>df['sum_result'] = df['numbers'].apply(sum)
</code></pre>
<p>Or <code>list comprehension</code>:</p>
<pre><code>df['sum_result'] = [sum... | python|pandas|list|dataframe | 6 |
8,382 | 63,670,931 | Create a date counter variable starting with a particular date | <p>I have a variable as:
<code>start_dt = 201901</code> which is basically Jan 2019</p>
<p>I have an initial data frame as:</p>
<pre><code>month
0
1
2
3
4
</code></pre>
<p>I want to add a new column (date) to the dataframe where for month 0, the date is the <code>start_dt</code> - 1 month, and for subsequent months, th... | <p>You can subtract <code>1</code> and add datetimes converted to month periods by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.to_period.html" rel="nofollow noreferrer"><code>Timestamp.to_period</code></a> and then output convert to timestamps by <a href="http://pandas.pydata.org... | python|pandas|datetime | 1 |
8,383 | 71,821,463 | Extract elements from a list into a dataframe based on a regex string | <p>I have a list that is built like this:</p>
<pre><code>mylist = ['2003 00045', 'John', 'Closed', '4/10/21', '19675-B', '2001 00065',
'Kate', 'Approved', '2005 00054', 'True']
</code></pre>
<p>I am trying to build a dataframe where the first column will contain all of the identifiers in the list (e.g., '2003 00045', '... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>import re
r = re.compile(r"\d{4} \d{5}")
data, id_ = {}, None
for v in mylist:
if (m := r.match(v)):
id_ = m.group(0)
else:
data.setdefault(id_, []).append(v)
df = pd.DataFrame(
[{"col1": k, "col2": ... | python|pandas|list|dataframe | 2 |
8,384 | 56,677,980 | Reading values within pandas.groupby | <p>I have a dataframe like below</p>
<pre><code> name item
0 Jack A
1 Sarah B
2 Ross A
3 Sean C
4 Jack C
5 Ross B
</code></pre>
<p>What I like to do is to produce a dictionary that connects people to the products they are related to.</p>
<pre><code>{Jack: [1, 0, 1], Sarah: [0, 1, ... | <p>Check with <code>crosstab</code> and <code>to_dict</code></p>
<pre><code>pd.crosstab(df.item,df.name).to_dict('l')
{'Jack': [1, 0, 1], 'Ross': [1, 1, 0], 'Sarah': [0, 1, 0], 'Sean': [0, 0, 1]}
</code></pre>
<hr>
<p>Another interesting option is using <code>str.get_dummies</code>:</p>
<pre><code># if you need cou... | pandas|pandas-groupby | 4 |
8,385 | 47,399,201 | How to store a dictionary and map words to ints when using Tensorflow Serving? | <p>I have trained an LSTM RNN classification model on Tensorflow. I was saving and restoring checkpoints to retrain and use the model for testing. Now I want to use Tensorflow serving so that I can use the model in production.</p>
<p>Initially, I would parse through a corpus to create my dictionary which is then used ... | <p>One approach to this is storing the vocabulary in the model's graph. This will then be shipped with the model. </p>
<pre><code>...
vocab_table = lookup.index_table_from_file(vocabulary_file='data/vocab.csv', num_oov_buckets=1, default_value=-1)
text = features[commons.FEATURE_COL]
words = tf.string_split(text)
de... | machine-learning|tensorflow|lstm|tensorflow-serving|word-embedding | 0 |
8,386 | 47,393,658 | Pandas generate missing dates & hours with 0 values | <p>I have this dataframe :</p>
<pre><code>date station count
2015-01-01 13:00:00 A 4
2015-01-01 14:00:00 B 2
2015-01-02 15:00:00 A 7
</code></pre>
<p>For simplicity, pretend that the station only have 2 values : A & B</p>
<p>My goal is to generate 0 count fo... | <p>For me it working nice, small improvement is use parameter <code>fill_value=0</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a>:</p>
<pre><code>new_index = pd.MultiIndex.from_product([all_dates, station_index], ... | python|pandas|dataframe|time-series | 1 |
8,387 | 47,118,677 | Does Numpy fancy indexing copy values directly to another array? | <p>According to the documentation that I could find, when using fancy indexing a copy rather than a view is returned. However, I couldn't figure out what its behavior is during assignment to another array, for instance:</p>
<pre><code>A = np.arange(0,10)
B = np.arange(-10,0)
fancy_slice = np.array([0,3,5])
A[fancy_sli... | <p>The interpreter will parse the code and issue the method calls as:</p>
<pre><code>A[idx] = B[idx]
A.__setitem__(idx, B.__getitem__(idx))
</code></pre>
<p>The <code>B</code> method is evaluated fully before being passed to the <code>A</code> method. <code>numpy</code> doesn't alter the Python interpreter or its s... | python|arrays|numpy | 3 |
8,388 | 47,313,765 | ValueError: Cannot feed value of shape (200,) for Tensor 'Placeholder_32:0', which has shape '(?, 1)' | <p>I am new to tensorflow. This code is just for a simple neural network.
I think the problem maybe is from:</p>
<pre><code>x_data = np.linspace(-0.5,0.5,200)[:np..newaxis]
</code></pre>
<p>I tried to write without <code>[:np.newaxis]</code>, but it looks like the same.</p>
<pre><code>import tensorflow as tf
import ... | <p>The defined placeholders (both <code>x</code> and <code>y</code>) are 2-dimensional, so you should reshape the input arrays to rank 2. Try to add this:</p>
<pre class="lang-py prettyprint-override"><code>x_data = x_data.reshape([-1,1])
y_data = y_data.reshape([-1,1])
</code></pre> | python|numpy|machine-learning|tensorflow|neural-network | 0 |
8,389 | 68,044,757 | Replacing -999 with a number but I want all replaced number to be different | <p>I have a Pandas DataFrame named <code>df</code> and in <code>df['salary']</code> column, there are 400 values represented by same number <code>-999</code>. I want to replace that <code>-999</code> value with any number in between <code>200</code> and <code>500</code>. I want to replace all 400 values with a differen... | <p>You can use <code>Series.mask</code> with <code>np.random.randint</code>:</p>
<pre><code>df = pd.DataFrame({"salary":[0,1,2,3,4,5,-999,-999,-999,1,3,5,-999]})
df['salary'] = df["salary"].mask(df["salary"].eq(-999), np.random.randint(200, 500, size=len(df)))
print (df)
salary
0 ... | pandas | 0 |
8,390 | 68,283,105 | Merits of avoiding allocations for soft realtime NumPy/CPython | <p>I read that (soft) real-time programs often avoid heap allocations in part due to unpredictable timings, especially when stop-the-world (STW) garbage collection (GC) is used to free memory. I'm wondering if avoiding heap allocations is at all helpful for reducing lag in a main loop (say, 100 Hz) that uses NumPy and ... | <blockquote>
<p>CPython uses reference counting for the most part and a STW GC for cyclic references. Does that mean the STW part would never trigger if I don't use any objects with cyclic references? For example, scalars and NumPy arrays don't seem to have cyclic references, and most of them would not go beyond the fu... | python|numpy|garbage-collection|real-time|cpython | 2 |
8,391 | 57,167,200 | Unable to train from flow_from_dataframe Got unexpected no. of classes | <p>I am going to train a model on the set of images whose labels are in a csv file. So I used <code>flow_from_dataframe from tf.keras</code> and specified the parameters, but when it comes to <code>class_mode</code> it says errors and says <code>Found 3662 validated image filenames belonging to 1 classes.</code> - for ... | <p>"sparse" class mode requires integer value and "categorical" requires one hot encoded vector of your class columns. So I would try:</p>
<pre><code>df['diagnosis'] = df['diagnosis'].astype(str)
</code></pre>
<p>and then use "sparse" class mode.</p>
<pre><code>train_generator= train_datagen.flow_from_dataframe(
... | python|tensorflow|keras | 2 |
8,392 | 46,021,216 | Implementing attention with beam search in tensorflow | <p>I have written my own code with reference to <a href="https://github.com/tensorflow/nmt" rel="nofollow noreferrer">this</a> wonderful tutorial and I am not able to get results when using attention with beam search as per my understanding in the class AttentionModel the _build_decoder_cell function creates separate d... | <p>I'm not sure what do you mean by "I am not able to get results" but I'm assuming that your model is not making use of the wieghts learnt while training . </p>
<p>if this is the case , then first of all you need to know that its all about variable sharing , the first thing you need to do is that you get rid of the... | tensorflow | 2 |
8,393 | 50,687,475 | I am getting an error when I load Pandas and Numpy in | <p>I am getting below error when execute below:</p>
<pre><code>import numpy as np
</code></pre>
<p><strong>The full stack trace:</strong></p>
<pre><code> File "C:\Anaconda3\lib\site-packages\numpy\__init__.py", line 142, in <module>
from . import add_newdocs
File "C:\Anaconda3\lib\site-packages\numpy\a... | <p>This looks like some of the dependencies are missing for the package <code>numpy</code>. The DLL load failed error points towards either incorrectly installed and/or missing files for package numpy. You should just try installing numpy again through Anaconda CLI using the following command:</p>
<pre><code>conda ins... | python-3.x|numpy | 0 |
8,394 | 50,829,492 | Extract list of JSON objects in string form from Pandas Dataframe column | <p>I have a perfectly normal pandas dataframe which I create after loading this dataset: <a href="https://www.kaggle.com/tmdb/tmdb-movie-metadata/data" rel="nofollow noreferrer">https://www.kaggle.com/tmdb/tmdb-movie-metadata/data</a></p>
<p>As you can see, the genres column contains a nested structure which appears t... | <p>Use:</p>
<pre><code>import ast
obj_movies = pd.read_csv('tmdb_5000_movies.csv')
obj_movies['uniq'] = [list(set([y['name'] for y in x])) for x in obj_movies['genres'].apply(ast.literal_eval)]
print (obj_movies[['uniq'] ].head(10))
uniq
0 [Fantasy, Science Fiction, Advent... | python|pandas|dictionary | 1 |
8,395 | 66,451,513 | Check if Column exceeding specific value and replace | <p>I use the long list of codes similar to below codes, to check data frame with multiple columns</p>
<p>I need to check if the column has any values greater than Eg. 1000. If >1000 its error value, so make it '0'</p>
<pre><code>b=1000
a = np.array(df['E8'].values.tolist()); df['E8'] = np.where(a > b, 0, a).tolis... | <p>You can simplify your solution with list of columns names:</p>
<pre><code>np.random.seed(2021)
cols = ['E8','E9','E10', 'E37']
df = pd.DataFrame(np.random.randint(0, 2000, size=(10, 4)), columns=cols)
b = 1000
df[cols] = np.where(df[cols] > b, 0, df[cols])
print (df)
E8 E9 E10 E37
0 0 0 57 ... | python|pandas|numpy | 4 |
8,396 | 66,404,756 | Converting Mobilenet Model to TFLite changes input size | <p>right now I'm trying to convert a SavedModel to TFLite for use on a raspberry pi. The model is MobileNet Object Detection trained on a custom dataset. The SavedModel works perfectly, and retains the same shape of <code>(1, 150, 150, 3)</code>. However, when I convert it to a TFLite model using this code:</p>
<pre><c... | <p>You can rely on TFLite converter V1 API to set input shapes. Please check out the input_shapes argument in <a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1/lite/TFLiteConverter" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/compat/v1/lite/TFLiteConverter</a>.</p> | python|tensorflow|tensorflow-lite|mobilenet | 1 |
8,397 | 57,696,395 | Finding the difference between two rows, over specific columns | <p>I'm wondering how I would find the difference between a number of columns in a pandas dataframe, while keeping other columns intact.</p>
<p>So if I have DataFrame, DF, I would want to find the difference between columns (val1, val2, val3), while retaining month and year. User type is not important, and can be remov... | <pre><code>df.groupby(['mo','yr'])['val1','val2','val3'].apply(lambda x : x.iloc[1]-x.iloc[0]).reset_index()
</code></pre>
<p><strong>Output</strong></p>
<pre><code> mo yr val1 val2 val3
0 6 2017 9 18 27
</code></pre> | python|pandas|dataframe | 2 |
8,398 | 70,914,878 | Pandas treat the same DataFrame differently when read from excel or read from an API | <p>I wrote a script before that read an excel file first and then manipulated the data frame, I replaced the read_excel part with an API and transposed it to look exactly as the excel file but now When I use the data directly from the API the rest of the script doesn't work properly but when I save the df to_excel and ... | <p>This is not an answer but cannot format code in Comments. If I do this:</p>
<pre><code>dict1 = {0:
{0: r'u7it'},
1: {0: 'تست'},
2: {0: None},
3: {0: 'کاملا موافقم'},
4: {0: 'موافقم'},
5: {0: 'کاملا موافقم'}
}
df = pd.DataFrame(dict1)
df.columns=['ID','Name','Tel','1','2','3']
</code></pre>
<p>I get no errors and df... | python|pandas|dataframe | 0 |
8,399 | 71,018,656 | Getting error: module 'tensorflow.keras.layers' has no attribute 'Normalization' | <p>I am using</p>
<pre><code>tf.keras.layers.Normalization(axis=-1)
</code></pre>
<p>and am getting the following error:</p>
<pre><code>module 'tensorflow.keras.layers' has no attribute 'Normalization'
</code></pre>
<p>I'm following the tensorflow tutorial available <a href="https://www.tensorflow.org/tutorials/keras/r... | <p>For anyone who may be looking for answer, I ditched Anconda altogether and set up everything from scratch. Thanks for all the responses.</p> | python|tensorflow|keras | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.