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,400
68,981,524
Synthetic timestamp pandas
<p>I need to add a timestamp to a dataframe with the following settings:</p> <pre><code>from datetime import datetime date_rng = pd.date_range(start='1/1/2020', end='1/21/2020', periods=len(df)) </code></pre> <p>I would like to know how to discard the miliseconds terms since I need to convert to this format <code>Jan...
<p>You can use <code>.floor('s')</code>:</p> <p>dummy example:</p> <pre><code>from datetime import datetime date_rng = pd.date_range(start='1/1/2020', end='1/21/2020', periods=12) date_rng.floor('s') </code></pre> <p>output:</p> <pre><code>DatetimeIndex(['2020-01-01 00:00:00', '2020-01-02 19:38:10', '202...
pandas|amazon-web-services|dataframe|amazon-quicksight
0
375,401
68,890,895
How to vectorize function that concatenates values in duplicated rows?
<p>I have a function that transforms table that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Year</th> <th>Period</th> <th>Duplicate</th> </tr> </thead> <tbody> <tr> <td>A9999</td> <td>2020</td> <td>23</td> <td>False</td> </tr> <tr> <td>A9999</td> <td>2019</t...
<p>You can use a combination of <code>groupby</code> and <code>agg</code> to get the &quot;Concat&quot; column, then merge to get the output:</p> <pre><code>df2 = (df.astype({'Year': str, 'Period': str}) .groupby('ID').agg({'Year': 'x'.join, 'Period': 'first'}) .apply('_'....
python|pandas
1
375,402
69,027,451
replace matrix elements with maximum value to symmetrize a matrix
<p>I have a matrix. I want to replace some elements of my matrix by applying the following condition: if <code>Xij&gt;Xji</code> or viceversa, replace the minimum value with the maximum value. For example:</p> <pre><code>Input_array = [[1, 5, 3], [1, 10, 2], [0, 9, 16]] </code></pre> <p>I ...
<pre><code>import numpy as np arr = np.array([[1, 5, 3],[1, 10, 2],[0, 9, 16]]) arr_sym = np.where(arr &gt; arr.T, arr, arr.T) print(f'arr_sym = \n{arr_sym}') </code></pre> <p>output:</p> <pre><code>arr_sym = [[ 1 5 3] [ 5 10 9] [ 3 9 16]] </code></pre>
python|numpy|matrix
2
375,403
69,033,605
how sort rows with respect of a group?
<p>Hi i have panda data frame. I wana sort data with respect of a group id and sorting with respect of order</p> <pre><code>id title order 2 A 2 2 B 1 2 C 3 3 H 2 3 T 1 </code></pre> <p>out put:</p> <pre><code>id title order 2 ...
<p>Since you're not aggregating, you can sort by multiple columns to get the output you want.</p> <pre><code>import pandas as pd df = pd.DataFrame({'id': [2, 2, 2, 3, 3], 'title': ['A', 'B', 'C', 'H', 'T'], 'order': [2, 1, 3, 2, 1]}) df = df.sort_values(by=['id', 'order']) print(d...
python|pandas|sorting
2
375,404
69,109,929
How to write value from a dataframe column to another column based on a condition?
<p>I'm having a bad time here trying to figure out how to set a column based on a condition. Basically, I want to copy the value from my &quot;Customer&quot; column to the rows of my &quot;Call Ref&quot; column, if the row is different from &quot;Enterprise&quot; and &quot;Client&quot;.</p> <p>Here is the code I'm tryi...
<p>Not shure if this is what you really want to do because you didn't provide an example of your input and output data frames but as far as I understand it I made a toy example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame([['A','Enterprise'], ['B','Client'], ...
python|pandas|dataframe
0
375,405
69,222,172
How to use pandas and Numpy data transformations within a Python function?
<p>I am trying to perform some simple transformations using pandas and NumPy inside a function. The transformations required are:</p> <ol> <li>Remove 'Verified' column from df</li> <li>Convert array into a dataframe (df2)</li> <li>Merge the two dfs together</li> </ol> <p>I've copied my code below. It works fine outside...
<p>If I understand you correctly, you want to merge the <code>df</code> (without <code>Verified</code> column) and the <code>array</code>:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( [[1, &quot;John&quot;, True], [2, &quot;Ann&quot;, False]], columns=[&quot;Id&quot;, &quot;Login&quot;, &q...
python|pandas|dataframe|numpy
0
375,406
69,295,546
Fill dataframe with duplicate data until a certain conditin is met
<p>I have a data frame df like,</p> <pre><code>id name age duration 1 ABC 20 12 2 sd 50 150 3 df 54 40 </code></pre> <p>i want to duplicate this data in same df until the duration sum is more than or equal to 300,</p> <p>so the df can be like..</p> <pre><code>id name age duration 1 ABC 20 12 2 sd 5...
<p>Try using <code>n</code> instead of <code>frac</code>.</p> <p><code>n</code> randomly sample n rows from your dataframe.</p> <pre><code>sample_df = df.sample(n=1).reset_index(drop=True) </code></pre> <p>To use <code>frac</code> you can rewrite your code in this way.</p> <pre><code>def fillPlaylist(df,duration): ...
python-3.x|pandas|dataframe|data-science
1
375,407
68,919,999
Pandas: How to transform nested json with dynamic keys and arrays to pandas dataframe
<p>How to transform nested json with dynamic keys and arays to pandas dataframe?</p> <ul> <li>Static keys: <code>data</code>, <code>label</code>, <code>units</code>, <code>date</code>, <code>val</code>, <code>num</code> (can be hardcoded)</li> <li>Dynamic keys/arrays: <code>data_1_a</code>, <code>data_1000_xyz</code> ,...
<h2>Python Pandas solution:</h2> <pre><code> import pandas as pd # 1) flatten json df = pd.json_normalize(json_1) df_dic = df.to_dict('records') # 2) split to levels data = [] for row in df_dic: k={} for item in row.items(): if item[0] == 'id': ...
python|json|pandas|dataframe
1
375,408
69,276,726
pandas sum of column based on index
<p>How to sum pandas columns based on index choice</p> <pre><code> 'A' 'B' </code></pre> <hr /> <pre><code>'G9' 15 16 </code></pre> <hr /> <pre><code>'G10' 20 30 </code></pre> <hr /> <pre><code>'G9PRO' 1 11 </code></pre> <p>if I choose 'G9' I want to get this dataFrame</p> <pre><code> 'logs'...
<p>You can use <code>df.index.isin()</code> and <code>.sum()</code> to generate the results you need</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'A': [15, 20, 1], 'B': [16, 30, 11] }, index=['G9', 'G10', 'G9PRO']) df </code></pre> <p>Test Case #1</p> <pre><code>selected = ['G9', 'G10'] sum_df = df[d...
python|pandas
2
375,409
68,941,407
pandas append row in a loop
<p>i need to add column and append rows to a dataframe by searching a text file and adding the occurrences</p> <p>below is my input dataframe 'dfl'</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>TextID</th> <th>Type</th> <th>Term</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>fname</td> <...
<p>You can save the 'match' values in a list, and when you are done, create the new column using that list:</p> <pre><code>target_string = [] words = [] match_list = [] s1 = '' for index, row in dfl.iterrows(): words = row['Term'] field_name = row['Type'] path = &quot;C:\\Users\\myfolder\\&quot;+str(row['ch...
python|pandas|dataframe
2
375,410
69,230,570
How to do batched dot product in PyTorch?
<p>I have a input tensor that is of size <code>[B, N, 3]</code> and I have a test tensor of size <code>[N, 3]</code> . I want to apply a dot product of the two tensors such that I get <code>[B, N]</code> basically. Is this actually possible?</p>
<p>Yes, it's possible:</p> <pre><code>a = torch.randn(5, 4, 3) b = torch.randn(4, 3) c = torch.einsum('ijk,jk-&gt;ij', a, b) # torch.Size([5, 4]) </code></pre>
pytorch
1
375,411
68,996,646
Scraping tables using Pandas read_html and identifying headers
<p>I am completely new to web scraping and would like to parse a specific table that occurs in the SEC filing DEF 14A of companies. I was able to get the right URL and pass it to panda. Note: Even though the desired table should occur in every DEF 14A, it's layout may differ from company to company. Right now I am stru...
<p>The table <code>html</code> is rather messed up. The empty cells are actually in the source code. It would be easiest to do some post processing:</p> <pre><code>import pandas as pd import requests r = requests.get(&quot;https://www.sec.gov/Archives/edgar/data/1000229/000095012907000818/h43371ddef14a.htm&quot;, head...
python|pandas|web-scraping
1
375,412
68,910,605
Pandas: how to parse values from column
<p>I have a somewhat large dataframe, formatted something like this:</p> <pre><code>colA colB 1 c, d 2 d, e, f 3 e, d, a </code></pre> <p>I want to get a dictionary that counts instances of unique values in colB, like:</p> <pre><code>a: 1 c: 1 d: 3 e: 2 f: 1 </code></pre> <p>My naive solution would be to i...
<p>Try with <code>explode</code> and <code>value_counts</code>:</p> <pre><code>&gt;&gt;&gt; df[&quot;colB&quot;].str.split(&quot;, &quot;).explode().value_counts().to_dict() {'d': 3, 'e': 2, 'c': 1, 'f': 1, 'a': 1} </code></pre> <h6>Input <code>df</code>:</h6> <pre><code>df = pd.DataFrame({&quot;colA&quot;: [1, 2, 3], ...
python|pandas|dataframe|iteration|counter
1
375,413
69,145,555
Pandas - extract method not matching anything
<p>I am having a problem with this seemingly easy task to do. Here 's a recreation of my problem:</p> <p>I have a dataframe called legal of this form:</p> <pre><code>+----+-----------------+ | | legal | |----+-----------------| | 0 | gmbh | | 1 | kg | | 2 | ag | | 3...
<p><code>str.extract()</code> does not recognize regex pattern with <code>/i</code> to indicate IGNORECASE. To solve this, you can do it in 2 ways:</p> <p><strong>Method 1:</strong> Change your definition of <code>legal_pattern</code> without the <code>/</code> and <code>/ig</code>:</p> <pre><code>legal_pattern = '(' +...
python|regex|pandas
1
375,414
68,986,597
DataFrame Pandas - How can I split a list of dictionary from each row to separated columns?
<p>I have the DataFrame below with 2 columns, and one of the columns is a list of dictionary inside an list of dictionary. I would like to split/separate this column in several columns.</p> <pre><code>import pandas as pd USERNAME = ['root', 'user1', 'user2','user3'] test_data = '[{&quot;conjunction&quot;:&quot;and&quo...
<p>It seems like the column <code>VALUE_STRING</code> contains json data, in that case we can parse the json data using <code>loads</code> method of <code>json</code> module, then extract the dictionaries associated with the key <code>expressions</code> from each row, create a new dataframe from these dictionaries and ...
python|pandas|dataframe
1
375,415
68,886,615
What is the calculation process of loss functions in multi-class multi-label classification problems using deep learning?
<p>Dataset description:</p> <p>(1) X_train: <code>(6000,4)</code> shape</p> <p>(2) y_train: <code>(6000,4)</code> shape</p> <p>(3) X_validation: <code>(2000,4)</code> shape</p> <p>(4) y_validation: <code>(2000,4)</code> shape</p> <p>(5) X_test: <code>(2000,4)</code> shape</p> <p>(6) y_test: <code>(2000,4)</code> shape<...
<p><strong>Mistake 1</strong> - The shape of <code>y_train</code>, <code>y_validation</code> and <code>y_test</code> should be <code>(6000,)</code>, <code>(2000,)</code> and <code>(2000,)</code> respectively.</p> <p><strong>Mistake 2</strong> - For multi-class classification, the loss should be <code>categorical_crosse...
python|tensorflow|machine-learning|keras|deep-learning
0
375,416
68,983,852
Pandas UDF Function Takes Unusually Long to Complete on Big Data
<p>I'm new to PySpark and Pandas UDFs, I'm running the following Pandas UDF Function to jumble a column containing strings (For Example: an input '<em>Luke</em>' will result in '<em>ulek</em>')</p> <pre><code>pandas_udf(&quot;string&quot;) def jumble_string(column: pd.Series)-&gt; pd.Series: return column.apply(lambd...
<p>As the <code>.apply</code> method is not vectorized, the given operation is done by looping through the elements which slows down the execution as the data size becomes large.</p> <p>For small sized data, the time difference is usually negligible. However, as the size increases, the difference starts to become notic...
python|pandas|pyspark|user-defined-functions
1
375,417
68,899,113
Using schema and table arguments in Pandas read_sql parameters
<p>I want to run the query <code>select count(?) from ?.?;</code> using pandas' <code>read_sql()</code> method with the parameters <code>select count(&lt;column_name&gt;) from &lt;schema_name&gt;.&lt;table_name&gt;;</code>.</p> <p>I get the error <code>ValueError: ('Could not connect to db.', DatabaseError('Execution f...
<p><code>Pyodbc</code> doesn't support parameterizing SQL identifiers like schemas and tables. The library <code>psycopg2</code> will allow you to create SQL strings dynamically with these types of identifiers. By following these docs on the <a href="https://www.psycopg.org/docs/sql.html" rel="nofollow noreferrer">psyc...
sql|pandas|postgresql|dataframe|query-parameters
0
375,418
69,151,019
How to solve the problem with tf.keras.optimizers.Adam(lr=0.001) command not working?
<p>I'm working on Google Colab and when I type</p> <p><code>model.compile(optimizer=tf.keras.optimizers.Adam(lr=1e-6), loss=tf.keras.losses.BinaryCrossentropy())</code></p> <p>it doesn't work and I get the following error message</p> <p><code>Could not interpret optimizer identifier: &lt;keras.optimizer_v2.adam.Adam ob...
<p>Generally, Maybe you used a different version for the layers import and the optimizer import. tensorflow.python.keras API for model and layers and keras.optimizers for SGD. They are two different Keras versions of TensorFlow and pure Keras. They could not work together. You have to change everything to one version. ...
python|tensorflow|keras|tf.keras|adam
1
375,419
68,941,232
Pandas: How to explode data frame with json arrays
<p>How to explode pandas data frame?</p> <p>Input df:</p> <p><a href="https://i.stack.imgur.com/K4Se9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K4Se9.png" alt="enter image description here" /></a></p> <p>Required output df:</p> <pre><code>+----------------+------+-----+------+ |level_2 ...
<p><code>Explode</code> the dataframe on <code>value</code> column, then <code>pop</code> the <code>value</code> column and create a new dataframe from it then <code>join</code> the new frame with the exploded frame.</p> <pre><code>s = df.explode('value', ignore_index=True) s.join(pd.DataFrame([*s.pop('value')], index=...
python|json|pandas|dataframe
6
375,420
69,218,874
Why is 'metrics = tf.keras.metrics.Accuracy()' giving an error but 'metrics=['accuracy']' isn't?
<p>Im using the given code example on the fashion_mnist dataset. It contains <code>metrics=&quot;accuracy&quot;</code> and runs through. Whenever I change it to <code>metrics=tf.keras.metrics.Accuracy()</code> it gives me following error:</p> <pre><code>ValueError: Shapes (32, 10) and (32, 1) are incompatible </code></...
<p>Based on the docs <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#compile" rel="nofollow noreferrer">here</a>:</p> <blockquote> <p>When you pass the strings <code>&quot;accuracy&quot;</code> or <code>&quot;acc&quot;</code>, we convert this to one of <code>tf.keras.metrics.BinaryAccuracy</code>, <c...
python|tensorflow|machine-learning|keras
2
375,421
69,173,640
How to get the coefficients of the polynomial in python
<p>I need to create a function <code>get_polynom</code> that will take a list of tuples <code>(x1, y1), (x2, y2), ..., (xn, yn)</code> representing points and find the coefficients of the polynomial <code>c0, c1, ..., cn</code>.</p> <p>I can't manage to understand the task, the only tip I have is the provided part of t...
<p>A polynomial is a function <code>f(x) = cn x^n + ... + c1 x + c0</code>. With the pair of tuples you get n+1 equations of the form <code>f(xi) = yi</code> for i going from 1 to n+1. If you substitute <code>xi</code> and <code>yi</code> in the first equation, you obtain a linear system of n equations, with the unknow...
python|numpy|polynomials|coefficients
1
375,422
69,108,115
custom padding in convolution layer of tensorflow 2.0
<p>In Pytorch, nn.conv2d()'s padding parameter allows a user to enter the padding size of choice(like p=n). There is no such equivalent for TensorFlow. How can we achieve similar customization?. Would be much appreciated if a small network is designed, using the usual CNN layers like pooling and FC, to demonstrate how ...
<p>You can use <code>tf.pad</code> followed by a convolution with no (&quot;valid&quot;) padding. Here's a simple example:</p> <pre><code>inp = tf.keras.Input((32, 32, 3)) # e.g. CIFAR10 images custom_padded = tf.pad(inp, ((0, 0), (2, 0), (2, 0), (0, 0))) conv = tf.keras.layers.Conv2D(16, 3)(custom_padded) # default p...
python-3.x|tensorflow|keras|deep-learning|tensorflow2.0
2
375,423
68,910,105
Trying to save a model to a pb file and I don't have a .meta file
<p>I trained a custom object detector model through TensorFlow object detection module and I used mobilenetssd as my pretrained model. After training was done, I have three files:</p> <pre><code> checkpoint ckpt-11.data-00000-of-00001 ckpt-11.index </code></pre> <p>Additionally I have this file as well:</p> <pre><code>...
<p>You can load the model with the above files only.</p> <p>The model will load weights based on the <code>index file ckpt-11.index</code> and <code>shard file ckpt-11.data-00000-of-00001</code></p> <p>Basically, <code>shard</code> file will contain the model weights and the <code>index</code> file indicates which weig...
python|tensorflow|object-detection
1
375,424
68,891,221
TypeError: swaplevel() got an unexpected keyword argument 'axis'
<p>i am kind of new to pandas, i am using <code>unstack</code> and <code>swaplevel</code> to pivot my dataframe and i am getting this error :</p> <blockquote> <p>TypeError: swaplevel() got an unexpected keyword argument 'axis'</p> </blockquote> <p>i have checked the pandas doc and the fucntion does take axis as argumen...
<p><code>swaplevel(i=- 2, j=- 1, axis=0)</code> does have an axis argument, i may have to see your code to be able to trace your error.</p> <p>On the other-hand, maybe you should try to use swaplevel for each axis individually. for example :</p> <pre><code>In [1]: df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b'...
python-3.x|pandas
0
375,425
69,053,558
How to remove NaN in subtracting?
<p>I am trying to perform subtraction in python. This is a simple task when performed in excel but I want to do this in jupyter notebook.</p> <p>Below is my code:</p> <pre><code>import pandas as pd from sklearn import linear_model import numpy as np #Read X1 anomaly X1= pd.read_csv (r'file\X1.csv') X1 = pd.DataFrame(...
<p>I found this answer after experimenting with the codes and I want to share them with you in case someone is experiencing similar issue.</p> <pre><code>regr = linear_model.LinearRegression() regr.fit(X1.values.reshape(-1,1), X2) Trend=regr.coef_*X1+regr.intercept_ X3=X2-np.array(Trend) print (X3) </code></pre> <p>Not...
numpy|jupyter-notebook|regression|subtraction
0
375,426
69,247,515
How to apply a function with several variables to a column of a pandas dataframe (when it is not possible to change the order of vars in func)
<p>I would like to apply a func to a column of pandas DataFrame. Such func takes one string and one column of the DF.</p> <p>As follows:</p> <pre><code>def check_it(language,text): print(language) if language == 'EN': result = 'DNA' in text else: result ='NO' return result df = pd.DataFr...
<p>You can always create a lambda, and in the body, invoke your function as needed:</p> <pre><code>df['col_3']=df['col_2'].apply(lambda text: check_it('EN', text)) df ID col_1 col_2 col_3 0 1 DNA sdfsf sdf s False 1 2 sdgasdf DNA True 2 3 sdfsdf sdgasdf False </code></pre>
python|pandas|apply
2
375,427
69,167,227
convert entire column with seconds to hours (pandas)
<p>there is such a dataframe</p> <pre><code> x laikas_s 0 meh 5237 1 elec 20925 </code></pre> <p>I want to get such a dataframe</p> <pre><code> x laikas_s 0 meh 1:27:17 1 elec 5:48:45 </code></pre> <p>in python i would translate it like this</p> <pre><code>import datetim...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>pd.to_timedelta()</code></a> and specify the unit as second, as follows:</p> <pre><code>df['laikas_s'] = pd.to_timedelta(df['laikas_s'], unit='S') </code></pre> <p>Result:</p> <pr...
python|python-3.x|pandas|dataframe
3
375,428
69,280,095
numpy arange functon throws AttributeError: while the same code gets executed over online ide
<p>This is very strange. The np.arange function throws an AttributeError while i execute the code on my computer but it works fine over the <a href="https://mybinder.org/v2/gh/spyder-ide/spyder/5.x?urlpath=/desktop" rel="nofollow noreferrer">online ide</a>. code is very simple : trange = np.arange(0,180,(12/60))</p> <p...
<p>Search in your code where you have set <code>np = ...</code></p> <p>Reproducible error:</p> <pre><code>import numpy as np np = 12.3 trange = np.arange(0, 180, (12/60)) </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>----&gt; 5 trange = np.arange(0, 180, (12/60)) AttributeError: 'float...
python|numpy
0
375,429
69,185,427
Combining three datasets removing duplicates
<p>I've three datasets:</p> <p><strong>dataset 1</strong></p> <pre><code>Customer1 Customer2 Exposures + other columns Nick McKenzie Christopher Mill 23450 Nick McKenzie Stephen Green 23450 Johnny Craston Mary Shane 12 Johnny Craston Stephen Green ...
<p>After concatenating the dataframe df1 and df2 (assuming they have same columns), we can remove the duplicates using <code>df1.drop_duplicates(subset=['customer1'])</code> and then we can join with <code>df2</code> like this</p> <pre><code>df1.set_index('Customer1').join(df2.set_index('Customer')) </code></pre> <p>In...
python|pandas
1
375,430
68,882,592
scraping all the data from attribute <a>
<p>This is the code I have written so far I need to get all the ids from the page. <a href="https://i.stack.imgur.com/6JFb0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6JFb0.png" alt="enter image description here" /></a></p> <pre><code>import requests import pandas as pd from bs4 import Beautiful...
<p>Is this what you want?</p> <pre><code>import requests import pandas as pd from bs4 import BeautifulSoup url = &quot;https://bugzilla.mozilla.org/buglist.cgi?quicksearch=all&quot; soup = BeautifulSoup(requests.get(url).content, &quot;html.parser&quot;) ID = soup.find_all(&quot;a&quot;) data =[] for name in ID: if ...
python-3.x|pandas|web-scraping|beautifulsoup
1
375,431
69,099,426
how to write a function to filter rows based on a list values one by one and make analysis
<p>I have a list contains more than 10 values and I have a full dataframe. I'd like to filter each value from the list to a subdataframe and do some analysis on each of them. How can I write a function so I don't need to copy paste and change value so many times.</p> <p>eg.</p> <pre><code>list = ['A','B','C'] df1 = df...
<p>First many DataFrames is here not necessary.</p> <p>You can filter only necessary values for <code>column1</code> and pass both columns to <code>groupby</code>:</p> <pre><code>L = ['A','B','C'] s = df1[df1['column1'].isin(L)].groupby(['column1', 'column2']).size() </code></pre> <p>Last select by values of list:</p>...
python|pandas|dataframe|filter
0
375,432
69,004,997
Pandas DataFrame Time index using .loc function error
<p>I have created DataFrame with DateTime index, then I split the index into the Date index column and Time index column. Now, when I call for a row of a specific time by using pd.loc(), the system shows an error.</p> <p>Here're an example of steps of how I made the DataFrame from beginning till reaching my considerati...
<h3>1. If you want to use <code>.loc</code>, you can just specify the time by:</h3> <pre><code>import datetime df.loc[(slice(None), datetime.time(11, 0)), :] </code></pre> <p>or use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.IndexSlice.html" rel="nofollow noreferrer"><code>pd.IndexSlice...
python|pandas|dataframe|datetime|indexing
1
375,433
69,288,920
String formatting of data in column of pandas dataframe
<p>How can I remove <code>'$'</code> in a column values?<br /> <strong>Example</strong>: I have a column with values like <code>$40</code>, <code>$23</code>, <code>$35</code>,<br /> I want to see those column values like <code>40</code>, <code>23</code>, <code>35</code>.</p> <p>I have already tried:</p> <pre><code>DF_[...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.replace.html#pandas.Series.replace" rel="nofollow noreferrer"><code>Series.replace</code></a> replaces all values in the column that <em>exactly match</em> the first argument. You want <a href="https://pandas.pydata.org/pandas-docs/st...
python|pandas|dataframe
3
375,434
69,045,906
How to access a specific column and also random simultaneously
<p>Accessing column in pandas.</p> <p>How to access a single column and multiple random columns in pandas data frame?. if I have 6 columns ['a', 'b', 'c', 'd', 'e', 'f'] how can I access column 'a' and the remaining 3 are random. I try using <code>df.sample()</code> but it will show random column and column 'a' not aut...
<p>Use <code>set_index</code> with <code>sample</code>:</p> <pre><code>&gt;&gt;&gt; df.set_index('a').sample(3, axis=1).reset_index() a d e b 0 1 4 5 2 1 7 10 11 8 2 13 16 17 14 3 19 22 23 20 4 25 28 29 26 </code></pre>
python|pandas|dataframe
2
375,435
68,961,523
Best method to cluster coordinates around set centroids (Improving Scikit K-Means output? Naive methods?)
<p>So basically I have two lists of coordinates, one with &quot;home&quot; points (centroids essentially) and one with &quot;destination&quot; points. I want to cluster these &quot;destination&quot; coordinates to the closest &quot;home&quot; points (as if the &quot;home&quot; points are centroids). Below is an example...
<p>You can use e.g. <code>scipy.spatial.KDTree</code>.</p> <pre><code>from scipy.spatial import KDTree import numpy as np # sample arrays with home and destination coordinates np.random.seed(0) home = np.random.rand(10, 2) destination = np.random.rand(50, 2) kd_tree = KDTree(home) labels = kd_tree.query(destination)[...
python|numpy|scikit-learn|coordinates|k-means
0
375,436
69,171,951
How to calculate the average of specific values in a column in a pandas data frame?
<p>My pandas data frame has 11 columns and 453 rows. I would like to calculate the average of the values in rows 450 to 453 in column 11. I would then like to add this 'average value' as a new column to my dataset.</p> <p>I can use <code>df['average']= df[['norm']].mean</code></p> <p>To get the average of column 11 (he...
<p>Here you go:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;average&quot;] = df[&quot;norm&quot;][450:].mean() </code></pre> <p>Demo:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df = pd.DataFrame({&quot;a&quot;: [1, 2, 6, 2, 3]}) &gt;&gt;&gt; df a 0 1 1 2 2 6 3 2 4 3 &gt;&...
python|pandas|dataframe
1
375,437
69,266,482
Create list of words and group them by index
<p>I have column of index and each index has it's corresponding word:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>word</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>word1</td> </tr> <tr> <td>1</td> <td>word2</td> </tr> <tr> <td>1</td> <td>word3</td> </tr> <tr> <td>2</td> <...
<pre><code># Import Dependencies import pandas as pd # Create DataFrame data = {'id': [1, 1, 1, 2, 2], 'word': ['word1', 'word2', 'word3', 'word4', 'word5']} df = pd.DataFrame(data) # Groupby and Merge df = df.groupby('id', as_index=False).agg({'word' : ','.join}) </code></pre> <pre><code># Result id word 0 ...
python|pandas|list|group-by|aggregation-framework
2
375,438
69,175,617
Getting a numpy array string from a csv file and converting it to a numpy array
<p>I made some calculations with my data and saved it into a csv file. In the file I have a cell with this string:</p> <pre><code>&quot;[array([3, 3, 3]), array([3, 3, 3]), array([3, 3, 3]), array([3, 3, 3]), array([3])]&quot; </code></pre> <p>I want to convert it to a valid numpy array. Tried some functions but got no...
<p>If you have pandas, use <code>pd.eval</code>:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; from numpy import array &gt;&gt;&gt; pd.eval(&quot;[array([3, 3, 3]), array([3, 3, 3]), array([3, 3, 3]), array([3, 3, 3]), array([3])]&quot;) [array([3, 3, 3]), array([3, 3, 3]), array([3, 3, 3]), array([3, 3,...
python|arrays|numpy|csv
2
375,439
68,926,975
Filter or selecting data between two rows in pandas by multiple labels
<p>So I have this df or table coming from a pdf tranformation on this way example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>ElementRow</th> <th>ElementColumn</th> <th>ElementPage</th> <th>ElementText</th> <th>X1</th> <th>Y1</th> <th>X2</th> <th>Y2</th> </tr> </thead> <tbody...
<p>It's a bit ugly, but this should do it. Basically you don't need the first or last two rows, so if you get rid of those, then pivot the X1 and ElemenTex columns you will be pretty close. Then it's a matter of getting rid of null values and promoting the first row to header.</p> <pre><code>df = df.iloc[1:-2][['Elem...
python|pandas|numpy|loops|slice
1
375,440
69,138,494
Pandas - Assign string values based on multiple ranges
<p>I have created a small function to assign a string value to a column based on ranges from another column ie: 3.2 == '0-6m', 7 == '6-12m' But I am getting this error: <code>TypeError: 'float' object is not subscriptable</code></p> <p>Dataframe</p> <pre><code> StartingHeight 4.0 3.2 8.0 ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a>:</p> <pre><code>df['height_factor'] = pd.cut(df['StartingHeight'], bins=[0, 6, 12, 18, 24, 30, np.inf], labels=[...
python|pandas
0
375,441
69,196,861
How to group rows together based on conditions from a list? Pandas
<p>I want to be able to group rows into one if they have matching values in certain columns, however I only want them to be grouped if the value is in a list. For example,</p> <pre><code>team_sports = ['football', 'basketball'] view of df country sport age USA football 21 USA football 28 USA...
<p>The more straightforward approach is to separate the DataFrame based on those rows where the <code>sports</code> column <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>isin</code></a> the list of <code>team_sports</code>. <a href="https://pandas.pydata.o...
pandas|database|group-by
0
375,442
68,945,587
Is there an efficient way of creating a dataframe column based on data in another dataframe?
<p>I have two dataframes. One contains data on user subscriptions, another on user session.</p> <p>Example of subscription data (df_subscriptions):</p> <pre><code> user_id created ended 10238 140baa7a-1641-41b5-a85b-c43dc9e12699 2021-08-13 19:37:11.373039 ...
<p>Create some example data:</p> <pre><code>subs = pd.DataFrame(zip([&quot;user_0&quot;, &quot;user_0&quot;, &quot;user_1&quot;, &quot;user_2&quot;], [1900, 1920, 1950, 2000], [1910, 1930, 2000, 2020]), columns=[&quot;user_id&quot;, &quot;created&quot;, &quot;ended&quot;]) user_id created ended 0 user_0 1900 ...
python|pandas
0
375,443
69,257,614
define Array without allocating it
<p>I see that Numba does not support Dict-of-Lists ... Thus, I decided to use 2D Numpy arrays instead. This is sad :(</p> <p>The second problem I have is that I want to create this array on demand. Here is an example:</p> <pre><code>@nb.njit(parallel=True) def blah(cond=True): ary = None if cond : ary = np.zero...
<p>If you want the code to be parallelized, then yes, it absolutely has to be allocated first. You can't have multiple threads trying to resize an array independently.</p>
python|numpy|allocation|numba
1
375,444
69,142,836
Import multiple excel files start with same name into pandas and concatenate them into one dataframe
<p>I have everyday multiple excel files with different names, but all these files start with the same name, for instance, &quot;Answer1.xlsx&quot;, &quot;AnswerAVD.xlsx&quot;,&quot;Answer2312.xlsx&quot;, etc.</p> <p>Is it possible to read and concatenate all these files in a pandas dataframe?</p> <p>I Know how to do on...
<p>use a glob method with <code>pathlib</code> and then <code>concat</code> using pandas and a list comprehension.</p> <pre><code>from pathlib import Path import pandas as pd src_files = Path('C:\\').glob('*Answer*.xlsx') df = pd.concat([pd.read_excel(f, index_col=None, header=0) for f in src_files]) </code></pre>
python|excel|pandas
1
375,445
69,212,097
Replace nan cells with lists in Pandas dataframe
<p>I have the following Pandas dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">index</th> <th style="text-align: left;">title</th> <th style="text-align: center;">Open</th> <th style="text-align: center;">Close</th> </tr> </thead> <tbody> <tr> <td styl...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>mask = df.title.notna() max_wid = df.loc[mask, &quot;title&quot;].str.len().max() zeros = np.zeros(max_wid, dtype=int).tolist() df.loc[~mask, &quot;title&quot;] = [zeros] print(df) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><cod...
python|pandas|dataframe|numpy
0
375,446
68,984,520
How to we replace log(0) with 0?
<p><code>RuntimeWarning: invalid value encountered in multiply</code></p> <p>I have a code:</p> <pre><code>a = Y_list * np.log(Y_list/E_Y) print(a) </code></pre> <p>My <code>Y_list</code> contains <code>0</code> values, I'm wondering how to do when <code>Y_list = 0</code> , <code>np.log(0) = 0</code>?</p>
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">np.where</a> It lets you define a condition for true and false and assign different values.</p> <pre><code>np.where((Y_list/E_Y)!= 0, np.log(Y_list/E_Y),0) </code></pre>
numpy
3
375,447
69,148,944
Loop through dataframe to identify subgroup and label with unique identifier
<p>I'm trying to complete the <code>Sessions</code> column with a unique integer per session for further processing.</p> <p>A session is defined by one day or a period from 9:30-16:00</p> <pre><code> Symbol Time Open High Low Close Volume LOD Sessions 2724312 AEHR 2019-09-23 09:31:00 ...
<p>Assuming the dataframe is sorted on <code>Date</code>, we can use <code>duplicated</code> along with <code>cumsum</code> to assign the unqiue sessions numbers</p> <pre><code>df['Sessions'] = (~df.duplicated(['Symbol', 'Date'])).cumsum() </code></pre> <hr /> <pre><code>print(df) Symbol Time ...
pandas|database|dataframe|loops
1
375,448
68,983,642
Memory usage of torch.einsum
<p>I have been trying to debug a certain model that uses <code>torch.einsum</code> operator in a layer which is repeated a couple of times.</p> <p>While trying to analyze the GPU memory usage of the model during training, I have noticed that a certain <strong>Einsum</strong> operation dramatically increases the memory ...
<p>Variable &quot;<code>x</code>&quot; is indeed overwritten, but the tensor data is kept in memory (also called the layer's <em>activation</em>) for later usage in the backward pass.</p> <p>So in turn you are effectively allocating new memory data for the result of <code>torch.einsum</code>, but you won't be replacing...
python|pytorch|numpy-einsum
1
375,449
69,091,092
How to sessionize data in python
<p>I have a requirement to tag user transactions to a session.</p> <p>A session is defined in such a way that all actions of a user that happens within 5 minutes after the first action of a session belong to that session. We identify a user by the userID</p> <p><strong>Sample Source Data</strong></p> <pre class="lang-n...
<p>We can start to define the session using a <code>groupby</code> and a <code>transform</code> like so :</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df['NewSession'] = (df.groupby('userID')['timestamp'] ... .transform(lambda x: x.diff().gt('5Min').cumsum()) + 1) &gt;&gt;&gt; ...
python|python-3.x|pandas|dataframe
0
375,450
69,213,744
Pandas column taking very long time to translate
<p>I have a pandas dataframe of some 200k records. It has two columns; the text in English and a score. I want to translate a column from English to a few other languages. For that, I'm using the Cloud Translation API from Google's GCP. It's however, taking an absurdly long time to translate them. My code is basically ...
<p>To fix the slow code, I just initialized the import and translate client outside the function once.</p> <p>In the case of the 403 POST error, I had to create another GCP account. When I saw the quotas in the old account (trial), nothing was exceeded or close to, but the trial period apparently ended and I didn't hav...
python|pandas|google-translation-api
1
375,451
44,538,313
Select one group and transform the remaining group to columns in pandas
<p>I've a dataframe that looks like</p> <pre><code>import pandas as pd from pandas.compat import StringIO origin = pd.read_table(StringIO('''label type value x a 1 x b 2 y a 4 y b 5 z a 7 z c 9''')) origin Out[5]: label type value 0 x a 1 1 x b 2 2 y a...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> for filtering first - in <code>df2</code> also remove rows which are not in <code>df1['type']</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/g...
python|pandas
1
375,452
44,683,956
Grouping customer orders by date, category and customer with one-hot-encoding result
<p>I have a dataframe containing order of customers from different categories (A-F). A one indicates a purchase from this category, wheres a zero indicates none. Now I would like to indicate with 1 and 0 encoding whether a purchase in each respective category was made on a per day and per customer basis. </p> <pre><co...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> and aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.max.html" rel="nofollow noreferrer"><code>max</cod...
python|pandas
1
375,453
44,611,800
Mapping an integer to array (Python): ValueError: setting an array element with a sequence
<p>I have a defaultdict which maps certain integers to a numpy array of size 20.</p> <p>In addition, I have an existing array of indices. I want to turn that array of indices into a 2D array, where each original index is converted into an array via my defaultdict.</p> <p>Finally, in the case that an index isn't found...
<p>You should give us a some sample arrays or dictionaries (in the case of <code>cVF</code>, so we can make a test run.</p> <p>Read what <code>vectorize</code> has to say about the return value. Since you don't define <code>otypes</code>, it makes a test calculation to determine the dtype of the returned array. My fi...
python|arrays|numpy
1
375,454
44,548,401
How to specify a scalar multiplier for units when using Quantities?
<p>The objective is to handle cell densities expressed as "1000/mm^3", i.e. thousands per cubic millimeter.</p> <p>Currently I do this to handle "1/mm^3":</p> <pre><code>import quantities as pq d1 = pq.Quantity(500000, "1/mm**3") </code></pre> <p>which gives: </p> <pre><code>array(500000) * 1/mm**3 </code></pre> <...
<p>One possible solution I have found is to create new units such as this:</p> <pre><code>k_per_mm3 = pq.UnitQuantity('1000/mm3', 1e3/pq.mm**3, symbol='1000/mm3') d1 = pq.Quantity(500, k_per_mm3) </code></pre> <p>Then on printing 'd1', I get:</p> <pre><code>array(500) * 1000/mm3 </code></pre> <p>which is what I req...
python|numpy|units-of-measurement|quantities
1
375,455
44,794,455
What's the optimal way to access a cell within a panda of nested dictionaries?
<p>I have a nested dictionary panda. It goes from a tuple of <code>(STRING, DATE)</code> to a dictionary that contains specific columns and values. I've been trying to figure out the syntax to get the individual cell's data. For instance, I'd like to call [('SYY', '1997-06-30')]['dvt'] and get 99.5740. I've tried using...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:</p> <pre><code>print (df.loc[('SYY', '1997-06-30'), 'dvt']) 99.574 </code></pre> <p>For complicated selects use <a href="http://pandas.pydata.org/pand...
python|pandas|dictionary
3
375,456
44,610,766
Select columns using pandas dataframe.query()
<p>The documentation on <code>dataframe.query()</code> is <em>very</em> terse <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html</a> . I was also unable to find examples of proj...
<p>After playing around with this for a while and reading through <a href="https://github.com/pandas-dev/pandas/blob/v0.20.2/pandas/core/frame.py#L2038-L2128" rel="noreferrer">the source code</a> for <code>DataFrame.query</code>, I can't figure out a way to do it.</p> <p>If it's not impossible, apparently it's at leas...
python|pandas|dataframe
8
375,457
44,794,220
pandas column value update from another dataframe value
<p>I have following 2 dataframe </p> <pre><code>df_a = id val 0 A100 11 1 A101 12 2 A102 13 3 A103 14 4 A104 15 df_b = id loc val 0 A100 12 1 A100 23 2 A100 32 3 A102 21 4 A102 38 5 A102 12 6 A102 18 7 A102 19 ..... </code></pre> <p>desired result: </p> <pre><code>df_b ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="noreferrer"><code>map</code></a> by <code>Series</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="noreferrer"><code>set_index</code></a>:</p> ...
python|pandas
6
375,458
44,811,405
Pandas: Concatenating DataFrame with Sparse Matrix
<p>I'm doing some basic machine learning and have a sparse matrix resulting from TFIDF as follows:</p> <pre><code>&lt;983x33599 sparse matrix of type '&lt;type 'numpy.float64'&gt;' with 232944 stored elements in Compressed Sparse Row format&gt; </code></pre> <p>Then I have a DataFrame with a <code>title</code> co...
<p>Consider the following demo:</p> <p>Source DF:</p> <pre><code>In [2]: df Out[2]: text 0 is it good movie 1 wooow is it very goode 2 bad movie </code></pre> <p>Solution: let's create a SparseDataFrame out of TFIDF sparse matrix:</p> <pre><code>from sklearn.feature_extrac...
python|pandas|dataframe
3
375,459
44,401,088
Using Training TFRecords that are stored on Google Cloud
<p>My goal is to use training data (format: tfrecords) stored on Google Cloud storage when I run my Tensorflow Training App, locally. (Why locally? : I am testing before I turn it into a training package for Cloud ML)</p> <p>Based on <a href="https://stackoverflow.com/questions/39783189/reading-input-data-from-gcs">thi...
<p>Try executing the following command</p> <p><code>gcloud auth application-default login</code></p>
tensorflow|google-cloud-ml|google-cloud-ml-engine
27
375,460
44,659,204
numpy dot product with missing values
<p>How do you do a numpy dot product where the two vectors might have missing values? This seems to require many additional steps, is there an easier way to do this?:</p> <pre><code>v1 = np.array([1,4,2,np.nan,3]) v2 = np.array([np.nan,np.nan,2,4,1]) np.where(np.isnan(v1),0,v1).dot(np.where(np.isnan(v2),0,v2)) </code>...
<p>We can use <a href="https://docs.scipy.org/doc/numpy-1.10.4/reference/generated/numpy.nansum.html" rel="noreferrer"><code>np.nansum</code></a> to sum up the values ignoring <code>NaNs</code> after element-wise multiplication -</p> <pre><code>np.nansum(v1*v2) </code></pre> <p>Sample run -</p> <pre><code>In [109]: ...
numpy|multidimensional-array|linear-algebra|numpy-ndarray|dot-product
9
375,461
44,459,935
Groupby .cumsum() blank if the summed column is equal to zero?
<p>I have a DataFrame .groupby() .cumsum(), with a DataFrame as follows:</p> <pre><code> Col_A Col_B Col_C 1 A 0 2 A 1 1 3 A 1 2 4 A 1 3 5 B 0 0 6 B 1 1 7 B 0 8 B 1 2 9 C 1 1 ...
<p>Having a column of 0s is not the same as having a completely blank column. If you have NAs in a column the .cumsum() for that column should in fact be NA(or 'blank' as you say). You could check to see if the whole column is NA and set the value accordingly.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stab...
python|pandas|group-by|sum|series
2
375,462
44,728,349
Unique values python
<p>I am trying to basically look through a column and if that column has a unique value then enter 1 but if it doesn't it just becomes a NaN, my dataframe looks like this:</p> <pre class="lang-none prettyprint-override"><code> Street Number 0 1312 Oak Avenue 1 1 14212 central Ave 2 2 981 fra...
<p>That's not really producing your desired result. The output of <code>df['Number'].unique()</code>, <code>array([1, 2], dtype=int64)</code>, just happened to be in the index. You'd encounter the same issue on that column if <code>Number</code> instead was <code>[3, 4, 3]</code>, say.</p> <p>For what you're looking f...
python|pandas|dataframe|unique
1
375,463
44,507,870
Is there an easy way to eliminate duplicate rows in a DataFrame in Python- pandas?
<p>My problem is that my data isn't a good representation of what is really going on because it has a lot of duplicate rows. Consider the following-</p> <pre><code> a b 1 23 42 2 23 42 3 23 42 4 14 12 5 14 12 </code></pre> <p>I only want 1 row and to eliminate all duplicates. It should look like ...
<p>Let's use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.drop_duplicates.html#pandas-dataframe-drop-duplicates" rel="nofollow noreferrer"><code>drop_duplicates</code></a> with <code>keep='first'</code>:</p> <pre><code>df2.drop_duplicates(keep='first') </code></pre> <p>Outpu...
python|pandas|dataframe
7
375,464
44,481,377
Tensorflow equivalent of this numpy axis-wise cartesian product for 2D matrices
<p>I currently have code that allows one to take a combinatorial (cartesian) product across a particular axis. This is in numpy, and originated from a previous question <a href="https://stackoverflow.com/questions/44323478/efficient-axis-wise-cartesian-product-of-multiple-2d-matrices-with-numpy-or-tens">Efficient axis-...
<p>Ok so I managed to find a pure tf based (partial) answer for two arrays. It's not currently generalizable like the numpy solution for M arrays, but that's for another question (perhaps a tf.while_loop). For those that are curious, the solution adapts from <a href="https://stackoverflow.com/questions/43534057/evaluat...
python|tensorflow|product|cartesian
0
375,465
44,649,603
ValueError: Cannot feed value of shape (3375, 50, 50, 2) for Tensor 'Reshape:0', which has shape '(?, 5000)'
<p>I am learning Tensorflow. Following is my code for MLP with TensorFlow. I have some issues with mismatching of data dimentions.</p> <pre><code>import numpy as np import tensorflow as tf import matplotlib.pyplot as plt wholedataset = np.load('C:/Users/pourya/Downloads/WholeTrueData.npz') data = wholedataset['wholeda...
<p>I think that the problem is that you use the same variable name <code>x</code> for the placeholder and the reshape, in lines </p> <pre><code>x = tf.placeholder('float', shape = [None,50,50,2]) </code></pre> <p>and </p> <pre><code>x = tf.reshape(x, [-1, dim]) </code></pre> <p>so that when you </p> <pre><code>fee...
tensorflow|python-3.5
0
375,466
44,594,292
Errors installing TensorFlow 1.2 GPU in Anaconda env with py 3.6 Ubuntu 16.04 Setup tools
<p>It seems TF is requiring setuptools 27.2.0 while I have setuptools (36.0.1) ????</p> <p>Using a newly created and downloaded Anaconda virtual environment on Ubuntu 16.04 (in another env I have TF1.1GPU running fine) (py362) I attempt to install the TF 1.2GPU, anaconda Command line client (version 1.6.3) Python 3.6....
<p><code>pip install setuptools==27.2.0</code></p>
python|ubuntu|tensorflow|anaconda|setuptools
1
375,467
44,778,876
Is there a systematic way to compute the receptive field of a neuron?
<p>I am interested in computing the receptive field of a neuron relatively to the input, or more generally relatively to an earlier layer.</p> <p>This can be done manually, but I would like to know if there is a built-in function to do it or otherwise if there is a way do compute it automatically.</p> <p>Is there som...
<p>Yes, as of Aug 2017, you can simply use <code>tf.contrib.receptive_field</code></p> <p>See <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/receptive_field" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/receptive_field</a> for detai...
tensorflow
1
375,468
44,774,829
python dataframe appending columns horizontally
<p>I am trying to make a simple script that concatenates or appends multiple column sets that I pull from xls files within a directory. Each xls file has a format of:</p> <pre><code>Index Exp. m/z Intensity 1 1000.11 1000 2 2000.14 2000 3 3000.15 3000 </code></pre> <p>Each file h...
<p>I think you need <code>append</code> <code>DataFrames</code> to list and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferrer"><code>pd.concat</code></a>:</p> <pre><code>dfs = [] for files in os.listdir(full_path): if os.path.isfile(os.path.join(full_path, file...
python|pandas|dataframe|append|concat
8
375,469
44,724,152
Why is .ix inclusive on the end of indexing ranges?
<p>Python Version: 2.7.6 Numpy Version: 1.10.2 Pandas: 0.17.1</p> <p>I understand that .ix is now deprecated, but I'm working on a legacy system and seeing this behavior with .ix and I'm preplexed </p> <pre><code># Native Python List Indexing is exclusive on the end index [0, 1, 2, 3][0:1] # returns [0] indexes wi...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label" rel="nofollow noreferrer"><code>.ix</code></a> is label-based indexing (same as <code>.loc</code>) which the docs state includes the stop range value which is different to <code>iloc</code> which is open-closed range so doesn't in...
python|pandas|numpy
4
375,470
44,553,937
Creating legend for graph with multiple lines representing a 'group'
<p>From a dataframe in pandas 'g' I have the following data:</p> <pre><code>index Speaker Date ARI Flesch Kincaid 0 Alan Greenspan 1996 15.234878 34.669383 14.533217 1 Alan Greenspan 1997 16.235605 31.415163 15.335869 11 Alan S. Blinder 2002 14.299481 ...
<p>Try to <code>groupby</code> by speaker and then plot as described <a href="http://pandas.pydata.org/pandas-docs/version/0.16.2/generated/pandas.core.groupby.DataFrameGroupBy.plot.html" rel="nofollow noreferrer">here</a></p>
python|pandas|matplotlib|graph
1
375,471
44,795,595
Why is my TFRecord file so much bigger than csv?
<p>I always thought that being a binary format, <a href="https://www.tensorflow.org/api_guides/python/python_io#tfrecords_format_details" rel="nofollow noreferrer">TFRecord</a> will consume less space then a human-readable csv. But when I tried to compare them, I saw that it is not the case.</p> <p>For example here I ...
<p>The fact that your file is bigger is due to the overhead that TFRecords has for each row, in particular the fact that the label names are stored every time.</p> <p>In your example, if you increase the number of features (from 10 to say 1000) you will observe that your tfrecord file is actually about half the size o...
tensorflow
2
375,472
44,508,502
KeyError from pandas DataFrame groupby
<p>This is a very strange error, I got <code>KeyError</code> when doing pandas DataFrame <code>groupby</code> for no obvious reason. </p> <pre><code>df = pd.read_csv('test.csv') df.tail(5) df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 165 entries, 0 to 164 Data columns (total 3 columns): Id 16...
<p>Got to the bottom of it -- it is in fact that the Windows based csv files IS the root cause. </p> <p>Proofs:</p> <ol> <li>I opened, copied &amp; saved the exactly content using Notepad++, and there won't be such problem with the newly saved file. </li> <li>If I convert it using <code>dos2unix</code> under Linux, t...
python|python-2.7|pandas|dataframe
1
375,473
44,458,947
Tensorflow keeps all files. How to prevent that?
<p>Since updating to tensoflow version 1.0 which introduced the new Saver V2, tf does not delete old files any more with the 'max_to_keep' argument. This is a problem on my system since my models are pretty big but my free space is limited.</p> <p>Using the dummy program below I end up with following files for every n...
<p>I can reproduce this. It seems to be a bug. </p> <p>However the problem is gone once I save into a different location (different from the executed .py file path)</p> <pre><code> save_path = saver.save(sess, 'data/testfile', global_step=i+1) </code></pre>
python|tensorflow
1
375,474
44,732,839
open txt file using read_csv by pandas
<p>I am trying to process txt file using pandas.<br> However, I get following error at read_csv </p> <blockquote> <p>CParserError Traceback (most recent call last) in () 22 Col.append(elm) 23 ---> 24 revised=pd.read_csv(Path+file,skiprows=Header+1,head...
<p>It fails because the part of the file you're reading looks like this:</p> <pre><code>Timestamp Trend Flags Status Value (ºC) ------------------------- ----------- ------ ---------- 20-Oct-12 8:00:00 PM HKT {start} {ok} 15.310 ºC 21-Oct-12 12:00:00 AM HKT { } {ok} 15.130...
python|pandas
1
375,475
44,699,092
Import NumPy gives me ImportError: DDL load failed: The specified procedure could not be found?
<p>My Environment: Win10 64 bits, Python 3.6 and I use pip install to install NumPy instead of Anaconda. NumPy version: 1.13.0</p> <p>I have seen several people posted similar questions, but most of them are using Python 2.7. The closest solution I have seen so far is: <a href="https://github.com/ContinuumIO/anaconda-...
<p>You should go with doing a clean install of numpy. Just don't go with the traditional way but download the wheel file instead. You can get the wheel file from here: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a> . Download this file- <cod...
python|python-3.x|numpy|pip
0
375,476
44,525,949
Pandas: Error while loading TSV file with JSON strings in one of the columns
<p>I am trying to load a tsv file which has only two columns: <em>property_id</em> &amp; <em>photo_urls</em></p> <p>For each <em>property_id</em> the <em>photo_urls</em> column contains string representation of an array of json where each json object represents one image (one URL).</p> <p><a href="https://pastebin.co...
<p>try</p> <pre><code> import pandas as pd pd.read_csv('pLurm1w1.txt',delim_whitespace=True) </code></pre> <p>returns</p> <pre><code> property_id photo_urls 0 ff808081469fd6e20146a5af948000ea [{title":"Balcony","name":"IMG_20131006_120837... 1 ff8080814702d3d10147068359d200cd...
python|json|python-3.x|pandas|parsing
0
375,477
44,764,887
How to restore trained LinearClassifier from tensorflow high level API and make predictions
<p>I have trained a logistic regression model model using tensorflow's LinearClassifier() class, and set the model_dir parameter, which specifies the location where to save metagrahps of checkpoints during model training:</p> <pre><code># Create temporary directory where metagraphs will evenually be saved model_dir = ...
<p><code>LinearClassifier()</code> has the 'model_dir' param, if when points to a trained model will restore the model.<br> During training, you do: </p> <pre><code>logistic_model = tf.contrib.learn.LinearClassifier(feature_columns=feature_columns, n_classes=num_labels, model_dir=model_dir) classifier.fit(X_train, y_...
python|tensorflow|logistic-regression
1
375,478
44,708,911
Structured 2D Numpy Array: setting column and row names
<p>I'm trying to find a nice way to take a 2d numpy array and attach column and row names as a structured array. For example:</p> <pre><code>import numpy as np column_names = ['a', 'b', 'c'] row_names = ['1', '2', '3'] matrix = np.reshape((1, 2, 3, 4, 5, 6, 7, 8, 9), (3, 3)) # TODO: insert magic here matrix['3'...
<p>As far as I know it's not possible to "name" the rows with pure structured NumPy arrays. </p> <p>But if you have <a href="/questions/tagged/pandas" class="post-tag" title="show questions tagged &#39;pandas&#39;" rel="tag">pandas</a> it's possible to provide an "index" (which essentially acts like a "row name"):</p>...
python|arrays|numpy|structured-array
19
375,479
44,631,279
assign in pandas pipeline
<p>Say, I have the following DataFrame with raw input data, and want to process it using a chain of pandas functions ("<em>pipeline</em>"). In particular, I want to rename and drop columns and add an additional column based on another. </p> <pre><code> Gene stable ID Gene name Gene type miRBase accession miR...
<p>You can use pipe:</p> <pre><code>tmp_df = ( df.drop(&quot;Gene type&quot;, axis=1) .rename(columns = {&quot;Gene stable ID&quot;: &quot;ENSG&quot;, &quot;Gene name&quot;: &quot;gene_name&quot;, &quot;miRBase accession&quot;: &quot;MI&quot;, ...
python|pandas
14
375,480
44,530,047
Why is my numeric data being treated as an object?
<p>DataFrame in Pandas being treated as an object when the data is actually numeric. How do I fix this issue? I'm assuming this is happening because I have certain values within my columns that are not numeric - which I am trying to convert to <code>NaN</code>. When I try and run the <code>to_numeric</code>function, it...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a>, but all <code>int</code> values are cast to <code>float</code>s:</p> <pre><code>df['D'] = pd.to_numeric(df['D'], errors='coerce') </code></pre> <p>But if mixed values - ...
python|pandas|dataframe
3
375,481
44,635,626
Rename result columns from Pandas aggregation ("FutureWarning: using a dict with renaming is deprecated")
<p>I'm trying to do some aggregations on a pandas data frame. Here is a sample code:</p> <pre><code>import pandas as pd df = pd.DataFrame({"User": ["user1", "user2", "user2", "user3", "user2", "user1"], "Amount": [10.0, 5.0, 8.0, 10.5, 7.5, 8.0]}) df.groupby(["User"]).agg({"Amount": {"Sum": "sum", ...
<h1>Use groupby <code>apply</code> and return a Series to rename columns</h1> <p>Use the groupby <code>apply</code> method to perform an aggregation that </p> <ul> <li>Renames the columns</li> <li>Allows for spaces in the names</li> <li>Allows you to order the returned columns in any way you choose</li> <li>Allows fo...
python|pandas|aggregate|rename
91
375,482
44,411,506
Pandas, sorting a dataframe in a useful way to find the difference between times. Why are key and value errors appearing?
<p>I have a pandas DataFrame containing 5 columns. </p> <pre><code>['date', 'sensorId', 'readerId', 'rssi'] df_json['time'] = df_json.date.dt.time </code></pre> <p>I am aiming to find people who have entered a store (rssi > 380). However this would be much more accurate if I could also check every record a sensorId a...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with mask created with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow noreferrer"><code>diff</code><...
python|pandas|datetime|multiple-columns|rows
0
375,483
60,895,213
Subtract multiple columns between two dataframes with different shapes based on multiple columns
<p>I'm looking at the following three datasets from JHU</p> <p><a href="https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv" rel="nofollow noreferrer">https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_...
<p>Consider <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>melt</code></a> to transform their wide data into long format then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">...
python|pandas
1
375,484
60,980,841
Zip variable becomes empty after running subsequent code
<p>I have a dataframe (<code>data</code>) which contains a few dates (<code>loss_date</code>, <code>report_date</code>, <code>good_date</code>), and I'm trying to count certain rows of the dataframe. The following code works perfectly the first time I run it:</p> <pre><code># Set up bins BUCKET_SIZE = 30 min_date = np...
<p>In short, the problem is your title concept: "zip variable". This is not a static list; it's a generator object.</p> <pre><code>buckets = zip(starts, ends) </code></pre> <p><code>buckets</code> is a callable interface, a function with a <code>yield</code>. Once you've iterated through the underlying structure, t...
python|pandas|list|variables|zip
2
375,485
61,172,737
How to get initial row's indexes from df.groupby?
<p>Actually, I have df</p> <p><code>print(df)</code>:</p> <pre><code> date value other_columns 0 1995 5 1 1995 13 2 1995 478 </code></pre> <p>and so on...</p> <p>After grouping them by date <code>df1 = df.groupby(by='date')['value'].min()</code> I wonder how to get initial row's index. In...
<p>You have to create a Column with the index value before doing the groupby:</p> <pre><code>df['initialIndex'] = df.index.values #do the groupby </code></pre>
python|pandas
1
375,486
60,984,045
trouble in applying a function to selected columns
<p>I am new to python programming. so, what i want to achieve is basically fill all the na values in columns that are object type with their modes.</p> <pre><code>object_columns=['A1','A4','A5','A6','A7']#these are object types columns #wrote this function def find_mode_fill(x): return data[x].fillna(data[x].mode...
<p>I think apply function is not proper for your problem. Try this.</p> <pre><code>for col in object_columns: mode_value = df[col].mode()[0] df[col][df[col].isnull()] = mode_value </code></pre>
python|pandas
0
375,487
60,893,208
Distributed training over local gpu and colab gpu
<p>I want to fine tune ALBERT.</p> <p>I see one can distribute neural net training over multiple gpus using tensorflow: <a href="https://www.tensorflow.org/guide/distributed_training" rel="nofollow noreferrer">https://www.tensorflow.org/guide/distributed_training</a></p> <p>I was wondering if it's possible to distrib...
<p>I don't think that's possible. Because in order to do GPU distributed training, you need NVLinks among your GPUs. You don't have such a link between your laptop's GPU and Colab GPUs. This is a good read <a href="https://lambdalabs.com/blog/introduction-multi-gpu-multi-node-distributed-training-nccl-2-0/" rel="nofoll...
python|tensorflow|gpu|google-colaboratory|distributed-training
1
375,488
61,095,560
How to select subsequent numpy arrays handling potential np.nan values
<p>I have a Series like this:</p> <pre><code>s = pd.Series({10: np.array([[0.72260683, 0.27739317, 0. ], [0.7187053 , 0.2812947 , 0. ], [0.71435467, 0.28564533, 1. ], [0.3268072 , 0.6731928 , 0. ], ...
<p>You can modify previous <a href="https://stackoverflow.com/a/61042803/2901002">answer</a> with remove missing values of <code>Series</code> and last add them by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reindex.html" rel="nofollow noreferrer"><code>Series.reindex</code></a> (on...
python|arrays|pandas|numpy
1
375,489
61,034,455
TensorFlow Federated: How can I write an Input Spec for a model with more than one input
<p>I'm trying to make an image captioning model using the federated learning library provided by tensorflow, but I'm stuck at this error </p> <p><code>Input 0 of layer dense is incompatible with the layer: : expected min_ndim=2, found ndim=1.</code></p> <p>this is my input_spec: </p> <pre><code>input_spec=collection...
<p>Great question! It looks to me like this error is coming out of TensorFlow proper--indicating that you probably have the correct nested structure, but the leaves may be off. Your input spec looks like it "should work" from TFF's perspective, so it seems it is probably slightly mismatched with the data you have</p> ...
python|tensorflow|tensorflow-federated
3
375,490
60,796,222
How can I Group By Year from a Date field using Python/Pandas
<p>I want to Group <strong>Return_On_Capital</strong> by <strong>datadate</strong> and <strong>Company name</strong></p> <pre><code>Compustat.groupby(Compustat['datadate'].dt.strftime('%Y'))['Return_On_Capital'].sum().sort_values() datadate Company name asset Debt_Curr_Liabilities Return_On_Capit...
<p>This might work - </p> <pre><code>Compustat['datadate'] = pd.to_datetime(Compustat['datadate'], format='%d/%m/%Y') Compustat.groupby([Compustat['datedate'].dt.year, 'Company name']).agg(sum=('Return_On_Capital', 'sum')).sort_values() </code></pre>
python-3.x|pandas|group-by
1
375,491
60,984,003
Why the backpropagation process can still work when I included 'loss.backward()' in 'with torch.no_grad():'?
<p>I'm working with a linear regression example in PyTorch. I know I did wrong including 'loss.backward()' in 'with torch.no_grad():', but why it worked well with my code?</p> <p>According to <a href="https://pytorch.org/docs/stable/autograd.html?highlight=no_grad#torch.autograd.no_grad" rel="nofollow noreferrer">pyto...
<p>This worked because the loss calculation has happened before the <code>no_grad</code> and you keep calculating the gradients according to that loss calculation (which calculation had gradient enabled). </p> <p>Basically, you continue update the weights of your layers using the gradients calculated outside of the <c...
pytorch|backpropagation
7
375,492
60,953,735
KeyError: "['belongs_to_collection' 'homepage' 'original_title' 'overview'\n 'poster_path' 'status' 'tagline'] not found in axis"
<p>This is my data</p> <pre><code> # Column Non-Null Count Dtype 0 belongs_to_collection 604 non-null object 1 budget 3000 non-null int64 2 genres 2993 non-null object 3 homepage 946 non-null object 4 imdb_id ...
<p>You can try with:</p> <pre><code>data.drop(columns=to_drop, inplace=True) </code></pre> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html" rel="nofollow noreferrer">pandas DOC</a></p> <p>EDIT</p> <p>both ways is working here!</p> <pre><code>import pandas as pd da...
python|csv|data-mining|data-cleaning|sklearn-pandas
0
375,493
60,804,944
Selective Groupby-Aggregate using Python Pandas DataFrame
<p>How can we aggregate all the rows after 4pm of one day till before 10am of the next day in the DataFrame by performing OHLC operations on the grouped rows?</p> <p>This will convert the original DataFrame from</p> <pre><code> symbol datetime open high low close date toCombine 0 AAPL 2020-01-01...
<p><strong>My approach</strong></p> <pre><code>#Group and agg m = df['toCombine'] agg_dict = {'datetime' : 'last', 'open' : 'first', 'high' : 'max', 'low' : 'min', 'close' : 'last'} reduce_df = (df.loc[m].groupby(['symbol',(~m).cumsum()], ...
python|pandas|dataframe|aggregate|ohlc
1
375,494
60,839,222
How to apply Speller from autocorrect to a specific column of a dataframe
<p>I tried this:</p> <pre><code>from autocorrect import Speller spell = Speller(lang='en') df['Text'] = df['Text'].apply(lambda x: spell(x)) </code></pre> <p>But I get the error: <code>TypeError: expected string or bytes-like object</code></p>
<p>Probably some of the values in <code>df['Text']</code> are neither <code>str</code> nor <code>bytes</code>. Try this:</p> <pre><code>from autocorrect import Speller spell = Speller(lang='en') df['Text'] = df['Text'].apply( lambda x: spell(x) if isinstance(x, str) or isinstance(x, bytes) else x) </code></pre>
python|pandas
0
375,495
60,817,191
Average pooling with window over variable length sequences
<p>I have a tensor <code>in</code> of shape (batch_size, features, steps) and want to get an output tensor <code>out</code> of the same shape by average pooling over the time dimension (steps) with a window size of <code>2k+1</code>, that is:</p> <pre><code>out[b,f,t] = 1/(2k+1) sum_{t'=t-k,...,t+k} in[b,f,t'] </code>...
<p>As far as I know, there is no such operation in TensorFlow. However, one can use a combination of two unmasked pooling operations, here written in pseudocode:</p> <ol> <li>Let <code>seq_mask</code> be a <a href="https://www.tensorflow.org/api_docs/python/tf/sequence_mask" rel="nofollow noreferrer">sequence mask</a>...
python|tensorflow|moving-average|pooling
0
375,496
60,892,714
How to get the Weight of Evidence (WOE) and Information Value (IV) in Python/pandas?
<p>I was wondering how to calculate the WOE and IV in python. Are there any dedication function in numpy/scipy/pandas/sklearn?</p> <p>Here is my example dataframe:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd np.random.seed(100) df = pd.DataFrame({'grade': np.random.cho...
<p>Formulas for woe and iv:</p> <p><a href="https://i.stack.imgur.com/LLp8M.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LLp8M.png" alt="enter image description here"></a></p> <p>Code to achieve this:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd np.random.se...
python|pandas|machine-learning
12
375,497
60,762,160
Python pandas groupby agg- sum one column while getting the mean of the rest
<p>Looking to group my fields based on date, and get a mean of all the columns except a binary column which I want to sum in order to get a count. </p> <p>I know I can do this by:</p> <p><code>newdf=df.groupby('date').agg({'var_a': 'mean', 'var_b': 'mean', 'var_c': 'mean', 'binary_var':'sum'})</code></p> <p>But ther...
<p>Something like this might work - </p> <pre><code>df = pd.DataFrame({'a':['a','a','b','b','b','b'], 'b':[10,20,30,40,20,10], 'c':[1,1,0,0,0,1]}, 'd':[20,30,10,15,34,10]) df a b c d 0 a 10 1 20 1 a 20 1 30 2 b 30 0 10 3 b 40 0 15 4 b 20 0 34 5 b 10 1 10 </code></pre> <p>Assuming <cod...
python|pandas|dataframe
1
375,498
60,917,399
Error trying to convert simple convolutional model to CoreML
<p>I'm trying to convert a simple GAN generator (from ClusterGAN):</p> <pre><code>self.name = 'generator' self.latent_dim = latent_dim self.n_c = n_c self.x_shape = x_shape self.ishape = (128, 7, 7) self.iels = int(np.prod(self.ishape)) self.verbose = verbose self.model = nn.Sequential( # Fully connected layers ...
<p>Core ML does not have 1-dimensional batch norm. The tensor must have at least rank 3.</p> <p>If you want to convert this model, you should fold the batch norm weights into those of the preceding layer and remove the batch norm layer. (I don't think PyTorch has a way to automatically do this for you.)</p>
pytorch|coreml|generative-adversarial-network
1
375,499
61,030,607
Create new columns based on a tree like pattern
<p>I have the following dataframe:</p> <pre><code>col1 col2 basic c c c++ c++ java ruby php java python python ...
<p>This can be solved through <a href="https://en.wikipedia.org/wiki/Graph_theory" rel="nofollow noreferrer">graph theory</a> analysis. It looks like you want to obtain all <a href="https://en.wikipedia.org/wiki/Glossary_of_graph_theory_terms#successor" rel="nofollow noreferrer">successors</a> starting from each of the...
python|pandas|graph|networkx|graph-theory
2