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 |
|---|---|---|---|---|---|---|
10,400 | 41,092,098 | get pandas categorical column categories and assign them as a dtype to another column | <p>I'm creating an empty dataframe with a given shape and want to fill it with some values from another given dataframe that contains categorical columns, is it possible to share the same categorical dtype for the column in the new dataframe if it will have only a subset of original one's unique values?</p> | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cat.remove_unused_categories.html" rel="nofollow noreferrer">Series.cat.remove_unused_categories()</a> method.</p>
<p>Here is a small demo:</p>
<pre><code>In [311]: df
Out[311]:
channel day month t1 ... | pandas | 1 |
10,401 | 40,869,034 | Even though device is cpu, a gpu error occurs | <p>I am trying to run a net (convolution, highway, fc, rnn) which is too big for the GPU. Thus I am defining the device, globally, as "cpu". Still when executing the script, after building the model, when initializing the variables, the script throws a gpu error.</p>
<pre><code> with tf.Session() as sess:
with tf... | <p>The GPU version of TensorFlow will always attempt to initialize the GPU runtime (including devices and allocators) if one is available and, <a href="https://stackoverflow.com/a/40870101/3574081">as X3liF observes</a>, the error you are seeing comes from allocating host (i.e. CPU) memory that can be accessed more eff... | cuda|tensorflow | 4 |
10,402 | 38,084,794 | How to divide two groupby objects in pandas? | <p>I have the following code:</p>
<pre><code>import numpy as np
import pandas as pd
obs = pd.DataFrame({
'storm': [1, 1, 1, 1, 0, 0, 0, 0],
'lightning': [1, 1, 0, 0, 1, 1, 0, 0],
'thunder': [1, 0, 1, 0, 1, 0, 1, 0],
'p': [0.20, 0.05, 0.04, 0.36, 0.04, 0.01, 0.03, 0.27]
})
g1=obs.g... | <p><code>g2.unstack()</code> to get last level into columns. Then divide, broadcasting over columns. Then <code>stack</code> again.</p>
<pre><code>g2.unstack().div(g1.p, axis=0).stack()
</code></pre>
<p><a href="https://i.stack.imgur.com/Omc0L.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Omc0L.png" alt... | python|pandas|group-by | 9 |
10,403 | 65,974,443 | Encounter errors when install pandas inn graalpython | <p>When I compile <code>graalpython -m ginstall install pandas</code> or <code>graalpython -m ginstall install bumpy</code>
I got the following error, please comment how to fix the error. Thank you.</p>
<pre><code>line 54, in __init__
File "number.c", line 284, in array_power
File "ufunc_object.c&quo... | <p>I found that there are a lot of environment variables in ~/.bash_profile. I comment all of them and compile numpy/pandas successfully. By the way, how do I verify the settings of gcc/clang is correct? Anyway, thank you for your help.</p>
<pre><code>#export CC=/usr/local/Cellar/gcc/10.1.0/bin/gcc-10
#export CXX=/usr/... | pandas|numpy|graalvm|graalpython | 1 |
10,404 | 52,532,580 | Get the indices of the first and last rows and columns containing non-masked values in a numpy 2D array | <p>With a 2D masked array in Python, what would be the best way to get the index of the first and last rows and columns containing a non-masked value?</p>
<pre><code>import numpy as np
a = np.reshape(range(30), (6,5))
amask = np.array([[True, True, False, True, True],
[True, False, False, True, True]... | <p>Here's one <a href="https://stackoverflow.com/a/47269413/3293881">based on <code>argmax</code></a> -</p>
<pre><code># Get mask for any data along axis=0,1 separately
m0 = a.all(axis=0)
m1 = a.all(axis=1)
# Use argmax to get first and last non-zero indices along axis=0,1 separately
axis0_out = m1.argmax(), a.shape[... | python|arrays|numpy | 1 |
10,405 | 52,854,452 | Pandas, round - function | <p>Running the round - function on a pandas dataframe has no effect.</p>
<blockquote>
<ol>
<li>Why is that happening?</li>
<li>What would be the more general approach?</li>
</ol>
</blockquote>
<pre><code>import pandas as pd
df_round=pd.DataFrame({'index': {0: 0.0, 1: 2.563624, 2: 5.127248, 3: 0.0},
'time': {... | <p>For me in last pandas version <code>0.23.4</code> it working nice, alternative solution is use <code>dictionary</code>:</p>
<pre><code>df_round=df_round.round({'time':1,'ph_1':0,'ph_2':2})
print(df_round)
index time ph_1 ph_2 text
0 0.000000 10.3 8.0 17.95 foo
1 2.563624 20.5 13.0 7.69 bar
2 ... | pandas | 0 |
10,406 | 52,688,583 | Time series resampling to a weekly interval in pandas throws error | <p>I am exploring time series data (in python) and wanted to convert dates into weekly interval via pandas, but it throws the following error:</p>
<blockquote>
<p>TypeError: Only valid with DatetimeIndex, TimedeltaIndex or
PeriodIndex, but got an instance of 'RangeIndex'</p>
</blockquote>
<p>Data (dates.csv):</p>... | <p>First convert the <code>install_date</code> column to <code>datetime</code> datatype then use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>resample</code></a> using the desired rule:</p>
<pre><code>print(df)
install_date user m... | python|pandas | 0 |
10,407 | 46,570,493 | Multiply two numerical columns on conditional using Pandas | <p>I have pd dataframe (data) with three columns, X, Y and Z.</p>
<p>I need to run the following: </p>
<p>X * Y where Z = 'value'</p>
<p>I'm working along the lines of:</p>
<pre><code>data[data['Z'] == 'value',[data['X']*data['Y']]]
</code></pre>
<p>Now I know that this isn't correct, but I can smell the correct... | <p>IIUC:</p>
<pre><code>(df.X * df.Y).where(df.Z == 'Value')
</code></pre>
<p>or</p>
<pre><code>df[df.Z == 'Value'].eval('X * Y')
</code></pre>
<p>Examples:</p>
<pre><code>np.random.seed(123)
df = pd.DataFrame({'X':np.arange(10),'Y':np.arange(10),'Z':np.random.choice(['Value',np.nan],10)})
(df.X * df.Y).where(df.... | python|pandas|numpy | 9 |
10,408 | 58,180,372 | Subtracting rows from each other in dataframe | <p>I have what I assume is a fairly simple issue but just can't get the code correct for it to work. This is a simplified version of my dataframe.</p>
<pre><code>df = pd.DataFrame([['Jan', 'Apples', 10], ['Feb', 'Apples', 14],
['Jan', 'Oranges', 24], ['Feb', 'Oranges', 18]],
col... | <p>IICU, this is what you need. As the number of months increase, this will give the difference in sales between two months.</p>
<pre><code>df['dif']= df.groupby(['Fruit'])['Sales'].diff().fillna(0).astype(int)
print(df)
</code></pre>
<p><strong>Output</strong></p>
<pre><code> Month Fruit Sales dif
0 Jan ... | python|pandas | 0 |
10,409 | 58,546,419 | How to effectively manage multiple URL responses in python 3? | <p><strong>Background</strong>:</p>
<p>I have a script that runs analytics against a series of URL response objects (json). I do this by iterating over a dictionary containing the URLs, and then dynamically creating filenames and writing those files to disk, performing the analytics upon opening the files into memory... | <p>You can just append the responses to a list as you loop through.</p>
<pre><code>alljsonvariables=[]
for key, value in url_dict.items():
print("Issuing query for {}".format(key))
json_response = s.get(value, verify=cert_authority)
alljsonvariables.append(json_response.json())
#the rest of your code goes ... | python-3.x|pandas|python-requests|jupyter-notebook | 1 |
10,410 | 58,511,804 | How to invoke each function in a row in a pandas column by an argument at the respective index? | <p>I would like to call a different function in column B with a different row value in column A.</p>
<p>I am not sure how to do this in pandas, but I don't want to iterate through the rows - just combine the rows and get their respective values - similar to what I have tried below.</p>
<p>Can this be done?</p>
<p>Se... | <p>This is a very weird situation, but you can do:</p>
<pre><code>df.apply(lambda x: x['B'](x['A']), axis=1)
</code></pre>
<p>which essentially iterate through the rows, just looks better. Output:</p>
<pre><code>0 0
1 159
2 318
3 477
4 636
...
155 24645
156 24804
1... | python|pandas | 1 |
10,411 | 58,505,800 | Fastest way to convert 3D coordinates from string to float in a numpy array | <p>I have 3D coordinates (strings) in a list that I would like to convert to arrays of floats.</p>
<pre><code># current list
iPoints = ['-50.0651394154927,-5.3133315588409,0', '-48.7824404616692,3.1894817418136,0', '-46.2317402190515,11.3986203175639,0']
# ideal output
array([[-50.0651394154927,-5.3133315588409,0], [... | <p>The original solution is surprisingly fast but it can be done faster.
You can join the strings to one large buffer and process it with one call to <code>np.fromstring</code>.</p>
<p>Try following code:</p>
<pre><code># put everthing to a buffer as a large 1D-array separated with commas
buf = ','.join(iPoints)
# pa... | arrays|python-2.7|numpy|type-conversion | 1 |
10,412 | 60,857,607 | How to do Group by processing, Cumulative sums, and Previous row-Current row processing in Python? | <p>I have the following data:</p>
<pre><code>df1 = pd.DataFrame({'AIRPORT': ['ORD','ORD','ORD','ORD','ORD','DCA','DCA','DCA','DCA','DCA','DCA','DCA'],
'MONTH': [3,4,5,6,7,1,2,3,4,5,6,7],
'VOLUME': [200, 500, 600, 900, 400, 44, 55, 66, 77, 88, 99, 77],
'MULT':... | <pre><code>df = pd.DataFrame({'AIRPORT': ['ORD','ORD','ORD','ORD','ORD','DCA','DCA','DCA','DCA','DCA','DCA','DCA'],
'MONTH': [3,4,5,6,7,1,2,3,4,5,6,7],
'VOLUME': [200, 500, 600, 900, 400, 44, 55, 66, 77, 88, 99, 77],
'MULT': [2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 7, 8... | python|pandas|numpy | 0 |
10,413 | 60,794,565 | Append 2 Dataframes together only if a value from a column in df2 is in df1 | <p>I have two dataframes, 1 that is has a list of emails and the second has a list of attachments. I want to create a single dataframe with emails and attachments, however, not all attachments have a corresponding email and these attachments should be excluded from the final dataframe. </p>
<p>Each attachment can be m... | <p>I suggest checking out the Pandas user guide to learn more about how to merge, join and concatenate dataframes: <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html</a></p>
<p>As a rule of thumb,... | python|pandas|dataframe | 0 |
10,414 | 61,059,534 | Create a buffer in a dataframe based on multiple columns - Python | <p>I have a dataframe</p>
<pre><code>EGID Start_date End_Date Consumption Number_day
1 2019-01-01 2019-05-28 30 152
1 2019-06-05 2019-07-31 40 60
1 2019-08-01 2019-09-31 40 0
1 2019-02-11 2019-04-14 60 60
2 ... | <p>Try this, and if the results are not the desired please adjust the current question to include those cases aling with the desired result.</p>
<pre><code>import pandas as pd #import library
# i am assuming that your dataframe name is df
df = pd.DataFrame({'EGID':['1', '1', '1', '1', '2', '2', '3', '3', '3', '3'],
... | python|pandas|dataframe|date | 1 |
10,415 | 60,857,928 | Search a list in column in pandas and return a string value if found and return null if not | <p>I have</p>
<pre class="lang-py prettyprint-override"><code>['2013 (63 reg)', '76,869 miles', '2.0L','Manual', 'Diesel</li>\n</ul>']
['2011 (61 reg)', 'Estate', '2.0L', '135BHP','Manual', 'Diesel', '4 owners</li>\n</ul>']
['2011 (11 reg)', 'Saloon', '112,000 miles', '2.1L', '201BHP','Manual',... | <p>Well, you are using <code>nested</code> loop to check each <code>element</code> on each list. where you code is currently check if <code>miles</code> in the element and return it, if not so you are just appending <code>''</code> corresponding to elements without <code>miles</code>.</p>
<p>But your logic here is to ... | python|pandas|dataframe|search|arraylist | 1 |
10,416 | 71,638,950 | How to concatenate at least three 2-D array in python? | <p>I am doing goal-oriented image captioning. It has three modalities- features extracted, OCR component and object detection. The features extracted from ResNeXt model is reshaped into a tensor of size (49, 2048). The OCR and Object Detection components have a maximum of 20 and 10 words respectively, each of dimension... | <p>Illustrating <code>concatenate</code> with different <code>axis</code>:</p>
<pre><code>In [32]: alist = [np.ones((2,4),int)*i for i in range(1,4)]
In [33]: alist
Out[33]:
[array([[1, 1, 1, 1],
[1, 1, 1, 1]]),
array([[2, 2, 2, 2],
[2, 2, 2, 2]]),
array([[3, 3, 3, 3],
[3, 3, 3, 3]])]
In [34]... | python|numpy|deep-learning|encoding|pytorch | 0 |
10,417 | 69,976,541 | Adding missing data to Dataframe | <p>Hello I have a dataframe that looks like this</p>
<pre><code>Year month pop slope intercept
2020 2 10 5.8 -3.2
2020 3 15 5.8 -3.2
2020 4 17 5.8 -3.2
2020 9 50 5.8 -3.2
2021 1 5 8 -8.5
2021 5 ... | <p>You can try</p>
<pre><code>out = df.pivot('month','Year').reindex(range(1,12+1)).stack(dropna=False).reset_index()
</code></pre>
<p>And next step is to fill the <code>nan</code></p> | pandas|dataframe|interpolation | 2 |
10,418 | 69,800,568 | 'matrix' object has no attribute 'eigenvals' | <p>I have the following code</p>
<pre><code>import numpy as np
import sympy as sp
def bra(i,d):
arr = np.zeros((1,d))
if i <= (d-1):
arr[:,i] = 1
else:
print("Index Out of bounds")
return arr
def density(i,j,d):
return bra(i,d).T*bra(j,d)
SIGMA = (1/3)*(np.kron(np.kro... | <p>Usually, numpy and sympy don't mix well. Numpy can't work with sympy functions and symbols. Also, sympy tries to calculate exact symbolic solutions, which doesn't work well together with floats (sympy strongly prefers integers, rationals and symbolic expressions such as <code>sp.sqrt()</code>).</p>
<p>In this case, ... | python-3.x|numpy|matrix|sympy|eigenvalue | 2 |
10,419 | 69,969,482 | Why aren't Pandas operations in-place? | <p>Pandas operations usually create a copy of the original dataframe. <a href="https://stackoverflow.com/a/59242208/14656198">As some answers on SO point out</a>, even when using <code>inplace=True</code>, a lot of operations still create a copy to operate on.</p>
<p>Now, I think I'd be called a madman if I told my col... | <p>As evidenced <a href="https://pandas.pydata.org/docs/getting_started/overview.html#mutability-and-copying-of-data" rel="nofollow noreferrer">here</a> in the pandas documentation, <em>"... In general we like to favor immutability where sensible."</em> The Pandas project is in the camp of preferring immutabl... | python|pandas|in-place | 8 |
10,420 | 43,352,072 | Write concurrently in a numpy array | <p>I have a task to do on a lot of line of data (in a <code>pandas</code> <code>DataFrame</code>), but each computation is independent, thus I would like to parallelize it.</p>
<p>So I have a function taking a row and outputting an object (the ouput is actually an array containing a string and a set).</p>
<pre><code>... | <p>Ok,
I found another way, using a <code>Pool</code> object.</p>
<pre><code>from multiprocessing import Pool
def compute_row(row):
return some_function(row)
pool = Pool()
output = pool.map(compute_row, (row for i, row in db.iterrows()))
</code></pre> | python|arrays|numpy|concurrency|parallel-processing | 0 |
10,421 | 43,418,825 | OSError: cannot identify image file | <p>I am trying impelement code in pytorch but I get bellow error. my python version is 3.6 and my os is linux ubuntu 16.04 lts. I installed my linux alongside of mac os. We will use torchvision and torch.utils.data packages for loading the data.There are 75 validation images for each class.</p>
<pre class="lang-py pre... | <p>I guess the pictures or folder containing the pictures are created in MacOS while you are doing with pillow in Windows environment. Manually create folders (like 'train/ants') and copy the images to the new folders would solve it.</p> | classification|deep-learning|pytorch | 0 |
10,422 | 72,221,643 | How to read csv from ftp using pandas? | <p>I connected to a sftp and got a list of files successfully:</p>
<pre><code>ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
ssh.connect(Hostname, username=Username, password=Password)
ftp = ssh.open_sftp()
files = ftp.listdir()
dir_oi = "blah"
foi = ftp.listdir(dir_... | <p>I found this method worked</p>
<pre><code>with ftp.open(remote_file) as f:
df = pd.read_csv(f, sep = '\t', header = None)
</code></pre> | python|pandas|csv|sftp | -1 |
10,423 | 50,332,455 | Concatenate columns of dataframes in a loop Pandas | <p>I have a dataset of csv files with two columns: wavelengths and absorbance values.</p>
<p>I'd like to do some statistical analysis within a loop, which contains a set of files, e.g. a mean absorbance file with standard deviation etc.</p>
<pre><code>myfiles = sorted(glob.glob('blanks/Day01/Batch02/*.csv'))
mypath =... | <p>First create list of all DataFrames - filter columns by parameter <code>usecols</code> in <code>read_csv</code> and also is possible omit <code>delimiter=','</code> because default parameter:</p>
<pre><code>dfs = []
for m in range(len(files)):
df = pd.read_csv(mypath + files[m],
skiprows=1... | python|pandas | 3 |
10,424 | 50,634,310 | Encoding and saving multiple arrays in a for loop python | <p>I am preprocessing data for a deep neural network and I have variables that I need to one hot encode. So far, this is what I am doing and it is working fine. However, I was wondering if I could implement this in a for loop as that may be more efficient?</p>
<pre><code># Only Educational Establishment Type
X6 = X.dr... | <p>You're actually not updating the existing dataframes, in either version; you're just creating new dataframes.</p>
<p>The difference is that in the repetitive code, you're rebinding each of the variables <code>X</code>, <code>X1</code>, etc. to each of those new dataframes, while in your loop, you're rebinding <code... | python|arrays|numpy|for-loop|one-hot-encoding | 0 |
10,425 | 50,271,291 | TensorFlow installation denied due to user permissions | <p>I tried to run tensorflow on Jupiter netbook, python 2.7 but I realized it requiered 3.6 pythong version so I followed this steps :</p>
<p>Installing with Anaconda</p>
<p>Create a conda environment named tensorflow by invoking the following command:</p>
<pre><code>C:> conda create -n tensorflow pip python=3.5
... | <p><a href="https://stackoverflow.com/a/42989020/2091339">This answer</a> has the necessary information for the pip permission error. It can be resolved with the <code>--user</code> flag, which is a conservative approach.</p>
<p>There is another way to install tensorflow for <code>conda-environment</code>. Write below... | python-3.x|tensorflow|anaconda|junit-jupiter | 5 |
10,426 | 50,309,183 | Merge not behaving as expected in Pandas | <p>I am trying to compute zscores for a subset of the columns in my dataframe (<code>combo</code>) and then create new columns in that data frame for those zscores. Notice that when the zscores are pd.concat'ed the resultant new columns are all NaN. That's the problem I need help with.</p>
<p>I think it might have to ... | <p>It is expected behaviour, because <code>dropna</code> filter out all rows in subset with <code>NaN</code>s, so last <code>concat</code> add only filtered new rows and another values are converted to <code>NaN</code>s:</p>
<pre><code>combos = pd.DataFrame({'A':list('abcdef'),
'B':[np.nan,5,4,5,5,4... | pandas | 1 |
10,427 | 50,309,668 | The conversion from csv to binary format reduces the file size abnormally | <p>I have <code>csv</code> dataset of size <code>5.2</code>GB (Taken from <a href="https://archive.ics.uci.edu/ml/datasets/HEPMASS" rel="nofollow noreferrer">here</a>). It has about 7M rows of <code>dimension = 29</code>. The values are of type <code>float64</code>. I want to convert this dataset into a binary file. To... | <p>Ok, so I went and downloaded a sample of the data. Each row is something like:</p>
<pre><code>0.000000000000000000e+00,9.439358860254287720e-02,1.275558676570653915e-02 ...
</code></pre>
<p>Each individual number seems to have 25 character overall, and actually, 26 or so if you include the comma. So that's one byt... | python|python-3.x|pandas|numpy | 7 |
10,428 | 45,512,696 | For loop Pandas Series, once True print another value | <p>Trying to seek a value from a dataframe as the following: </p>
<pre><code>df = pd.DataFrame({'Price': [2,4,6,7,8],
'compare': [True, True, False, False, True]})
</code></pre>
<p>If the value in 'compare' is True, I want to print the number that corresponds in the same row but in the 'Price' colu... | <p>IIUC:</p>
<pre><code>In [42]: df.assign(prev_price=df.Price.shift(), next_price=df.Price.shift(-1))
Out[42]:
Price compare next_price prev_price
0 2 True 4.0 NaN
1 4 True 6.0 2.0
2 6 False 7.0 4.0
3 7 False 8.0 6... | python|pandas|series | 3 |
10,429 | 62,843,192 | Pandas column of lists: How to get the average, max length, and standard deviation of the list lengths of that column | <p>I have a pandas column containing lists of ints, which vary in length.</p>
<p>I am wondering how to get the max, average, and standard deviation of the length of those lists.</p>
<p>So far, I found this command</p>
<p><code>df['lists'].str.len()</code></p>
<p>Which seems to give the length for each row. Although I a... | <p>Yes, <code>df['lists'].str.len()</code> gives you lengths of lists in your series. To get the stats:</p>
<pre><code>df['lists'].str.len().agg(['mean','max','std'])
</code></pre> | python|pandas | 2 |
10,430 | 54,307,344 | Avoid duplicate random values | <p>Following <a href="http://sunny.today/generate-random-integers-with-fixed-sum/" rel="nofollow noreferrer">this post</a>, I can generate random integers with a fixed sum. However, I want to avoid any duplicate numbers (such as <code>20</code> in the following example):</p>
<pre><code>import numpy as np
_sum = 100
n... | <p><code>random.sample</code> returns a list of unique values (<a href="https://docs.python.org/3.3/library/random.html#random.sample" rel="nofollow noreferrer">see the docs</a>.) It's called like this:</p>
<pre><code>sample = random.sample(range(100), 5)
</code></pre>
<p>Edit: For using this to get fixed sum, I sugg... | python|python-2.7|numpy|random | 4 |
10,431 | 54,519,912 | Pandas dataframe to PostgreSQL table using psycopg2 without SQLAlchemy? | <p>I'd like to write a Pandas dataframe to PostgreSQL table <strong>without using SQLAlchemy</strong>.</p>
<p>The table name should correspond to the pandas variable name, or replace the table if already exists. Data types need to match as well.</p>
<p>I'd like to avoid SQLAlchemy's to_sql function for several reason... | <p>you can try but this code in your:</p>
<pre><code> cursor = conn.cursor()
cur.copy_from(df, schema , null='', sep=',', columns=(my_data))
</code></pre>
<p>reference code:
<a href="https://stackoverflow.com/questions/51522105/copy-dataframe-to-postgres-table-with-column-that-has-defalut-value">copy dataframe to ... | python|postgresql|pandas|dataframe|psycopg2 | 2 |
10,432 | 54,283,697 | I'm trying to convert a 3D list from 2D list in Python 3 | <p>I could not find anything that works for the type of list I am trying to convert. The 2d list is </p>
<pre><code>[[2,3,4],[5,6,7],[8,9,10],[11,12,13]]
</code></pre>
<p>and i need a list like </p>
<pre><code>[[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]
</code></pre>
<p>I have tried all of these but it does not work.... | <p>How about first casting your list to arrays and find out the shapes you wanted and then reshaping accordingly ?</p>
<pre><code>In [2]: lol = [[2,3,4],[5,6,7],[8,9,10],[11,12,13]]
In [3]: lol_arr = np.array(lol)
In [4]: lol3 = [[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]
In [5]: lol3_arr = np.array(lol3)
In [6]... | python|arrays|list|numpy|multidimensional-array | 1 |
10,433 | 54,484,797 | Numpy IndexError: tuple index out of range | <p>I'm trying to run my code using python 2.7, and OpenCV 3.3, but I`m running into the following error:</p>
<blockquote>
<p>Traceback (most recent call last): File "CameraTest.py",
line 52, in
height = np.size(Frame,0) File "/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line
2700, in s... | <p>You are always setting <code>Frame</code> to 0</p>
<pre><code>(grabbed, Frame) = camera.read(), 0
</code></pre>
<p><code>grabbed</code> gets output of <code>camera.read()</code> and <code>Frame</code> gets 0. For and <code>int</code>, <code>np.size</code> returns 1.</p> | python|numpy|raspberry-pi3|raspbian|index-error | 0 |
10,434 | 73,792,219 | pandas isn't recognising my datetime column | <p>I exported this from a postgres table as a tab-separated csv, like so:</p>
<pre class="lang-sql prettyprint-override"><code>\copy (select * from mytable) to 'labels.csv' csv DELIMITER E'\t' header
</code></pre>
<p>Which is (file head)</p>
<pre class="lang-py prettyprint-override"><code>user_id session_id start_ti... | <p>See the docs for <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>pd.read_csv</code></a>:</p>
<blockquote>
<p><strong><code>parse_dates</code></strong> : <em><strong>bool or list of int or names or list of lists or dict, default False</strong></em></p>
<p>..... | python|pandas|csv | 3 |
10,435 | 71,127,153 | Python -> csv to Dictionary -> | <p>I have this CSV (file):</p>
<pre><code>uid,aabreo
objectClass,top
objectClass,inetOrgPerson
objectClass,UnabPerson
cn,Angela Abreo Garcia
sn,Abreo Garcia
administrativo,no
AdmPortales,no
AdmSisInformacion,no
uid,aabreo265
objectClass,top
objectClass,inetOrgPerson
objectClass,UnabPerson
cn,ANDRES FELIPE ABREO SERRAN... | <p>Your initial file is not a csv file. In a csv file, a record should be contained in one single row, while in you file a record only ends on an empty line. Using pandas csv to process it is close to using a hammer to drive a screw: if the hammer is heavy enough, the screw will end into the board yet it is not the rig... | python|pandas|csv | 1 |
10,436 | 52,425,332 | Merge pandas groupBy objects | <p>I have a huge dataset of 292 million rows (6GB) in CSV format. Panda's <code>read_csv</code> function is not working for such big file. So I am reading data in small chunks (10 million rows) iteratively using this code : </p>
<pre><code>for chunk in pd.read_csv('hugeData.csv', chunksize=10**7):
#something ..... | <p>You can use <code>pd.concat</code> to join groupby results and then apply <code>sum</code>:</p>
<pre><code>>>> pd.concat([xd0,xd1],axis=1)
export export
origin dest year
aus ind 2000 6 6
2001 8 8
chn aus 2001 40 40
ind... | python|pandas|performance|bigdata|pandas-groupby | 4 |
10,437 | 60,416,907 | TypeError: can't multiply sequence by non-int type of 'tuple' in pytorch | <p>The code as below:</p>
<pre><code>class L2Norm(nn.Module):
def __init__(self):
super(L2Norm, self).__init__()
self.eps = 1e-10
def forward(self, x):
norm = torch.sqrt(torch.sum(x * x, dim = 1) + self.eps)
x = x / norm.unsqueeze(-1).expand_as(x)
return x
</code></pre>
... | <p><code>x</code> is a tuple of two tensors, as shown in your output. <code>x * x</code> would require a way to multiply two tuples. </p>
<p>If I simply define <code>x</code> as a tuple of ints, e.g. <code>x=(1, 1)</code>, and tried the same code: <code>x * x</code>, I get the same error:</p>
<pre><code>>>> ... | python|pytorch | 1 |
10,438 | 60,376,405 | Pandas: grab positions in dataframe which indexes are listed in another dataframe | <p>Suppose that I have 2 dataframes, with indexes populated so that elements in columns are unique, because in real data they are:</p>
<pre><code>vals = pd.DataFrame(np.random.randint(0,10,(10, 3)), columns=list('ABC'))
indexes = pd.DataFrame(np.argsort(np.random.randint(0,10,(10, 3)), axis=0)[:5], columns=list('ABC')... | <p>use <code>.loc</code> within a loop to replace non existing index with nan</p>
<pre><code>for i in vals.columns:
vals.loc[vals[i].isin(list(indexes[i].unique())),i]=np.nan
print(vals)
</code></pre>
<pre><code> A B C
0 NaN 2.0 NaN
1 NaN 5.0 NaN
2 2.0 3.0 NaN
3 NaN NaN NaN
4 NaN NaN 6.0
... | python|pandas | 2 |
10,439 | 60,478,810 | pandas groupby where and else | <p>I have a dataframe like this:</p>
<pre><code> col1 col2
0 a 100
1 a 200
2 a 150
3 b 1000
4 c 400
5 c 200
</code></pre>
<p>what I want to do is group by col1 and count the number of occurrences and if count is equal or greater than 2, then calculate mean of col2 for those rows and i... | <p>I'm not sure this is what you need, but you can resolve to <code>apply</code>:</p>
<pre><code>def aggregator(x):
if len(x)==1:
return pd.Series( (x['col1'] + x['col2'].astype(str)).values)
else: return pd.Series(x['col2'].mean())
df.groupby('col1').apply(aggregator)
</code></pre>
<p>Output:</p>
<... | python|pandas|group-by|where-clause | 0 |
10,440 | 60,602,630 | Partial keyword match not working when I am trying to create a new column from a pandas data frame in python? | <p>I have a data frame Description as mentioned below </p>
<pre><code> Description
</code></pre>
<p>I am trying to do a keyword search on the description column and I have list of keywords as a list .</p>
<p>My current code checks only exact matches not partial matches.If there are multiple keywords present in ... | <p><code>extractall</code> will do the job, but you must first build the pattern:</p>
<pre><code>...
keywords_lower = [item.lower() for item in keywords]
pattern = '(' + '|'.join('(?:' + i + ')' for i in keywords_lower) + ')'
df['Keyword'] = df['Description'].str.extractall(pattern, re.I).groupby(level=0).agg('/'.join... | python|regex|pandas|dataframe|nltk | 0 |
10,441 | 60,481,343 | Numpy sum over repeated entries in index array | <p>Given numpy ndarray <code>A</code> and an integer array <code>I</code>, of the same shape, with highest value <code>imax</code> and an array <code>B = np.zeros(imax)</code> we can do <code>B[I] = A</code>. However if <code>I</code> has repeated entries the last assignment holds. I need to do this while summing over ... | <pre><code>In [1]: A = np.array((1,2,5,9))
...: I = np.array((0,1,2,0),dtype=int)
...: B = np.zeros(3)
...: B[I] += A
In [2]: B ... | python|arrays|numpy|indexing|sum | 4 |
10,442 | 72,778,033 | Pandas merge_asof Question: one-to-multiple merge | <p>I am trying to merge two dataframes by nearest time point.
I tried <code>merge_asof</code>. However, the issue is two entries have the same time point, then
<code>merge_asof</code> will only merge one entry into the final dataframe.</p>
<p>Here is an example:</p>
<p>df_A:</p>
<pre><code> time ticker price
0... | <p>You need to perform a double <code>merge</code>, first with the <code>merge_asof</code>, then a classical <code>merge</code>. The trick is to identify the duplicates in the asof merged right DataFrame:</p>
<pre><code>df_B2 = df_B.assign(idx=df_B.groupby('time').ngroup())
out = (pd
.merge_asof(df_A, df_B2, on='time... | python|pandas|dataframe|merge | 1 |
10,443 | 72,531,611 | How to setup CMake project to use PyTorch C++ API installed via Conda | <p>I have Miniconda3 on a Linux system (Ubuntu 22.04). The environment has Python 3.10 as well as a functioning (in Python) installation of PyTorch (installed following official instructions).</p>
<p>I would like to setup a CMake project that uses PyTorch C++ API. The reason is not important and also I am aware that it... | <p>As an alternative to using <code>conda</code>, I would suggest to just grab the pre-built library using the link <a href="https://download.pytorch.org/libtorch/nightly/cpu/libtorch-shared-with-deps-latest.zip" rel="nofollow noreferrer">https://download.pytorch.org/libtorch/nightly/cpu/libtorch-shared-with-deps-lates... | c++|cmake|pytorch|conda | 1 |
10,444 | 59,536,352 | append to nested NumPy arrays | <p>I have a list of NumPy arrays:</p>
<pre class="lang-py prettyprint-override"><code>self.xy_lat_lon_list = [array([3986139.12431615, 3889959.08475953]),
array([3987252.31922408, 3889959.08475953]),
array([3988365.51413201, 3889959.08475953]),
ar... | <p>making your list:</p>
<pre><code>In [107]: alist = [np.array([3986139.12431615, 3889959.08475953]),
...: np.array([3987252.31922408, 3889959.08475953])
...: ,
...: np.array([3988365.51413201, 3889959.08475953])
...: ,
...: ... | python|arrays|numpy|nested | 1 |
10,445 | 59,631,423 | How to swap elements in different list and different size Pandas? | <p>I have a dataframe df1. The dataframe has one column named 'Path'. Each row has a list. They are like this:</p>
<pre><code>Path
____________________
[OAK, PHX, MIA, FLL, PBG]
[OAK, SEA, FLL, PBG]
[OAK, LAS, ORD, FLL, PBG]
[OAK, DFW, FLL, PBG]
...
</code></pre>
<p>I wish to swap the <str... | <pre><code>out = df['Path'].apply(lambda x : pd.Series(x) )
dfLength = len(df)
if dfLength%2==0:
oddIndex = list(range(0,dfLength-1, 2))
evenIndex = list(range(1, dfLength,2))
else:
oddIndex = list(range(0,dfLength, 2))
evenIndex = list(range(1, dfLength,2))
#Swapping odd-even rows
oddData = out.iloc... | python-3.x|pandas|list|dataframe|swap | 0 |
10,446 | 59,678,718 | Restore binary data with numpy fromfile that has been saved with numpy save | <p>I have a huge 3D-array (float16) that was stored to disk using <code>numpy.save</code>. When I load it, it floods my memory, so I need to read it in chunks and process the data step by step. But it seems that the data is read in a different order of dimensions than it had been saved. I prepared the following simple ... | <pre><code>In [103]: myArray = np.zeros((2, 5, 3))
...: content = np.arange(0,10).reshape((2, 5))
...: myArray[:,:,0] = content
...: myArray[:,:,1] = content*10
...: myArray[:,:,2] = content*100
...: ... | python|numpy|binaryfiles | 1 |
10,447 | 32,245,035 | How to represent a data structure like this in python pandas? | <p>Somehow I can't figure out what would be the best/most convenient representation of my data in python pandas. </p>
<p>In principle the data is structured like this:</p>
<pre><code> | Group1 | | Group2 | ...
x y z prop1 prop2 prop3 prop1 prop2 prop3
0 o o o ... | <pre><code>df = pd.DataFrame(np.arange(27).reshape(3,9) ,
columns = [
['x' , 'y' , 'z' , 'Group1' , 'Group1' , 'Group1' , 'Group2' , 'Group2' , 'Group2'] ,
[ 'x' , 'y' , 'z' , 'prop1' , 'prop2' , 'prop3' , 'prop1' , 'prop2' , 'prop3']
]
)
df['Group1']['prop1']
# 0 3
# 1 12
# 2 21
</cod... | python-2.7|pandas | 0 |
10,448 | 32,378,777 | Combining two datasets to form a boolean column (pandas) | <p>I have two <code>DataFrames</code> in <code>pandas</code>:</p>
<p>dfm_one</p>
<pre><code> data group_a group_b
0 3 a z
1 1 a z
2 2 b x
3 0 b x
4 0 b x
5 1 b z
6 0 c x
7 0 c y
8 3 c z
9 3 c z
</code></pre>
<p>dfm_two</p>
<pre><code> data grou... | <p>OK this is a slight hack, if we cast the df to <code>str</code> dtype then we can call <code>sum</code> to concatenate the rows into a string, we can use the resultant string as a kind of unique identifier and then call <code>isin</code> on the other df, again converting to a <code>str</code>:</p>
<pre><code>In [91... | python|pandas | 1 |
10,449 | 40,471,198 | Using scipy.stats.chisquare with masked arrays | <p>I need to calculate the chi-squared fit to a set of arrays (<code>observed</code> and <code>expected</code>). The arrays are the same size, but some of the elements of <code>expected</code> are <code>None</code> because I don't know the expected value. </p>
<p>I would like to use the <code>scipy.stats.chisquare</co... | <p>While it seems logical that <code>numpy.ma.masked_where(expected == None, expected)</code> would in fact mask <code>expected</code> where <code>None</code> occurs, <code>numpy.ma</code> does not recognize <code>None</code> as comparable to <code>expected</code>, so <code>None</code> must be cast to an <code>np.array... | python|arrays|numpy|scipy|chi-squared | 1 |
10,450 | 58,012,178 | Resolving pytorch distributed execution printing multiple log statements for each process spawned? | <p>I am running pytorch distributed environment to train some models and in the same script I am also using logging to print status of the program. The problem is that with pytorch distributed since its spawning multiple processes I see my log statements being printed <code>n</code> times where <code>n</code> is the nu... | <p>You can choose to use NVIDIA pytorch scripts, it's optimized, which means it runs fast and print log normally.
here is the link:
<a href="https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch" rel="nofollow noreferrer">https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch</a></p> | multiprocessing|pytorch|distributed-computing|distributed | -2 |
10,451 | 54,846,398 | Make a custom loss function for mean intersection of union for regression in bounding boxes | <p>I am trying to iterate over the batch one by one to calculate the mean intersection over union. but fit function showing this </p>
<blockquote>
<p><strong>Error</strong>: An operation has <code>None</code> for the gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). C... | <p>It means that all operations inside your custom loss function should be differentiable since otherwise the optimization procedure cannot be executed. To that end, you just need to check one by one which operation is a culprit in your code and substitute it with a Keras differentiable backend analogue or to find some... | python-3.x|tensorflow|machine-learning|keras|conv-neural-network | 0 |
10,452 | 54,945,043 | Python String representation of numpy array | <p>Iam trying to get a FULL string representation of an 2D float32 512x512 array. I can either use numpys <code>string2array(array)</code> or <code>repr(array)</code>. But the problem is that I always get a shortened output like that:</p>
<pre><code> '...[2.0886018e-04 1.7029114e-04 2.8904244e-05 ... 4.1985390e-06
1... | <p>The answer is that numpy array2string has a threshold option which can be set to np.inf. Then a full representation is possible! :)</p> | python|arrays|string|numpy | 0 |
10,453 | 73,299,816 | modifying numpy ndarray by index | <p>I'm stuck on trying to add values to the numbers column.</p>
<pre><code>import pandas as pd
def twod_array(num):
data = {"group": [-1, 0, 1, 2],
'numbers': [[2], [14, 15], [16, 17], [19, 20, 21]],
}
df = pd.DataFrame(data=data)
print(df)
return 0
</code></pre>
<p>C... | <pre><code>num = 14.5
mask = (df.numbers.apply(min).lt(num) &
df.numbers.apply(max).gt(num))
index = mask[mask].index[0]
df.numbers.at[index].append(num)
df.numbers.at[index].sort()
print(df)
# Output:
group numbers
0 -1 [2]
1 0 [14, 14.5, 15]
2 1 [16, 17]
3 ... | python|arrays|pandas|numpy|insert | 1 |
10,454 | 73,187,537 | Python dataframe from 2 text files (different number of columns) | <p>I need to make a dataframe from two txt files.</p>
<p>The first txt file looks like this <strong>Street_name <em>space</em> id</strong>.
The second txt file loks like this <strong>City_name <em>space</em> id</strong>.</p>
<p>Example:</p>
<p><strong>text file 1:</strong></p>
<pre><code>Roseberry st 1234
Brooklyn st 4... | <p>There's nothing that I'm aware of in pandas that does this automatically.
Below, I built a script that will merge those addresses (addy + st) into a single column, then merges the two data frames into one based on the "id".</p>
<p>I assume your actual text files are significantly larger, so assuming they f... | python|pandas|merge | 0 |
10,455 | 73,405,718 | How to install pandas and numpy on Apple M2 | <p>Running code that worked well on my 2019 Mac book air, I face issues with my new M2 Mac book pro. The problem is related to Numpy and Pandas. How can I get them to work on M2.</p>
<p>The error code is</p>
<p>Traceback (most recent call last):
File "/Users/wolfgangseidel/Documents/HF_Project/Hike_Radar.py",... | <p>I would not recommend using the MacOS built in Python framework. Try to install the Python environment using homebrew.</p> | python|pandas|numpy | 0 |
10,456 | 34,911,276 | Cannot gather gradients for GradientDescentOptimizer in TensorFlow | <p>I've been trying to gather the gradient steps for each step of the GradientDescentOptimizer within TensorFlow, however I keep running into a TypeError when I try to pass the result of <code>apply_gradients()</code> to <code>sess.run()</code>. The code I'm trying to run is:</p>
<pre><code>import tensorflow as tf
fro... | <p>The <a href="https://www.tensorflow.org/versions/master/api_docs/python/train.html#Optimizer.compute_gradients"><code>Optimizer.compute_gradients()</code></a> method returns a list of (<code>Tensor</code>, <code>Variable</code>) pairs, where each tensor is the gradient with respect to the corresponding variable.</p>... | python|tensorflow | 11 |
10,457 | 35,168,076 | Select all possible subarrays of length n | <p>How can a get a 2D array containing all possible consecutive sub-arrays of a certain length?</p>
<p>For example, say my array was <code>['a', 'b', 'c', 'd', 'e']</code>, and n was 3, the result should be</p>
<pre><code>[['a', 'b', 'c']
['b', 'c', 'd']
['c', 'd', 'e']]
</code></pre>
<p>I found a <a href="https:/... | <p>Third and final no-loop answer:</p>
<pre><code>def substrings(n, x)
return numpy.fromfunction(lambda i, j: x[i + j], (len(x) - n + 1, n),
dtype=int)
</code></pre>
<p>You'll have to profile all of these solutions yourself to find the one that's most performant. If you like one of thes... | python|arrays|numpy | 2 |
10,458 | 34,984,985 | Merging multiple pandas datasets with non-unique index | <p>I have several similarly structured pandas dataframes stored in a dictionary. I access a dataframe in the following way.</p>
<pre><code>ex_dict[df1]
date df1price1 df1price2
10-20-2015 100 150
10-21-2015 90 100
</code></pre>
<p>I want to merge all of these dataframes into one data... | <p>You can use a <code>concat</code> followed by a <code>groupby('date')</code> to flatten the result.</p>
<pre><code>In [22]: pd.concat([df1,df2,df3]).groupby('date').max()
Out[22]:
df1price1 df1price2 df2price1 df2price2 df3price1 df3price2
date
10-20-2015 100 150 110 140... | python|pandas|merge|concat | 1 |
10,459 | 34,893,080 | Apply (map) function to CERTAIN Pandas dataframe elements | <p>I'm trying to apply a time discounting function on only the datetime cells in the following dataframe. The first column has a user ID and scattered through the rest of the dataframe are pandas date time entries. </p>
<p><a href="https://i.stack.imgur.com/9ES06.png" rel="nofollow noreferrer"><img src="https://i.stac... | <p>You should try applying your function only to not-null elements, like so :</p>
<pre><code>h.apply(lambda x: my_func(x) if(np.all(pd.notnull(x[1]))) else x, axis = 1)
</code></pre> | python|python-2.7|pandas|dataframe|map-function | 1 |
10,460 | 30,940,421 | Pandas split a column value to new column if list | <p>I am still learning pandas and have a pandas dataframe with 2 columns as shown below:</p>
<pre><code>actual label pred label
0 -1
0 -1
1 [1, 0.34496911461303364]
1 -1
</code></pre>
<p>What I would like to accomplish is ... | <p>Here's one way to achieve it</p>
<pre><code>In [74]: df
Out[74]:
actual label pred label
0 0 -1
1 0 -1
2 1 [1, 0.344]
3 1 -1
</code></pre>
<p>Using <code>apply</code> check if value is list <code>isinstance(x,list)</code> and take the value... | python|pandas | 2 |
10,461 | 67,244,669 | In Pandas, how to merge multiple CSV files with a unnamed date index | <p>I have a bunch of file all having the same format, note the first column does not have a name.</p>
<pre><code> USD_EUR USD_JPY USD_GBP USD_AUD USD_CAD USD_CHF USD_HKD
1/1/2000 0.995421063 102.2596058 0.618853275 1.535138364 1.454111089 1.597750348 7.767569182
1/2/2000 0.995421063 102.2596058 0.618853275... | <p>Suppose that all your files are in <code>root_folder</code>, you can get a <code>DataFrame</code> with the content of all your files and sorted by date in this way:</p>
<pre class="lang-py prettyprint-override"><code>import os
import pandas as pd
df = pd.concat([
pd.read_csv(os.path.join(root_folder, filename),... | python|pandas | 0 |
10,462 | 34,733,291 | reclassify a numpy array in python between a range | <p>I have an numpy array in Python and i need to classify between a range of value (>= 2 to < 5 = 100). I got an error message and I don't understand the use of <code>a.any() or a.all()</code></p>
<pre><code> import numpy as np
myarray = np.array([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]])
myarray[myarray >... | <p>You were so close.</p>
<pre><code>>>> myarray[(myarray >= 2) & (myarray < 5)] = 100
>>> myarray
array([[ 1, 100, 100, 100, 5],
[ 1, 100, 100, 100, 5],
[ 1, 100, 100, 100, 5]])
</code></pre> | python|arrays|numpy | 7 |
10,463 | 60,197,113 | pandas calculate delta time | <p>Here's some code where that will generate some random data, and chart plus lines representing 30th & 90th percentiles.</p>
<pre><code>import pandas as pd
import numpy as np
from numpy.random import randint
import matplotlib.pyplot as plt ... | <pre><code>minStart = df.loc[df['Random_Number'] < df.quantile(0.3)[0]].index[0]
maxStart = df.loc[df['Random_Number'] > df.quantile(0.90)[0]].index[0]
hours = maxStart - minStart
hours
</code></pre>
<p>df.quantile doesn't return a number so you need to get the first entry of it</p> | python|pandas|data-science | 0 |
10,464 | 65,403,673 | indexing pandas data frame with multiindex | <p>I have a data frame like this with multi index:</p>
<p><a href="https://i.stack.imgur.com/Vq3bx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vq3bx.jpg" alt="enter image description here" /></a></p>
<p>I have the following multiindex:</p>
<pre><code>MultiIndex([('2019-09', 1617),
('2... | <p>If you want to use partial indexing to get all elements with <code>2020-02</code> in the first <code>createdAt_ym</code> level, you should be using this syntax:</p>
<pre class="lang-py prettyprint-override"><code>df.loc['2020-02']
</code></pre> | pandas|multi-index | 0 |
10,465 | 49,862,092 | Pandas subtract series by iloc, not by index | <p>I have two <code>pd.Series</code>:</p>
<pre><code>>>> a = pd.Series([1,2,3],index=[1,2,3])
>>> b = pd.Series([2,3,4],index=[2,3,4])
</code></pre>
<p>I would like to subtract these two series according to the elements' <code>.iloc</code>, not the index, and then get back the index of the first (or... | <p>You can do this via accessing <code>numpy</code> array representation:</p>
<pre><code>res = pd.Series(a.values - b.values, index=a.index)
print(res)
# 1 -1
# 2 -1
# 3 -1
# dtype: int64
</code></pre> | python|pandas | 3 |
10,466 | 63,859,402 | Out of Sample Forecasting using Neural Network in Keras (Python) | <p>I am doing a time series forecasting exercise using the window method but i am struggling to understand how to do the forecast out of sample.
Here is the code:</p>
<pre><code>def windowed_dataset(series, window_size, batch_size, shuffle_buffer):
dataset = tf.data.Dataset.from_tensor_slices(series)
dataset = data... | <p>The for loop is returning the predictions in order, whereas if you call model.predict(dataset_validation) you'll get the predictions in a shuffled order (assumed you shuffled the dataset).</p>
<p>As for the point of using datasets - it can just help with code organization. There is no need to ever use one if you don... | python-3.x|tensorflow|keras|neural-network|forecasting | 3 |
10,467 | 64,057,516 | select top 2 rows every 5 rows in pandas | <p>I want to select top two rows every 5 rows in pandas dataframe. How could I do this?</p>
<p>Consider the following dataframe:</p>
<pre><code>col1 | col2 | col3
1 | 1 | 1
2. | 2. | 2
3. | 3. | 3
4 | 4 | 4
5. | 5. | 5
6. | 6. | 6
7. | 7. | 7
</code></pre>
<p>I would like to ... | <p>Use floor division on the index and <code>groupby</code> on it with <code>head</code>:</p>
<pre><code>df.groupby(df.index//5).head(2)
</code></pre> | python|pandas | 7 |
10,468 | 46,971,307 | How to merge two pandas dataframe with left join when both dataframe contains duplicate keys? | <p>I have two Python Pandas Dataframe like below:</p>
<pre><code>left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K1', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K0', 'K0', 'K0', 'K1'],
'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6'],
'B': ['B0', 'B... | <p>Unfortunately, your question does not describe what you want to achieve in a way that it could become useful to anyone with a similar problem. </p>
<p>Indeed, you wanted to obtain a <strong>sorted merge for repeated merging keys</strong>.</p>
<p>The logical way to proceed is <a href="https://stackoverflow.com/ques... | python|pandas|merge|left-join | 1 |
10,469 | 46,675,627 | reading and executing sql queries into pandas data frame | <p>I have a long-assed sql query that runs quite well in Python, into a data frame
but I have hundreds of them, so I tried creating a function that reads my files and executes them.
The sql statements look like this:</p>
<pre><code>"SELECT IIf(Left([Milestone_Next_Expected],4)='Proc',1, \
....\
120 lines
....\
dbo.... | <p>The correct method is:
1. the sql script script does not require any line continuation symbols, "\"
and does not need to be encased in quotes
2. The correct way to read the input file is:</p>
<pre><code>file=open(filename,'r')
SQLfile = s = " ".join(file.readlines())
</code></pre>
<p>Now, when the code is exec... | python|sql|pandas | 0 |
10,470 | 46,678,142 | How to remove the multiindex from GroupBy.apply()? | <p>Based off <a href="https://stackoverflow.com/q/46677822/4909087">this question</a>.</p>
<blockquote>
<pre><code>df = pandas.DataFrame([[2001, "Jack", 77], [2005, "Jack", 44], [2001, "Jill", 93]],columns=['Year','Name','Value'])
Year Name Value
0 2001 Jack 77
1 2005 Jack 44
2 2001 Jil... | <p>IIUC, use <code>group_keys=False</code>:</p>
<pre><code>df.groupby('Name', group_keys=False).apply(lambda x: x.sort_values('Value').head(1))
</code></pre>
<p>Output:</p>
<pre><code> Year Name Value
1 2005 Jack 44
2 2001 Jill 93
</code></pre> | python|pandas|dataframe|multi-index | 17 |
10,471 | 32,827,998 | Pandas: Change dates in dataframe to same date format | <p>I have a dataframe that contains a column which holds: </p>
<pre><code>Date:
31MAR2005
30-06-05
311205
</code></pre>
<p>I would like to convert these dates to the format : 30-06-05 (DD-MM-JJ). What is the simplest way to do this? The fields are not in a date format yet, only strings.</p> | <p>Here is my example :</p>
<pre><code>def string_to_date(my_string):
if '-' in my_string:
return datetime.datetime.strptime(my_string, '%d-%m-%y')
elif my_string.isdigit():
return datetime.datetime.strptime(my_string, '%d%m%y')
elif my_string.isalnum():
return datetime.datetime.str... | python|pandas | 3 |
10,472 | 63,165,903 | How to halt process only when something like "No Internet" or "Network Error" occurs while downloading images using requests | <p>I have written a script to download and save the images in a directory from the urls provided. It uses the <code>requests</code> to access the URL given in a <code>DataFrame</code> (CSV file) and download the images in my directory using <code>PILLOW</code>. NAme of the image is the index number of that url in my CS... | <p>Better than sleep is to use exponential backoff.</p>
<pre><code>from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
retry_strategy = Retry(
total=3,
status_forcelist=[429, 500, 502, 503, 504],
method_whitelist=["HEAD", "GET", "OPTIONS... | python|pandas|python-requests|python-imaging-library|urllib | 1 |
10,473 | 63,101,261 | Find unique values for all the columns of a dataframe | <p>How can i get the unique values of all the column in a dataframe ?
I am trying to do something like below as of now.</p>
<pre><code>for col in train_features_df.columns:
print(train_features_df.col.unique())
</code></pre>
<p>But this gives me the error <code>AttributeError: 'DataFrame' object has no attribute 'c... | <p>You can apply <code>unique</code> on each series by transposing like,</p>
<pre><code>>>> df
A B C
0 1 4 7
1 1 5 7
2 3 6 7
>>> df.T.apply(lambda x: x.unique(), axis=1)
A [1, 3]
B [4, 5, 6]
C [7]
dtype: object
>>>
</code></pre> | python|pandas|dataframe | 4 |
10,474 | 67,852,096 | accessing an element in a numpy matrix using a list (python) | <p>I have a 10x10 numpy matrix and I have a list containing indices of elements I want to query.</p>
<p><code>matrix = np.zeros((10, 10), dtype=int)</code></p>
<p><code>indices = [[2,3], [3,4]]</code></p>
<p>the issue I'm facing is, what I actually want is the element <code>matrix[2,3]</code> but <code>matrix[indices[0... | <p>I ended up finding a solution.</p>
<p>storing the indices as tuples inside of a list works</p>
<p><code>indices = [(2,3), (3,4)]</code> and then <code>matrix[indices[0]]</code> gives the desired output</p> | python|numpy | 1 |
10,475 | 67,909,418 | Python pandas filter data by groupby second level values | <p>I have a groupby object with two groups (Time & Region). I need to plot the values of each region by time. Before plotting I figured I would create a dataframe of each region but I'm having trouble extracting all of the Times for a specific region - for example filter out all regions except for those with a va... | <p>Looks like the solution is to filter the data before grouping:</p>
<pre><code>df[df.region==2].groupby('time').mean()
</code></pre> | python|pandas|group-by | 0 |
10,476 | 32,074,753 | How to install OpenCV for Python 3.x on Windows 8.1? | <p>I am trying to install and run OpenCV 3.0.0 for python 3.4.2, in Windows 8.1.</p>
<ol>
<li>I have downloaded the OpenCV file from <a href="http://opencv.org/" rel="nofollow noreferrer">http://opencv.org/</a>.</li>
<li>Extracted the folder in C:.</li>
<li>I went to <em>System</em> → <em>Advanced System Settings</em>... | <p>The right way to install OpenCV 3.0.0 for Python 3.4.2 on Windows 8.1:</p>
<ol>
<li>Go to <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv" rel="nofollow noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv</a></li>
<li>Download OpenCV, NumPy and SciPy</li>
</ol>
<p>For me I needed:</p>
<u... | python|opencv|numpy|cmake | 10 |
10,477 | 41,552,255 | what if index access fails in pandas df | <p>I am trying to access a scalar value in a multi column dataframe via a lookup as follows:</p>
<pre><code>targetDate = '2016-01-01'
df['revenue'][df['date']== targetDate].values[0]
</code></pre>
<p>Now, in my case there is nothing found in the dataframe for the <code>targetDate</code>. So I get the following index ... | <p>If you precede with <code>head(1)</code> and remove the subscript on values then that will avoid the error message although it won't fill with a nan (it will just be an empty numpy array).</p>
<pre><code>df['revenue'][df['date']== targetDate].head(1).values
</code></pre>
<p>But you could do something like this to ... | python|pandas | 1 |
10,478 | 41,330,073 | Count number of preceding zeroes based on last occurrence | <p>I have the following dataframe in Python (multiple rows by product store and week combination (sorted)).</p>
<pre><code>product store week visit prob
123 321 1 0 0.003
123 321 2 0 0.234
123 321 3 1 0
123 321 4 0 0.198
123 301 1 0 0.290
123 301 2... | <p>I'll create a working data set <code>d1</code> and assign some new columns to it.</p>
<ul>
<li><code>iszero</code> tracks where <code>prob</code> is zero. I'll multiply by this column later</li>
<li><code>novist</code> tracks where we <code>visit</code> is not zero. I'll multiply by this later and use it to help ... | python|python-3.x|pandas | 2 |
10,479 | 41,486,948 | Pandas groupby a timedelta greater than N minutes | <p>I have a dataframe with columns for the timetag, a satellite ID, and a site ID. My goal is to break up the data set into individual "tracks" where each "track" is a unique combination of satellite and site IDs. I can do this easily using the standard pandas groupby functionality and specifying <code>by=['site', 'sat... | <p>After fiddling around with <a href="https://stackoverflow.com/users/190597/unutbu">unutbu</a>'s solution and combining it with the suggestions from <a href="https://stackoverflow.com/questions/20670726/computing-diffs-in-pandas-after-using-groupby-leads-to-unexpected-result">this post</a> I was able to solve the pro... | python|pandas | 2 |
10,480 | 41,607,144 | Loading two models from Saver in the same Tensorflow session | <p>I have two networks: a <code>Model</code> which generates output and an <code>Adversary</code> which grades the output.</p>
<p>Both have been trained separately but now I need to combine their outputs during a single session.</p>
<p>I've attempted to implement the solution proposed in this post: <a href="https://s... | <p>Solving this problem took a long time so I'm posting my likely imperfect solution in case anyone else needs it.</p>
<p>To diagnose the problem I manually looped through each of the variables and assigned them one by one. Then I noticed that after assigning the variable the name would change. This is described here:... | python|tensorflow | 26 |
10,481 | 41,511,601 | Pandas loc() method with boolean array on axis 1 | <p>I am experimenting with the Pandas <code>loc()</code> method, used with boolean arrays as arguments.</p>
<p>I created a small dataframe to play with:</p>
<pre><code> col1 col2 col3 col4
0 a 1 2 3
1 b NaN NaN 6
2 c NaN 8 9
3 d NaN 11 ... | <p>You need convert <code>Series</code> to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow noreferrer"><code>values</code></a>:</p>
<pre><code>print (df.loc[: , a1.values])
col1 col3
0 a 2.0
1 b NaN
2 c 8.0
3 d 11... | python|arrays|pandas|boolean|pandas-loc | 4 |
10,482 | 27,501,694 | pandas: iterating over DataFrame index with loc | <p>I can't seem to find the reasoning behind the behaviour of .loc. I know it is label based, so if I iterate over Index object the following minimal example should work. But it doesn't. I googled of course but I need additional explanation from someone who has already got a grip on indexing.</p>
<pre class="lang-py p... | <p>The problem is not in <code>df.loc</code>;
<code>df.loc[idx, 'Weekday']</code> is just returning a Series.
The surprising behavior is due to the way <code>pd.Series</code> tries to cast datetime-like values to Timestamps.</p>
<pre><code>df.loc[0, 'Weekday']
</code></pre>
<p>forms the Series</p>
<pre><code>pd.Se... | python|pandas|indexing | 13 |
10,483 | 61,204,684 | Add value in Pandas Dataframe from Numpy Array | <p>I have a data frame which has a (3,1) df-shape like this:-</p>
<p><strong>My Dataframe:</strong> </p>
<blockquote>
<pre><code> KDB
0 2
1 7
2 9
</code></pre>
</blockquote>
<p>And I have a NumPy array that looks like this</p>
<p><strong>My Numpy Array:</strong></p>
<blockquote>
<p>[[40],[50],[60]]</... | <p>Your code did not cause any error, but my DataFrame has:</p>
<ul>
<li><em>0, 1, 2</em> as the <strong>index</strong> column,</li>
<li>the only <strong>data</strong> columns is <em>KDB</em>.</li>
</ul>
<p>But the result is wrong, as it contains <strong>2</strong> columns.</p>
<p>To get the proper result, use the f... | python|arrays|pandas|dataframe|numpy-ndarray | 0 |
10,484 | 61,393,313 | Pandas: Select rows and add on the right as multiple sets of columns (reshape?) | <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({
'pid': [10,20,10,30],
'sid': [1,1,2,3],
'data1': ['a','b','a','c'],
'data2': ['q','w','e','e'],
})
pid sid data1 data2
0 10 1 a q
1 20 1 b w
2 10 2 a e
3 30 3 c e
</code></pre>
... | <p>There's a very good link in the comment. However to answer your specific question, here's a way to achieve it:</p>
<pre><code>>>> df = df.pivot(index='pid',columns='sid',values=['data1','data2'])
>>> df
data1 data2
sid 1 2 3 1 2 3
pid ... | python|pandas|pandas-groupby | 2 |
10,485 | 61,472,204 | Plotting a blackbody radiation curve using matplotlib, but I dont understand the error I'm getting? | <pre><code>import math
import random
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
</code></pre>
<pre><code>h=6.62607015E-34 # Planck constant, units of J*s
hbar=h/(2*math.pi) # Reduced Planck constant
k=1.380649E-23 # Boltzmann constant, units of J/K
c=299792458.00 # speed of light M/s
sb=(2*(... | <p>There are several issues with </p>
<pre class="lang-py prettyprint-override"><code>Intensity=((2*h*c**2)/(x**5))(1/(exp(((h*c)/(x*k*T)-1))
</code></pre>
<p>The parentheses are unbalanced, there is a missing <code>*</code> between closed sets of parentheses, and the <code>exp</code> function is undefined. Since <co... | python|numpy|matplotlib|physics | 0 |
10,486 | 68,836,815 | Return a list from an array by providing two more lists | <p>I have a dataframe like this:</p>
<pre><code> a b c
2 100.0 0.0 0.0
23 200.0 1.0 0.0
44 300.0 2.0 0.0
65 400.0 3.0 0.0
86 500.0 4.0 0.0
107 600.0 5.0 -0.5
128 700.0 6.0 0.0
149 800.0 7.0 0.0
170 900.0 8.0 0.0
</code></pre>
<p>I want to find for a given... | <p>Try this, creating a <code>pd.MultiIndex</code> and then using <code>reindex</code> of the zipped lists generating a list of tuples:</p>
<pre><code>df.set_index(['a', 'b']).reindex(list(zip(a, b)))['c'].tolist()
</code></pre>
<p>Output:</p>
<pre><code>[0.0, -0.5, 0.0]
</code></pre> | python|pandas|dataframe|find | 1 |
10,487 | 68,736,827 | Evaluate the model during training affects its performance PyTorch | <p>In <code>PyTorch</code>, I want to evaluate my model on the validation set every <code>eval_step</code> during training, and I wrote code like this:</p>
<pre class="lang-py prettyprint-override"><code>def tune(model, loader_train, loader_dev, optimizer, epochs, eval_step):
for epoch in range(epochs):
for... | <p>I think you probably set 'shffule=True' in your dataloader. Even though you fix 'random seed', dataloader in torch will generate different results if you use another dataloader while using current dataloader. In the scenario you describe, it may cause your model get data input in different order and then result in d... | python|pytorch | 1 |
10,488 | 36,450,595 | Pandas read_csv is super slow on NFS | <p>I have very simple script that uses <code>pandas.parse_csv</code> method to load large dataset.</p>
<pre><code>import pandas as pd
import numpy as np
USE_COLUMNS = [0,1,2,11,13,14]
def parse_csv(filename):
df = pd.read_csv(filename,
header=None,
compression='bz2',
... | <p>I would suggest you to pre-filter your data (using standard tools: <code>bzip2</code> and <code>gawk</code>) before loading it to pandas:</p>
<pre><code>bzip2 -dc /path/to/test.log.bz2 | gawk -F"," 'NR > 4 && $15 > 600000.0 {print}' > /path/to/test_filtered.log
</code></pre>
<p>this should be much... | python|python-2.7|pandas|nfs | 0 |
10,489 | 5,176,060 | insertion sort in numpy? | <p>Is there a insertion sort somewhere in numpy? I require a argsort for my array but the builtin quick,merge and heap are not suitable for nearly sorted array.</p> | <p>From the <a href="https://github.com/numpy/numpy/blob/master/doc/release/1.17.0-notes.rst#timsort-has-replaced-mergesort-as-the-stable-sorting-implementation" rel="nofollow noreferrer">numpy 1.17.0 release notes</a>:</p>
<blockquote>
<p>Timsort has been implemented and is now used in place of mergesort. [...] Tim... | python|numpy|sorting|scipy|insertion-sort | 3 |
10,490 | 53,342,637 | Matrix from Excel to Python | <p>I'm writing a Python program that will import a square matrix from an Excel sheet and do some NumPy work with it. So far it looks like OpenPyXl is the best way to transfer the data from an XLSX file to the Python environment, but it's not clear the best way to turn that data from a tuple of tuples* of cell reference... | <p>As commented above, the ideal solution is to use a pandas dataframe. For example:</p>
<pre><code>import pandas as pd
dataframe = pd.read_excel("name_of_my_excel_file.xlsx")
print(dataframe)
</code></pre>
<p>Just <code>pip install pandas</code> and then run the code above, only replacing <code>name_of_my_excel_fi... | python|excel|numpy|openpyxl | 1 |
10,491 | 65,786,862 | select column value based on index name in Pandas DataFrame | <p>I have a DataFrame named <code>score_df</code> having one column named <code>Score</code> and there are names of indices as following</p>
<pre><code> Score
year 0.029827
yesterday 0.029827
you 0.089482
zeros 0.029827
zones 0.029827
</code></pre>
<p>I have another <code>df</code> hav... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> with default inner join:</p>
<pre><code>print (score_df)
Score
year 0.029827
yesterday 0.029827
you 0.089482
zeros ... | python|pandas|dataframe | 2 |
10,492 | 65,654,159 | How to extract cell state of LSTM model through model.fit()? | <p>My LSTM model is like this, and I would like to get state_c</p>
<pre><code>def _get_model(input_shape, latent_dim, num_classes):
inputs = Input(shape=input_shape)
lstm_lyr,state_h,state_c = LSTM(latent_dim,dropout=0.1,return_state = True)(inputs)
fc_lyr = Dense(num_classes)(lstm_lyr)
soft_lyr = Activation('... | <p>I am unsure of what you mean by "How to get state_c", because your LSTM layer is already returning the <code>state_c</code> with the flag <code>return_state=True</code>. I assume you are trying to train the multi-output model in this case. Currently, you only have a single output but your model is compiled... | python-3.x|tensorflow|keras|lstm | 0 |
10,493 | 65,882,103 | I want to be able to create a polynomial function using the data frame column names as terms and the column values as their power raised to it | <p>I want to be able to create a polynomial function using the data frame column names as terms and the column values as their powers raised, I've added an example below on what I am looking for, but unfortunately running out of ideas on how to do it</p>
<p><a href="https://i.stack.imgur.com/J4LGy.png" rel="nofollow no... | <p>Given <code>df</code> for instance as:</p>
<pre><code> coefficient Term1 Term2
0 25 1 0
1 36 2 0
2 -16 0 0
3 4 2 1
</code></pre>
<p>and a dataframe <code>dfv</code> with values:</p>
<pre><code> Term1 Term2
0 0 1
1 2... | pandas | 2 |
10,494 | 63,395,522 | Pandas - expending several values to new columns with some column name manipulation | <p>I'm new to pandas.<br />
Consider you have a state in which you have a pandas <code>Dataframe</code> structure of columns like below:</p>
<p><code>user_id | timestamp | foo_name1 | foo_name2 | foo_name3</code></p>
<p>As we can see <code>Dataframe</code> has several metadata parameters, having raw string values:
<cod... | <ol>
<li>I synthesised the structure you defined</li>
<li>use <code>pd.concat(axis=1)</code> and <code>pd.json_normalize()</code> gets you to your answer</li>
<li>an additional use of a <code>dict</code> comprehension to name columns as per your requirement</li>
</ol>
<pre><code>df = pd.DataFrame([{**{"userid"... | python|python-3.x|pandas | 1 |
10,495 | 63,352,434 | Parsed between list of two dates for each client Python | <p>I have a df with sales which is looks like this:</p>
<pre><code>id date cost
a 2019-01-04 -1350.0
b 2019-01-04 7500.0
b 2019-01-04 17800.0
c 2019-01-04 17750.0
d 2019-01-04 1179.0
</code></pre>
<p>And I need to get information for each client with their sales before 1 year since they did las... | <p>Use:</p>
<pre><code>df = sales.merge(client, on='id')
orders = df[(df['date']<=df['year_ago'])&(df['date']>=df['last_order'])]
</code></pre> | python|pandas | 0 |
10,496 | 63,648,045 | Is it possible to create a NumPy array of characters and access contiguous slices of that array in constant time? | <h3>This Is Not a Duplicate</h3>
<p>I searched quite a bit, and I'm very aware that many posts already exist on related topics, but not one that I've seen answers this simple question.</p>
<h3>Question</h3>
<p>Is it possible to use NumPy to create an array of characters (let's assume unicode) that then allows contiguou... | <pre><code>In [89]: n = 10
...: chars = 'x' * n
...: np_chars = np.array(chars)
In [90]: chars
Out[90]: 'xxxxxxxxxx'
</code></pre>
<p>I don't see anything odd about <code>np_chars</code>. You asked ... | python|python-3.x|numpy | 1 |
10,497 | 63,335,152 | Share same Pandas Dataframe between process Pool without copying again and again | <p>I have a dataframe which holds a query result for about 1 million or more</p>
<p>When i pass this to map function which performs comparison of two dataframes , the above mentioned dataframe gets copied for every process and gives me memory error.</p>
<p>Sample code</p>
<pre><code>df = pd.read_sql_query('Query return... | <blockquote>
<p>i am on Windows and this df object is in main function</p>
</blockquote>
<p>Then you're out of luck.</p>
<p>Since there isn't copy-on-write memory on Windows, you can't share a Python variable transparently between multiple processes without copying occurring.</p>
<p>(<a href="https://docs.microsoft.com... | python|pandas|multiprocessing | 1 |
10,498 | 21,532,877 | Initialize numpy array using in-place sorted list | <p>I'm observing some odd behavior. Here is the snippet of code:</p>
<pre><code>>>> import numpy as np
>>> a = [[1, .3], [0, .5], [2, .23]]
>>> b = np.array(a.sort())
>>> b
array(None, dtype=object)
</code></pre>
<p>Is this behavior expected? If I add an intermediate step for the... | <p>The issue is that <code>a.sort()</code> does not return the sorted list. It returns <code>None</code>:</p>
<pre><code>>>> a.sort() is None
True
</code></pre>
<p>You could use <code>sorted(a)</code>:</p>
<pre><code>>>> b = np.array(sorted(a))
>>> b
array([[ 0. , 0.5 ],
[ 1. , ... | python|sorting|numpy|in-place | 3 |
10,499 | 24,491,501 | Scipy Handling of Large COO matrix | <p>I have a large sparse matrix in the form of a scipy <code>coo_matrix</code> (size of 5GB). I have to make use of the non-zero entries of the matrix and do some further processing.</p>
<p>What would be the best way to access the elements of the matrix? Should I convert the matrix to other formats or use it as it is?... | <p>First let's build a random COO matrix:</p>
<pre><code>import numpy as np
from scipy import sparse
x = sparse.rand(10000, 10000, format='coo')
</code></pre>
<p>The non-zero values are found in the <code>.data</code> attribute of the matrix, and you can get their corresponding row/column indices using <code>x.nonze... | python|numpy|matrix|scipy|sparse-matrix | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.