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,700 | 59,499,843 | int8 scipy sparse matrix creation errors creating int64 structure? | <pre><code>Python 3.5.4 (default, Sep 27 2019, 09:11:05)
[GCC 7.4.0] on linux
numpy==1.18.0
scipy==1.4.1
</code></pre>
<p>I've been trying to use scipy.sparse to create a very large square matrix, where the lower left half of which is zeros, and the upper right half is ones. I've used dtype <code>int8</code> to rep... | <p>This answer is a work in progress.</p>
<p>Sparse matrices are space and time efficient when they are sparse. Rough experience suggests that 10% sparsity, or less is good. 50% is not.</p>
<p>The core of this package was developed for linear algebra work (e.g. finite element ODE solutions). The <code>csr</code> f... | python|python-3.x|numpy|matrix|scipy | 2 |
364,701 | 59,764,455 | Flatten pandas dataframe column containing list of dictionaries | <p>I am flattening a data frame in which the column contains a list of dictionaries. I have written the code for it. However, it takes around 25 seconds to process only 5000 rows which is a lot.</p>
<p>Here is the sample dataset:</p>
<pre><code>event_date timestamp event_name user_properties
20191117 1.574... | <p>I converted the dataframe column to dictionary and processed the data there. Then converted the processed dictionary to dataframe and joined with original dataframe by 'index'.
It took around around 8 seconds to process 500K records.</p>
<pre><code>def flatten_dataframe_column(df,column):
temp_dict = df[column... | python|pandas|dictionary|swifter | 0 |
364,702 | 59,540,492 | Csv pandas groupby with a 'modified' median | <p>I want to do a 'modified' df.groupby.median() of a dataset by date and time combination, using the 'count' column.</p>
<p>Below is a sample of the dataset I'm working with:</p>
<pre><code> date time count
0 20160730 02:30 415
1 20160730 02:30 18
2 20160730 ... | <p>You can use custom function with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a> before <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel... | python|pandas|csv|group-by|median | 2 |
364,703 | 59,802,019 | Python joining many dataframes using duration match | <p>I have many data frames staked in a list. Data in each dataframes occurs every 30 minutes at distinctive times. I want to join them using a duration match. An example is given below: </p>
<pre><code>biglist3 = [df1,df2,df3] # actually up to df26
df1 =
index S1POA
2019-01-09 13:20:17 742.96... | <p>I would have tried something like:</p>
<pre><code>final = pd.concat(biglist3,sort=False)
final.groupby(final.index.floor('30min')).first()
</code></pre>
<hr>
<pre><code> S1POA S2POA S3POA
index
2019-01-09 13:00:00 742.961815 ... | python|pandas|dataframe | 1 |
364,704 | 59,534,130 | Numpy load a memory-mapped array (mmap_mode) from google cloud storage | <p>I want to load a <strong>.npy</strong> from google storage (gs://project/file.npy) into my google ml-job as training data. Since the file is +10GB big, I want to use the <strong>mmap_mode</strong> option of numpy.load() to not run out of memory. </p>
<p>Background: I use Keras with fit_generator and Keras Sequence ... | <p>You can pass from BytesIO to bytes using <code>b.getvalue()</code></p>
<pre class="lang-py prettyprint-override"><code>x_file = BytesIO(file_io.read_file_to_string(filename + '.npy', binary_mode = True))
x = np.load(x_file.getvalue(), mmap_mode = 'r')
</code></pre> | python|numpy|keras|google-cloud-storage|numpy-memmap | 0 |
364,705 | 59,508,668 | Creating tensor from a swift array | <p>This works fine:</p>
<pre class="lang-swift prettyprint-override"><code>import TensorFlow
var t = Tensor<Float>([[1, 0], [0, 1]])
</code></pre>
<p>But the following gives an error</p>
<pre class="lang-swift prettyprint-override"><code>import TensorFlow
var a = [[1, 0], [0, 1]]
var t = Tensor<Float>(a)... | <p>Your first code works because it uses <em>literals</em>, as opposed to an already declared variable (whose type is already determined) to initialise the <code>Tensor<Float></code>. Literals get special treatment by the compiler.</p>
<p>The overload of <code>Tensor.init</code> that you are calling is <a href="... | swift|tensorflow|swift-for-tensorflow | 4 |
364,706 | 32,316,407 | numpy remove row where any value matches condition | <p>I have RGB values in range [0,1] in an array as such:</p>
<pre><code>[[0.2, 0.2, 0.3], [0.1, 0.1, 0.1], [0.4, 0.3, 0.5]]
</code></pre>
<p>I would like to remove any rows where any value is below 0.15 (any colour is less than 0.15 in intensity). That is, I'd like the above array to change to:</p>
<pre><code>[[0.2,... | <p>Use: <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html" rel="nofollow"><code>any()</code></a>:</p>
<pre><code>In [146]:
arr = np.array([[0.2, 0.2, 0.3], [0.1, 0.1, 0.1], [0.4, 0.3, 0.5], [0.4, 0.3, 0.5]])
arr
Out[146]:
array([[ 0.2, 0.2, 0.3],
[ 0.1, 0.1, 0.1],
[ 0.4, 0... | python|numpy | 2 |
364,707 | 32,363,098 | Pandas Dataframe Groupby multiple columns then sum | <p>Assume the following for each Python code:</p>
<pre><code>import pandas as pd
import numpy as np
</code></pre>
<p>In Pandas, if I have a dataframe of 2 columns, one of which is an array of numbers, I can sum over the values of the array to get a single array.</p>
<pre><code>df = pd.DataFrame({'A': ['foo', 'bar', ... | <p>You can use a <code>lambda</code> expression. The <code>iat</code> expression takes the scalar value of the first element in the Series (here just the list of numbers), and then sums the results.</p>
<pre><code>>>> df2.groupby(['A', 'B']).numbers.apply(lambda x: x.iat[0].sum())
A B
bar al 16
... | python|arrays|pandas|aggregate-functions | 1 |
364,708 | 32,491,783 | How to efficiently shuffle numpy array in chunks | <p>I have a numpy array that looks like the following [-1,0,1,0,1,2,1,2,3,...,n-1,n,n+1,n,n+1,n+2..]
I would like to shuffle the array in chunks of 3, is there an efficient way to do it in numpy?</p>
<p>I know you can shuffle a numpy array using the following shuffle method, but this gives me a fully shuffled array. I... | <p>Reshape into 3 columns. <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html" rel="noreferrer"><code>shuffle</code></a> doc says it just shuffles the 1st dimension:</p>
<pre><code>ind=np.arange(99) # multple of 3
ind=ind.reshape(-1,3)
rng.shuffle(ind)
ind.flatten()
</code></pre> | python|numpy | 6 |
364,709 | 32,219,150 | Taking second last observed row | <p>I am new to pandas. I know how to use drop_duplicates and take the last observed row in a dataframe. Is there any way that I can use it to take only second last observed. Or any other way of doing it.
For example:
I would like to go from </p>
<p><code>df = pd.DataFrame(data={'A':[1,1,1,2,2,2],'B':[1,2,3,4,5,6]})</... | <p>The idea is that you'll group the data by the duplicate column , then check the length of group , if the length of group is greater than or equal 2 this mean that you can slice the second element of group , if the group has a length of one which mean that this value is not duplicated , then take index <code>0</code>... | pandas|dataframe | 2 |
364,710 | 32,496,996 | Numpy: Referencing an array column in another array without copies | <p>Using numpy, say you have a 3D array called <em>img</em> filled with pixel values and you want to build an array filled with zeros everywhere but on a given color channel. For example say that <code>img[0,0]=(42,84,126)</code> in the output array dedicated to the red channel I'd like to have <code>output_red[0,0]=(4... | <p>As the question is phrased, the answer is no.</p>
<p>(If you explain more about your goal and how you'd eventually use the output array, we might be able to suggest alternative solutions, e.g. that the output array doesn't have to be an array at all, or that it doesn't have to have the same shape as the input.)</p>... | pointers|numpy|optimization | 1 |
364,711 | 32,200,805 | Understanding numpy.gradient | <p>I have a time-series of voltage values recorded in <code>mV</code> every <code>0.02 ms</code>, stored as a numpy array.</p>
<p>If I do this,</p>
<pre><code>dv_dt = np.gradient(v),
</code></pre>
<p>what will the units of <code>dv_dt</code> be? Will it be some multiple of <code>V/s</code>; e.g. <code>mV/s</code>, <c... | <p>Watch out for the unit spacing of dt. As noted in the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html" rel="nofollow noreferrer">documentation</a> <code>gradient</code> assumes unit spacing of 1 unless you provide the sample distance by the <code>vararg</code> argument. Your case is ... | python|arrays|numpy|derivative | 2 |
364,712 | 32,334,322 | Find adjacent elements in a 2D numpy grid | <p>so I have a 2D Numpy array that looks something like this:</p>
<pre><code>[[1,1,1,2,2],
[1,1,1,2,2],
[1,2,2,2,2]]
</code></pre>
<p>where each number in the array represents a region. I want to generate a boolean array that shows <strong><code>True</code></strong> on positions whos adjacent elements are NOT all e... | <p>Generally speaking, you're looking for an edge detection filter.</p>
<p>There's more than one way to handle this, but the basic idea is that you convolve a simple filter such as <code>[-1, 1]</code> or <code>[-1, 0, 1]</code> with your data. <code>scipy.ndimage</code> and scikit-image are good places to start for ... | python|arrays|numpy|grid|boundary | 6 |
364,713 | 32,506,689 | Replace NaN in DataFrame index | <p>I have a DataFrame which looks like this:</p>
<pre><code> one | two
a | 2 | 5
b | 3 | 6
NaN | 0 | 0
</code></pre>
<p>How do I replace the NaN in the index with a string, say "No label"?</p>
<p>I tried:</p>
<pre><code>df = df.replace(np.NaN, "No label")
</code></pre>
<p>and </p>
<pre><code>d... | <p>You can process the original index as a Series first and then re-assign the index:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'one': [2, 3, 0], 'two': [5, 6, 0]}, index=['a', 'b', np.nan])
df.index = pd.Series(df.index).replace(np.nan, 'No label')
print df
</code></pre>
<p>Output:</p>... | pandas|replace|label|dataframe|nan | 7 |
364,714 | 32,312,206 | Fast indexing: Cython with numpy array of bool and str | <p>I am trying to speed up a Python script. I have profiled the code and re-factored quite a lot already in pure Python. It seems that I am still spending a lot of time in accessing some numpy arrays in a way that looks like:</p>
<pre><code>KeyArray[BoolArray[index]]
</code></pre>
<p>where <code>KeyArray</code> is nd... | <p>As @Joe said, moving a single indexing statement to Cython won't give you speed. If you decide to move more of your program to Cython, you need to fix a number of problems. </p>
<p>1) You use <code>def</code> instead of <code>cdef</code>, limiting you to Python-only functionality.<br>
2) You use the old buffer synt... | python|numpy|indexing|cython | 1 |
364,715 | 32,547,440 | Python Pandas: How to move one row to the first row of a Dataframe? | <p>Given an existing Dataframe that is indexed. </p>
<pre><code>>>> df = pd.DataFrame(np.random.randn(10, 5),columns=['a', 'b', 'c', 'd', 'e'])
>>> df
a b c d e
0 -0.131666 -0.315019 0.306728 -0.642224 -0.294562
1 0.769310 -1.277065 0.735549 -0.900214 -1.8... | <p>To move the third row to the first, you can create an index moving the target row to the first element. I use a conditional list comprehension to join by lists.</p>
<p>Then, just use <code>iloc</code> to select the desired index rows.</p>
<pre><code>np.random.seed(0)
df = pd.DataFrame(np.random.randn(5, 3),column... | python|numpy|pandas|dataframe | 13 |
364,716 | 32,409,504 | split randomly a list of array in Python | <p>i have a list of array in Python</p>
<pre><code>import numpy as np
mylist = [np.random.randint(0, i, int(10)) for i in (10,100,3)]
[array([5, 5, 7, 2, 0, 5, 7, 8, 6, 9]), array([42, 70, 30, 62, 44, 8, 40, 68, 46, 93]), array([0, 0, 0, 0, 0, 1, 2, 0, 1, 2])]
</code></pre>
<p>i wish to divide (if possible randomly)... | <p>You can try this:</p>
<pre><code>from numpy.random import permutation
from numpy import split
ratio = 0.3
l1, l2 = zip(*map(lambda x: split(permutation(x), [int(ratio*len(x))]), mylist))
print list(l1)
print list(l2)
</code></pre>
<p>where a permutation operation is used so that the partitioning is randomized, and... | python|arrays|numpy|random | 2 |
364,717 | 32,517,681 | Solve for the argument to a function that will produce a particular return value | <p>Suppose I have a Python function <code>y</code> of <code>x</code>, where <code>x</code> must be a number, and the return value is always a number. <code>y</code> is a mathematical function of one variable.</p>
<p>Is there a function in Python (i.e., in <code>numpy</code>, <code>scipy</code>, etc.) that would be ab... | <p>You can wrap your function y(x) so that it's offset by the desired value. Here's a simple demo of the long way to do that:</p>
<pre><code>def y(x):
return x*x
def offset_function(f, desired=0):
def newf(x):
return f(x) - desired
return newf
y9 = offset_function(y, 9)
for x in range(5):
pr... | python|numpy|optimization|scipy|solver | 2 |
364,718 | 32,263,913 | How to plot in python where x-axis values appears more than once, like 0 1 2 3 2 1 0 | <p>I'm new to python, and was playing around with it's plotting capability. I wanted to plot <code>Y1</code> and <code>Y2</code> where <code>X</code> values go from 10 to 100 with steps of 10, and 100 to 10 with steps of -10. </p>
<p>I was able to plot this using Excel.
Here are the <code>X</code> and <code>Y</code> ... | <p>Its unclear exactly what you are asking. Do you want the repeated <code>X</code> values to plot on top of each other? In which case, you can use <code>ax.plot</code> as shown in the first example (<code>ax1</code>) below.</p>
<p>If you want the X axis to show all the <code>X</code> values in the order they appear i... | python|numpy|matplotlib|plot | 1 |
364,719 | 32,531,143 | Issue with scipy install on windows | <p>I had previously install scipy, numpy and then scikit-learn which were all working fine.
Today, I updated all my libraries with a pip install.
numpy and scikit-learn updated to the latest versions, but scipy had a compile issue and was rolled back.</p>
<p>When I try </p>
<pre><code>from sklearn.ensemble import Ran... | <p>On Windows, you can run into problems if installing <code>scipy</code> using <code>pip</code>. If you're running anaconda, you can try what was suggested in the comments:</p>
<pre><code>conda install scipy
</code></pre>
<p>Or you can try downloading a Windows version of the latest scipy from <a href="http://www.lf... | python|numpy|scipy|scikit-learn | 10 |
364,720 | 40,377,157 | copy_blanks(df,column) should copy the value in the original column to the last column for all values where the original column is blank | <pre><code>def copy_blanks(df, column):
like this, Please suggest me.
Input:
e-mail,number
n@gmail.com,0
p@gmail.com,1
h@gmail.com,0
s@gmail.com,0
l@gmail.com,1
v@gmail.com,0
,0
</code></pre>
<p>But, here we are having default_value option. In that we can use any value. when we have used this option. that value wil... | <p>consider your sample <code>df</code></p>
<pre><code>df = pd.DataFrame([
['n@gmail.com', 0],
['p@gmail.com', 1],
['h@gmail.com', 0],
['s@gmail.com', 0],
['l@gmail.com', 1],
['v@gmail.com', 0],
['', 0]
], columns=['e-mail','number'])
print(df)
e-mail number
0 n@gmail.com ... | pandas | 0 |
364,721 | 40,422,047 | Nans on pd.factorize return object | <p>I'm using the code bellow to encode a data set:</p>
<pre><code>foo= pd.DataFrame({
'Col1' : ['B', 'A', 'B', 'C', 'B', 'A', 'C'],
'Val' : np.random.randn(7)
})
r=pd.factorize(foo['Col1'], sort=True)
foo['Col1'] = r[0]
</code></pre>
<p>which produces the fol... | <p>Since the column contains dtypes of <code>float</code>+ <code>str</code> in it as a result of <code>Nans</code> present in it, <code>pd.factorize</code>excludes the missing values after allocating a value of -1(default).</p>
<p>An alternative would be to compute the unique values present in the series and later con... | python|python-2.7|pandas | 2 |
364,722 | 40,666,466 | multiple row selection in multi indexed dataframe | <p>Suppose I write this code in pandas to create a dataframe:</p>
<pre><code>pd.DataFrame({'x':random.sample(range(1,100), 4),
'y':random.sample(range(1,100), 4),
'z':random.sample(range(1,100), 4)},
index = [['a1', 'b1', 'c1','d1'], ['a2', 'b2', 'c2', 'd2']])
</code></pre>
<p>This results... | <p>You were very close: you need to define the indexes as a list of tuples and not as a list of lists:</p>
<pre><code>target_index = [('a1', 'a2'), ('b1', 'b2'), ('c1', 'c2')]
</code></pre>
<p>Then </p>
<pre><code>df.loc[target_index]
</code></pre>
<p>gives you the desired output:</p>
<pre><code> x y z
a1 ... | python|pandas|dataframe|multi-index | 3 |
364,723 | 40,454,030 | Count and Sort with Pandas | <p>I have a dataframe for values form a file by which I have grouped by two columns, which return a count of the aggregation. Now I want to sort by the max count value, however I get the following error:</p>
<blockquote>
<p>KeyError: 'count'</p>
</blockquote>
<p>Looks the group by agg count column is some sort of i... | <p>I think you need add <code>reset_index</code>, then parameter <code>ascending=False</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="noreferrer"><code>sort_values</code></a> because <code>sort</code> return:</p>
<blockquote>
<p>FutureWarning: sort(co... | python|sorting|pandas|count|group-by | 91 |
364,724 | 40,696,128 | Python Invalid syntax ':' when trying to select a list of rows to skip when importing from excel | <p>I'm trying to import some data from an excel file which has a very large footer.</p>
<p>When i put <code>skip_footer=[245:]</code> it tells me that : is invlaid syntax.</p>
<p>How can i cut out the footer from row <code>(0-indexed) 245</code> to the end of the footer?
I dont want to manually list it <code>[245, 24... | <p>skip_footer requires an integer. To skip from line 245 onward, unfortunately you need to know the number of lines in the file. </p>
<pre><code>import openpyxl
wb = openpyxl.load_workbook('your_file.xlsx')
sheet = wb.worksheets[0]
last_row = wb.max_row
pd.read_excel('your_file.xlsx', skip_footer=last_row-245)
</cod... | excel|pandas | 0 |
364,725 | 40,518,780 | How to `np.loads()` an `np.save()`d array? | <p>To wit:</p>
<pre><code>>>> foo = np.array([1, 2, 3])
>>> np.save('zomg.npy', foo)
>>> np.load('zomg.npy')
array([1, 2, 3])
</code></pre>
<p>All good. What about <code>loads</code>?</p>
<pre><code>>>> np.loads(open('zomg.npy', 'rb').read())
Traceback (most recent call last):
F... | <p>I'd suggest sticking with the <code>np.save</code> and <code>np.load</code> unless there is some extra functionality of pickle that you need. Then it might be less confusing to use <code>pickle</code> directly rather via one of the <code>np</code> synonyms.</p>
<p>============</p>
<p>There is an undocumented <code... | python|python-3.x|numpy|serialization|pickle | 2 |
364,726 | 40,408,346 | Formatting nlargest output pandas | <p>I'm new to pandas and so am a bit unfamiliar with how it works. I have processed some data and obtained the results I want, however, I am having trouble figuring out how to format the output with print. For instance, I only want to display certain rows of data, as well as putting certain values in ().</p>
<p>From d... | <p>My professor helped me figure this out. Really what I needed was to know how to iterate through values in the DataFrame. My solution looks like this:</p>
<pre><code>df = pd.read_csv('data_file.csv')
tallmen = df[df['gender'] == 'M'].nlargest(2, 'height')
for i, val in tallmen.iterrows():
feet = val['heigh... | python|pandas|formatting | 0 |
364,727 | 40,615,459 | How do I re-organise data into a new dataframe in pandas that displays the changes in data in this way? | <p>I have started with two separate dataframes; one retrieved from a MySQL database (df_database) and another that has been created following a web scrape. The web scrape dataframe has already been split into two - df_new (rows not currently in the database) and df_existing (rows that already exist in the database).</p... | <p>IIUC</p>
<pre><code>pd.melt(
df1,
id_vars=['unique_identifier', 'version'],
value_vars=['ticker', 'name']
).set_index(['unique_identifier', 'variable', 'version']) \
.value.unstack().reset_index()
</code></pre>
<p><a href="https://i.stack.imgur.com/UaExx.png" rel="nofollow noreferrer"><img src="htt... | python|pandas|dataframe | 1 |
364,728 | 40,658,894 | ImportError: HDFStore requires PyTables, "No module named tables" | <p>I followed the installation guidelines from here. <a href="http://www.pytables.org/usersguide/installation.html" rel="nofollow noreferrer">http://www.pytables.org/usersguide/installation.html</a></p>
<p>So, whenever I run this command in iPython from PyTables/build/lib.linux-x86_64-2.7 folder, it works fine.</p>
<... | <p>To know what version of PyTables you are using, execute</p>
<pre><code>python -c 'import tables ; print tables.__file__'
</code></pre>
<p>for Python 2, or</p>
<pre><code>python3 -c 'import tables ; print(tables.__file__)'
</code></pre>
<p>for Python 3.</p>
<p>It will give you the path to the tables library.</p>... | python|pandas|pytables|hdfstore | 0 |
364,729 | 40,498,956 | python pandas new row attached to last one in csv when using to_csv in append mode | <p>I am trying to add a new row to the data in a csv file. While the data is added, instead of being inserted into the next row, it is added onto the end of the previous row. My problem code currently looks like: </p>
<pre><code>qlist = list(data)
entries = [response, 0,0,0,0]
df = pd.DataFrame([entries], columns=ql... | <p>Although your code snippet doesn't make much sense, I think your question is interesting. If I'm understanding you correctly, you have (1) an existing csv file, and (2) some output from a code snippet that you would like to add to that csv file. But your new data is being added in the last row of the existing csv fi... | python|csv|pandas|dataframe | 0 |
364,730 | 40,557,822 | Sum values from DataFrame into Parent Index - Python/Pandas | <p>I'm working with Mint transaction data and trying to sum the values from each category into it's parent category.</p>
<p>I have a dataframe mint_data that is created from all my Mint transactions:</p>
<pre><code>mint_data = tranactions_data.pivot(index='Category', columns='Date', values='Amount')
</code></pre>
<p... | <p>Let's call your dictionary "dct" and then make a new column that maps to the parent:</p>
<pre><code>>>> df['parent'] = df.reset_index()['index'].map(dct).values
A B C D E parent
par_a 0 0 5 0 0 par_a
cat1a 5 2 3 2 1 par_a
cat2a 0 1 2 1 0 par_a
par_b 1 0 1 1 2 par_b
cat1b... | python|pandas|dataframe | 1 |
364,731 | 40,531,829 | Retrain im2txt model with Open Images dataset | <p>I have a trained <em>im2txt</em> model (<a href="https://github.com/tensorflow/models/tree/master/im2txt" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/im2txt</a>). I used MSCOCO imageset for the training as it was written in the docs.</p>
<p>I want to continue training with Google Open... | <p>While it might be possible to retrain the model, remember that these two data sets come with different labeling semantics and conventions, so understand that the results might not be 100% comparable.</p>
<p>You need to pre-process the data using a script similar to the <a href="https://github.com/tensorflow/models/... | tensorflow | 4 |
364,732 | 40,513,466 | tensorflow retrain.py app.run() got unexpected keyword argument 'argv' | <p>I am trying to run the Tensorflow for Poets sample. I pass the following:</p>
<p><code>python examples/image_retraining/retrain.py --bottlenext_dir=tf_files/bottlenecks --how_many_training_steps 500 --model_dir=tf_files/inception --output_graph=tf_files/retrained_graph.pb --output_labels=tf_files/retrained_labels.... | <p>I had the same problem earlier. Downloading the examples from a different branch fixed it.</p>
<pre><code>git clone -b r0.11 https://github.com/tensorflow/tensorflow.git
</code></pre> | python|tensorflow | 6 |
364,733 | 40,515,589 | Having trouble converting df index to datetime object | <p>So this is my dataframe</p>
<pre><code> Ticker Owner \
SEC Form 4
Nov 09 02:19 PM HSY HERSHEY TRUST
Nov 09 02:05 PM HSY HERSHEY TRUST CO
Nov 09 02:03 PM WDFC PITTARD ... | <p>Maybe you missed to append the year since it is not specified in the data. Here is a possible solution.</p>
<pre><code>zz = """"SEC Form 4" Ticker Owner
"Nov 09 02:19 PM" "HSY" "HERSHEY TRUST"
"Nov 09 02:05 PM" HSY "HERSHEY TRUS... | datetime|pandas | 1 |
364,734 | 40,553,474 | Do I need to iterate through every row of data to calculate time per column category? | <p>I have list of data in python that looks like the table below.</p>
<p>Basically, it's generated from observing what our robot is doing in our maze/arena. We have timestamps for events, at the moment the timestamps are event driven and not periodic. </p>
<p>I need to find the time spent in each arena in an efficien... | <p>Create the vector of time deltas, then group and sum against it:</p>
<pre><code>df['delta'] = df.TimeStamp - df.TimeStamp.shift()
df.groupby('Arena').delta.sum()
Out[62]:
Arena
Arena_A 21.0
Arena_B 23.0
Arena_C 10.0
Arena_D 32.0
Arena_E 22.0
Name: delta, dtype: float64
</code></pre> | python|pandas|dataframe|data-processing | 2 |
364,735 | 40,432,553 | Cython numpy array with Openmp (No GIL) | <p>I am not sure if this has been addressed previously, i tried searching but didnt find exactly what i was looking for. I would like to get the following code working (name of file being some_CD.pyx)</p>
<pre><code>import numpy as np
cimport numpy as np
cimport cython
from cython.parallel import *
ctypedef np.float6... | <p>This loop can't be parallelized because it's an iterative algorithm. In other words, later iterations depend on the result of the earlier iterations.</p>
<p>Ignoring this problem, here's how you would change the code..</p>
<p>Without the GIL you can only use basic indexing (no slicing) and a very small number of P... | python|arrays|numpy|openmp|cython | 1 |
364,736 | 40,697,241 | Is it possible to retain the datatype of individual numpy arrays with concatenation | <pre><code>import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
a = np.reshape(a,(1,6))
b = np.array([[1,2.1],[3.5,4],[5,6.8]])
b = np.reshape(b,(1,6))
c = np.concatenate((a,b))
</code></pre>
<p>When I concatenate the arrays a and b with <strong>np.concatenate</strong>. I get an array of type float. Is it possible to... | <p>There are mixed types... If I have read you correctly you essentially want to pair the values from 'a' and 'b'. If that is the case, you can flatten your input arrays and reassemble them while retaining the appropriate dtype. This is one approach, shown verbosely so you can alter the format if you want to construc... | python|numpy | 0 |
364,737 | 18,581,404 | Trigger an event in Python traits package when an Array element is changed | <p>I'm using Python's traits package, and I'm trying to figure out the right way to use the traits.trait_numeric.Array class. It's straightforward to write a subclass of traits.api.HasTraits with an Array trait, so that when the Array changes, an on_trait_change is triggered, but I can't figure out how to trigger any s... | <p>I'm afraid that it's not really possible. numpy arrays view raw memory. Anything can change that memory without going through the numpy array object itself. The pattern we usually use is to reassign the whole array after doing the slice/index assignment.</p>
<pre><code>import numpy as np
from traits.api import Arra... | python|arrays|numpy|traits|traitsui | 8 |
364,738 | 18,756,034 | How to trim a a list and generate a numpy 2-D array? | <p>Say I have a numpy array:</p>
<pre><code>[[1,2],
[3,4],
[5,6,7]]
</code></pre>
<p>Is there any compact method to trim the array and make it aligned along the second dimension, i.e.</p>
<pre><code>[[1,2],
[3,4],
[5,6]]
</code></pre> | <p>Does slicing work for numpy arrays? If so the following code should do the trick.</p>
<pre><code>array = [[1,2],
[3,4],
[5,6,7]]
array = numpy.array([a[:2] for a in array])
</code></pre>
<p>I'm not sure if slicing works for numpy arrays so I will delete this answer if it's wrong.</p> | python|arrays|list|numpy | 3 |
364,739 | 18,536,352 | What direction should I go to go faster than np.fft | <p>I have some code that is <strong>heavily</strong> using <code>np.fft.rfft</code> and <code>np.fft.irfft</code>, such that this is the bottleneck for optimisation.</p>
<p>Is there any chance of going faster than this, and if so what are my best options. Thoughts that occur to me would be:</p>
<ul>
<li>Cython - hea... | <p>I've found this question/answer which actually answer part of this:</p>
<p><a href="https://stackoverflow.com/a/8481916/1900520">https://stackoverflow.com/a/8481916/1900520</a></p>
<p>Shows that there is another FFT implementation in scipy that is quite a bit faster, but also that there is a package called FFTW th... | optimization|python-2.7|numpy|fft|cython | 6 |
364,740 | 18,665,873 | Filtering a list based on a list of booleans | <p>I have a list of values which I need to filter given the values in a list of booleans:</p>
<pre><code>list_a = [1, 2, 4, 6]
filter = [True, False, True, False]
</code></pre>
<p>I generate a new filtered list with the following line:</p>
<pre><code>filtered_list = [i for indx,i in enumerate(list_a) if filter[indx]... | <p>You're looking for <a href="http://docs.python.org/3.1/library/itertools.html#itertools.compress" rel="noreferrer"><code>itertools.compress</code></a>:</p>
<pre><code>>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compre... | python|list|numpy | 249 |
364,741 | 62,036,284 | Rolling count pandas for categorical variables using time | <p>I have a dataframe that looks like this: </p>
<pre><code>Datetime | Category | ID
--------------------------
2020-01-30 | A | 1
2020-02-01 | B | 1
2020-02-02 | A | 1
2020-02-20 | A | 1
2020-01-28 | B | 2
2020-01-29 | C | 2
2020-01-30 | C | 2
2020-01-31 | D |... | <p>You can use <code>resample()</code> rather than <code>rolling()</code>, because your time index frequency is daily and you want weekly stats, so try something like this:</p>
<pre><code>df.groupby('ID').resample('1w').apply(lambda s: s.value_counts().head(2))
</code></pre>
<p>Note that this only works in versions o... | python|pandas|rolling-computation | 1 |
364,742 | 61,796,532 | Tensorflow asking to run the build even though it is done | <p>As always, tensorflow the weird dumb framework is going unintuitive haywire piece of crap on me. Can someone please be kind enough to help me out with this? I am able to run the checkpointing (how much of a mess can saving a model be? leave it to tensorflow to make a mountain out of a molehill) <a href="https://www.... | <p>TL/DR: This is not a problem with <code>save_weight</code> method. In order to build a subclassed model, you need to run the subclassed model on a real input. I only added two lines to the end of your code as shown below.</p>
<pre><code>#net.build(input_shape=[1,]) # don't need it. When you call the model with real... | tensorflow|tensorflow2.0|tf.keras | 1 |
364,743 | 61,895,538 | How can I save Excel worksheets in a single workbook as workbooks with their data | <p>How can I save Excel worksheets in a single workbook as workbooks with their data?
I've been able to load the workbook into python with:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
sheets = pd.read_excel('File.xlsx', sheet_name=None)
new_sheet=sheets.keys()
</code></pre>
<p>My issue is ... | <p>Try this:</p>
<pre><code>import pandas as pd
df=pd.read_excel(File.xlsx', sheet_name=None)
sheet_names=df.keys()
for sheet_name in sheet_names:
sheet_name=pd.DataFrame(df[sheet_name].head())
sheet_name.to_csv(str(sheet_name)+'.csv', index=False)
</code></pre>
<p>Note: Ensure your 'File.xlsx' is in the sa... | python|python-3.x|pandas | 1 |
364,744 | 61,729,905 | Plotting every 30th file of a list | <p>I have 1000 files and if I want to plot every 30th file. I tried to reach out the simplest way of separating but it does not work because I have sorted files and by the code, it tries to plot every single file. </p>
<pre><code>import os
import numpy as np
import matplotlib.pyplot as plt
import pylab
import matplotl... | <p>I believe that you just need to slice <code>l</code> with an appropriate <code>step</code>, hence replacing this:</p>
<pre><code>for i, d in enumerate(l):
</code></pre>
<p>with this:</p>
<pre><code>for i, d in enumerate(l[::30]):
</code></pre>
<p>will do.</p> | python|numpy|matplotlib | 0 |
364,745 | 62,039,237 | Train test split Fastai | <p>I am using numpy.random.seed() to split the dataset in same order every time I am going to train using keras.</p>
<p>I have a doubt when I am trying fastai, is that numpy.random.seed() function will work same as in keras, where I am using ImageDataBunch.from_folder() function to load the dataset...</p>
<p>If not, ... | <p>According the documentation of <a href="https://docs.fast.ai/vision.data.html#ImageDataBunch.from_folder" rel="nofollow noreferrer"><code>from_folder()</code></a> there is a <code>seed</code> argument that you can use:</p>
<pre><code>ImageDataBunch.from_folder(seed=1234)
</code></pre> | python|machine-learning|deep-learning|pytorch|fast-ai | 0 |
364,746 | 61,698,094 | Pandas custom sorting of the rows based on a list | <p>Given a dataframe and a list, with the values of a column of a dataframe.
(the list is equaly long as the rows of the dataframe and each value appear exactly ones)
How can i sort the rows in the dataframe according to the order in the list?</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'user': ['Bob', 'Jane... | <p>Let us do <code>pd.Categorical</code> with <code>argsort</code></p>
<pre><code>df=df.iloc[pd.Categorical(df.user,z).argsort()]
df
user income
1 Jane 50000
2 Alice 42000
0 Bob 40000
</code></pre>
<p>Or <code>reindex</code></p>
<pre><code>df=df.set_index('user').reindex(z).reset_index()
</code></pr... | python|pandas | 1 |
364,747 | 62,040,534 | Filter rows based on the total number of years present using pandas | <p>Suppose I have a data frame <code>df</code> with these columns:</p>
<pre><code>import pandas as pd
df = pd.read_csv('data.csv')
df
Cities Start_date End_date data_avail
A 1-03-2000 1-03-2012 12
B 1-12-2002 1-12-2005 3
C 1-04-2000 1-04-2010 10
D 1-04-2009 1-04-2016 7
E ... | <p>Does this work for you?</p>
<p>data.csv</p>
<pre><code>Cities,Start_date,End_date,data_avail
A,1-03-2000,1-03-2012,12
B,1-12-2002,1-12-2005,3
C,1-04-2000,1-04-2010,10
D,1-04-2009,1-04-2016,7
E,1-04-2003,1-05-2007,5
</code></pre>
<pre class="lang-py prettyprint-override"><code>def can_allow(row):
allowed_years... | python|pandas | 1 |
364,748 | 61,890,729 | creating dataframe from nested dictionary using python | <p>The following is the json data available to me</p>
<pre><code>{
"status": "success",
"message": "Transactions Details",
"TxnArray": [
{
"transactionAmount": {"0": 3500},
"createdAt": {"0": "17/04/2020"}
},
{
"transactionAmount": {"1": 4500},
"createdAt": {"1": "19/0... | <p>A more compact approach:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([
{k: v[str(i)] for k, v in list_item.items()} for i, list_item in enumerate(json_data['TxnArray'])
])
</code></pre> | python-3.x|pandas | 1 |
364,749 | 61,724,420 | MELT: multiple values without duplication | <p>Cant be this hard. I Have</p>
<pre><code>df=pd.DataFrame({'id':[1,2,3],'name':['j','l','m'], 'mnt':['f','p','p'],'nt':['b','w','e'],'cost':[20,30,80],'paid':[12,23,45]})
</code></pre>
<p>I need</p>
<pre><code> import numpy as np
df1=pd.DataFrame({'id':[1,2,3,1,2,3],'name':['j','l','m','j','l','m'], 't':['f','p','... | <p>EDIT: I think simpliest here is set missing values by <code>variable</code> column in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a>:</p>
<pre><code>df2 = df.melt(['id', 'name','cost','paid'], value_name='t') ... | python-3.x|pandas | 1 |
364,750 | 61,772,676 | Error in meanSquaredError: Shapes 10,1 and 10,2 must match (tensorflow.js) | <p>My code loads data from csv. Then I build a model and pass the data to it. Then I try to train my model with the data.</p>
<p>Right now the above error occurs. As I have very small experience on javascript I do not know where to search. I assume it has something to do with my .batch-call. If I change the line to "}... | <p>The last layer has <code>units:2</code> whereas only a single column <code>quit</code> is set as label. </p>
<p>Either another column is set as label or the number of unit should be 1</p> | javascript|neural-network|tensorflow.js | 1 |
364,751 | 61,849,832 | Use boolean numpy array for indexing a list? | <p>can anyone tell my what I am doing wrong?
I created an integer array from a boolean array but still cannot use it as an index for a list:</p>
<pre><code>dataset = []
dataset.append({
"a": "few",
"b": "cd"
})
dataset.append({
"a": "fe",
"b":... | <p>That magic only works with numpy arrays, <code>dataset</code> is a list. </p>
<p>You could convert it to a numpy array with a custom datatype.</p>
<p>And it only works if you don't use <code>np.where</code> and stick with a boolean array.</p>
<p>Negating <code>~</code> a result of <code>np.where</code> does not m... | numpy | 0 |
364,752 | 61,915,461 | Targets must be 1-dimensional Top_k_categorical_accuracy in Tensorflow | <p>I've just finished training an Inception V3 CNN and I'm trying to measure accuracy on the training dataset, specifically, top-k accuracy. I invoke the function called <code>top_k_categorical_accuracy</code> from <code>tensorflow.keras.metrics</code> ordering my parameters properly <code>(y_true, y_pred, k)</code> bu... | <p>Have you tried this one?</p>
<pre class="lang-py prettyprint-override"><code>y_pred = np.argmax(y_pred, axis=1)
</code></pre>
<p>As I understand you have something like <code>Dense(6, activation='softmax')</code> at last layer. That's why <code>y_pred</code> is matrix. The script above can help.</p> | python|tensorflow|machine-learning|keras|deep-learning | 1 |
364,753 | 61,826,144 | Averaging n elements along 1st axis of 4D array with numpy | <p>I have a 4D array containing daily time-series of gridded data for different years with shape (year, day, x-coordinate, y-coordinate). The actual shape of my array is (19, 133, 288, 620), so I have 19 years of data with 133 days per year over a 288 x 620 grid. I want to take the weekly average of each grid cell over... | <p>You can reshape and take mean:</p>
<pre><code>week_mean = dummy_data.reshape(2,-1,7,3,3).mean(axis=2)
# in your case .reshape(year, -1, 7, x_coord, y_coord)
# check:
(dummy_data.reshape(2,2,7,3,3).mean(axis=2) == solution).all()
# True
</code></pre> | python-3.x|numpy | 1 |
364,754 | 61,877,535 | Elegant way to encode a list of lists | <p>Currently I am trying to one hot encode a list of lists that contain single elements. What is a clean Pythonic way to go from representation 2 to representation 1? Additionally I would like to know a clean approach to go from representation 1 to representation 2. </p>
<p>Representation 1</p>
<pre><code>[[1. 0. ... | <p>Using pure basic conditionnal list comprehension, for representation 1 to 2:</p>
<pre><code>r1 = [[1., 0., 0., 0., 0., 0.],
[0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1., 0.]]
len_r1l = len(r1[0]) # length of each sublist, here 6
r2 = [[0], [3], [4]]
r1_r2 = [[i] for l in r1 for i in range(len_r1l) if... | python|numpy|encoding|one-hot-encoding | 3 |
364,755 | 61,811,670 | pandas appending a streaming data series | <p>I am trying to append a streaming data series to a pandas dataframe.
The columns are constant. I have used the following</p>
<pre><code>import pandas as pd
import random
import time
while True:
ltp=random.randint(0, 100)
trade={'token':12345,'name':'abc','ltp':ltp}
time.sleep(2)
df=pd.DataFrame(trad... | <p>Your problem is that you create <code>DataFrame</code> object each iteration, using this line:</p>
<pre><code>while True:
...
df=pd.DataFrame(trade,index=[1])
...
</code></pre>
<p>You need to create new <code>DataFarme</code> before starting the <code>while</code> loop, like this:</p>
<pre><code>impor... | pandas | 0 |
364,756 | 61,855,881 | Trouble using FIFOQueue in Tensorflow C++ | <p>I have had some success using this programming format in tensorflow with other ops, but I am unable to get the FIFOQueue to work properly. The following code will compile and run, but there is never any data placed on the queue.</p>
<pre><code>vector<Tensor> outputs;
Scope root = Scope::NewRootScope();
auto... | <p>I was actually pretty close, but there was some misunderstanding of the nature of the call. Each of the operations in the graph start from queue, so repeated calls to session->Run requesting the appropriate output are what is needed to effect the action of the queue. A slightly more detailed example follows. It p... | c++|tensorflow|queue | 1 |
364,757 | 61,748,123 | How to train two pytorch networks with different inputs together? | <p>I'm totally new to pytorch, so it might be a very basic question. I have two networks that should be trained together. </p>
<ol>
<li><p>First one takes data as input and returns its embedding as output.</p></li>
<li><p>Second one takes pairs of embedded datapoints and returns their 'similarity' as output.</p></li>
... | <p>You can use single optimizer for this purpose, and even pass different learning rate for each network.</p>
<pre class="lang-py prettyprint-override"><code>optimizer = optim.Adam([
{'params': network1.parameters()},
{'params': network2.parameters(), 'lr': 1e-3}
], lr=1e-4)
# ...
loss = loss1 + loss2
loss.b... | deep-learning|neural-network|pytorch | 0 |
364,758 | 61,988,285 | How to use my own picture to generate adversarial example using FGSM? | <p>I am trying to generate adversarial example using FGSM, and the code frame i am using is from Google Colab code(<a href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/generative/adversarial_fgsm.ipynb#scrollTo=wpYrQ4OQSYWk" rel="nofollow noreferrer">https://colab.research.go... | <p>I tested your code with some of my images and everything is ok.</p>
<p>it's just about your image encode.
run again with some other images or change the image encoding.</p> | python|tensorflow|keras|deep-learning|jupyter-notebook | 0 |
364,759 | 61,878,031 | Fitting a linear combination of distributions | <p>I have 5 arrays (columns of a pandas data frame)
and I want calculate the best fit for a linear combination of the distributions to an exponential distribution.
for example:</p>
<pre><code>a*(d1)+b*(d2)+c*(d3)+d*(d4)+e*(d5)=Y
</code></pre>
<p>where Y has an exponential distribution (which i know) and a,b,c,d,e ar... | <p>What you're describing is a linear model. Use the package <a href="https://scikit-learn.org/stable/index.html" rel="nofollow noreferrer">scikit-learn</a>:</p>
<pre><code>from sklearn.linear_model import LinearRegression
X = df[['d1', 'd2', 'd3', 'd4', 'd5']]
reg = LinearRegression().fit(X, Y)
reg.get_params()
</co... | python|pandas|statistics|distribution|curve-fitting | 0 |
364,760 | 61,838,743 | Convert JSON list to pandas dataframe | <p>I have very large json data with the following syntax:</p>
<pre><code>[
{
"origin": 101011001,
"destinations": [
{"destination": 101011001, "people": 7378},
{"destination": 101011002, "people": 120}
]
},
{
"origin": 101011002,
"destinations": [
{"destination": 101011001, "people": 754}... | <p>Use <code>json_normalize</code>. This should work as intended:</p>
<p><strong>Edit</strong> (from <code>string</code> to <code>list of dicts</code>, then <code>json_normalize</code>)</p>
<pre><code>data = """[
{
"origin": 101011001,
"destinations": [
{"destination": 101011001, "people": 7378},
{"des... | python|sql|json|pandas|dataframe | 1 |
364,761 | 61,672,258 | What should be the Input types for Earth Mover Loss when images are rated in decimals from 0 to 9 (Keras, Tensorflow) | <p>I am trying to implement the NIMA Research paper by Google where they rate the image quality. I am using the TID2013 data set. I have 3000 images each one having a score from 0.00 to 9.00</p>
<pre><code>df.head()
>>
Image Name Score
0 I01_01_1.bmp 5.51429
1 i01_01_2.bmp 5.56757
2 i01_01_3... | <p>Following what was introduced <a href="https://stackoverflow.com/questions/61673551/working-of-the-earth-mover-loss-method-in-keras-and-input-arguments-data-types">here</a>, I have a couple of ideas about the <a href="https://stackoverflow.com/questions/31919818/theano-sqrt-returning-nan-values">NaN gradient</a>...<... | python|tensorflow|keras|deep-learning|image-recognition | 3 |
364,762 | 61,629,395 | How to prune weights less than a threshold in PyTorch? | <p><em>How to prune weights of a CNN (convolution neural network) model which is less than a <strong>threshold value</strong> (let's consider prune all weights which are <= 1).</em> </p>
<p>How we can achieve that for a weight file saved in .pth format in pytorch?</p> | <p>PyTorch since <code>1.4.0</code> provides model pruning out of the box, <a href="https://pytorch.org/tutorials/intermediate/pruning_tutorial.html" rel="noreferrer">see official tutorial</a>.</p>
<p>As there is no <code>threshold</code> method to prune in PyTorch currently, you have to implement it yourself, though ... | python|pytorch|conv-neural-network|pruning | 17 |
364,763 | 61,984,995 | Deserialize DateTime field in json file using Python (Pandas) | <p>I am parsing a json file using Pandas in Python. There is a field called DateTime with the following string in it: <code>1581251737000</code>. Does anybody know the format of this DateTime field so that I can parse it using the pandas.to_datetime() function?</p> | <p>The quickest way to do this is by using pandas:</p>
<pre><code>import pandas as pd
from datetime import datetime
x = "1581251737000"
pd.to_datetime(x, unit="ms")
#Output
Timestamp('2020-02-09 12:35:37')
</code></pre>
<p>You can use strftime to convert this to your desired format:</p>
<pre><code>pd.to_datetime(x... | python|json|pandas|datetime|parsing | 2 |
364,764 | 61,664,407 | Is there a way to create dummy variables in pandas that represent shared values of three dataframes? | <p>I have three dataframes that I've created three different sets of dummy columns. Each dataframe has a slightly different set of dummy variables than the other two. </p>
<p>I am trying to combine something that looks like this - </p>
<p>set1 - (a, b, c, d, e, f)</p>
<p>set2 - (a, b, c, d, f, k)</p>
<p>set3 - (a, ... | <p>I think this is what you meant, to merge the data-frames. And the answer for that is absolute yes. Pandas provide great functionality to merge data-frames into one. If you choose it, you probably assume that both of the data-frames share some common values:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({
... | python|pandas | 0 |
364,765 | 61,737,935 | How to highlight an Excel row when there is a string value in a cell on a row using Openpyxl? | <p>I'm trying to highlight a row in a spreadsheet (generated from my split_values dataframe) when there is a value in the cell under the "New Record ID" column The absolute reference for the row is 'J'. </p>
<p>Below is my most recent attempt at doing this: </p>
<pre><code># Group entries by client name and create... | <p>First, don't import in a loop, or you will have a bad day. Imports go on the top of your code, see the <a href="https://www.python.org/dev/peps/pep-0008/#imports" rel="nofollow noreferrer">PEP8 guidelines</a> for more info on that and other guidelines on styling Python code.</p>
<pre><code>from openpyxl import Work... | python|excel|pandas|openpyxl | 0 |
364,766 | 61,984,689 | Create a distance matrix from individual distances | <p>I have a list of distance increase between every two adjacent stations in a railroad in the right order. What I need to do is to create a matrix for the distances between every two stations. This is this list.</p>
<pre><code>
+-------------------------+-------------------------+---------------+
| Depart... | <p>You can compute the "positions" of the stations as the <code>cumsum</code> of distances and then use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html" rel="noreferrer"><code>scipy.spatial.distance.pdist</code></a> for computing the distances:</p>
<pre><code>from scipy.... | python|pandas|numpy|dictionary|matrix | 7 |
364,767 | 61,614,852 | Difference between prod and cumprod in python | <p>I cant figure what is the difference between the following methods:</p>
<ol>
<li><code>prod()</code></li>
<li><code>cumprod()</code></li>
</ol>
<p>And when do I use them</p> | <p><code>prod()</code> simply calculates the multiplication of the values with each other.</p>
<p><code>cumprod()</code> returns a Series of the cumulative product, i.e. the first element will be itself, the second - the multiplication of the two first elements, the third - multiplication of the three first elements a... | python|pandas|math|statistics | 2 |
364,768 | 61,713,051 | Conditional data imputation in Python | <p>I am trying to impute values in my dataset conditionally.</p>
<p>Say I have three columns, If Column 1 is 1 then Column 2 is 0 and Column 3 is 0; If column 1 is 2 then Column 2 is Mean () and Column 3 is Mean().</p>
<p>I tried running an if statement with the function any() and defined the conditions separately.</... | <p>Try it like this. </p>
<pre><code>mask1 = df['Retention_Term']==6
mask2 = df['cl_tot_calls_term_seq_1'] == 999
df.loc[mask1 & mask2, 'cl_tot_calls_term_seq_1'] = np.nan
</code></pre>
<p>Then the rest should be ok. </p>
<pre><code>df['cl_tot_calls_term_seq_1'].fillna(df['cl_tot_calls_term_seq_1'].median(), in... | python-3.x|pandas|valueerror | 0 |
364,769 | 61,738,590 | How can I compare the excel and csv column using python | <p>I just want to compare column A from wedartmore.csv to column C of Book1.xlsx and want to get index where values are same. </p>
<pre><code>import csv
# opening the CSV file
with open('wedartmore.csv', mode ='r')as file:
# reading the CSV file
csvFile = csv.reader(file)
# displaying the contents of the CSV f... | <p>Try this:</p>
<pre><code> import pandas as pd
df_csv = pd.read_csv('wedartmore.csv')
df_xlsx = pd.read_excel('Book1.xlsx')
merged_data = df_csv.merge(df_xlsx, left_on = 'Name', right_on = 'Artist')
print(merged_data)
</code></pre>
<p>There are two common rows in the CSV and xlsx files.</p>
<p>Please let me ... | python|excel|pandas|csv|compare | 1 |
364,770 | 61,968,875 | Get gradients with respect to inputs in Keras ANN model | <pre><code>bce = tf.keras.losses.BinaryCrossentropy()
ll=bce(y_test[0], model.predict(X_test[0].reshape(1,-1)))
print(ll)
<tf.Tensor: shape=(), dtype=float32, numpy=0.04165391>
print(model.input)
<tf.Tensor 'dense_1_input:0' shape=(None, 195) dtype=float32>
model.output
<tf.Tensor 'dense_3/Sigmoid:0' sha... | <p>One can do this using <a href="https://www.tensorflow.org/api_docs/python/tf/GradientTape" rel="nofollow noreferrer">tf.GradientTape</a>. I wrote the following code to learn a sin wave, and get its derivative in the spirit of <a href="https://stackoverflow.com/questions/56772362/derivative-of-neural-network-with-res... | tensorflow|keras|neural-network|gradient | 3 |
364,771 | 62,023,419 | Increment values of a column based on the current row of another column and the previous row of the same column | <p>I want to create a column with multiple conditions wherein if the column ' Batt' contains 'Discharge' and the previous row contains 'none' then increment the value by 1 starting with 0 if not then return the same value without any increments.</p>
<blockquote>
<p></p>
</blockquote>
<pre><code> Batt Disch ... | <p>IIUC, You can create a <code>boolean mask</code> and then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>Series.cumsum</code></a> to get the result:</p>
<pre><code>df['Continous Cycle count'] = (
(df['Batt Disch'].eq('Discharge'... | python|pandas|dataframe|where-clause | 1 |
364,772 | 61,723,714 | How to plot average and standard deviation together on a single graph using numpy and matplotlib in python? | <p>Calculated mean and standard deviation of a number of 2 column text files as follow:</p>
<pre><code>hvsr = np.array(hvsra)
hvsrm = hvsr.mean(axis=0)
hvsrstd = hvsr.std(axis=0)
</code></pre>
<p>Now, I want to plot them together that the average line and the standard deviation would be in the same figure, or at leas... | <p>When I used the <code>plt</code> syntax in the question the plot wasn't quite right. So I suggest using the <code>fig, ax</code> syntax as below. Also <code>errorbar</code> takes arguments <code>x, y, yerr</code>, so your syntax should look like below to plot mean values with std:</p>
<pre><code>fig, ax = plt.subpl... | python|numpy|matplotlib | 0 |
364,773 | 61,955,079 | Geodesic distance between geometry shapes Python | <p>Having a dfA with a column called geometry with the following geometrical shapes:</p>
<pre><code>d = {'id': [1, 2], 'geometry': ['POINT (-70.66000 -33.45000)', 'POINT (-74.08000 4.60000)']}
dfA = pd.DataFrame(data=d)
dfA
| | id | geometry |
|---|----|-----------------------|
| 0 | 1 | POINT (-70.66... | <p>If you can reduce the problem to figuring the geodesic distance to a collection of points, then a <a href="https://en.wikipedia.org/wiki/Vantage-point_tree" rel="nofollow noreferrer">vantage point tree</a> will give you an efficient solution. See my answer to a similar question <a href="https://stackoverflow.com/a/... | python|distance|geopandas|shapely|geodesic-sphere | 2 |
364,774 | 61,620,242 | vectorizing Pandas dataframes | <p>This is a data-cleaning exercise where specific elements of a dataframe A ought to be set to NaN depending on values that are decoded through B.</p>
<p>I have written the following code in which the 3-nested loops would run for 17h:</p>
<pre><code>def Convert(input):
X = np.fromstring(input[1:-1], dtype=np.int... | <p>If you want to substitute with <code>np.nan</code> any entry of A equal to the entry of Y in the same position you can use:</p>
<pre><code>A[A==Y]=np.nan
</code></pre>
<p>Does this solve your problem?</p>
<p>Your first code works but it's very slow.</p>
<p>Your second code doesn't work because the if statement i... | python|pandas|auto-vectorization | 1 |
364,775 | 61,730,245 | Analysing timeseries data using Panda dataframes | <p>I have some timeseries data as per below that I want to do some specific analysis on</p>
<pre><code>"timestamp","epic","closeprice_bid","closeprice_ask","last_traded_volume"
"2020-03-24 12:00:00","KA.D.BARC.DAILY.IP","91.17","91.38","7836277"
"2020-03-24 13:00:00","KA.D.BARC.DAILY.IP","90.33","90.66","8001075"
"202... | <p>you can do something like :</p>
<pre><code> (stock_data['closeprice_bid'].shift(-1) -stock_data['closeprice_bid'])/stock_data['closeprice_bid'] > 0.01
</code></pre>
<p>and similar for per hour case.</p> | python|pandas | 1 |
364,776 | 61,777,997 | Converting two Numpy data sets into a particularr PyTorch data set | <p>I want to play around with a neural network that recognizes handwritten numbers. I found some of these on the web which use PyTorch, however they seem to download the data from the MNIST website in a particular format. My data is, however, available as follows:</p>
<pre><code>with np.load('prediction-challenge-01-d... | <p>You can easily create your own dataset. Just inherit from <code>torch.utils.data.Dataset</code> and implement
<code>__getitem__</code> at the very least:<br>
Here is a quick and dirty example to get you going:</p>
<pre class="lang-py prettyprint-override"><code>class YourOwnDataset(torch.utils.data.Dataset):
d... | python|neural-network|pytorch | 1 |
364,777 | 61,637,363 | Formatting Excel sheets from Pandas | <p>I'm using the following code to print a dataframe to a csv;</p>
<pre><code>writer = pd.ExcelWriter('dataframe.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='dataframe')
writer.save()
</code></pre>
<p>But my df is about 200 columns wide (20 columns of 10 categories) and only 5 rows deep. </p>
<p>Is ... | <p>One solution might be to transpose the dataset using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transpose.html" rel="nofollow noreferrer"><code>.T</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>writer = pd.ExcelWriter('dataframe.xlsx', engine='xlsxwriter')
... | python|excel|pandas|formatting|data-manipulation | 1 |
364,778 | 61,999,310 | Get n rows before specific value in pandas | <p>Say, i have the following dataframe:</p>
<pre><code>import pandas as pd
dict = {'val':[3.2, 2.4, -2.3, -4.9, 3.2, 2.4, -2.3, -4.9, 2.4, -2.3, -4.9],
'label': [0, 2, 1, -1, 1, 2, -1, -1,1, 1, -1]}
df = pd.DataFrame(dict)
df
val label
0 3.2 0
1 2.4 2
2 -2.3 1
3 -4.9 -1
4 ... | <p>You can get the <code>index</code> values and then get the previous two row index values:</p>
<pre class="lang-py prettyprint-override"><code>idx = df[df.label == -1].index
filtered_idx = (idx-1).union(idx-2)
filtered_idx = filtered_idx[filtered_idx > 0]
df_new = df.iloc[filtered_idx]
</code></pre>
<p>output:</p... | python|pandas|for-loop|indexing | 3 |
364,779 | 61,946,391 | Pandas visualization time series | <p>I have time series class data. First column contains <code>join time</code>. Second column contains <code>leave time</code> for various students.Third column is <code>Class ID</code>. So there is possibility that student left the class in 10 min and again joined it after some time. His time is again recorded for bot... | <p>I think a sankey diagram can resolve your problem. Below is my test code.</p>
<pre><code>import pandas as pd
import numpy as np
from itertools import product
import seaborn as sns
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)
# generate test hours between 8:00 and 12:00
... | python|pandas|numpy|matplotlib|data-visualization | 0 |
364,780 | 61,636,627 | Read selected data from multiple files | <p>I have 200 .txt files and need to extract one row data from each file and create a different dataframe.</p>
<p>For example (abc1.txt,abc2.txt, .etc) set of files and i need to extract 5th row data from each file and create a dataframe. When reading files, columns need to be separated by '/t' sign.</p>
<p>like this... | <p>Here you go:</p>
<pre><code>import os
import pandas as pd
directory = 'C:\\Users\\PC\\Desktop\\datafiles\\'
aggregate = pd.DataFrame()
for filename in os.listdir(directory):
if filename.endswith(".txt"):
data = pd.read_csv(directory+filename, sep="\t", header=None)
row5 = pd.DataFrame(data.iloc[... | python|pandas|dataframe | 0 |
364,781 | 61,877,577 | Create different dataframes from dictionary | <p>I have created a dictionary by grouping some raingauges by their code with this coding</p>
<pre><code>dict_of_gauges = {k: v for k, v in PE_14.groupby('gauge_code')}
</code></pre>
<p>which gave me some entries like the ones shown below</p>
<pre><code> 11800 261070705A PAULISTA PE 2014-08-21 17:10:00 0.2... | <p>Probably the best way to do this is to just use the result of <code>groupby()</code>.</p>
<pre class="lang-py prettyprint-override"><code>>>> gb = PE_14.groupby('gauge_code')
>>> df0 = gb.get_group("261070705A") # Get a single group.
>>> list(gb.groups)
['261070705A', '261070704A', ..... | python|pandas|for-loop|iteration | 1 |
364,782 | 61,987,351 | Dropping rows with contain of a list of certain strings in Pandas | <p>I'm trying to drop rows which contain certain sub strings in a column. I want to drop all values that contain the sub strings 'Year', 'Monday', '/'</p>
<p>My <code>dataframe</code> looks like:</p>
<pre><code>col1
24/05/2020
May Year 2020
Monday
May 2020
</code></pre>
<p>The code I tried:</p>
<pre><code>drop_valu... | <p>The <code>Series.str.contains</code> method accepts a regex.</p>
<pre><code>>>> df
col1
0 24/05/2020
1 May Year 2020
2 Monday
3 May 2020
>>> drop_values = ['Monday','Year', '/']
>>> df[~df['col1'].str.contains('|'.join(drop_values))]
col1
3 May 2020
... | python|pandas | 4 |
364,783 | 61,817,278 | folium Choropleth colors showing grey only | <p>I'm trying to show happiness levels based on the country using folium choropleth, however, it doesn't work and all countries are just grey. This is what I get: </p>
<p><a href="https://i.stack.imgur.com/eVPCS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eVPCS.png" alt="image output"></a></p>
... | <p>Here the error:</p>
<pre><code>Key_on='feature.properties.name',
</code></pre>
<p>Modify it as:</p>
<pre><code>key_on='feature.properties.name',
</code></pre>
<p>and you get:</p>
<p><a href="https://i.stack.imgur.com/dhsxu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dhsxu.png" alt="enter ... | python|python-3.x|pandas|folium|choropleth | 0 |
364,784 | 61,938,124 | Filtering Numpy Array representing state | <p>There are various questions regarding filtering of the numpy arrays including:</p>
<p><a href="https://stackoverflow.com/questions/26154711/filter-rows-of-a-numpy-array">Filter rows of a numpy array?</a></p>
<p>But I have a slightly different issue:</p>
<pre><code>>>> x = np.empty(shape=(5,), dtype=[('ts... | <p>Couldn't find a built-in numpy solution for this kind of 'positive lookbehind' matching problem. Maybe something like this will do:</p>
<pre><code>idx_l = np.where(x['ts']<=2)[0]
idx_r = np.where(x['ts']>=4.9)[0]
x[idx_l[-1]+1:idx_r[0]+1]
</code></pre>
<p>To prevent <code>IndexError</code> in case <code>idx_... | python|numpy | 1 |
364,785 | 61,842,006 | SQL Server Merge using Pandas Dataframe? | <p>I have a dataframe that I want to merge back to a SQL table - not merge in the pandas sense, which would be a join, but a SQL merge operation to update/insert records into the table based on a comparison between the dataframe and the table.</p>
<p>There are a few work arounds I can see, such as writing the datafram... | <p>The concat function in pandas allows one to accomplish something similar to a merge.</p>
<p>I encountered a similar issue and was able to develop a function that "merges" two dataframes assuming a shared index. In my case, I turned a field "PrimaryKey" into the index for each dataframe and then m... | python|sql|sql-server|pandas | 1 |
364,786 | 61,726,904 | Weird exponential increase in running time when using dataframe.mean() (Pandas performance non-numeric column) | <p>I am playing around with a dataset of weather data (To reproduce; data can be found <a href="https://s3.amazonaws.com/keras-datasets/jena_climate_2009_2016.csv.zip" rel="nofollow noreferrer">here</a> unzip it and run the code below), and I wanted to normalize the data. To do this, I tried the second answer of this q... | <p>I did some tests, and it seems that the culprit, in this case, is "Date Time" - the non-numeric column. </p>
<p>First, when calculating the mean for different columns on their own, there's clearly no exponential behavior (see chart below - the X axis is the number of rows, the y-axis is time). <a href="https://i.st... | python|pandas | 5 |
364,787 | 61,645,449 | Calculate mean of data rows in dataframe with date-headers, dictated by a 'datetime'-column | <p>I have a dataframe with ID's of clients and their expenses for 2014-2018. What I want is to have the mean of the expenses per ID but only the years before a certain date can be taken into account when calculating the mean value (so column 'Date' dictates which columns can be taken into account for the mean).</p>
<p... | <p>Due to your naming convention, one need to extract the years from column names for comparison purpose. Then you can mask the data and taking mean:</p>
<pre><code># the years from columns
data = df.filter(like='y_')
data_years = data.columns.str.extract('(\d+)')[0].astype(int)
# the years from Date
years = pd.to_da... | python|pandas|datetime|mean | 1 |
364,788 | 61,894,789 | Is there a way to force pandas `to_numeric` to always return float64? | <p>I'm reading data from a file into a data frame using <code>pandas#read_csv</code>, using <code>pandas#to_numeric</code> as a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">converter</a> for one of the columns. I'd like this column to be always read... | <p>You can specify the dtype with <code>astype()</code>:</p>
<pre><code>df = pd.read_csv("foo.csv", converters={
"some_col": lambda x: pd.to_numeric(x).astype('float64'),
})
</code></pre>
<p>Which is somewhat equivalent to:</p>
<pre><code>df = pd.read_csv('foo.csv')
df['some_col'] = pd.to_numeric(df['some_col'])... | python|pandas | 1 |
364,789 | 61,890,845 | Obtain a view of a DataFrame using the loc method | <p>I am trying to obtain a view of a pandas dataframe using the <code>loc</code> method but it is not working as expected when I am modifying the original DataFrame.<br>
I want to extract a row/slice of a DataFrame using the <code>loc</code> method so that when a modification is done to the DataFrame, the slice reflect... | <p>The reason the slice didn't reflect the changes you made in the original dataframe is b/c you created the slice first.</p>
<p>When you create a slice, you create a "copy" of a slice of the data. You're not directly linking the two.</p>
<p>The short answer here is that you have two options 1) changed the or... | python|pandas|dataframe | 0 |
364,790 | 57,998,859 | Efficient boolean masking with Tensorflow SparseTensors | <p>So, I want to mask out entire rows of a <code>SparseTensor</code>. This would be easy to do with <code>tf.boolean_mask</code>, but there isn't an equivalent for <code>SparseTensor</code>s. Currently, something that is possible is for me to just go through all of the indices in <code>SparseTensor.indices</code> and f... | <p>You can do that like this:</p>
<pre><code>import tensorflow as tf
def boolean_mask_sparse_1d(sparse_tensor, mask, axis=0): # mask is assumed to be 1D
mask = tf.convert_to_tensor(mask)
ind = sparse_tensor.indices[:, axis]
mask_sp = tf.gather(mask, ind)
new_size = tf.math.count_nonzero(mask)
new... | python|tensorflow|sparse-matrix|tensorflow2.0 | 1 |
364,791 | 57,930,495 | LSTM after CNN how to feed in and what dimensions (input size)? | <p>I am trying to build a Convolutional Recurrent Network that takes a fixed input size of 32000 x 1 raw audio time series. It's just a numpy array of length 32000. So for example if we have a batch size of 1, my dimensions would be</p>
<pre><code>torch.size([1,32000,1])
</code></pre>
<p>1 audio time series, 32000 in... | <p>Adding an LSTM on top of the CNN here doesn’t make sense. You’ve already used the CNN to learn features based on the time dimension, so using an LSTM on top to try and learn the relationship over time of the CNN features that represent the relationship over time doesn’t make sense. </p>
<p>You use an LSTM on top of... | audio|deep-learning|conv-neural-network|pytorch|recurrent-neural-network | 0 |
364,792 | 58,023,526 | How can i move values from one column to another column row-wise? | <p>I have the following dataframe:</p>
<pre><code> preference Other
588 NaN goes to work with sister
461 NaN google
88 NaN ... | <p>You can sorting and assign to original first:</p>
<pre><code>df = df.sort_values(by = "Other", ascending = False)
</code></pre>
<p>And then reaasign values with selecting by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>DataFrame.ilo... | python|python-3.x|pandas|dataframe | 1 |
364,793 | 57,973,628 | Re-index pandas dataframe by union of two columns | <p>Probably a duplicate, but I'm not even sure what to search for.</p>
<p>If I have a pandas dataframe like so:</p>
<pre><code>index RH LH Data1 Data2 . . .
1 A1 A2 A B
2 B1 NaN C D
3 NaN C2 E F
</code></pre>
<p>And I want to re-index as so:</p>
<pre><code>index Data1 Data2
A1 ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with all columns without names defined in list and reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFr... | python|pandas | 2 |
364,794 | 58,076,140 | Multindex to one hot vector in pandas | <p>I have a multiindex dataframe like this</p>
<pre><code> bill
City Month
3 01 14586
02 14316
03 17261
04 16642
05 14977
06 14237
07 1448... | <p>First convert <code>MultiIndex</code> to columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>DataFrame.reset_index</code></a>, then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.ht... | python|pandas | 3 |
364,795 | 57,990,841 | "How to calculate difference in succesive time values in Python" | <p>I'am trying to calculate the difference between string time values but i could not read microseconds format. Why i have this type of errors ? and how i can fix my code for it ?</p>
<p>I have already tried "datetime.strptime" method to get string to time format then use pandas.dataframe.diff method to calculate the ... | <p>Just because your time format must include colons and point like this</p>
<pre><code>"%H:%M:%S.%f"
</code></pre> | python|excel|pandas|datetime | 0 |
364,796 | 58,054,367 | How do I find lowercase words in a DataFrame column that has NaNs? | <p>I have a dataframe column that has these values in one of its columns:</p>
<pre><code>Jerry
NaN
bill
Sol
</code></pre>
<p>I want to catch the all lowercase names, i.e., <code>bill</code>. But my code keeps getting stuck, I think on the <code>NaN</code>.</p>
<p>Here is my code:</p>
<pre class="lang-py prettyprint... | <p>We can using <code>str.islower</code></p>
<pre><code>df[df.name.str.islower().fillna(False)]
Out[243]:
name
2 bill
</code></pre> | python|pandas | 2 |
364,797 | 57,763,470 | pandas: get second row and put it at the end of first row (and automatically create new columns) | <p>I have a pandas df with multiple row entries and 3 column entries. Now i want to take every second row and append it at the row above. Therefore first I should create the 3 additional columns so that i have 6 column in total. But how does the row appending work?</p>
<p><a href="https://i.stack.imgur.com/NoVvX.png" ... | <p>So we can do it with <code>groupby</code> </p>
<pre><code>pd.DataFrame([y.values.ravel() for x , y in df.groupby(np.arange(len(df))//2)])
0 1 2 3 4 5
0 ab bc cd dd ac cc
1 aa cx yd dg as cs
</code></pre> | python|pandas|dataframe | 3 |
364,798 | 57,797,960 | Pandas - Create a DataFrame of Maximum Key-Value Pairs | <p>I have a Pandas DataFrame of key-value pairs for a collection of IDs. The columns in the DataFrame are (ID, Key, Value).</p>
<pre><code>data = {
"ID":{0:1,1:1,2:1,3:2,4:2,5:2,6:3,7:3,8:3,9:4,10:4,11:4},
"Key":{0:"A",1:"B",2:"B",3:"A",4:"B",5:"B",6:"A",7:"B",8:"B",9:"A",10:"B",11:"C"},
"Value":{0:28,1:94... | <p>Something like <code>pivot_table</code> </p>
<pre><code>data.pivot_table(index='ID',columns='Key',values='Value',aggfunc='max')
Out[22]:
Key A B C
ID
1 28.0 107.0 NaN
2 67.0 70.0 NaN
3 24.0 87.0 NaN
4 24.0 83.0 83.0
</code></pre> | pandas | 2 |
364,799 | 57,952,462 | How to reset MultiIndex? | <p>This is my <code>df</code>:</p>
<pre><code>id val1 val2 cnt
1 5 6 1
2 2 5 2
2 5 1 1
3 4 2 1
3 1 3 2
</code></pre>
<p>I run this code and get MultiIndex:</p>
<pre><code>df = df.pivot(index="id",
columns=... | <p>If need flatten <code>MultiIndex</code> in columns use <code>f-string</code>s in list comprehension:</p>
<pre><code>df = df.pivot(index="id",
columns="cnt",
values=["val1","val2"]) \
.fillna(0)
df.columns = [f'{a}_{b}' for a, b in df.columns]
df = df.reset_index()
print (df)
... | python|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.