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
375,900
73,655,690
Parsing Nested JSON to one data file
<p>I am trying to parse a nested json.</p> <p>I've got the dataset stored here so that you can see what I'm seeing specifically if you want: <a href="https://mega.nz/file/YWNSRBjK#V9DpoY5LSp-VL8Mnu7NEfNf3FhDOCj9FHBiTQ4KHEa8" rel="nofollow noreferrer">https://mega.nz/file/YWNSRBjK#V9DpoY5LSp-VL8Mnu7NEfNf3FhDOCj9FHBiTQ4K...
<p>I think the code that you want looks like this:</p> <pre><code>with open('unzipped_json.json') as f: data = json.load(f) negotiated_rates_and_prices_df = pd.json_normalize( data[&quot;in_network&quot;], record_path=[&quot;negotiated_rates&quot;, [&quot;negotiated_prices&quot;]], meta=[ &quot...
python|json|pandas
2
375,901
73,710,989
Find row which value in either one of the column is NaN
<p>Here is a dataframe that I am working with:</p> <pre><code>cl_id a c d e A1 A2 A3 0 1 -0.419279 0.843832 -0.530827 text76 1.537177 -0.271042 1 2 0.581566 2.257544 0.440485 dafN_6 0.144228 2.3622...
<p>You can do <code>count</code></p> <pre><code># 1 here is len(['A2', 'A3']) - count_na count_na = 1 df[df[['A2','A3']].count(axis=1) == 1] </code></pre> <p>Or you can check with <code>isna</code> and sum the result:</p> <pre><code>count_na = 1 df[df[['A2','A3']].isna().sum(axis=1) == count_na] </code></pre>
python|pandas
0
375,902
73,693,268
How to pivot a table based on the values of one column
<p>let's say I have the below dataframe:</p> <pre><code>dataframe = pd.DataFrame({'col1': ['Name', 'Location', 'Phone','Name', 'Location'], 'Values': ['Mark', 'New York', '656','John', 'Boston']}) </code></pre> <p>which looks like this:</p> <pre><code>col1 Values Name Mark Location New York P...
<p>Create a new <code>index</code> using <code>cumsum</code> to identify unique sections then do <code>pivot</code> as usual...</p> <pre><code>df['index'] = df['col1'].eq('Name').cumsum() df.pivot('index', 'col1', 'Values') </code></pre> <hr /> <pre><code>col1 Location Name Phone index 1 N...
python|pandas|dataframe|pivot
2
375,903
73,559,770
Remote ray call Ignoring function arguments
<p>I am trying to apply <code>ray</code> to a transformer pipeline as:</p> <pre><code>@ray.remote def predict(pipeline, text_data, max_length, min_length, do_sample): return pipeline(text_data, max_length, min_length, do_sample) </code></pre> <p>and initializing as:</p> <pre><code>predictions = ray.get(predict.remo...
<p>Copy-pasting from <a href="https://discuss.ray.io/t/remote-ray-call-ignoring-function-arguments/7413" rel="nofollow noreferrer">discuss</a>:</p> <p>Sorry I’m not exactly sure what you mean by the args getting ignored. Could you post a runnable reproduction, preferably without the actual pipeline (you can just use an...
python|python-3.x|huggingface-transformers|ray
0
375,904
73,759,925
Convert string dictionary in pandas.core.series.Series to dictionary in python
<p>I read my data from excel and saved it in data frame format. One of the columns of the data has data in a dictionary format(same shape but not dictionary format), which is recognized as a string format. So, I want to change the data type of all rows (more than 40k) in that column from string to dictionary format. Th...
<p>Use:</p> <pre><code>import pandas as pd df = pd.DataFrame({'string dict':[&quot;{'a': 1}&quot;, &quot;{'b':2}&quot;]}) df['string dict'].apply(eval) </code></pre> <p>which can be validated as follows:</p> <pre><code>type(df['string dict'].apply(eval)[0]) </code></pre> <p>returns:</p> <pre><code>dict </code></pre> <...
python|pandas|string|dictionary|type-conversion
1
375,905
73,764,642
How to group dates which are in sequential to 'From' and 'To'?
<p>I have dates in sequential and some are not in sequence. How can I group those dates to 'From date' and 'To Date'?</p> <pre><code>Name Date ABC Jan 1, 2022 ABC Jan 2, 2022 ABC Jan 3, 2022 ABC Feb 1, 2022 DEF Jan 1, 2022 DEF Mar 1, 2022 DEF Mar 2, 2022 </code></pre> <p>This should group...
<p>Doing <code>diff</code> with <code>cumsum</code> create the <code>groupby</code> key</p> <pre><code>x = pd.to_datetime(df.Date).diff().dt.days.ne(1).cumsum() out = df.groupby([df['Name'],x])['Date'].agg(['first','last']).reset_index(level=0) Out[219]: Name first last Date ...
python|pandas
1
375,906
73,785,695
How to join dataframes on columns of lists with 'contains' conditions in python
<p>I have two dataframes that look like this:</p> <p>Dataframe 1:</p> <pre><code>antecedents consequents 0 (20679) (15056BL) 1 (20675) (20676) 2 (20675) (20677) 3 (20723) (20724) 4 (22356) (20724) ... ... ... 178 (22355, 20724, 22356) (20719) 179 (20724, 22356, 20719) (22355) 180 (21212, 84991, 84992) (...
<p>try:</p> <pre><code>df = df1.explode('antecedents').merge(df2.explode('StockCode'), right_on='StockCode', left_on='antecedents', how='left') df antecedents consequents Customer ID StockCode 0 20679 20676 NaN NaN 1 85048 20719 13085.0 85048 2 22143 22355 1810...
python|pandas|dataframe|join
0
375,907
73,719,164
Python Pandas Dataframe drop columns if string contains special character
<p>I have a dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Product</th> <th style="text-align: center;"></th> <th style="text-align: right;">Storage</th> <th style="text-align: right;">Price</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;"...
<p>I would do something like this</p> <pre><code>import pandas as pd from io import StringIO text = &quot;&quot;&quot; Product,Perc,Storage,Price Azure,(2.4%,Server,£540 AWS,,Server,£640 GCP,,Server,£540 &quot;&quot;&quot; data = pd.read_csv(StringIO(text)) print(data) drop_columns = list() for col_name in data.colum...
python|pandas|dataframe|conditional-statements
1
375,908
73,678,556
How to transform a csv file into a multi-dimensional list using Python?
<p>I started out with a 4d list, something like</p> <pre><code>tokens = [[[[&quot;a&quot;], [&quot;b&quot;], [&quot;c&quot;]], [[&quot;d&quot;]]], [[[&quot;e&quot;], [&quot;f&quot;], [&quot;g&quot;]],[[&quot;h&quot;], [&quot;i&quot;], [&quot;j&quot;], [&quot;k&quot;], [&quot;l&quot;]]]] </code></pre> <p>So I converted ...
<p>Assuming you wanted your csv file to look something like this (there were a couple typos in the posted code):</p> <pre><code>A,B,C,word 0,0,0,a 0,0,1,b ...
python|pandas|list|csv|nested-lists
0
375,909
73,543,508
How to only display the "subcontrol"
<p>I have the following dataframe: (containing information like the one below)</p> <pre><code>import pandas as pd data = { &quot;items&quot;: [&quot;4.2 Paint&quot;, &quot;4.2.1 Paint job&quot;, &quot;4.2.1.10 Paint red&quot;, &quot;3.2 Seats&quot;, &quot;3.2.3.8 Seat belt&quot;] } df = pd.DataFrame(data) print(...
<p>It's very hard to workout what the criteria is here but if it's looking for the 4th subgroups then filter for when there are 3 dots.</p> <p><code>df[df['items'].apply(lambda x: x.count(&quot;.&quot;)==3)]</code></p> <p>-=-=-EDIT-=-==-</p> <p>If want the max per subgroup then something like this would work.</p> <ul> ...
python|pandas
1
375,910
73,678,262
Error while trying to save data into hdfs
<p>I'm trying to move data from local to hdfs using jupyter after the Data cleaning, i found some issues while doing it, and the data won't move into hdfs ( hdfs &amp; jupyter deployed in minikube k8s)</p> <p>This is the code in jupyter :</p> <pre><code>writer = pd.ExcelWriter(&quot;data.xlsx&quot;) data.to_excel( exce...
<p>This is how i solved my problem :</p> <pre><code>Client = InsecureClient('http://hdfs-namenode.default.svc.cluster.local:50070', user='hdfs') data = pd.read_csv('name_of_file.csv') with client.upload('path/name_of_file.csv' , 'name_of_file.csv', n_threads=1, temp_dir=None) as writer : data.to_csv(writer) </cod...
pandas|kubernetes|hadoop|hdfs|pandas.excelwriter
0
375,911
73,728,110
How to show different horizontal bar colors in grouped time series data in Pandas according to a column value (0/1)?
<p>I have the following sampled data frame from a million rows. It'll show value counts of anomalous rows, a dataframe with only anomalous rows, and the plot.</p> <p>Input data:</p> <pre class="lang-py prettyprint-override"><code>df_sample = pd.DataFrame({ 'AbsoluteTopImpressionPercentage': [0.0, 1.0, 1.0, 0.0, ...
<p>Without changing your code too much, you need to create the list of colors on your grouped data which you will plot later.</p> <p>The line, where I create <code>out</code>, I used <code>max</code> as aggregation for the column <code>Anomaly</code>. In your example data for each group of <code>Anomaly</code> there is...
python|pandas|dataframe|matplotlib|time-series
2
375,912
73,642,093
Python Pandas to_datetime Without Zero Padded
<p>I am trying to convert a date &amp; time string using Pandas 'to_datetime', but the string values is non-zero padded:</p> <pre><code>3/31/22 23:30 3/31/22 23:45 4/1/22 0:00 4/1/22 0:15 </code></pre> <p>I have the following but get a mismatch error</p> <pre><code>pd.to_datetime(df.TimeStamp, format=&quot;%m/%d/%y %H:...
<p>The trouble isn't in the padding, it's actually in your formatting call. Note the capitalization of minutes (M) vs months (m), you used (m) for both. (<a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow noreferrer">documentation here</a>).</p> <p>Demonstration of wo...
python|pandas|string-to-datetime
1
375,913
73,672,691
How to find percentage change in values of a column using a variable for another column with pandas "category" data type?
<p>Here's the data frame:</p> <p><a href="https://i.stack.imgur.com/pF2tm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pF2tm.png" alt="enter image description here" /></a></p> <pre><code>df_temp = pd.DataFrame({'pos': {0: '1-10', 1: '11-20', 2: '21-30', 3: '31-40', 4: '41-50', 5: '51-60'...
<p>Let's say we have some sequence of ages and a refference table between age bins and some value <em>imp</em>:</p> <pre><code>import pandas as pd import numpy as np rng = np.random.default_rng(42) N = 10 # number of data data = pd.Series(rng.integers(1, 111, N), name='Ages') imp = pd.Series( data=[18647, 566...
python|pandas|dataframe|numpy
1
375,914
73,679,996
Given a list of random variable and an expected value, how to generate probability distribution in python
<p>I have a list of random values x_1,x_2, ... x_n and an expected value X.I wanna write a function that takes these 2 things and randomly generates one of the many discrete probability distributions defined on the set {1,2....n} that meets the above mentioned constraint.</p> <p>Rephrasing the question as generate a ve...
<p>After trying to create a recursive solution for hours I gave up and coded an iterative brute force ish approach myself.</p> <pre><code>@numba.jit(nogil = True) def normal_random_distribution(data_array, X_array, expd_vl): # print(&quot;here&quot;) EPSILON = 0.001 data_len = data_array.size data_arr...
python|numpy|random|scipy|probability
0
375,915
73,540,650
numpy reshape and the base attribute of an array
<p>I'm trying to understand when, after a reshape, numpy made a copy or a view. I was trying it analyzing the content of the <code>base</code> attribute. I expected it to be <code>None</code> when the array is a copy, the original array if it is a view. However, with the following code:</p> <pre class="lang-py prettypr...
<p>For <code>B</code>, the base is the <code>A</code> array; the id's match:</p> <pre><code>In [111]: id(A) Out[111]: 2579202242096 In [112]: id(B.base) Out[112]: 2579202242096 </code></pre> <p>For <code>D</code>, the base is a copy of <code>C</code>, same values but different id:</p> <pre><code>In [113]: id(C) Out[11...
python|numpy|reshape|numpy-ndarray
1
375,916
73,658,346
Remove duplicates and keep row that certain column is Yes in a pandas dataframe
<p>I have a dataframe with duplicated values on column &quot;ID&quot;, like this one:</p> <pre><code>ID Name Street Birth Job Primary? 1 Fake1 Street1 2000-01-01 Job1 Yes 2 Fake2 Street2 2000-01-02 Job2 No 3 Fake3 Street3 2000-01-03 Job3 Yes 1 Fake1 Street1 2000-01-01 Job4 ...
<p>Using <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.idxmax.html" rel="nofollow noreferrer"><code>groupby.idxmax</code></a> on a boolean Series derived from the &quot;Primary?&quot; column:</p> <pre><code>out = df.loc[df['Primary?'].eq('Yes').groupby(df['ID']).idxmax()] </...
python|pandas|filter|duplicates|find
2
375,917
73,738,162
Python - Method to get the array around an slice in a matrix
<p>I define a Matrix NxN, with random values(0,1). I need to get the sum of the digits around the consecutive 1's.</p> <p>For example:</p> <pre class="lang-none prettyprint-override"><code>100110001 101001000 100001001 000000000 000111001 000000100 .. .. </code></pre> <p>For 111 in the above, the sum of the surroundin...
<p>This might not fully answer your question, but it might point you in the right direction :</p> <pre><code>In [1]: import numpy as np In [2]: from scipy import ndimage as nd In [3]: mat = np.random.randint(0,2,(6,6)) In [4]: mat Out[4]: array([[1, 1, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0], [1, 0, 1, 1, 1, ...
python|arrays|numpy|matrix
0
375,918
73,633,416
Sum value in specific combinations of rows
<p>I have the following dataframe:</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame({'Name' : ['Jake', 'Nate', '', 'Alex', '', 'Max', 'Nate', 'Jake'], 'Color' : ['', 'red;blue', 'blue;pink', 'green;blue;red', '', '', 'blue', 'red;yellow'], 'Value_1' : [121...
<p>You can use:</p> <pre><code>(df1.assign(Color=df1['Color'].str.split(';')) .explode('Color') .groupby(['Name', 'Color'], as_index=False) .sum() .replace('', pd.NA).dropna() ) </code></pre> <p>output:</p> <pre><code> Name Color Value_1 Value_2 Value_3 3 Alex blue 0.000000e...
python|pandas|dataframe
1
375,919
73,606,579
End of the execution too long using Pool.starmap
<p>I'm executing a paralelized function using Pool.starmap function. The execution of the function it self only takes 6.5 minutes according to tqdm library but the program stays in execution for 20 min more until it finishes. The function is processing and applying filters to some strings in some colums of a pandas dat...
<p>In the demos below, generator function <code>params</code> simulates generating arguments to worker function <code>foo</code> <em>slowly</em> and <code>foo</code>, which just returns the passed argument, which is either a list when using <code>imap</code> or individual arguments that are the elements of a list.</p> ...
python|pandas|multiprocessing|pool|starmap
1
375,920
73,737,782
AttributeError: 'bool' object has no attribute 'any'. only thrown for arrays exceeding certain size
<p>I am running some Pandas/numpy data manipulation code as shown below with a random sample dataframe:</p> <pre><code>import pandas as pd; import numpy as np; nrows = 200 df = pd.DataFrame(np.random.randint(0,25,size=(nrows, 8)), columns=list('ABCDEFGH')) array_val = df.values array_obj = ((array_val == array_val[:,N...
<p>I ended up getting the code to run without an error on 75k/80k by using another environment with a different Pandas/numpy version. Though I'm still not sure why the issue is tied to package version</p>
python|arrays|pandas|numpy
0
375,921
73,795,151
Python - how to get add a counter inside a IF condition to add track the number of times something has occured
<p>I am new to python and learning it in bits and peices from internet. I have been tring to get a volume monitor for binance volumes.</p> <pre class="lang-py prettyprint-override"><code>for x in range(len(name)): # Code to get the data into panda dataframes for each token in name[] hrlyvol = res1[&quot;volume...
<p>I am using the example of odd number or even number to showcase the condition</p> <pre><code>i=0 j=0 for n in range(100): i = i+1 if n%2 == 0 else i+0 j = j+1 if n%2 == 1 else j+0 </code></pre>
python|pandas|dataframe|loops|binance
0
375,922
73,671,952
How to speed up for loops in dataframe
<p>I want to convert a data frame to the format I want by scanning each latitude and longitude in the for loop, but this process takes too long. Is there a way to make the following script faster, such as using multi threads or processing? Can you show me how?</p> <pre><code>p=0 for i in tqdm(df_wind_monthly[&quot;lat&...
<p>Looping is definetly NOT the way to go. If you type <code>for ... in</code> while using pandas DataFrame, you're almost always doing it wrong.</p> <p>What you want is to switch your data from long format (1 row = 1 observation) to wide format (1 row = 12 observations). It is a fairly common usecase, so pandas provid...
python|pandas|dataframe|performance|latitude-longitude
1
375,923
73,791,940
How to re-write tensorflow code to make model training faster?
<p>QUESTION: My training is super slow. How do I rewrite my code to make my deep learning model training faster?</p> <p>BACKGROUND: I have built a CNN with TensorFlow 2.8.1 to classify CIFAR-100 images using a custom loss function. The CIFAR dataset includes 32x32-pixel RGB images of 100 fine classes (e.g., bear, c...
<h2>Quantization</h2> <ul> <li>Quantization is the technique that converts your number type <code>float32</code> to <code>int8</code>. It means your model size will be lesser.</li> <li>There are two types of quantization before training and after training.</li> <li>Try to apply quantization before training and let me k...
tensorflow|keras|eager-execution
0
375,924
73,731,376
Python Concat two dataframe after grouping and sort
<p>i have two pandas frame and i want to get one</p> <pre><code> asks_price asks_qty exchange_name_ask 0 20156.51 0.000745 Coinbase 1 20156.52 0.050000 Coinbase </code></pre> <pre><code> bids_price bids_qty exchange_name_bid 2 20153.28 0.000200 Coinbase 3 2015...
<p>The two columns <code>exchange_name..</code> doesn't disappear when you use <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferrer"><strong><code>pandas.concat</code></strong></a> but they simply doesn't exist in the two dataframes passed as arguments.</p> <p>Try this :</p...
python|pandas
1
375,925
71,365,871
adding elements to a numpy array and reshape it
<p>I have the following numpy array</p> <pre><code>a= np.array([1,1]) </code></pre> <p>I have the two elements</p> <pre><code>b= [2, 2] c= [3, 3] </code></pre> <p>I would like to add those elements b and c, so that my output seems like this</p> <pre><code>a= [[1, 1], [2, 2]. [3, 3]], #shape=(3,2) </code></pre>...
<p>Create a new <code>numpy</code> array with the three elements</p> <pre><code>&gt;&gt;&gt; np.array([a,b,c]) array([[1, 1], [2, 2], [3, 3]]) # shape : (3, 2) </code></pre> <p>If a had more than 1 dimension, <code>np.append</code> can be used :</p> <pre><code>&gt;&gt;&gt; a= np.array([[1,1], [4,4]]) &gt;&gt;&gt;...
python|arrays|numpy
1
375,926
71,268,742
Python libraries for representing distance between a point and DNF of inequalities
<p>Let us fix the number of variables to be 4: so x0, x1, x2, x3.</p> <p>I am looking for a python construct which allows me to:</p> <p>(i) store in memory, a disjunctive normal formula where the atomic formulas are inequalities: a0x0 + a1x1 + a2x2 + a3x3 &gt;= a4 or equalities: a0x0 + a1x1 + a2x2 + a3x3 == a4.</p> <p>...
<p>My response is to my interpretation of your problem, but I recognize that I am filling some gaps with my assumptions.</p> <p>(i) can be solved with <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html" rel="nofollow noreferrer">linear programming</a>.</p> <p>(ii) is a very open q...
python|numpy|scipy|pyeda
0
375,927
71,143,308
merge two datasets to find a mean
<p>I have two similar looking tables: df1:</p> <pre><code>country type mean count last_checked_date Brazil Weather x 2 2022-02-13 Brazil Corona y 3 2022-02-13 China Corona z 1 2022-02-13 China Fruits s 2 20...
<p>We may consider the problem this way, we combine them into one table,</p> <pre><code>df = pd.concat([df1, df2]) </code></pre> <p>then use <code>groupby</code> to apply aggregations on each group of the rows that share the same <code>country</code> and <code>type</code>.</p> <pre><code>df.groupby(['country', 'type'])...
python|pandas|dataframe|numpy|mean
0
375,928
71,223,806
Taking the average of one column with a certain value in another column Pandas
<p>I want to find the average of one column based on the value of another. So if i have col1 with columns ['1','2'].</p> <pre><code>data = [['A',10],['B',12],[['A',41],['B',14]] df1 = pd.DataFrame('data',columns=['1','2'] df1.head() </code></pre> <p>so how would i create a new column with the average for '1' A and B</p...
<p>You can do do a <code>groupby</code> and <code>transform</code> to get the mean of each group</p> <pre><code>df1[&quot;avg&quot;] = df1.groupby(['1']).transform('mean') print(df1) 1 2 avg 0 A 10 25.5 1 B 12 13.0 2 A 41 25.5 3 B 14 13.0 </code></pre> <hr /> <p>Or, if you want a literal column of t...
pandas|dataframe|aggregate
0
375,929
71,434,956
Optimalization of my script whcich calculate weekly qty of product
<p>I have a task where I need to change multiple times data in my data frame. I wrote the answer in Jupyter notebook, using loops and it's take around 2,5min to run.</p> <p>However, when I rewrite my code to pycharm using modules and definitions it takes around 20min and I do not know where I made a mistake.</p> <p>Her...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.clip.html" rel="nofollow noreferrer"><code>clip</code></a>:</p> <pre><code>p10, p90 = np.percentile(df.iloc[:, 1:], [10, 90], axis=1) out = df.iloc[:, 1:].clip(p10, p90, axis=0) out['Average'] = out.mean(axis=1) out = pd.concat([df.il...
python|dataframe|pycharm|pandas
1
375,930
71,248,632
How to convert data from DataFrame to form
<p>I'm trying to make a report and then convert it to the prescribed form but I don't know how. Below is my code:</p> <pre><code>data = pd.read_csv('https://raw.githubusercontent.com/hoatranobita/reports/main/Loan_list_test.csv') data_pivot = pd.pivot_table(data,('CLOC_CUR_XC_BL'),index=['BIZ_TYPE_SBV_CODE'],columns=['...
<p>Hi First create a worksheet using <a href="https://pypi.org/project/XlsxWriter/" rel="nofollow noreferrer">xlsxwriter</a></p> <pre><code>import xlsxwriter #start workbook workbook = xlsxwriter.Workbook('merge1.xlsx') #Introduce formatting format = workbook.add_format({'border': 1,'bold': True}) #Adding a workshee...
python|pandas|numpy
2
375,931
71,304,442
randomly choose value between two numpy arrays
<p>I have two numpy arrays:</p> <pre><code>left = np.array([2, 7]) right = np.array([4, 7]) right_p1 = right + 1 </code></pre> <p>What I want to do is</p> <pre><code>rand = np.zeros(left.shape[0]) for i in range(left.shape[0]): rand[i] = np.random.randint(left[i], right_p1[i]) </code></pre> <p>Is there a way I could ...
<p>You could try with:</p> <pre><code> extremes = zip(left, right_p1) rand = map(lambda x: np.random.randint(x[0], x[1]), extremes) </code></pre> <p>This way you will end up with a <code>map</code> object. If you need to save memory, you can keep it that way, otherwise you can get the full <code>np.array</code> pa...
numpy
2
375,932
71,304,944
Panda- How can some column values can be moved to new column?
<p>I have the below data frame</p> <pre><code>d = { &quot;name&quot;:[&quot;RRR&quot;,&quot;RRR&quot;,&quot;RRR&quot;,&quot;RRR&quot;,&quot;RRR&quot;,&quot;ZZZ&quot;,&quot;ZZZ&quot;,&quot;ZZZ&quot;,&quot;ZZZ&quot;,&quot;ZZZ&quot;], &quot;id&quot;:[1,1,2,2,3,2,3,3,4,4],&quot;value&quot;:[12,13,1,44,22,21,23,53,64,9] }...
<p>First pivot by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with counter by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow...
python|pandas
2
375,933
71,299,388
Pandas - new column based on `max` of grouped values
<p>I have a Pandas dataframe with multiple groups in it, A, B, C. Each group has multiple counts associated with it and I want to create a new column that is normalised to the max value of each group.</p> <p>i.e.</p> <pre><code>index, group, year, count 0, A, 2015, 1 1, A, 2016, 2 2, A, 2017, 3 3, B, 2012, 10 4, B, 201...
<p>You can use <code>groupby</code> + <code>transform</code> to calculate the ratio between current value and maximum value in each group:</p> <pre><code>df['normalised'] = df['count'].groupby(df.group).transform(lambda x: x / x.max()) df index group year count normalised 0 0 A 2015 1 0.333333 ...
python|pandas|assign
4
375,934
71,101,277
Append rows of same data and Transpose it into columns
<p>I have created a dataframe from an excel sheet using pandas. The issue with this data frame is the data structure provided to me. The data structure is somewhat complex where the same data types were given in rows structure. So I had to use df.transpose() to first transpose the data, but the issue occurs after trans...
<p>since you haven't provided any reproducible code, we wouldn't be able to provide any solution as a code. However, I can answer at high level.</p> <p>The transpose that you have done is absolutely right. Why don't you make a new data frame with the repeated data from columns E, F, G, H and then concat the two data fr...
python|pandas|csv
0
375,935
71,111,376
Unable to create directory and download model on local directory from Azure
<p>I have created a pipeline script where I have defined the pipeline steps and submit the pipeline.</p> <pre><code>dataPrep_step = PythonScriptStep(name='01 Data Preparation', source_directory='/home/ubuntu/Desktop/AzureMLProject/PytorchProject', script_name...
<p>Pipeline script and training script can have different directory/file paths. Please check and specify the correct <strong>source</strong> and <strong>destination</strong> path of the download file.</p> <p>For example:</p> <blockquote> <p>run.download_file(name='outputs/my_output_file', output_file_path='my_destinati...
python|azure|pytorch|pipeline
0
375,936
71,303,481
Writing function including pandas query with numeric value in function cal
<p>I'm trying to write a function with two calls, one which is the data frame and the other which is some numeric value. I get the error that name &quot;t is not defined.&quot; When I hard code that numeric value, everything works well.</p> <p>Here is minimal reproducible example.</p> <pre><code>df = pd.DataFrame([[1, ...
<p>You could use an f-string to replace the value of the variable <code>t</code> in your query string instead of a literal <code>&quot;t&quot;</code> string:</p> <pre><code>l = df.query(f&quot;A == {t}&quot;) </code></pre> <hr /> <p>Complete code:</p> <pre><code>df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A',...
python|pandas|dataframe
2
375,937
71,233,779
How to create dataframe based on matrix?
<p>There are two dataframe I have &quot;df1&quot; and &quot;df2&quot; and one matrix &quot;res&quot;</p> <pre><code>df1= a df2 = a b c c e d </code></pre> <p>there are 4 record in df1 and 3 record in df2 so, res = 4*3 matrix</p> <pre><code>res = ...
<p>Set index and columns names by <code>df1, df2</code>:</p> <pre><code>res.index = df1[:len(res.index)] res.columns = df2[:len(res.columns)] </code></pre> <p>And then reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt...
python|pandas|python-2.7|nlp
1
375,938
71,246,570
Preserve Timestamp Column during Pandas Groupby
<p>I have a sizeable pandas df that I would like to aggregate by a Timestamp. The timestamps are on a granular scale(one second). Post aggregation, I would like the df to retain the first instance of that timestamp, but aggragated the following data by one minute periods.</p> <pre><code>Original: Timestamp Col...
<p>You can use:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;Timestamp&quot;] = pd.to_datetime(df[&quot;Timestamp&quot;]) df[&quot;Hour_Minute&quot;] = df[&quot;Timestamp&quot;].apply(lambda x: x.strftime(&quot;%Y-%m-%d %H:%M&quot;)) df.groupby(&quot;Hour_Minute&quot;).first() </code></pre>
python|pandas|pandas-groupby
1
375,939
71,192,010
Remove consecutive positive/negative numbers from a dataframe
<p>(EDITED) This is my current DataFrame:</p> <pre><code> aapl tigr srpt 4 58.254690 2475.247525 131.665569 5 56.869882 2386.634845 140.016802 6 -58.709564 -2597.402597 NaN 7 NaN 2314.814815 145.539223 8 -60.786578 NaN -154.822728 9 -57.780089 -2283.105023 -1...
<p>Use:</p> <pre><code>In [1481]: x = df.fillna(1)['aapl'].gt(0) In [1487]: ix = x[~x.eq(x.shift(1))].index In [1488]: df.loc[ix] Out[1488]: aapl tigr srpt 4 58.254690 2475.247525 131.665569 6 -58.709564 -2597.402597 -143.492610 7 NaN 2314.814815 145.539223 8 -60.786578 -2032.5...
python|pandas
0
375,940
71,294,644
Rolling Pandas unique values with same window size
<p>I would like to sum rolling unique values with same window count.</p> <p>as example if if have values 20,30,30,40 i want sum of (20,30,40)</p> <p><a href="https://i.stack.imgur.com/OL9kh.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>If the duplicates are grouped like your example you can try drop the duplicates in your dataframe using df.drop_duplicates() then apply .rolling(3).sum() to the new dataframe without any repeated values.</p> <pre><code>series = pd.Series([20, 30, 30,30,40, 50,50 , 60]) unique_series = series.drop_duplicates() unique...
pandas|cumsum
1
375,941
71,337,157
Split dataframe string (when string can hold n values of that cell variable), into multiple columns
<p>Currently working on a dataset with a lot of contact data, being Emails one of the variables.</p> <p>A cell in the Emails column can have more than one email (1 to n) and they are all separated by a comma and a space.</p> <p>For contacts with only two emails, the process would be quite straightforward. One can split...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a><a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.rsplit.html" rel="nofollow noreferrer"><code>Series.str.rsplit</code></a...
python|pandas|string|dataframe|split
1
375,942
71,439,153
Pandas groupby -> aggregate - function of two columns
<p>I'm using pandas <code>aggregate</code> as folows:</p> <pre><code>In [6]: gb = df.groupby(['col1', 'col2']) ...: counts = gb.size().to_frame(name='counts') ...: (counts ...: .join(gb.agg({'col3': 'mean'}).rename(columns={'col3': 'col3_mean'})) ...: .join(gb.agg({'col4': 'median'}).rename(columns={'col4...
<p>First create column <code>new</code> before <code>groupby</code> and then aggregate <code>sum</code>, your solution rewritten in named aggregation is:</p> <pre><code>counts = (df.assign(new = df['col3'] * df['col4']) .groupby(['col1', 'col2'], as_index=False) .agg(counts=('col1','size'), ...
python|pandas|aggregate
0
375,943
71,133,574
Efficient chaining of boolean indexers in pandas DataFrames
<p>I am trying to very efficiently chain a <strong>variable</strong> amount of boolean pandas Series, to be used as a filter on a DataFrame through boolean indexing.</p> <p>Normally when dealing with multiple boolean conditions, one chains them like this</p> <pre><code>condition_1 = (df.A &gt; some_value) condition_2 =...
<p>Use <code>np.logical_and</code>:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'A': [0, 1, 2], 'B': [0, 1, 2], 'C': [0, 1, 2]}) m1 = df.A &gt; 0 m2 = df.B &lt;= 1 m3 = df.C == 1 m = np.logical_and.reduce([m1, m2, m3]) # OR m = np.all([m1, m2, m3], axis=0) out = df[np.logical_and.reduce(...
python|python-3.x|pandas|dataframe|boolean-indexing
3
375,944
71,404,715
Reshape a pandas DataFrame by expanding it horizontally
<p>I have a DataFrame with 4000 rows and 5 columns.</p> <p>They are information from multiple excel workbooks that I read in to one single sheet. Now I want to rearrange them in a horizontal manner, basically every time the header of the original excel sheet appears in the data, I want to move it horizontally.</p> <pre...
<p>An alternative, provided that your dataframe looks like</p> <pre><code>data = { 'symbol': [1712, 1726, 1824, 1871, 1887, 1871, 1887, 1871, 1887], 'weight': [0.007871, 0.00765, 0.032955, 0.006443, 0.00784, 0.006443, 0.00784, 0.006443, 0.00784], 'lqdty': [7.023737, 3.221021, 3.475508, 4.615002, 6.678486, 4...
python|excel|pandas|dataframe|numpy
1
375,945
71,224,956
Get a count of occurrence of string in each row and column of pandas dataframe
<pre><code>import pandas as pd # list of paragraphs from judicial opinions # rows are opinions # columns are paragraphs from the opinion opinion1 = ['sentenced to life','sentenced to death. The sentence ...','', 'sentencing Appellant for a term of life imprisonment'] opinion2 = ['Justice Smith','This concerns a sent...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.count.html" rel="nofollow noreferrer"><code>pd.Series.str.count</code></a>:</p> <pre><code>counts = df.apply(lambda col: col.str.count('sentenc')) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; counts p1 p2 p3 p4 0 1 2 0 ...
python|pandas|dataframe
3
375,946
71,163,903
Convert pandas Columns in Rows using (melt doesn't work)
<p>How can I achieve this in pandas, I have a way where I take out each column as a new data frame and then so a insert in SQL but in that way if I have 10 columns I want to do the same I cannot make 10 data frames so I want to know how can I achieve it dynamically</p> <p>I have a data set where I have the following da...
<p><code>melt</code> <strong>does work</strong>, you just need a few extra steps for the exact output.</p> <p>Assuming &quot;Id&quot; is a column (if not, <code>reset_index</code>).</p> <pre><code>(df.melt(id_vars='Id', value_name='col1') .sort_values(by='Id') .drop('variable', axis=1) ) </code></pre> <p>Output:<...
python-3.x|pandas|dataframe
2
375,947
71,141,595
If a date column doesn't have a certain date, then do something
<p>I am trying to read from dataframe on <code>Date</code> column, if a certain date doesn't exist, then insert new data for that date.</p> <p>I've tried to googled on how to know if a return is none, but I can't find any result.</p> <p>So this is the way I handle it, if the return is <code>KeyError</code>, then I inse...
<p>You don't want to select rows based on a condition that is applied to the <code>index</code>.</p> <p>Make the 'date' a proper column, and write a proper mask/condition, e.g.</p> <pre><code>relevant_data = data[data['date'] &gt; pd.Timestamp.today()] </code></pre> <p>An explicit condition will allow you to contro...
python|pandas
1
375,948
71,221,975
Filter pandas dataframe rows based on multiple conditions
<p>This is my main dataframe that I want to filter.</p> <pre><code> first.seqnames first.start first.end first.width first.strand second.seqnames second.start second.end second.width second.strand 126457 chr1 10590184 10590618 GTTAATTATAGATAAATGGGCTAAAATTGCCTCTTGGTTTTGTAAC... * chr1 107...
<p>Assuming <code>df1</code> and <code>df2</code> the two dataframes, you can inner <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge.html" rel="nofollow noreferrer"><code>merge</code></a>:</p> <pre><code>df1.merge(df2, left_on=['first.seqnames', 'first.start', 'first.end'], right_o...
python-3.x|pandas|dataframe
1
375,949
71,285,825
Using create_tf_dataset_for_client() to define the training examples in the dataset
<p>I am preparing a dataset for federation settings, in the code below, I have multiple CSV files and used each is considered a single client.</p> <pre><code>dataset_paths = { 'client_0': '/content/drive/ds1.csv', 'client_1': '/content/drive/ds2.csv', 'client_2': '/content/drive/ds3.csv', 'client_3': '/content/...
<p>You can try something like this:</p> <pre><code>import tensorflow as tf # Create dummy data samples = 5 data = (tf.random.uniform((samples,), maxval=50, dtype=tf.int32), tf.random.uniform((samples,), maxval=50, dtype=tf.int32), tf.random.uniform((samples,), maxval=50, dtype=tf.int32), tf.ran...
python|tensorflow|tensorflow-datasets|tensorflow-federated|federated-learning
1
375,950
71,388,924
How can I use Tensorflow.Checkpoint to recover a previously trained net
<p>I'm trying to understand how to recover a saved/checkpointed net using <code>tensorflow.train.Checkpoint.restore</code>.</p> <p>I'm using code that's strongly based on Google's Colab tutorial for creating a pix2pix GAN. Below, I've excerpted the key portion, which just attempts to instantiate a new net, then to fill...
<p>The problem arose because tf.Checkpoint.restore needs the directory in which the checkpointed net is stored, not the specific file (or, what I took to be the specific file - ./weights/ckpt-40.data-00000-of-00001)</p> <p>When it is not given a valid directory, it silently proceeds to the next line of code, without up...
tensorflow|checkpointing
0
375,951
71,295,254
Writing excel work books to Google Cloud Storage bucket using Google Cloud Composer
<p>I have a requirement where I have to create excel workbook (.xlsx) with 2 different workbooks. But when storing the data into GCS bucket, getting file not found error. I was able to save .csv files successfully. Please find the below example</p> <pre class="lang-py prettyprint-override"><code> import pandas as pd...
<p>You are trying to access the bucket directly without using the <a href="https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python" rel="nofollow noreferrer">Google Cloud Storage API Client Libraries</a>. This is not a recommended approach. So try to use the Google Cloud Storage API Client ...
pandas|google-cloud-platform|google-cloud-storage|google-cloud-composer
1
375,952
71,343,980
Sum the values in selected rows of a data frame
<p>I have a list of dictionaries:</p> <pre><code>mylist = [{'Date': '01/02/2020', 'Value': '13'}, {'Date': '01/03/2020', 'Value': '2'}, {'Date': '10/3/2020', 'Value': '4'}, {'Date': '12/25/2020', 'Value': '2'}] </code></pre> <p>I wanted to sum the Values of the Date from 01/01/2020 to 01/04/2020. I tried the following ...
<p>From your data, convert values with the right type:</p> <pre><code>mylist = [{'Date': '01/02/2020', 'Value': '13'}, {'Date': '01/03/2020', 'Value': '2'}, {'Date': '10/3/2020', 'Value': '4'}, {'Date': '12/25/2020', 'Value': '2'}] df = pd.DataFrame(mylist).astype({'Date': 'datetime64', '...
python|pandas
3
375,953
71,422,639
How to load data from multiply datasets in pytorch
<p>I have two datasets of images - indoors and outdoors, they don't have the same number of examples.</p> <p>Each dataset has images that contain a certain number of classes (minimum 1 maximum 4), these classes can appear in both datasets, and each class has 4 categories - red, blue, green, white. Example: Indoor - cat...
<p>Assuming the question is:</p> <ol> <li>Combine 2+ data sets with potentially overlapping categories of objects (distinguishable by label)</li> <li>Each object has 4 &quot;subcategories&quot; for each color (distinguishable by label)</li> <li>Each batch should only contain a single object category</li> </ol> <p>The f...
pytorch|dataset|multiple-databases|dataloader
1
375,954
71,352,723
Sort Categorial values within groupby in pandas
<p>I have this example df:</p> <pre><code> df3 = pd.DataFrame({'Customer':['Sara','John','Didi','Sara','Didi' ,'Didi'], 'Date': ['15-12-2021', '1-1-2022' , '1-3-2022','15-3-2022', '1-1-2022' , '1-4-2022'], 'Month': ['December-2021', 'January-2022', 'March-2022','March-2022', 'Ja...
<pre><code>df3['Month'] = pd.to_datetime(df3['Month'], infer_datetime_format=True) df3 = df3.sort_values(by=[&quot;Month&quot;],ascending=False).groupby( ['Customer','Product','Month','Date']).agg({ 'status':'first'}).reset_index() df3['Month'] = df3['Month'].dt.strftime('%B-%Y') df3 </code></pre> <p>Your desi...
python|pandas|numpy|sorting
2
375,955
71,430,787
Looping through pandas value_counts()
<p>I'm manually looking for all values in my df columns like this (to search for weird entries):</p> <pre><code>df['sex'].value_counts(), df['famsize'].value_counts(), df['Pstatus'].value_counts(), df['traveltime'].value_counts()... </code></pre> <p>then i get:</p> <pre><code>(F 591 M 453 Name: sex, dtype: int6...
<p>I would just do:</p> <pre class="lang-py prettyprint-override"><code>for v in df.columns: print(df[v].value_counts()) </code></pre>
python|pandas|dataframe
1
375,956
71,302,832
Replace a specific value with another using Pandas
<p>I would like to replace a specific value or values with another value.</p> <p><strong>Data</strong></p> <pre><code>ID Date hi hello AA Q4.2022 1 0 BB Q4.2022 1 1 CC Q4.2022 HI111 1 </code></pre> <p><strong>Desired</strong></p> <pre><code>ID Date hi hello AA Q4.2022 1 0 BB Q4....
<p>Perhaps, the numbers are int types; then you could try <code>to_numeric</code> + <code>isna</code> and use it in <code>mask</code>:</p> <pre><code>df['hi'] = df['hi'].mask(pd.to_numeric(df['hi'], errors='coerce').isna(), '') </code></pre> <p>or if you want to change the type of the numbers to strings as well, you co...
python|pandas|dataframe|numpy
1
375,957
71,119,396
How to detect dips with pandas or numpy array when data has repetitions?
<p>I'm trying to find the position of dips and bumps in an array by checking that <code>n &lt; n-1</code> and <code>n &gt; n+1</code>.</p> <p>It is a valid approach, but it fails when data repeats before bouncing, e.g. <code>{100,80,80,100}</code>.</p> <p>See this example:</p> <pre><code>import numpy as np import panda...
<p>I got it:</p> <pre><code>from scipy.signal import find_peaks dips, bumps = find_peaks(-data), find_peaks(data) </code></pre>
python|arrays|pandas|numpy
1
375,958
71,167,116
Convert a column to a list of prevoius columns in a Dataframe
<p>I would like to create a column that is the form of a list of values from two previous columns, such as location that is made up of the long and lat columns.</p> <p><a href="https://i.stack.imgur.com/0fqSK.png" rel="nofollow noreferrer">This is what the DataFrame looks like</a></p>
<p>You can create a new columne based on other columns using <code>zip</code>, as follows:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ 'admin_port': ['NORTH SHIELDS', 'OBAN'], 'longitude': [-1.447104, -5.473469], 'latitude': [55.008766, 54.415695], }) df['ne...
pandas|dataframe
0
375,959
71,275,335
IndexError after trying to iter over rows and columns
<p>Imagine a table with rows and columns. I want to read the table row by row. I don't understand what has to get fixed and what's the best way to do so:</p> <pre><code>import pandas as pd num_rows = 4 num_cols = 5 value = &quot;test&quot; for i in range(num_rows): s = pd.Series() for c in range(num_cols): ...
<p>Use:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd num_rows = 4 num_cols = 5 value = &quot;test&quot; for i in range(num_rows): #here is the problem s = pd.Series(index=range(num_cols)) for c in range(num_cols): s[c] = value </code></pre>
python|pandas
2
375,960
71,273,200
Reading a CSV file into Pandas
<p>I have csv data that looks like this and I'm trying to read it into a pandas df and I've tired all sorts of combinations given the ample documentation online - I've tried things like:</p> <pre><code>pd.read_csv(&quot;https://www.nwrfc.noaa.gov/natural/nat_norm_text.cgi?id=TDAO3.csv&quot;, delimiter=',', skiprows=0, ...
<p>It is not link directly to file CSV but to page which displays it as HTML using tags <code>&lt;pre&gt;</code>, <code>&lt;br&gt;</code>, etc. and this makes problem.</p> <p>But you can use <code>requests</code> to download it as text.</p> <p>Later you can use standard <code>string</code>-functions to get text between...
python|pandas|csv
1
375,961
71,232,777
What does the result numbers mean in Tensorflow text_classification
<p>Tensorflow text_classification:</p> <p><a href="https://www.tensorflow.org/tutorials/keras/text_classification" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/keras/text_classification</a></p> <p>There are only two classes in this text_classification example,</p> <pre><code>Label 0 corresponds to neg...
<p>You should define a threshold that whenever you get a value greater than it it is considered as positive, otherwise it considers it as negative. In your example to get [1,1,0] a threshold of 0.4 for example gives the right predictions.</p>
python|tensorflow
1
375,962
52,023,257
Transpose or Pivot multiple columns in Pandas
<p>I would like to transpose multiple columns in a dataframe. I have looked through most of the transpose and pivot pandas posts but could not get it to work. </p> <p>Here is what my dataframe looks like.</p> <pre><code>df = pd.DataFrame() df['L0'] = ['fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'vegetable',...
<p>Add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> before <code>unstack</code>:</p> <pre><code>df = (df.groupby(['L0', 'L1', 'Type'])['A', 'B', 'C'] .sum() .stack() .unstack('Type') .reset_i...
python|pandas|pivot|transpose
2
375,963
52,266,397
Create new column in DataFrame from a conditional of a list
<p>I have a DataFrame like:</p> <pre><code>df = pd.DataFrame({'A' : (1,2,3), 'B': ([0,1],[3,4],[6,0])}) </code></pre> <p>I want to create a new column called test that displays a 1 if a 0 exists within each list in column B. The results hopefully would look like:</p> <pre><code>df = pd.DataFrame({'A' : (1,2,3), 'B'...
<p>This should do it for you:</p> <p><code>df['test'] = pd.np.where(df['B'].apply(lambda x: 0 in x), 1, 0)</code></p>
python|pandas|list|conditional
1
375,964
52,423,147
Difference of Pre-Padding and Post-Padding text when preprossing different text sizes for tf.nn.embedding_lookup
<p>I have seen two types of padding when feeding to embedding layers. </p> <blockquote> <p><strong>eg:</strong></p> <p>considering two sentences:</p> <p>word1 = "I am a dog person."</p> <p>word2 = "Krishni and Pradeepa both love cats."</p> <p>word1_int = [1,2,3,4,5,6] </p> <p>word2_int = [7,...
<p>Commonly, when we use LSTM or RNN's, we use the final output or the hidden state and pass it along to make predictions. You are also doing the same thing as seen in this line: </p> <pre><code>logit = tf.contrib.layers.fully_connected(hidden, num_outputs=20, activation_fn=None) </code></pre> <p>Here the two methods...
python-3.x|tensorflow|machine-learning|text-classification|word-embedding
1
375,965
52,107,914
Pandas - From list of dates, get the last date in each month
<p>I have a fairly simple question but can't find a clean pandas solution to it.</p> <p>Given a list of dates in a series like below:</p> <pre><code>LoadedDate 0 2016-02-18 1 2016-02-19 2 2016-02-20 3 2016-02-23 4 2016-02-24 5 2016-02-25 6 2016-02-26 7 2016-02-27 8 2016-03-01 9 2016-03-02 10 2016...
<p>You could use</p> <pre><code>In [300]: df.groupby(df.LoadedDate.astype('datetime64[M]')).last().reset_index(drop=True) Out[300]: LoadedDate 0 2016-02-27 1 2016-03-31 2 2016-04-30 3 2016-05-04 </code></pre> <p>Or,</p> <pre><code>In [295]: df.groupby(df.LoadedDate - pd.offsets.MonthEnd()).last().reset_index(drop=...
python|pandas|date
7
375,966
52,054,694
Appending list sometimes give 'IndexError: list index out of range' error and results in not as expected
<p>So i'm still new to programming and trying to implement an initialization method for a clustering problem using python-2.7.<br> The steps are: </p> <ol> <li>Pick a random data from dataset as first centroid</li> <li>While number of data in centroid &lt; n_klas : Calculate the data distance to the data in centroids...
<p>The <code>randint(a, b)</code> returns random integers from <code>a</code> to <code>b</code>, <em>including</em> <code>b</code>. So, when you use <code>randint(0, len(x))</code>, you might get the value <code>len(x)</code> as output, which is out of range when used as index. </p> <p>For your use case, you could pro...
python|python-2.7|pandas|cluster-analysis
2
375,967
52,441,474
Assign numbers to values of rows in a dataframe
<p>lets say i have a dataframe </p> <pre><code>A B C john I agree ryan II agree rose V strongly agree Shawn VI disagree </code></pre> <p>what i want to do is to assign numbers to C column values like this ?</p> <pre><code>A B C john I 1 ryan II 1 rose V 2 Shawn VI ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> by <code>dictionary</code>:</p> <pre><code>df['C'] = df['C'].map({'agree':1, 'strongly agree':2, 'disagree':0}) print (df) A B C 0 john I 1 1 ryan II 1 2 ros...
python|pandas|loops
3
375,968
52,228,639
pandas string replace any value of string after one rounded bracket "Only single Rounded bracket by python
<p>i need to replace any after "(" in pandas dataframe by "" </p> <pre><code>Tuscaloosa (University of Alabama &gt;&gt; Tuscaloosa and df['RegionName']= df['RegionName'].str.replace(r"\s+\(.*\"","") </code></pre> <p>not work</p>
<p>You can using <code>str.split</code></p> <pre><code>s Out[417]: 0 Tuscaloosa (University of Alabama &gt;&gt; Tuscaloosa 0 Tuscaloosa (University of Alabama &gt;&gt; Tuscaloosa 0 Tuscaloosa (University of Alabama &gt;&gt; Tuscaloosa 0 Tuscaloosa (University of Alabama &gt;&gt; Tuscaloosa dtype: object s...
python|pandas|dataframe
1
375,969
52,442,499
How to separate null and non-null containing rows into two different DataFrames?
<p>Say I have a big DataFrame (>10000 rows) that has some rows containing one or more nulls. How do I remove all the rows containing a null in one or more of its columns from the original DataFrame and putting the rows into another DataFrame?</p> <p>e.g.:</p> <p>Original DataFrame:</p> <pre><code> a b ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isna.html" rel="nofollow noreferrer"><code>DataFrame.isna</code></a> for checking missing values:</p> <pre><code>print (df.isna()) #print (df.isnull()) a b c 1 False False False 2 False False False 3 True F...
python|pandas|numpy|dataframe
2
375,970
52,229,059
EM score in SQuAD Challenge
<p>The <a href="https://rajpurkar.github.io/SQuAD-explorer/" rel="noreferrer">SQuAD Challenge</a> ranks the results against the F1 and EM scores. There is a lot of information about the F1 score (a function of precision and recall). But what would the EM score be?</p>
<blockquote> <p><strong>Exact match.</strong> This metric measures the percentage of predictions that match any one of the ground truth answers exactly.</p> </blockquote> <p>According to <a href="https://arxiv.org/pdf/1606.05250.pdf" rel="nofollow noreferrer">here</a>.</p>
tensorflow|machine-learning|deep-learning|stanford-nlp|reinforcement-learning
20
375,971
52,178,508
Can't install tensorflow on windows 7 32-bit
<p>I can't install TensorFlow in Windows 7, Python 3(32-bit, Lenovo ThinkPad X201s). When I type <code>pip3 install tensorflow</code>:</p> <pre><code>Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\sjkim&gt;pip3 install tensorflow Collecting tensorflow Co...
<p>TensorFlow is only tested and supported for 64-bit, x86 systems. I don't believe you can install TensorFlow through pip or conda normally from a 32-bit system. You CAN run a linux docker container thought docker for windows, but it is based on vm and it didn't support gpu.</p> <p>I have provided a 32 bit tensorflow...
python|tensorflow|windows-7
1
375,972
52,393,659
Pandas DataFrame check if column value exists in a group of columns
<p>I have a DataFrame like this (simplified example)</p> <pre><code>id v0 v1 v2 v3 v4 1 10 5 10 22 50 2 22 23 55 60 50 3 8 2 40 80 110 4 15 15 25 100 101 </code></pre> <p>And would like to create an additional column that is either 1 or 0. 1 if v0 value is in the values of v1 to v4, and...
<p>You can use the underlying <code>numpy</code> arrays for performance:</p> <p><strong><em>Setup</em></strong></p> <pre><code>a = df.v0.values b = df.iloc[:, 2:].values </code></pre> <hr> <pre><code>df.assign(out=(a[:, None]==b).any(1).astype(int)) </code></pre> <p></p> <pre><code> id v0 v1 v2 v3 v4 ou...
python|pandas|numpy|dataframe
15
375,973
52,087,985
TFLearn regression loss function is uninitialized
<p>I'm messing around trying to replicate the tflearn autencoder listed <a href="https://github.com/tflearn/tflearn/blob/master/examples/images/autoencoder.py" rel="nofollow noreferrer">here</a> in a Kaggle Kernel. The invocation looks like this:</p> <pre><code>class AutoEncoder(): def __init__(self, layers): ...
<p>You can try like this to fix this particular error. Move <code>fit</code> before the previous line. </p> <pre><code> self.decoding_model = tflearn.DNN(net) self.decoding_model.fit(X, X, n_epoch=20, batch_size=256) #encoding self.encoding_model = tflearn.DNN(self.encoder[-1], session=self.decoding_mo...
python|tensorflow|tflearn
0
375,974
52,012,587
Save Python data-frame as Table in Teradata
<p>I want to pull a table from Teradata as a Python data-frame. I know how to accomplish this step. Next I want to run algorithms on the data to transform it however I want. Once I am done with manipulating the data in Python, I want the resulting data-frame to be saved as a new table in Teradata so that I can perform ...
<p>One option is to use <a href="https://github.com/mark-hoffmann/fastteradata" rel="nofollow noreferrer"><code>fastterdata</code></a>, specifically the <code>load_table</code> function:</p> <pre><code>load_table(abs_path, df, table_name, env, db, connector = "teradata", clear_table=True) Loads a pandas dataframe fro...
python|sql|python-3.x|pandas|teradata
3
375,975
52,426,828
Boolean Dataframe filter for another Dataframe
<p>The following dataframe <code>df1</code> contains numerical values</p> <pre><code> IDs Value1 Value2 Value Value4 AB 1 1 1 5 BC 2 2 2 3 BG 1 1 4 1 RF ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html" rel="nofollow noreferrer"><code>np.any</code></a> per <code>index</code> (<code>axis=0</code>...
python|pandas|dataframe
3
375,976
52,222,676
pandas replace multiple values
<p>Below is sample dataframe</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'a': [1, 1, 1, 2, 2], 'b':[11, 22, 33, 44, 55]}) &gt;&gt;&gt; df a b 0 1 11 1 1 22 2 1 33 3 2 44 4 3 55 </code></pre> <p>Now I wanted to update/replace b values that are matched on a column from other dict ba...
<p>Here's one way. The idea is to calculate a cumulative count by group and use this to filter rows. Use <code>itertools.chain</code> to create a single array of values. Finally, use <code>pd.DataFrame.loc</code> and Boolean indexing to set values.</p> <pre><code>from itertools import chain count = df.groupby('a').cu...
python|pandas|dataframe
4
375,977
52,058,848
Tensorflow - Access weights while doing backprop
<p>I want to implement C-MWP as described here: <a href="https://arxiv.org/pdf/1608.00507.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1608.00507.pdf</a> in keras/tensorflow. This involves modifying the way backprop is performed. The new gradient is a function of the bottom activation responses the weight param...
<p>The gradient computation in TF is fundamentally per-operation. If the operation whose gradient you want to change is performed on the weights, or at least the weights are not far from it in the operation graph, you can try finding the weights tensor by walking the graph inside your custom gradient. For example, say ...
python|tensorflow|keras|backpropagation
0
375,978
52,285,621
How do deep learning frameworks such as PyTorch handle memory when using multiple GPUs?
<p>I have recently run into a situation where I am running out of memory on a single Nvidia V100. I have limited experience using multiple GPUs to train networks so I'm a little unsure on how the data parallelization process works. Lets say I'm using a model and batch size that requires something like 20-25GB of memory...
<p>You should keep model parallelism as your last resource and only if your model doesn't fit in the memory of a single GPU (with 16GB/GPU you have plenty of room for a gigantic model).</p> <p>If you have two GPUs, I would use data parallelism. In data parallelism you have a copy of your model on each GPU and each cop...
deep-learning|gpu|hardware|pytorch
3
375,979
52,378,987
Tensorflow dimensions /placeholders
<p>I want to run a neural network in tensorflow. I am trying to do email classification, so my training data is an array of count vectorized documents.</p> <p>Im trying to understand the dimensions for how I should input data into tensorflow. I am creating placeholders like this:</p> <p>X = tf.placeholder(tf.int64, [...
<p>A little unsure as to what your "#" symbols refer. This if often used to mean "number" in which case what you have written would be incorrect. To be clear you want to define your placeholders for X and Y as</p> <pre><code>X = tf.placeholder(tf.int64, [None, input_dimensions]) Y = tf.placeholder(tf.int64, [None, 1])...
tensorflow
1
375,980
52,009,202
Python Pandas compare values in multiple columns for partial duplicates and drop record
<p>I need to create a function/expression that compares multiple columns (<code>'Cust ID Count'</code>, <code>'Revenue'</code> and possibly <code>'Family Name'</code> for a record match and then keeps only the first record based on ascending order. Also, this function will be looking at 2 different scenarios where the...
<p>Try this:</p> <pre><code>(df.sort_values('Family Name') .drop_duplicates(['Cust ID Count', 'Revenue'], keep='first') .sort_index() .reset_index(drop=True)) </code></pre>
python|pandas
0
375,981
52,216,124
Deleting numpy subarray based off of first element in subarray
<p>I have a <code>numpy</code> array being generated from a function as follows</p> <pre><code> circles = [[ 56, 152, 26], [288, 300, 25], [288, 362, 25], [288, 238, 24], [318, 298, 45], [220, 366, 29]] </code></pre> <p>I want to check if all the values in the first element of each subarray are consistent (ma...
<p>A possible solution using <code>mode</code>: </p> <pre><code>&gt;&gt;&gt; from scipy.stats import mode &gt;&gt;&gt; eps = 5 &gt;&gt;&gt; most_freq = mode(circles[:, 0])[0][0] &gt;&gt;&gt; mask = np.abs(circles[:, 0] - most_freq) &lt;= eps &gt;&gt;&gt; circles[mask] array([[288, 300, 25], [288, 362, 25], [28...
python|numpy
2
375,982
52,300,777
pandas dataframe group by next occurance of column value
<p>Below is my dataframe</p> <pre><code> info date time file msg 0 INFO: 2018-09-12 16:10:10: view.py: phone 1 INFO: 2018-09-12 16:10:10: view.py: asdasd 2 INFO: 2018-09-12 16:10:43: view.py: contact start 3 INFO: 2018-09-12 16:10:43: view...
<p>Use a dictionary for a variable number of related variables. Here you can combine with <code>GroupBy</code> + <code>cumsum</code>:</p> <pre><code>d = dict(tuple(df.groupby(df['msg'].eq('phone').cumsum()))) </code></pre> <p>Then access your dataframes via <code>d[1]</code>, <code>d[2]</code>, ..., <code>d[n]</code>...
python|python-3.x|pandas|dataframe|pandas-groupby
1
375,983
52,263,225
Error converting data type float to datetime format
<p>I would like to convert the data type float below to datetime format:</p> <blockquote> <p>df</p> </blockquote> <pre><code> Date 0 NaN 1 NaN 2 201708.0 4 201709.0 5 201700.0 6 201600.0 Name: Cred_Act_LstPostDt_U324123, dtype: float64 </code></pre> <blockquote> <p>pd.to_datet...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>pd.Series.str.replace</code></a> to clean up your month data:</p> <pre><code>s = [x.replace('00.0', '01.0') for x in df['Date'].astype(str)] df['Date'] = pd.to_datetime(s, form...
python|pandas|datetime
0
375,984
52,273,801
Rotating Rows and columns pandas
<p>Hi i have been trying to figure out how to rotate my rows and columns.I tried using the transpose but it didnt work. My dataframe looks like this </p> <pre><code>Country | Rates 2015 | Rates2016 | Rates2017 | GDP 2015| GDP 2016 | GDP2017 World | 6 | 7 | 8 | 2355 | 1235 | 324325 </...
<p>Ensure that the transposed part is in the index. I can only assume that if you have tried <code>df.T</code> that you have not set the index correctly</p> <pre><code>In [185]: df.set_index('Country Name').T Out[185]: Country Name A B C 2000 5 2 ...
python|pandas
0
375,985
52,420,881
Getting index name for the max value in DF
<p>I have the following dataframe:</p> <pre><code>data = {'Algorithm': ['KNN', 'Decision Tree', 'SVM', 'Logistic Regression'], 'Jaccard': [0.75,0.65,0.67,0.70], 'F1-score': [0.69,0.78, 0.75, 0.77], 'LogLoss': ['NA', 'NA', 'NA', 5.23]} report= pd.DataFrame(data = data) report = report[['Algor...
<p>Try <code>np.where</code>:</p> <pre><code>print(report.index[np.where(report['Jaccard'].max())[0][0]]) </code></pre> <p>Updated Try <code>np.where</code>:</p> <pre><code>print(report['Algorithm'][np.where(report['Jaccard'].max())[0][0]]) </code></pre> <p>Or <code>idxmax</code>:</p> <pre><code>print(report['Jacc...
python|pandas|indexing|max
3
375,986
52,172,098
Getting average per minute in pandas
<p>There are already plenty of question on stack overflow regarding what i am asking but i have a small doubt and because of that i think my question is different. In my time series i want to get the average per minute. My time series is something like below:-</p> <pre><code> time duration...
<p>This is what <code>.resample()</code> is for:</p> <blockquote> <p><code>resample()</code> is a time-based groupby, followed by a reduction method on each of its groups.</p> </blockquote> <p>Verifiable example:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.random...
python|pandas|time-series|pandas-groupby
4
375,987
52,011,509
What is difference between tf.layers.conv2d and tf.layers.Conv2D?
<p>What is difference between <code>tf.layers.conv2d</code> and <code>tf.layers.Conv2D</code>?</p> <p>Why <code>tf.layers.Conv2D</code> used in example code in this <a href="https://arxiv.org/pdf/1807.03247.pdf" rel="nofollow noreferrer">paper</a>?</p> <p>Here is a full code snippet:</p> <pre><code>class AddCoords(b...
<p><code>tf.layers.conv2d</code> is a simple <code>function</code>/<code>method</code> to compute its input's convolution, so it needs input <code>feature maps</code> and <code>kernel</code> or <code>filter</code> to run this method. One user just call this method to computing convolution.<br> But <code>tf.layers.Conv2...
python|tensorflow
2
375,988
52,232,742
How to use ast.literal_eval in a pandas dataframe and handle exceptions
<p>I have a <code>dataframe</code> with a column containing a <code>tuple</code> data as a string. Eg. <code>'(5,6)'</code>. I need to convert this to a tuple structure. One way of doing it is using the ast.literal_eval(). I am using it in this way.</p> <pre><code>df['Column'] = df['Column'].apply(ast.literal_eval) </...
<p>I would do it simply requiring a string type from each entry:</p> <pre><code>from ast import literal_eval df['column_2'] = df.column_1.apply(lambda x: literal_eval(str(x))) </code></pre> <p>If You need to advanced Exception handling, You could do, for example:</p> <pre><code>def f(x): try: return lite...
python|pandas|tuples
12
375,989
52,011,190
What datetime format is this and how do I parse it?
<p>I have some data that I'm pulling from an API and the date is formatted like this: '1522454400000'</p> <p>Not sure how to parse it but this is what I have (unsuccessfully tried)</p> <pre><code>df = DataFrame(test) df.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'] df.set_index('Date') df.index = pd.to...
<p>This is almost certainly a variation on <a href="https://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">"Unix time"</a>: instead of seconds since the 1 Jan 1970 epoch, it's <em>milliseconds</em> since the 1 Jan 1970 epoch:</p> <pre><code>&gt;&gt;&gt; datetime.datetime.utcfromtimestamp(int('1522454400000') / 1000...
python|pandas|datetime|datetime-format|ccxt
9
375,990
52,249,639
Can pd.DataFrame.set_index mantain dtype?
<p>I am trying to call <code>df.set_index</code> in such a way that the <code>dtype</code> of the column I set_index on is the new <code>index.dtype</code>. Unfortunately, in the following example, set_index changes the <code>dtype</code>.</p> <pre><code>df = pd.DataFrame({'a': pd.Series(np.array([-1, 0, 1, 2], dtype=...
<p>Despite my bloviating in the comments above, this might suffice to get an appropriate index that is both low memory and starts from <code>-1</code>.</p> <h3><code>pandas.RangeIndex</code></h3> <p>Takes a start and stop parameters like <code>range</code></p> <pre><code>df = df.set_index(pd.RangeIndex(-1, len(df) -...
python|pandas
1
375,991
52,220,023
find duplicates and mark as variant
<p>I'm trying to create a data frame where I add duplicates as variants in a column.To further illustrate my question:</p> <p>I have a pandas dataframe like this:</p> <pre><code> Case ButtonAsInteger 0 1 130 1 1 133 2 1 42 3 2 165 4 2 158 5 2 157 6 3 158 7...
<p>This groups by all columns and returns the group index (+ 1 because zero based indexing is the default). I think this should be what you want.</p> <pre><code>id_df['Variant'] = id_df.groupby( id_df.columns.values.tolist()).grouper.group_info[0] + 1 </code></pre> <p>The resulting data frame, given your input da...
python|pandas|numpy|dataframe|duplicates
0
375,992
52,284,234
Two versions of Pandas causing problems
<p>It appears that when I run <code>&gt;conda list</code>, I have two versions of <code>pandas</code> installed. </p> <pre><code>pandas 0.23.4 py36h830ac7b_0 pandas 0.22.0 &lt;pip&gt; </code></pre> <p>I cannot run <code>import pandas</code> or <code>import pan...
<p>It will be hard for someone on SO to debug your exact issue: The fastest way to fix your particular problem is most likely a fresh install of <code>Anaconda</code>. Then to set up a <code>conda</code> environment in your fresh install.</p> <p>See the following:</p> <ul> <li><a href="https://conda.io/docs/user-guid...
python|pandas|numpy|version|conda
1
375,993
52,387,537
Understand tensorflow slice operation
<p>I am confused about the follow code:</p> <pre> import tensorflow as tf import numpy as np from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.framework import dtyp...
<p>The confusing thing here is that <code>tf.random_uniform</code> (like every random operation in TensorFlow) produces a new, different value on each evaluation call (each call to <code>.eval()</code> or, in general, each call to <code>tf.Session.run</code>). So if you evaluate <code>a_crop</code> you get one thing, i...
python|tensorflow
1
375,994
52,110,869
FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated use `arr[tuple(seq)]` instead of `arr[seq]`
<p>I would like not to use the non-tuple sequence for multidimensional indexing so that the script will support future release of Python when this changes.</p> <p>Below is the code that i am using for plotting the graph:</p> <pre><code>data = np.genfromtxt(Example.csv,delimiter=',', dtype=None, names=True, conve...
<p>I can reproduce the warning with:</p> <pre><code>In [313]: x = np.zeros((4,2)) In [315]: x[:,1] Out[315]: array([0., 0., 0., 0.]) </code></pre> <p>By replacing the <code>:</code> with a <code>slice(None)</code> we can write this indexing as:</p> <pre><code>In [316]: x[[slice(None),1]] /usr/local/bin/ipython3:1: F...
python|arrays|python-3.x|numpy|matplotlib
16
375,995
52,171,582
format conversion not working in calculating fiscal year based on the month
<p>I am trying to calculate the fiscal year based on my month. The conversion is not working. Currently my time stamp is type <code>object</code>. I have converted it to int to get the necessary values it does not work.</p> <pre><code>import pandas as pd upload_raw['Month_']= upload_raw['CREAT_TS'].str[:10] upload_raw...
<p>You can accomplish what you want using np.where()</p> <p>Based on your example, I've created a simplified dataframe to demonstrate. Note that I changed the final month to 7, so that we have an example where your condition evaluates to True.</p> <pre><code>df Out[74]: Month_ Year_ 0 6 18 1 6 ...
python|pandas
1
375,996
52,349,686
Error replacing values in a column using pandas
<p>I am trying to replace the values in a column with numbers. These are the unique values in the column:</p> <pre><code>['R2' '01' '02' 'C1'] </code></pre> <p>So I did this </p> <pre><code>data = pd.read_csv('file.csv') df = pd.DataFrame(data) df['rates'].apply({'R2': 1, '01' : 2, '02' : 3, 'C1' : 4}.get) </code><...
<p>Try <code>map</code>:</p> <pre><code>df['rates'].map({'R2': 1, '01' : 2, '02' : 3, 'C1' : 4},inplace=True) </code></pre> <p>Or:</p> <pre><code>df['rates'] = df['rates'].map({'R2': 1, '01' : 2, '02' : 3, 'C1' : 4}) </code></pre> <p>Actually your code works but need to assign:</p> <pre><code>df['rates']=df['rates...
python|pandas
1
375,997
52,372,690
Keep eliminating data points until good correlation coefficient is obtained
<p>I have been trying to find out a way in order to eliminate outliers from a dataset. The outliers are removed the following way: Any value which results into a 10% reduction in R2 value needs to be removed. When 4.2 in A-data set got replaced with 1.3 (in B-dataset), it changed the R2 >10% and thus was eliminated in ...
<p>You want <strong>robust linear regression</strong>, ignoring the outliers. Such a thing is already implemented in <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.HuberRegressor.html#sklearn.linear_model.HuberRegressor" rel="nofollow noreferrer">sklearn module</a> but since it's not amo...
python|python-3.x|numpy|scikit-learn|scipy
2
375,998
52,272,676
Combined group by using pandas
<p>Imagine a <code>pandas</code>data frame given by</p> <pre><code>df = pd.DataFrame({ 'id': range(1, 10), 'mfr': ('a', 'b', 'a', 'c', 'd', 'e', 'd', 'd', 'f'), 'vmn': ('A', 'A', 'B', 'C', 'D', 'E', 'F', 'F', 'D') }) </code></pre> <p>which gives the following table</p> <pre><code> id mfr vmn 0 1 a ...
<p>As suggested in the comments in the original post it can be solved by using <a href="https://networkx.github.io/" rel="nofollow noreferrer"><code>networkx</code></a>. </p> <pre><code>import networkx as nx import pandas as pd df = pd.DataFrame({ 'id': range(1, 10), 'mfr': ('a', 'b', 'a', 'c', 'd', 'e', 'd',...
python|pandas|pandas-groupby
0
375,999
52,421,405
AttributeError: exp when using numpy on data loaded using scipy.io.loadmat
<p>I get the following output from the unit test below:</p> <pre><code>[[array([[-1.57079633]])]] [[array([[0.+1.57079633j]])]] &lt;module 'numpy' from '/usr/local/lib/python2.7/dist-packages/numpy/__init__.pyc'&gt; E ====================================================================== ERROR: test_TestWECTrain_Basic...
<p>It turns out the answer is simple, these loaded variables were themselves oringinally matlab structures, and I was omitting the index when retrieving them, the correct thing to do is the following (note the extra [0,0]s when retrieving phase and sigma):</p> <pre><code>import unittest import os import scipy.io as si...
python|numpy
1