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 |
|---|---|---|---|---|---|---|
356,000 | 58,698,675 | Creating a timestamp from 2 columns | <p>I dont know is this will count as duplicate since maybe is more specific, i've been coding a file reader. This data ends formated like this.</p>
<pre><code>#StartDate StartTime EndDate EndTime ScanDirection Sheath_Press Sheath_Temp Sheath_Avg Sheath_Sdev Sheath_RH ColSamp_Avg ColSamp_Sdev ColSamp_RH Co... | <p>Use <code>to_datetime</code> and <code>to_timedelta</code>:</p>
<pre><code>data['new_StartDate'] = (pd.to_datetime(data['StartDate'], format='%Y%m%d') +
pd.to_timedelta(data['StartTime']))
# similar for `EndDate` and `EndTime`
</code></pre> | python|pandas|dataframe|datetime|timestamp | 2 |
356,001 | 59,009,706 | Can I create a numpy array of dictionary values from an array of dictionary keys? | <p>Say I have a dictionary:</p>
<pre><code>d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
</code></pre>
<p>Given a numpy array** of keys, e.g. <code>['a' 'c' 'e']</code>, is there an easy way to create a numpy array of the corresponding values, e.g. <code>[1 3 5]</code>?</p>
<p>** for reasons of the context I'm using ... | <p>You could do this with a <a href="https://docs.scipy.org/doc/numpy/user/basics.rec.html?highlight=structured%20array#module-numpy.doc.structured_arrays" rel="nofollow noreferrer">structured array</a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow noreferrer"><code>np... | python|arrays|numpy|dictionary | 1 |
356,002 | 58,773,320 | If duplicate, return the corresponding row value in Python Pandas | <p>I am trying to sort a column of excel to show duplicate Zip Codes. If there is a duplicate, I am trying to get pandas to look one column over from the duplicate zipcodes, sum the values, and create a new list with the duplicated/summed values. Currently I am able to create a list of all of the duplicates, but am los... | <p>So a way to get information about duplicates in a pandas dataframe is to use the groupby function. You can group your dataframe by zipcode and count the number of occurrences and at the same time sum the quantity field. </p>
<p>In the code below I've created a simple dataframe of 10 Zipcodes with their respective Q... | python|excel|python-3.x|pandas | 0 |
356,003 | 58,901,664 | Groupby sum by Inspector_ID, and Day in pandas | <p>I have a dataframe as shown below. Which is the distance travelled by two inspector in different day.</p>
<pre><code>Inspector_ID Timestamp Distance
1 2018-07-24 7:31:00 0
1 2018-07-24 7:31:01 2.3
1 2018-07-24 7:33:01 ... | <pre><code> import pandas as pd
from datetime import datetime as dt
df={"Inspector_ID":[1,1,1,1,1,2,2,2,2,2,2] ,"Timestamp" :["2018-07-24 7:31:00" ,"2018-07-24 7:31:01" ,"2018-07-24 7:33:01" ,"2018-07-25 7:32:04" ,"2018-07-25 7:33:06","2018-07-20 7:31:00" ,"2018-07-20 8:36:10" ,"2018-07-20 8:37:09","201... | pandas|datetime|pandas-groupby | 0 |
356,004 | 59,015,860 | Convert strings in numpy array using title attribute | <p>I have an array with city names with different combinations of upper and lower case spellings. The city names need to be converted so that if the city was spelled "NEW YORK" it would become "New York".
I have a working solution, however I was wondering if there is any simpler or more elegant way of doing the same th... | <p>You can make it one liner</p>
<pre><code>cities = [x.title() for x in cities]
</code></pre> | python|numpy | 1 |
356,005 | 58,644,698 | MinMaxScaler + DecisionTree classifier with numerical and categorical data | <p>I would like to know how should I managed the following situation: </p>
<p>I have a dataset which I need to analyze. It is labeled data and I need to perform over it a classification task. Some features are numerical and others are categorical (non-ordinal), and my problem is I don't know how can I handle the categ... | <p>I don't have enough reputation to comment, but note that decision tree classifiers don't require their input to be scaled. So if you're using a decision tree classifier, just use the features as they appear.</p>
<p>If you're using a method that requires feature scaling, then you should probably do one-hot-encoding ... | python|pandas|decision-tree | 0 |
356,006 | 58,863,165 | How do I get a number for each value in my list? | <p>New to Python and programming in general. I'm trying to create a program that will pull device counts from Cisco UCM. Currently, I can get the program to print me out a list of models from CUCM, but ultimately I would like to see how many of each model occurs. For example, if the CUCM server has 5 8845's and 3 8865'... | <p>It doesn't look like you need Pandas here, plain old Python can write a helper like <code>counts</code> below —</p>
<pre><code>from collections import defaultdict
def counts(xs):
counts = defaultdict(int)
for x in xs:
counts[x] += 1
return counts.items()
</code></pre>
<p>And then you can use ... | python|pandas|list|cisco|cucm | 1 |
356,007 | 59,029,722 | Calculte kurtosis and skewness using for loop | <p>i'm trying to calculteskewness and kurtosis for different fields. I want to get in the end table with each field name. the kurtosis and the skewness.
for that I have written the next code:</p>
<pre><code>for i in data_dis.columns:
print('skewness',i,':',i.skew())
print('Kurtosis',i,':',i.kurtosis())
</code>... | <p>You don't need a for loop, you can just calculate <em>skewness</em> and <em>kurtosis</em> for each numerical column using the dataframe methods:</p>
<pre><code>data_dis.skew()
data_dis.kurtosis()
</code></pre>
<p>They both return a Pandas Series, with indexes column names and as values the column skewness and colu... | python|pandas|distribution|kurtosis | 2 |
356,008 | 58,843,149 | How do I replace a row value with the previous cell value in pandas dataframe? | <p>I am trying to replace values in rows with the previous row in pandas dataframe.
I tried using: </p>
<pre><code>p2['top3_today']=p2['top3_today'].shift()
</code></pre>
<p>AND </p>
<pre><code>p2['top3_today']=p2['top3_today'].shift(-1)
</code></pre>
<p>But this does not work. Kindly help!</p> | <pre><code>p2['top3_today'].shift(1, axis = 0)
</code></pre>
<p>it will replace each row with the previous value, except for the first row which will be "NaN".</p>
<p>IF you do:</p>
<pre><code>p2['top3_today'].shift(-1, axis = 0 )
</code></pre>
<p>it will still replace each value in a row with its previous except f... | python|pandas|dataframe | 0 |
356,009 | 58,610,048 | indian rupee symbol UnicodeEncodeError while uploading file to s3 using pandas | <p>I have scraped some data from a website for my assignment. It consists of Indian rupee character - "₹". The data when I'm trying to save into CSV file in utf-8 characters on local machine using pandas, it is saving effortlessly. The same file, I have changed the delimiters and tried to save the file to s3 using pand... | <p>The error gives an evidence that the code tries to encode the <code>filename_str2.csv</code> file in cp1252. From your stack trace:</p>
<p>...<br/>File "C:\local_path\spiders\Pduct_Scrape.py", line 430, in closed<br/>
search_df.to_csv('s3://my-bucket/folder_path/ <strong>filename_str2.csv</strong> '... | python|python-3.x|pandas|amazon-s3 | 0 |
356,010 | 58,662,301 | Got a `TypeError` when using `np.unique` on a list of objects containing a `datetime` (Python / Numpy) | <p>I am trying to use <code>np.setdiff1d</code> between 2 python objects, but couldn't manage. I found out that I can't use <code>np.union</code> on a list of objects containing a datetime!</p>
<p>To reproduce the error :</p>
<pre><code>import numpy as np
from datetime import datetime
d = datetime.now()
a = [(1, d),... | <p>Here's the reason: <code>numpy.unique</code> will flatten the array first. From the documentation: </p>
<blockquote>
<p>Input array. Unless axis is specified, this will be flattened if it is not already 1-D.</p>
</blockquote>
<p>So, you have to think along which axis you'd like the elements to be unique (for Num... | python|numpy|datetime | 0 |
356,011 | 58,609,931 | Pandas Multiple DataFrames from other DataFrames | <p>Suppose I have a base "test" dataframe of varying length, which I am constructing based off of a slider date selector. </p>
<pre><code> seasons
test
2018-02-19 Winter
2018-02-20 Winter
2018-02-21 Winter
2018-02-22 Winter
... ...
2019-06-25 Summer
2019-06-26 Summer
2019-06-27 Summer
2019-06-28 ... | <p>Building off of @Mayeul sgc's <a href="https://stackoverflow.com/questions/58609931/pandas-multiple-dataframes-from-other-dataframes#comment103531784_58609931">comment</a> for a multiple case scenario and for the benefit of anyone looking for an answer to the same question:
you can do the following:</p>
<pre><code... | python|pandas|dataframe | 1 |
356,012 | 58,993,231 | Convert a str(numpy array) representaion to a numpy array - Python | <p>Let's say I have a numpy array <code>a = numpy.array([1,2,3,4])</code>. Now
<code>str(a)</code> will give me <code>"[1 2 3 4]"</code>. How do I convert the string <code>"[1 2 3 4]"</code> back to a <code>numpy.array([1,2,3,4])</code>?</p> | <p>Try <code>numpy.array([int(v) for v in your_str[1:-1].split()])</code></p> | python|numpy | 2 |
356,013 | 58,679,355 | Generate data for dates based on a constraint | <p>I have a dataframe df1 having column for date_1 with values from 01/09/2019 to 30/09/2019. i.e. 30 values and respective count. </p>
<p><strong>DF1</strong></p>
<pre><code> date_1 count
01/09/2019 5
02/09/2019 4
03/09/2019 5
04/09/2019 6
05/09/2019 7
06/09/2019 8
07/09/2019... | <p>To solve your problem you can create a customized function that returns random date in specified format between <code>date-30</code> and <code>date-1</code> and apply this function to repeated dates of your new Dataframe:</p>
<pre><code>import pandas as pd
import random
def get_randomized_str_date(input_str_date):... | python|pandas|numpy | 1 |
356,014 | 58,810,204 | Filter on only two dates in pandas | <p>I have some <code>df</code> with dates as the index. I need to aggregate over unique pair of dates. Thus, basically, I need to choose only two dates in the <code>df</code>, coming from the <code>itertools.combinations()</code> function. Notice I don't need the <em>range</em> but I need to filter for the two exact da... | <p>Ok, so, I found a solution. I don't think it's optimal, but it does work.</p>
<pre><code>Dtest = ['2019-09-23', '2019-09-24']
for pair in itertools.combinations(Dtest, 2):
tframe = pd.concat([df[pair[0]], df[pair[1]]])
</code></pre> | python|pandas|datetime | 0 |
356,015 | 58,788,054 | Fast alternative for numpy.median.reduceat | <p>Relating to <a href="https://stackoverflow.com/a/51029521/2431885">this answer</a>, is there a fast way to compute medians over an array that has groups with an <strong><em>unequal</em></strong> number of elements?</p>
<p>E.g.:</p>
<pre><code>data = [1.00, 1.05, 1.30, 1.20, 1.06, 1.54, 1.33, 1.87, 1.67, ... ]
ind... | <p>Sometimes you need to write non-idiomatic numpy code if you <em>really</em> want to speed up your calculation which you can't do with native numpy.</p>
<p><a href="https://numba.pydata.org/" rel="nofollow noreferrer"><code>numba</code></a> compiles your python code to low-level C. Since a lot of numpy itself is usu... | python|performance|numpy|median|numpy-ufunc | 7 |
356,016 | 58,947,482 | Difference between xx[:,9] and xx[:][9]? | <p>I would like to understand the difference between the notations below.</p>
<pre><code>print(np.min(xx[:,9]))
print(np.min(xx[:][9]))
</code></pre>
<pre><code>0.015971377798342325
-0.7342680230504756
</code></pre>
<p>Why the results are different?</p> | <p>They are completely different.
Consider this example : </p>
<pre><code>>>> arr = numpy.array([[1,2,3],[1,2,3],[1,2,3]])
>>> arr[:,1]
array([2,2,2])
</code></pre>
<p>Here you are slicing in 2 dimensions, you are selection 2nd column of all the three rows. For our reference let us call this as <str... | python|numpy | 1 |
356,017 | 58,745,717 | Val Loss starts close to zero and stays - Train loss normal | <p>I am trying to optimize my LSTM regression based forecasting model. Therefore i put a loop in my code to find the best learning rate. But i think something is wrong. The validation loss it starts close to zero and remains there (compare picture). <a href="https://i.stack.imgur.com/ylexN.png" rel="nofollow noreferre... | <p>You have very little data for the purpose of deep learning.</p>
<p>According to the graph, it is very likely that you are overfitting to the validation set. There are other cases in which the validation loss can be smaller than the training loss, considering the cases in which the dropout is not enabled when testin... | python|validation|tensorflow|keras|loss-function | 0 |
356,018 | 58,954,542 | Python adds only first entry to excel file | <p>I have a list of urls which im parsing for a contact section on that side. So far so good.
After i found the contact path i wanna write the url + the parsed path to my excel file.
The problem is: it only writes the last value. Im sure im failing the loop but i cant find the mistake.</p>
<p>I am new at coding please... | <p>You are overwriting data in loop so last item is saved. You can modify your code according to following sample. </p>
<pre><code>finalFormular = []
for link in [1, 2, 3, 4]:
finalFormular.append(link)
if finalFormular:
data = pd.DataFrame({'Formulare': finalFormular})
datatoexcel = pd.ExcelWriter(os.pat... | python|pandas|xlsxwriter | 1 |
356,019 | 58,714,357 | Python NLP - Sklearn - text classifier, unigrams and bigrams the same for both negative and positive labels | <p>I'm trying to create a text classifier to determine whether an abstract indicates an access to care research project. I am importing from a dataset that has two fields: Abstract and Accessclass. Abstract is a 500 word description about the project and Accessclass is 0 for not access-related and 1 for access-relate... | <p>I think the problem in your code is setting <code>min_df</code> with a big number like <code>4</code> on this small dataset. According to your data that you have posted, the most common words are stopwords that will be removed after using <code>TfidfVectorizer</code>. Here they are:</p>
<pre><code>to : 19
and : 1... | python|scikit-learn|nlp|text-classification|sklearn-pandas | 1 |
356,020 | 58,815,986 | Unique values from multipel column in pandas | <pre><code>distinct_values = df.col_name.unique().compute()
</code></pre>
<p>But what if I don't know the names of columns. </p> | <p>You can try this,</p>
<pre class="lang-py prettyprint-override"><code>>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1, 2, 3], 'b': [2, 3, 5]})
>>> d = dict()
>>> d['any_column_name'] = pd.unique(df.values.ravel('K'))
>>> d
{'any_column_name': array([1, 2, 3, 5])}
... | python|python-3.x|pandas | 1 |
356,021 | 58,684,526 | Unexpected Python KeyError | <p>I have loaded a CSV file into a Pandas dataframe:</p>
<pre><code>import pandas as pd
Name ID Sex M_Status DaysOff
Joe 3 M S 1
NaN NaN NaN NaN 2
NaN NaN NaN NaN 3
df = pd.read_csv('People.csv')
</code></pre>
<p>This data will th... | <p>Just a hunch, but your error message suggests that you are trying to access your dataframe column with the key <code>days_off</code>, when it should be <code>DaysOff</code>. I don't see any place in the code you provided where this happens, but I would double-check your source code file to make sure that you are usi... | python|pandas|csv|dataframe|keyerror | 1 |
356,022 | 70,274,440 | What's the difference between torch.mean and torch.nn.avg_pool? | <p>Taking a tensor with shape [4,8,12] as an example, what's the difference between the two lines:</p>
<pre><code>torch.mean(x, dim=2)
torch.nn.functional.avg_pool1d(x, kernel_size=12)
</code></pre> | <p>With the very example you provided the result is the same, but only because you specified <code>dim=2</code> and <code>kernel_size</code> equal to the dimensionality of the third (index 2) dimension.
But in principle, you are applying two different functions, that sometimes just happen to collide with specific choic... | pytorch | 1 |
356,023 | 70,214,639 | Pandas merge not working after using StringIO | <p>I need to convert a string into a pandas DataFrame to further merge it with another DataFrame, unfortunately the merge is not working.</p>
<pre><code>str_data = StringIO("""col1;col2
one;apple
two;lemon""")
df = pd.read_csv(str_data, sep =";")
df2 = pd.DataFrame([['one', 10]... | <p>For me working well:</p>
<pre><code>from io import StringIO
str_data = StringIO("""col1;col2
one;apple
two;lemon""")
df = pd.read_csv(str_data, sep =";")
df2 = pd.DataFrame([['one', 10], ['two', 15]], columns = ['col1', 'col3'])
df=df.merge(df2, how='left', on='col1')
prin... | python|pandas|merge|stringio | 1 |
356,024 | 70,286,955 | Based on some rules, how to expand data in Pandas? | <p>Please forgive my English. I hope I can say clearly.</p>
<p>Assume we have this data:</p>
<pre><code>>>> data = {'Span':[3,3.5], 'Low':[6.2,5.16], 'Medium':[4.93,4.1], 'High':[3.68,3.07], 'VeryHigh':[2.94,2.45], 'ExtraHigh':[2.48,2.06], '0.9':[4.9,3.61], '1.5':[3.23,2.38], '2':[2.51,1.85]}
>>> df =... | <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> for unpivot and then sorting by indices, create <code>Snow</code> column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric... | pandas|dataframe|serialization|pandas-groupby | 1 |
356,025 | 70,223,518 | ERROR: torch-1.10.0+cu113-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform | <p>I tried to install pytorch from site using,</p>
<pre><code>pip3 install torch==1.10.0+cu113 torchvision==0.11.1+cu113 torchaudio===0.10.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html
</code></pre>
<p>That didn't work, so I downloaded it from
'https://download.pytorch.org/whl/cu113/torch_stable.h... | <p>pip3 install torch-1.10.0+cu113-cp36-cp36m-win_amd64.whl</p>
<p>You need to ensure you have CPython 3.6 otherwise you may get an error saying the file is not a supported wheel on this platform. Also, this package is compiled for 64bit Windows, so you need to be on that architecture.</p>
<p>More on the naming convent... | pytorch | 0 |
356,026 | 70,314,058 | How to implement a diagonal data for a linear layer in pytorch | <p>I would like to have a network in pytorch that only scale the data.</p>
<p>The mathematical notations for my request is:
<a href="https://i.stack.imgur.com/CBtmO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CBtmO.png" alt="" /></a></p>
<p>which means that if my input is <code>[1, 2]</code> and ... | <p>It seems like an apparent constraint here is the fact that <code>self.linear_layer</code> needs to be a squared matrix. You can use the diagonal matrix <code>self.mask</code> to zero out all non-diagonal elements in the forward pass:</p>
<pre><code>class ScalingNetwork(nn.Module):
def __init__(self, in_features)... | python|deep-learning|neural-network|pytorch | 1 |
356,027 | 70,109,826 | Add new columns to existing dataframe with loops and conditions | <p>I have two dataframes. One is excel file and another will be created by user inputs. Based on the user inputs and conditions on columns in the 1st dataframe, new columns should be added to 1st dataframe with calculations. I have wrote the code, which was successful for the test data, but the results are not coming t... | <p>Finally I found the proper code. Thank you for your replies.</p>
<pre><code>for a,b in zip(month_data.month_list, month_data.month_range):
contr_calc_new[a] = np.where(contr_calc_new['Join Date'].dt.strftime('%Y-%m') == b.date().strftime('%Y-%m'),0,((contr_calc_new['Present Basic'] + (contr_calc_new['Present Bas... | python|pandas|dataframe|loops|append | 0 |
356,028 | 70,045,405 | Fill NaN in second level of multi indexed pandas data frame | <p>I do have a multiindexed pandas data frame with sensor data like this:</p>
<pre><code> high1 low1 high2 low2 offset
timestamp channel
2021-01-01 A 966.6100 965.0300 967.7900 965.0300 27.307721
B 1.4105 ... | <p>The short answer is that you are probably looking for</p>
<pre class="lang-py prettyprint-override"><code>df.loc[(slice(None), 'B'), :] = df.loc[(slice(None), 'B'), :].fillna(method='ffill')
</code></pre>
<p>The long answer is as follows.</p>
<p>In a lot of cases when Pandas returns a copy of the original dataset it... | python|pandas|dataframe|multi-index | 2 |
356,029 | 70,303,222 | Extract values in dataframe where index name equals to column name | <p>Lets say I have the following data set:</p>
<pre><code>import numpy as np
import pandas as pd
d = {'column1': ['a', 'b', 'c'], 'a': [10, 8, 6], 'a1': [1, 2, 3], 'b': [4, 2, 6], 'b1': [1, 4, 8], 'c': [2, 6, 8], 'c1': [2, 1, 8] }
data_frame = pd.DataFrame(data=d).set_index('column1')
</code></pre>
<p>What I want to... | <p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a>, comapre indices by columns names without numbers and for not equal aggregate <code>sum</code>:</p>
<pre><code>df = data_frame.melt(ignore_index=False... | python|pandas | 3 |
356,030 | 70,075,110 | Sort string values delimited by commas in a column using pandas | <p>I have this dataframe, and I'm looking a pythonic way using Pandas to sort these values.
Column 2 is a string.</p>
<pre><code>C1 C2
0 b,g,f
1 a,f,c
2 f,e,a,c
</code></pre>
<p>The Output should look like:</p>
<pre><code>C1 C2
0 b,f,g
1 a,c,f
2 a,c,e,f
</code></pre> | <pre><code>import pandas as pd
data = [
{
"C1":0,
"C2":"b,g,f"
},
{
"C1":1,
"C2":"c,b,a"
},
{
"C1":2,
"C2":"f,e,a,c"
}
]
df = pd.DataFrame.from_dict(data)
d... | python|pandas|dataframe|sorting|delimited | 0 |
356,031 | 70,154,110 | how to get the part of the day from a given 24 hour time format in pandas and python | <p>Hi I have dataset in which a col value looks like 08:25:00 I want to the resultant value as morning.</p>
<pre><code>10:36:00 - Morning
16:00:00 - afternoon
17:00:00 - afternoon
19:00:00 -evening
</code></pre>
<p>I tried with this below steps but for few rows I am getting Nan values and incorrect result</p>
<pre>... | <p>Assuming 'time' the initial column as string type, you could split the hours, and use <code>pandas.cut</code>:</p>
<pre><code>df = pd.DataFrame({'time': ['10:36:00', '16:00:00', '17:00:00', '19:00:00']})
bns=[0,4,8,12,16,20,24]
part_days=['Late Night','Early Morning','Morning','Noon','Evening','Night']
s = df['time... | python|pandas | 0 |
356,032 | 70,040,547 | Python function to select all municipalities | <p>So I want to import some data from the Dutch databank CBS. I need to select all the municipalities. They all have a code that starts with GM and then 4 numbers.</p>
<p>Do I have to type them all in? Or is there a quicker way to get them all in in one time.</p>
<pre><code># Downloaden van selectie van data
data = pd.... | <p>I'm not sure how <code>cbsodata.get_data</code> works but it seems to me that you could generate <code>filters</code>.</p>
<pre class="lang-py prettyprint-override"><code>filters = "RegioS eq " + ", ".join(["'GM" + str(i).zfill(4) + "'" for i in range(3, 8)])
</code></pre>
<p>... | python|pandas | 1 |
356,033 | 70,301,636 | AttributeError: 'Flatten' object has no attribute 'shape' | <p>I am new to TensorFlow and was trying to implement a CNN model using <code>tf.keras.layers</code> API. This is the code that I am trying to implement.</p>
<pre><code>def convolutional_model(input_shape):
input_img = tf.keras.Input(shape=input_shape)
Z1 = tf.keras.layers.Conv2D(filters = 16 , kernel_size= (4,... | <p>The <a href="https://keras.io/guides/functional_api/" rel="nofollow noreferrer">Keras functional API</a> is designed so you pass in the previous layers of the model as input to the next layer. You didn't really do that for most of the layers you've defined, and instead made them standalone layers that aren't connect... | python|python-3.x|tensorflow|keras | 1 |
356,034 | 70,124,485 | Join pandas Dataframe and Series Without NaN values | <p>I want to join the pandas data frame and series, to understand better i am taking the following example, the real scenario is having multiple columns
any suggestions would be appreciable</p>
<pre><code>import pandas as pd
data = [[1,2],[2,3],[3,4]]
df1 = pd.DataFrame(data, columns=['A',"B"])
print(df1)
di... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>DataFrame.assign</code></a>, but <code>df2</code> cannot be Series, because column <code>name</code>:</p>
<pre><code>df = df1.assign(**df2.loc[0])
print (df)
A B C
0 1 2 5
1 2... | python|pandas|dataframe | 1 |
356,035 | 70,378,406 | Create surrogate rows in Pandas based on missing condition | <p>Given a df as shown below, and assume the value under column <code>lapse</code> is unique and range from 0 to 18. However, some of the values is not available within this range. For this example, the value <code>0</code>,<code>16</code> and <code>18</code> is missing.</p>
<pre><code> lapse (a, i) (a, j) (... | <p>You can also use:</p>
<pre><code>df.set_index('lapse', inplace=True)
df = df.reindex(np.arange(0,20,2)).reset_index()
</code></pre>
<p><code>OUTPUT</code></p>
<pre><code> lapse (a, i) (a, j) (b, k) c
0 0 NaN NaN NaN NaN
1 2 0.423655 0.645894 0.437587 0.891773
... | python|pandas|numpy | 3 |
356,036 | 70,110,083 | How to count values in one dataframe matching the key from another? | <p>I want to count values in one dataframe matching the key from another.</p>
<p><strong>What do I have:</strong></p>
<p><code>df_a</code>:</p>
<pre><code>df_a = pd.DataFrame(data = {'keys':['key1', 'key2', 'key3'], 'total':[0, 0, 0], '>5':''})
df_a
</code></pre>
<p>output:</p>
<pre><code> keys total >5
0... | <p>Create new column by compare greater like <code>5</code>, then aggregate <code>size</code> and <code>mean</code> and join to <code>df_a</code>:</p>
<pre><code>df = (df_b.assign(tmp = df_b['value'].gt(5))
.groupby('keys')
.agg(**{'total':('tmp','size'),'>5':('tmp','mean')}))
print (df)
to... | python|pandas | 1 |
356,037 | 70,353,605 | How to load huge time series windows dataset without memory errors? | <p>I want to convert a typical time series dataset of about 1 million lines into 100-item windows with 50% overlap. Note that it's a multivariate one, so for example given 8 features and 1000 windows with 100 items the final shape would be <code>(1000, 100, 8)</code> replacing <code>(n_samples, n_timesteps, n_features)... | <p>I think you are looking for <code>tf.data.Dataset</code>. I'm working on a million rows dataset, and the following code runs well for me:</p>
<pre><code>convert = tf.data.TextLineDataset("path_to_file.txt")
dataset = tf.data.Dataset.zip(convert)
</code></pre>
<p>Now you have initialized your dataset, but f... | numpy|tensorflow|pytorch | 0 |
356,038 | 70,148,704 | Pair each value in a row with other rows in pandas dataframe | <p>I have a dataframe of 500 rows sorted as follows:</p>
<pre><code>Col1 Val1
asd 0.27
pqer 0.37
psdf 0.54
</code></pre>
<p>I am trying to pair each value of <code>Col1</code> with another row in <code>Col1</code> who have higher <code>Val1</code> to get the following list:</p>
<pre><code>[['asd', 'pqer'],... | <p>Try self merge and filtering:</p>
<pre><code>df.merge(df, how='cross')\
.query('Val1_x < Val1_y')[['Col1_x','Col1_y']]\
.to_numpy().tolist()
</code></pre>
<p>Output:</p>
<pre><code>[['asd', 'pqer'], ['asd', 'psdf'], ['pqer', 'psdf']]
</code></pre> | pandas|dataframe|python-3.8 | 2 |
356,039 | 70,314,285 | Input shape for a RNN in keras | <p>My data set has the following shapes:</p>
<pre><code>y_train.shape,y_val.shape
((265, 2), (10, 2))
x_train.shape, x_val.shape
((265, 4), (10, 4))
</code></pre>
<p>I'm trying to use a simple RNN model</p>
<pre><code>model=models.Sequential([layers.SimpleRNN(20,input_shape=(None,4),return_sequences=True),
... | <p>First thing input should be 3D with shape <code>[batch, timesteps, feature]</code>.</p>
<p><code>x_train</code> and <code>x_val</code> do not follow this rule. You can easily expand their dims by:</p>
<pre><code>x_train = np.expand_dims(x_train, axis = -1) # (265, 4, 1)
x_val= np.expand_dims(x_val, axis = -1) # (10,... | tensorflow|recurrent-neural-network|tf.keras | 0 |
356,040 | 70,223,572 | disable default na parsing in pandas read_csv only for specific column | <p>I need to read a csv file as pandas dataframe but keep certain column exactly as it is without filling in NaN.</p>
<pre class="lang-py prettyprint-override"><code>from io import StringIO
import pandas as pd
main_ts_str = """key,dt,value
5013,2020-06-19,NULL
NA,2020-06-18,25.5
"""
df = ... | <p>You can use the <code>converters</code> parameter from <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> and pass a dictionary for converting values only in certain columns (<code>key</code> column in this specific example).</p>
<pre class... | python|pandas|dataframe | 1 |
356,041 | 70,300,576 | How to access loss at each epoch from Pytorch Lighting? | <p>I'm using Pytorch Lighting and Tensorboard as PyTorch Forecasting library is build using them. I want to create my own loss curves via matplotlib and don't want to use Tensorboard.</p>
<p>It is possible to access metrics at each epoch via a method? Validation Loss, Training Loss etc?</p>
<p>My code is below:</p>
<pr... | <p>My recommendation is that you:</p>
<ol>
<li>Create a csv logger:</li>
</ol>
<pre class="lang-py prettyprint-override"><code>from pytorch_lightning.loggers import CSVLogger
csv_logger = CSVLogger(
save_dir=str'./',
name='csv_file'
)
</code></pre>
<ol start="2">
<li>Pass it to your trainer</li>
</ol>
<pre cla... | python|tensorboard|pytorch-lightning | 0 |
356,042 | 70,027,498 | How to add outliers as separate colored markers to a line plot | <pre><code>val time
5.6 2021-11-18 03:00:00
2.034 2021-11-18 05:00:00
1.171 2021-11-18 07:00:00
3.023 2021-11-18 09:00:00
4.202 2021-11-18 16:00:00
1.202 2021-11-18 17:00:00
5.202 2021-11-18 18:00:00
7.202 2021-11-18 19:00:00
2.202 2021-11-18 20:00:00
12.202 2021-11-18 21:00:00
1.202 ... | <ul>
<li>The easiest solution is to use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer">Boolean indexing</a> to create a separate dataframe for values greater then 5, and then plot them as a scatter plot with <a href="https://pandas.pydata.org/d... | python|pandas|matplotlib|time-series|scatter-plot | 2 |
356,043 | 70,287,472 | Unable to convert tensorflow Mask-Rcnn to IR with Open Vino toolkit | <pre><code>python mo_tf.py
--saved_model_dir C:\DATASETS\mask50000\exports\saved_model
--output_dir C:\DATASETS\mask50000
--reverse_input_channels
--tensorflow_custom_operations_config extensions\front\tf\mask_rcnn_support_api_v2.0.json
--tensorflow_object_detection_api_pipeline_config C:\DATASETS\mask50000\exports... | <p>OpenVINO 2020.4 is not compatible with TensorFlow 2. Support for TF 2.0 Object Detection API models was fully enabled only in OpenVINO 2021.3.</p>
<p>I’ve successfully converted the model <a href="http://download.tensorflow.org/models/object_detection/tf2/20200711/mask_rcnn_inception_resnet_v2_1024x1024_coco17_gpu-8... | tensorflow|tensorflow2.0|faster-rcnn|openvino | 0 |
356,044 | 70,258,641 | Adding a vertical line to a time series plot in pandas df | <p>I used the answer to this question to try and add a vertical line to my time series plot: <a href="https://stackoverflow.com/questions/19213789/how-do-you-plot-a-vertical-line-on-a-time-series-plot-in-pandas">How do you plot a vertical line on a time series plot in Pandas?</a></p>
<p>This is my code:</p>
<pre><code>... | <p>I assume that pandas does not set the axis format to date time, but converts the date-time values to number and changes the tick labels. Explicitly creating the axis and setting the correct format works.</p>
<p>Following this <a href="https://stackoverflow.com/questions/32972371/how-to-show-date-and-time-on-x-axis-i... | python|pandas|plot|time-series | 1 |
356,045 | 70,293,723 | How do I make a simple, multi-level Sankey diagram with Plotly? | <p>I have a DataFrame like this that I'm trying to describe with a Sankey diagram:</p>
<pre><code>import pandas as pd
pd.DataFrame({
'animal': ['dog', 'cat', 'cat', 'dog', 'cat'],
'sex': ['male', 'female', 'female', 'male', 'male'],
'status': ['wild', 'domesticated', 'domesticated', 'wild', 'domesticated']... | <p>You can create with Plotly a Sankey diagram in the following way:</p>
<pre><code>import pandas as pd
import plotly.graph_objects as go
label_list = ['cat', 'dog', 'domesticated', 'female', 'male', 'wild']
# cat: 0, dog: 1, domesticated: 2, female: 3, male: 4, wild: 5
source = [0, 0, 1, 3, 4, 4]
target = [3, 4, 4, 2... | python|pandas|plotly|plotly-python|sankey-diagram | 2 |
356,046 | 70,101,080 | Pandas Group Columns by Value of 1 and Sort By Frequency | <p>I have to take this dataframe:</p>
<pre><code>d = {'Apple': [0,0,1,0,1,0], 'Aurora': [0,0,0,0,0,1], 'Barn': [0,1,1,0,0,0]}
df = pd.DataFrame(data=d)
Apple Aurora Barn
0 0 0 0
1 0 0 1
2 1 0 1
3 0 0 0
4 1 0 0
5 0 1 0
</code></pre>
<p>And count the frequency of the number one in e... | <p>If I understand correctly, you could do simply this:</p>
<pre><code>freq = df.mean()
</code></pre>
<p>Output:</p>
<pre><code>>>> freq
Apple 0.333333
Aurora 0.166667
Barn 0.333333
dtype: float64
</code></pre> | pandas|dataframe|count|pandas-groupby | 2 |
356,047 | 70,159,108 | List to data frame in python | <p>I'm trying to grab transaction data from plaid and input it into a data frame with clean columns. The "before" format is a list as excerpted below.</p>
<p>My goal is that the "after" format is a data frame where there is a column for each name in the list (e.g., "account_id" or "am... | <p>In this case, I would use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer">DataFrame constructor</a>, in the list-of-records format.</p>
<p>Example:</p>
<pre><code>import datetime
import pandas as pd
transaction = {'account_id': 'nKllGzvJQeIpZwvxlv1Mhw98Zdo5... | python-3.x|pandas | 0 |
356,048 | 70,354,257 | Block to block operations between 2 dask arrays | <p>Good day friends, I have a question about <code>map_blocks()</code>. I'm trying something simple, I want to take the dot product between columns (the blocks) of 2 arrays like so:</p>
<pre class="lang-py prettyprint-override"><code> x=da.random.random((100,5), chunks=(100,1))
y=da.random.random((100,5), chunks... | <p>For future reference: this question was resolved in Slack, <a href="https://dask.slack.com/archives/C02282J3Q6Q/p1639506482143700" rel="nofollow noreferrer">https://dask.slack.com/archives/C02282J3Q6Q/p1639506482143700</a></p>
<p>One way to resolve this (as per Slack) is to use <code>np.squeeze</code> to make sure t... | python|numpy|dask | 1 |
356,049 | 70,094,565 | Is there a way of unnesting a column with a list of dictionaries into a pandas Dataframe | <p>This is how my data looks like. I tried everything from turning into a list then into a dataframe but no use.</p>
<pre><code>["[[{'uuid': '3cb5da6c-6db2-4893-9ebb-39443a7c83be', 'answers': 'Vibinators', 'votes': '74'}, {'uuid': '564b3357-df5f-4543-bd07-fa0c3c9401de', 'answers': 'I AM’s', 'votes': '139'}]]"... | <p>solution:</p>
<pre><code>import ast
data = ["[[{'uuid': '3cb5da6c-6db2-4893-9ebb-39443a7c83be', 'answers': 'Vibinators', 'votes': '74'}, {'uuid': '564b3357-df5f-4543-bd07-fa0c3c9401de', 'answers': 'I AM’s', 'votes': '139'}]]"]
df = pd.DataFrame(ast.literal_eval(data[0])[0])
</code></pre>
<p>df:</p>
<pre><c... | python|pandas|dataframe | 0 |
356,050 | 70,276,224 | If condition is True, output a txt file to directory path with a message | <p>I am looking to output a text file with a certain message to a directory path if the below results is a 'True'.</p>
<pre><code>df['Fraud Account'].isnull().values.any()
</code></pre>
<p>Is there a way to do this in Jupyter notebook?</p>
<p>Thank you!</p> | <p>I'm not 100% sure what you mean, but reading literally your question I think the answer would be sth like that:</p>
<pre><code>if df['Fraud Account'].isnull().values.any():
open("my_file.txt", "wt").write("My message")
</code></pre>
<p>Contents of file would be replaced. If you want... | python|pandas|jupyter | 1 |
356,051 | 70,141,706 | Backward loop in Python | <p>I need to loop backwards from i=n-2 to i = 0 to code this math formula:</p>
<p><img src="https://i.stack.imgur.com/POU3j.png" alt="math formula" /></p>
<pre><code>for i in range(n-2,0):
X[i] = Y[i]
for m in range(i+1,n):
X[i] = X[i] - T[i,m] * X[m]
</code></pre>
<p>It doesn't work, what am I doing w... | <p>if you want to loop backward you can use the for loop like following</p>
<pre><code>range(start, end, step)
</code></pre>
<p>the step is 1 by default. in your case, you have to specify the decrement in order the loop the work.</p> | python|numpy|for-loop|math | 1 |
356,052 | 70,067,291 | How to overlay multiple images onto certain original images using python | <p>I am trying to create a program in which I should be able to overlay one image over another base image using python and opencv and store the output image in an other folder . I am using opencv to achieve this however the code I have written is not giving the desired result.</p>
<pre><code>import cv2
from os import l... | <p>There are two issues in the following line:</p>
<pre><code>name = 'C:\Flare\flare_img'+str(fn[n])
</code></pre>
<ol>
<li>In Python, special characters in strings are escaped with backslashes. Some examples are <code>\n</code> (newline), <code>\t</code> (tab), <code>\f</code> (form feed), etc. In your case, the <cod... | python|numpy|opencv|file-handling | 1 |
356,053 | 70,242,744 | Getting closest observations using Euclidean distance | <p>I have a data frame that looks like this</p>
<pre><code>ID PC1 PC2
12 0.355 0.362
24 0.577 0.425
15 0.257 0.486
06 0.585 0.254
34 0.367 0.533
</code></pre>
<p>I want to use Euclidean distance on PC1 and PC2 to get the closest data points.</p>
<p>So my desired out is that when I put in <code>ID = 15</code> in pytho... | <p>If you need to to query many points, you may want to construct a <code>KDTree</code> first. Here is an example using <code>scipy</code>:</p>
<pre><code>from scipy import spatial
# WARNING: This assumes that all points in the DataFrame are distinct.
# construct a KDTree given a set of points
tree = spatial.cKDTree(... | python|pandas|dataframe | 3 |
356,054 | 70,364,203 | How to extract specific columns in python and render the results in another file | <p>I'm a beginner in python, and I need your help in a issue, I have
126 files that contains more than 12 columns and more than 1000 lines, I want to create a file which contains column 1 and 2 of all files.</p>
<p>so for example if I have the file 1 which contains 5 columns from A to E</p>
<pre><code>A B C ... | <p>simply merge subsets of the two dataframes on 'A'</p>
<pre><code>df[['A','B']].merge(df2[['A','B']], on=['A'])
</code></pre>
<p>The two similar-named columns (B) will have to be renamed, since you can't have two columns with the same name. Default is (“_x”, “_y”).</p>
<p>You can choose your own suffixes by adding <c... | python|pandas|dataframe|file|multiple-columns | 1 |
356,055 | 70,147,517 | Finding the common elements in 2 columns which is present in a single dataframe | <p>[image of a data frame]</p>
<p><img src="https://i.stack.imgur.com/0aUNI.png" alt="1" /></p>
<p>I want to find the common elements which is present in top30 and played games column</p>
<p>i have used the below code , but it does not give me the right output</p>
<pre><code>output : {f, 1, , ,, a, s, t, r, g, 2, ', y,... | <p>You can use <code>apply</code> to check the <code>set</code> intersection:</p>
<pre><code>df['result'] = df.apply(lambda r: set(r['games']).intersection(r['played_games']), axis=1)
</code></pre>
<p>Example:</p>
<pre><code> games played_games result
0 [abc, def, ghi] [def, abc] {abc, def}
</code>... | python|pandas|recommendation-engine | 0 |
356,056 | 70,127,107 | Difficulties in removing characters and white space to tokenize text via Spacy | <p>I'm testing the Spacy library, but I'm having trouble cleaning up the sentences (ie removing special characters; punctuation; patterns like [Verse], [Chorus], \n ...) before working with the library.</p>
<p>I have removed, to some extent, these elements, however, when I perform the tokenization, I notice that there ... | <p> This regex pattern removes almost all extra <em>white spaces</em> since I change the sentences <code>" "</code> by <code>""</code> and finally add <code>' +':' '</code> like this</p>
<pre><code>replacer = {'\n':'',"[\[].*?[\]]": "",'[!"#%\'()*+,-./:;<=>?@\[\]^_`{|}... | python|pandas|spacy | 1 |
356,057 | 70,346,629 | Default function argument value for Numpy Arrays and lists | <p>I want to define a function that determines whether an input to a function is a numpy array or list or the input is none of the two mentioned data types. Here is the code:</p>
<pre><code>def test_array_is_given(arr = None):
if arr != None:
if type(arr) in [np.ndarray, list]:
return True
r... | <p>Your function might be fixes and ameloriated using <code>isinstance</code> built-in function as follows:</p>
<pre><code>import numpy as np
def test_array_is_given(arr=None):
return isinstance(arr, (np.ndarray, list))
print(test_array_is_given()) # False
print(test_array_is_given(np.ones(1))) # True
print(test_... | python|numpy | 1 |
356,058 | 70,240,746 | Is there a pandas function to re-organize a dataframe around one column (and total rows with a specific column value)? | <p>I have a dataframe that contains every movie in a certain genre and the year it was released (plus some other stuff). I want to reorganize the dataframe so that it contains the number of films per year (and each year appears only once). Is there a way to do this?</p> | <p>You should look into <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby</a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer">value_counts</a></p>
<p>For ... | python|pandas|dataframe | 0 |
356,059 | 70,212,272 | RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0 | <p>I have a wrapper for a huggingface model. In this wrapper I have some encoders, which are mainly a series of embeddings. In forward of the wrapped model, I want to call forward of each of encoders in a loop, but I get the error:</p>
<pre><code>Traceback (most recent call last):
File "/home/pouramini/mt5-comet... | <p>Based on comments, I added the following code before training.</p>
<pre><code> wrapped_model.to(device=device)
for encoder in wrapped_model.prompt_encoders:
encoder.to(device=device)
</code></pre>
<p>Interestingly, when there was a single encoder or a list of encoders including one encoder, I ... | pytorch | 0 |
356,060 | 70,170,793 | Splitting data frame into smaller data frames based on unique column values | <p>this is my data frame:</p>
<pre><code> Quantity Code Value
0 1757 08951201 717.0
1 1100 08A85800 0.0
2 2500 08A85800 0.0
3 323 08951201 0.0
4 800 08A85800 0.0
</code></pre>
<p>and i what to split this into smaller d... | <p>As suggested you could use <code>groupby()</code> on your dataframe to segregate by one column name values:</p>
<pre><code>import pandas as pd
cols = ['Quantity', 'Code', 'Value']
data = [[1757, '08951201', 717.0],
[1100, '08A85800', 0.0],
[2500, '08A85800', 0.0],
[323, '08951201',... | python|pandas|dataframe | 1 |
356,061 | 70,096,455 | Replacing certain elements of an array based on a given index | <p>I have three numpy arrays:</p>
<pre><code>Arr1 = [9,7,3,1] (1 x 4 array)
Arr2 = [[14,6],[13,2]] (2 x 2 array)
Arr3 = [0,2] (1 x 2 array)
</code></pre>
<p>I need to replace the elements in Arr1 with the elements in Arr2 with the corresponding indices given in Arr3, such that the output would be:</p>
<... | <p>you can do it with list comprehension, which will save you some code lines and make it more interpretable, though it won't improve the runtime, as it uses loops under the hood. Also note that by incorparating a varying length lists, you'll loose any runtime improvements of the <code>NumPy</code> library, as to do so... | python|arrays|numpy|for-loop | 1 |
356,062 | 70,042,388 | Create a nested dictionary from a dataframe where the first column would be the key for the parent dictionary | <p>I'm trying to created a nested dictionary from a pandas DataFrame. The table is structured as below and is a lookup table that I want to create a nested dictionary from for later use.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">A</th>
<th style="text-align: ... | <p>Use Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> over the column <code>A</code>, then, iterate over the groups to create the dictionary. Using the dictionary comprehension combined with the built-in function <code>zip</... | python|pandas|dataframe | 1 |
356,063 | 70,290,011 | Efficient way to load big heterogeneous dataset in a numpy array? | <p>I have to load a dataset into a big array with <code>p</code> instances where each instance has 2 dimensions <code>(n_i, m)</code>. The length of the first dimension <code>n_i</code> is variable.</p>
<p>My first approach was to pad all the instances to the <code>max_len</code> over the first dimension, initialize an... | <p>The slow repeated vstack:</p>
<pre><code>In [200]: n=5; l=2
...: big_array = np.zeros([1,l])
...: for i in range(1,n):
...: big_array = np.vstack([big_array, np.full([i,l], i)])
...:
In [201]: big_array
Out[201]:
array([[0., 0.],
[1., 1.],
[2., 2.],
[2., 2.],
[3.... | python|arrays|numpy|array-broadcasting|vstack | 0 |
356,064 | 70,175,663 | Drop duplicates based on 2 columns if the value in another column is null - Pandas | <p>If I have a dataframe</p>
<pre><code>Index City Country State
0 Chicago US IL
1 Sacramento US CA
2 Sacramento US
3 Naperville US IL
</code></pre>
<p>I want to find rows with duplicate values for 'City' and 'Country' but only drop the row with no entry for... | <p>Use a boolean mask to get the index of rows to delete then use <code>drop</code> to remove this rows with <code>inplace=True</code> as argument:</p>
<pre><code>df.drop(df.loc[(df.duplicated(['City','Country'])
& df['State'].notna())].index, inplace=True)
print(df)
# Output:
City Country ... | pandas | 1 |
356,065 | 70,091,813 | array_2 = array_1 vs. array_2 = array_1.view() | <p>what is the difference between:</p>
<pre><code>array_2 = array_1
array_2 = array_1.view()
</code></pre>
<p>like I want an example where the effect of changing <code>array_2</code> to <code>array</code> in the 1st case does something different in the 2nd case</p> | <p>The key thing to understand is that <strong>assignment never copies or creates a new object</strong>. Assignment merely assigns the <em>same object</em> to a new name. It creates an "alias" to the same object - a different name for the same thing. A view creates <em>a new object</em>, which shares the same... | python|numpy | 7 |
356,066 | 70,143,154 | python sum a column's value with condition | <p>I have the below dataframe. I would like to return a second column that is the sum of every item in the column with a condition: only those larger than -1.</p>
<p>input</p>
<pre><code> Price
0 12
1 14
2 15
3 10
4 2
5 4
6 -5
7 -4
8 -3
9 -5
10 16
11 15
</code></pre>
<p>output</p>
... | <p>To get the sum of positive values in the column, use the appropriate condition</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'price': [12, 14, 15, 10, 2, 4, -5, -4, -3, -5, 16, 15]})
total = df.loc[df['price'] > 0, 'price'].sum()
print(total) # 88
</code></pre>
<hr />
<p>That isn't a good idea to set a ... | python|pandas|dataframe|numpy | 2 |
356,067 | 70,130,853 | Python Pandas Column Names | <p>I have a CSV file with four columns: <code>Category</code>, <code>Type</code>, <code>Provider</code>, and <code>Cost</code>.</p>
<pre><code>Category ,Type,Provider,Cost
Home,Mortgage,Real Homes,"$1,500.00"
Utilities,Gas,Landsberg Gas,$100.00
Utilities,Electric,Edison,$100.00
Utilities,Internet,Verizon Fio... | <p>Your CSV file has spaces around some of the column names, which is why you are having errors. Right after you call <code>pd.read_csv</code>, add this line:</p>
<pre><code>bills.columns = bills.columns.str.strip()
</code></pre>
<p>Then you should be able to do <code>bills.Category</code> etc. (if you change <code>mai... | python|pandas|dataframe | 1 |
356,068 | 70,113,432 | df.loc() doesn't seem to be working or filtering out the rows I need | <p>I'm trying to figure out how to use <code>df.loc</code> to calculate the number of orders per courier that are eligible for a bonus pay.</p>
<pre><code>df['Eligible'] = df.loc[(df['DeliveryOnTime'] == "On-time") & (df['DeliveryOnTime'] == "Early"), 'Total Orders'].sum()
</code></pre>
<p>So wh... | <p>Will this helps?</p>
<pre><code>data = {'ID': [1, 1, 1, 2, 2, 3, 4, 5, 5],
'DeliveryOnTime': ["On-time", "Late", "Early", "On-time", "On-time", "Late", "Late", "Early", "Early"],
}
data = pd.DataFrame(data)
data... | python|pandas | 0 |
356,069 | 70,071,045 | doing same operation on multiple variables using pandas | <p>I am new to python and am working with 18 pandas dataframes at once. I want to do the same operation on all the dataframes but havent seemed to find a one line bit of code to do it for me. I get what I want but I do individual lines of code for all 18 variables just now.</p>
<p>example</p>
<pre><code> a = [1,3; 2... | <p>Just use a simple loop and do your thing for each dataframe:</p>
<pre class="lang-py prettyprint-override"><code>for df in [df1, df2, df3, df4, df5, ...]:
# do your thing with df, e.g.:
print(df)
</code></pre> | python|pandas|dataframe | 0 |
356,070 | 70,128,790 | Reading URLs from .csv and appending scrape results below previous with Python, BeautifulSoup, Pandas | <p>I got this code to almost work, despite much ignorance. Please help on the home run!</p>
<ul>
<li>Problem 1: INPUT:</li>
</ul>
<p>I have a long list of URLs (1000+) to read from and they are in a single column in .csv. I would prefer to read from that file than to paste them into code, like below.</p>
<ul>
<li>Probl... | <p>Store your data in a list of dicts, create a data frame from it. Split the list of <code>drivers</code> / <code>challenges</code> into single <code>columns</code> and concat it to the final data frame.</p>
<h3>Example</h3>
<pre><code>import requests
from bs4 import BeautifulSoup
import pandas as pd
urls = ['https:/... | python|pandas|web-scraping|beautifulsoup|export-to-csv | 3 |
356,071 | 70,096,922 | Replace values dataframe column values if there is a perceptual change regarding the previous rows | <p>I have the following dataframe where if the drop or raise regarding the previous row larger or equal than 50% is to be replaced with NaN. (i need that in order to interpolate outliers)</p>
<pre><code>x=[16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
y=[6,6,3,3,8,8,7,2,2,2]
data=pd.DataFrame({'x': x, 'y': y})
</code></pre>... | <p>Your input is incorrect, so I assumed the following:</p>
<pre><code> x y
0 16 6
1 17 6
2 18 3
3 19 3
4 20 8
5 21 8
6 22 7
7 23 2
8 24 2
9 25 2
</code></pre>
<p>You can use <code>pct_change</code> to find the values where there is a drop, <code>mask</code> and <code>ffill</code> to identify t... | python|pandas|numpy|interpolation | 1 |
356,072 | 70,024,311 | Converting column value to ascii | <p>I have a data frame with columns, say v1~v4</p>
<pre><code>| _NAME | _TIMESTAMP | v0 | v1 | v2 | v3 | v4 |
|----------|---------------------|-------|------|-------|-------|-------|
| BRAKE_LH | 17-11-2021 22:50:43 | 13896 | 8262 | 12339 | 13110 | 13107 |
| BRAKE_LH | 17-11-2021 22:51:34 | 1... | <p>You can set columns <code>_NAME</code> and <code>_TIMESTAMP</code> as index (to exclude them for processing) by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>.set_index()</code></a>. Then use <a href="https://pandas.pydata.org/pa... | python|pandas|ascii | 2 |
356,073 | 70,253,592 | How to parse a Pandas DataFrame string in Unreal C++? | <p>I have a web service, which offers labelled 3d points which were serialized using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html" rel="nofollow noreferrer">Pandas' DataFrame's to_json method</a> like so:</p>
<pre class="lang-json prettyprint-override"><code>{
"x": {... | <p>I've never done Unreal C++ development before, but something like this should work:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <string>
void AHttpActor::OnResponseReceived(
FHttpRequestPtr Request,
FHttpResponsePtr Response,
bool bWasSuccessful
){
FString fcontent = Response... | c++|pandas|unreal-engine4 | 2 |
356,074 | 70,267,296 | How to delete part of the JSON that is corrupted in a dataframe? | <p>I have a dataframe which has one column with rows as json, and I am able to parse them correctly as long as a particular key is removed.</p>
<pre><code> id | email | phone no | details
-------------------------------------------------
0 10 | abc@g.com | 123 | {"a" : "hello", "b&qu... | <p>Try a regular expression with <code>str.replace</code>:</p>
<pre><code>PAT = re.compile(r',\s*"b"\s*:\s*{.*?}\s*,\s*')
df['details'] = df['details'].str.replace(PAT, ', ')
print(df)
# Output:
id email phone no details
0 10 abc@g.com 123 {"a" : "hello... | python|json|pandas|dataframe | 1 |
356,075 | 56,380,949 | Find absolute difference between 2 columns with dates of different formats as number of days | <p>I need to find the absolute difference in days between 2 columns which have dates in python.
This is pretty easy in excel but I want in python.</p>
<p>I have a xlsx file which I have read to a python dataframe(using <code>pd.read_excel</code>) with sample data reading as below:
The columns have the date details in ... | <p>First fomratting options is a good idea. Avoids confusion as to which is day or month.</p>
<pre><code># Recreate dataframe
df = pd.DataFrame([["1102012", pd.np.NaN],["26071993","27122007"],
["28062010","3122015"],["16012010","21022016"],
["02082015","14092010"]], columns=["A","... | python|pandas|python-datetime | 3 |
356,076 | 56,427,598 | How to "downgrade" a Keras/Tensorflow model so older code can work with it | <p>I'm quite new to Keras and Tensorflow, and I'd like to export my model to Javascript to be able to run it in a web browser. This worked great with <a href="https://mil-tokyo.github.io/webdnn/docs/tutorial/keras.html" rel="nofollow noreferrer">WebDNN</a> a year ago.</p>
<p>Today I updated my Tensorflow installation ... | <p>You can try <code>pip uninstall tensorflow</code> and then <code>pip install tensorflow-gpu==1.4.0</code>.</p>
<p>It is good practice to install your dependencies in separate environments, to avoid global pollution.</p> | python|tensorflow|keras | 2 |
356,077 | 56,201,835 | How to solve Unknown label type: 'unknown' in decision trees Python | <p>I am new to decision and trying to make a decision tree from a Review dataframe that has scores so far I tried this bu it is giving me </p>
<pre><code>X = ndf.drop('Score', axis=1)
y = ndf['Score']
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.30)
model = tree.DecisionTree... | <p>Make sure all of your labels (<code>y_train</code> and <code>y_test</code>) are in a single type only (either <code>int</code> or <code>string</code>).</p>
<p>For your case, <code>int</code> might be an appropriate type for the label, convert it to <code>int</code> if you see the type of <code>Score</code> is <code... | python|pandas|dataframe | 0 |
356,078 | 56,238,622 | Appending column based on multiple conditions | <p>I would like to create a new column and add the number 1 if multiple columns have nan values. However I keep encountering an error message when I run the code that I have written</p>
<pre><code>df_test2['notsure']=np.where((df_test2[df_test2[['android','blackberry','chrome_os','linux',
'macintosh'... | <p>Here is necessary filter by nested list:</p>
<pre><code>cols = ['android','blackberry','chrome_os','linux',
'macintosh','tizen','windows_phone','windows',
'ipad','iphone','device_other']
df_test2['notsure'] = np.where(df_test2[cols].isna().any(1),1,0)
</code></pre>
<p>Alternative is convert boolea... | python|pandas|numpy | 2 |
356,079 | 56,270,954 | Running variables | <p>I am quite new with TensorFlow, I am trying to use variables, but I do not get what I expect</p>
<p>When I declare a constant into tensorflow, and then I run into a session it works. but when I try to do the same with a variable, it does not.</p>
<p>Below you see simple experiments from the command line</p>
<pre ... | <p>You need to run a tensor which initializes all variables in your session, e.g.:</p>
<pre><code># Build graph
b = tf.Variable(5.)
# Get init tensor for all variables defined in the graph
init_op = tf.global_variables_initializer()
sess = tf.Session()
# Initialize all variables for the session
sess.run(init_op)
#... | python|tensorflow|variables | 0 |
356,080 | 56,305,326 | Replacing values in a string with NaN | <p>Faced a simple task, but I can not solve. There is a table in df:</p>
<pre><code>Date X1 X2
02.03.2019 2 2
03.03.2019 1 1
04.03.2019 2 3
05.03.2019 1 12
06.03.2019 2 2
07.03.2019 3 3
08.03.2019 4 1
09.03.2019 1 2
</code></pre>
<p>And I need for rows where Date < 05.03.2019 set X1... | <p>First convert column <code>Date</code> to datetimes and then set values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'], format='%d.%m.%Y')
df.loc[df['Dat... | python-3.x|pandas|dataframe | 3 |
356,081 | 56,075,717 | Model.fit_generator throwing a Run time error : | <p>Training a CNN using Keras, even though I did model.compile, <code>keras. fit_generator</code> throws a runtime error saying to do compile my model before using <code>fit</code>. </p>
<pre><code>Error:
Using TensorFlow backend.
WARNING:tensorflow:From C:\Users\..\Desktop\venvpy36\lib\site-packages\tensorflow\pytho... | <p>You have to assign input shape for your model, I think that is what it missing. Because in your <code>Sequential()</code> model you have not assigned input.</p>
<p>Here in your code <code>model.add(Conv2D(32, (3, 3), padding='same'))</code>, for the first layer you have to assign <code>input_shape</code>. </p> | python|python-3.x|tensorflow|keras | 1 |
356,082 | 56,039,301 | How to add extra column with values based on previous rows in Pandas data frame? | <p>I have this data frame:</p>
<pre><code>'C1'|'C2'
0 | x
1 | x1
1 | x2
2 | x3
0 | y
1 | y1
2 | y2
0 | z
1 | z1
</code></pre>
<p>I need to create an extra column like this: </p>
<pre><code>'C1'|'C2'|'C3'
0 | x | x
1 | x1 | x
1 | x2 | x
2 | x3 | x
0 | y | y
1 | y1 | y
2 | y2 | y
0... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" rel="nofollow noreferrer"><code>Series.where</code></a> for mising values if not match condition with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><c... | python|pandas | 3 |
356,083 | 56,046,811 | How make a correct gradient map using Numpy.gradient | <p>I made use of <code>numpy.gradient</code> to calculate the gradient map of a scalar-field map. I guess I have not known <code>numpy.gradient</code> very well so that I might produce an incorrect gradient map. I post my code and the resulting map below:</p>
<pre class="lang-py prettyprint-override"><code>from astrop... | <p>1) Because the 'white part' is not the top of the mountain, it goes, blue -> white -> red, as you can see in the bar in the right hand side. So the blue is the valley and the red are the mountains, and the arrows point where it is uphill.</p>
<p>2) The edges of the map don't have a gradient calculation because the ... | python|numpy|gradient | 1 |
356,084 | 56,062,423 | Numpy reshape function. How are these two lines of code different? | <p>How are these two lines of codes different:</p>
<pre><code>X_flatten = X.reshape(X.shape[0], -1).T
X_flatten = X.reshape(-1, X.shape[0])
</code></pre> | <p>these two lines have different outputs which are <strong>not related</strong> to each other
look at this example:
suppose <code>X</code> is like the following:</p>
<pre><code>>>> X = np.arange(6).reshape(2,3)
>>> X
array([[0, 1, 2],
[3, 4, 5]])
</code></pre>
<p>first line output:</p>
<pre... | python|numpy | 1 |
356,085 | 56,135,012 | How to Handle the pandas dataframe if the column name itself is a date in the Excel file | <p>How to select a specific column in the dataframe if the column name itself is a date, I've a column names in the excel as 1-Jan-18 2-Jan-18 3-Jan-18
but in the dataframe it is displaying something like below</p>
<blockquote>
<p>Index([ 'Names', 'Unnamed: 1', 2018-01-01 00:00:00,<br>
2... | <p>It should be like this,</p>
<pre><code>df['columnName1', 'columnName2']= df['columnName1', 'columnName2'].dt.strftime('%d-%m-%y')
</code></pre>
<p>Change <code>columnNames</code> to your actual columns which you want to change.<br>
Cheers!</p> | python|excel|pandas|date | 0 |
356,086 | 56,420,160 | When using Conv2D in PyTorch, does padding or dilation happen first? | <p>Consider the following bit of code:</p>
<p><code>torch.nn.Conv2d(1, 1, 2, padding = 1, dilation = 2)</code></p>
<p>Which of the following two cases is a correct interpretation?</p>
<p><a href="https://i.stack.imgur.com/bu138.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bu138.png" alt="enter ... | <p>If you look at the bottom of the <a href="https://pytorch.org/docs/stable/nn.html#conv2d" rel="nofollow noreferrer"><code>nn.Conv2d</code></a> documentation you'll see the formula used to compute the output size of the conv layer:</p>
<p><a href="https://i.stack.imgur.com/8CoP1.png" rel="nofollow noreferrer"><img s... | python|neural-network|deep-learning|pytorch | 1 |
356,087 | 56,311,579 | Add custom title to a data-frame in Pandas and convert it to HTML | <p>I am reading certain csv files from list of directories namely actual_results and expected_results. Now I glob through each csv in actual_results and compare it csvs in expected_results. Then I want to display the whole data into an HTML as below</p>
<p>I have already written some code for actually cleaning the dat... | <p>Pandas have a special object for <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html" rel="nofollow noreferrer">styling</a> that can be exported to HTML using its <code>.render</code> method or excel with <code>.to_excel</code>. You can use CSS to format your table and add captions as such:</... | html|python-3.x|pandas|csv|data-science | 2 |
356,088 | 56,391,392 | How to fix '_pickle.UnpicklingError: invalid load key, '<' ' error in Pytorch | <p>The problem I encountered when I ran the official code of maskrcnn-benchmark for facebookresearch,which was wrong when loading the pre-training model.</p>
<p>The code runs on a remote server at the school and the graphics card is an NVIDIA P100.</p>
<p>checkpointer = DetectronCheckpointer(
cfg, model, opti... | <p>The reason about the problem is that the previous download was not finished. So when I deleted the original file and re-downloaded it, the problem was solved.</p> | python-3.x|pytorch | 3 |
356,089 | 56,047,458 | Creating a dataframe columns with lists of matching values from another dataframe | <p>I am trying to create a pandas dataframe column (in df1) where each element is a list of all values from another dataframe (df2) that match an existing columns in df1. This is different from a pandas left merge because that function would create new rows for each time the df1 value is duplicated in df2. </p>
<p>I h... | <p>Try:</p>
<pre><code>df1.set_index('col4', inplace=True)
df1['col4'] = df2.groupby('col3').col2.apply(list)
df1.reset_index(drop=True, inplace=True)
</code></pre> | python|python-3.x|pandas | 3 |
356,090 | 56,225,815 | MemoryError dealing with huge set of data from requests | <p>I am downloading the Data from Rest API using requests and using data frame to download it in a flat file. I am getting the below memory Error. Any suggestion on resolving this?</p>
<pre><code>File "C:\Python\Python37-32\my_script.py", line 74, in <module>
df1= pd.DataFrame(my_list)
File "C:\Python\Python37-3... | <p>Depends on the size of the dataset. If you are dealing with huge dataset which exceeds the limit of your local memory, you wont be able to do this operation. These libraries load the entire data directly into the memory, which in case of big data is never a good approach.</p> | python|pandas | 0 |
356,091 | 56,361,510 | Implementing DFT, inverse function not working properly | <p>I've implemented DFT and the inverse DFT Function according to the following formulas:</p>
<p><img src="https://i.ibb.co/8gw4qfJ/Code-Cogs-Eqn-2.gif" alt="" /></p>
<p>The DFT function works, but when testing the inverse on the output I don't get the original series.</p>
<pre class="lang-py prettyprint-override"><cod... | <p>Shouldn't your test be</p>
<pre><code>print(np.allclose(inv, orig))
</code></pre>
<p>since </p>
<pre><code>orig = myidft(mydft(orig))
</code></pre>
<p>because when I plot your DFT</p>
<p><a href="https://i.stack.imgur.com/WcQOZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WcQOZ.png" alt="D... | python|numpy|dft | 2 |
356,092 | 56,014,914 | what tensorflow.nn.softmax do? | <p>I'm following coursera tensorflow course and I can not understand below code can you explain itusing simple english please..</p>
<p>here is code</p>
<pre><code>model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
... | <p>Here's the docs: <a href="https://www.tensorflow.org/api_docs/python/tf/nn/softmax" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/nn/softmax</a></p>
<p>Basically, softmax is good for classification. It will take any number and map it to an output of either 0 or 1 (for example) because we ... | python|tensorflow|keras | 2 |
356,093 | 56,043,710 | I am trying to divide certain rows and columns in a dataframe and end up with the original dataframe but with those new values | <p>I have a dataframe with the date and prices of different stocks. I am trying to change the values in certain rows and column to adjust for a stock split and end up with the original dataframe but with those new values.</p>
<p>With df.iloc I can get the values that I want, but I cannot fit them as the new values in ... | <p>You are very close. Just add the <code>.iloc</code>:</p>
<pre><code>t.iloc[:2,1] = t.iloc[:2,1] / 7
</code></pre>
<pre><code>print(t)
Date_bought Price_bought Date_sold Price_sold
AAPL 12/01/2017 -100.071429 5/04/2019 123.5
AAPL 12/02/2017 -101.457143 2/05/2018 128.1
AAPL 5/04/2018 -126.... | python|pandas | 0 |
356,094 | 56,200,657 | Rearranging data frame after combining two data frames | <p>I have two CSV files- file1, file2. File2 is a subset of file1. I would like to merge the content of file2 in file1 and put the entries of file2 at the bottom of file1 so that the total number of entries in file1 remain same after merging. </p>
<p>Here is what I have tried so far but it is basically adding the entr... | <p>Try <code>data1.update(data2)</code>.</p>
<p>The join is on index and update is <em>in place</em>.</p>
<p>In future questions include sample data for source DataFrames and expected result.</p>
<h1>Edit</h1>
<p>If you want to have first "original" (not updated) rows from
<em>data1</em> and <strong>after them</str... | python|pandas | 0 |
356,095 | 56,365,434 | Consultation python in csv .20 major movements by department | <p>I need to get the 20 biggest 'MOV12' for 'DPTO', using python and pandas</p>
<p>I have a csv (.del) with the following fields</p>
<pre><code>"CODCLI" "DPTO" "SEG" "TIPPER" "MOV12"
11 20 "SEG1" "NAT" 6480.00
19 20 "SEG1" "NAT" 0.00
28 20 "SEG1" "NAT" 900.00
29 24 "SEG4" "NAT" 1800.00
31 20 "SEG1" "NAT" 3050... | <p>Use <code>groupby</code> and <code>apply</code> with <code>nlargest</code></p>
<pre><code>import pandas as pd
df = pd.read_csv("c.del", sep = ' ')
result=df.groupby('DPTO').apply(
lambda x: x.nlargest(20,'MOV12')
)
</code></pre>
<p>This will find the rows corresponding to the 20 largest values of 'MOV12' for e... | python|pandas|csv|numpy|dataframe | 0 |
356,096 | 56,081,811 | Did something change in the encoding of Whatsapp chat exports? | <p>I was trying to follow a tutorial/example on how to import Whatsapp chat text exports into a Pandas dataframe, found <a href="https://imrankhan17.github.io/pages/Exploring%20WhatsApp%20chats%20with%20Python.html" rel="nofollow noreferrer">here</a>.</p>
<p>When I tried to run it, there was an encoding issue (<code>U... | <p>I made 3 small changes and the code is now working well for me:</p>
<p>1- The format of the dates don't always have two digits for days and months, but it always has two digits for years. I adjusted the regex to reflect it:</p>
<p>r'^(\d+/\d+/\d\d.*?)(?=^^\d+/\d+/\d\d,*?)'</p>
<p>2- The end of the datatime field has... | python|pandas | 0 |
356,097 | 56,013,542 | Azure Machine Learning Studio pandas package update | <p>I am tring on microsoft azure ml to update pandas package.the problem is that i am trying to execute a python script and the supported python version are still at3.5 . unfortunately i did not notice that so my code is not execute cause is written on python 3.7 . so there is any way to update pandas in azure ml stud... | <p>You can try the new "Visual Interface" in Azure ML service, which as an updated Python runtime. It is a new architecture over the UI of Azure ML Studio:
<a href="https://www.youtube.com/watch?v=QBPCaZo9xx0" rel="nofollow noreferrer">https://www.youtube.com/watch?v=QBPCaZo9xx0</a></p> | python|pandas | 0 |
356,098 | 56,315,059 | What should be the output of the custom loss function in Keras? | <p>I am trying to build a custom loss function in Keras, but I am confused about the way it works. I am training the network on batches, and I am not sure if the output of the loss function should be an array with the same dimension as the batch or just a scalar.</p> | <p>As described in the documentation, <a href="https://keras.io/losses/" rel="nofollow noreferrer">keras loss</a>, You can pass a function that returns a scalar for each data-point and takes the two arguments: y_true (True labels) and y_pred (Predictions).</p>
<p>Keras execute the mean over sample inside batch, so the ... | python|tensorflow|keras|conv-neural-network | 3 |
356,099 | 56,105,935 | Counting the number of numbers between each dots in every element of the array in Pandas | <p>I have column in spreedsheet with IP numbers like;</p>
<pre><code>IP
107.57.251.192
219.209.105.108
96.138.34.175
172.135.215.244
89.83.162.207
53.197.57.183
172.53.157.32
</code></pre>
<p>and I have them inside of an array like </p>
<pre><code>array=['107.57.251.192', '219.209.105.108', '96.138.34.175', '172.135... | <p>You can use a regular expression with <code>re.sub</code></p>
<pre><code>import re
[
re.sub(r'(\d+)', lambda x: f'{len(x.group(1))}sign', el) for el in array
]
</code></pre>
<p></p>
<pre><code>['3sign.2sign.3sign.3sign',
'3sign.3sign.3sign.3sign',
'2sign.3sign.2sign.3sign',
'3sign.3sign.3sign.3sign',
'2s... | string|pandas|dataframe|for-loop|count | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.