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 |
|---|---|---|---|---|---|---|
20,600 | 62,811,932 | Drop all rows that meet condition except the first one | <p>I would like to drop all rows in a <code>pandas</code> dataframe that meet a certain condition except the first one. Note that the rows are not identical, so I cannot use <code>drop_duplicates()</code>.</p>
<p>For example, if I have the dataframe:</p>
<pre><code>Type Count
A 4
X 33
X ... | <p>We can set the first value to <code>False</code> with <code>idxmax</code>:</p>
<pre><code>m = df.Type.isin(['X', 'Y'])
m.loc[m.idxmax()] = False
df[~m]
Type Count
0 A 4
1 X 33
3 E 51
</code></pre> | python|pandas | 1 |
20,601 | 54,558,671 | Is there a worked example for neural network pruning for the Faster-RCNN architecture from TensorFlow's object detection api? | <p>I am trying to find a worked example of neural network pruning for the Faster-RCNN architecture. </p>
<p>My core stack is Tensorflow 1.12, its object_detection API (<a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">link</a>) on Python3.5.2 in Ubuntu 16.04... | <p>Pruning is orthogonal to the meta-architecture used for object detection. When we talk about the TensorFlow Object Detection API, it heavily relies on builders that read the config and create corresponding nets, classes etc. I believe you want to prune the feature extractor as the most heavy part. If so, you need to... | tensorflow|object-detection-api | 0 |
20,602 | 54,493,853 | Pandas Groupby and apply a custom function to each N- rows of a Column in that group | <p>I have a pandas dataframe, and i want to perform a groupby over a column and apply a custom function to another column. But that function has to be applied over every two entries of the apply-column.</p>
<pre><code>df = pd.DataFrame({'id':[1,1,2,2,2,3,3,3,3,3], 'vals':['ANZ', 'ABC', 'SAT', 'SATYA', 'SQL', 'WER', '... | <p>So i tried out something like below.</p>
<p>Myfunc is used to find string similarity between two string, i used the awesome fuzzywuzzy library for that</p>
<pre><code>from fuzzywuzzy import fuzz
def myfunc(x):
x = x.tolist() # converted series to list
y = []
for i in range(0, len(x)):
if i == ... | python|pandas | 2 |
20,603 | 73,833,461 | Pandas dataframe group by column and apply min, max, average on different columns | <p>I am looking a way to transform this dataframe below</p>
<pre><code>itemid clock value_min value_avg value_max item_type
A1 27/05/2021 4 7 38 cpu
A2 27/05/2021 4 5 15 mem
B1 27/05/2021 1 2 5 cpu
B2 27/... | <p>this should answer your question:</p>
<pre><code>df = df.groupby('itemid').agg({'value_min': 'min', 'value_avg': 'mean', 'value_max': 'max', 'item_type': 'first'})
</code></pre> | python|pandas | 2 |
20,604 | 73,802,853 | Pandas perform functions using multiple dataframes | <p>I have two pandas dataframes in Python, one only has one row of data. The other has many rows. I would like to go through each row of the first one and subtract the second one from it. I would then like to store the results in a dataframe the size of the second one. The first one is</p>
<pre><code>df1 = pd.DataFrame... | <p>You need to convert <code>df1</code> to Series and to numpy array to bypass index alignment:</p>
<pre><code>df3 = df2.sub(df1['Amounts'].to_numpy(), axis=1)
</code></pre>
<p>There are many alternative, like full numpy:</p>
<pre><code>df3 = df2.sub(df1.to_numpy().ravel(), axis=1)
</code></pre>
<p>Or full pandas:</p>
... | python|pandas | 2 |
20,605 | 73,566,655 | Speed up apply in Pandas | <p>df:</p>
<pre><code>Person,utility,selected,innovation
2012001153_7_E02005533_1_2012002698,130.2333,yes,0
2012001153_7_E02005533_1_2012002698,110.33,no,1
2012001153_7_E02005533_1_2012002698,83,no,2
2012001153_7_E02005533_1_2012002698,-100,no,3
2012001153_7_E02005533_1_2012002698,49,no,4
</code></pre>
<p>I wish to cre... | <p>If you have a speed issue, you should avoid using <code>.apply</code> altogether, as it's going to loop over your DataFrame.</p>
<p>Note: from your function, I infer that each 'person' only has one and one only row where <code>'selected' == 'yes'</code>.</p>
<p>That should do it:</p>
<pre class="lang-py prettyprint-... | python|pandas|numpy | 0 |
20,606 | 71,277,138 | FileNotFoundError: Entity folder does not exist! in Google Colab | <p>Can anyone help me in sorting out this issue?
When I run these lines in Colab</p>
<p>:param files_name: containing training and validation samples list file.
:param boxes_and_transcripts_folder: gt or ocr result containing transcripts, boxes and box entity type (optional).
:param images_folder: whole images file fol... | <p>There is error in <a href="https://github.com/wenwenyu/PICK-pytorch/blob/master/config.json" rel="nofollow noreferrer">https://github.com/wenwenyu/PICK-pytorch/blob/master/config.json</a> file. you have to change the path of data as per your working directory. Check line number 61 to 64 and 73 to 76.</p> | nlp|pytorch|google-colaboratory|torchvision|torchtext | 1 |
20,607 | 52,206,075 | Change dataframes in dict | <p>Please help me to understand how to change dataframes in dictionary.</p>
<p>Let's consider the simplest case and create two dataframes and construct the dict from them.</p>
<pre><code>dates = pd.date_range('20130101',periods=6)
df1 =pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))
df2 =pd.DataFr... | <p>You need to assign values to dictionary keys as you iterate:</p>
<pre><code>for name, df in m.items():
m[name] = df[df['B'] > 0]
</code></pre>
<p>Otherwise, you're constantly overriding a variable <code>df</code> and not storing it anywhere.</p> | python|pandas|dictionary|for-loop | 2 |
20,608 | 60,720,953 | Numpy replace matrix elementwise with another matrix | <p>I have an n * x numpy matrix, which could look like this:</p>
<pre><code>a = np.array([[1, 0], [0, 1]])
</code></pre>
<p>and I have another n * n numpy matrix, which look like this:</p>
<pre><code>b = np.array([[2, 2], [2, 2]])
</code></pre>
<p>I would like to replace zero elements of <code>a</code> with the cor... | <p>You can use <code>np.where</code>:</p>
<pre><code>np.where(a!=0, a, b)
array([[1, 2],
[2, 1]])
</code></pre> | python|numpy | 4 |
20,609 | 60,394,026 | Adding new column to pandas df based on condition | <p>I have the following dataset: </p>
<pre><code>ID Asset Boolean
1 "A" True
1 "B" False
1 "B" False
2 "A" True
3 "A" True
3 "A" True
3 "B" False
3 "B" False
4 "A" True
4 "A" True
5 "A" True
5 "B" False
</code></pre>
<p>I w... | <p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>GroupBy</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transform.html" rel="nofollow noreferrer"><code>transform</code></a> w... | python|pandas|series | 4 |
20,610 | 60,442,272 | How to change certain values in a torch tensor based on an index in another torch tensor? | <p>This is an issue I'm running while <code>convertinf</code> DQN to Double DQN for the <code>cartpole</code> problem. I'm getting close to figuring it out.</p>
<pre><code>tensor([0.1205, 0.1207, 0.1197, 0.1195, 0.1204, 0.1205, 0.1208, 0.1199, 0.1206,
0.1199, 0.1204, 0.1205, 0.1199, 0.1204, 0.1204, 0.1203, 0.1... | <p>You can use <a href="https://pytorch.org/docs/stable/torch.html#torch.where" rel="noreferrer"><code>torch.where</code></a> - <code>torch.where(condition, x, y)</code></p>
<p><strong>Ex.:</strong></p>
<pre class="lang-py prettyprint-override"><code>>>> x = tensor([0.2853, 0.5010, 0.9933, 0.5880, 0.3915, 0.... | python|pytorch|tensor|torch|openai-gym | 5 |
20,611 | 72,490,710 | Creating and assigning values of a new Pandas DataFrame column | <p>Problem Statement-Create a new categorical variable with value as Open and Closed. Open & Pending is to be categorized as Open and Closed & Solved is to be categorized as Closed.</p>
<p>Description: I have a dataframe where there is a column 'Status' with the following values</p>
<pre><code>0 Closed
1 ... | <p>IIUC you can use a <code>np.select()</code> to get what you are looking for</p>
<pre><code>import numpy as np
condition_list = [(df['Status'] == 'Open') | (df['Status'] == 'Pending'), (df['Closed'] == 'Open') | (df['Solved'] == 'Pending')]
choice_list = ['Open', 'Closed']
df['Final Status'] = np.select(condition_lis... | python-3.x|pandas | 0 |
20,612 | 57,950,199 | Convert datetime column using function | <p>I have a dataframe with a column of datetimes.
I'm trying to get the top answer from <a href="https://stackoverflow.com/questions/43299500/pandas-how-to-know-if-its-day-or-night-using-timestamp">this post</a> to work on my dataframe.</p>
<pre><code>def sunrise(timee):
sun = ephem.Sun()
observer = ephem.Observer... | <p>You should do <code>return current_sun_alt * 180 / math.pi</code> instead of printing it.</p> | python|pandas|dataframe|python-datetime | 2 |
20,613 | 54,726,275 | Retraining or Continuing Training | <p>Ive started experimenting with tensorflow lately and there is one thing I'm not quite sure i get right:
If i have a set of training data, train the model on it for N number of epochs and than use <code>model.save("Multi_stage_test.model")</code> to save the model.</p>
<p>After running the program again with the ... | <p>If you load your model before the training instructions, then you are continuing to train the same model. Tensorflow will just load the pre-trained weights of your model and continue updating them during the new training session.</p> | python|tensorflow | 1 |
20,614 | 55,015,186 | Error rounding time to previous 15 min - Python | <p>I've developed a crude method to round timestamps to the previous 15 mins. For instance, if the timestamp is <code>8:10:00</code>, it gets rounded to <code>8:00:00</code>. </p>
<p>However, when it goes over 15 mins it rounds to the previous hour. For instance, if the timestamp was <code>8:20:00</code>, it gets roun... | <pre><code>- timedelta(hours=t.minute//15)
</code></pre>
<p>If minute is 20, then <code>minute // 15</code> equals 1, so you're subtracting one hour.</p>
<p>Try this instead:</p>
<pre><code>return t.replace(second=0, microsecond=0, minute=(t.minute // 15 * 15), hour=t.hour)
</code></pre> | python|pandas|datetime|rounding | 3 |
20,615 | 55,121,155 | 3d coordinates x,y,z to 3d numpy array | <p>I have a 3d mask which is an ellipsoid. I have extracted the coordinates of the mask using <code>np.argwhere</code>. The coordinates can be assigned as x, y, z as in the example code. My question is how can I get my mask back (in the form of 3d numpy or boolean array of the same shape) from the coordinates x, y, z ?... | <p>You can use directly x, y and z to reconstruct your mask. First, use a new array with the same shape as your mask. I pre-filled everything with zeros (i.e. <code>False</code>). Next, set each coordinate defined by x, y and z to <code>True</code>:</p>
<pre><code>new_mask = np.zeros_like(mask)
new_mask[x,y,z] = True
... | python|numpy|mask|quaternions|scikit-image | 2 |
20,616 | 49,367,799 | pandas dataframe append string to id column | <p>I have a csv file loaded in pandas and I want to append the id with a string</p>
<p>here is my code to do so.</p>
<pre><code>for index_data, row_data in dataset.iterrows():
dataset.set_value(index_data,'person_id', "u_"+ row_data['person_id'].tostring())
</code></pre>
<p>so basically instead of 1,2...n what... | <p>The issue is because <code>person_id</code> is an integer column, and <code>set_value</code> would expect a value of the <em>same</em> dtype as the column being mutated. Since you pass a string, the error is thrown (it expected a long, not a string).</p>
<p>Here's the pandaic way of doing it - vectorized string con... | python|pandas | 1 |
20,617 | 73,293,724 | Rolling Quantile Bins | <p>I wanna achieve the following:
I have some series/df of floats and now I wanna compute for each value in that series the quantile bin it belongs to with respect to some window in the past. Basically a rolling quantile bin calculation.</p>
<p>I have a solution, but it is incredibly slow</p>
<pre><code>def rolling_q_s... | <p>In case somebody was wondering. I ended up using Numba.</p>
<pre><code>@njit
def calc_quantile_nb(a):
n_smaller = 0
for i in range(len(a)):
if a[i] <= a[-1]:
n_smaller += 1
return n_smaller / len(a)
@njit
def calc_quantile_bin_nb(a, quantiles):
bin = 0
q = calc_quantile_nb(a)
... | python|pandas | 0 |
20,618 | 73,217,291 | How to append a dictionary with multiple keys to a dataframe | <p>I am trying to append a dictionary to my DataFrame.</p>
<p>This is how the DataFrame looks:</p>
<pre><code>NR RS BP
0471 10 11.41
0652 10 11.50
0650 20 11.35
6519 40 11.06
</code></pre>
<p>And this is the dictionary:</p>
<pre><code>bpDict = {"nr":["0471","0652","0650&qu... | <p>You can use the <code>merge()</code> method from Pandas dataframes. You can do something like that :</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({
"nr":["0471","0652","0650","6519"],
"RS":[10,10,20,40],
"BP":[... | python|pandas | 1 |
20,619 | 73,197,288 | How to calculate new column based on values from multiple columns | <p>I'm trying to calculate the standard deviation of values from other columns, but also based on another column value, like this:</p>
<p>Consider this sample dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">product</th>
<th style="text-align: left;">janu... | <p>Using <code>numpy</code> and a <code>mask</code>:</p>
<pre><code>df2 = df.drop(columns=['product', 'sales_months'])
a = df2.to_numpy()
mask = np.arange(a.shape[1]) >= a.shape[1]-df['sales_months'].to_numpy()[:,None]
df['std_dev'] = df2.where(mask).std(axis=1)
</code></pre>
<p>output:</p>
<pre><code> product ja... | python|pandas|dataframe | 1 |
20,620 | 67,567,172 | Throw out rows of same ID that are close in time | <p>I have a pandas dataframe that includes a column with an ID called VIN and a column with a date. If the same VIN has multiple rows with dates that are less than 2 months apart, I would like to throw out the later dates. Here's a minimal example:</p>
<pre><code>rng = pd.date_range('2015-02-24', periods=5, freq='M')
d... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>.groupby()</code></a> on column <code>ID</code> and get the difference between 2 dates with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.... | python|pandas|datetime | 3 |
20,621 | 67,394,614 | How do I sort the average of a group using Python Pandas? | <p>The data frame has country, height, and many other columns. I want to report the average height by country and sort it with the highest average on top. I am stuck at the sort. So far, I have this.</p>
<pre><code>cH = df.("Country")["Height"].mean()
</code></pre>
<p>This allowed me to find the ave... | <p>Try this:</p>
<pre><code> df= pd.DataFrame({
'Country':['a','b','a','b'],
'Height':[10,20,30,40]
})
df.groupby("Country", as_index=False).Height.mean().sort_values('Height', ascending=False)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> Country Height
1 b 30
0 a 20... | python|pandas | 1 |
20,622 | 59,980,132 | Aggregating, Ranking, Binning, Renaming, Each Column in a Dataframe | <p>How can we write a function that will aggregate, rank, bin each column of the df, rename the aggregated by adding a prefix, ranked, and binned columns, then join the new rank & bin columns to the df? </p>
<pre><code>Import pandas as pd
data = {"index_id": range(101, 131),
'company': ['Opera', 'Opera', '... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> with lambda function, then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add_prefix.html" rel="nofollow noreferrer"><cod... | python|pandas|group-by | 2 |
20,623 | 60,148,060 | Find duplicate rows based on the first two columns from a data frame and add its third column | <p>I have two data frames df1 and df2 with three columns in each. I want to find the duplicate rows based on the first two columns and replace the third column of the duplicate entries in df1 with the sum of third columns in the corresponding duplicate entries</p>
<p>simple exsample</p>
<pre><code>df1
col1 col2 col3
... | <p>Try this for no tolerance:</p>
<pre><code>pd.concat([df1, df2]).groupby(["col1", "col2"], as_index=False)["col3"].sum()
col1 col2 col3
0 80.3 29.9 20
1 80.3 30.0 20
2 80.3 30.2 20
3 80.3 30.3 20
4 80.3 30.4 20
5 80.4 29.9 10
</code></pre>
<p>For tolerance see @jezrael answer.</p> | python|pandas|duplicates | 4 |
20,624 | 59,999,893 | Slicing a range from a pandas dataframe column using loc | <p>I tried to extract a value range from a pandas column using <code>loc</code> but I fail with:</p>
<pre><code>df.loc[0.5<df['a']<1.5, ['a']]
</code></pre>
<p>What is the correct pandas way to do this?</p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html" rel="nofollow noreferrer"><code>Series.between</code></a>:</p>
<pre><code>df.loc[df['a'].between(0.5, 1.5, inclusive=False), ['a']]
</code></pre>
<p>Or chain conditions with <code>&</code> for bitwise <code>AND</... | python|pandas|slice|pandas-loc | 3 |
20,625 | 60,273,777 | How to fo transfer learning of a resnet50 model with with own dataset? | <p>I am trying to build a face verification system using keras and resnet50 model with vggface weights. The way i am trying to achieve this is by the following steps: </p>
<ul>
<li>given two image i first find out the face using mtcnn as embeddings</li>
<li>then i calculate the cosine distance between two vector em... | <p>What I would suggest is to go with triplet or siamese with these many number of classes. Use MTCNN to extract faces and then use facenet architecture to generate 512 dimensions embedding vectors, then visualize it using TSNE plot. Every face will be assigned a small embedding cluster. Go through this link for Keras ... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
20,626 | 65,253,853 | Appending only a subset of a dataframe with another one | <p>For two dataframes like</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'A' : [1,5,6] , 'B' : [3,8,9]})
df2 = pd.DataFrame({'A' : [1,7,6] , 'B' : [31,81,91]})
</code></pre>
<p>how could we append (or other combining technique) <code>df2</code> to <code>df1</code> but consider only those rows of <code>df2</cod... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer">isin</a> to find the common values and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer">concat</a> to join the DataFrames:</p>
<p... | python|pandas|dataframe | 1 |
20,627 | 65,367,327 | Subtract the value in a field in one row from all other rows of the same field in pandas dataframe | <p>I have a dataframe as shown below:</p>
<pre><code>data = {'sid':[1,1,1,2,2,2],
'field1':['start', None, None, 'start', None, None],
'field2':['a', 'b', 'z', 'd', 'z','s'],
'val':[20, 22, 23, 40, 45, 47]}
df = pd.DataFrame(data)
print(df)
sid field1 val
0 1 start 20
1 1 None ... | <p>You can use groupby with a helper column and <code>sid</code> and then get first value of the group and then subtract from <code>val</code> field.</p>
<pre><code>df['new_val'] = (df['val']-
df.groupby(['sid',df['field1'].eq("start").cumsum()])['val'].transform("first"))
</code></pre>
<hr />
... | python|pandas|dataframe | 5 |
20,628 | 65,430,580 | Error when loading torch.hub.load('pytorch/fairseq', 'roberta.large.mnli') on AWS EC2 | <p>I'm trying to run some code using Torch (and Roberta language model) on an EC2 instance on AWS.
The compilation seems to fail, does anyone have a pointer to fix?</p>
<p><em>Confirm that Torch is correctly installed</em></p>
<pre><code>import torch
a = torch.rand(5,3)
print (a)
</code></pre>
<p>Return this: tensor([[... | <p>Got it to work by loading the pretrained model locally instead of from the hub.</p>
<pre><code>from fairseq.models.roberta import RobertaModel
roberta = RobertaModel.from_pretrained('roberta.large.mnli', 'model.pt', '/home/ubuntu/deployedapp/roberta.large')
roberta.eval()
</code></pre>
<p>Note that I had to go for a... | amazon-ec2|pytorch|torch|roberta-language-model | 0 |
20,629 | 65,315,716 | pandas: convert date interval into regular date | <p>How to change a date that is expressed as an interval to be expressed as a regular %Y-%M-%D format.</p>
<p>I originally had a df that looked like this:</p>
<pre><code> Id Date Quantity
1000A 2018-03-22 20.0
1000A 2018-03-29 8.0
1000A 2018-03-27 4.0
1000A 2018-03-28 10.0
</code></pre>... | <p>You have a categorial dtype in <code>Date</code>. One way to handle it is by converting it to <code>str</code> so that you can extract the pattern you want, then convert it to <code>datetime</code>:</p>
<pre><code>data11['Date'] = data11.Date.astype(str).str.extract(', (.+?)]').astype('datetime64[ns]')
</code></pre> | python|pandas | 2 |
20,630 | 65,183,307 | How to group by key and only return observation by max from pandas dataframe | <p>How does one return all observations from a dataframe that only hold the max value for each unique key associated? I tried groupby and max but for every difference I get more than on value per key returned back. See example below:</p>
<pre><code>import pandas as pd
key = [111,111,222,333,444,555]
flag = [0,1,1,1,1... | <p>One possible solution (although maybe not the best one) is to use an inner join after the <code>groupby</code> method. This ensures that the flags are taken from the original dataframe, either they are 0 or 1.</p>
<pre><code>df.groupby(['key'])\
.agg({'date': 'max'})\
.reset_index()\
.merge(df, how='inne... | python|pandas|dataframe|group-by | 1 |
20,631 | 49,834,173 | How to save results from websocket into pandas? | <p>I am streaming data from a websocket into my python application successfully using these lines of code: </p>
<pre><code>wsClient = GDAX.WebsocketClient(url="wss://ws-feed.gdax.com", products="LTC-USD")
wsClient.start()
</code></pre>
<p>I am having trouble saving the results of <code>wsClient.start()</code>into a ... | <p>If you look at the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow noreferrer">documentation for <code>append</code></a> you can see that it returns the resulting DataFrame, and doesn't alter the DataFrame on which <code>append</code> is called nor the Data... | python|pandas|websocket | 2 |
20,632 | 50,023,744 | Conditions based on days per groups | <pre><code> A B C D E
0 2002-01-12 2018-04-25 10:00:00 John 19 19
1 2002-01-12 2018-04-25 11:00:00 John 6 25
2 2002-01-13 2018-04-25 09:00:00 John 5 30
3 2002-01-13 2018-04-25 11:00:00 John -25 5
4 2002-01-14 2018-04-25 11:00:00 John 1 6
5 2002-0... | <p>I believe need change condition with chain condition for compare <code>E</code> and for second group by <code>A</code> use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow noreferrer"><code>factorize</code></a>, for second group use <code>>0</code>:</p>
<pre><co... | python|pandas|conditional | 1 |
20,633 | 50,053,968 | Is it possible to perform real-time communication with a Google Compute Engine instance? | <p>I would like to run a program on my laptop (Gazebo simulator) and send a stream of image data to a GCE instance, where it will be run through an object-detection network and sent back to my laptop in near real-time. Is such a set-up possible?</p>
<p>My best idea right now is, for each image:</p>
<ol>
<li>Save the ... | <p>If your question is "is it possible to set up such a system and do those actions in real time?" then I think the answer is yes I think so. If your question is "how can I reduce the number of steps in doing the above" then I am not sure I can help and will defer to one of the experts on here and can't wait to hear t... | python|numpy|tensorflow|google-compute-engine|google-cloud-pubsub | 1 |
20,634 | 63,809,591 | Adding to a dataframe a new column | <pre><code>Start_Time
2016-02-08 05:46:00
2016-02-08 06:07:59
2016-02-08 06:49:27
2016-02-08 07:23:34
</code></pre>
<p>This is a column of a dataframe I am working with. How can I add to the dataframe an extra column that holds the day of the week that the <code>Start_Time</code> occurred in each line?</p> | <p>assuming your column is already a datetime we can use the <code>dt.</code> accessor to use datetime methods</p>
<p>if not use <code>pd.to_datetime(df['Start_Time'])</code></p>
<pre><code>df['day_name'] = df['Start_Time'].dt.day_name()
</code></pre>
<p>or</p>
<pre><code>df['dayofweek'] = df['Start_Time'].dt.dayofweek... | python|pandas|dataframe | 1 |
20,635 | 64,034,130 | Sum first occurence of value from two columns in different dataframes | <p>I have two dataframes that look like this:</p>
<pre><code>df1
Category Year cat_counts
43 5.0 1988 1
44 1.0 1987 4
45 3.0 1987 3
46 3.0 1987 3
47 1.0 1987 4
48 2.0 1985 2
49 3.0 1985 3
50 1.0 1983 4
51 1.0 1983 4
52 2.0 1982 2
53 4.0 1980 1
df2
Category Year ... | <p><code>concat</code> then <code>value_counts</code></p>
<pre><code>pd.concat([df1, df2])['Category'].value_counts()
1.0 14
2.0 8
3.0 4
5.0 3
4.0 2
Name: Category, dtype: int64
</code></pre> | python|pandas|dataframe | 1 |
20,636 | 64,146,106 | Create multiple empty columns and assign it to 0 in pandas dataframe | <p>I am not sure if it's a good idea. I am using transfer learning to train some new data. The model shape has 180 columns(features) and the new data input has 500 columns. It 's not good to cut columns from the new data. So I am thinking to add more columns to the dataset used in the original model. So if I want to ad... | <p>Since you don't care about columns label, use <code>pd.concat</code> on new construct dataframe from <code>np.zeros</code></p>
<p>Sample df</p>
<pre><code>In [336]: df
Out[336]:
0 1 2 3 4 5
0 0.28001 0.32042 0.93222. 0.87534. 0.44252 0.2321
1 0.38001 0.42042 0.13... | python|pandas | 1 |
20,637 | 63,822,222 | Find value of one column within another column | <p>I have a dataframe:</p>
<pre class="lang-python prettyprint-override"><code>df = pd.DataFrame({'start': ['2020-08-01', '2020-08-02', '2020-08-03', '2020-08-04', '2020-08-05', '2020-08-06', '2020-08-07', '2020-08-08'],
'end': ['2020-08-03', '', '', '2020-08-06', '', '2020-08-08', '', ''],
... | <p>Check with</p>
<pre><code>s = df['start'].isin(df['end']).astype(int)
df['New'] = s.where(s==1 ,'')
</code></pre> | python|pandas|dataframe | 2 |
20,638 | 64,171,427 | Pandas to_dict() converts datetime to Timestamp | <p>In my pandas DataFrame, I have some date values which I converted from a timestamp to datetime, using the <code>datetime</code> module. Printing out the DataFrame looks good, but when I convert the DataFrame to a dictionary using <code>to_dict()</code>, the datetime values appear to be of the pandas <code>Timestamp<... | <p>The why can be found <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.html" rel="nofollow noreferrer">here</a>.</p>
<p>I don't know how to prevent it from happening but you could convert the Timestamps to datetime64 aftwards:</p>
<pre><code>for rec in list_out:
rec['created'] ... | python|pandas|dataframe|datetime|timestamp | 4 |
20,639 | 46,858,890 | Simple ML Algo not working: ValueError: Error when checking input: expected dense_4_input to have shape (None, 5) but got array with shape (5, 1) | <p>I have an incredible simple algorithm that is erroring with, "ValueError: Error when checking input: expected dense_4_input to have shape (None, 5) but got array with shape (5, 1)"....
Here is the code I am running.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequentia... | <p>There are two problems:</p>
<p><strong>First</strong>: As the output already says: <code>"ValueError: Error when checking input: expected dense_4_input to have shape (None, 5) but got array with shape (5, 1)"</code> This means, that the Neural Network expects an array of shape (*, 5). With the asterisk I want to ... | numpy|machine-learning|keras | 2 |
20,640 | 46,777,564 | Python Pandas if statement based on group by sum | <p>Working with this python pandas dataframe df: </p>
<pre><code>CategoryA | CategoryB | Count
1 A 0
1 A -1
2 B 1
2 B 1
3 C 1
3 C -1
</code></pre>
<p>I basically want to mark for deletion, all group... | <p>You're on the right track. </p>
<pre><code>m = df.groupby(['CategoryA', 'CategoryB']).transform('sum').gt(0)
df['decision'] = np.where(m, 'keep', 'delete')
df
CategoryA CategoryB Count decision
0 1 A 0 delete
1 1 A -1 delete
2 2 B 1 keep
... | python|pandas|dataframe|group-by|pandas-groupby | 3 |
20,641 | 62,943,363 | Print specific rows that are common between two dataframes | <p>i have a dataframe (df1) like this</p>
<pre><code>id link
1 google.com
2 yahoo.com
3 gmail.com
</code></pre>
<p>i have another dataframe(df2) like this:</p>
<pre><code>id link numberOfemployees
1 linkedin.com 15
2 facebook.com 70
3 gmail.com 90
4 ... | <p>You could try this simple solution:</p>
<pre><code>df2[df2.link.isin(df1.link)]
</code></pre> | python|pandas|dataframe | 2 |
20,642 | 63,163,454 | Yelp Web Scraping | <p>When running my code on Jupyter notebook, I ran across this error. I installed <code>matplotlib</code> and <code>pandas</code>. Does anyone know what it could be?
Code:</p>
<pre><code>def average_words(x):
words = x.split()
return sum(len(word) for words in word) / len(words)
df['average_word_length'] = df['re... | <p><strong>Problem:</strong></p>
<p>NameError: name 'word' is not defined. You are trying to access word, but word is obviously not defined.</p>
<p><strong>Possible Solution:</strong></p>
<p>I think the correct return statement is like this:</p>
<p><code>return sum(len(word) for word in words) / len(words)</code></p>
<... | python|pandas|dataframe|web-scraping|jupyter-notebook | 0 |
20,643 | 68,000,285 | Travel time - Python | <p>Is there any way to calculate the minimum travel time from O-D route to point A, using Python and Google API or OSMnx library?</p>
<p>O and D refer to the Origin and Destination points, respectively.</p>
<p>For example:</p>
<p>O is <code>(30.2641922, -97.746646)</code></p>
<p>D is <code>(30.3034562, -97.7073463)</co... | <p>How about computing the distance of every node along the way and taking the shortest path?
In the code below, I use a point A that is much closer since your point A is too far for me to store a graph that contains as many nodes as there are in between the path O-D and the point A.
This solution will work for short d... | python|pandas|numpy|google-api|osmnx | 2 |
20,644 | 67,787,148 | pandas get days in a column from start date? | <p>pandas get days in a column from start date?</p>
<p>start_date = '01/01/2021' (dd/mm/yyyy)</p>
<p>df</p>
<pre><code> dates
2021-01-01
2021-01-02
.
.
.
2021-02-01
.
.
.
2021-06-01 (end date should be current date)
</code></pre> | <p>If there is always <code>1.1.</code> pandas parse datetimes like <code>mm/dd/YYYY</code> so because same day and month here working well only passing string to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer"><code>date_range</code></a> with <a href... | pandas|dataframe|numpy|python-datetime | 1 |
20,645 | 67,612,099 | pandas dataframe regex filtering of hierarchical columns | <p>Consider the following dataframe:</p>
<pre><code>df = pd.DataFrame(columns=['[mg]', '[mg] true'], index=range(3))
</code></pre>
<p>To filter for the column ending in <code>]</code>, one may use:</p>
<pre><code>print(df.filter(regex="\]$"))
[mg]
0 NaN
1 NaN
2 NaN
</code></pre>
<p>Next, consider a hiera... | <p>One option is to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html#pandas-series-str-contains" rel="nofollow noreferrer">str.contains</a> on the <a href="https://pandas.pydata.org/docs/reference/api/pandas.Index.get_level_values.html#pandas-index-get-level-values" rel="nofollo... | python|regex|pandas|dataframe|hierarchical | 1 |
20,646 | 61,471,104 | How would I best normalize the pd MultiIndex df? | <p>I have a PD df that is MultiIndex. I would like to run a function over each symbol but am running the normalizing function over full d. The first symbol is good but the symbols that follow are getting manipulated by the first symbol. How would I normalize with vectorization rather than iterating over the symbol and ... | <p>Let us do <code>groupby</code> + <code>transform</code> </p>
<pre><code>df.loc['Adj_Close_Norm']=df['Adj_Close_Price']/df.groupby(level=0)['Adj_Close_Price'].transform('first')
</code></pre> | python|pandas|dataframe|multi-index | 1 |
20,647 | 68,571,619 | Extract JSON arrays into dataframe | <p>I have <code>project.json</code> file, which contains data like this :</p>
<pre><code>{"student_id": "ST0001", "project": [{"subject_id": "S003", "date_of_submission": "2021-05-23 20:03:05"}, {"subject_id": "S004", "date_o... | <pre><code>import pandas as pd
df=pd.read_json('project.json', lines=True)
df = pd.DataFrame(df).explode('project')
df = df.join(pd.json_normalize(df.pop('project')))
df.set_index("student_id",inplace=True)
print(df)
"""
student_id project_year subject_id date_of_submission
ST0001 ... | python|pandas | 1 |
20,648 | 68,862,495 | Learning Object Detection Detected result showed in discolouration | <p><strong>Breif Description</strong></p>
<p>Recently begin to learning Object Detection, Just starting off with PyTorch, YOLOv5. So I thought why not build a small side project to learn? Using it to train to detect Pikachu.</p>
<p><strong>The Problem</strong></p>
<p>I've successfully trained the model with Pikachu and... | <p>The problem is that <code>Image.fromarray</code> expects image in RGB and you're providing them in BGR. You just need to change that. There are multiple places you could do that, for instance:</p>
<pre class="lang-py prettyprint-override"><code>Image.fromarray(img[...,::-1]) # assuming `img` is channel-last
</code>... | python|colors|pytorch|object-detection|yolov5 | 3 |
20,649 | 52,915,107 | How to build a list of numpy arrays where each array is uniquely sized | <p>I'm trying to create a python list of numpy arrays, where each array in the list will have unique dimensions - how I can construct it and also alter a specific entry within a specific within the list on the fly?</p>
<p>For example: I have three matrices (numpy arrays) with dimensions MxN, PxQ and AxB where {A,B,P,Q... | <p>Just create the list:</p>
<pre><code>l = [np.zeros((M, N)), np.zeros((P,Q)), np.zeros((A,B))]
</code></pre>
<p>And use <code>0</code>, <code>1</code> or <code>2</code> to get to the element you want.</p> | python|arrays|numpy | 0 |
20,650 | 53,273,662 | Pytorch. Can autograd be used when the final tensor has more than a single value in it? | <p>Can autograd be used when the final tensor has more than a single value in it?</p>
<p>I tried the following. </p>
<pre><code>x = torch.tensor([4.0, 5.0], requires_grad=True)
y = x ** 2
print(y)
y.backward()
</code></pre>
<p>Throws an error</p>
<pre><code>RuntimeError: grad can be implicitly created only for sc... | <p>See <a href="https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html#gradients" rel="noreferrer">https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html#gradients</a></p>
<p><code>y.backward()</code> is same as <code>y.backward(torch.tensor(1.0))</code></p>
<p>Usually, the output is scalar ... | python|pytorch|autograd | 10 |
20,651 | 53,348,215 | CV2 not displaying colors when converting to uint8 | <p>I have a python list that contains the RGBA data of a PNG image represented as int32, which was sent over from a Java socket server.</p>
<p>A sample output of this data as a numpy array without any conversions:</p>
<pre><code>[[-12763847 -12763847 -12763847 ... -5590160 -12039396 -12434915]
[-12763847 -12763847 ... | <p>Hopefully this will help you see how to extract the Red, Green and Blue channels from the 32-bit values. I started off with the first row of your array.</p>
<pre><code>im=np.array([-12763847,-12763847,-12763847,-5590160,-12039396,-12434915],dtype=np.int32)
R = ((im & 0xff).astype(np.uint8)
# array([ 57, 57, ... | python|numpy|cv2|rgba | 2 |
20,652 | 65,603,205 | How to find the frequency of list of words in a DataFrame using Pandas | <p>my <code>df</code> looks like this:</p>
<pre><code>category text_list
-------- ---------
soccer [soccer, game, is, good, soccer, game]
basketball [game, basketball, game]
volleyball [sport ,volleyball, sport]
</code></pre>
<p>What I want to do is <code>groupby</code> <code>category</code... | <p>Try <code>explode</code> then <code>groupby</code>:</p>
<pre><code>(df.explode('text_list')
.groupby(['category','text_list']).size()
.to_frame(name='frequency')
)
</code></pre>
<p>Output:</p>
<pre><code> frequency
category text_list
basketball basketball 1
... | python|pandas|nltk | 2 |
20,653 | 65,509,955 | TensorFlow/Keras model __call__ gets slower and slower when run on GPU | <p>I'm trying to implement an AlphaZero-like boardgame AI for the game Gomoku (Monte Carlo Tree Search in combination with a CNN that evaluations board positions).</p>
<p>Right now, the MCTS is implemented as a separate component.
Additionally, I have a simple TCP server written in Python that receives positions from t... | <p>I had a similar issue and was due to having the wrong NVIDIA drivers installed for my card and not having CUDA installed. Hope that was helpful.</p>
<p><a href="https://developer.nvidia.com/cuda-downloads" rel="nofollow noreferrer">https://developer.nvidia.com/cuda-downloads</a></p> | python|tensorflow|keras | 0 |
20,654 | 65,703,709 | Input contains infinity or a value too large for dtype('float64') error | <p>Input contains infinity or a value too large for dtype('float64') error shows up when I run this code. How can I solve it?</p>
<pre><code>from sklearn import preprocessing
from tensortrade.data.cdd import CryptoDataDownload
import pandas as pd
cdd = CryptoDataDownload()
data = cdd.fetch("Bitstamp", &quo... | <p>Try running this. You need to replace Nan and Inf values with a number of your choice</p>
<pre><code>import numpy as np
from sklearn import preprocessing
from tensortrade.data.cdd import CryptoDataDownload
import pandas as pd
cdd = CryptoDataDownload()
data = cdd.fetch("Bitstamp", "USD", "... | python|python-3.x|pandas|scikit-learn|tensorboard | 2 |
20,655 | 63,549,926 | tensorflow.python.framework.errors_impl.AlreadyExistsError when training LSTM model | <p>I'm trying to make a machine learning model in keras that guesses the next word, given a series of words using a LSTM. This is the code for my model:</p>
<pre><code>gen=Sequential()
gen.add(Embedding(vocab_size,embed_dim))
gen.add(LSTM(vocab_size,activation='softmax'))
gen.compile(loss='categorical_crossentropy',opt... | <p>So I just tried an experiment, and discovered that it was the output shape of the LSTM, and having a smaller output length and then expanding it with a Dense Layer removes the error.</p> | python|tensorflow|keras|lstm | 1 |
20,656 | 63,434,199 | Encoded and decoded version of bouding box regression offsets are different | <p>I'm trying to replicate bounding box regression technique used in faster-rcnn as given <a href="https://lilianweng.github.io/lil-log/2017/12/31/object-recognition-for-dummies-part-3.html" rel="nofollow noreferrer">here</a>. I've made a decoding fuunction and an encoding function. Ideally, when passing a bounding box... | <p>The problem was in my <code>decode</code> function in calculating <code>[x_min, y_min, x_max, y_max]</code>. It should have been like this:</p>
<pre><code># [x_min, y_min, x_max, y_max]
boxes = tf.concat([boxes[:, :2] - boxes[:, 2:] / 2, boxes[:, 2:] / 2 + boxes[:, :2]], axis=1)
</code></pre> | python|numpy|tensorflow|regression|faster-rcnn | 0 |
20,657 | 63,401,706 | Pandas: Convert Yfinance dictionary to dataframe but the row is empty | <p>I have a Yfinance dictionary like this:</p>
<p>{'zip': '94404',
'sector': 'Healthcare',
'fullTimeEmployees': 11800,
'circulatingSupply': None,
'startDate': None,
'regularMarketDayLow': 67.99,
'priceHint': 2,
'currency': 'USD'}</p>
<p>I want to convert it into DataFrame but the output has no information on Row:</p>
<... | <pre><code># Data returned back by yfinance
stock = yf.Ticker('AAPL')
# Store stock info as dictionary
stock_dict = stock.info
# Create DataFrame from non-compatible dictionary
stock_df = pd.DataFrame(list(stock_dict.items()))
0 1
0 zip 95014
1 sector Technology
2 fullTimeEmployees 137000
3 longBus... | python|pandas|dataframe|yfinance | 0 |
20,658 | 72,046,201 | How to make a copy of Pandas DataFrame in the correct way | <p>I have the following dataframe:</p>
<pre><code>import pandas as pd
d = {'col1': [1, 2], 'col2': [{"a": 5}, {"a": 8}]}
df = pd.DataFrame(data=d)
df
</code></pre>
<p>Output:</p>
<pre><code> col1 col2
0 1 {'a': 5}
1 2 {'a': 8}
</code></pre>
<p>And I have the following code pie... | <p>You can't simply use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.copy.html" rel="nofollow noreferrer"><code>DataFrame.copy</code></a> here. See the note at the bottom of the page:</p>
<blockquote>
<p>Note that when copying an object containing Python objects, a deep copy will copy the data... | python|python-3.x|pandas|dataframe | 1 |
20,659 | 56,476,043 | Condition for an python panda dataframe using an List with range | <p>How can I create an if conditions in a data frame that includes a list with a range between the elements? I want a new smaller data frame that is in a range of certain values. Like <code>x</code> element of <code>[2,4]</code> and save it in a new data frame.</p>
<p>For example:</p>
<pre><code>x y
1 4
2 7
3 8
4 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html" rel="nofollow noreferrer"><code>Series.between</code></a> for boolean mask:</p>
<pre><code>df = df[df['x'].between(2,4)]
print (df)
x y
1 2 7
2 3 8
3 4 11
</code></pre>
<p>It working same like 2 conditio... | python|pandas|dataframe | 2 |
20,660 | 67,147,498 | Python/Pandas - How to Create a Line Graph in a multi-level pivoted table | <p>I pivoted a DF, setted the indexes according the organization I want.</p>
<p>But I'm not able to create a graph with years in x-axis and each country with its value. In order to show to evolution of each country.</p>
<p>I tried Seaborn and Matplotlib and I wasn't able to do so.</p>
<p>The link for my GitHub: <a href... | <p>With seaborn, working with explicit columns is easiest. Pandas' <code>reset_index()</code> converts the index to regular columns. Here is a code example starting from test data:</p>
<pre><code>from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
countries = ['abc', 'def'... | python|pandas|matplotlib|seaborn|pivot-table | 0 |
20,661 | 47,387,561 | how to calculate the flops from tfprof in tensorflow? | <p>how can i get the number of <code>flops</code> from <code>tfprof</code> i have the code as:</p>
<pre><code>def calculate_flops():
# Print to stdout an analysis of the number of floating point operations in the
# model broken down by individual operations.
param_stats = tf.contrib.tfprof.model_analyzer.p... | <p>First of all, as of now, <code>tfprof.model_analyzer.print_model_analysis</code> is deprecated and <code>tf.profiler.profile</code> should be used instead according to the official documentation.</p>
<p>Given that we know the number of <code>FLOP</code>, we can get the FLOPS (FLOP per second) of a forward pass by m... | tensorflow | 8 |
20,662 | 68,343,961 | Saving a trained Detectron2 model and making predictions on a single image | <p>I am new to detectron2 and this is my first project. After reading the docs and using the tutorials as a guide, I trained my model on the custom dataset and performed the evaluation.</p>
<p>I would now like to make predictions on images I receive via an API by loading this saved model. I could not find any reading m... | <p>for a single image, create a list of data. Put image path in the <code>file_name</code> as below:</p>
<pre><code>test_data = [{'file_name': '.../image_1jpg',
'image_id': 10}]
</code></pre>
<p>Then do run the following:</p>
<pre><code>from detectron2.config import get_cfg
from detectron2.engine import D... | deployment|pytorch|prediction|fastapi|detectron | 1 |
20,663 | 68,432,666 | Tensorflow Dataset in predict() method throws error | <p>I am currently trying to use a Tensorflow dataset as input to the predict() function of a tensorflow model. For some reason, I always get an error, details are below.</p>
<p>I have the following generator:</p>
<pre><code>def create_dataset(Q, unary_potentials, features_1, features_2, features_3, kernel_size, depth_i... | <p>From the documentation of <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#predict" rel="nofollow noreferrer">tf.keras.Model.predict()</a> method:</p>
<blockquote>
<p>x Input samples. It could be:</p>
</blockquote>
<blockquote>
<blockquote>
<p>A Numpy array (or array-like), or a list of arrays (in... | python|tensorflow|tensorflow2.0 | 0 |
20,664 | 68,275,288 | Python: How do I filter from a list of files in a directory using a datetime index? | <p>I want to use python to iterate through a list of files in a directory that look like this, however I want to use a date range to filter out only the dates I want:</p>
<pre><code>I:/directory
-file_2019-01-01.parquet
-file_2019-01-02.parquet
-file_2019-01-03.parquet
-file_2019-01-04.parquet
...
</code></pre>
<p>In R... | <p>Here's one way:</p>
<pre><code>from pathlib import Path
from datetime import datetime
def pull_files(dir, start, stop):
start_date_time = datetime.strptime(start, '%Y-%m-%d')
stop_date_time = datetime.strptime(stop, '%Y-%m-%d')
return [file
for file in Path(dir).glob('*')
if (sta... | python|pandas|datetime | 0 |
20,665 | 46,126,362 | pandas group by and then select certain columns | <p>I have an input dataframe</p>
<pre><code>df_orders = pd.DataFrame({'item_id': [1, 1, 2, 2, 3, 4, 4, 5, 7, 8],
're_order':[0, 1, 0, 1, 1, 0, 1, 1, 1, 0],
'count':[27, 49, 3, 1, 6, 8, 14, 1, 1, 6] },
columns=['item_id', 're_order', 'count'])
or... | <p>You can precalculate the <code>re_order</code> column by multiplying <code>re_order</code> with <code>count</code> and then do <code>groupby.sum</code>:</p>
<pre><code>(df_orders.assign(re_order = df_orders['re_order'] * df_orders['count'])
.groupby('item_id', as_index=False).sum())
# item_id re_order count
... | python|pandas|dataframe|group-by | 2 |
20,666 | 50,885,598 | Selection rows in Pandas | <p>how to select rows that are between 2 dates and I have 2 column valid from and valid too. I want to select rows between certain dates that match up these 2 columns.</p> | <p>This will provide a view of rows where the <code>DateFrom</code> and <code>DateTo</code> columns are between the dates you specify. Is this what you wanted?</p>
<pre><code>from datetime import datetime
df.loc[(df.DateFrom >= datetime(2018, 1, 1)) & (df.DateTo <= datetime(2018, 2, 1))]
</code></pre> | pandas | 0 |
20,667 | 51,053,088 | Add legend to barplot composed of numerous catogies | <p>This question is related to this <a href="https://stackoverflow.com/questions/18897261/pandas-plot-dataframe-barplot-with-colors-by-category">one</a>. After I plot the barplot with different colors, I would like to add a corresponding legend but I cannot figure out how. Is it even possible?</p>
<pre><code>df = pd.D... | <p>You can use <code>.pivot</code> to get things into the right structure and then just use <code>.plot</code>:</p>
<pre><code>df.pivot("index", "group")["values"].plot(kind="bar")
</code></pre>
<p><a href="https://i.stack.imgur.com/LGeCe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LGeCe.png" a... | python|pandas|matplotlib|legend | 1 |
20,668 | 66,470,967 | iteration through column values in python w.r.t index | <p><a href="https://i.stack.imgur.com/pyjiN.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>where columns are true ,i want column name,
where more than one columns are true: columns name separated with /</p>
<p>blank cells are empty string</p>
<p>Required output:</p>
<p>Natural gas: Dark cloud
Co... | <p>You can do this unsing <code>pandas.DataFrame.apply()</code> on <code>axis=1</code>.</p>
<p>Example:</p>
<pre><code>df = pd.DataFrame({'a':[np.nan, True], 'b':[True, np.nan], 'c':[True, np.nan]})
>> df
a b c
0 NaN True True
1 True NaN NaN
df_ = df.apply(lambda x: ' / '.join(x.dropna()... | pandas|dataframe | 0 |
20,669 | 72,915,371 | Access Panda index in apply function to create html | <p>I have panda Series with index as product name and values as its rate. I want to create string as below</p>
Product Name Product rate
<p>Currently I am using for loop
for p,v in srs.items():
some_var='<font ...>' + p + '' + '%.2f' % v + ''</p>
<p>Can I do above code without for loop like using apply or any o... | <p>You can use:</p>
<pre><code>srs = srs.to_frame()
srs['some_var'] = '<font ...>' + srs.index + '' + '%.2f' % srs['column_name'] + ''
</code></pre>
<p>Where <code>'column_name'</code> is the name of the column after transforming the series to a DataFrame.</p> | python-3.x|pandas | 0 |
20,670 | 73,031,553 | Concatenating lists across different rows within a dataframe according to another column | <p>Would like to create a nested list of lists within one table according to a matching key in another table. To illustrate this, I've anonymized the PII data and built a small example of what I'm trying to do.</p>
<hr />
<p>I'm starting with a table that lists all parent_id's for a given child_id stored as a list with... | <p>You can explode <code>child_parent_relations_df</code> <code>parent_id_list</code> column to rows then <code>merge</code> <code>parent_tag_ids</code> column from <code>parent_id_with_tags_df</code> and <code>groupby.agg</code></p>
<pre class="lang-py prettyprint-override"><code>child_parent_relations_df = child_pare... | python|pandas|dataframe|lookup|nested-lists | 1 |
20,671 | 70,460,683 | How to convert an Iterator into Pandas DataFrame? | <p>I was trying to extract checkbox values from a PDF which I am able to with the help of the code below which I found from a thread in stackoverflow and it was provided by @Fabian.</p>
<p><a href="https://stackoverflow.com/questions/55812539/python-pdf-how-to-read-from-a-form-with-radio-buttons">Python: PDF: How to re... | <p>IIUC:</p>
<pre><code>import pandas as pd
data = []
for i in fields:
#Rest of logic
print (f'{name}: {value}')
data.append([name, value])
df = pd.DataFrame(data, columns=['name', 'value'])
df.to_excel("output.xlsx", index=False)
</code></pre> | python|pandas|dataframe|pdfminer | 0 |
20,672 | 51,258,419 | Append number of times a string occurs in Pandas dataframe to another column | <p>I'd like to create an extra column on this dataframe:</p>
<pre><code>Index Value
0 22,88,22,24
1 24,24
2 22,24
3 11,22,24,12,24,24,22,24
4 22
</code></pre>
<p>So that the number of times a value occurs is stored in... | <p>If want count only one value use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.count.html" rel="nofollow noreferrer"><code>str.count</code></a>:</p>
<pre><code>df['22 Count'] = df['Value'].str.count('22')
print (df)
Value 22 Count
Index ... | python|pandas|dataframe|counting | 3 |
20,673 | 71,044,661 | Sort and create new columns by specific values using Pandas | <p>How to sort or group by dataframe by specific values from multiple columns with Pandas?</p>
<p>The dataframe that I am working with looks like below. I have 3 type columns with corresponding parameters <code>count</code> and <code>param</code>. For each type accordingly <code>count</code> and <code>param</code> colu... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer"><code>wide_to_long</code></a> for reshape first, then create helper column <code>type1</code> used for groups by add to <code>MultiIndex</code> in <a href="http://pandas.pydata.org/pandas-docs/s... | python|pandas|dataframe | 2 |
20,674 | 70,865,732 | Faster numpy isin alternative for strings using numba | <p>I'm trying to implement a faster version of the <code>np.isin</code> in <code>numba</code>, this is what I have so far:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import numba as nb
@nb.njit(parallel=True)
def isin(a, b):
out=np.empty(a.shape[0], dtype=nb.boolean)
b = set(b)
... | <p>Strings are barely supported by Numba (like <code>bytes</code> although the support is slightly better). Set and dictionary are supported with some strict restriction and are quite experimental/new. <strong>Sets of strings are not supported yet</strong> regarding the <a href="https://numba.readthedocs.io/en/stable/r... | python|string|numpy|performance|numba | 2 |
20,675 | 51,645,003 | How to merge only chosen columns of right frame? | <p>How to join only column 'd'? And avoid of joining 'c' as well. It's deliberate that names of key-columns are different ('a' and 'c', accordingly).</p>
<p>t1</p>
<pre><code> a b
0 5 2
1 3 4
2 1 6
</code></pre>
<p>t2</p>
<pre><code> c d
0 1 20
1 3 40
2 5 60
</code></pre>
<p>resul... | <p>If you want to only add the <strong><code>d</code></strong> column to the first Dataframe, just concat <strong><code>d</code></strong>:</p>
<pre><code>pd.concat([t1, t2.d], 1)
a b d
0 5 2 20
1 3 4 40
2 1 6 60
</code></pre>
<p>Or using <strong><code>join</code></strong>:</p>
<pre><code>t1.join(t2.d... | python|pandas|merge | 2 |
20,676 | 51,655,623 | how to ignore index comparison for pandas assert frame equal | <p>I try to compare below two dataframe with "check_index_type" set to False. According to the documentation, if it set to False, it shouldn't "check the Index class, dtype and inferred_type are identical". Did I misunderstood the documentation? how to compare ignoring the index and return True for below test?</p>
<p>... | <p>If you really don't care about the index being equal, you can drop the index as follows:</p>
<pre><code>assert_frame_equal(d1.reset_index(drop=True), d2.reset_index(drop=True))
</code></pre> | python|pandas | 51 |
20,677 | 51,640,064 | Can a Neural Network learn a simple interpolation? | <p>I’ve tried to train a 2 layer neural network on a simple linear interpolation for a discrete function, I’ve tried lots of different learning rates as well as different activation functions, and it seems like nothing is being learned!</p>
<p>I’ve literally spent the last 6 hours trying to debug the following code, b... | <p>Although your problem is quite simple, it is poorly scaled: <code>x</code> ranges from 255 to 200K. This poor scaling leads to numerical instability and overall makes the training process unnecessarily unstable.<br>
To overcome this technical issue, you simply need to scale your inputs to <code>[-1, 1]</code> (or <c... | machine-learning|neural-network|deep-learning|pytorch | 1 |
20,678 | 36,066,475 | Optimizing web-scraper python loop | <p>I'm scraping articles from a news site on behalf of the owner. I have to keep it to <= 5 requests per second, or ~100k articles in 6 hrs (overnight), but I'm getting ~30k at best.</p>
<p>Using Jupyter notebook, it runs fine @ first, but becomes less and less responsive. After 6 hrs, the kernel is normally un-in... | <p>I'm going to take an educated guess and say that your script turns your machine into a swap storm as you get around 30k articles, according to your description. I don't see anything in your code where you could easily free up memory using:</p>
<pre><code>some_large_container = None
</code></pre>
<p>Setting somethi... | python|pandas|web-scraping | 1 |
20,679 | 36,095,185 | Python Pandas output rounded DataFrame to dictionary | <p>I've got a spreadsheet containing (among other things) rows of people and their education levels, which I've read into a DataFrame. </p>
<p>I am trying to return a dictionary containing relative frequencies which have been rounded to 3 decimal places.</p>
<pre><code>return self.data['education'].value_counts(norma... | <p>try this:</p>
<pre><code>pd.options.display.float_format = '{:,.3f}'.format
</code></pre> | python|pandas | 1 |
20,680 | 35,856,095 | While loop doesn't stop when looping through dates | <p>Why does this while loop never stop?</p>
<pre><code>t = pd.to_datetime('2016.03.04')
T = pd.to_datetime('2019.09.04')
dates = T
while dates > t:
dates = T- pd.DateOffset(years=1)
print(dates)
</code></pre>
<p>Please help</p> | <p>The problem is that you're not summing the offsets.</p>
<p>Change this line:</p>
<pre><code>dates = T - pd.DateOffset(years=1)
</code></pre>
<p>to this:</p>
<pre><code>dates -= pd.DateOffset(years=1)
</code></pre> | python|loops|pandas | 2 |
20,681 | 35,940,600 | How to write consistent code using Numpy/Scipy? | <p>I'm new to python and numpy/scipy. The design of Numpy array and the broadcasting rule in numpy/scipy is sometime quite helpful while remaining a lot of pain to me.</p>
<p>I read something like </p>
<blockquote>
<p>Numpy tries to keep the array in the lowest dimension.</p>
</blockquote>
<p>somewhere.</p>
<p>He... | <p><code>np.atleast_2d</code> might solve all your issues.</p>
<p>Even the last might be written as:</p>
<pre><code>np.dot(weight.T, (X - np.atleast_2d(mu)).T)
</code></pre>
<p>or maybe</p>
<pre><code>np.dot(X-np.atleast_2d(mu), weight) # tested with (3,2),(2,3) arrays
</code></pre>
<hr>
<p>The issue of matlab/n... | python|numpy|scipy|scikit-learn | 2 |
20,682 | 37,545,824 | How to change DataFrame Series from price to percentage with pandas/python | <p>I have a pandas dataFrame with date,time and stock price like this:</p>
<pre><code>+------------+-------+-------+-------+
| | 08:01 | 08:02 | 08:03 |
+------------+-------+-------+-------+
| 01/01/2016 | 50 | 50.5 | 50.7 |
+------------+-------+-------+-------+
| 02/01/2016 | 49.6 | 49.5 | 49.6 |... | <p>Use difference by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a> with first column selected by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code></a> and last substr... | python|python-3.x|pandas | 3 |
20,683 | 42,055,278 | Combine matrices - numpy | <p>I have four numpy matrix, each which shape is <code>(2544, 2544).</code> I wish to combine them to create a matrix which is <code>(2544, 2544)</code> by adding the corresponding elements from each. How can I do this? For example if I had this matrix:</p>
<pre><code>x = [1,2
3,4]
y = [4,3
2,2]
</code></pre... | <p>I've edited my answer to reflect your specific question, but if you define your variables as matrices, you can simply add the variables as long as they are the same shape. Some example code is seen below:</p>
<pre><code>import numpy as np
x = np.matrix([[1,2],[3,4]])
y = np.matrix([[4,3],[2,2]])
d = x + y
print ... | python|numpy|matrix | 0 |
20,684 | 37,948,271 | assigning bounds to individual independent points within the scipy.optimize.curve_fit function | <p>I am trying to fit a Planck curve to radiance readings. I know the radiance at some known wavelengths (11 data points), the parameter to fit is the temperature.</p>
<p>The Planck function that returns the radiance from the wavelength and the temperature:</p>
<pre><code>def bbody(lam, T) :
lam = 1e-6 * lam # fr... | <p>It seems that your "bounds" somehow quantify uncertainties of the readings of the independent variable (wavelengths). </p>
<p><code>bounds</code> parameter is definitely not helpful: it's job is to set the allowed bounds for the parameter you're estimating (e.g., you know that the temperature is not negative).</p>
... | python|numpy|scipy|curve-fitting | 2 |
20,685 | 37,836,275 | Memory error in pandas | <p>I have a csv file which has a size of around 800MB which I'm trying to load into a dataframe via pandas but I keep getting a memory error. I need to load it so I can join it to another smaller dataframe.</p>
<p>Why am I getting a memory error even though I'm using 64bit versions of Windows, and Python 3.4 64bit and... | <p>reading your CSV in chunks might help:</p>
<pre><code>chunk_size = 10**5
df = pd.concat([chunk for chunk in pd.read_csv(filename, chunksize=chunk_size)],
ignore_index=False)
</code></pre> | pandas|memory-management | 1 |
20,686 | 31,475,301 | how can we give index while calculating 3 days moving average | <p>I have a data sets like below and want to calculate the max value 3 days moving average and tried this code</p>
<pre><code>pd.rolling_mean(data['prec'], 3).max()
</code></pre>
<p>this code gives the moving average but without date</p>
<pre><code> year month day prec
0 1981 1 1 1.5
1 1981... | <p>Assign the result of <code>pd.rolling_mean</code> or <code>pd.rolling_max</code> to a DataFrame column:</p>
<pre><code>import pandas as pd
df = pd.read_table('data', sep='\s+')
df['moving average'] = pd.rolling_mean(df['prec'], 3)
df['max of moving average'] = pd.rolling_max(df['moving average'], 3)
</code></pre>
... | pandas|moving-average | 0 |
20,687 | 64,531,236 | UnidentifiedImageError when training a model using TF ImageGenerator | <p>I'm running a binary classifier of 21250 images (total for the 2 classes). My batch size is at 425 with steps at 50.</p>
<p>When I run the model I get the following error:</p>
<pre><code>UnknownError: 2 root error(s) found.
(0) Unknown: UnidentifiedImageError: cannot identify image file <_io.BytesIO object at ... | <p>This error could be happening due to the images being of 'NoneType' where although you may see them being of <code>.jpeg or .png</code> the image was actually corrupted somehow during preprocessing the image. On large datasets I have faced this issue numerous times.</p>
<p>What you can do is remove these images as I... | tensorflow|image-processing|keras|deep-learning | 2 |
20,688 | 70,286,537 | reading Excel file getting unicodes | <p>I am reading an excel file with pandas.</p>
<p>When i open the file in microsoft excel then I got the output like this</p>
<p><a href="https://i.stack.imgur.com/jon6h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jon6h.png" alt="enter image description here" /></a></p>
<p>when I see this file in... | <p>Currently I am only able to solve this issue by finding these types of unicodes and then replacing them.</p>
<pre><code>df.replace({r"_x([0-9a-fA-F]{4})_": ""}, regex=True)
</code></pre>
<p>Let me know if someone having better idea.</p> | python|excel|pandas | 1 |
20,689 | 56,401,585 | Parsing deeply nested JSON with pandas json_normalize | <p>I can't seem to extract all the metadata I need from nested json using json_normalize. Refer to JSON below. I'm trying to retrieve title ("Some Book") from the content node but I'm only successful going as deep as content.</p>
<p>For example:</p>
<pre><code>json_normalize(result_data, 'data', ['title', 'key',['gro... | <p>you can use the following package that I made. It will expand every <code>dict</code> that it fill found in the DataFrame.</p>
<pre><code>import flat_table
# I am selecting group dimentions, key, metadata, and title.
df = pd.DataFrame(result_data).iloc[:,1:]
flat_table.normalize(df)
</code></pre>
<p>It will find a... | pandas|python-2.7 | 0 |
20,690 | 56,032,550 | Python 3 - ValueError: Found array with 0 sample(s) (shape=(0, 11)) while a minimum of 1 is required by MinMaxScaler | <p>I'm really having trouble trying to get this project of mine up and running, but I'm remaining resilient and I think I'm close! </p>
<p>I'm trying to customize this project to work with my own dataset:</p>
<p><a href="https://github.com/notadamking/Bitcoin-Trader-RL" rel="noreferrer">https://github.com/notadamking... | <p>I found an answer to this.</p>
<p>I changed the line:</p>
<pre><code>scaled_df = pd.DataFrame(end, columns=self.df.columns)
</code></pre>
<p>...to read:</p>
<pre><code>scaled_df = pd.DataFrame(data=scaled_df, columns=self.df.columns)
</code></pre>
<p>...and then changed:</p>
<pre><code>self.observation_space =... | python|python-3.x|pandas|numpy|scikit-learn | 1 |
20,691 | 64,939,959 | Moving rows to columns through loops (pandas, python) | <p>I am wanting to move year code to columns, and then move the corresponding population to rows in the columns. I think that I have the first steps but I get lost after the what I have listed below.</p>
<pre><code>for index, row in df.iterrows():
cities = row['City']
year = row['Year_code']
df.loc[ind... | <p>You can "pivot" the year code into the columns like so:</p>
<p><code>pivot = df.pivot(index=['City', 'State', 'Area'], columns='Year_code', values='Population')</code></p>
<p>If you then want to go back to the regular 0, 1, 2... index, you can use
<code>pivot = pivot.reset_index()</code></p> | python|pandas|dataframe|loops | 0 |
20,692 | 64,717,985 | Try and give a grouped (by two variables) average, and if not possible give column average in python pandas | <p>I am trying to group by <strong>2</strong> variables and use the grouped average to fill the missing values in a column. Then, if that doesn't work, I want to groupby <strong>1</strong> variable and give the grouped average to fill the missing values of the same column, and if that doesn't work, I want to give the <... | <p>Not the most efficient way around this but because time is pressuring me I ended up doing something like this, which actually does exactly what I wanted it to do:</p>
<pre><code>dict_list_1 = []
for v in dat[features_to_impute]:
comp_mean = env.groupby('company')[v].mean().to_frame()
dict_list_1.append(comp_... | python|pandas|try-catch|pandas-groupby|average | 1 |
20,693 | 64,629,100 | Why is 'key' an unexpected keyword of sort_values() | <p>I am trying to implement the code</p>
<pre><code>sort_order = {
'Documentary':0,
'Film-Noir':1,
'Biography':2,
'History':3,
'War':4,
'News':5,
'Animation':6,
'Musical':7,
'Music':8,
'Drama':9
}
df.sort_values(by=['genre'], key=lambda x: x.map(sort_order))
</code></pre>
<p>But I receive this error:</p>
<pre><code>Ty... | <p>As mentioned in the comments section, <a href="https://pandas.pydata.org/pandas-docs/stable/whatsnew/v1.1.0.html#sorting-with-keys" rel="noreferrer">Sorting with Keys is introduced in version 1.1.0</a>.</p>
<p>You may run the following to update the package (note the <code>-U</code> flag):</p>
<pre><code>python -m p... | python|pandas|dataframe|sorting|typeerror | 5 |
20,694 | 39,615,871 | Function to calculate value from first row in Python Pandas | <p>Is there any function in pandas to simulate excel formula like '=sum($A$1:A10'(for 10th row), i.e. the formula should take rolling data from 1st row.</p>
<p>Pandas rolling function needs a integer value as window argument.</p> | <p>The equivalent of <code>=SUM($A$1:A1)</code> in pandas is <code>.expanding().sum()</code> (requires pandas 0.18.0):</p>
<pre><code>ser = pd.Series([1, 2, 3, 4])
ser
Out[3]:
0 1
1 2
2 3
3 4
dtype: int64
ser.expanding().sum()
Out[4]:
0 1.0
1 3.0
2 6.0
3 10.0
</code></pre>
<p>You can al... | python|pandas|numpy | 2 |
20,695 | 69,463,032 | pandas groupby only aggregating rows that are common between two consecutive fields that are grouped | <p>I am trying to calculate a sum for each <code>date</code> field, however I only want to calculate the sum of IDs that are in both the current and next <code>date</code>, so a <code>rolling</code> comparison of IDs and then a <code>groupby</code> sum. Currently I have to loop over the dataframe which is very slow.</p... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with aggregate <code>sum</code>, compare for not equal with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.di... | python|pandas | 2 |
20,696 | 69,656,396 | Find the max of a list in a Pandas dataframe column | <p>I am reading data from an RSS feed into a dataframe, and am trying to convert words (toddlers,kids,adults) to integers that represent min/max ages. I have gotten as far as replacing the words with numerical strings:</p>
<pre><code>df['audience_max'].head(10)
0 10
1 2,4,3
2 2,4,3
3 10,3
... | <p>You need also convert values to integers from strings after <code>split</code>:</p>
<pre><code>df['max_age'] = df['audience_max'].apply(lambda x: max(map(int, x.split(','))))
#alternative
#df['max_age'] = df['audience_max'].apply(lambda x: max(int(y) for y in x.split(',')))
print (df)
audience_max max_age
0 ... | python|pandas | 2 |
20,697 | 69,436,451 | To Extract Substring from Column of DataFrame | <p><img src="https://i.stack.imgur.com/H2wCg.jpg" alt="Code Error" /></p>
<p>I am trying to extract 4 characters after First,second,third and so on occurance of '/' from Column of Dataframe</p>
<p><img src="https://i.stack.imgur.com/AoClp.jpg" alt="DataFrame" /></p>
<p>Can someone suggest possible code let me know what... | <p>Try with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.findall.html" rel="nofollow noreferrer"><code>str.findall</code></a>:</p>
<pre><code>>>> df["NE Name"].str.findall(r"/([^/]{4})")
0 [01HJ]
1 [01HL, 02HL, 03HL, 10HL]
2 [01HL, 02HL,... | python|pandas | 0 |
20,698 | 69,615,762 | ValueError: Shape of passed values is (20, 1), indices imply (20, 6) | <p>I am trying to get data from tif files, store it in <code>data</code> and create a pandas <code>df0</code></p>
<pre><code>data = []
listOfPages = glob.glob(r"C:/Users/name/*.tif")
for entry in listOfPages:
text = pytesseract.image_to_string(
Image.open(entry), lang="en"
)
... | <p>You just have to stop appending <code>text</code> initially to <code>data</code> as you are doing it at the last of the loop in the list and this creates <code>data</code> as a list of lists with shape(20,6) which you need.</p>
<pre><code>for entry in listOfPages:
text = pytesseract.image_to_string(
... | python|pandas|list|dataframe | 0 |
20,699 | 69,368,758 | Splitting DataFrame rows into multiple based on a condition | <p>I have a Dataframe <code>df1</code> that has a bunch of columns like so:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>val_1</th>
<th>val_2</th>
<th>start</th>
<th>end</th>
<th>val_3</th>
<th>val_4</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>10</td>
<td>70</td>
<td>1/1/20... | <p>Here's a different approach. Note that I've already converted <code>start</code> and <code>end</code> to datetimes, and I didn't bother sorting the resultant DataFrame because I didn't want to assume a specific ordering for your use-case.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
def ... | python|pandas|dataframe | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.