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 |
|---|---|---|---|---|---|---|
4,900 | 69,079,214 | convert timestamp information to session information Python | <p>I have a dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">user</th>
<th style="text-align: center;">timestamp</th>
<th style="text-align: center;">minutes</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">Ram</td>
<td style="text-align... | <p>Increment the session_id when:</p>
<ol>
<li>The user changes, or</li>
<li>Minutes > 30</li>
</ol>
<h5>Code:</h5>
<pre><code>df["session_id"] = ((df["user"]!=df["user"].shift())|(df["minutes"]>30)).cumsum()
</code></pre>
<h5>Output:</h5>
<pre><code> user ... | python|pandas|dataframe|numpy | 2 |
4,901 | 68,873,625 | How does calculation in a GRU layer take place | <p>So I want to understand <strong>exactly</strong> how the outputs and hidden state of a GRU cell are calculated.</p>
<p>I obtained the pre-trained model from <a href="https://github.com/nanoporetech/taiyaki" rel="nofollow noreferrer">here</a> and the GRU layer has been defined as <code>nn.GRU(96, 96, bias=True)</code... | <p><strong>TLDR; This confusion comes from the fact that the weights of the layer are the concatenation of <em>input_hidden</em> and <em>hidden-hidden</em> respectively.</strong></p>
<hr />
<h4>- <a href="https://pytorch.org/docs/stable/generated/torch.nn.GRU.html" rel="nofollow noreferrer"><code>nn.GRU</code></a> laye... | pytorch|recurrent-neural-network|gated-recurrent-unit | 2 |
4,902 | 69,273,384 | Random sample the model scores into 4 groups with a similar distribution in python | <p>I have a dataset with model scores ranging from 0 to 1. The table looks like below:</p>
<pre><code>| Score |
| ----- |
| 0.55 |
| 0.67 |
| 0.21 |
| 0.05 |
| 0.91 |
| 0.15 |
| 0.33 |
| 0.47 |
</code></pre>
<p>I want to randomly divide these scores into 4 groups. <code>control</code>, <code>treatment 1</code>,... | <p>You can use <code>numpy.random.choice</code> to set random groups with defined probabilities, then <code>groupby</code> to split the dataframe:</p>
<pre><code>import numpy as np
group = np.random.choice(['control', 'treatment 1', 'treatment 2', 'treatment 3'],
size=len(df),
... | python|pandas|distribution | 1 |
4,903 | 44,771,853 | Mac: OSError: [Errno 1] Operation not permitted: '/tmp/pip-XcfgD6 | <p>When I played with tensorflow in Mac OS, I got this error:</p>
<pre><code>Installing collected packages: html5lib, bleach, markdown, backports.weakref, numpy, funcsigs, pbr, mock, protobuf, tensorflow
Found existing installation: numpy 1.8.0rc1
DEPRECATION: Uninstalling a distutils installed project (numpy) h... | <p>Add the argument <code>--ignore-installed</code> to the pip command you're running. See <a href="https://stackoverflow.com/questions/31900008/oserror-errno-1-operation-not-permitted-when-installing-scrapy-in-osx-10-11">this question for more</a>.</p> | python|tensorflow|sip | 11 |
4,904 | 44,727,726 | Nested list to a dictionary of index counts | <p>I'm very new to Python 3 and I'm working with Keras sigmoid activations which produce a nested list of probabilities.</p>
<p>I have a nested list that looks something like this:</p>
<pre><code>[[0.1, 0.2, 0.3, 0.2, 0.4, 0.5]
[0.2, 0.3, 0.3, 0.3, 0.2, 0.1]
...
[0.1, 0.1, 0.4, 0.5, 0.1, 0.2]]
</code></pre>
<p>Wh... | <p>With <code>a</code> as the list of lists of same lengths, we could convert to an array, giving us a <code>2D</code> array. Then, compare against <code>2</code> and then sum the <code>True</code> matches along each column, as the counts. Finally setup the output dictionary from it.</p>
<p>Thus, one implementation ... | python|list|numpy|dictionary|keras | 4 |
4,905 | 60,774,959 | Use part of string in DF | <p>Please a need to return a part of string</p>
<p>I have this (example):</p>
<pre><code>df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': ['XXX2100M', 'yyyy2100M', 'AAA850M',
'BBB2100M']})
</code></pre>
<p>My goal:</p>
<pre><code> vals ids test
0 1 XXX2100M 2100M
1 2 yyyy2100M 2100M
2 ... | <p>We can use <code>np.where</code> with <code>str.contains</code>:</p>
<pre><code>import numpy as np
df['test'] = np.where(df.ids.str.contains('2100M'), '2100M', '')
</code></pre>
<hr>
<pre><code>print(df)
vals ids test
0 1 XXX2100M 2100M
1 2 yyyy2100M 2100M
2 3 AAA850M
3 ... | python|pandas | 2 |
4,906 | 71,636,041 | Error on transfer learning model, ValueError: Unexpected result of `train_function` (Empty logs) | <p>thanks for reading, I am having an issue when using a transfer learning model. However I believe the issue is due to the model.fit_generator() as the exact same error occurs when I try to run my custom convolutional neural network.</p>
<pre><code># transfer learning model, vgg16
vgg = VGG16(input_shape= IMAGE_SIZE +... | <p>Check Your input images have a shape; they are grayscale or RGB, or the possibility of an empty input image.</p> | python|tensorflow|keras|conv-neural-network|transfer-learning | 0 |
4,907 | 69,859,163 | How to modify dataframe based on column values | <p>I want to add relationships to column 'relations' based on rel_list. Specifically, for each tuple, i.e. ('a', 'b'), I want to replace the relationships column value '' with 'b' in the first row, but no duplicate, meaning that for the 2nd row, don't replace '' with 'a', since they are considered as duplicated. The fo... | <p>You can craft a dataframe and <code>merge</code>:</p>
<pre><code>(df.drop('relations', axis=1)
.merge(pd.DataFrame(rel_list, columns=['names', 'relations']),
on='names',
how='outer'
)
# .fillna('') # uncomment to replace NaN with empty string
)
</code></pre>
<p>Output:</p>
<pre><co... | pandas|dataframe | 1 |
4,908 | 70,001,976 | How do I add the matching records of one of two different datasets with the same date to the other in python? | <p>I have 2 different datasets.</p>
<p>Table-1: df1</p>
<pre><code>Date sales product
2021-08-01 10000 a
2021-08-02 575 a
2021-08-03 12212 a
2021-08-04 902 a
2021-08-05 456 a
</code></pre>
<p>Table-2: df2</p>
<pre><code>Date sales product
2021-08-03 1000 b
20... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>pd.merge</code></a> on the date and sales columns, joining on Date on the left dataframe (df1), adding the suffixes _a and _b to the resulting column names. You can then fill i... | python|pandas|dataframe | 0 |
4,909 | 43,433,075 | Create list of tuples from 2d array | <p>I'm looking to create a list of tuples from a 2xn array where the first row is an ID and the second row is that IDs group assignment. I'd like to create a list of the IDs organized to their group assignments. </p>
<p>For example:</p>
<pre><code>array([[ 0., 1., 2., 3., 4., 5., 6.],
[ 1., 2., 1., 2.... | <p>The standard (sorry, not creative -- but reasonably quick) numpy way would be an indirect sort:</p>
<pre><code>import numpy as np
data = np.array([[ 0., 1., 2., 3., 4., 5., 6.],
[ 1., 2., 1., 2., 2., 1., 1.]])
index = np.argsort(data[1], kind='mergesort') # mergesort is a bit
... | python|arrays|numpy | 1 |
4,910 | 43,095,955 | Rename duplicated index values pandas DataFrame | <p>I have a DataFrame that contains some duplicated index values:</p>
<pre><code>df1 = pd.DataFrame( np.random.randn(6,6), columns = pd.date_range('1/1/2010', periods=6), index = {"A", "B", "C", "D", "E", "F"})
df1.rename(index = {"C": "A", "B": "E"}, inplace = 1)
ipdb> df1
2010-01-01 2010-01-02 2010-01-0... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.where.html" rel="noreferrer"><code>Index.where</code></a>:</p>
<pre><code>df1.index = df1.index.where(~df1.index.duplicated(), df1.index + '_dp')
print (df1)
2010-01-01 2010-01-02 2010-01-03 2010-01-04 2010-01-05 2010... | python|pandas | 24 |
4,911 | 43,167,362 | R to Python pandas numpy.where conversion | <p>what is the best way to write the following R code in Python (pandas dataframe) using numpy.where syntax.</p>
<pre><code>Data$new = ifelse(Data$Diff > 1.652*Data$Diff10, 1,
ifelse(Data$Diff < 3.95*Data$Diff10, -1, 0 ))
</code></pre> | <p>You can use:</p>
<pre><code>Data['new'] = np.where(Data['Diff'] > 1.652*Data['Diff10'], 1,
np.where(Data['Diff'] < 3.95*Data['Diff10'], -1, 0 ))
</code></pre>
<p>EDIT:</p>
<p>It seems code above have logic error, because never return <code>0</code>.</p>
<p>Maybe need:</p>
<pre><code>Data = p... | python|pandas|numpy | 0 |
4,912 | 43,382,237 | NumPy ndarray.all() vs np.all(ndarray) vs all(ndarray) | <p>What is the the difference between the three "all" methods in Python/NumPy? What is the reason for the performance difference? Is it true that ndarray.all() is always the fastest of the three?</p>
<p>Here is a timing test that I ran:</p>
<pre><code>In [59]: a = np.full(100000, True, dtype=bool)
In [60]: timeit a.... | <p>The difference between <code>np.all(a)</code> and <code>a.all()</code> is simple:</p>
<ul>
<li>If <code>a</code> is a <code>numpy.array</code> then <code>np.all()</code> will simply call <code>a.all()</code>.</li>
<li>If <code>a</code> is not a <code>numpy.array</code> the <code>np.all()</code> call will convert it... | python|performance|numpy | 11 |
4,913 | 72,379,115 | KDE shows higher count as compared acutal pandas dataframe | <p>I am getting started with Titanic Spaceship dataset. (<a href="https://www.kaggle.com/competitions/spaceship-titanic" rel="nofollow noreferrer">https://www.kaggle.com/competitions/spaceship-titanic</a>)</p>
<p>I am trying to understand the effect of the foodcourt feature on the transported result. On plotting a viol... | <p>I have tried the same code that you posted, the results I got from the violin plot (and swarm plot) are identical to the data.
Slicing the dataframe to the passengers that got transported and not transported:</p>
<pre><code>temp_0 = temp[temp["Transported"] == True]
temp_1 = temp[temp["Transported&quo... | python|pandas | 0 |
4,914 | 72,228,086 | Inconsistent indexing of subplots returned by `pandas.DataFrame.plot` when changing plot kind | <p>I know that, this issue is known and was already discussed. But I am encountering a strange behaviour, may be someone has idea why:
When I run this:</p>
<pre><code>plot = df.plot(kind="box", subplots=True, layout= (7,4), fontsize=12, figsize=(20,40))
fig = plot[0].get_figure()
fig.savefig(str(path) + "... | <p>This seems to be an inconsistency in Pandas. According to their <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html" rel="nofollow noreferrer">docs</a>, indeed, the <code>DataFrame</code>'s method <code>.plot()</code> should return</p>
<blockquote>
<p><code>matplotlib.axes.Axes</code> or... | python|pandas|numpy|plot|figure | 1 |
4,915 | 72,418,115 | FuncAnimation how to update text after each iteration | <p>I am trying to create an animation of a Monte-Carlo estimation of the number pi, for each iteration I would like the numerical estimation to be in text on the plot, but the previous text is not removed and makes the values unreadable. I tried <code>Artist.remove(frame)</code> with no success. The plot is done with J... | <p>As you have already done in <code> init_func</code>, you should clear the plot in each iteration with <code>ax.clear()</code>. Then it is necessary to edit slighlty the plot function:</p>
<pre><code>ax.plot(x[i:i+data_skip], y[i:i+data_skip], color='k')
</code></pre>
<p>And finally you have to fix x axis limits in e... | python|numpy|matplotlib|animation|math | 1 |
4,916 | 72,386,928 | Apply Function on Dataframe Returns RangeIndex Error | <p>Below is the code I'm trying to execute but I am getting the error:
<code>KeyError: 'None of [RangeIndex(start=0, stop=54, step=1)] are in the [columns]'</code></p>
<p>I've tried feeding in columns a few ways using dev_cols, feeding in RangeIndex identical to the index of the dataframe. I'm just a bit stuck.</p>
<pr... | <p>It is expected, because <code>dev</code> is empty DataFrame, so select by any column(s) failed:</p>
<pre><code>dev = pd.DataFrame()
dev[dev_sentences.columns]
</code></pre>
<p>Need:</p>
<pre><code>dev_sentences = pd.DataFrame(dev_sentences).astype(str)
dev = dev_sentences.copy()
dev['dev_combined'] = dev.apply(' '.j... | python|pandas | 0 |
4,917 | 50,252,761 | How to count comma seperated repeated values in a pandas column? | <p>I have a dataframe column like this:</p>
<pre><code>1 Applied Learning, Literacy & Language
2 Literacy & Language, Special Needs
3 Math & Science, Literacy & Language
4 Literacy & Language, Math & Science
6 Math & Science, Applied Learni... | <p>Try using <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="noreferrer"><code>collections.Counter</code></a>, which is built specifically for high performance of tasks like this one.</p>
<p>Say you start with</p>
<pre><code>df = pd.DataFrame({'Category': ['Applied Learning, Lite... | python|string|pandas|dataframe | 5 |
4,918 | 50,451,793 | Pandas pivot table selecting rows with maximum values | <p>I have pandas dataframe as:</p>
<pre><code>df
Id Name CaseId Value
82 A1 case1.01 37.71
1558 A3 case1.01 27.71
82 A1 case1.06 29.54
1558 A3 case1.06 29.54
82 A1 case1.11 12.09
1558 A3 case1.11 ... | <p><code>sort_values</code> + <code>drop_duplicates</code></p>
<pre><code>df.sort_values('Value').drop_duplicates(['Id'],keep='last')
Out[93]:
Id Name CaseId Value
7 1558 A3 case1.16 33.35
0 82 A1 case1.01 37.71
</code></pre>
<p>Since we post same time , adding more method </p>
<pre><code>df.so... | pandas|python-3.5 | 5 |
4,919 | 62,824,004 | Expected input batch_size (32) to match target batch_size (19840) BERT Classifier | <p>I ran into this error with code:</p>
<pre><code>model = BertForSequenceClassification.from_pretrained("pretrained/", num_labels=ohe_count)
model.to(device)
from IPython.display import clear_output
train_loss_set = []
train_loss = 0
model.train()
for step, batch in enumerate(train_dataloader):
# до... | <p>Never mind, I was trying to do multi-label classification, but BertForSequenceClassification can't do that.</p> | python|deep-learning|nlp|pytorch | 0 |
4,920 | 62,565,272 | How to split a column of dictionary type into two different pandas column of different type? | <p>I have a dataframe with 2 columns (plus index) like this, it has around 14,000 lines.</p>
<pre><code>Employee | RecordID
{'Id': 185, 'Title': 'Full Name'} | 9
</code></pre>
<p>I'd like to split the columns like this:</p>
<pre><code>Id | Title | RecordID
185 | 'Full Name' | ... | <p>You can do</p>
<pre><code>data_df1= data_df.dropna()
df2 = pd.DataFrame(data_df1["Employee"].values.tolist(), index= data_df1.index)
data_df=data_df.join(df2,how='left')
</code></pre> | python|pandas|dataframe|dictionary | 2 |
4,921 | 62,651,300 | pandas groupby and countif in multiple columns | <p>I have the following df</p>
<pre><code>import pandas as pd
# -- create a dataframe
list_columns = ['pet', 'grade', 'class']
list_data = [
['dog', 'A', 'A'],
['cat', 'A', 'C'],
['dog', 'B', 'E'],
['mouse', 'C', 'A'],
['dog', 'A', 'B'],
['cat', 'B', 'E'],
['dog', 'C', 'D'],
['dog', 'A'... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table... | python|pandas | 1 |
4,922 | 54,396,178 | Creating new pandas dataframe based on existing columns with duplicates | <p>I have a pandas dataframe that looks like</p>
<pre><code>Event Person Data
Event1 Person1 Data1
Event1 Person2 Data2
Event1 Person3 Data3
Event2 Person1 Data4
Event2 Person2 Data5
Event2 Person3 Data6
</code></pre>
<p>and so on. I would like to create a new dataframe w... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer">df.pivot()</a></p>
<pre><code>df.pivot(columns='Event', values='data', index='Person')
</code></pre>
<p>Output:</p>
<pre><code>Event Event1 Event2
Person
Person1 Data1 Da... | python|pandas|dataframe | 1 |
4,923 | 54,457,788 | Double backslashes for filepath_or_buffer with pd.read_csv | <p>Python 3.6, OS Windows 7</p>
<p>I am trying to read a .txt using <code>pd.read_csv()</code> using relative filepath. So, from pd.read_csv() API checked out that the filepath argument can be any valid string path. </p>
<p>So, in order to define the relative path I use pathlib module. I have defined the relative pat... | <p>You need a filename to call pd.read_csv. In the example 'a' is a only the path and does not point to a specific file. You could do something like this:</p>
<pre><code>df_rel_path = pathlib.Path.cwd() / ("folder1") / ("folder2")
a = str(df_rel_path)
df = pd.read_csv(a+'/' +'filename.txt')
</code></pre>
<p>With the ... | python-3.x|pandas|pathlib | 0 |
4,924 | 73,525,998 | How do I restore the normal color after blur-filtering this image with a NP matrix? | <p>I managed to blur an image using only a NP matrix, but for some reason can't restore the normal color channels to it. If someone can give me guidance on how to fix this without calling me an idiot, that would be appreciated.</p>
<pre><code>def convolve(image,kernel):
image_copy = image.copy()
height=image_co... | <p>First of all, you are not an idiot and don't take anyone seriously who calls you that. You made a strong first attempt at blurring an image and did a good job for the first try. You are almost there so be proud. To fix this, you should separate the Red, Green, and Blue channels before you do any blurring. Blur them ... | python|numpy|colors|numpy-ndarray|array-broadcasting | 1 |
4,925 | 73,637,365 | How to convert a json object into a dataframe when arrays are of different lengths? | <p>I am trying to convert a json format into a dataframe but getting an error saying "All arrays must be of the same length".
Below is the code. Any advice are highly appreciated.</p>
<p>I have the following codes</p>
<pre><code>import pandas as pd
import requests
import json
from pandas import json_normalize... | <p>Here is how to convert the entire json using Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.from_dict.html" rel="nofollow noreferrer">from_dict</a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transpose.html" rel="nofollow noreferrer">transpose</a> (T) met... | python-3.x|pandas|dataframe|python-requests | 1 |
4,926 | 71,241,648 | Get max time of grouped by time series dataframe | <p>I have a dataframe as follows:</p>
<pre><code>Date User Tag
2-22-2022 09:00:00 u1 a
2-22-2022 10:00:00 u1 b
2-22-2022 11:00:00 u2 c
2-23-2022 09:00:00 u1 a
2-23-2022 10:00:00 u2 b
</code></pre>
<p>Want to creat, for each user, a column with the time difference be... | <p>First of all, I had to split your calculation of the "diff" column in two steps to reach the same output as you:</p>
<pre><code>>>> df["diff"] = df.groupby("User")["Date"].diff()
>>> df["diff"] = df.groupby("User")["diff"].shift(... | pandas | 0 |
4,927 | 60,710,211 | Neural network classification loss from validation set: Does it update anything dynamically | <p>I'm attempting t study up a bit on the theory of training neural networks, and right now i have gotten to validation sets. </p>
<p>Now, I can understand that a validation set gives us a loss-index, which helps us in knowing whether we are overfitting or not. But when I read in books and and watch videos, everyone s... | <p><code>Loss</code> and <code>Accuracy</code> refer to the current loss and accuracy of the training set.</p>
<p>The <code>Loss</code> is being fixed during back propagation of the epoch to improve the <code>Accuracy</code>. </p>
<p>At the end of each epoch your trained Neural Network is evaluated against your valid... | tensorflow|artificial-intelligence | 0 |
4,928 | 72,796,183 | how to use keras demo code siamese_contrastive.py to use a custom dataset? | <p>I am following this example <a href="https://keras.io/examples/vision/siamese_contrastive/" rel="nofollow noreferrer">Image similarity estimation using a Siamese Network with a contrastive loss</a>.</p>
<p>The given code snippet reads directly from <code>keras.datasets.mnist.load_data()</code>.</p>
<p>I am trying to... | <p>You can load images like this :</p>
<pre><code>anchor_images = sorted([str(anchor_images_path / f) for f in os.listdir(anchor_images_path)])
</code></pre>
<p>Same for positives and negatives.</p>
<p><strong>Detailed example here:</strong></p>
<p><a href="https://keras.io/examples/vision/siamese_network/" rel="nofoll... | python|tensorflow|keras|deep-learning|siamese-network | 0 |
4,929 | 72,747,918 | Nested dictionary to Dataframe in the most efficient way possible | <p>I have a nested dictionary like this one:</p>
<pre><code>my_dict[user_profile][user_id][level] = [[9999, 'Heavy Purchaser', 340, 'Star_chest', 999, 1000],
[9999, 'Heavy Purchaser', 340, 'Star_chest', 998, 5],
[9999, 'Heavy Purchaser', 340, 'Star_chest', 3, 1],
[9999, 'Heavy Purchaser', 340, 'Star_chest', 4,... | <p>The data that you are starting with is <em>not</em> a nested dictionary, it is just a nested list. You may want to consider transitioning to a nested dictionary that would seem to make more sense for the type of data you are gathering... But that is another question. :)</p>
<p>In <code>pandas</code>, generally th... | python|pandas|dictionary|optimization|nested | 1 |
4,930 | 72,610,478 | Problem using Pandas for joining dataframes | <p>I am trying to join a lot of CSV files into a single dataframe after doing some conversions and filters, when I use the append method for the sn2 dataframe, the exported CSV contains all the data I want, however when I use the append method for the sn3 dataframe, only the data from the last CSV is exported, what am ... | <p>You have to pass <em>all</em> the dataframes that you want to concatenate to <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>sn3 = pd.concat([sn3, temp2])
</code></pre> | python|pandas|concatenation | 1 |
4,931 | 59,666,834 | Joining dataframe based on ranges | <p>I would like to left join one dataframe to another based on whether the values in the left data frame occur between a specified range indicated in the right dataframe:</p>
<pre><code>df1 = pd.DataFrame()
df2 = pd.DataFrame()
df1['col1'] = ['A', 'B', 'C', 'D','E']
df1['col2'] = ['alpha', 'beta', 'gamma', 'delta','ep... | <p>Here is another from <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.IntervalIndex.html" rel="nofollow noreferrer"><code>IntervalIndex</code></a> :</p>
<p>Note: <code>min</code> and <code>max</code> are methods (your df it is column names) so be careful if you use <code>.</code> (dot) not... | python|pandas | 2 |
4,932 | 59,687,567 | How to perform Kneser-Ney smoothing in NLTK at word-level for tri-gram language model? | <p>I am trying to train a tri-gram language model on a text corpus and want to perform KN smoothing. Apparently, the 'nltk.trigrams' does this at character-level. I was wondering how I would be able to do this at word-level and also perform KN smoothing. Here is a piece of code that I wrote and doesn't work: </p>
<pre... | <p>Replace the line:</p>
<pre><code>print(kneser_ney.prob('you go to'))
</code></pre>
<p>with:</p>
<pre><code>print(kneser_ney.prob('you go to'.split()))
</code></pre>
<p>Then it works ok. I get a value of 0.05217391304347826 when using a as training file the text from the novel "Moby Dick" downloaded from Project ... | python|nlp|nltk|pytorch|trigram | 0 |
4,933 | 61,966,029 | Convert text to binary columns | <p>I have a column in my dataframe that contains many different companies separated by commas (assume there are additional rows with even more companies).</p>
<pre><code>company
apple,microsoft,disney,nike
microsoft,adidas,amazon,eBay
</code></pre>
<p>I want to convert this to binary columns for every possible compan... | <p>Let us try <code>get_dummies</code></p>
<pre><code>s=df.brand.str.get_dummies(',')
adidas amazon apple disney eBay microsoft nike
0 0 0 1 1 0 1 1
1 1 1 0 0 1 1 0
</code></pre> | python|pandas|dataframe|text | 4 |
4,934 | 61,984,525 | Assigning List Values to Pandas df Column generates NaN or Length Error | <p>I have a DataFrame</p>
<pre><code> Close Delta
Date
2020-05-11 2920.50 -440
2020-05-11 2920.25 -9
2020-05-11 2920.25 -27
2020-05-11 2920.50 2
2020-05-11 2920.75 117
</code></pre>
<p>Now i'm calculating consecutive increments of 'Close' with this function:... | <p>There are a few issues with your solution that might stem from my misunderstanding of your goals.</p>
<p>If you want the column to have the same number of values as the other column, you will want to add a value to <code>tickbox</code> for EVERY element. In your case, you're not appending anything in the <code>else... | python|pandas|dataframe | 1 |
4,935 | 57,844,567 | How can I create a function that iterates a list and simultaneously creates a new column in a dataframe? | <p>I want to create a function that returns multiple columns containing moving averages with different windows. But I get only one column returned.</p>
<p>This is what I've tried:</p>
<pre><code>[3] data = pd.read_csv('data.csv')
[4] data.head()
[4] close
0 126.70
1 127.30
2 127.38
3 128.4... | <p>check line "return data". Should not be in for-loop.</p> | python|pandas | 0 |
4,936 | 58,010,075 | How to reduce time taken by to convert dask dataframe to pandas dataframe | <p>I have a function to read large csv files using dask dataframe and then convert to pandas dataframe, which takes quite a lot time. The code is:</p>
<pre><code>def t_createdd(Path):
dataframe = dd.read_csv(Path, sep = chr(1), encoding = "utf-16")
return dataframe
#Get the latest file
Array_EXT = "Export_GTT_Tea... | <p>I would encourage you to consider, with reference to the Dask documentation, why you would expect the process to be any faster than using Pandas alone.
Consider: </p>
<ul>
<li>file access may be from several threads, but you only have one disc interface bottleneck, and likely performs much better reading sequentia... | python-3.x|pandas|dask|dask-delayed | 1 |
4,937 | 54,975,554 | Converting a Dict having blank list (Values) to a df | <p>I'm a neophyte to pandas and have been struggling to convert a Dict to a df using <code>pd.DataFrame(Dict)</code>. Here's further detail: This Dict is part of a for loop that in every iteration reads in a new input file. As a result, Dict Values (lists) update every time and take different List sizes. The problem is... | <p>Running your dictionary example through the <code>pd.DataFrame(Dict)</code> command does not give me any errors, I just get an empty DataFrame. And that's how it should be, as those empty lists you have as values are not scalars, they are iterables. This <code>ValueError</code> shows up when all values are in fact... | python|pandas|list|dataframe|dictionary | 0 |
4,938 | 49,351,001 | Convert a list of dict that has list to one dataframe | <p>whats the most efficient way to convert this?</p>
<p>given a list of dict with a list.</p>
<pre><code>list_df = [
{'High':[2,3,4,5,5,3,3,4,5,5],'Low':[0,-3,1,4,1,2,2,3,1,-1],'Name':['A','A','A','A','A','A','A','A','A','A']},
{'High':[35,23,424,5,25,3,223,4,5,255],'Low':[3,3,44,5,2,3,22,2,1,25]},'Name':['B','B'... | <p>IIUC</p>
<pre><code>pd.concat([pd.DataFrame(x) for x in list_df])
Out[190]:
High Low Name
0 2 0 A
1 3 -3 A
2 4 1 A
3 5 4 A
4 5 1 A
5 3 2 A
6 3 2 A
7 4 3 A
8 5 1 A
9 5 -1 A
0 35 3 B
1 23 3 B
2 4... | pandas | 0 |
4,939 | 49,577,645 | ask user which column to read in pd.read_csv() | <p>I have a large data set with multiple columns and I would like the user to tell me which col to analyze.
so far I have:</p>
<pre><code>file = some_file
col_name = raw_input("Enter column name: ")
cols_used = ["X",col_name]
read_cols = pd.read_csv(file, usecols = cols_used, skiprows = [0,1], name =cols_used)
test =... | <p>this should work</p>
<pre><code>file = some_file
col_name = raw_input("Enter column name: ")
cols_used = ["X",col_name]
read_cols = pd.read_csv(file, usecols = cols_used, name =cols_used)
test = pd.unique(read_cols["X"])
</code></pre>
<p>it seams that </p>
<pre><code>skiprows = [0,1]
</code></pre>
<p>cause prob... | python|pandas | 0 |
4,940 | 49,469,337 | Finding the count of letters in each column | <p>I need to find the count of letters in each column as follows:</p>
<pre><code>String: ATCG
TGCA
AAGC
GCAT
</code></pre>
<p>string is a series.</p>
<p>I need to write a program to get the following:</p>
<pre><code> 0 1 2 3
A 2 1 1 1
T 1 1 0 1
C 0 1 2 1
G 1 1 1 1
</code></pre>
<p>I have ... | <p>Here is one way you can implement your logic. If required, you can turn your series into a list via <code>lst = s.tolist()</code>.</p>
<pre><code>lst = ['ATCG', 'TGCA', 'AAGC', 'GCAT']
arr = [[i.count(x) for i in zip(*lst)] for x in ('ATCG')]
res = pd.DataFrame(arr, index=list('ATCG'))
</code></pre>
<p><strong>R... | python|pandas|bioinformatics|biopython | 3 |
4,941 | 49,347,002 | pandas: count rows within time moving window | <pre><code>import pandas as pd
d = [{'col1' : ' B', 'col2' : '2015-3-06 01:37:57'},
{'col1' : ' A', 'col2' : '2015-3-06 01:39:57'},
{'col1' : ' A', 'col2' : '2015-3-06 01:45:28'},
{'col1' : ' B', 'col2' : '2015-3-06 02:31:44'},
{'col1' : ' B', 'col2' : '2015-3-06 03:55:45'},
{'col1' :... | <p>The problem is, that <code>apply</code> is very expensive.
One option is to optimize the code via cython or with the use of numba.</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/enhancingperf.html" rel="nofollow noreferrer">This</a> might be helpful.</p>
<p>Another option is the following:</p>
<ol>
... | python-3.x|pandas|dataframe|count | 3 |
4,942 | 49,772,706 | How to initialize a tuple of lists to columns of an existing DataFrame in python pandas | <p>I have a function which takes the text as input and returns a tuple of lists. I want to convert the tuple into columns of an existing DataFrame.</p>
<pre><code>def func(text):
// some code //
return (tuple)
</code></pre>
<p>The tuple is in this format:</p>
<pre><code>(['1','2','3'],['abc','def','efg'])
</... | <p>I believe you need convert output to <code>Series</code> if need columns of <code>list</code>s:</p>
<pre><code>df = pd.DataFrame({'col_text':range(5)})
def func(text):
a = (['1','2','3'],['abc','def','efg'])
return pd.Series(a)
df[['col1','col2']] = df.col_text.apply(func)
print (df)
col_text col... | python|pandas|tuples | 1 |
4,943 | 73,411,720 | Cross Regularization between two Neural Networks | <p>I am trying to add a loss term to regularise between two neural networks and make them as similar as possible while still performing different tasks. The closes I could find is the answers in this post:
<a href="https://stackoverflow.com/questions/44641976/pytorch-how-to-add-l1-regularizer-to-activations">Pytorch: h... | <p>Problem Solved. The issue seems to come from using <code>p.data</code> instead of <code>p</code> when getting <code>params</code>.</p>
<p>The working solution looks like this:</p>
<pre><code>params = t.cat(tuple(t.flatten(p) for p in net.parameters()))
assert params.requires_grad
distance = criterion(params, avg)
r... | python|machine-learning|neural-network|pytorch|loss-function | 0 |
4,944 | 59,919,391 | Why is match.columns.get_loc returning a boolean array, not an indice? | <p>I'm trying to identify the index position of a particular column name in Python. I used this exact same method previously on the same dataframe and it returned the number of the index position of the column name. However, in this case it doesn't seem to be working. Here is the relevant code:</p>
<p>The dataframe:</... | <p>Problem is both columns are duplicated, <code>home_player_1</code> and also <code>away_player_11</code> (and many another columns too).</p>
<p>So if same values in columns you can remove duplicated columns by:</p>
<pre><code>match = match.loc[:, ~match.columns.duplicated()]
</code></pre>
<p>Or you can deduplicate... | python|pandas | 4 |
4,945 | 65,157,083 | visualize tuple with entities grouped | <p>I have a tuple with named entity values in a Dataframe, how do I group the values by each entities over the column containing tuples and visualize it.</p>
<pre><code>s = pd.Series("At noon, Trump became the 45th president of the United States, taking the oath of office with Chief Justice John Roberts. Trump was... | <p>You don't have "a tuple with named entity values in a Dataframe". You have "a list of tuples".
In order to do that, you have to follow the instructions below:</p>
<p>Use a for-loop to iterate through a list of tuples. Within the for-loop, use the indexing syntax tuple[0] to access the first eleme... | python|pandas|matplotlib|seaborn | 0 |
4,946 | 65,399,531 | Forward fill pandas based on column conditions with increment | <p>I have the following dataframe. I would like to forward fill from the startTime till the endTime for each id I have.</p>
<pre><code>id current startTime endTime
1 2015-05-10 2015-05-10 2015-05-12
2 2015-07-11 2015-07-11 2015-07-13
3 2015-10-01 2015-10-01 2015-10-03
4 2015-12-01 None None
</code></pre>
... | <p>I use <code>date_range</code> and <code>explode</code> for this.</p>
<pre><code>df['current'] = df.apply(lambda row: row['current'] if row['startTime'] is None else pd.date_range(row['startTime'], row['endTime'], freq='D'), axis=1)
df = df.explode('current')
</code></pre> | python|pandas | 1 |
4,947 | 65,394,235 | How to compare last value to previous 6 values in pandas dataframe? | <p>Is there a way to find out if the last value is in the lower 50% range of the previous six days values? I want to add another column that shows yes or no. I tried sorting the previous six to get the middle value, but could not compare it to last and/or make it iterate to populate the new column. My data looks like ... | <p>Understanding your question as asking for the ratio of the previous day's closing price to the average of the previous six days, I created the following code. Sort the closing prices of the retrieved stocks in descending order. In a new column, use the rolling function to calculate the six-day average and add it. Th... | python|pandas|dataframe|finance|technical-indicator | 0 |
4,948 | 65,396,264 | How do I efficiently map transformations over a pandas DataFrame | <p>a bit of a funny ask.</p>
<p>I have a (big) table that looks like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>transaction_date (index)</th>
<th>store_id</th>
<th>department_id</th>
<th>gross_revenue</th>
</tr>
</thead>
<tbody>
<tr>
<td>'2020-01-01'</td>
<td>Store1</td>
<td>Fruit</td... | <p>Use <code>map</code>:</p>
<pre><code>store_adjust = {'Store1': 1.25, 'Store10':1.3}
dep_adjust = {'Veg': 1.10, 'Fruit':1.75}
df['gross_revenue'] *= ( df['store_id'].map(store_adjust).fillna(1) *
df['department_id'].map(dep_adjust).fillna(1) )
</code></pre> | python|pandas|performance|dataframe | 3 |
4,949 | 49,893,741 | tensorflow: CNN for non square image | <p>tensorflow version 1.5.0rc1
python version:3.5</p>
<p>When reshape a rectangular image to <code>[height,width]</code>
by using <code>tf.reshape(x,[-1,x,y,1])</code> </p>
<blockquote>
<p>eg. tf.reshape(x,[-1,14,56,1]) run conv2d returns:
InvalidArgumentError (see above for traceback): Input to reshape is a
t... | <p>I don't exactly agree with reshaping a rectangular picture as you destroy the relationship between neighbour pixels. Instead, you have several options to apply CNNs on a non-quadratic image:</p>
<p>1.) Use padding. During preprocessing, you could fill in pixels to get a quadratic image. Through this you can apply t... | python|tensorflow | 0 |
4,950 | 50,076,420 | How to combine Python 32bit and 64bit modules | <p>For one my Robotics projects, I am trying to grab an image from Nao Robot's camera and use Tensorflow for object recognition. </p>
<p>The problem is that the Robot's NaoQi API is built on Python2.7 32bit.
(<a href="http://doc.aldebaran.com/1-14/dev/python/install_guide.html" rel="nofollow noreferrer">http://doc.al... | <p>I don't think there is a way to have both modules work in the same interpreter if you say one is 32bit only and the other 64bit only.</p>
<p>So, consider running two interpreters, and having them communicate with each other with message exchange, remote procedure call, and such.</p>
<p>I strongly discourage to use... | python|tensorflow|robotics|nao-robot | 3 |
4,951 | 64,079,215 | Same keras models do not give the same output for get_config() method | <p>I would like to know why for two same keras models, sometimes get_method() gives the same results (See <code>model_dense_A</code> and <code>model_dense_B</code>) and sometimes not (example for <code>model_conv_A</code> and <code>model_conv_B</code>).</p>
<p>Even if I use the <code>clear_session()</code> method and t... | <p>It usually helps to take a look at where exactly both configs differ, i.e.</p>
<pre><code>print(mdl_conv_A.get_config() == mdl_conv_B.get_config(), (mdl_conv_A.get_config(), mdl_conv_B.get_config())) # False !?
</code></pre>
<p>In this case they differ because of the lambda layer, which is not very serializable.</... | python|tensorflow|keras|conv-neural-network|lstm | 0 |
4,952 | 63,780,445 | Python - Comparing two dataframes | <p><strong>Comparing two Dataframes // Deciphering one Dataframe with another</strong></p>
<p>Hello everyone and thanks for the help!</p>
<p>I have two dataframes. The first (df1) contains all my data, including a column with a long list of abbreviations (df1[ab]) which i want to translate into numbers via the second ... | <p>If you just want the additional column:</p>
<pre><code>df1.merge(df2, left_on='ab', right_on='key', how='left')
</code></pre>
<p>Output</p>
<pre><code> ab key value
0 Sl2 Sl2 25.0
1 Sl4 Sl4 30.0
2 Ss Ss 11.0
3 Tu4 NaN NaN
4 Slu Slu 33.0
5 Su2/Su3 Na... | python|pandas|dataframe | 1 |
4,953 | 63,955,968 | Is there a javascript implementation of MediaPipe's Palm Tracking? | <p>I found a javascript implementation of MediaPipe's FaceMesh and HandPose but not Palm Tracking.</p> | <p>They currently do not have a javascript API for hand tracking.</p> | mediapipe|tensorflow.js | 0 |
4,954 | 64,118,898 | pandas: from how to unpack nested JSON as dataframe? | <p>I have an JSON output like this</p>
<p><code>json.json</code></p>
<pre><code>{"SeriousDlqin2yrs": {"prediction": "0", "prediction_probs": {"0": 0.95, "1": 0.04}}}
{"SeriousDlqin2yrs": {"prediction": "0", "prediction_probs&... | <p>Tested in pandas <code>1.1.1</code> - convert values to <code>list</code>s and pass to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.json.json_normalize.html" rel="nofollow noreferrer"><code>json_normalize</code></a>:</p>
<pre><code>s = pd.read_json('json.json', lines=True)['SeriousDlq... | python|pandas | 3 |
4,955 | 62,962,795 | How to read SPSS aka (.sav) in Python | <p>It's my first time using Jupyter Notebook to analyze survey data (.sav file), and I would like to read it in a way it will show the metadata so I can connect the answers with the questions. I'm totally a newbie in this field, so any help is appreciated!</p>
<pre><code>import pandas as pd
import pyreadstat
df, meta =... | <p>The meta object contains the metadata you are looking for. Probably the most useful attributes to look at are:</p>
<ul>
<li>meta.column_names_to_labels : it's a dictionary with column names as you have in your pandas dataframe to labels meaning longer explanations on the meaning of each column</li>
</ul>
<pre><code>... | python|pandas|jupyter-notebook|metadata|spss | 7 |
4,956 | 62,922,147 | How to pick from multiple lists randomly to fill DFcolumns | <p>I want to fill a Pandas DataFrame with 3 columns and 20 rows based on random values from the 3 lists below. I cant quite figure out what I am doing wrong. Any suggestions?</p>
<pre><code>import random
import pandas as pd
import numpy as np
tests= ['TestA', 'TestB', 'TestC', 'TestD']
projects = ['AK', 'AA', 'JH',... | <p>You can use <code>np.random.choice</code>:</p>
<pre><code>tests= ['TestA', 'TestB', 'TestC', 'TestD']
projects = ['AK', 'AA', 'JH', 'WM']
number = [10, 100, 200, 1000, 2000]
num_rows = 20
# for repeatability, drop in actual code
np.random.seed(1)
df = pd.DataFrame({
'TEST': np.random.choice(tests, size=num_ro... | python|pandas|dataframe|random | 2 |
4,957 | 63,074,439 | Can not uninstall Tensorflow 2.1.0 as conda can't find the package and solving environment fails | <p>The tensorflow 2.1.0 package is shown under <code>conda list</code> as follows:</p>
<p><a href="https://i.stack.imgur.com/9Ho54.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Ho54.png" alt="conda list output" /></a></p>
<p>But when I try to uninstall it using <code>conda remove tensorflow</code>... | <p>First obtain the path where your packages are installed in anaconda-spyder using this command. Refer <a href="https://stackoverflow.com/a/49028561/9279666">this link</a> for more information</p>
<pre><code>python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
</code></pre>
<p>... | python|tensorflow|pip|anaconda|conda | 0 |
4,958 | 67,823,576 | External datasources do not recognize header row of csv exported from Pandas dataframe | <p>My code follows below</p>
<pre><code>HVSPointsJoined = pd.read_csv(r'M:\08_Geography\CurrentSurveys\HVS\HVSMap\pointsjoined.csv',dtype='object')
HVSPointsJoined = HVSPointsJoined[['Join_Count',u'psu', u'tract', u'block',
u'outcome_code', u'g_short_1', u'lat', u'lon', u'building_type',
u'description', u... | <p>Disregard this question, the issue is not related to pandas. External programs not recognizing a header row if the column names contain numeric characters only.</p> | python|pandas | 0 |
4,959 | 61,540,658 | CS231n assignment 2: TwoLayerNet and Solver | <p>I'm running into an error message when I try to execute solver.train.</p>
<p>I finished editing fc_net, including initialization, feed-forward, loss and backward propagation. When I executed the FullyConnectedNets code that meant to compare their solution vs mine, everything went fine (my analytic gradients identic... | <p>I used <code>db = np.ones((1, dout.shape[0])) @ dout</code> in the <code>affine_backward</code> and also got your error. After changing the line into <code>db = dout.T @ np.ones(N)</code>, the error is gone.</p> | numpy|neural-network | 0 |
4,960 | 68,536,412 | Convert python pandas dataframe into different format | <p>I have a data frame in python and I want to convert in different format :</p>
<p>Below is the example of the same :</p>
<p>Current Data frame :</p>
<pre><code> Header 1 Header 1
Col_A Col_B Col_A Col_B
2021-07-15 1 2 3 4
2021-07... | <p>That’s literally what <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>.stack()</code></a> does:</p>
<blockquote>
<p>Stack the prescribed level(s) from columns to index.</p>
</blockquote>
<p>With some tweaking to rename columns as... | python|pandas|sklearn-pandas | 1 |
4,961 | 68,466,535 | How to get a date_range and insert them as a 'list' to a new column in dataframe? | <p>I have a dataframe with 50k+ rows. <code>df.head(5)</code> is below:</p>
<pre><code> start_date finish_date months_used
2841 2019-06-23 2019-07-17 2
2842 2019-06-16 2019-06-23 1
2843 2019-03-27 2019-07-17 5
2844 2019-05-29 2019-06-05 2
2845 2019-03-25 2019-07-17 ... | <p>Try using:</p>
<pre><code>df['rep_list'] = df[['start_date', 'finish_date']].apply(lambda x: pd.date_range(start=x[0], end=x[1], freq='M').tolist(), axis=1)
</code></pre>
<p>And now:</p>
<pre><code>print(df)
</code></pre>
<p>Would give the expected result.</p> | python|pandas | 1 |
4,962 | 68,740,447 | How to drop all strings in a column using a wildcard? | <p>I have some data that changes regularly but the column headers need to be consistent (so I cant drop the headers) but I need to clear our the strings in a given column.</p>
<p>This is what I have now but this only seems to work for where I know what the string is called and one at a time?</p>
<pre><code> df1= pd.... | <p>You can use the <code>pd.drop</code> function which removes rows having a specific index from a dataframe.</p>
<pre class="lang-py prettyprint-override"><code>for i in df.index:
if type(df.loc[i, 'Aborted Reason']) == str:
df.drop(i, inplace = True)
</code></pre>
<p><code>df.drop</code> will remove the ... | python|python-3.x|pandas | 2 |
4,963 | 53,074,937 | Transforming a Pandas datafrom based on condition | <p>I have a dataframe of the form:</p>
<pre><code> order_id product_id
0 2 33120
1 4 28985
2 4 9327
3 7 45918
4 14 30035
</code></pre>
<p>I would like to transform or create a new dataframe where all of the product_id's for each order_id are in the same... | <p>This is a <code>pivot</code> problem , you just need <code>cumcount</code> create the key </p>
<pre><code>newdf=df.assign(key=df.groupby('order_id').cumcount()).pivot('order_id','key','product_id').fillna('')
newdf
Out[124]:
key 0 1
order_id
2 33120.0
4 28985.0 ... | python|pandas | 1 |
4,964 | 52,979,089 | Read and Write to a specific cell in a file | <p>I am writing a program where it reads from an excel sheet, it randomly picks a row (100 rows, 2 columns). </p>
<pre><code>with open("file1.csv") as f:
reader = csv.reader(f)
for index, row in enumerate(reader):
if index == 0:
chosen_row = row
else:
r = random.rand... | <p>From the example code on openpyxl:</p>
<pre><code>from openpyxl import Workbook
wb = Workbook()
# grab the active worksheet
ws = wb.active
# Data can be assigned directly to cells
ws['A1'] = 42
</code></pre>
<p>Given this, you should be able to see assigned the value of a given cell with </p>
<pre><code>ws['A1'... | python|pandas|numpy | 0 |
4,965 | 53,242,570 | Pandas dataframe find first and last element given condition and calculate slope | <p><b>The situation</b>:</p>
<p>I have a pandas dataframe where I have some data about the production of a product. The product is produced in 3 phases. The phases are not fixed meaning that their cycles (the time till last) is changing. During the production phases, at each cycle the temperature of the product is mea... | <p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with subtract last value with first and divide by length:</p>
<pre><code>f = lambda x: (x.iloc[-1] - x.iloc[0]) / len(x)
df['new'... | python|pandas|dataframe | 2 |
4,966 | 65,520,833 | If I Trace a PyTorch Network on Cuda, can I use it on CPU? | <p>I traced my Neural Network using <code>torch.jit.trace</code> on a CUDA-compatible GPU server. When I reloaded that Trace on the same server, I could reload it and use it fine. Now, when I downloaded it onto my laptop (for quick testing), when I try to load the trace I get:</p>
<pre><code>RuntimeError: Could not run... | <p>I had this exact same issue. In my model I had one line of code that was causing this:</p>
<pre><code>if torch.cuda.is_available():
weight = weight.cuda()
</code></pre>
<p>If you have a look at the official documentation for trace (<a href="https://pytorch.org/docs/stable/generated/torch.jit.trace.html" rel="nof... | pytorch|torchscript | 0 |
4,967 | 65,570,123 | creating a matrix from multiple pandas data frames | <p>I have basically no experience with pandas and I'm trying to force myself to use it more.</p>
<p>I'm trying to join the "count" of multiple data frames based on a specific column to create a count matrix. I usually do this with good old python dictionaries, but if there's a simple way to do this with panda... | <p>Try <code>pd.concat</code>:</p>
<pre><code>pd.concat([d.set_index(['geneID','geneName']).rename(columns={'count':f'df{i}'})
for i,d in enumerate([df1,df2])], axis=1
).fillna(0)
</code></pre>
<p>Output:</p>
<pre><code> df0 df1
geneID geneName
A123 ABC 202... | python|pandas|dataframe|join | 1 |
4,968 | 63,443,650 | Can tabula lead with merge columns? | <p>Recently I've working in table extraction, specifically with <em>stream</em> tables. An in <a href="https://github.com/camelot-dev/camelot/wiki/Comparison-with-other-PDF-Table-Extraction-libraries-and-tools" rel="nofollow noreferrer">this</a> post I saw that tabula achieves very well this kind of extraction.
For exa... | <p>maintainer of Tabula here.</p>
<p>You can try specifying the horizontal coordinates of the column boundaries. This parameter is exposed in <code>tabula-py</code> in the <code>columns=</code> keyword argument of the <code>read_pdf</code> method.</p> | python|pandas|tabula | 0 |
4,969 | 63,419,095 | Populate Pandas Dataframe Based on Column Values Matching Other Column Names | <p>I'd like to populate one dataframe (df2) based on the column names of df2 matching values within a column in another dataframe (df2). Here is a simplified example:</p>
<pre><code>names = list('abcd')
data = list('aadc')
df1 = pd.DataFrame(data,columns=['data'])
df2 = pd.DataFrame(np.empty([4,4]),columns=names)
... | <p>You can do numpy broadcasting here:</p>
<pre><code>df2[:] = (df1['data'].values[:,None] == df2.columns.values).astype(int)
</code></pre>
<p>Or use <code>get_dummies</code>:</p>
<pre><code>df2[:] = pd.get_dummies(df1['data']).reindex(df2.columns, axis=1)
</code></pre>
<p>Output:</p>
<pre><code> a b c d
0 1 0 ... | python|pandas|numpy | 1 |
4,970 | 53,469,325 | Percentage growth between values in column | <p>Let's say that I have a df like below:</p>
<pre><code>x name
12 q
1 q
3 q
383 z
31 z
21 z
68 r
32 r
2 r
</code></pre>
<p>I need to count the percentage growth between first and last value for each of name, so result should be like this</p>
<pre><code>x name
300% q
1723% z
2... | <p>First aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow noreferrer"><code>first</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.last.html" rel="nofollow noreferrer"><code>last</code>... | python-3.x|pandas|dataframe|percentage | 1 |
4,971 | 71,900,015 | Initialize a list in cells in specific indexes (the indexes are in a list) | <p>I have a list of indexes in each of which I need to initialize a list in a specific column. I tried this:</p>
<pre><code>index = [0, 1, 2, 3, 4]
dataframe.at[indexes, 'column_x'] = [] * len(indexes)
</code></pre>
<p>which resulted in the error message:</p>
<pre><code>pandas.errors.InvalidIndexError: Int64Index([0, 1... | <p>You can create an empty series with <code>[]</code> then use <code>combine_first</code> to fill right index:</p>
<pre><code>sr = pd.Series([[]] * len(df))
df['column_x'] = df['column_x'].mask(df.index.isin(index)).combine_first(sr)
</code></pre> | pandas|dataframe | 1 |
4,972 | 55,561,467 | Extracting subrows from rows | <p>i have a dataset having year, total runs scored per ball, inning and batting_team.
i want to display the data where i will have year in which innings are displayed in which i will list the team who has scored the highest runs in that inning of that year</p>
<p>i have reached till this extent but dont know to take t... | <p>If you just want to see the top result for each GroupBy you can use <code>.head(1)</code></p> | python|pandas | 0 |
4,973 | 66,801,447 | Merge pandas dataframes by timestamps | <p>I've got a few pandas dataframes indexed with timestamps and I would like to merge them into one dataframe, matching nearest timestamp. So I would like to have for example:</p>
<pre><code>a =
CPU
2021-03-25 13:40:44.208 70.571797
2021-03-25 13:40:44.723 14.126870
2021-03-25 13:40:45.228 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a> with <code>direction='nearest'</code>:</p>
<pre><code>pd.merge_asof(df1, df2, left_index=True, right_index=True, direction='nearest')
</code></pre> | python|pandas|dataframe | 2 |
4,974 | 47,527,747 | Pandas: Rolling mean over array of windows | <p>Similar to <a href="https://stackoverflow.com/a/42152692/2327328">this answer</a>, I can calculate multiple rolling means</p>
<pre><code>d1 = df.set_index('DateTime').sort_index()
ma_1h = d1.groupby('Event').rolling('H').mean()
ma_2h = d1.groupby('Event').rolling('2H').mean()
</code></pre>
<p>But how can I do this... | <p>I believe you need convert offsets and create new <code>DataFrame</code>s in loop by list comprehension, last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:</p>
<pre><code>from pandas.tseries.frequencies import to_offset
df1 = p... | python|pandas|time-series|moving-average | 1 |
4,975 | 47,310,132 | Number of CNN learnable parameters - Python / TensorFlow | <p>In TensorFlow, is there any function to something I can do to find out the amount of learning parameters in my network?</p> | <p>No function I am aware of, but you can still count yourself using a for loop on the <code>tf.trainable_variables():</code></p>
<pre><code>total_parameters = 0
for variable in tf.trainable_variables():
variable_parameters = 1
for dim in variable.get_shape():
variable_parameters *= dim.value
total... | python|tensorflow|conv-neural-network | 6 |
4,976 | 68,098,852 | Lookup value from data Pandas | <p>I have a list of postcodes coordinates in a <code>df</code></p>
<pre><code>print(df)
out[0]:
X Y Postcode
84060.2933273726 452334.434562507 2543
842443.2065506417 452310.49440726795 2544
78129.7656972764 450394.36304550205 2542
76143.40136149981 452922.51687671... | <p>A merge will get you the coordinates of the origin or of the destination, so 2 merges should be enough:</p>
<pre><code>>>> orig = df2.reset_index().merge(df, left_on='OrigLoc', right_on='Postcode')\
... .set_index('index')[['X', 'Y']].add_prefix('O_')
>>> orig
O_X ... | python|pandas|dataframe | 0 |
4,977 | 68,141,627 | Add a path to libraries for python in VS Code Windows | <p>I have <code>pandas</code> installed in computer via Anaconda that I downloaded previously and now when I wish to use VS Code, I tried installing <code>pandas</code> using <code>pip install pandas</code> and it said that the Requirement is already satisfied. I am not sure what path to change and how to change, thoug... | <p>You do not need to install pandas again even tho you're using a different IDE, you might have added the python PATH in your environment variables and that's it.
Can you just try</p>
<pre><code>import pandas as pd
</code></pre>
<p>in your VSCode to cross check?</p> | python|pandas|windows|visual-studio-code|cmd | 0 |
4,978 | 68,258,207 | How to use fillna function in pandas? | <p>I have a dataframe which has three Battery's charging and discharging sequence:</p>
<pre><code> Battery 1 Battery 2 Battery 3
0 32 3 -1
1 21 11 -31
2 23 27 63
3 12 -22 -22
4 -21 22 44
5 ... | <p>Change the lane here with <code>reindex</code></p>
<pre><code>charging = bess[bess<=0].reindex(df.index,fill_value=0) #Charging
discharging = bess[bess>0].reindex(df.index,fill_value=0) #Discharging
</code></pre> | python|pandas|fillna | 3 |
4,979 | 59,076,441 | Different color in hvplot.box | <p>The following code generates the linked image. It generates mostly what I want but I would like the box color to be different between Real and Preds. How would I do that with Holoviews or Hvplot?</p>
<pre><code>import hvplot.pandas
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(20), col... | <p>You can do it by <strong>setting the color and cmap parameter</strong>:</p>
<pre><code>df.hvplot.box(
y='Value',
by=['Item', 'Source'],
color='Source',
cmap=['blue', 'orange'],
legend=False,
)
</code></pre>
<p>Or by setting <strong>.opts(box_color)</strong>:</p>
<pre><code>df.hvplot.box(
y... | python|pandas|holoviews|hvplot | 4 |
4,980 | 59,159,444 | Cumulative histogram with bins in frequency python | <p><a href="https://i.stack.imgur.com/clMGJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/clMGJ.png" alt="histogram barplot and cumulative histogram curve"></a></p>
<p>I am looking for a python function to get a cumulative curve of frequency with regularly spaced frequence (y axis) and not values ... | <p>A very rough version, you can use pandas' <code>qcut</code>:</p>
<pre><code># toy data
np.random.seed(1)
a = np.random.rand(100)
# Quantile cut into 10 bins
cuts = (pd.qcut(a, np.arange(0,1,0.1)) # change arange to your liking
.value_counts().cumsum()
)
plt.plot([a.right for a in cuts.index],... | python|numpy|scipy|cumulative-frequency | 1 |
4,981 | 57,168,393 | How to add a column in a df with mapped values from identical column in df2? | <p>I have two data frames <code>categories</code> and <code>data</code> and would like to add a column to <code>data</code> based on a column of <code>categories</code>. Here's some of the information for these data frames.</p>
<pre><code>items: DataFrame | (22170, 3) | Column names: item_name, item_id, item_category_... | <p>You could <code>merge</code> only on the slices of your DataFrames containing the columns that you need in the final result:</p>
<pre><code>data_cols = ['date', 'shop_id', 'item_id']
items_cols = ['item_id', 'item_category_id']
pd.merge(data[data_cols], items[items_cols], how='left', on='item_id')
</code></pre>
<... | python|pandas | 1 |
4,982 | 57,130,434 | Monitoring weight sparsity during training | <p>I wonder if it is possible to monitor the percentage of nonzero weights of the full network (not just a layer) during training? </p>
<p>For example, I use </p>
<pre><code>optim = AdagradDAOptimizer(learning_rate=0.01).minimize(my_loss)
</code></pre>
<p>and </p>
<pre><code>for i in range(10):
sess = tf.Session(... | <p>The following code calculate the number of nonzero weights.</p>
<pre><code>import tensorflow as tf
import numpy as np
tvars = sess.run(tf.trainable_variables())
nonzero_parameters = np.sum([np.count_nonzero(var) for var in tvars])
</code></pre>
<p>Here shows how to calculate the total number of weights: <a href="... | tensorflow|deep-learning | 0 |
4,983 | 45,950,723 | Error: Tensorflow BRNN logits and labels must be same size | <p>I have an error like this:</p>
<pre><code>InvalidArgumentError (see above for traceback): logits and labels must
be same size: logits_size=[10,9] labels_size=[7040,9] [[Node:
SoftmaxCrossEntropyWithLogits =
SoftmaxCrossEntropyWithLogits[T=DT_FLOAT,
_device="/job:localhost/replica:0/task:0/gpu:0"](Reshape, Reshape_... | <p>The first return value of <a href="https://www.tensorflow.org/api_docs/python/tf/nn/static_bidirectional_rnn" rel="nofollow noreferrer"><code>static_bidirectional_rnn</code></a> is a list of tensors - one for each rnn step. By using only the last one in your <code>tf.matmul</code> you're losing all the rest. Instead... | tensorflow|deep-learning|rnn | 1 |
4,984 | 45,907,431 | Shape mismatch in LSTM in keras | <p>I am trying to run a LSTM using Keras on my custom features set. I have train and test features in separate files. Each csv file contains 11 columns with last column as class label. There are total 40 classes in my dataset. The problem is I am not able to figure out the correct input_shape to the first layer. I had ... | <p>you don't have a time dimension in your input.
Input for RNN should be <code>(batch_size, time_step, features)</code> while your input has dimension <code>(batch_size, features)</code>.</p>
<p>If you want to use your 10 columns one at a time you should reshape the array with
<code>numpy.reshape(train_dataset, (-1, ... | python|numpy|keras|lstm|keras-layer | 1 |
4,985 | 46,090,386 | Keep columns after a groupby in an empty dataframe | <p>The dataframe is an empty df after query.when groupby,raise runtime waring,then get another empty dataframe with no columns.How to keep the columns?</p>
<pre><code>df = pd.DataFrame(columns=["PlatformCategory","Platform","ResClassName","Amount"])
print df
</code></pre>
<p>result:</p>
<pre><code>Empty DataFrame
Co... | <p>You need <code>as_index=False</code> and <code>group_keys=False</code>:</p>
<pre><code>df = df.groupby(["PlatformCategory","Platform","ResClassName"], as_index=False).count()
df
Empty DataFrame
Columns: [PlatformCategory, Platform, ResClassName, Amount]
Index: []
</code></pre>
<p>No need to reset your index after... | python|pandas|dataframe|group-by|pandas-groupby | 5 |
4,986 | 51,045,781 | Tensorflow: How to retrieve information from the prediction Tensor? | <p>I have found a neural network for semantic segmentation purpose. The network works just fine, I feed my training, validation and test data and I get the output (segmented parts in different colors). Until here, all is OK. I am using Keras with Tensorflow 1.7.0, GPU enabled. Python version is 3.5</p>
<p>What I want ... | <p>for segmentation tasks, considering that your batch is one image, each pixel in the image is assigned a probability to belong to a class. Suppose you have 5 classes, and the image has 784 pixels(28x28) , you will get from the <code>net.predict</code> an array of shape <code>(784,5)</code> each pixel among 784 is ass... | python|tensorflow | 3 |
4,987 | 50,740,557 | PyTorch how to implement disconnection (connections and corresponding gradients are masked)? | <p>I try to implement the following graph. As you can see, the neurons are not fully connected, i.e., the weights are masked and so are their corresponding gradients.</p>
<p><a href="https://i.stack.imgur.com/J15OL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J15OL.png" alt="enter image descripti... | <p>Actually, the above method is correct. <strong>The disconnections essentially block feed-forward and back-propogation on corresponding connections.</strong> In other words, weights and gradients are masked. The codes in question reveal the first while this answer reveals the latter.</p>
<pre><code>mask_weights.regi... | python|neural-network|pytorch | 1 |
4,988 | 50,745,224 | Replacing column value by NaN when another column has a certain value in pandas | <p>I have the following data frame:</p>
<pre><code>Month,Value1,Value2
02,1,10
03,2,2
04,3,12
</code></pre>
<p>In this Dataframe I wish to replace <code>Value1</code> by NaN each time <code>Value2</code> is < to 10. So the desired output will look as follow:</p>
<pre><code>Month,Value1,Value2
02,1,10
03,NaN,2
04,... | <p>You don't need a double assignment. Try this:</p>
<pre><code>data.loc[data['Value2'] < 10, 'Value1'] = np.nan
</code></pre>
<p>Remember <a href="https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>pd.DataFrame.loc</code></a> can be used both as... | python|pandas|dataframe|nan | 2 |
4,989 | 66,496,428 | Automatically detect security identifier columns using Visions | <p>I'm interested in using the <a href="https://dylan-profiler.github.io/visions/index.html" rel="nofollow noreferrer">Visions</a> library to automate the process of identifying certain types of security (stock) identifiers. The <a href="https://dylan-profiler.github.io/visions/visions/applications/validation.html" rel... | <p>Great question and use-case! Unfortunately, the <a href="https://dylan-profiler.github.io/visions/visions/getting_started/extending.html" rel="nofollow noreferrer">documentation</a> on making new types probably needs a little love right now as there were API breaking changes with the 0.7.0 release. Both the previous... | pandas|dataframe|custom-data-type | 0 |
4,990 | 66,404,003 | Oversampling of image data for keras | <p>I am working on Kaggle competition and trying to solve a multilabel classification problem with keras.</p>
<p>My dataset is highly imbalanced. I am familiar with this concept and did it for simple machine learning datasets, but now sure how to deal with both images and csv data.</p>
<p>There are a couple of question... | <p>I'm not sure if this answer satisfies you or not, but here is my thought. If I were you, I wouldn't try to balance it in the way you're trying it now. IMO, that's not the proper way. Your main concern is this <a href="https://www.kaggle.com/c/vinbigdata-chest-xray-abnormalities-detection/data" rel="nofollow noreferr... | python|tensorflow|keras|oversampling | 1 |
4,991 | 57,659,624 | Renaming columns in dataframe w.r.t another specific column | <p><strong>BACKGROUND:</strong> Large excel mapping file with about 100 columns and 200 rows converted to .csv. Then stored as dataframe. General format of df as below. </p>
<p>Starts with a named column (e.g. Sales) and following two columns need to be renamed. This pattern needs to be repeated for all columns in exc... | <p>1.You need is to make a list with the column names that you would want.<br>
2.Make it a dict with the old column names as the keys and new column name as the values.<br>
3. Use df.rename(columns = your_dictionary). </p>
<pre><code>import numpy as np
import pandas as pd
df = pd.read_excel("name of the excel file",s... | python-3.x|pandas|dataframe | 2 |
4,992 | 57,391,329 | Numeric precision of climate science calculations in python | <p>I am currently trying to recreate findings of a paper (<a href="https://www.researchgate.net/publication/309723672_Evidence_for_wave_resonance_as_a_key_mechanism_for_generating_high-amplitude_quasi-stationary_waves_in_boreal_summer" rel="nofollow noreferrer">https://www.researchgate.net/publication/309723672_Evidenc... | <p>If its issue with numerical precision then the algorithm is not the issue but what variable types you are using. if you switch to longer float representations like dtype='c16l' ( 128- complex floating-point number.
<a href="https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html" rel="nofollow noreferrer">http... | python|numpy|precision|calculation | 0 |
4,993 | 72,945,031 | Find date of the first occurance of values in columns of a data frame - Find start dates for each column | <p>How to find the date of the first occurrence of a value for columns A and B in this data frame?</p>
<p>So, I want <code>2012-04-03</code> of <strong>A</strong> and <code>2012-04-04</code> of column <strong>B</strong>:</p>
<pre><code>| | A | B |
|:--------------------|----:|----:|
| 2012-04-01... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.first_valid_index.html" rel="nofollow noreferrer"><code>first_valid_index</code></a>:</p>
<pre><code>>>> df.apply(lambda x: x.first_valid_index())
A 2012-04-03
B 2012-04-04
dtype: datetime64[ns]
</code></pre> | python|pandas | 2 |
4,994 | 72,979,240 | pandas replace text for top N rows for each category in a column | <p>I have a df something like this</p>
<pre><code> animal age comment
1 cat 1 xyz
2 cat 2 xyz
3 cat 3 xyz
4 cat 4 xyz
5 cat ... | <p>The trick here is to use <code>cumcount</code> to create a sequential counter per <code>animal</code> group, then use <code>np.where</code> to update values in <code>comment</code> based on the value of seq counter</p>
<pre><code>i = df.groupby('animal').cumcount()
df['comment'] = np.where(i < 2, 'young', 'old')
... | python|pandas|dataframe | 3 |
4,995 | 51,420,032 | using saved sklearn model to make prediction | <p>I have a saved logistic regression model which I trained with training data and saved using joblib. I am trying to load this model in a different script, pass it new data and make a prediction based on the new data.</p>
<p>I am getting the following error "sklearn.exceptions.NotFittedError: CountVectorizer - Vocabu... | <p>Your training part have 3 parts which are fitting the data:</p>
<ul>
<li><p><code>CountVectorizer</code>: Learns the vocabulary of the training data and returns counts</p></li>
<li><p><code>TfidfTransformer</code>: Learns the counts of the vocabulary from previous part, and returns tfidf</p></li>
<li><p><code>Logis... | python|pandas|numpy|scikit-learn|logistic-regression | 5 |
4,996 | 51,825,862 | python pandas changing several columns in dataframe based on one condition | <p>I am new in Python and Pandas. I worked with SAS. In SAS I can use IF statement with "Do; End;" to update values of several columns based on one condition.<br>
I tried np.where() clause but it updates only one column. The "apply(function, ...)" also updates only one column. Positioning extra update statement ins... | <p>You could use:</p>
<pre><code>for col in df:
df[col] = np.where(df[col] == your_condition, value_if, value_else)
</code></pre>
<p>eg:</p>
<pre><code> a b
0 0 2
1 2 0
2 1 1
3 2 0
for col in df:
df[col] = np.where(df[col]==0,12, df[col])
</code></pre>
<p>Output:</p>
<pre><code> a b
0 12 ... | python|pandas | 0 |
4,997 | 36,095,363 | How to replace values in a column if another column is a NaN? | <p>So this should be the easiest thing on earth. Pseudocode:</p>
<pre><code>Replace column C with NaN if column E is NaN
</code></pre>
<p>I know I can do this by pulling out all dataframe rows where column E is NaN, replacing all of Column C, and then merging that on the original dataset, but that seems like a lot of... | <p>Use <code>np.where</code>:</p>
<pre><code>In [34]:
dfz['C'] = np.where(dfz['E'].isnull(), dfz['E'], dfz['C'])
dfz
Out[34]:
A B C D E
0 1 1 1 1 22
1 0 0 0 0 15
2 0 0 NaN 0 NaN
3 1 1 1 1 10
4 0 0 NaN 0 NaN
5 0 1 1 0 557
</code></pre>
<p>Or simply mask the df:</p>
<pre><... | python|pandas | 7 |
4,998 | 35,928,114 | TypeError: 'numpy.ndarray' object is not callable - working with banded/sparse matrices | <p>Hello I am trying to create a banded matrix - when I try to extract the upper diagonal and add a zero to the array I get the following error - "TypeError: 'numpy.ndarray' object is not callable"</p>
<pre><code>>>> A = np.eye(5, k=-1) -2 * np.eye(5) + np.eye(5, k=1)
>>> udA = np.insert (np.diag(A, ... | <p>What <code>numpy</code> version are you using? In my version (1.9) your code works.</p>
<p>I think it's a problem using <code>np.diag</code> inside the <code>insert</code> function. </p>
<p>In 1.9 version, <code>np.diag</code> has this warning:</p>
<blockquote>
<p>See the more detailed documentation for <code... | python|numpy|matrix | 0 |
4,999 | 36,073,425 | Concating a nested numpy array into 2D array | <p>I am using Pandas to generate some information and features. I will be using that database as my input for sklearn. Currently, I am converting the dataframe to array using <code>.as_matrix()</code>. Following is the output:</p>
<pre><code>array([[0.4437294900417328, 0.13434134423732758, 0.474, 0.482,
array([0, ... | <p>As I commented, the exact structure of your array is unclear. I'm sure the outer dtype is object. Pandas often uses that to hold mixed data.</p>
<p>Here's a guess, and possible solution:</p>
<p>Make an object array and fill it with some floats and arrays of integers:</p>
<pre><code>In [38]: A=np.empty((3,5),dty... | python|arrays|numpy|pandas|scikit-learn | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.