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
364,100
60,874,814
pairwise t-tests on numpy arrays
<p>I am trying to run some t-tests in one-dimensional arrays and get all their pairwise results. Ι am not sure how to do it though. I know how to do it for those ones, with slicing each array from the list, but I don't want to hardcode it, rather I'd like it to work for any list of 1-d arrays.</p> <pre><code>import nu...
<p>you can use <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow noreferrer">itertools.combinations</a>:</p> <pre><code>import numpy as np from scipy import stats from itertools import combinations a = np.random.randint(10, size=100) b = np.random.randint(10, size=160) c...
python|arrays|python-3.x|list|numpy
0
364,101
61,016,701
Issue in applying str.contains across multiple columns in Python
<p>Dataframe:</p> <pre><code>col1 col2 col3 132jh.2ad3 34.2 65 298.487 9879.87 1kjh8kjn0 98.47 79.8 90 8763.3 7hkj7kjb.k23l 67 69.3 3765.9 3510 </code></pre> <p>Desired output:</p> <pre><code>col1 col2 ...
<p>You can just use <code>to_numeric</code>:</p> <pre><code>df[df.apply(pd.to_numeric, errors='coerce').notnull().all(1)] </code></pre> <p>Output:</p> <pre><code> col1 col2 col3 2 98.47 79.8 90 4 69.3 3765.9 3510 </code></pre>
python|pandas|dataframe
4
364,102
60,796,321
Slice indices must integer
<p>I am working on ODE circuit suddenly face this problem . How to solve it ?</p> <p><a href="https://i.stack.imgur.com/K5bPb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K5bPb.png" alt="enter image description here"></a></p>
<p>Most probably, if your N/2 is not an integer, you get such an error.</p> <p>I would change to <code>w[0:int(N/2)+1] = 2</code>....</p> <p>This is also available for every place you divide <code>N/2</code>.</p>
numpy|tensorflow|ode|numpy-slicing
1
364,103
60,821,865
convert all duplicates of permutation into one unique element
<p>I have a data which contains the following 10 words:</p> <p>[A,B,C,D,E,F,G,H,I,J]</p> <p>I have a dataset which contains permutations of these words such as:</p> <ul> <li>A,B</li> <li>A,B,C,D</li> <li>E,F,G</li> <li>H ... and so on. </li> </ul> <p>Most of the combinations are non-repetitive, but unfortunately, t...
<p>You could use a set of frozensets. Assuming that dataset is a list of lists (or more generally an iterable of iterables, you could do:</p> <pre><code>resul = set((frozenset(elt) for elt in dataset)) </code></pre> <p>Inner elements have to be <code>frozenset</code>, because a set cannot contain mutable elements.</p...
python|pandas|numpy|math|permutation
1
364,104
61,144,300
Pandas: remove duplicate multiple conditions based on column values
<p>I have a big multi-index dataframe with lots of columns with lots of duplicate timestamps.</p> <p>Now I want to drop duplicates but the problem is I want to keep the max value for column 1 and last value for other columns.</p> <pre><code>timestep headers col1 col2 col3 1 2 5 ...
<p>If you <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>.groupby()</code></a> on the index you can take the <code>.max()</code> of each column:</p> <pre class="lang-py prettyprint-override"><code>df.groupby(df.index).max() </code></pr...
python|pandas|dataframe
1
364,105
60,773,640
python pandas index of ones (1s) at row-wise
<p>From Pandas Dataframe, how to get the index of all ones at the row level?</p> <p>My data frame has around a hundred columns. here is an example:</p> <pre><code> a b c d 0 1 0 1 0 1 0 0 0 1 2 1 1 0 1 3 1 1 0 0 4 1 1 1 1 </code></pre> <p>The e...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df=df.stack() df=df.loc[df.eq(1)].reset_index(level=1).groupby(level=0).agg(', '.join) </code></pre> <p>Outputs:</p> <pre class="lang-py prettyprint-override"><code> level_1 0 a, c 1 d 2 a, b, d 3 a, b 4 a, b, c, d </code><...
python|pandas
1
364,106
60,801,316
How to Conditionally Remove Duplicates from Pandas DataFrame with a List
<p>I have a <code>df</code>, and want to remove all duplicates on <code>ID</code>.</p> <pre><code> Name Symbol ID 0 ZOO INC Remove 88579Y101 1 Zoo Inc ZZZ 88579Y101 2 A Inc AAA 90138A103 3 a inc. Remove 90138A103 4 2U Inc TWUO 90214J101 5 Keep R...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</code></a> with <code>keep=False</code> for all dupes and chain with compare for <code>Remove</code>, chain together by <code>|</code> for bitwise <code>OR</code> an...
python|pandas|dataframe|duplicates
4
364,107
61,128,913
how to simulate pandas dataframe data with increment datetime
<p>In python3 and pandas:</p> <p>assuming i have a dataframe:</p> <pre><code>datetime,id,value 2020-03-12,1,100 2020-03-13,1,105 2020-03-14,1,110 2020-03-12,2,100 2020-03-13,2,105 2020-03-14,2,110 </code></pre> <p>I am trying to simulate these datasets with x extra historical days. </p> <p>Let us say x=2 for now, a...
<p>one way could be to <code>set_index</code> the datetime and id columns, then <code>reindex</code> with all the dates you want generated through <code>date_range</code> using <a href="https://pandas.pydata.org/docs/reference/api/pandas.MultiIndex.from_product.html" rel="nofollow noreferrer"><code>pd.MultiIndex.from_p...
python|pandas
2
364,108
61,148,962
Why am I not getting the same result every time I run through my loop?
<p>I'm doing some signal processing, and I have a loop in Python in which I'm trying to optimize a result, ln(B), over a parameter alpha. When I ran it, I got an optimal alpha value of -0.8, but when I used it in my regular code it gave me a different result than the loop had given me. For clarity's sake, the regular c...
<p>Possibly, as you iterate over <code>nf in fzoomindx</code>, you change <code>nf</code>, which is used in calculation of <code>denominator</code> in <code>denominator += (n*fecho)**(2-2*alpha)/(var_f[n*nf])**2</code> ...</p>
python|numpy|loops
3
364,109
60,799,113
Tensorflow - adding Dropout layer increases inference time significantly
<p>I have relatively small CNN</p> <pre><code>model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(input_shape=(400,400,3), filters=6, kernel_size=5, padding='same', activation='relu'), tf.keras.layers.Conv2D(filters=12, kernel_size=3, padding='same', activation='relu'), tf.keras.layers.Conv2D(filte...
<p>Apparently this is a known problem in TensorFlow 2.0.0: <a href="https://github.com/tensorflow/tensorflow/issues/33487#issuecomment-589441736" rel="noreferrer">see this GitHub comment</a>.</p> <p>Try to use <code>model.predict(x)</code> instead of <code>model(x)</code>.</p> <p>This can also be fixed by updating to...
performance|tensorflow|deep-learning
5
364,110
60,976,101
Finding the difference between two data frames
<p>I have two data frames say df1, df2 each has two columns <code>['Name', 'Marks']</code></p> <p>I want to find the difference between the two ifs for corresponding Name Values.</p> <p>Eg: </p> <pre><code>df = pd.DataFrame([["Shivi",70],["Alex",40]],columns=['Names', 'Value']) df2 = pd.DataFrame([["Shivi",40],["And...
<p>You can use:</p> <pre><code>diff = df1.set_index("Name").subtract(df2.set_index("Name"), fill_value=0) </code></pre> <p>So a complete program will look like this:</p> <pre><code>import pandas as pd data1 = {'Name': ["Ashley", "Tom"], 'Marks': [40, 50]} data2 = {'Name': ["Ashley", "Stan"], 'Marks': [80, 90]} df1...
python|pandas|numpy|dataframe
2
364,111
60,999,753
Pandas, Future Warning: Indexing with multiple keys
<p>Pandas throws a Future Warning when I apply a function to multiple columns of a groupby object. It suggests to use a list as index instead of tuples. How would one go about this?</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]]) &gt;&gt;&gt; df.groupby([0,1])[1,2].apply(sum) &lt;stdin&gt;:1: ...
<p>This warning was introduced in pandas 1.0.0, following a <a href="https://github.com/pandas-dev/pandas/issues/23566" rel="noreferrer">discussion on GitHub</a>. So best use what was suggested there:</p> <pre class="lang-py prettyprint-override"><code>df.groupby([0, 1])[[1, 2]].apply(sum) </code></pre> <p>It's also po...
python|pandas
59
364,112
60,776,788
How can I convert individual days into one date colum of Pandas
<p>I have a pandas data frame with each day as a column. I would like to convert the dates into a single data column to perform some analysis. I tried searching at many places but none of them talk about this scenario.</p> <pre><code>Product_ID 1/22/2020 1/23/2020 1/24/2020 1/25/2020 1/26/2020 ABC 1...
<p>If your initial data frame looks like this:</p> <pre><code>data = { 'Product_ID': {0: 'ABC', 1: 'ABD', 2: 'ABC', 3: 'ABD', 4: 'ABC', 5: 'ABE'}, '1/22/2020': {0: 1, 1: 2, 2: 0, 3: 1, 4: 3, 5: 6}, '1/23/2020': {0: 3, 1: 1, 2: 1, 3: 1, 4: 0, 5: 2}, '1/24/2020': {0: 2, 1: 2, 2: 0, 3: 1, 4: 0, 5: 2}, ...
python|pandas
1
364,113
71,490,868
How can i fix "(df[df['id']==id_value].name == 1).any()" 'The truth value of a Series is ambiguous error'?
<p>The following code will run fine in most cases in python(jupyter), but I'm getting an error from time to time in my web app using the following code:</p> <pre><code> if (df[df['id']==id_value].name == 1).any(): </code></pre> <p>I haven't been able to determine in which case the error occurred because it was used in ...
<p>Change to <code>isin</code> + <code>loc</code></p> <pre><code> if (df.loc[df['id'].isin(id_value),'name']== 1).any(): </code></pre>
python|pandas|dataframe
1
364,114
71,640,929
ModuleNotFoundError: No module named 'numpy.random.bit_generator'
<p>I would like to use the <code>classification_report</code> module from <code>sklearn.metrics</code> in my project. However, I am receiving this error message which I am not sure how to resolve.</p> <pre><code>from sklearn.metrics import classification_report File &quot;C:\ProgramData\Anaconda3\envs\tf\lib\site-pac...
<p>Running the following line, forced to reinstall the <code>numpy</code> package. Since the package was somehow corrupted, it was fixed.</p> <pre><code>conda install numpy --force-reinstall </code></pre>
numpy|scikit-learn|anaconda3
2
364,115
71,600,714
Pandas Time difference of each column
<p>I have this dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>STEP 1</th> <th>STEP 2</th> <th>...</th> <th>STEP 40</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2022-03-08 09:23:35</td> <td>2022-03-08 10:23:35</td> <td>...</td> <td>2022-03-19 09:23:35</td> </tr> <t...
<p>Use vectorial code.</p> <p>If you don't have datetime type, uncomment the second step:</p> <pre><code>out = ( df.set_index('ID') #.apply(lambda c: pd.to_datetime(c)) .diff(axis=1).iloc[:, 1:] .set_axis([f'Time {i+1}-{i+2}' for i in range(len(df.columns)-2)], axis=1) .reset_index() ) </code></pre> <p>out...
python|pandas|dataframe
0
364,116
71,777,990
Remove related row from pandas dataframe
<p>I have the following dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>relatedId</th> <th>coordinate</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>125</td> <td>55</td> </tr> <tr> <td>125</td> <td>123</td> <td>45</td> </tr> <tr> <td>128</td> <td>130</td> <td>60</t...
<p>You can sort the values and get the first value per group using a <code>frozenset</code> of the 2 ids as grouper:</p> <pre><code>(df .sort_values(by='coordinate') .groupby(df[['id', 'relatedId']].agg(frozenset, axis=1), as_index=False) .first() ) </code></pre> <p>output:</p> <pre><code> id relatedId coordina...
pandas|dataframe
1
364,117
71,490,552
Is there any way I can plot each of my for loops as a subplot?
<p>Probably a really stupid question but I am trying to condense my use of plots for my current project as it is currently producing a lot of them I will have to use as appendices for my thesis.</p> <p>Below I've attached my current code which iterates through a list of dataframes to generate multiple plots using Matpl...
<p>Create a plot with 5 panels arranged in 5 rows, 1 column:</p> <pre><code>fig, ax = plt.subplots(5,1, figsize=(10,20)) #find an appropriate size for i, (title, df) in enumerate(df_list): ... percentageChange['Normalised Direct Involvement'].plot(ax=ax[i], label='Direct') percentageChange['Normalised I...
python|pandas|csv|matplotlib|visualization
0
364,118
71,677,264
Python: change column month to separate quarter columns; SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
<p>I would like to add to my DF 4 new columns with boolean type representing quarters of the year. I have column with month numbers and would like to get this result:</p> <pre><code>month Q1 Q2 Q3 Q4 6 0 1 0 0 7 0 0 1 0 8 0 0 1 0 9 0 0 1 0 10 0 0 0 1 11 ...
<p>Do not loop, you should rather <code>map</code> and <code>get_dummies</code>:</p> <pre><code>quarters = {'Q1': [1, 2, 3], 'Q2': [4, 5, 6], 'Q3': [7, 8, 9], 'Q4': [10, 11, 12]} # compute a better mapping format d = {k:v for v,l in quarters.items() for k in l} # {1: 'Q1', 2: 'Q1', 3: 'Q1', 4: 'Q2'...} df.join(pd.get_...
python|pandas|dataframe|pandas-settingwithcopy-warning
0
364,119
71,472,485
Is this an efficient method of updating columns based on conditions in other columns using pandas
<p>Is this an efficient method of updating columns based on conditions in other columns using pandas? I am looking to generalize an update function that will move gaussian values and I had difficulty using lambda because there are multiple columns that could be conditions. Similarly apply was problematic because I coul...
<p>I'm not sure the examples below are any faster (I'm sure the <code>apply()</code> is slower), but it's how I would do it. Looking back on your problem - I'm not sure it's even different enough to write up, but here it is.</p> <h2>Make the data</h2> <pre class="lang-py prettyprint-override"><code>import numpy as np ...
python|pandas|dataframe
0
364,120
71,598,273
How to create two dataframes from a given dataframe?
<p>Assume I have the following data frame:</p> <p><a href="https://i.stack.imgur.com/rzR74.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rzR74.png" alt="enter image description here" /></a></p> <p>I want to create two data frames such that for any row if column <code>Actual</code> is equal to colum...
<p>Use boolean indexing:</p> <pre><code>m = df['Actual'] == df['Predicted'] correct_df = df.loc[m] incorrect_df = df.loc[~m] </code></pre>
python|python-3.x|pandas|dataframe
1
364,121
71,615,080
Calculate counter for each month for dataframe in Python
<p>I have the following dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>cluster_ID</th> <th>counter_1</th> <th>counter_2</th> <th>date</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>1</td> <td>0</td> <td>2021-01-02 10:00:00</td> </tr> <tr> <td>0</td> <td>1</td> <td>2</td> <td>20...
<p>You can convert datetimes to <code>YYYY-MM</code> strings, pivoting by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with <code>aggfunc='sum'</code>, sorting columns by dates and flatten <code>Mul...
python|pandas|dataframe|date
0
364,122
71,623,688
How to change float to date type in python? (ValueError: day is out of range for month)
<p>I have the following column:</p> <pre><code>0 3012022.0 1 3012022.0 2 3012022.0 3 3012022.0 4 3012022.0 ... 351 24032022.0 352 24032022.0 df.Data = df.Data.astype('str') </code></pre> <p>I converted the float to string and I'm trying to transform them in datetype:<...
<p>Convert to string, remove the decimal point and coerce to datettime. Code as follows</p> <pre><code> df['data'] = pd.to_datetime(df['data'].astype(str).str.split('\.').str[0], format='%d%m%Y') data 0 2022-01-30 1 2022-01-30 2 2022-01-30 3 2022-01-30 4 2022-01-30 351 2022-03-24 352 2022-03-24 </code>...
python-3.x|pandas|dataframe|datetime
0
364,123
71,746,987
How can generator get input noise z?
<p>Hi I'm looking this GAN implementation code. <a href="https://github.com/eriklindernoren/PyTorch-GAN/blob/36d3c77e5ff20ebe0aeefd322326a134a279b93e/implementations/gan/gan.py" rel="nofollow noreferrer">code here</a></p> <p>My question is generator class has no input parameter when defining class Generator(#38 from th...
<p>Consider every quoted line (38, 88 and 141):</p> <ul> <li>On line 38 is a definition of class, by putting <code>nn.Module</code> in brackets it's declaring inheritance of <code>class Generator</code> from <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html" rel="nofollow noreferrer">class nn.Modu...
pytorch|generative-adversarial-network
0
364,124
71,486,471
How to find elements that are in first pandas Data frame and not in second, and viceversa. python
<p>I have two data frames.</p> <p><code>first_dataframe</code></p> <pre><code>id 9 8 6 5 7 4 </code></pre> <p><code>second_dataframe</code></p> <pre><code>id 6 4 1 5 2 3 </code></pre> <p><strong>Note:</strong> My dataframe has many columns, but I need to compare only based on ID | I need to find:</p> <ol> <li>ids that ...
<p>Use <code>set</code> subtraction:</p> <pre><code>inDF1_notinDF2 = set(df1['id']) - set(df2['id']) # Removes all items that are in df2 from df1 inDF2_notinDF1 = set(df2['id']) - set(df1['id']) # Removes all items that are in df1 from df2 </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; inDF1_notinDF2 {7, 8, 9} ...
python|python-3.x|pandas|dataframe|data-science
0
364,125
71,504,776
How to create a new column based on the mean difference between date columns in a data frame?
<p>I have a data-frame formatted like so (I simplified it for the sake of my explanation):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Date_1</th> <th style="text-align: center;">Date_2</th> <th style="text-align: center;">Date_3</th> </tr> </thead> <tbody> <tr...
<p>Interesting problem. Since you're getting the diffs of several items in each row, <code>itertools.combinations(iterable, N)</code> will help. It returns all a possible <code>N</code>-length combinations of the items in <code>iterable</code>. So we can use that for each row, diff each combination, absolute it (since ...
python|pandas|dataframe
1
364,126
71,529,640
Pandas set values for part of column with multiindex
<p>I'm sure that there is a simple way to do this, but I can't seem to find it. Essentially, I have a <code>DataFrame</code> with a <code>MultiIndex</code> and I want to set one part of a column (corresponding to a value in the first index level) with a <code>Series</code>. However, whatever I try, the values are being...
<p>Assuming you don't have in s values that are not present in df's Index, you could do:</p> <pre><code>df.loc[('a1', s.index), 'col3'] = s.values </code></pre> <p>This will work independently of the order of s</p> <p>output:</p> <pre><code> col1 col2 col3 idx1 idx2 a1 b1 0 1 ...
python|pandas|multi-index
1
364,127
71,669,183
How to insert a value in a fixed positon of pytorch
<p>I have a PyTorch tensor</p> <pre><code>x = [[1,2,3,4,5]] </code></pre> <p>Now I want to add a value to a fixed position of the tensor x, for example, I want to add 11 in position 3 then the x will be</p> <pre><code>x= [[1,2,3,11,4,5]] </code></pre> <p>How can I perform this operation in Pytorch?</p>
<p>Dynamically extending arrays to arbitrary sizes along the non-singleton dimensions, such as the ones you mentioned, are unsupported in PyTorch mainly because the memory is <em>pre-allocated</em> during tensor construction and set to fixed size depending on the data type. The only way to <em>grow</em> non-singleton d...
python|pytorch|tensor
1
364,128
71,618,760
Python - How to set exact values to the Y Axis
<p>I already saw many explanations about the right way to do it. But, it seems I am not capable of seeing what I am doing wrong... I just want to have to the Y axe the values 0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90% and 100%.</p> <p>My code is:</p> <pre><code>MPPDataframe = pd.DataFrame(listaPDS, columns = [&quo...
<p>First of all, when yoh had some problems with matplotlib, check official documentation: <a href="https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.yticks.html" rel="nofollow noreferrer">https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.yticks.html</a></p> <pre><code>plt.yticks(np.arange(0,10,100)) ...
python|pandas|matplotlib
0
364,129
71,702,857
influx result set to datetime column pandas
<p>i have influxdb result set as</p> <pre><code>results2 = ResultSet({'('options_price_reference_limits', None)': [{'time': '2022-03-22T16:37:39.643127Z', 'lower_boundary': -439.8286562572736, 'mark_price': 144.060885, 'symbol': 'C-BTC-44000-250322', 'upper_boundary': 556.8514272321878}, {'time': '2022-03-22T16:37:44.6...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>Series.dt.floor</code></a> for remove miliseconds with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.tz_convert.html" rel="nofollow noreferrer"><co...
python|pandas|dataframe|datetime|series
2
364,130
71,632,415
subtract value from next rows until condition then subtract new value
<p>say I have:</p> <pre><code>df ={'animal' : [1, 1, 1, 1, 1, 1, 1, 2, 2], 'x':[76.551, 77.529, 78.336,77, 78.02, 79.23, 77.733, 79.249, 76.077], 'y': [151.933, 152.945, 153.970, 119.369, 120.615, 118.935, 119.115, 152.004, 153.027], 'time': [0, 1, 2, 0, 3,2,5, 0, 1]} df = pd.DataFrame(df) # get distanc...
<p>You can create a boolean mask based on <code>start</code>, and then use <code>cumsum</code> to turn that into a perfect grouper. Group by it, and then get the first value of <code>x</code> and <code>y</code> for each group. Subtract <code>x</code> and <code>y</code> from those firsts and you have your new columns:</...
python|pandas
1
364,131
71,591,455
Creating a new column in dask (arrays ,list)
<p>What would be the equivalent of transforming this to a dask format</p> <pre class="lang-py prettyprint-override"><code>df['x'] = np.where(df['y'].isin(a_list), 'yes', 'no') </code></pre> <p>The <code>df</code> will be a dask dataframe with <code>n</code> partitions and <code>a_list</code> is a just a list of items.<...
<p>This can be achieved without <code>np</code>:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;x&quot;] = df[&quot;y&quot;].isin(a_list).map({False: &quot;No&quot;, True: &quot;Yes&quot;}) </code></pre> <p>Here's a reproducible example:</p> <pre class="lang-py prettyprint-override"><code>import dask df ...
python|list|numpy|dask|dask-dataframe
2
364,132
71,701,586
Group by week and rank to pick top 5
<p>I have a DataFrame with one month's data:</p> <pre><code>initiated_date | specialist_id | rating 21/10/2020 05:00:01 | ab12 | 8.1 21/10/2020 12:20:01 | gc35 | 7.3 22/10/2020 04:30:01 | ad32 | 6.4 22/10/2020 03:40:01 | fe45 | 9.2 22/10/2020 01:50:01 ...
<p>Let us do in steps:</p> <ul> <li>groupby <code>week</code> and <code>specialist_id</code> and calculate <code>avg_rating</code></li> <li>groupby <code>week</code> and assign the numerical rank for <code>avg_rating</code> per <code>week</code></li> <li>(Optional) sort the values by <code>week</code> and <code>rank</c...
python|pandas|dataframe|pandas-groupby
1
364,133
71,745,066
What does DataAccessor do in tfx?
<p>I'm reading the tfx <a href="https://www.tensorflow.org/tfx/tutorials" rel="nofollow noreferrer">tutorials</a>, which all uses the <code>DataAccessor</code> to load data. The code looks something like this:</p> <pre class="lang-py prettyprint-override"><code> return data_accessor.tf_dataset_factory( file_patt...
<p>Looking through the <a href="https://github.com/tensorflow/tfx/blob/r1.7.0/tfx/components/trainer/fn_args_utils.py" rel="nofollow noreferrer">documentations</a>, <code>DataAccessor</code> seems to be a utility wrapper around a <code>tf.data.Dataset</code> factory. The object that is returned is an instance of <code>...
tensorflow|tensorflow-datasets|tfx
-1
364,134
71,573,285
Syncing another company's financial year to another company using EDGAR database
<p>I'm working on a school project that was built by a previous group, and one of my tasks is to synchronize the fiscal year's start date according to the start date of the company of focus. This is the code used to grab the json from EDGAR using their API.</p> <pre><code>d = requests.get(f&quot;https://data.sec.gov/ap...
<p>You could try the following. I selected <code>cik</code> based on the name given through a <a href="https://www.edgarcompany.sec.gov/servlet/CompanyDBSearch?start_row=-1&amp;end_row=-1&amp;main_back=1&amp;cik=&amp;company_name=AUTOZONE+INC&amp;reporting_file_number=&amp;series_id=&amp;series_name=&amp;class_contract...
python|pandas|finance|edgar
1
364,135
71,558,286
Pandas Profiling, profile_report method error
<p>I installed <code>pandas-profiling</code> with pip for jupyter notebook (not using conda!), and everything was working fine, until I installed <code>plotly</code></p> <p>Now, when I try to use the <code>df.profile_report()</code> method, I get the following error:</p> <blockquote> <p>DispatchError: Function &lt;code...
<p>got the same error here.</p> <p>This is what I did to solve this issue:</p> <p>Uninstall all following dependencies and then install them again with these specific versions:</p> <pre><code>pandas-profiling==2.7.1 Jinja2==3.0.3 itsdangerous==2.0.1 Flask==1.1.1 </code></pre> <p>Reference: <a href="https://github.com/p...
python-3.x|pandas|plotly|pandas-profiling
1
364,136
71,617,057
Import pandas could not be resolved from source Pylance(reportMissingModuleSource)
<p>I've been trying to use the packages pandas, numpy, matplotlib, seaborn in my &quot;Visual Studio Code&quot;, but the program keeps showing me the following message:</p> <blockquote> <p>&quot;import pandas could not be resolved from source Pylance(reportMissingModuleSource)&quot;</p> </blockquote> <p>Previously to V...
<p>I also received similar an error on my IDE VSCode and currently using mac m1 .First we need to make sure that the python3 interpreter version from terminal version is the same with our python version selection in VSCode.</p> <ol> <li>open terminal.</li> <li>type 'python3'</li> <li>then you will see your python versi...
pandas|visual-studio-code|jupyter-notebook|anaconda|pylance
5
364,137
71,621,318
Pandas computing the data inside the column itself in dataframe
<pre><code>I have come up with a problem where my data in the column has been recorded as 90-2,91-3,90+4 etc.My motive here is to add and subtract the data directly into the column itself. Datatype of the column is an object. df = df1[&quot;ldm&quot;].str.split('+',expand =True) if df.shape[1]&gt;1: df_2 = df[0].st...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.eval.html" rel="nofollow noreferrer"><code>pandas.eval</code></a>. It supports a limited range of operations, which makes it much safer to use than python's <code>eval</code> and more convenient than <code>ast.literal_eval</code>.</p> <p>From the docum...
python|pandas|dataframe|pandas-groupby|fillna
0
364,138
71,744,428
Aggregate only one of the duplicated values with groupby pandas
<p>I have the following data with the last column as the desired output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">activity</th> <th style="text-align: center;">teacher</th> <th style="text-align: right;">group</th> <th style="text-align: right;">students</th...
<p>IIUC:</p> <pre class="lang-py prettyprint-override"><code>x = ( df.drop_duplicates(subset=[&quot;activity&quot;, &quot;group&quot;]) .groupby(&quot;activity&quot;)[&quot;students&quot;] .sum() ) df[&quot;the desired column&quot;] = df[&quot;activity&quot;].map(x) print(df) </code></pre> <p>Prints:</p> <p...
python|pandas|pandas-groupby|transform
3
364,139
71,567,593
ValueError x and y must have same first dimension, but have shapes (4500,) and (4499,)
<p>#I have a dataframe for a growing polymerization reaction that looks like this:</p> <pre><code>d_result['M']= array([70. , 69.99738611, 69.98974828, ..., 0.02669216, 0.02664559, 0.02659911]) </code></pre> <h1>Also ;</h1> <pre><code>d_result['time']= array([ 0. , 0.1, 0.2, ..., 449.7, 449.8, 449...
<p><code>d_trajectory['M'][:-1]</code> doesn't include the last element of the array and is therefore shorter by 1 than <code>d_trajectory['time']</code>, see <a href="https://stackoverflow.com/questions/509211/understanding-slice-notation">Understanding slice notation</a>. Try <code>d_trajectory['M']</code> or <code>d...
pandas|numpy|numpy-ndarray
1
364,140
71,628,134
Creating a new Dataframe based on rows with certain values and removing the rows from the original Dataframe
<p>I try to separate a Dataframe based on rows with a certain value in multiple columns, so that the original Dataframe is split in two with all rows containing the value in one Dataframe and the other Dataframe with the residual rows.</p> <pre><code>df = pd.DataFrame(np.random.randint(-1,100,size=(100, 4)), columns=li...
<p>Lets assume you would like to filter data by value equals to <code>80</code>.</p> <p>Possible solution is the following:</p> <pre><code># pip install pandas import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(-1,100,size=(100, 4)), columns=list('ABCD')) df </code></pre> <p><a href="https://i...
python|pandas|dataframe
4
364,141
71,579,895
How to make other values other than the one I needed to be NaN?
<p>I am trying to convert RGB value from a png file into dBZ value. I want to make other value other than the one I needed to be NaN. Here is my code:</p> <pre><code>def convert_dbz(image, rgbradar, rgbdbz): &quot;&quot;&quot; This function for converting RGB color from .png image into dbz value image : image file with...
<p>I think the variable <code>image</code> is of type <code>np.int</code> and <code>np.nan</code> is of type <code>np.float</code>, hence it fails to assign the value. You may want to use <code>image[i,j,:] = None</code> instead or change the <code>dtype</code> of <code>image</code> to <code>np.float</code>.</p>
python|arrays|numpy|nan
0
364,142
71,505,039
What is the difference between <class 'numpy.ndarray'> and numpy.ndarray?
<p>I have been doing some calculations using numpy arrays and have arrived at the question of what is the difference between:</p> <p><code>&lt;class 'numpy.ndarray'&gt;</code> and <code>numpy.ndarray</code></p> <p>I have noticed that the following operation only works on <code>&lt;class 'numpy.ndarray'&gt;</code>: <cod...
<p>There's no difference; they're identical.</p> <p><code>numpy.ndarray</code> is the actual type of numpy arrays; <code>&lt;class 'numpy.ndarray'&gt;</code> is the <em>string represention</em> ot <code>numpy.ndarray</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([1, 2, 3]) array([1, 2...
numpy|numpy-ndarray
1
364,143
71,578,754
Filling a DataFrame based on conditions for both columns and rows
<p>I have a dataframe (df_1) which contains coordinates and value data with no order that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>x_grid</th> <th>y_grid</th> <th>n_value</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>204.0</td> <td>32.0</td> <td>45</td> <...
<p>IIUC:</p> <pre><code>df_2 = df_1.pivot('x_grid', 'y_grid', 'n_value') \ .reindex(index=pd.RangeIndex(0, df_1['y_grid'].max()+1), columns=pd.RangeIndex(0, df_1['x_grid'].max()+1), fill_value=0) </code></pre> <p>If you have duplicated values for the same (x, y), use <...
python|pandas|dataframe|indexing|heatmap
0
364,144
71,619,468
drop rows based on condition
<p>I want to keep only the rows in which the time is between the July 4 and May 24 of the same year, so I'm using this code :</p> <pre><code>def fix_time(data): 12 data['timestamp'] = pd.to_datetime(data['timestamp'], format=&quot;%d-%m-%Y %H:%M:%S&quot;) ---&gt; 13 indexNames = data[ (data['timestamp'] &l...
<p><code>between</code> works better for this:</p> <pre><code>def fix_time(data): data['timestamp'] = pd.to_datetime(data['timestamp'], format=&quot;%d-%m-%Y %H:%M:%S&quot;) return data[data['timestamp'].between('2021-05-07', '2021-05-24')] </code></pre> <p>Also, note that you <strong>must</strong> use the ISO ...
python|pandas|timestamp|drop
4
364,145
71,541,087
Clustering Data with pandas / matplotlib
<p>As a beginner in data science, I want to cluster data to visualize the distribution of the data.</p> <p>This is the current state. Each point is a data point with some x and y value.</p> <p><a href="https://i.stack.imgur.com/scKHt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/scKHt.png" alt="cur...
<p>Here is my crack at it -- note I am no matplot-wiz or pandas ninja (I am more of an R/ggplot guy). There are probably easier ways to work with the data in python/pandas.</p> <pre><code>import numpy as np print('numpy: {}'.format(np.__version__)) import matplotlib as mpl print('matplotlib: {}'.format(mpl.__version__)...
python|pandas|matplotlib
1
364,146
71,469,808
How to replace a list with first element of list in pandas dataframe column?
<p>I have a pandas dataframe <code>df</code>, which look like this:</p> <pre><code>df = pd.DataFrame({'Name':['Harry', 'Sam', 'Raj', 'Jamie', 'Rupert'], 'Country':['USA', &quot;['USA', 'UK', 'India']&quot;, &quot;['India', 'USA']&quot;, 'Russia', 'China']}) Name Country Harry USA...
<p>Try something like:</p> <pre class="lang-py prettyprint-override"><code>import ast def changeStringList(value): try: myList = ast.literal_eval(value) return myList[0] except: return value df[&quot;Country&quot;] = df[&quot;Country&quot;].apply(changeStringList) df </code></pre> <h4>Output</h4> <div c...
python|pandas
1
364,147
71,784,718
How to create custom k-fold cross validation datasets for training models
<p>I have a dataset on <code>daily</code> level granularity for 4 years - 2018, 2019, 2020 and 2021. There is also some data available for Q1 2022 which I will be using as unseen data for model testing. I want to use K-fold for creating datasets per year where in I can loop through each fold and train a model and gener...
<p>Scitkit-learn's <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html" rel="nofollow noreferrer">TimeSeriesSplit</a> would allow you to generate continuous train and test folds of defined size - <code>TimeSeriesSplit(max_train_size=365, test_size=91)</code> will prod...
python|pandas|scikit-learn
1
364,148
71,703,267
How to read data from .docx file in python pandas?
<p>I have a word file (.docx) containing comma separated data as shown in format below:</p> <pre><code>Id,Firstname,Lastname,Salary,Department 1,ABC,XYZ,10000,ENG 2,DEF,XYZ,20000,FIN </code></pre> <p>I want to read this comma separated data directly as a dataframe in pandas. Please help.<br /> I have already foun...
<p>You can use a combination of <a href="https://python-docx.readthedocs.io/en/latest/" rel="nofollow noreferrer"><code>docx</code></a>, <a href="https://docs.python.org/3/library/io.html#io.StringIO" rel="nofollow noreferrer"><code>io.StringIO</code></a>, and <a href="https://pandas.pydata.org/docs/reference/api/panda...
python|pandas|jupyter-notebook
1
364,149
71,741,193
Error while reading data from csv file using pandas
<pre class="lang-py prettyprint-override"><code>import yfinance as yahooFinance import time import datetime import pandas as pd ticker = 'TSLA' period1 = int(time.mktime(datetime.datetime(2022, 12, 1, 23, 59).timetuple())) # year,month,date period2 = int(time.mktime(datetime.datetime(2022, 12, 31, 23, 59).timetuple(...
<p>Both <code>period1</code> and <code>period2</code> are invalid, as they lie in the future. Adjust them e. g. with <code>datetime.date(2021,4,5)</code> or <code>datetime.date.today()</code> to get the current date, which is the latest possible date.</p> <pre><code>import time import datetime import pandas as pd tick...
python|pandas|yahoo-finance|read.csv
2
364,150
71,585,510
Remove records from dataframe that exist in another column but keeping some based on a specific priority with python
<p>I want to plot on a map those names that do not have already a neighbour, so I need to remove from my dataframe all names that already have a known neighbour preserving those with the highest age.</p> <pre><code>df=pd.DataFrame( list(zip( ['Isabel Garcia','Isabel Garcia','Raul Jimenez','Laura Gomez','Laura Gomez','M...
<p>I'm not sure if this is satisfying for you but here is a way to get your expected output.</p> <pre><code>known = set() remaining_ppl = set(df['Name']) for _, row in df.iterrows(): known.add(row['Name']) if row['Neighbour'] in known: remaining_ppl.discard(row['Name']) print(remaining_ppl) #because re...
python|pandas
1
364,151
71,606,741
dask dataframe to spark not working the same way as pandas dataframe to spark
<p>I'm reading in some windspeed data from netcdf files. This produces an xarray dataset which I can convert to pandas and/or dask dataframes. Ultimately I want to convert to dask dataframes then to pyspark due to the volume of data. However when converting from dask to spark I'm receiving an error which I don't when d...
<p>Aside: are you sure you want spark to process this data? Dask integrated well with xarray and you might well find that the conversion is not worth your while, not least because you will need to duplicate and convert the data and have two cluster systems running.</p> <p>Short answer: <code>createDataFrame</code> supp...
pandas|pyspark|dask|python-xarray
0
364,152
71,496,267
Python : Correlation coefficient between two 2D arrays
<p>Let's assume that we have two different 2D np.arrays</p> <p><code>a = (np.random.randint(25,30,1512000)).reshape(1050,1440)</code></p> <p><code>b = (np.random.randint(20,25,1512000)).reshape(1050,1440)</code></p> <p>So, the dimension of <code>a</code> and <code>b</code> is <code>(1050,1440)</code></p> <p>I want to c...
<p>You can do this with nctoolkit. Assuming the files have the same grid, the following will work:</p> <pre><code>import nctoolkit as nc ds1 = nc.open_data(&quot;file1.nc&quot;) ds2 = nc.open_data(&quot;file2.nc&quot;) ds_cor = nc.cor_space(ds1, ds2) ds_cor.plot() </code></pre> <p>Likely the grids do not match, so you ...
python|numpy|correlation|netcdf|python-xarray
1
364,153
42,407,483
Tensorflow supervisor for both training and evaluating operations?
<p>I've been using tensorflow supervisor (<a href="https://www.tensorflow.org/programmers_guide/supervisor" rel="nofollow noreferrer">https://www.tensorflow.org/programmers_guide/supervisor</a>) for loading the model from the saved checkpoints for both training and running a network. But I noticed that the checkpoint f...
<p>Your model is usually saved to a file names 'model.ckpt-NUM'. As long as the evaluation does not update that file (and it shouldn't), then you're safe.</p> <p>If you are worried about overwriting logging/summaries. You should be careful in choosing the summaries names. </p> <p>E.g. for evaluation, choose a summary...
tensorflow
1
364,154
42,451,088
Tensorflow : TypeError: expected string or bytes-like object
<p>I am beginner in tensorflow , I am trying to add summaries to a code of neural network from this link <a href="https://pythonprogramming.net/rnn-tensorflow-python-machine-learning-tutorial/" rel="nofollow noreferrer">https://pythonprogramming.net/rnn-tensorflow-python-machine-learning-tutorial/</a> I got an error bu...
<p><a href="https://www.tensorflow.org/api_docs/python/tf/summary/scalar" rel="nofollow noreferrer"><code>tf.summary.scalar</code></a> expects a name as the first argument, not an array. This should work instead:</p> <pre><code>tf.summary.scalar(value.op.name, value) </code></pre>
tensorflow
0
364,155
42,271,479
Use columns as row and column headers in a matrix
<p>I have a csv file like this:</p> <pre><code>1 A 10 2 A 20 1 B 30 1 C 40 2 B 50 </code></pre> <p>And I want to organize my matrix like this:</p> <pre><code> 1 2 A 10 20 B 30 50 C 40 0 </code></pre> <p>What is the best way to achieve this? </p> <p>My current solution (using in...
<p>Using <code>pd.pivot_table</code></p> <pre><code>In [913]: df.pivot_table(index='col2', columns='col1', values='col3', aggfunc='sum', fill_value=0) Out[913]: col1 1 2 col2 A 10 20 B 30 50 C 40 0 </code></pre> <p>Or, using <code>pd.crosstab</code></p> <pre><code>In [92...
python|pandas|numpy
3
364,156
42,356,852
match_template from skimage returns 1X1 area
<p>I'm trying to coalign sequential images of astonomical object using match_template from skiimage. Images are numpy areas 500x500, and very similar. The only difference is introduced by slow rotation of the object itself (movement is less than pixel between images, I tried to increase difference by making average tem...
<p>Well, it took me some time, but I figured out what is going on. <br> The problem is that images are too similar to each other. If the change between images is a sub-pixel resolution, this particular code will return just one number, simply because images do match to each other almost perfectly.<br> The workaround I ...
python|numpy|scikit-image
0
364,157
42,320,834
Sklearn changing string class label to int
<p>I have a pandas dataframe and I'm trying to change the values in a given column which are represented by strings into integers. For instance:</p> <pre><code>df = index fruit quantity price 0 apple 5 0.99 1 apple 2 0.99 2 orange 4 0.89 ...
<p>You can use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html" rel="noreferrer">sklearn.preprocessing</a> </p> <pre><code>from sklearn import preprocessing le = preprocessing.LabelEncoder() le.fit(df.fruit) df['categorical_label'] = le.transform(df.fruit) </code></...
python|pandas|scikit-learn
22
364,158
42,193,669
Increasing Efficiency of Checking for Duplicates -- Python
<p>I'm a researcher working with climate model output using Python to find certain types of storms. I have 8 large numpy arrays (dimensions are 109574 x 52 x 57). These arrays are filled with 1's to signify there was a storm on that day (first dimension is time), 0 for no storm. The other two dimensions are latitude an...
<p>Here is a vectorised function that can replace your innermost loop:</p> <pre><code>def do(KK): # find stretches of ones switch_points = np.where(np.diff(np.r_[0, KK, 0]))[0] switch_points.shape = -1, 2 # isolate stretches starting on odd days and create mask odd_starters = switch_points[switch_p...
python|arrays|numpy
2
364,159
42,313,890
Strange pandas.DataFrame.sum(axis=1) behaviour
<p>I have a pandas DataFrame compiled from some web data (for tennis games) that exhibits strange behaviour when summing across selected rows.</p> <pre><code>DataFrame: In [178]: tdf.shape Out[178]: (47028, 57) In [201]: cols Out[201]: ['L1', 'L2', 'L3', 'L4', 'L5', 'W1', 'W2', 'W3', 'W4', 'W5'] In [177]: tdf[cols]....
<p>Problem is with <code>empty string</code> - then <code>dtype</code> of column <code>W3</code> is <code>object</code> (obviously <code>string</code>) and <code>sum</code> omit it.</p> <p>Solutions:</p> <p>Try replace problematic <code>empty string</code> value to <code>NaN</code> and then cast to <code>float</code>...
pandas
0
364,160
42,249,567
Merging two Pandas series using a key
<p>I am having two pandas series, namely, x and y.</p> <p>x.head() gives:</p> <pre><code> user hotel rating id 0 1 1253 5 2783_1253 1 4 589 5 2783_589 2 5 1270 4 2783_1270 3 3 1274 4 2783_1274 4 2 741 5 2783_741 </code></pre> <p>y.head() g...
<p>I think you need first convert <code>float</code> column to <code>int</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow noreferrer"><code>merge</code></a>:</p> <pre><code>y['user'] = y.UserID.astype(int) df = pd.merge(x,y, on='user') print (df) user ...
python|pandas|merge
2
364,161
42,352,669
DataFrame: if value in a cell, copy value to cells below it
<p>I'm working on a stock analysis program and need to find 'SPLIT' amounts from the 'UNP_action', and then copy the corresponding 'UNP_action_amount' to rows above it only. </p> <p>I'm able to do this in a complicated way via loops, but I'm wondering if there's a more efficient way to do this within Pandas.</p> <p>C...
<p>If every split row has a corresponding value to fill with, you can just use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a> with the <code>backfill</code> method to propagate values backwards. </p> <pre><code>df.UNP_actio...
python|pandas|dataframe
2
364,162
42,380,322
Show multiple steps per image in tensorboard
<p>Is it possible to view the images for all steps in the Image viewer of tensorboard? Only the images corresponding to the last step are shown in the Images tab, though they are accessible changing the index of the the url of the image:</p> <p>(Changing the 0 for the required step in the url: localhost:6006/data/indi...
<p>As I understood, an additional slider was added at TensorFlow v. 1.1.0:</p> <ul> <li><a href="https://i.stack.imgur.com/YDEVo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YDEVo.png" alt="enter image description here"></a></li> </ul>
tensorflow|tensorboard
2
364,163
42,507,307
How to apply changes to pandas groupby based on values from another dataframe?
<p>I have a pandas groupby series with 3 columns and I would like to make a change on third column according to values from another pandas dataframe</p> <pre><code>Data1 Data2(unique names) name col1 col2 name col a 10 -0.2 x 0.002 b ...
<p>This is an simple as using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer">pandas.Series.map</a>. You'll be creating a mapping between 'name' and 'col'. You don't need to 'merge' (join) the two data frames in this case as you're only interested to retr...
python|pandas|dataframe
4
364,164
42,374,849
Implementation of Stateful LSTM
<p>I want to create a stateful LSTM</p> <p>My data is of 68871 x 43, where the features are in the column no. 1-42 and label in column no. 43</p> <p>My keras LSTM code for classification of the data is</p> <pre><code>import numpy import matplotlib.pyplot as plt import math from keras.models import Sequential from ke...
<pre><code>model.add(LSTM(10, input_shape=(5,43), stateful=True)) </code></pre> <p>is what you are looking for I think. See <a href="https://keras.io/layers/recurrent/#recurrent" rel="nofollow noreferrer">here for documentation</a>.</p> <p>Also, if you want to use stateful lstm it doesn't make sense to shuffle the tr...
machine-learning|tensorflow|deep-learning|keras
0
364,165
42,320,813
Difference between Numpy and Matlab in multiplication of arrays
<p>I am rewriting a program from Matlab to Python. I realised a difference in a multiplication between arrays. Here is an example:</p> <pre><code> A = [-1822.87977846-4375.93518777j 3675.88618351+3824.34290883j 971.68964707-2393.36758923j] </code></pre> <p>In Matlab:</p> <pre><code>A*A'= 5.7282e+0...
<p>First of all remember, in MATLAB, <code>'</code> is different than <code>.'</code>. </p> <p><code>'</code> does <a href="https://www.mathworks.com/help/matlab/ref/ctranspose.html" rel="nofollow noreferrer">complex conjugate transpose</a></p> <p><code>.'</code> does <a href="https://www.mathworks.com/help/matlab/re...
python|arrays|matlab|numpy|complex-numbers
4
364,166
42,512,874
Cumulate data based on two column values in df python
<p>I am trying to cumulate the data usage based on the ID and the month so that the cumulative data will be added as an additional column.</p> <p>This is my code for a sample of the df:</p> <pre><code>df = pd.DataFrame({'ID':["SAD1", "SAD2", "SAD1", "SAD2", "SAD1", "SAD2", "SAD3"], 'Month':["201701","...
<p><code>groupby</code> and <code>cumsum</code></p> <pre><code>df['Cum Usage'] = df.groupby('ID').cumsum() </code></pre>
python|pandas|cumulative-sum
4
364,167
42,236,574
AttributeError: 'module' object has no attribute 'histogram' when using tf-faster-rcnn
<p>Please have a look at this issue and let me know if you know how to fix it? Here's the link to the original repo: <a href="https://github.com/endernewton/tf-faster-rcnn" rel="nofollow noreferrer">https://github.com/endernewton/tf-faster-rcnn</a></p> <pre><code>mona@pascal:~/computer_vision/tf-faster-rcnn$ ./experim...
<p>You are using an older version of tensorflow. The old version was <code>tf.histogram_summary</code>. You can see a list of API changes in our <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/compatibility/tf_upgrade.py#L116" rel="nofollow noreferrer">upgrade script</a>.</p>
python|ubuntu|tensorflow|pip|deep-learning
2
364,168
42,306,755
How to remove illegal characters so a dataframe can write to Excel
<p>I am trying to write a dataframe to an Excel spreadsheet using ExcelWriter, but it keeps returning an error:</p> <pre><code>openpyxl.utils.exceptions.IllegalCharacterError </code></pre> <p>I'm guessing there's some character in the dataframe that ExcelWriter doesn't like. It seems odd, because the dataframe is for...
<p>Based on Haipeng Su's answer, I added a function that does this:</p> <pre><code>dataframe = dataframe.applymap(lambda x: x.encode('unicode_escape'). decode('utf-8') if isinstance(x, str) else x) </code></pre> <p>Basically, it escapes the unicode characters if they exist. It worked and I can now wr...
pandas|export-to-excel
44
364,169
42,561,596
Tensorflow: Linear model diverges when adding examples to the training vector
<p>First, apologies if I'm making a silly mistake - this is one of my first tensorflow programs. To my defense - I've searched the subject and did not find any reasonable explanation.</p> <h1>The code</h1> <p>The code is adapted from the <a href="https://www.tensorflow.org/get_started/get_started" rel="nofollow noref...
<p>By adding new single data, due to short size of previous data, you are increasing number of data about 15% ! This is a big change especially when your new data is very different from samples in current train data. You can not solve the problem by only increasing learning iteration, since gradient step can not compen...
python|machine-learning|tensorflow|linear-regression
0
364,170
42,577,773
Initializing Tensors
<pre><code>tf_coo = tf.SparseTensor(indices=np.array([[0, 0, 0, 1, 1, 2, 3, 9], [1, 4, 9, 9, 9, 9, 9, 9]]).T, values=[1, 2, 3, 5,1,1,1,1], shape=[10, 10]) </code></pre> <p>I get the error message</p> <pre><code>InvalidArgument...
<p>Just remove the duplicate <code>[1,9]</code> in <code>indices</code>:</p> <pre><code>from __future__ import print_function import tensorflow as tf import numpy as np tf_coo = tf.SparseTensor(indices=np.array([[0, 0, 0, 1, 2, 3, 9], [1, 4, 9, 9, 9, 9, 9]]).T, ...
tensorflow|sparse-matrix
0
364,171
42,563,981
Tensorflow complains about missing feed_dict during graph restore
<p>I've built a CNN for image classification. During training I've saved several checkpoints. The data is fed through a feed_dictionary into the network.</p> <p>Now I want to restore the model which fails and I cant figure out why. The important lines of code are as follows:</p> <pre><code>with tf.Graph().as_default(...
<p>The problem was cause by a SessionRunHook for process logging:</p> <p>original hook:</p> <pre><code>class _LoggerHook(tf.train.SessionRunHook): """Logs loss and runtime.""" def begin(self): self._step = -1 def before_run(self, run_context): self._step += 1 self._start_time = time.time() ret...
tensorflow|feed|restore
1
364,172
42,309,460
Boolean masking on multiple axes with numpy
<p>I want to apply boolean masking both to rows and columns.</p> <p>With</p> <pre><code>X = np.array([[1,2,3],[4,5,6]]) mask1 = np.array([True, True]) mask2 = np.array([True, True, False]) X[mask1, mask2] </code></pre> <p>I expect the output to be</p> <pre><code>array([[1,2],[4,5]]) </code></pre> <p>instead of</p>...
<p><code>X[mask1, mask2]</code> is described in <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean-array-indexing" rel="noreferrer">Boolean Array Indexing Doc</a> as the equivalent of</p> <pre><code>In [249]: X[mask1.nonzero()[0], mask2.nonzero()[0]] Out[249]: array([1, 5]) In [250]: X[[0...
python|numpy
6
364,173
42,540,955
Group by and find consecutive time and create a flag in Python
<p>The following is the data I am having,</p> <pre><code>id name unused time 1 a 1 2/21/2017 18:01:31.168 1 a 2 2/21/2017 18:01:31.168 1 a 3 2/21/2017 18:11:44.054 1 a 4 2/21/2017 18:19:03.147 1 b 5 2/21/2017 18:19:03.147 1 b 6 ...
<p>One approach may be to just use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>shift</code></a> to compare one forward and one behind with your columns of interest. </p> <pre><code>eval_cols = df[['id', 'name', 'time']] df['flag'] = ((eval...
python|python-2.7|python-3.x|pandas|dataframe
2
364,174
42,170,786
How can I contract 2 indices at my choice in a rank N tensor (ndarray)
<p>I have a 2^L x 2^L matrix which is then converted to a tensor of rank 2L by reshape command with each axis having 2 elements. For example for L =2 it would be:</p> <pre><code>Z = np.asarray([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]) X = np.reshape(Z,[2,2,2,2]) </code></pre> <p>I have tried to use <code>np....
<p>I'm assuming you are referring to tensor contraction in the sense of "generalised trace", so let's see what <code>numpy.trace</code> can do for us:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.arange(16).reshape(2, 2, 2, 2) &gt;&gt;&gt; L, i, j = 2, 0, 1 &gt;&gt;&gt; np.trace(a, axis1=i, axis2...
python|numpy
2
364,175
42,513,614
Select specific rows and cells in text file and put into data frame: python or R
<p>Either python or R is fine to use for this but could someone advise me on how to select the "Basic stats" rows a text file that looks like the one below. I want this information and the name of the ROI to be put in a pandas data frame or as a data table in R. </p> <pre><code>ROI: mrc_ranch_house [Red] 195 points ...
<p>With R, using:</p> <pre><code># read the text file txt &lt;- readLines('https://dl.dropboxusercontent.com/u/45095175/rois_all.txt') # create an index for the lines that are needed ti &lt;- rep(which(grepl('ROI:', txt)), each = 3) + 1:3 # create a grouping vector of the same length grp &lt;- rep(1:33, each = 3) # ...
python|r|pandas|dataframe|data.table
4
364,176
42,306,802
Numpy functions/methods without brackets explanation
<p>I'm just trying to wrap my head around the syntax here:</p> <pre><code># some data import numpy as np x = linspace(0, 1, 100) x.sum() # works with brackets &gt; 50.0 x.shape # works without brackets &gt; (100,) x.shape() # fails with brackets &gt; TypeError </code></pre> <p>Why is it that some methods/fu...
<p>When you access an attribute of your instance you really access a descriptor. There are three common cases:</p> <ul> <li><p>The descriptor returns a function like <code>x.sum</code>, that returns a bound function. Bound because the first argument to that function will be <code>x</code>. You obviously need to call <...
python|numpy|methods|properties
3
364,177
42,491,428
How are features ranked in RFECV in scikit learn(sklearn)?
<p>I used recursive feature elimination and cross-validated (rfecv) in order to find the best accuracy score for several features I had (m =154).</p> <pre><code>rfecv = RFECV(estimator=logreg, step=1, cv=StratifiedKFold(2), scoring='accuracy') rfecv.fit(X, y) </code></pre> <p>The rankings (<code>rfecv.r...
<p><code>_grid_scores</code> is not a score for the i-th feature, it is the score the estimator produced when trained with the i-th subset of features.</p> <p>To understand what that means, remember that Recursive Feature Elimination (RFE) works by training the model, evaluating it, then removing the <code>step</code>...
python|machine-learning|scikit-learn|sklearn-pandas
6
364,178
42,476,493
pip install tensorflow-gpu installing in python 3.5
<p>I am trying to install tensorflow for python 2.7 on Ubuntu 16. I am using pip install tensorflow-gpu and I get the following message in the terminal:</p> <pre><code>pip install tensorflow-gpu </code></pre> <p>Requirement already satisfied: tensorflow-gpu in /usr/local/lib/python3.5/dist-packages Requirement alread...
<p>I would suggest you to use anaconda and run the following command</p> <p><code>conda install -c anaconda tensorflow-gpu</code></p> <ul> <li>Anaconda will make your life easier... hope this helps This will also install the <code>cuda toolkit</code> and <code>cudnn</code> for you and you are good to go</li> </ul>
python|python-2.7|ubuntu|tensorflow
1
364,179
42,432,474
How to handle System Error in Python?
<p>When I run the following code:</p> <pre><code>import pandas as pd web_states = {'Day':[1,2,3,4,5,6], 'Visitors': [43,53,46,78,88,24], 'BounceRates':[65,74,99,98,45,56]} df= pd.DataFrame(web_states) print(df) </code></pre> <p>I get the following error:</p> <blockquote> <p>File ...
<p>Bounce Rates is too short.</p> <p><strong>Your code:</strong></p> <pre><code>web_states = {'Day': [1, 2, 3, 4, 5, 6], 'Visitors': [43, 53, 46, 78, 88, 24], 'BounceRates': [65, 74, 99, 98, 45]} df = pd.DataFrame(web_states) </code></pre> <p><strong>Produces:</strong></p> <pre><code> F...
python|numpy|matplotlib
0
364,180
42,395,842
Use boolean series of different length to select rows from dataframe
<p>I have a dataframe that looks like this:</p> <pre><code>df = pd.DataFrame({"piece": ["piece1", "piece2", "piece3", "piece4"], "No": [1, 1, 2, 3]}) No piece 0 1 piece1 1 1 piece2 2 2 piece3 3 3 piece4 </code></pre> <p>I have a series with an index that corresponds to the "No"-column in the datafram...
<p>I think you need <code>map</code> the value in <code>No</code> column to the <code>true/false</code> condition and use it for subsetting:</p> <pre><code>df[df.No.map(s)] # No piece #2 2 piece3 #3 3 piece4 </code></pre> <hr> <pre><code>df.No.map(s) # 0 False # 1 False # 2 True # 3 True # N...
python|pandas
4
364,181
69,845,012
Index with ndarray/ tensor
<p>I have a tensor A with shape (NB, N, 2, 2).</p> <p>If I have a list B, consisting of indices with length NB that I want to keep in tensor A, how should I do that? That is to say, I want to keep 1 (out of N) element per batch, based on the indices in B.</p> <p>I can get it done with a for loop specifying the batch <e...
<p><a href="https://pytorch.org/docs/stable/generated/torch.gather.html" rel="nofollow noreferrer"><code>torch.gather</code></a> comes to rescue.</p> <p>Prepare your index list like</p> <pre><code># A.shape = (NB, N, 2, 2) B = torch.tensor([1, 3, 0]) # should be of length NB B = B[:, None, None, None].repeat(1, # your ...
python|pytorch|tensor
0
364,182
69,943,975
Add a column to an array with values from a position in another array if rows match
<p>I have two arrays, one looks like this:</p> <pre><code>[[1 2 1 0 2 0 1] [1 2 1 0 2 0 1] [1 2 1 0 2 0 1] [1 2 1 0 2 0 1] [0 1 2 1 0 0 2] [0 1 2 1 0 0 2] [0 0 1 0 1 0 3] [0 0 0 1 1 0 4] [0 0 0 0 1 0 5] [0 0 0 0 0 1 6]] </code></pre> <p>The other looks like this:</p> <pre><code>[[1 2 1 0 2 0] [1 1 1 0 2 0] [1 1 1 0 2 0...
<p>You could use:</p> <pre><code>import numpy as np m = (B == A[:,None,:6]).all(2) new_A = np.c_[B, np.where(m.any(0), np.take(A[:,6], m.argmax(0)), 0)] </code></pre> <p>How it works:</p> <p>1- use broadcasting to compare B with all combinations of rows of A (limited to first 6 columns), and build a mask</p> <p>2- Usin...
arrays|numpy|matrix|numpy-slicing
1
364,183
69,992,038
Creating xarray from multiple numpy arrays - time series
<p>I want to create an Xarray DataArray with the following coordinates using a series of numpy arrays for annual time series data (let's say it's temperature over a uniform 1500X1500 matrix).</p> <p>('time', 'lon', 'lat') Coordinates:</p> <ul> <li>time (time) datetime64[ns] 2000-12-31 2001-12-31 ... 2020-12-31</li>...
<p>Thanks to Michael Delgado for guidance. Here is my solution:</p> <pre><code>xll = -20.0 xur = 55.0 yll = -35.0 yur = 40.0 cellsize = 0.1 lon_tup = np.arange(xll, xur, cellsize) + (cellsize / 2) lat_tup = np.arange(yll, yur, cellsize) lat_tup = lat_tup[::-1] + (cellsize / 2) StartYear = 2000 EndYear = 2020 for x in...
python|arrays|numpy|python-xarray
1
364,184
69,695,159
Add a column with the hourly difference of the Datetime Index
<p>I have a Dataframe with a datetimeindex and I need to create a column that contains the difference in time between the rows of the datetimeindex expressed in hours. This is what I have:</p> <pre><code>Datetime Numbers 2020-11-27 08:30:00 1 2020-11-27 13:00:00 2 2020-11-27 15:15:00 3 2020-11-27 20...
<p>I assume that <code>Datetime</code> is set as index:</p> <pre><code>df.reset_index(inplace=True) df['Delta'] = df['Datetime'].diff().dt.total_seconds()/3600 df.set_index('Datetime', inplace=True) </code></pre> <p>OUTPUT:</p> <pre><code> Numbers Delta Datetime 2020-11-2...
python|pandas|numpy|timedelta|datetimeindex
1
364,185
69,715,763
Function to generate arrays with given choices Python
<p>I want to output something like: [array([-1, 1, -1]), array([-1, 1, 1])] etc. 100 times. I have been editing my code without success for invalid syntax.</p> <pre><code>test = [] i =1 def testdata(): while i&lt;= 100: new = [random.choices([-1,1], k=3) for _ in range(100)] test.append(new) ...
<pre><code>import random as r c = [-1, 1] [np.array([r.choice(c), r.choice(c), r.choice(c)]) for _ in range(100)] </code></pre>
python|numpy
2
364,186
69,751,669
Append missing category into rows
<p>i have a set of <code>id</code> having some <code>category</code>. However, i want each <code>id</code> have the same number of <code>category</code> which can be specified as <code>df.id.category.unique()</code>.</p> <p>For example: <code>Input</code></p> <pre><code>df1 = {&quot;id&quot;: [1,1,1,2,2,3,3,3,3], ...
<p>You might use <code>numpy.tile</code> together with <code>numpy.repeat</code> for this as follows</p> <pre><code>import numpy as np id_col = np.repeat([1,2,3,4,5],5).reshape(-1,1) category_col = np.tile([&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;],5).reshape(-1,1) arr = np.hstack([id_col,c...
python|pandas|algorithm|numpy
1
364,187
69,956,534
Intersect points on a line
<p>I have a set of lines made of points of which I have to compute the total distance from the section S to the section E.</p> <p><a href="https://i.stack.imgur.com/aiKoY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aiKoY.png" alt="enter image description here" /></a></p> <p>To do that I am comput...
<p>Perhaps use linear regression to find the slope and intercept of the three &quot;lines&quot; of points, then solve a system of equations with two unknowns to get the intersection of each line with the bounding box.</p>
python|numpy
2
364,188
69,999,215
Catching filter exception in pandas loc in multi index dataframe
<p>I have a multi index time series data as below -</p> <p>stock_list</p> <pre><code>datetimestamp,stock_id,period_value,date,stock_code,broker_token,period,open,high,low,close,volume,open_interest,candle_no 2021-10-25 09:15:00,AAA,1,2021-10-25,AAA,10100000007,1 min,1018.0,1018.9,1011.1,1014.25,5575,0.0,0 2021-10-25 09...
<p>Use <code>try - except KeyError</code>:</p> <pre><code>stock_list = ['AAA','BBB'] index_slice = pd.IndexSlice for stock in stock_list: try: open_price = period_file_df.loc[index_slice[('2021-10-25 09:15:00'), stock, 1]]['open'] print (open_price) except KeyError: print ('keyerror') </...
python-3.x|pandas|dataframe
1
364,189
69,668,249
Automatically adjusting columns width with pandastable
<p>I use the package <code>pandastable</code> to display <code>dataframes</code> from <code>pandas</code>. I would like to adjust the width of the columns automatically, depending on the content. In the documentation (<a href="https://pandastable.readthedocs.io/en/latest/_modules/pandastable/core.html#Table.setRowColor...
<p>If you look into the source of <code>pandastable</code>, there is an attribute <code>maxcellwidth</code> of <code>Table</code> which is set to 300 by default. Therefore even though you have called <code>adjustColumnWidths()</code> the width of each column cannot be greater than <code>maxcellwidth</code>.</p> <p>Se...
python|pandas|tkinter
1
364,190
69,967,737
Messed up plots using boxplot with Seaborn
<p>I was using this code to plot all data in my df:</p> <pre><code>m_cols = ['is_canceled','lead_time', 'arrival_date_year','arrival_date_week_number','arrival_date_day_of_month','stays_in_weekend_nights','adults','children','babies','is_repeated_guest','previous_cancellations','previous_bookings_not_canceled','booking...
<p>The boxplots seem to show that the large majority of values is zero, and the rest are shown as outliers. So e.g. previous_annulations is usually zero, a few have some specif value. All outliers with the same value are drawn on top of each other. Note that the &quot;box&quot; of a <a href="https://en.wikipedia.org/w...
python|pandas|matplotlib|seaborn
1
364,191
70,013,407
Matplot lib line plot legend shows wrong color code for the lines
<p>The mat plot lib gives legend of line graph, but the color doesn't match. Here is a code to illustrate the issue.</p> <pre><code>import matplotlib.pyplot as plt import math d = {'Training': [270,180,160,150,135,130,120,110,100,95],'Validation': [290,220,200,180,170,173,175,185,188,195] ,'Validation Lr Drecay':...
<p>Here is the simple solution. Remove <code>plt.plot(df)</code>.</p> <p>It occurs because <code>df.plot()</code> makes plot with blue, orange, and green colors with legend, but plt.plot(df) makes new plot with other colors without legend.</p>
python|pandas|matplotlib
1
364,192
69,901,153
Regex replace first two letters within column in python
<p>I have a dataframe such as</p> <pre><code>COL1 A_element_1_+_none C_BLOCA_element D_element_3 element_' BasaA_bloc B_basA_bloc BbasA_bloc </code></pre> <p>and I would like to remove the first <code>2 letters</code> within each row of <code>COL1</code> only if they are within that list :</p> <pre><code>the_list =['...
<p>If the values to replace in <code>the_list</code> always have that format, you could also consider using str.replace with a simple pattern matching an uppercase char A-D followed by an underscore at the start of the string <code>^[A-D]_</code></p> <pre><code>import pandas as pd strings = [ &quot;A_element_1_+_...
python|regex|pandas
2
364,193
69,796,732
Numpy: Folding an array column-wise
<p>I have an n-dimensional boolean numpy array. How can I apply the logical AND operation between each of the columns. I want to get the number of rows that contain only ones.</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>n = np.array([[0, 0], [1, 0], [1, 1], ...
<p>You can use <code>.all(1)</code> to check <code>and</code> on each row then use np.sum() for counting like below:</p> <pre><code>&gt;&gt;&gt; res = n.all(1) &gt;&gt;&gt; res array([False, False, True, False, False, False, True]) &gt;&gt;&gt; res.sum() 2 </code></pre>
python|numpy|fold
2
364,194
69,747,119
Pytorch cifar10 images are not normalized
<pre><code>transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainset.data[0] </code></pre> <p>I am us...
<p>The <code>torchvision.transforms.Normalize</code> is merely a <em>shift-scale</em> operator. Given parameters <code>mean</code> (the <code>&quot;shift&quot;</code>) and <code>std</code> (the <code>&quot;scale&quot;</code>), it will map the input to <code>(input - shift) / scale</code>.</p> <p>Since you are using <co...
pytorch
2
364,195
69,980,305
Removing values from DataFrame columns based on list of values
<p>I have a slightly specific problem.</p> <p>A pandas DataFrame with let's say 6 columns. Each column has a unique set of values, which need to be looked for and removed / updated with a new value.</p> <p>The lookup list would look like this:</p> <pre><code>lookup_values_per_column = [[-99999], [9999], [99, 98],[9],[9...
<p>We can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>DataFrame.replace</code></a> with a dictionary built from the <code>list</code> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.columns.html" rel="nofollow norefe...
python|pandas|dataframe
1
364,196
69,760,341
Convert sparse matrix to pandas dataframe
<pre><code>import numpy as np from scipy.sparse import csr_matrix csr = csr_matrix(np.array( [[0, 0, 4], [1, 0, 0], [2, 0, 0],])) # Return a Coordinate (coo) representation of the csr matrix. coo = csr.tocoo(copy=False) # Access `row`, `col` and `data` properties of coo matrix. df = pd.DataFrame({'inde...
<p>One approach is to create a <code>filling</code> DataFrame and combine it (using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>combine_first</code></a>) with the one you already have:</p> <pre><code>df = pd.DataFrame({'index': coo.row, 'col...
python|pandas|dataframe|matrix|scipy
0
364,197
69,855,511
Why low mAP on fine-tuned model from Tensorflow 2 Object Detection API?
<p>I follow all the steps and read everything online and I trained successfully SSD-MobileNetV1 from Model Zoo of TF2 OD API.</p> <p>I fine-tuned this model with new classes &quot;Handgun&quot; and &quot;Knife&quot; and I use a balanced dataset of 3500 images. The training proceeds well, but when I run the evaluation p...
<p>It's a bug of the library as reported at this <a href="https://github.com/tensorflow/models/pull/9956" rel="nofollow noreferrer">link</a>. COCO metrics don't have this problem, so use it to evaluate your model. The problem is not fixed yet. If you want to follow updates made to the code(they work fine) please follow...
python|tensorflow|object-detection|object-detection-api
0
364,198
69,841,868
Transpose and save a one column pandas dataframe
<p>I removed all except one row of a pandas dataframe and pandas automatically transposed it. I then try to retranspose it back (and eventually want save it as a .csv) without effect.</p> <p>As a final result I want to have:</p> <pre><code>df3: col1 col2 col3 2 7 5 </code></pre> <p>instead of</p> <pre><code...
<p>In your case do <code>to_frame</code></p> <pre><code>df3.to_frame().T </code></pre>
python|pandas|dataframe|transpose
2
364,199
69,855,929
Python Sorting elements in a List in pandas Dataframe
<p>My company requires me to upload data as a list with quotations around it and its not the best but it is what it is. For Example if i have data that is 2 inches and 3 inches I have to upload it as [&quot;2 in&quot;, &quot;3 in&quot;].</p> <p>When I try and sort the elements in the list for each row I get this: [1, 2...
<p>Because you have strings, you first need to split the data into chunks. Fo this remove the first 2 and last 2 characters <code>[&quot;</code> ad <code>&quot;]</code>, then split on <code>&quot;,&quot;</code> to get a list of the data.</p> <p>Here is one way using apply:</p> <pre><code>from natsort import natsorted (...
python|pandas|list|dataframe|sorting
2