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
500
63,629,719
Creating new column by column names
<p>I need to create new column by using existing ones. I want to assign column name as value to corresponding row if that column has value (i.e not <code>NaN</code> values). I also need to exclude some columns for example in the sample dataframe <code>Column5</code> should be excluded. I couldn't come up with solution....
<p>Use <code>DataFrame.notna</code> + <code>DataFrame.dot</code>:</p> <pre><code>c = df.columns.difference(['Column5']) df['newcol'] = df[c].notna().dot(c).replace('', np.nan) </code></pre> <p>Result:</p> <pre><code> Column1 Column2 Column3 Column4 Column5 newcol 0 NaN 1.0 NaN NaN f Colu...
python|pandas|dataframe
4
501
63,363,642
python sum all next n values in array at each index
<p>I have an array:</p> <p>my_array = [1, 13, 6, 100, 12,23,45] and would like to create a new array that for each index in my_array is the sum of 3 next index values</p> <p>summed_array = [119, 118, 135, 80, 68,45,0] I tried something like np.cumsum but this cumlative values</p> <pre><code>import numpy as np sum_valu...
<p>This should do the trick using <a href="https://www.w3schools.com/python/numpy_array_slicing.asp#:%7E:text=Slicing%20arrays,start%3Aend%3Astep%5D%20." rel="nofollow noreferrer">slices</a>.</p> <pre><code>import numpy as np sum_value = 0 my_array = [1, 13, 6, 100, 12,23,45] summed_array = [0, 0, 0, 0, 0,0,0] n = 3;...
python|arrays|numpy|sum|cumsum
1
502
63,607,212
Pandas dataframe plot(): x-axis date labels display but not data
<p>I am trying to plot data as a function of time (years) from a pandas data frame. A summary of the data is shown here:</p> <pre><code> DATE WALCL 0 2010-08-18 2313662 1 2010-08-25 2301015 2 2010-09-01 2301996 3 2010-09-08 2305802 4 2010-09-15 2296079 517 2020-07-15 6958604 518 2020...
<ul> <li>Dataset is at <a href="https://fred.stlouisfed.org/series/WALCL" rel="nofollow noreferrer">Assets: Total Assets: Total Assets (Less Eliminations from Consolidation): Wednesday Level (WALCL)</a></li> <li>Verify the <code>DATE</code> column is in a datetime format by using <code>parse_dates</code> with <code>.re...
python|pandas|matplotlib|datetime64
3
503
63,525,673
How to split time series index based on continuity
<p>So I have a series of dates and I want to split it into chunks based on continuity.Series looks like the following:</p> <pre><code>2019-01-01 36.581647 2019-01-02 35.988585 2019-01-03 35.781111 2019-01-04 35.126273 2019-01-05 34.401451 2019-01-06 34.351714 2019-01-07 34.175517 2019-01-08 33.6...
<p>I assume that your DataFrame:</p> <ul> <li>has columns named <em>Date</em> and <em>Amount</em>,</li> <li><em>Date</em> column is of <em>datetime</em> type (not <em>string</em>).</li> </ul> <p>To generate your result, define the following function, to be applied to each group of rows:</p> <pre><code>def grpRes(grp): ...
python|pandas
0
504
21,559,866
Pandas align multiindex dataframe with other with regular index
<p>I have one dataframe, let's call it <code>df1</code>, with a a MultiIndex (just a snippet, there are many more columns and rows)</p> <pre><code> M1_01 M1_02 M1_03 M1_04 M1_05 Eventloc Exonloc chr10:52619746...
<p>If I understand what you are doing, you need to either explicity construct the tuples (they must be fully qualifiied tuples though, e.g. have a value for EACH level), or easier, construct a boolean indexer)</p> <pre><code>In [7]: df1 = DataFrame(0,index=MultiIndex.from_product([list('abc'),[range(2)]]),columns=['A'...
python|indexing|pandas|alignment|dataframe
2
505
24,799,257
Saving numpy arrays as part of a larger text file
<p>How can I save NumPy arrays as part of a larger text file? I can write the arrays to a temp file using <code>savetxt</code>, and then read them back into a string, but this seems like redundant and inefficient coding (some of the arrays will be large). For example:</p> <pre><code>from numpy import * a=reshape(aran...
<p>First parameter of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="nofollow">savetxt</a></p> <blockquote> <p><strong>fname</strong> : filename or <em><strong>file handle</strong></em></p> </blockquote> <p>So, you can open file in <a href="https://stackoverflow.com/questions/...
python|numpy
2
506
30,249,337
`numpy.tile()` sorts automatically - is there an alternative?
<p>I'd like to initialize a <code>pandas</code> DataFrame so that I can populate it with multiple time series. </p> <pre><code>import pandas as pd import numpy as np from string import ascii_uppercase dt_rng = pd.date_range(start = pd.tseries.tools.to_datetime('2012-12-31'), end = pd.tseries....
<p>A combination of <code>reduce()</code> and the <code>append()</code> method of a <code>pandas.tseries.index.DatetimeIndex</code>object did the trick.</p> <pre><code>import pandas as pd import numpy as np from string import ascii_uppercase dt_rng = pd.date_range(start = pd.tseries.tools.to_datetime('2012-12-31'), ...
python|numpy|pandas
0
507
53,543,705
pandas: How to search by a list of values and return in the same order?
<p>Forgive me if this is a dupe, I've searched all morning and only found pieces of the puzzles and couldn't quite fit it all together.</p> <h1>My Quest:</h1> <p>I have a simple <code>DataFrame</code> where I want to extract a view by the a search <code>list</code> <code>searches</code> in the same order of said <cod...
<h3><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> + <a href="https://pandas....
python|pandas
3
508
53,549,167
Have pandas produce error when multiplying with nan
<p>I'd like to have pandas produce an error when trying to do arithmetic involving cells with nan values. So if I create a dummy DataFrame:</p> <pre><code>test_input = pd.DataFrame(columns=['a','b','c'], index=[1,2], data=[[np.nan, np.nan, 2.0],[np.nan, 1.0, 3.0]]) <...
<p><code>NaN</code> values are of type <code>float</code>. As such, they work fine with arithmetic operations in Pandas / NumPy. You would have to override Pandas / NumPy methods to achieve your goal. <strong>This is not recommended.</strong></p> <p>Instead, just perform an explicit check before your computation:</p> ...
python|python-3.x|pandas|numpy
2
509
20,292,995
Numpy: Comparing two data sets for fitness
<p>I'm drawing a blank on this.</p> <p>I have two data sets: </p> <pre><code>d1 = [(x1,y1), (x2,y2)...] d2 = [(x1,y1), (x2,y2)...] </code></pre> <p>I would like to get some type of statistical value, maybe something like an r-value, that tells me how well <code>d2</code> fits to <code>d1</code>.</p>
<p>It dependents on what are those two vectors. you may want to be more specific.</p> <p>If they are something like X-Y coordinates in Cartesian system, distance correlation is probably the most appropriate (<a href="http://en.wikipedia.org/wiki/Distance_correlation#Alternative_formulation:_Brownian_covariance" rel="n...
python|numpy|data-fitting
2
510
71,965,040
Check a given word in each cell and extract it to put in an array
<p>I have a multiple column and in one of a column There is a paragraph written along with a keyword. I need to extract that keyword and put it in an array.</p> <p>EX: <a href="https://i.stack.imgur.com/rtfKn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rtfKn.png" alt="Example" /></a></p> <p>Now I...
<p>You can use <code>pandas.Series.str.extract</code>.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ 'col1': ['a', 'b', 'c'], 'col2': ['a', 'b', 'c'], 'col3': ['a\n\nTEST: MATH', 'b\nTEST: ENG', 'c\n\nTEST: PSY'] }) df['col3'].str.extract('TEST:(.*)$') </cod...
python|python-3.x|excel|pandas|dataframe
1
511
72,015,289
Read .xls file with Python pandas read_excel not working, says it is a .xlsb file
<p>I'm trying to read several .xls files, saved on a NAS folder, with Apache Airflow, using the read_excel python pandas function.</p> <p>This is the code I'm using:</p> <pre><code>df = pd.read_excel('folder/sub_folder_1/sub_folder_2/file_name.xls', sheet_name=April, usecols=[0,1,2,3], dtype=str, engine='xlrd') </code>...
<p>Try:</p> <pre><code>import openpyxl xls = pd.ExcelFile('data.xls', engine='openpyxl') df = pd.read_excel(xls) </code></pre> <p>XLRD has removed the ability to read in some excel datatypes recently like xlxs</p>
python|pandas|excel-2007|xls|xlsb
0
512
72,103,054
Create a column in a dataframe based on probabilities stored in another dataframe
<p>I have a python dataframe, pop, which has a few hundred thousand rows, the first of which are presented here:</p> <p><strong>pop:</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Index</th> <th>Unique_ID</th> <th style="text-align: center;">Code</th> <...
<p><a href="https://docs.python.org/3/library/random.html#random.choices" rel="nofollow noreferrer"><code>random.choices()</code></a> allows you to use a <code>weights</code> sequence. So, if you want for each row of <code>pop</code> a <code>response</code> based on the distributions in <code>prob</code>, then you coul...
python|pandas|dataframe|probability|data-wrangling
0
513
72,047,392
Python SUMIF with one condition across dataframes
<p>I'm working with two dataframes</p> <ul> <li>MRP:</li> </ul> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Material</th> <th>Description</th> <th>Septiembre</th> </tr> </thead> <tbody> <tr> <td>1208181</td> <td>ADSV,NA,MX,ADH HOTMET 814433PM</td> <td>630.2888856</td> </tr> <tr> <td>1206500...
<p>If I'm not wrong, that excel formula calculates the sum of 'Septiembre' in column C of MRP when 'Material' in SMCalc matches 'Material' in MRP...</p> <p>Assuming you have both excel sheets as pandas dataframes, I would then do:</p> <pre><code>mrp.groupby('Material')['Septiembre'].sum().reset_index() </code></pre> <p...
python|pandas|sumifs
0
514
22,043,601
Count NaNs when unicode values present
<p>Good morning all, </p> <p>I have a <code>pandas</code> dataframe containing multiple series. For a given series within the dataframe, the datatypes are unicode, NaN, and int/float. I want to determine the number of NaNs in the series but cannot use the built in <code>numpy.isnan</code> method because it cannot safe...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.common.isnull.html" rel="noreferrer">pandas.isnull</a>:</p> <pre><code>In [24]: test = pd.Series(data = [NaN, 2, u'string']) In [25]: pd.isnull(test) Out[25]: 0 True 1 False 2 False dtype: bool </code></pre> <p>Note however,...
python|numpy|pandas|nan|python-unicode
7
515
22,391,462
converting a list of strings into integers in python, skipping masked terms
<p>Let's say I have a list of strings:</p> <pre><code>fnew: masked_array(data = [-- -- '56527.9529' '56527.9544' '109.7147' '0.0089' '14.3638' '0.0779' '14.3136' '0.0775' '14.3305' '0.1049' '14.3628' '0.0837' '14.3628' '0.0837' '70.9990' '40.0050' '173.046' '-30.328' '73' '-99.175' '0.000' '0.000' '59.8' '0.0' '1....
<p>Something like this:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = ['Foo', '59.8', 'bar', 'spam'] &gt;&gt;&gt; arr = np.ma.array(a, mask=[True, False, True, True]) &gt;&gt;&gt; arr.compressed().astype(float) array([ 59.8]) &gt;&gt;&gt; arr[arr.mask].data array(['Foo', 'bar', 'spam'], dtype=...
python|numpy|integer|masking
2
516
17,698,975
Pandas: Convert DataFrame Column Values Into New Dataframe Indices and Columns
<p>I have a dataframe that looks like this:</p> <pre><code>a b c 0 1 10 1 2 10 2 2 20 3 3 30 4 1 40 4 3 10 </code></pre> <p>The dataframe above as default (0,1,2,3,4...) indices. I would like to convert it into a dataframe that looks like this:</p> <pre><code> 1 2 3 0 10 0 0 1 0 ...
<p>You can use the <code>pivot</code> method for this.</p> <p>See the docs: <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-pivoting-dataframe-objects">http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-pivoting-dataframe-objects</a></p> <p>An example:</p> <pre><...
python|pandas
12
517
8,822,370
Plot line graph from histogram data in matplotlib
<p>I have a numpy array of ints representing time periods, which I'm currently plotting in a histogram to get a nice distribution graph, using the following code:</p> <pre><code>ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r") </code></pre> <p>However I'm trying to modify this graph to represent the exact...
<p>I am very late to the party - but maybe this will be useful to someone else. I think what you need to do is set the histtype parameter to 'step', i.e.</p> <pre><code>ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r", histtype = 'step') </code></pre> <p>See also <a href="http://matplotlib.sourceforge.net/...
python|numpy|matplotlib
52
518
55,527,383
Cannot import tensorflow in python3 and ImportError: This package should not be accessible on Python 3
<p>I am trying to use tensorflow for research in my macbook. I use pip3 to install tensorflow in the system (not in virtual environment). </p> <p>At first, I just want to verify tensorflow can be correctly imported via python3 in terminal. However, sometimes, I got the following problem when importing. </p> <pre><cod...
<p>I tried the same scenario. It is working fine for me. In the first error it seems your python installation is messed up. If you are using python3 in terminal, it should not refer to 2.7 libraries. </p> <p>Also I dont think you require unset PYTHONPATH everytime. First thing is you dont need to setup PYTHONPATH. It ...
python|python-3.x|macos|tensorflow
0
519
55,556,315
TensorFlow: slice Tensor and keep original shape
<p>I have a Tensor <code>tensor</code> of shape <code>(?, 1082)</code> and I want to slice this Tensor into <code>n</code> subparts in a for-loop but I want to keep the original shape, including the unknown dimension <code>?</code>.</p> <p>Example:</p> <pre><code>lst = [] for n in range(15): sub_tensor = tensor[n...
<p>Considering that your problem can have many constraints, I can think of at least 3 solutions. You can use <code>tf.split</code>. I'll use tf.placeholder, but it's applicable to tensors and variables as well.</p> <pre><code>p = tf.placeholder(shape=[None,10], dtype=tf.int32) s1, s2 = tf.split(value=p, num_or_size_sp...
tensorflow|slice
1
520
55,523,104
Impute value based on other columns value
<p>There is a dataframe (df) in below format:</p> <pre><code>Name, Col-1, Col-2, Col-3, Col-4 abc, 0, 1, 0, 0 cba, 1, 0, 0, 0 bns 1, 0, 0, 0 abd 0 0, 0, 1 </code></pre> <p>Now i am trying to add new column to this dataframe like below:</p> ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.idxmax.html" rel="nofollow noreferrer">idxmax</a>:</p> <pre><code>In [11]: df Out[11]: Name Col-1 Col-2 Col-3 Col-4 0 abc 0 1 0 0 1 cba 1 0 0 0 2 bns 1 0 0...
pandas
2
521
55,353,703
How to calculate all combinations of difference between array elements in 2d?
<p>Given an array <code>arr = [10, 11, 12]</code> I want to calculate all the ways that one element can be subtracted from another. For a <code>1xN</code> array the desired output is a NxN array where <code>output[i, j] = arr[i] - arr[j]</code>. My approach was to generate all the possible pairings of two numbers, subt...
<p>Here's a generic vectorized way to cover both 1D and 2D cases leveraging <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> after reshaping the input array to broadcastable shpaes against each other -</p> <pre><code>def permute_axes_subtr...
python|numpy|itertools
2
522
56,697,419
Slicing on Pandas Series Object with Index List Having Multiple Datatypes
<p>I just started learning Pandas and I don't understand how slicing works when the index list contains objects of multiple types. </p> <pre><code>import pandas as pd arr = pd.Series([10, 20, 30, 40], index = [2, 3, 'six', 'eight']) arr[2:3] #Output -- 30 arr[3:'six'] #TypeError: cannot do slice indexing on &lt;class ...
<p>Pandas working best if not mixed types of values in index.</p> <p>Working general solution here is get positions for each index by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_loc.html" rel="nofollow noreferrer"><code>Index.get_loc</code></a> and select by <a href="http://pand...
python|pandas|slice
2
523
56,497,242
Grouping rows in list with multiple columns
<p>I have this in <code>pandas</code>:</p> <pre><code> a b c 0 A 1 6 1 A 2 5 2 B 3 4 3 B 4 3 4 B 5 2 5 C 6 1 </code></pre> <p>and I want to tranform it to this:</p> <pre><code> a b c 0 A [1, 2] [6, 5] 1 B [3, 4, 5] [4, 3, 3] 2 C [6] [1]...
<p>Ok so it is:</p> <pre><code>df = df.groupby('a').agg({'b': list, 'c':list}).reset_index() </code></pre> <p>If there is anything better then you can let me know.</p>
python|python-3.x|pandas
0
524
25,500,217
Groupby Sum ignoring few columns
<p>In this DataFrame I would like to groupby 'Location' and get the sum of 'Score' but I wouldn't want 'Lat','Long' &amp; 'Year' to be affected in the process;</p> <pre><code>sample = pd.DataFrame({'Location':['A','B','C','A','B','C'], 'Year':[2001,2002,2003,2001,2002,2003], ...
<p>You have to provide some form of aggregation method for the other columns. But you can use <code>mean</code>, <code>first</code> or <code>last</code> in this case, which would all work.</p> <pre><code>grouped = sample.groupby(['Location']).agg({'Lat': 'first', 'Long': 'f...
python|pandas
6
525
25,675,301
Using rolling_apply with a function that requires 2 arguments in Pandas
<p>I'm trying to use rollapply with a formula that requires 2 arguments. To my knowledge the only way (unless you create the formula from scratch) to calculate kendall tau correlation, with standard tie correction included is:</p> <pre><code>&gt;&gt;&gt; import scipy &gt;&gt;&gt; x = [5.05, 6.75, 3.21, 2.66] &gt;&gt;&...
<p><a href="https://github.com/pydata/pandas/issues/5071#ref-pullrequest-27077199" rel="noreferrer">As of Pandas 0.14</a>, <code>rolling_apply</code> only passes NumPy arrays to the function. A possible workaround is to pass <code>np.arange(len(A))</code> as the first argument to <code>rolling_apply</code>, so that the...
python|numpy|pandas|scipy|dataframe
6
526
25,528,320
MS SQL Server Management Studio export to CSV introduces extra character when reading from pandas
<p>I'm using MS SQL Server Management Studio and I have a simple table with the following data:</p> <pre><code>CountryId CommonName FormalName --------- ---------- ---------- 1 Afghanistan Islamic State of Afghanistan 2 Albania Republic of Albania 3 Algeria People'...
<p>Try using the <code>encoding = "utf-8-sig"</code> option with <code>read_csv</code>. For example:</p> <pre><code>df = pd.read_csv("countries.csv", encoding = "utf-8-sig") </code></pre> <p>That should get it to ignore the Unicode Byte Order Mark (BOM) at the start of the CSV file. The use of BOM unnecessary here as...
python|pandas|ssms
3
527
26,325,652
Fastest way to keep one element over two from long numpy arrays?
<p>Let's consider a numpy array </p> <pre><code>a = array([1,2,25,13,10,9,4,5]) </code></pre> <p>containing an even number of elements. I need to keep only one element of the array every two at random: either the first or the second, then either the third or the fourth, etc. For example, using a, it should result i...
<p>You can select the elements using fancy indexing, <code>a[idx]</code>:</p> <pre><code>def random_skip(a, skipsize=2): idx = np.arange(0, len(a), skipsize) idx += np.random.randint(skipsize, size=len(idx)) idx = np.clip(idx, 0, len(a)-1) return a[idx] In [141]: a = array([1,2,25,13,10,9,4,5]) ...
python|arrays|numpy
4
528
66,829,925
Reading nested JSON file in Pandas dataframe
<p>I have a JSON file with the following structure (it's not the complete json file, but the structure is the same):</p> <pre><code>{&quot;data&quot;:[{&quot;referenced_tweets&quot;:[{&quot;type&quot;:&quot;retweeted&quot;,&quot;id&quot;:&quot;xxxxxxx&quot;}],&quot;text&quot;:&quot;abcdefghijkl&quot;,&quot;created_at&q...
<pre><code>import pandas as pd with open('Test_SampleRetweets.json') as json_file: raw_data = json.load(json_file) data = [] for item in raw_data[&quot;data&quot;]: item[&quot;tweet_id&quot;] = item[&quot;id&quot;] item.update(item[&quot;referenced_tweets&quot;][0]) del item[&quot;referenced_tweets&...
python|json|pandas|nested|tweets
1
529
66,877,578
How to pass multiple values from a panda df to pyspark SQL using IN OPERATOR
<p>The output of my df returns three distinct values as below</p> <pre><code>print(df[&quot;ID&quot;]) </code></pre> <p>returns three ID's <code>1</code>,<code>2</code> and <code>3</code>.</p> <p>I want to pass these values within a pyspark SQL</p> <pre><code> Query = 'select col 1 from temptable where ID IN (*need to ...
<p>If <code>Query</code> is a string then convert <code>df[&quot;ID&quot;]</code> to string</p> <p>For example</p> <pre><code>','.join( df['ID'].astype(str).to_list() ) </code></pre> <p>gives string</p> <pre><code>'1,2,3' </code></pre> <p>And then you can use it in string with query using ie. f-string.</p> <hr /> <p>Mi...
python|pandas|pyspark|apache-spark-sql
1
530
67,173,745
Group by on pandas datetime with null values
<p>So im looking at manipulating data to perform autoregression forecasting on the data. I have managed to group by the week without any issues, however the weeks that do not have any flagged values is left out of the created dataframe. The shape of the data frame is (28, 141), meaning only 28 weeks are grouped, the mi...
<p>You can do a <strong>right</strong> <strong>join</strong> to set of dates you want.</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;date&quot;:pd.date_range(&quot;1-feb-2020&quot;, freq=&quot;4d&quot;, periods=28)}) (df.groupby(df.date.dt.to_period(&quot;w&quot;)).count() .join(pd.DataFrame(index=pd.d...
pandas|datetime|jupyter-notebook|grouping
0
531
67,103,144
How to convert index and values to a proper dataframe with callable column names? Python Pandas
<p>I am working on this dataset where I have used the <code>sort_values()</code> function to get two distinct columns: the <code>index</code> and the <code>values</code>. I can even rename the index and the values columns. However, if I rename the dataset columns and assign everything to a new dataframe, I am not able ...
<p>Check out the comment here, not sure if still correct: <a href="https://stackoverflow.com/a/18023468/15600610">https://stackoverflow.com/a/18023468/15600610</a></p>
python|python-3.x|pandas|dataframe
0
532
66,796,929
find all - to find all occurrence of matching pattern one column of a data frame to other and get the corresponding value
<p>I am working on a requirement, there are 2 CSV as below -</p> <p>CSV.csv</p> <pre><code> Short Description Category Device is DOWN! Server Down CPU Warning Monitoron XSSXSXSXSXSX.com ...
<p>A possible approach:</p> <pre class="lang-py prettyprint-override"><code>my_dict = dict(zip(reference_df['Category'].values, reference_df['Complexity'].values)) def match_key(key, default_value): for d_key in my_dict.keys(): if key in d_key or d_key in key: return my_dict[d_key] return ...
python|python-3.x|pandas|dataframe|findall
1
533
47,490,576
How to do a rolling week-to-date sum in python's Pandas
<p>Suppose I have the following code:</p> <pre><code>import pandas as pd frame = pd.DataFrame( { "Date":["11/1/2017","11/2/2017","11/3/2017","11/4/2017", "11/5/2017","11/6/2017","11/7/2017","11/8/2017","11/9/2017","11/10/2017","11/11/2017", "11/12/2017"], "Day":["Wed","Thr","Fri...
<p>We using <code>cumsum</code> twice in group and group calculation</p> <pre><code>df['WTDSum']=df.groupby(df.Day.eq('Sun').cumsum()).Sales.cumsum() df Out[520]: Date Day Sales WTDSum 0 11/1/2017 Wed 5 5 1 11/2/2017 Thr 5 10 2 11/3/2017 Fri 10 20 3 11/4/2017 ...
python|pandas
4
534
47,475,611
Fastest coincidence matrix
<p>I have two arrays and I want to compute a list/array of coincidences. That is, a list of all the indices i, j so that a[i] == b[j]. This is my code now:</p> <pre><code>b = np.array([3, 5, 6, 4]) a = np.array([1, 2, 3, 4]) np.array([[i, j] for i in range(a.size) for j in range(b.size) if a[i] == b[j]]) </code></pre...
<h3>Approach #1</h3> <p>One approach would be using <code>np.in1d</code> -</p> <pre><code>m_a = np.in1d(a,b) I = np.flatnonzero(m_a) J = np.flatnonzero(np.in1d(b, a[m_a])) </code></pre> <p>Sample input, output -</p> <pre><code>In [367]: a Out[367]: array([1, 2, 3, 4]) In [368]: b Out[368]: array([3, 5, 6, 4]) In ...
python|numpy
2
535
68,048,889
Why do I have to write both 'read' and 'r' to write a file by using pandas
<pre><code>import pandas as pd import numpy as np df = pd.read_csv(r'C:\Users\OneDrive\Desktop\Python\Python_coursera\Course 1 - Notebook Resources\resources\week-2\datasets\census.csv') </code></pre> <p>If I omit the 'r', I cannot read the csv file. Is it normal to write both 'read' and 'r'? Because the course tutori...
<p>The <code>r</code> preceding a string literal in Python indicates that it's a <a href="https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals" rel="nofollow noreferrer">raw string</a>. This allows it to treat the backslashes (<code>\</code>) as literal backslashes, instead of Unicode esc...
python|pandas|dataframe|csv
2
536
68,088,504
My accuracy stays around the same, what can I do to fix this
<p>After finally fixing all the errors this code gave me, I have stumbled upon a new problem. This time it is the working model that supplies me with it. Here is the code I have created, this is now my third Deep Learning code I made and I am having a lot of fun making it, however, because I am a beginner in Python in ...
<p>Your model is not sufficiently big enough to handle the data.<br /> So, try increasing your model size.<br /> However, increasing your model size makes it more vulnerable to overfitting, but using some <a href="https://keras.io/api/layers/regularization_layers/dropout/" rel="nofollow noreferrer">Dropout</a> layers s...
python|tensorflow|machine-learning|keras|neural-network
0
537
68,238,839
replace/remove everything before a specified string
<p>I have a string in a pandas dataframe.</p> <p><code>This is target 1</code></p> <p><code>We also have target 2</code></p> <p>I want to remove all text before the <code>target</code> string so it turns into:</p> <p><code>target 1</code></p> <p><code>target 2</code></p> <p>I've been looking through regex patterns, but...
<p>To remove everything before the first <code>target</code>, you can use <code>^.*?(?=target)</code>, where:</p> <ol> <li><code>^</code> matches the beginning of string;</li> <li><code>.*?</code> matches everything non-greedily;</li> <li><code>?=target</code> asserts that the match is before pattern <code>target</code...
pandas|replace
1
538
68,301,270
How do I vstack or concatenate matricies of different shapes?
<p>In a situation like the one below, how do I vstack the two matrices?</p> <pre><code>import numpy as np a = np.array([[3,3,3],[3,3,3],[3,3,3]]) b = np.array([[2,2],[2,2],[2,2]]) a = np.vstack([a, b]) Output: ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dim...
<p>Be careful with those &quot;Numpy is faster&quot; claims. If you already have arrays, and make full use of array methods, <code>numpy</code> is indeed faster. But if you start with lists, or have to use Python level iteration (as you do in <code>Pack...</code>), the <code>numpy</code> version might well be slower....
python|arrays|numpy|concatenation|vstack
1
539
68,440,087
Is there a way to show activation function in model plots tensorflow ( tf.keras.utils.plot_model() )?
<p>The model plot in TensorFlow shows the shape of input, dtype and layer name. Is there some way to show the type of activation function as well? If there is some other better way of showing/plotting the neural networks please tell.</p>
<p>Updating the tensorflow version solved the <em>'Error: bad label' issue</em> when setting both show_shapes and show_layer_activation to True for me. (TF Version 2.8.0) Update tensorflow version with</p> <pre><code>pip install -U tensorflow </code></pre> <p>plot model call</p> <pre><code>tf.keras.utils.plot_model(mod...
python|tensorflow|neural-network
2
540
59,100,865
trying to append a dense layer to vgg19 network
<p>I am trying to append a dense layer to vgg19 network, but it gives me the below error. Can anyone help me with this?</p> <pre><code>import tensorflow from tensorflow.keras.applications.vgg19 import VGG19 model = VGG19() x = tensorflow.keras.layers.Dense(10, activation="relu",name="",trainable=True)(model.layers...
<p>Assuming it's a classification problem, therefore, you should use <code>softmax</code> activation instead of <code>relu</code> in the output layer. Also you can access input and output of the backbone <code>VGG19</code> model. You should manually pool or flatten the output of base model if you instantiate it with de...
python|tensorflow|keras
0
541
59,337,848
Why is this simple reindex Panda df function not working?
<p>I'm trying to reindex dataframes within a function but it's not working. It works outside of the function so I'm totally lost. Here's what I'm doing:</p> <p>Reindexing df2 based on index from df1</p> <p>Outside of function:</p> <pre class="lang-py prettyprint-override"><code>df2 = df2.reindex(df1.index) </code>...
<p>Compare 2 following examples:</p> <ol> <li><p>A function <strong>substituting</strong> a new value under a parameter:</p> <pre><code>def f1(a): a = a + 1 a = 10 print(f'Before: {a}') f1(a) print(f'After: {a}') </code></pre> <p>The result is:</p> <pre><code>Before: 10 After: 10 </code></pre> <p>so that th...
python|pandas|python-3.6
1
542
59,423,859
Swapping to numpy arrays element wise
<p>I have two <code>NumPy</code> arrays <code>l</code> and <code>g</code>, and I want to swap the elements of <code>l</code> that are greater than the corresponding elements in <code>g</code>.</p> <p>for example:</p> <pre><code>l = [0,19,1] g = [1,17,2] </code></pre> <p>after the operation</p> <pre><code>l = [0,17,...
<p>Just use <code>np.minimum</code> and <code>np.maximum</code>:</p> <pre><code>l = np.array([0,19,1]) g = np.array([1,17,2]) l, g = np.minimum(l, g), np.maximum(l, g) </code></pre>
python|numpy
2
543
59,349,536
A target array with shape (15000, 250) was passed for an output of shape (None, 1) while using as loss `binary_crossentropy`. What do I do?
<p>I have created a model but I can't run it because of the target array shape and output shape. I am trying to just train it but not sure what to make out of the error.</p> <p>Error:</p> <pre><code>--------------------------------------------------------------------------- ValueError T...
<p>Change </p> <pre><code>y_val = train_data[:10000] y_train = train_data[10000:] </code></pre> <p>to</p> <pre><code>y_val = train_labels[:10000] y_train = train_labels[10000:] </code></pre>
python|tensorflow|machine-learning|keras|deep-learning
1
544
44,855,380
Tensorflow: runn error with reader_test.py in models.tutorials.rnn
<p>I use anaconda2 with python 3.5 based tensorflow-gpu environment in wind10. I test the installation of tensorflow (v1.2) by run:</p> <pre><code>import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello)) </code></pre> <p>There is no problem with the installation. </...
<p>I solved the problem by updating anaconda (<code>conda upate --all</code>) and then restarting PC.</p>
tensorflow|lstm
1
545
45,199,910
Dates from 1900-01-01 are added to my 'Time' after using df['Time'] = pd.to_datetime(phData['Time'], format='%H:%M:%S')
<p>I am a self taught coder (for around a year, so new). Here is my data</p> <pre><code>phData = pd.read_excel('phone call log &amp; duration.xlsx') called from called to Date Time Duration in (sec) 0 7722078014 7722012013 2017-07-01 10:00:00 303 1 7722078014 7722052018 2017-07-01 10:21:00 502 ...
<p>Pandas doesn't have such dtype as Time. You can have either <code>datetime</code> or <code>timedelta</code> dtype.</p> <p><strong>Option 1</strong>: combine Date and Time into single column:</p> <pre><code>In [23]: df['TimeStamp'] = pd.to_datetime(df.pop('Date') + ' ' + df.pop('Time')) In [24]: df Out[24]: cal...
python|pandas|datetime
1
546
44,889,692
Zscore Normalize column in Dataframe using groupby
<p>I have a dataframe representing customers orders with many columns, two of those being 'user_id' and 'dollar'. </p> <p>for example : </p> <pre><code> user_id dollar 0 1 0.34592 5 1 1 0.02857 7 2 1 0.26672 6 3 1 0.34592 5 4 1 0.02857 9 5 1 0.26672 10 6 1 0.34592 6 [...] 7 40 0.028...
<p>Different ways to do this—like joining the <code>groupby</code> dataframe back to the original—but I'm starting to like the use of <code>transform</code> for stuff like this.</p> <p>The syntax is still verbose, but I think it's more readable than the join method.</p> <pre><code>df['norm_dollar'] = (df['dollar'] ...
python|pandas|numpy|scipy
1
547
57,243,727
Gradients in Keras loss function with RNNs
<p>I have a simple test LSTM model:</p> <pre><code>inputs = Input(shape=(k, m)) layer1 = LSTM(128, activation='relu', return_sequences=True)(inputs) layer2 = LSTM(128, activation='relu')(layer1) predictions = Dense(1, activation='linear')(layer2) model = Model(inputs=inputs, outputs=predictions) </code></pre> <p>and ...
<p>Setting Unroll property helped to resolve the issue:</p> <pre><code>layer1 = LSTM(128, activation='relu', return_sequences=True, unroll=True)(inputs) layer2 = LSTM(128, activation='relu', unroll=True)(layer1) </code></pre>
tensorflow|keras|loss-function
1
548
57,283,440
Compute number of occurance of each value and Sum another column in Pandas
<p>I have a pandas dataframe with some columns in it. The column I am interested in is something like this,</p> <pre><code>df['col'] = ['A', 'A', 'B', 'C', 'B', 'A'] </code></pre> <p>I want to make another column say, <code>col_count</code> such that it shows count value in <code>col</code> from that index to the end...
<p>Use <code>pandas.Series.groupby</code> with <code>cumcount</code> and <code>cumsum</code>.</p> <pre><code>g = df[::-1].groupby('col') df['col_count'] = g.cumcount().add(1) df['X_sum'] = g['X'].cumsum() print(df) </code></pre> <p>Output:</p> <pre><code> col X col_count X_sum 0 A 10 3 70 1 A ...
python|pandas
2
549
57,195,650
Non-reproducible results in pytorch after saving and loading the model
<p>I am unable to reproduce my results in PyTorch after saving and loading the model whereas the in-memory model works as expected. Just for context, I am seeding my libraries, using model.eval to turn off the dropouts but still, results are not reproducible. Any suggestions if I am missing something. Thanks in advanc...
<p>Since the date that Szymon Maszke posted his response above (2019), a new API has been added, <a href="https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html" rel="nofollow noreferrer">torch.use_deterministic_algorithms()</a>.</p> <p>This new function does everything that <code>torch.backe...
deep-learning|pytorch
2
550
23,013,440
how to read "\n\n" in python module pandas?
<p>There is a data file which has <code>\n\n</code> at the end of every line.<br> <a href="http://pan.baidu.com/s/1o6jq5q6" rel="nofollow noreferrer">http://pan.baidu.com/s/1o6jq5q6</a><br> My system:win7+python3.3+R-3.0.3<br> In R </p> <pre><code>sessionInfo() [1] LC_COLLATE=Chinese (Simplified)_People's Republic ...
<p>Your file when read with <code>open('test.pandas', 'rb')</code> seems to contain '\r\r\n' as its line terminators. Python 3.3 does seem to convert this to '\n\n' while Python 2.7 converts it to '\r\n' when read with <code>open('test.pandas', 'r', encoding='gbk')</code>.</p> <p><a href="http://pandas.pydata.org/pand...
python-3.x|pandas
2
551
23,393,397
Code / Loop optimization with pandas for creating two matrixes
<p>I need to optimize this loop which takes 2.5 second. The needs is that I call it more than 3000 times in my script. The aim of this code is to create two matrix which are used after in a linear system.</p> <p>Has someone any idea in Python or Cython?</p> <pre><code> ## df is only here for illustration and date_indic...
<p>Here you go. I tested the following and I get the same resultant matrices in mat and mat_bp as in your original code, but in 0.07 seconds vs. 1.4 seconds for the original code on my machine.</p> <p>The real slowdown was due to using result.index and result2.index. Looking up by a datetime is much slower than lookin...
python|performance|optimization|pandas|cython
1
552
23,447,023
How to create an array of array indexes?
<p>I'm trying to create an array of of the number of elements I have in another array, but appending to the array in a loop gives me too many numbers. </p> <pre><code> xaxis = np.zeros(len(newdates)) for i in newdates: xaxis = np.append(xaxis, i) </code></pre> <p>Instead of [1,2,3,4,.....] like I want, it's givi...
<p>You can avoid the loop entirely with something like (assuming len(newdates) is 3):</p> <pre><code>&gt;&gt;&gt; np.array(range(1, len(newdates)+1)) array([1, 2, 3]) </code></pre>
python|arrays|numpy|indexing
1
553
35,371,499
Vectorize repetitive math function in Python
<p>I have a mathematical function of this form <code>$f(x)=\sum_{j=0}^N x^j * \sin(j*x)$</code> that I would like to compute efficiently in <code>Python</code>. N is of order ~100. This function f is evaluated thousands of times for all entries x of a huge matrix, and therefore I would like to improve the performance (...
<p>Welcome to Sack Overflow! ^^</p> <p>Well, calculating <code>something ** 100</code> is some serious thing. But notice how, when you declare your array <code>J</code>, you are forcing your function to calculate <code>x, x^2, x^3, x^4, ...</code> (and so on) independently.</p> <p>Let us take for example this functio...
python|numpy|vectorization|mathematical-expressions
5
554
35,697,404
Why it's a convention to import pandas as pd?
<p>I see that in the pandas documentation they recommend importing pandas as:</p> <pre><code>import pandas as pd </code></pre> <p>I can see some sense in doing that for when you are using pandas in an interactive context (as with a ipython/jupyter notebook), but I've seen it in production code and in widespread libra...
<p>Because there are <code>built-in</code> methods in python which overlap with the pandas methods. Like <code>map(), all(), any(), filter(), max(), min()</code> and many others. In order to avoid the confusion that these methods used are from pandas or built-in. It is always better to import pandas as <code>import pan...
python|pandas
8
555
50,914,362
Pandas: concatenate strings in column based on a flag in another column until flag changes
<p>I'm trying to concatenate strings in a column based on the values in another column. While this inherently isn't difficult, here the order of the flags matter so I can't think of a pythonic method to accomplish this task (currently trying multiple counters/loops).</p> <p>Example table:</p> <pre><code>text flag...
<p>I'd do it this way:</p> <pre><code>In [6]: (df.groupby(df.flag.diff().ne(0).cumsum(), as_index=False) .agg({'text':'sum','flag':'first'})) Out[6]: text flag 0 ab 0 1 c 1 2 d 0 3 efg 1 </code></pre>
python|pandas
3
556
50,844,505
Using Pandas Getdummies or isin to create Bool Features from feature that contains lists
<p>I have a pandas dataframe with one column containing a list of unique strings for each instance:</p> <pre><code>obj_movies['unique_genres'].head() 0 [Action, Fantasy, Adventure, Science Fiction] 1 [Action, Fantasy, Adventure] 2 [Action, Adventure, Crime] 3 ...
<p>so if your column is composed of lists, you can indeed use <code>get_dummies</code> on your column with a bit of transformation (<code>apply(pd.Series)</code>, <code>stack</code> and then <code>groupby</code>):</p> <pre><code>df_dummies = pd.get_dummies(obj_movies['unique_genres'] ...
python|pandas
1
557
33,160,949
cosine distance between two matrices
<p>Take two matrices, arr1, arr2 of size mxn and pxn respectively. I'm trying to find the cosine distance of their respected rows as a mxp matrix. Essentially I want to take the the pairwise dot product of the rows, then divide by the outer product of the norms of each rows.</p> <pre><code>import numpy as np def cosin...
<p>It sounds like you need to divide by the outer product of the L2 norms of your arrays of vectors:</p> <pre><code>arr1.dot(arr2.T) / np.outer(np.linalg.norm(arr1, axis=1), np.linalg.norm(arr2, axis=1)) </code></pre> <p>e.g.</p> <pre><code>In [4]: arr1 = np.array([[1., -2., 3.], ...
python|numpy|cosine-similarity
4
558
9,104,968
Slow python image processing with PIL and numpy
<p>I'm trying to implement some image processing (finding regions of similar colour) in Python with PIL and Numpy. Can't figure out how to speed up this code. Could you help?</p> <pre><code>def findRegions(self, data): #data is numpy.array ret = [[False for _ in range(self.width)] for _ in range(self.heigth)] ...
<p>Rather than looping over each row and column you can shift the array left, right, up, and down for the appropriate number of elements. On each shift you accumulate your values in a base array. After the shifting and accumulating you compute your average and apply your threshold to return a mask. See this <a href=...
python|image-processing|numpy|python-imaging-library
4
559
6,267,008
Modifying axes on matplotlib colorbar plot of 2D array
<p>I have a 2D numpy array that I want to plot in a colorbar. I am having trouble changing the axis so that they display my dataset. The vertical axis goes 'down' from 0 to 100, whereas I want it to go 'up' from 0.0 to 0.1. So I need to do two things:</p> <ul> <li>Flip the array using np.flipud() and then 'flip' the a...
<p>You want to look at the imshow options "origin" and "extent", I think. </p> <pre><code>import matplotlib.pyplot as plt import numpy as np x,y = np.mgrid[-2:2:0.1, -2:2:0.1] data = np.sin(x)*(y+1.05**(x*np.floor(y))) + 1/(abs(x-y)+0.01)*0.03 fig = plt.figure() ax = fig.add_subplot(111) ticks_at = [-abs(data).max(...
python|numpy|matplotlib|colorbar
9
560
66,377,925
Python: Running Code using Jupyter Notebook (Online)
<p>I am new to the world of Python. I am using a computer with very little space left, so I decided to try to use the online version of Python without explicitly installing anacondas or python.</p> <p>I used this link over here: <a href="https://notebooks.gesis.org/binder/jupyter/user/ipython-ipython-in-depth-eer5tgdf/...
<p>To simplify the development different functionalities are allocated to different scripts/modules.</p> <p>You are simply taking the main script (<code>decision_tree.py</code>) and trying to run it. But it has some imports from other modules. For example, in the directory where you opened <code>decision_tree.py</code>...
python|numpy|matplotlib|module|jupyter-notebook
1
561
66,411,797
Is there an alternative, more efficient way to unstack columns from a multiindex of a pandas dataframe?
<p>I have an object that I got from performing a groupby([&quot;A&quot;, &quot;B&quot;] combined with .nlargest(3) function in pandas.</p> <p>i.e:</p> <pre><code>df.groupby([&quot;A&quot;, &quot;B&quot;])[&quot;Column&quot;].nlargest(3).reset_index().unstack() </code></pre> <p>Now I have 3 values per &quot;A&quot; &quo...
<p>As far as I understand <code>pivot_table</code> should help after some initial prep</p> <p>create the data:</p> <pre><code>import numpy as np np.random.seed(2021) df = pd.DataFrame({'A':np.random.randint(1,3,15), 'B':np.random.randint(1,3,15), 'C':np.random.normal(0,1,15)}) df </code></pre> <p>looks like this</p> <p...
pandas|pandas-groupby
3
562
16,339,704
Converting a numpy string array to integers in base-16
<p>I am looking for a way to convert an array of strings in numpy to the integers they represent in hexadecimal. So in other words, the array version of:</p> <pre><code>int("f040", 16) </code></pre> <p>I can convert a string array to integers base-10 by calling arr.astype(numpy.int32), but I can't see any obvious way...
<pre><code>ar = ['f040', 'deadbeaf'] int_array = [int(a, 16) for a in ar] print int_array </code></pre> <p>output:</p> <p>[61504, 3735928495L]</p>
python|numpy
3
563
57,629,697
How to Transform sklearn tfidf vector pandas output to a meaningful format
<p>I have used sklearn to obtain tfidf scores for my corpus but the output is not in the format I wanted. </p> <p>Code:</p> <pre><code>vect = TfidfVectorizer(ngram_range=(1,3)) tfidf_matrix = vect.fit_transform(df_doc_wholetext['csv_text']) df = pd.DataFrame(tfidf_matrix.toarray(),columns=vect.get_feature_names()) ...
<pre><code>df1 = df.filter(like='word').stack().reset_index() df1.columns = ['filename','word_name','score'] </code></pre> <p>Output:</p> <pre><code> filename word_name score 0 0 word1 0.01 1 0 word2 0.04 2 0 word3 0.05 3 1 word1 0.02 4 1 word2 ...
python|pandas|scikit-learn|tf-idf|tfidfvectorizer
2
564
57,374,748
Pandas: How to convert string to DataFrame
<p>Hi I have the following data (string) and am struggling to convert it into a pandas dataframe.</p> <p>Any help would be greatly appreciated!</p> <p>pd.DataFrame with "," as the delim doesnt work given the commas else where in the data. </p> <pre><code>[["Time","Forecast"],["2019-07-08T23:00:00Z",20],["2019-07-08T...
<p>IIUC, you can use <code>ast.literal_eval</code>:</p> <pre><code>s='[["Time","Forecast"],["2019-07-08T23:00:00Z",20],["2019-07-08T23:30:00Z",26],["2019-07-09T00:00:00Z",24],["2019-07-09T00:30:00Z",26]]' l=ast.literal_eval(s) #convert to actual list of list df=pd.DataFrame(l[1:],columns=l[0]) </code></pre> <hr> <pr...
python|string|pandas|dataframe
3
565
57,677,197
How to extract single word (not larger word containing it) in pandas dataframe?
<p>I would like to extract the word like this:</p> <pre><code>a dog ==&gt; dog some dogs ==&gt; dog dogmatic ==&gt; None </code></pre> <p>There is a similar link: <a href="https://stackoverflow.com/questions/46921465/extract-substring-from-text-in-a-pandas-dataframe-as-new-column">Extract substring from text in a pan...
<p>We can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>str.extract</code></a> with <code>negative lookahead</code>: <code>?!</code>. We check if the the characters after the match are not more than 2 letters. For example <code>do...
python|regex|pandas
4
566
57,461,352
Python n-dimensional array combinations
<p>Suppose an arbitrary number of arrays of arbitrary length. I would like to construct the n-dimensional array of all the combinations from the values in the arrays. Or even better, a list of all the combinations.</p> <p>However, I would also like the previous "diagonal" element along each combination, except when su...
<p>Take a look at <a href="https://docs.python.org/3.7/library/itertools.html#itertools.product" rel="nofollow noreferrer">itertools.product()</a>.</p> <p>To get the "diagonals" you could take the product of the vectors indices instead of the vectors themselves. That way you can access the values of each combination a...
python|pandas|numpy|itertools|n-dimensional
1
567
57,646,858
Python3: fast decode bytes to signed integer, special encoding
<p>I have a connection from my PC to a sensor thru an ethernet connection (UDP protocol) that sends me data. The data looks is a long array of bytes, like this</p> <pre><code>data Out[260]: b'03000248023003e802a003a002f8044003c80478038802f002d8024002b00258030003a80300035002a803c0031002e802c8030802e001f8029002a003c8045...
<p>you didn't provide a complete minimal reproducable question, so i improvised somewhat to make your provided code work.</p> <pre class="lang-py prettyprint-override"><code>data = b"03000248023003e802a003a002f8044003c80478038802f002d8024002b00258030003a80300035002a803c0031002e802c8030802e001f8029002a003c8045002d803f0...
python|decode|numpy-ndarray
0
568
24,166,112
Pandas Dataframe: Adding the occurrence of values
<p>I have a dataframe that contains a list of integers that represent the occurrence of an event. I'm looking to add another column that adds the number of events within an occurrence.</p> <pre><code>d = {'Occurrence_col' : pd.Series([1., 1., 2., 2., 2.]), 'Values' : pd.Series([101, 102, 103, 104, 105])} df = pd....
<p>You can use <code>groupby</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#enumerate-group-items" rel="nofollow"><code>cumcount</code></a> in pandas >= 0.13.0:</p> <pre><code>&gt;&gt;&gt; df["Desired_Output"] = df.groupby("Occurrence").cumcount() + 1 &gt;&gt;&gt; df Occurrence Value...
python|pandas|dataframe
2
569
43,896,553
Variable bidirectional_rnn/fw/lstm_cell/weights already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:
<p>When I call the function tf.nn.bidirectional_dynamic_rnn, it returns Variable bidirectional_rnn/fw/lstm_cell/weights already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:</p> <p>My code:</p> <pre><code>tf.reset_default_graph() sess = tf.InteractiveSession() PAD = 0 EOS = 1...
<p>I would try to define the encoder as follows:</p> <pre><code>with tf.variable_scope('encoder_cell_fw'): encoder_cell_fw = LSTMCell(encoder_hidden_units) with tf.variable_scope('encoder_cell_bw'): encoder_cell_bw = LSTMCell(encoder_hidden_units) ( (encoder_fw_outputs, encoder_bw_outputs), (encoder_fw_fi...
python|tensorflow
0
570
73,137,848
Fill larger dataframe from a smaller dataframe using identical column names
<p>I am trying to merge two dataframes where one has duplicate column names and one with unique names. I am trying to fill in the empty larger one with values from the smaller one based on the column names but the merge or concat statement doesn't seem to work in this case</p> <pre><code>df = pd.DataFrame(data=([1,2,3]...
<p>Would it help you to subset the smaller <code>df</code> with the column names of the empty wider <code>finaldf</code>?</p> <pre class="lang-py prettyprint-override"><code>df[finaldf.columns] A B C B 0 1 2 3 2 1 6 7 8 7 </code></pre>
python|pandas|merge|concatenation
0
571
73,174,486
How to get a correct group in my geopandas project?
<p>I'm making a project which find the nearest linestring(simulate a river) to points or a single point,looks like this:</p> <pre><code>linestrings points linestring1 point1 linestring2 point4 linestring1 point2 linestring2 point5 linestring1 point3 linestring2 point6 </code></pre> <p>And it loo...
<p>you can't group on geometries at all. they're not hashable and can't be used as a pandas index. instead, use geopandas' spatial join tools, such as <a href="https://geopandas.org/en/stable/docs/reference/api/geopandas.sjoin_nearest.html" rel="nofollow noreferrer"><code>geopandas.sjoin_nearest</code></a>:</p> <pre cl...
python|pandas|group-by|geopandas
1
572
10,422,504
line, = plot(x,sin(x)) what does comma stand for?
<p>I'm trying to make an animated plot. Here is an example code:</p> <pre><code>from pylab import * import time ion() tstart = time.time() # for profiling x = arange(0,2*pi,0.01) # x-array line, = plot(x,sin(x)) for i in arange(1,200): line.set_ydata(sin(x+i/10.0)) # update the data ...
<p>The comma is Python syntax that denotes either a single-element tuple. E.g.,</p> <pre><code>&gt;&gt;&gt; tuple([1]) (1,) </code></pre> <p>In this case, it is used for argument unpacking: <code>plot</code> returns a single-element list, which is unpacked into <code>line</code>:</p> <pre><code>&gt;&gt;&gt; x, y = [...
python|numpy|matplotlib
17
573
3,910,301
ndarray field names for both row and column?
<p>I'm a computer science teacher trying to create a little gradebook for myself using NumPy. But I think it would make my code easier to write if I could create an ndarray that uses field names for both the rows and columns. Here's what I've got so far:</p> <pre><code>import numpy as np num_stud = 23 num_assign = 2...
<p>From you description, you'd be better off using a different data structure than a standard numpy array. <code>ndarray</code>s aren't well suited to this... They're not spreadsheets. </p> <p>However, there has been extensive recent work on a type of numpy array that <em>is</em> well suited to this use. <a href="h...
python|numpy
11
574
70,430,166
Is there any vectorized way of check string of column is substring in Pandas?
<p>I have a series of pandas, and I want filter it by checking if strings in columns are substring of another string.</p> <p>For example,</p> <pre class="lang-py prettyprint-override"><code>sentence = &quot;hello world&quot; words = pd.Series([&quot;hello&quot;, &quot;wo&quot;, &quot;d&quot;, &quot;panda&quot;]) </code...
<p>How about:</p> <pre><code>out = words[words.apply(lambda x: x in sentence)] </code></pre> <p>But list comprehension is still pretty fast:</p> <pre><code>out = [w for w in words if w in sentence] </code></pre>
python|pandas
1
575
70,649,379
attributeerror: 'dataframe' object has no attribute 'data_type'
<p>I am getting the following error : <code>attributeerror: 'dataframe' object has no attribute 'data_type'&quot;</code> . I am trying to recreate the code <a href="https://gist.github.com/susanli2016/92c41e7222a5d6d2db933e6d22294d7e" rel="nofollow noreferrer">from this link</a> which is based on this <a href="https://...
<p>The error means you have no <code>data_type</code> column in your dataframe because you missed <a href="https://towardsdatascience.com/multi-class-text-classification-with-deep-learning-using-bert-b59ca2f5c613#5a37" rel="nofollow noreferrer">this step</a></p> <pre><code>from sklearn.model_selection import train_test...
python|pandas
1
576
42,680,133
Copy just two columns from one DataFrame to another in pandas
<p>I have a DataFrame with shape of (418, 13) and I want to just copy the two columns into a new DataFrame for outputting to a csv file. (I am writing a prediction)</p> <pre class="lang-py prettyprint-override"><code>csv_pred = prediction[["PassengerId", "Survived"]].copy() csv_pred.to_csv('n.csv') </code></pre> <p>H...
<p>There is no need to create a new DF:</p> <pre><code>prediction[["PassengerId", "Survived"]].to_csv('/path/to/file.csv', index=False) </code></pre>
python|csv|pandas
5
577
42,752,096
How to get the average of a group every 9 years
<p>I have a data frame called EPI. it looks like this:</p> <p><a href="https://i.stack.imgur.com/OyzZz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OyzZz.png" alt="enter image description here"></a></p> <p>It has 104 countries. Each country has values from 1991 till 2008 (18 years). I want to h...
<p>I think you can first convert years to datetime and then <code>groupby</code> with <code>resample</code> <code>mean</code>. Last convert to <code>year</code>s.</p> <pre><code>#sample data for testing np.random.seed(100) start = pd.to_datetime('1991-02-24') rng = pd.date_range(start, periods=36, freq='A') df = pd.D...
pandas|average|pandas-groupby
0
578
42,676,859
numpy condition loop np.where
<p>I am trying to compare a sample column to two reference columns, D and R. If sample matches D or R it replaces that data with D or R; unless ./. is in the sample column then I want the call to be NR. I have added the LogicCALL column to demonstrate-- in my actual data dataframe those calls would replace (1,0, ./.)</...
<p>It's not a functional syntax but the most readable way to do this would be to procedurally make the assignemnts:</p> <pre><code>df.loc[df['ReferenceD'].astype(str) == df['sample'], 'LogicCALL'] = 'D' df.loc[df['ReferenceR'].astype(str) == df['sample'], 'LogicCALL'] = 'R' df.loc[df['sample'] == './.', ...
python|loops|numpy|conditional-statements
0
579
43,023,665
using pandas to create a multi-tile multi-series scatter chart
<p>Consider the following sample data frame:</p> <pre><code>rng = pd.date_range('1/1/2011', periods=72, freq='H') df = pd.DataFrame({ 'cat': list('ABCD'*int(len(rng)/4)), 'D1': np.random.randn(72), 'D2': np.random.randn(72), 'D3': np.random.randn(72), 'D4': np.random.randn(72) ...
<p>This is my guess at what you want.</p> <pre><code>fig, axes = plt.subplots(2, 2, figsize=(8, 6), sharex=True, sharey=True) for i, (cat, g) in enumerate(df.groupby('cat')): ax = axes[i // 2, i % 2] for j, c in g.filter(like='D').iteritems(): c.plot(ax=ax, title=cat, label=j, style='o') ax.legend...
python|pandas|plot|scatter|tiling
1
580
42,784,768
python: Multiply slice i of a matrix stack by column i of a matrix efficiently
<pre><code>import numpy as np M,N,R = 2,3,4 # For a 3-dimensional array A: A = np.reshape(np.r_[0:M*N*R], [M,N,R], order = 'C') # and 2-dimensional array B: B = np.reshape(np.r_[0:M*R], [R,M], order = 'C') </code></pre> <p>I would like the <code>N*M</code> matrix that results from multiplying slice <code>i</code> of...
<p>With <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a>, we would have -</p> <pre><code>np.einsum('ijk,ki-&gt;ji',A,B) </code></pre> <p>Let's verify the results using the given sample and using matrix-multiplication with <code>np.do...
python|arrays|numpy
2
581
26,996,140
Ploting the same numerical relationship in multiple units / representations
<p>Consider an <code>X</code> and <code>Y</code> relationship where, for a change in the <strong>unit system</strong> in <code>X</code> and <code>Y</code>, the numerical relationship does <strong>not</strong> change.</p> <p>How can I plot this relationship in both unit systems on the <strong>same</strong> plot? (i.e. s...
<h3>The Original Answer</h3> <p><a href="http://matplotlib.org/examples/subplots_axes_and_figures/fahrenheit_celsius_scales.html" rel="nofollow noreferrer">This example</a>, from the excellent matploblib documentation, exactly solves your problem, except that you may want to use an <em>ad hoc</em> solution for the sec...
python|numpy|matplotlib
1
582
14,493,026
Read Values from .csv file and convert them to float arrays
<p>I stumbled upon a little coding problem. I have to basically read data from a .csv file which looks a lot like this:</p> <pre><code>2011-06-19 17:29:00.000,72,44,56,0.4772,0.3286,0.8497,31.3587,0.3235,0.9147,28.5751,0.3872,0.2803,0,0.2601,0.2073,0.1172,0,0.0,0,5.8922,1,0,0,0,1.2759 </code></pre> <p>Now, I need to ...
<p>Boy, have I got a treat for you. <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow">numpy.genfromtxt</a> has a <code>converters</code> parameter, which allows you to specify a function for each column as the file is parsed. The function is fed the CSV string value. Its...
python|arrays|csv|numpy|data-conversion
6
583
25,024,679
Convert years into date time pandas
<p>If I have a list of integers (e.g. [2006, 2007, 2008, 2009, ...]), and I have them set as a Pandas DataFrame index, how do I convert that index into a Datetime index, so when plotting the x-axis is not represented as [0, 1, 2, 3...] +2.006E3?</p>
<p>You can construct a DatetimeIndex if you cast the integers as strings first, i.e.</p> <pre><code>index = pd.DatetimeIndex([str(x) for x in [2005,2006,2007]]) </code></pre> <p>will give you a DatetimeIndex with January 1 of each year.</p>
datetime|pandas
1
584
39,138,299
Dataframe Simple Moving Average (SMA) Calculation
<p>Is there any simple tool/lib that can help me easily calculate the Simple Moving Average SMA(N) of dataframe ?</p> <pre><code> GLD SMA(5) Date 2005-01-03 00:00:00+00:00 43.020000 Nan 2005-01-04 00:00:00+00:00 42.740002 Nan 2005-01-05 00:00:00+00:0...
<pre><code>df['SMA(5)'] = df.GLD.rolling(5).mean() df </code></pre> <p><a href="https://i.stack.imgur.com/Li6Ke.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Li6Ke.png" alt="enter image description here"></a></p>
python|pandas|dataframe
14
585
39,001,457
hdf5 not supported (please install/reinstall h5py) Scipy not supported! when importing TFLearn?
<p>I'm getting this error:</p> <pre><code>hdf5 not supported (please install/reinstall h5py) Scipy not supported! </code></pre> <p>when I try to import <code>tflearn</code>. And I think due to this problem my TFLearn code is not working properly?</p>
<p>I ran into the same issue a few minutes ago, pretty much you just need to reinstall h5py using the package manager of your current environment. </p> <p><a href="http://docs.h5py.org/en/latest/build.html" rel="noreferrer">http://docs.h5py.org/en/latest/build.html</a></p>
python|scipy|tensorflow
10
586
12,840,847
Filling higher-frequency windows when upsampling with pandas
<p>I am converting low-frequency data to a higher frequency with pandas (for instance monthly to daily). When making this conversion, I would like the resulting higher-frequency index to span the entire low-frequency window. For example, suppose I have a monthly series, like so:</p> <pre><code>import numpy as np from ...
<p>How about this?</p> <pre><code>s.reindex(DatetimeIndex(start=s.index[0].replace(day=1), end=s.index[-1], freq='D')) </code></pre>
python|pandas
5
587
33,673,971
Find a string in a huge string file
<p>I have to find a list of strings in a txt.file</p> <p>The file has 200k+ lines</p> <p><strong>This is my code:</strong> </p> <pre><code>with open(txtfile, 'rU') as csvfile: tp = pd.read_csv(csvfile, iterator=True, chunksize=6000, error_bad_lines=False, header=None, skip_blank_lines=True, ...
<p>Do you really need to open the file first then use pandas? If it's an option you can just read with pandas then <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">concatenate</a>.</p> <p>To do that just use <code>read_csv</code>, <code>concat</code> the files, then loop through them.<...
python|performance|csv|pandas
1
588
33,831,395
How do I split repeated blocks of data into multiple columns and parse datetime?
<pre><code>import pandas as pd f = pd.read_table('151101.mnd',header = 30) print f.head() print f.shape 2015-11-01 00:10:00 00:10:00 0 # z speed dir W sigW bck error 1 30 5.05 333.0 0.23 0.13 1.44E+05 0.00 2 40 5.05 337.1 -0.02 0.14 7.69E+03 0.00 ...
<h2>Case ( 1 ) rows repeat themselves at the same step</h2> <hr> <pre><code>pd.read_table(sep = '\s+', skiprows = np.arange(0 , 4607, 32)) </code></pre> <h2>Case ( 2 ) the unwanted rows appear randomly</h2> <hr> <p>if not so you've to remove it manually , so you need first to load your data into single column</p> ...
python|file|pandas|dataframe|multiple-columns
1
589
23,492,409
Adding labels to a matplotlib graph
<p>Having the following code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates days, impressions = np.loadtxt('results_history.csv', unpack=True, delimiter=',',usecols=(0,1) , converters={ 0: mdates.strpdate2num('%d-%m-%y')}) plt.plot_date(x=days, y=impressi...
<p>You need <a href="http://matplotlib.org/users/annotations_intro.html" rel="nofollow">annotate</a>, e.g.:</p> <pre><code>plt.annotate('some text',xy=(days[0],impressions[0])) </code></pre> <p>To adjust the x axis text you could add:</p> <pre><code>fig=plt.figure() # below the import statements ... fig.autofmt_xdat...
python|csv|numpy|matplotlib
5
590
22,516,290
Pandas idiom for attaching a predictions column to a dataframe
<p>What is the Pandas idiom for attaching the results of a prediction to the dataframe on which the prediction was made.</p> <p>For example, if I have something like (where <code>qualityTrain</code> is the result of a <code>stats models</code> <code>fit</code>)</p> <pre><code>qualityTrain = quality_data[some_selectio...
<p>You can just do</p> <pre><code>qualityTrain['Pred1'] = pred1 </code></pre> <p>Note that we're (statsmodels) going to have pandas-in, pandas-out for predict pretty soon, so it'll hopefully alleviate some of these pain points.</p>
indexing|pandas|dataframe|statsmodels
1
591
13,592,618
python pandas dataframe thread safe?
<p>I am using multiple threads to access and delete data in my pandas dataframe. Because of this, I am wondering is pandas dataframe threadsafe?</p>
<p>No, pandas is not thread safe. And its not thread safe in surprising ways.</p> <ul> <li>Can I delete from pandas dataframe while another thread is using?</li> </ul> <p>Fuggedaboutit! Nope. And generally no. Not even for GIL-locked python datastructures.</p> <ul> <li>Can I read from a pandas object while someone else...
python|thread-safety|pandas
33
592
29,688,899
Pandas: Checking if a date is a holiday and assigning boolean value
<p>I have a pandas data frame with date column, and I am trying to add a new column of boolean values indicating whether a given date is a holiday or not.</p> <p>Following is the code, but it does not work (all the values are False) because the types seem to be different, and I can't figure out how to get the 'date' i...
<p>You don't need to convert anything. Just compare straight up. <code>pandas</code> is smart enough to compare a lot of different types with regards to dates and times. You have to have a slightly more esoteric format if you're having issues with date/time compatibility.</p> <pre><code>import pandas as pd from pandas...
python|pandas
50
593
62,239,130
What is the best way to calculate the standard deviation
<p>I have a 50x22 matrix/vector, and i need to calculate the standard deviation from each column, precisely it looks like this.<a href="https://i.stack.imgur.com/idagY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/idagY.jpg" alt="enter image description here"></a></p> <p>For instance, the first co...
<p>I am not sure what you are really asking, but if your array is <code>foo</code>, then</p> <pre><code>np.std(foo, axis=0) </code></pre> <p>Will compute the standard deviations of all the columns.</p>
python|arrays|python-3.x|numpy|statistics
1
594
62,419,661
Pandas style applymap highlight duplicates with lambda function
<p>I have a Pandas dataframe and am working in a Jupyter notebook. I want to highlight rows in which column pairs are duplicated. Here is an example:</p> <pre><code>colA = list(range(1,6)) colB = ['aa', 'bb', 'aa', 'cc', 'aa'] colC = [14,3,14,9,12] colD = [108, 2001, 152, 696, 696] df = pd.DataFrame(list(zip(colA, col...
<p>Personally, I would break the problem into two steps rather than use one complicated lambda function. We can find the index of all the duplicate rows, then highlight the rows by index number. Also don't forget that in your lambda function, you should use a list comprehension in what you are returning.</p> <pre><cod...
python-3.x|pandas|jupyter-notebook|duplicates|highlight
4
595
62,109,730
Sorting columns having lists with reference to each other in pandas
<p>Suppose my data frame is like:</p> <pre><code> A B Date [1,3,2] ['a','b','c'] date1 </code></pre> <p>I want to sort both the columns but with reference to each other. Like the output should be:</p> <pre><code> A B Date [1,2,3] ['a','c','b'] date1 </cod...
<p>If all cells have the same number of values, try this flattening and groupby approach:</p> <pre><code>df A B 0 [1, 3, 2] [a, b, c] 1 [4, 6, 5] [d, f, e] # added an extra row for demonstration </code></pre> <p></p> <pre><code>(df.apply(pd.Series.explode) .groupby(level=0) .apply(lamb...
python|pandas
2
596
62,110,398
I can't install tensorflow on win10
<p>I can't install tensorflow I commanded pip3 install tensorflow --user and result is </p> <blockquote> <p><code>ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\\Users\\kosh9\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\\LocalCac...
<p>Try installing directly form PyPi.</p> <p>Your on a Windows system so try one of these:</p> <p><code>pip install tensorflow-gpu</code> or if on an Intel processor <code>pip install intel-tensorflow</code></p> <p>If that dons't work try to grab the <code>.whl</code> file. For Python 3.8 on windows that's: <code>p...
python|tensorflow|environment
0
597
51,349,186
ValueError: could not broadcast input array from shape (11253,1) into shape (11253)
<p>I am creating a Neural Network using this <a href="https://machinelearningmastery.com/time-series-prediction-with-deep-learning-in-python-with-keras/" rel="nofollow noreferrer">example</a> and I am getting the error "ValueError: could not broadcast input array from shape (11253,1)" into shape (11253), in the line : ...
<p>Convert <code>trainPredict</code> from 2D array to 1D vector before assigning:</p> <pre><code>trainPredictPlot[look_back:len(trainPredict)+look_back] = trainPredict.ravel() </code></pre>
python|tensorflow|neural-network
1
598
51,274,847
How to optimize chunking of pandas dataframe?
<p>I need to split my dataset into chunks, which i currently do with the following simple code:</p> <pre><code> cases = [] for i in set(df['key']): cases.append(df[df['key']==i].copy()) </code></pre> <p>But my dataset is huge and this ends up taking a couple hours, so I was wondering if there is a way ...
<p>I'm fairly certain you want to group-by unique keys. Use the built-in functionality to do this.</p> <pre><code>cases = list(df.groupby('key')) </code></pre>
python|pandas|python-multiprocessing|python-multithreading
1
599
51,294,657
I need to get only the next sequence of variable in timestamp format
<pre><code>#count ,date 98.000000, 2014-03-16 267.000000, 2014-03-23 298.000000, 2014-03-30 313.000000, 2014-04-06 225.000000, 2014-04-13 226.000000 2014-04-20 </code></pre> <p>I have two variables: one is count and other is date time with week sequence in it.</p> <p>When I concatenate the first variable with...
<pre><code>import pandas as pd import datetime df = pd.read_csv("ex1.csv", names=['count', 'date'], index_col='date') df2 = pd.DataFrame(); df2['count'] = [50]; df2['date'] = pd.to_datetime(df.index.values[len(df)-1]) + ( datetime.datetime.strptime(df.index.values[len(df)-1], "%Y...
python|python-3.x|pandas|datetime|dataframe
1