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 |
|---|---|---|---|---|---|---|
5,100 | 63,127,564 | why does batch normalization make my batches so abnormal? | <p>I'm playing with pytorch for the first time, and I've noticed that when training my neural net, about one time in four or so the loss takes a left turn towards infinity, then nan shortly after that. I've seen a few other questions about nan-ing, but the recommendations there seem to be essentially to do normalizatio... | <p>Welcome to pytorch!</p>
<p>Here is how I would set up your training. Please check the comments.</p>
<pre><code># how the comunity usually does the import:
import torch # some people do: import torch as th
import torch.nn as nn
import torch.optim as optim
if __name__ == '__main__':
# setting some paramete... | python|neural-network|pytorch|batch-normalization | 1 |
5,101 | 63,014,971 | Create new column that is the sum of two rows, but repeat every two rows | <p>I am working on building an additional column in a data frame which is the sum of two rows for one Time Period. A picture is attached here:</p>
<p><a href="https://i.stack.imgur.com/oKCbD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oKCbD.png" alt="enter image description here" /></a></p>
<p>I ... | <p>You can try to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pandas.DataFrame.groupby()</code></a> method to compute sum of lives for every time period. After that you can enrich <code>sa</code> dataframe by the computed column ... | python|pandas | 1 |
5,102 | 63,149,034 | Sometimes get the error "err == cudaSuccess || err == cudaErrorInvalidValue Unexpected CUDA error: out of memory" | <p>I'm very lost on how to solve my particular problem, which is why I followed the getting help guideline in the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">Object Detection API</a> and made a post here on Stack Overflow.</p>
<p>To start off, my goal w... | <p>It might be related to the batch size used by the API.<br>
Try to control the batch size, maybe as described in this answer:
<a href="https://stackoverflow.com/a/55529875/2109287">https://stackoverflow.com/a/55529875/2109287</a></p> | tensorflow|object-detection | 0 |
5,103 | 67,628,309 | Pandas read_excel UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte | <p>The following codes creates the error</p>
<p><strong>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte</strong></p>
<pre><code>with open(file_path) as excel_file:
df = pd.read_excel(excel_file)
</code></pre> | <p>The following code solved the issue</p>
<pre><code>with open(file_path,mode="rb") as excel_file:
df = pd.read_excel(excel_file)
</code></pre> | python|pandas | 1 |
5,104 | 67,906,187 | Write all pandas dataframe in workspace to excel | <p>I'm trying to write all the currently available pandas dataframe in workspace to excel sheets. By following example from this <a href="https://stackoverflow.com/q/41113663">SO thead</a>, but I'm unable to make it work.</p>
<p>This is my not working code:</p>
<pre><code>alldfs = {var: eval(var) for var in dir() if is... | <p>Just a small fix will do the job:</p>
<pre class="lang-py prettyprint-override"><code>alldfs = {var: eval(var) for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)}
for df_name, df in alldfs.items():
print(df_name)
fmane = df_name+".xlsx"
writer = pd.ExcelWriter(fmane)
df.to_e... | excel|pandas|dataframe | 1 |
5,105 | 67,909,456 | node-tflite - GLIBC_2.27 not found (required by libtensorflowlite_c.so) | <p>I am trying to deploy a Node.js server to IBM cloud (Linux) using <code>node-tflite</code> as a dependency, and get the following error preventing the server from starting:</p>
<pre><code>un 9 17:04:57 Code Engine deployment-0001 /usr/src/app/node_modules/bindings/bindings.js:121
throw e;
^
Jun 9 17... | <p>Found the solution, works for sure on deployment, this is the <code>dockerfile</code>:</p>
<pre><code>FROM ubuntu
RUN apt-get update
RUN apt-get install -y curl wget make g++
RUN curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -
RUN apt-get install -y nodejs
COPY package*.json ./
RUN npm install
COPY . .
... | javascript|node.js|linux|docker|tensorflow.js | 1 |
5,106 | 67,898,455 | How to save dictionary to csv | <pre><code>import pandas as pd
df = pd.read_excel('test.xlsx')
dict_of_region = dict(iter(df.groupby('Region')))
dict_of_region
</code></pre>
<p>df is a dataframe having 100 rows and 20 columns with a column name region which have 4 regions like say north, south, east, west. By using group by I have made a dictionary ... | <pre><code>for df_name, df in dict_of_region.items():
df.to_csv(f'{df_name}.csv', index=False)
</code></pre> | python|pandas | 1 |
5,107 | 41,475,758 | Problems while filtering pandas dataframe by row values? | <p>I have the following pandas dataframe:</p>
<pre><code> Col
0 []
1 []
2 [(foo, bar), (foo, bar)]
3 []
4 []
5 []
6 []
7 [(foo, bar), (foo, bar)]
</code></pre>
<p>I would like to remove all the empty lists (*):</p>
<pre><code> Col
2 [(foo, bar), (foo, bar)]
7 [(foo, bar), (foo, bar)]
</code... | <p>Slicing through the data frame as though the values were <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow noreferrer">strings</a> instead of lists may work:</p>
<pre><code>df[df.astype(str)['Col'] != '[]']
</code></pre> | python|python-3.x|pandas | 3 |
5,108 | 41,635,738 | Get Pretrained Inception v3 model from Open Images dataset working on Android | <p>I tried a while to get the pretrained model working on android. The problem is, I only got the ckpt and meta file for the pretrained net. In my opinion I need the .pb for the android app. So I tried to convert the given files to an .pb file. </p>
<p>Therefore I tried the freeze_graph.py but without succes. So I use... | <p>You'll need to use the optimize_for_inference.py script to strip out the unused nodes in your graph. "decodeJpeg" is not supported on Android -- pixel values should be fed in directly. ClassifierActivity.java has more detail about the specific nodes to use for inception v3.</p> | android|tensorflow | 2 |
5,109 | 27,488,032 | 'latin-1' codec can't encode character u'\u2014' in position 23: ordinal not in range(256) | <p>I am loading data into a pandas dataframe from an excel workbook and am attempting to push it to a database when I get the above error.</p>
<p>I thought at first the collation of the database was at issue which I changed to utf8_bin</p>
<p>Next I checked the database engine create statement on my end which I added... | <p>Apparently I needed to add ?charset-utf8 to the query string as well as the encoding variable which resulted in me ending up wht the engine create statement</p>
<pre><code>engine = create_engine('mysql+pymysql://root@localhost/test?charset=utf8', encoding="utf-8")
</code></pre> | mysql|excel|utf-8|pandas|latin1 | 9 |
5,110 | 61,466,228 | pandas Third Column answer is based on column 1 and column 2 | <p>First - I have tried reviewing similar posts, but I am still not getting it.</p>
<p>I have data with corporate codes that I have to reclassify. First thing, I created a new column -['corp_reclassed'].</p>
<p>I populate that column with the use of the map function and a dictionary. </p>
<p>Most of the original co... | <pre><code>df.loc[df['gem_reclassed']= pd.np.nan, 'final_number'] = df['corp_reclassed']
</code></pre> | python|pandas | 0 |
5,111 | 61,195,022 | Pivot Table in Pandas with two column(Index and Value) | <p>I have a CSV file with <code>obj</code> and <code>VS</code> column.
I need to sum <code>VS</code> values for each <code>obj</code> and have output like below</p>
<p><strong>Input:</strong></p>
<pre><code>+-----+------+
| obj | VS |
+-----+------+
| B | 2048 |
| A | 1024 |
| B | 10 |
| A | 1024 |
| B ... | <p>Just consider that as you read from CSV, values are string, you need to convert them to int by <code>df['VS']=pd.to_numeric(df['VS'])</code>
<code>print(df.dtypes)</code> show the type of column in df</p>
<pre><code>import pandas as pd
import numpy as np
filename='1test.csv'
df = pd.read_csv(filename, dtype='str... | python|pandas|csv|dataframe | 1 |
5,112 | 68,573,859 | GAN Model Code Modification — 3 Channels to 1 Channel | <p>This model is designed for processing 3-channel images (RGB) while I need to handle some black and white image data (grayscale), so I’d like to change the “ch” parameter to “1” instead of “3.”</p>
<p>The full code is available here — <a href="https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html" rel="nof... | <p>A grayscale image is a "special case" of a color image: a pixel has a gray color iff the red channel equals the green equals the blue. Thus a pixel with values <code>[200, 10, 30]</code> will be green-ish in color, while a pixel with values <code>[180, 180, 180]</code> will have a gray color.<br />
Therefo... | python|pytorch|generative-adversarial-network | 1 |
5,113 | 68,752,887 | Pandas- Create column based on sum of previous row values | <p>Sample dataset:</p>
<pre><code> id val
0 9 1
1 9 0
2 9 4
3 9 6
4 9 2
5 9 3
6 5 0
7 5 1
8 5 6
9 5 2
10 5 4
</code></pre>
<p>From the dataset, I want to generate a column <code>sum</code>. For the first 3 rows: <code>sum</code>=<code>sum</code>+<code>val</code>(group by id)... | <p>Are you sure the expected output is correct?</p>
<p>I would do:</p>
<pre><code>df['sum'] = df.groupby('id')['val'].rolling(min_periods=1, window=3).sum().values
</code></pre>
<p>output:</p>
<pre><code> id val sum
0 5 1 1.0
1 5 0 1.0
2 5 4 5.0
3 5 6 10.0
4 5 2 12.0
5 5 ... | pandas | 3 |
5,114 | 68,639,166 | Dictionary Unique Keys Rename and Replace | <p>I have a dictionary format structure like this</p>
<pre><code>df = pd.DataFrame({'ID' : ['A', 'B', 'C'],
'CODES' : [{"1407273790":5,"1801032636":20,"1174813554":1,"1215470448":2,"1053754655":4,"1891751228":1},
{"1497066526":19,"1801032636&quo... | <p>You can use apply here:</p>
<p>Assuming the unique list dataframe is <code>unique_list_df</code>:</p>
<pre><code>u = df['CODES'].map(lambda x: [*x.keys()]).explode().unique()
d = dict(zip(u,'np_'+pd.Index((pd.factorize(u)[0]+1).astype(str))))
f = lambda x: {d.get(k,k): v for k,v in x.items()}
df['CODES'] = df['CODE... | pandas|dictionary|replace|unique | 2 |
5,115 | 68,588,784 | Select top K value from a tensor with no duplication | <p><code>torch.Tensor.topk</code> provides an efficient way to extract top k values in a tensor along one dimension. Is it possible to restrict the top k value to be <strong>non-repetitive</strong>?</p>
<p>For example,</p>
<pre><code>input = torch.tensor([0.2,0.2,0.1])
k = 2
dim = 0
output[0] = torch.tensor([0.2,0.1]... | <p>You could apply <a href="https://pytorch.org/docs/stable/generated/torch.unique.html" rel="nofollow noreferrer"><code>torch.unique</code></a> on the input tensor.</p>
<pre><code>>>> input.unique().topk(k=2).values
tensor([0.2000, 0.1000])
</code></pre>
<p>Do note you will lose the indices at this point.</p>... | pytorch|selection | 0 |
5,116 | 68,544,939 | Search for different variations of text in pandas | <p>I have a pandas dataframe that consists of people and their degree type:</p>
<pre><code>data = {'Name': ['Alice','Bob','Chris','David'],
'Degree': ['phd','BA','MBA','B.Sc.']
}
df = pd.DataFrame(data, columns = ['Name', 'Degree'])
</code></pre>
<p>And I would like to one hot encode based on the degree type:<... | <p>Since the same degree types all start with the same character you can lower them and map on the first character:</p>
<pre><code>data = {'Name': ['Alice','Bob','Chris','David'],
'Degree': ['phd','BA','MBA','B.Sc.']
}
df = pd.DataFrame(data, columns = ['Name', 'Degree'])
df['Degree'] = df['Degree'].str.lower(... | python|pandas | 1 |
5,117 | 68,455,389 | ValueError: could not convert string to float: 'Yes, policy' while fitting to my Logistic Regression Model | <p>I am reading an excelsheet using pandas, the excelsheet has columns more than 10, out of which I am only interested in 3, so I read it, remove the rows which have Null values and then creating test and a validation set. While fitting it to the Logistic regression Model, I am getting an error</p>
<p>Here's the code</... | <p>It looks like your <code>ANSWER</code> and <code>TEXT</code> columns contains categorical values, and you have to encode them in numeric form before feeding it to the model. Because machine learning models don't understand text. Use this code on the dataframe before using <code>train_test_split</code></p>
<pre><code... | python|pandas|machine-learning|scikit-learn | 2 |
5,118 | 36,569,933 | Updating values with another dataframe | <p>I have 2 pandas dataframes. The second one is contained in the first one. How can I replace the values in the first one with the ones in the second?</p>
<p>consider this example:</p>
<pre><code>df1 = pd.DataFrame(0, index=[1,2,3], columns=['a','b','c'])
df2 = pd.DataFrame(1, index=[1, 2], columns=['a', 'c'])
ris=... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow"><code>copy</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow"><code>combine_first</code></a>:</p>
<pre><code>d... | python|pandas|replace|dataframe | 1 |
5,119 | 36,621,778 | Pandas Dataframe datetime slicing with Index vs MultiIndex | <p>With single indexed dataframe I can do the following:</p>
<pre><code>df2 = DataFrame(data={'data': [1,2,3]},
index=Index([dt(2016,1,1),
dt(2016,1,2),
dt(2016,2,1)]))
>>> df2['2016-01 : '2016-01']
data
2016-01-01 1
201... | <p>Cross-section should work:</p>
<pre><code>df.xs(slice('2016-01-01', '2016-01-01'), level='date')
</code></pre>
<p>Documentation: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html</... | python|datetime|pandas|dataframe|slice | 14 |
5,120 | 36,289,127 | How do I draw a area plot in ggplot with timeseries data? | <p>I'm trying to post a graph like <a href="http://chrisalbon.com/python/ggplot_area_plot.html" rel="nofollow">this</a>. </p>
<p>My data set looks like this. It has two columns. The first is the date and the second is the total number:</p>
<pre><code>date volume
3/21/16 280
3/20/16 279
3/18/16 278
3/4/16 277
... | <p>There are a couple issues here. First <code>aes</code>, <code>geom_area</code> etc, are classes of the <code>ggplot</code> module. Thus as in the referenced post they import via <code>from ggplot import *</code> instead of <code>import ggplot</code>. What I would recommend for easier debugging and maintainable code ... | python|pandas|ggplot2 | 1 |
5,121 | 5,064,822 | How to add items into a numpy array | <p>I need to accomplish the following task:</p>
<p>from:</p>
<pre><code>a = array([[1,3,4],[1,2,3]...[1,2,1]])
</code></pre>
<p>(add one element to each row) to:</p>
<pre><code>a = array([[1,3,4,x],[1,2,3,x]...[1,2,1,x]])
</code></pre>
<p>I have tried doing stuff like a[n] = array([1,3,4,x])</p>
<p>but numpy comp... | <p>Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python <code>list</code> will. You'll find that every "append... | python|numpy | 133 |
5,122 | 65,649,030 | Transpose specific rows into columns in pandas | <p>I have a dataset that has information like below:</p>
<pre><code>Title Year Revenue (Mi)
---------------------------------------------------------------
Guardians of the Galaxy 2015 313.13
Split 2016 138.0
Sing ... | <p>Try with</p>
<pre><code>out = df.pivot(index='Title', columns='Year', values='Revenue (Mi)').reset_index()
</code></pre> | python|pandas|dataframe|numpy | 2 |
5,123 | 65,902,816 | Removing stop words from a pandas column | <pre><code>import nltk
nltk.download('punkt')
nltk.download('stopwords')
import datetime
import numpy as np
import re
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
# Load the Pandas libraries with alia... | <ol>
<li><p>after applying a function to a column you need to assign the result back to the column, it's not an in-place operation.</p>
</li>
<li><p>after tokenization <code>ukdata['text']</code> holds a <code>list</code> of words, so you can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-co... | python|pandas|dataframe|tokenize | 1 |
5,124 | 65,777,807 | Python Pandas: How to get previous dates with a condition | <p>I have dataset with the following columns:</p>
<ul>
<li>encounterDate</li>
<li>FormName</li>
<li>PersonID</li>
</ul>
<p>In the FormName, I have the following forms:</p>
<ol>
<li>Baseline</li>
<li>Follow-up</li>
</ol>
<p>Here's a sample data:</p>
<pre><code>encounterDate, FormName, PersonID
2019-01-12, Baseline, 01
2... | <p>This would be fairly straight forward in <code>pandas</code></p>
<p>It looks like you need to <code>groupby</code> both the <code>PersonID</code> and <code>FormName</code> to get the proper groupings. Within those groups you need to shift <code>encounterDate</code> and you need a cumulative count of the same.</p>
<... | python|pandas | 1 |
5,125 | 21,201,618 | pandas.merge: match the nearest time stamp >= the series of timestamps | <p>I have two dataframes, both of which contain an irregularly spaced, millisecond resolution timestamp column. My goal here is to match up the rows so that for each matched row, 1) the first time stamp is always smaller or equal to the second timestamp, and 2) the matched timestamps are the closest for all pairs of ti... | <p><code>merge()</code> can't do this kind of join, but you can use <code>searchsorted()</code>:</p>
<p>Create some random timestamps: <code>t1</code>, <code>t2</code>, there are in ascending order:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(0)
base = np.array(["2013-01-01 00:00:00"], "date... | python|pandas | 32 |
5,126 | 21,403,398 | Troubleshooting Latex table from pandas dataframe to_latex() | <p>I am unable to visualize the Latex table generated using <code>dataframe.to_latex()</code> from pandas in my IPython notebook. It shows the exact string with the <code>"\begin.."</code> line in a box.</p>
<p>I am also curious why the table is formatted <code>{lrrrrr}</code> and how I can change it columns with line... | <p>1) Live Notebook does not support full LaTeX it support Math. Table are not math. Hence table are not rendered. </p>
<p>2) You are printing your latex representation, so you are not triggering the display hook. Hence only the text will show. </p>
<p>3) do not "choose" the representation of on object you like, just... | python|pandas|latex|ipython-notebook|ubuntu-13.04 | 3 |
5,127 | 21,160,134 | Flatten a column with value of type list while duplicating the other column's value accordingly in Pandas | <p>Dear power Pandas experts:</p>
<p>I'm trying to implement a function to flatten a column of a dataframe which has element of type list, I want for each row of the dataframe where the column has element of type list, all columns but the designated column to be flattened will be duplicated, while the designated colum... | <p>I guess easies way to flatten list of lists would be a pure python code, as this object type is not well suited for pandas or numpy. So you can do it with for example</p>
<pre><code>>>> b_flat = pd.DataFrame([[i, x]
... for i, y in input['B'].apply(list).iteritems()
... f... | python|pandas|dataframe|data-manipulation | 12 |
5,128 | 63,592,683 | Wondering why scipy.spatial.distance.sqeuclidean is twice slower than numpy.sum((y1-y2)**2) | <p>Here is my code</p>
<pre><code>import numpy as np
import time
from scipy.spatial import distance
y1=np.array([0,0,0,0,1,0,0,0,0,0])
y2=np.array([0. , 0.1, 0. , 0. , 0.7, 0.2, 0. , 0. , 0. , 0. ])
start_time = time.time()
for i in range(1000000):
distance.sqeuclidean(y1,y2)
print("--- %s seconds ---" ... | <p>Here is a more comprehensive comparison (credit to @Divakar's <code>benchit</code> package):</p>
<pre><code>def m1(y1,y2):
return distance.sqeuclidean(y1,y2)
def m2(y1,y2):
return np.sum((y1-y2)**2)
in_ = {n:[np.random.rand(n), np.random.rand(n)] for n in [10,100,1000,10000,20000]}
</code></pre>
<p><a href="ht... | python|performance|numpy|scipy|matrix-multiplication | 6 |
5,129 | 63,675,559 | how can i adjust space between elements of numpy array? | <p>I want such type of output</p>
<pre><code> [[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
</code></pre>
<p>But I am getting This</p>
<pre><code> [[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
</code></pre>
<p>My code is this :</p>
<pre><code>import numpy
print(numpy.identity(size))
</code></pre> | <p>use <strong>numpy.arrange(start, stop, size)</strong>
as follow</p>
<pre><code>import numpy as np
arr1 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 0]])
arr2 = np.arange(1, 9, 1)
print(arr2)
</code></pre>
<p>output</p>
<pre><code>[1 2 3 4 5 6 7 8]
</code></pre> | python|numpy|formatting|spacing | 0 |
5,130 | 63,400,447 | Pandas : how to consider content of certain columns as list | <p>Let's say I have a simple pandas dataframe named df :</p>
<pre><code> 0 1
0 a [b, c, d]
</code></pre>
<p>I save this dataframe into a CSV file as follow :</p>
<pre><code>df.to_csv("test.csv", index=False, sep="\t", encoding="utf-8")
</code></pre>
<p>Then later in my script ... | <p>Try this, Since you are reading from csv file,your dataframe value in column <code>A</code> (<code>1</code> in your case) is essentially a string for which you need to infer the values as list.</p>
<pre><code>import pandas as pd
import ast
df=pd.DataFrame({"A":["['a','b']","['c']"],&quo... | python-3.x|pandas|dataframe | 0 |
5,131 | 53,546,605 | What's happened to pandas data reader using stooq? | <p>I have built a set of scripts that obtain and perform technical analysis on stocks using pandas-datareader. It has been up and working now for 6-8 months without problems.</p>
<p>Suddenly this week the datareader function is returning empty frames eg:-</p>
<pre><code> import pandas_datareader as web
BAC = w... | <p>A bug was introduced in 0.7.0 which automatically appends <code>.US</code> to every ticker. This is likely being reverted in 0.8.0 (see this pull request), but for now, use:</p>
<p><code>
BAC = web.DataReader("AAPL", "stooq")
</code></p>
<p>as a workaround.</p> | python-2.7|pandas-datareader | 0 |
5,132 | 53,459,234 | How to get the Numpy array of file stream of any image | <p>I'm trying to use the imageai python library, and more particularly this function:</p>
<pre><code>detector.detectObjectsFromImage()
</code></pre>
<p>The doc says it should be used with a Numpy array of file stream of any image.</p>
<p><a href="https://imageai.readthedocs.io/en/latest/detection/index.html" rel="no... | <p>I know it's old, but for anyone who needs help: </p>
<p>Try to set 2 additional params:</p>
<pre class="lang-py prettyprint-override"><code>minimum_percentage_probability=0, output_type='array'
</code></pre>
<p>For more info, go into <code>imageai\Detection\__init__.py -> detectObjectsFromImage</code></p> | numpy | 0 |
5,133 | 53,364,292 | Finding the probability of a variable in collection of lists | <p>I have a selection of lists of variables</p>
<pre><code>import numpy.random as npr
w = [0.02, 0.03, 0.05, 0.07, 0.11, 0.13, 0.17]
x = 1
y = False
z = [0.12, 0.2, 0.25, 0.05, 0.08, 0.125, 0.175]
v = npr.choice(w, x, y, z)
</code></pre>
<p>I want to find the probability of the value V being a selection of vari... | <p>There are several issues in the code, I think you want the following:</p>
<pre><code>import numpy.random as npr
import math
from collections import Counter
def probability(v=0.12):
return float(c[v]/len(combined))
w = [0.02, 0.03, 0.05, 0.07, 0.11, 0.13, 0.17]
x = [1]
y = [False]
z = [0.12, 0.2, 0.25, 0.05,... | python|numpy|random|probability | 0 |
5,134 | 17,663,393 | indexing spherical subset of 3d grid data in numpy | <p>I have a 3d grid with coordinates</p>
<pre><code>x = linspace(0, Lx, Nx)
y = linspace(0, Ly, Ny)
z = linspace(0, Lz, Nz)
</code></pre>
<p>and I need to index points (i.e. x[i],y[j],z[k]) within some radius R of a position (x0,y0,z0). N_i can be quite large. I can do a simple loop to find what I need</p>
<pre><cod... | <p>How about this:</p>
<pre><code>import scipy.spatial as sp
x = np.linspace(0, Lx, Nx)
y = np.linspace(0, Ly, Ny)
z = np.linspace(0, Lz, Nz)
#Manipulate x,y,z here to obtain the dimensions you are looking for
center=np.array([x0,y0,z0])
#First mask the obvious points- may actually slow down your calculation depend... | python|numpy|3d|grid|subset | 3 |
5,135 | 20,095,685 | Python NumPy - How to print array not displaying full set | <p>I'm converting a list into a NumPy array:</p>
<pre><code>a = np.array(l) # Where l is the list of data
return a
</code></pre>
<p>But whenever I go to print this array:</p>
<pre><code>print (a)
</code></pre>
<p>I only get a slice of the array:</p>
<blockquote>
<p>[-0.00750732 -0.00741577 -0.00778198 ..., 0.0... | <p>You can change the summarization options with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html#numpy.set_printoptions" rel="nofollow"><code>set_printoptions</code></a></p>
<pre><code>np.set_printoptions(threshold = your_threshold)
</code></pre>
<p>The threshold parameter set... | python|arrays|numpy | 3 |
5,136 | 12,576,313 | Convert excel or csv file to pandas multilevel dataframe | <p>I've been given a reasonably large Excel file (5k rows), also as a CSV, that I would like to make into a pandas multilevel DataFame. The file is structured like this:</p>
<pre><code>SampleID OtherInfo Measurements Error Notes
sample1 stuff more stuff
... | <p>Looks like your file has fixed width columns, for which read_fwf() can be used.</p>
<pre><code>In [145]: data = """\
SampleID OtherInfo Measurements Error Notes
sample1 stuff more stuff
36 6
... | python|excel|csv|dataframe|pandas | 5 |
5,137 | 71,980,410 | How to draw the smooth lineplot and display the dates on the x-axis with python? | <p>I would really really appreciate it if you guys can point me to where to look. I have been trying to do it for 3 days and still can't find the right one. I need to draw the chart which looks as the first picture's chart and I need to display the dates on the X axis as it gets displayed on the second chart. I am comp... | <p><a href="https://seaborn.pydata.org/generated/seaborn.lmplot.html" rel="nofollow noreferrer">lmplot</a> is a model based method, which requires numeric <code>x</code>. If you think the date values are evenly spaced, you can just create another variable <code>range</code> which is numeric and calculate <code>lmplot</... | python|pandas|numpy|matplotlib|seaborn | 0 |
5,138 | 71,929,783 | Save generated random numbers with numpy in dictionary | <p>I have a code that generates numbers using NumPy uniform distribution, but I want to save them in a dictionary.</p>
<pre><code>x = [1391096.378,
9187722.876,
516012.8602,
238575.7104,
228114.5731,
4685929.962,
675871.7576,
2371583.637,
368942.1523,
39899030.28,
2068330.11,
2663072.562,
587247.8119,
2077461.753,
6620... | <p>In this case, the keys of the dictionary will be integers from 0 to 20. If you'd like to have the value of <code>x</code> as a key, then you can substitute the <code>t</code> with the <code>x</code>, like this: <code>stored[x] = dft</code>.</p>
<p>Or you can use <a href="https://docs.python.org/3/tutorial/inputoutpu... | pandas|numpy|dictionary|random | 0 |
5,139 | 72,135,587 | Efficient way to update values in a GeoDataFrame based on the result of DataFrame.within method | <p>I have two large GeoDataFrame:</p>
<p>One came from a shapefile where each polygons has a float value called 'asapp'.</p>
<p>Second are the centroids of a fishnet grid with 3x3 meters and a column 'asapp' zeroed.</p>
<p>What I need is to fill the 'asapp' of the second one base where the centroid is within the polygo... | <p>I solved the problem.</p>
<p>I readed about using <code>geopandas.overlay</code> (<a href="https://geopandas.org/en/stable/docs/user_guide/set_operations.html" rel="nofollow noreferrer">https://geopandas.org/en/stable/docs/user_guide/set_operations.html</a>) with work with a lot of polygons, but the problem is that ... | python|performance|geopandas | 2 |
5,140 | 19,079,819 | Pandas dataframe column multiplication | <p>how to multiply, if you have 2 df's to multiply using selected columns , and store the result in a new column for example</p>
<p>df1:</p>
<pre><code> AAPL IBM GOOG XOM
2011-01-10 16:00:00 1500 0 0 0
</code></pre>
<p>df2:</p>
<pre><code>AAPL IBM GOOG XOM
340.99 143.41 614.21 72.02
3... | <pre><code>transaction_amount = np.diag(df1.dot(df2.T))
</code></pre>
<p>Basically, to do what you want, you want to do some form of dot product of df1 with df2</p>
<pre><code>df1.dot(df2)
</code></pre>
<p>but since they have matching dimensions you need to transpose one of the DataFrames</p>
<pre><code>df2.T
</cod... | python|numpy|pandas | 0 |
5,141 | 22,190,638 | Python: Round time to the nearest second and minute | <p>I have a <code>DataFrame</code> with a column <code>Timestamp</code> where each values are the number of seconds since midnight with nanosecond precision. For example:</p>
<pre><code>Timestamp
34200.984537482
34201.395432198
</code></pre>
<p>and so on. 34200 seconds since midnight is 9:30:00am. </p>
<p>I would li... | <p>There is a Series <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.round.html" rel="nofollow">round</a> method:</p>
<pre><code>In [11]: df.Timestamp.round()
Out[11]:
0 34201
1 34201
Name: Timestamp, dtype: float64
In [12]: df.Timestamp.round(1)
Out[12]:
0 34201.0
1 34201.4... | python|time|pandas | 4 |
5,142 | 4,387,878 | simulator of realistic ECG signal from rr data for matlab or python | <p>I have a series of rr data (distances between r-r peak in PQRST electrocardiogramm signal)
and I want to generate realistic ECG signal in matlab or python. I've found some materials for matlab (<code>ecg</code> built-in function in matlab) but I can't figure out how to generate it from rr data, and I've found nothin... | <p>Does this suit your needs? If not, please let me know. Good luck.</p>
<pre><code>import scipy
import scipy.signal as sig
rr = [1.0, 1.0, 0.5, 1.5, 1.0, 1.0] # rr time in seconds
fs = 8000.0 # sampling rate
pqrst = sig.wavelets.daub(10) # just to simulate a signal, whatever
ecg = scipy.concatenate([sig.resample(pqrs... | python|matlab|numpy|signal-processing|scipy | 13 |
5,143 | 8,824,739 | Global Interpreter Lock and access to data (eg. for NumPy arrays) | <p>I am writing a C extension for Python, which should release the Global Interpreter Lock while it operates on data. I think I have understood the mechanism of the GIL fairly well, but one question remains: Can I access data in a Python object while the thread does not own the GIL? For example, I want to read data fro... | <blockquote>
<p>Is this safe?</p>
</blockquote>
<p><del>Strictly, no. I think you should move the calls to <code>PyArray_SIZE</code> and <code>PyArray_DATA</code> outside the GIL-less block; if you do that, you'll be operating on C data only. You might also want to increment the reference count on the object before ... | python|numpy|python-c-api | 6 |
5,144 | 55,542,719 | Make pandas dataframe column of length of lists in entries on other column | <p>Suppose I have the dataframe:</p>
<pre><code> df=pd.DataFrame(data={'col1':[[1,4,4,1],[2,3]],'col2':[[1,2],[1,5,2,4]]})
</code></pre>
<p>How can I add a new column to this dataframe whose entry at every row is the length of the corresponding list in, say, col1?</p> | <p>use <code>str.len()</code></p>
<pre><code>df['length'] = df.col1.str.len()
print(df)
col1 col2 length
0 [1, 4, 4, 1] [1, 2] 4
1 [2, 3] [1, 5, 2, 4] 2
</code></pre> | python|python-3.x|pandas | 0 |
5,145 | 55,317,695 | Convert table having string column, array column to all string columns | <p>I am trying to convert a table containing string columns and array columns to a table with string columns only</p>
<pre><code>Here is how current table looks like:
+-----+--------------------+--------------------+
|col1 | col2 | col3 |
+-----+--------------------+--------------------+
|... | <p>Conver the columns to lists and after that to <code>numpy.array</code>, finally convert them to a <code>DataFrame</code>:</p>
<pre><code>vals1 = np.array(df.col2.values.tolist())
vals2 = np.array(df.col3.values.tolist())
col1 = np.repeat(df.col1, vals1.shape[1])
df = pd.DataFrame(np.column_stack((col1, vals1.rave... | python|pandas | 0 |
5,146 | 55,566,084 | How to turn a dataframe into a dictionary variable and make a barchart from it | <p>I need to convert a data frame query into a dictionary variable but it is saving the STATE and Occurrences as one variable. I need them separate so I can plot a bar chart from it
Am I doing it wrong?</p>
<p>Code for dataframe to dict</p>
<pre><code>df = pd.DataFrame(data_dict)
df = df['xyz'].value_counts().to_fram... | <p>In my opinion convert back to <code>dictionary</code> is not necessary, use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.plot.bar.html" rel="nofollow noreferrer"><code>Series.plot.bar</code></a> instead:</p>
<pre><code>df = pd.DataFrame(data_dict)
s = df['STATE'].value_counts()
... | python|pandas|dataframe|bar-chart | 0 |
5,147 | 55,190,988 | numpy ndarray indexing with __index__ method | <p>I don't understand how indexing of a numpy ndarray works, when using a custom class instance as the index.</p>
<p>I have the following code:</p>
<pre><code>import numpy as np
class MyClass:
def __index__(self):
return 1,2
foo = np.array([[1,2,3],[4,5,6]])
bar = MyClass()
print(foo[1,2])
print(foo[ba... | <p>As mentioned <a href="https://docs.python.org/3/reference/datamodel.html#object.__index__" rel="nofollow noreferrer">here</a>, <code>__index__</code> method <code>Must return an integer.</code></p>
<p>That's why your attempt didn't work, while the "one index" example worked.</p> | python|arrays|numpy|indexing|magic-methods | 2 |
5,148 | 7,635,237 | numpy: syntax/idiom to cast (n,) array to a (n, 1) array? | <p>I'd like to cast a numpy <code>ndarray</code> object of shape (<em>n</em>,) into one having shape (<em>n</em>, 1). The best I've come up with is to roll my own _to_col function:</p>
<pre><code>def _to_col(a):
return a.reshape((a.size, 1))
</code></pre>
<p>But it is hard for me to believe that such a ubiquitou... | <p>I'd use the following:</p>
<pre><code>a[:,np.newaxis]
</code></pre>
<p>An alternative (but perhaps slightly less clear) way to write the same thing is:</p>
<pre><code>a[:,None]
</code></pre>
<p>All of the above (including your version) are constant-time operations.</p> | python|arrays|vector|numpy|casting | 10 |
5,149 | 56,681,889 | How to write the data in excel file using pandas excel writer? | <p>I have some code which gives output through several for loops in the form of multiple lists and I want to write the output in excel or csv file using pandas excel writer.</p>
<pre><code>from pulp import *
from openpyxl import load_workbook
import pandas as pd
import numbers
from pulp import solvers
import xlwt
P=[... | <p>I haven't been able to reproduce the same output on my computer. But here isn't the question.</p>
<p>The reason why you only have the last row is that you're writing the <code>csv</code> file in the <code>for</code> loop. So you only get the last row because you overwrite all of them each time.</p>
<p>On solution ... | excel|python-3.x|pandas|writer | 1 |
5,150 | 56,441,025 | Using a function to replace cell values in a column | <p>I have a fairly large Dataframes 22000X29 . I want to clean up one particular column for data aggregation. A number of cells can be replaced by one column value. I would like to write a function to accomplish this using replace function. How do I pass the column name to the function?</p>
<p>I tried passing the ... | <p>Try accessing your column as:</p>
<pre><code>mydf[mycol]
</code></pre> | python-3.x|pandas | 1 |
5,151 | 56,858,698 | How to convert a multi dimensional list to numpy array and then write to a csv file | <p>I am running a query using psycopg2 in python. The results of the query is saved to a list. I am trying to convert this list into a numpy array and then write to a csv file. Here is how I did that. </p>
<pre><code>rows = rcursor.fetchall()
df = pd.DataFrame(np.array(rows), columns = rows("db1 db2 db3 db4 db5"))
df.... | <p>You can use pandas.read_sql_query directly to convert a sql query + connection into a dataframe. See <a href="https://gist.github.com/jakebrinkmann/de7fd185efe9a1f459946cf72def057e" rel="nofollow noreferrer">here</a> for example.</p> | python-3.x|pandas|dataframe|psycopg2|numpy-ndarray | 0 |
5,152 | 26,368,194 | Specifying a numpy.datype to read GPX trackpoints | <p>I want to represent a GPS track extracted from GPX file as a Numpy array. For that, each element will be of type "trackpoint", containing one datetime and three floats.</p>
<p>I am trying to do this (actually, after parsing the GPX file with some XML library):</p>
<pre><code>import numpy
trkptType = numpy.dtype([... | <p><a href="http://docs.scipy.org/doc/numpy/reference/arrays.datetime.html" rel="nofollow">As explained here</a>, you have to use at least <code>datetime64[m]</code> (minutes), instead of <code>datetime64</code>, then your code will work. You could also use a datetime that goes down to seconds or miliseconds, such as <... | python|arrays|numpy|user-defined-types|recarray | 1 |
5,153 | 67,147,195 | Unable to uninstall cuda even after purging it and removing the files | <p>I'm working on a computer on which Nvidia drivers and Cuda were installed by someone else so I don't know the method they used to install them.
In the <code>/usr/local/</code> there were two directories <code>cuda</code> and <code>cuda.10.0</code>. Running <code>nvidia-smi</code> would output:</p>
<blockquote>
<p>CU... | <p>The <code>nvidia-smi</code> command does not show which version of CUDA is installed, it shows which CUDA version the installed nVidia driver supports, so there is no problem here, just the incorrect interpretation of the output of this command.</p>
<p>Even if you remove all CUDA installations, <code>nvidia-smi</cod... | tensorflow|ubuntu|cuda|nvidia | 3 |
5,154 | 66,793,010 | Warning when reassigning to series in pandas | <p>Please suggest the right way of doing the following.</p>
<pre><code>data_tr['loss'] = data_tr['loss'].apply(lambda x:x**0.25)
</code></pre>
<pre><code><ipython-input-368-59c3c700212e>:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_... | <p>Have you tried what's suggested?</p>
<pre><code>data_tr.loc[:,'loss'] = data_tr.loc[:,'loss']**0.25
</code></pre> | pandas|series | 0 |
5,155 | 67,014,120 | Exploding pandas dataframe by list to multiple rows with a new column for multiindex | <p>I have a Pandas dataframe where the columns are 'month' and 'year', and a 'value_list' which is a list of values - one for each day of the month. Something like this -</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">year</th>
<th style="text-align: left;">month<... | <p>After you <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><strong><code>explode</code></strong></a>, you can create the <code>day</code> sequences using <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.... | python|pandas|dataframe|multi-index | 3 |
5,156 | 66,973,617 | get value from dataframe based on row values without using column names | <p>I am trying to get a value situated on the third column from a pandas dataframe by knowing the values of interest on the first two columns, which point me to the right value to fish out. I do not know the row index, just the values I need to look for on the first two columns. The combination of values from the first... | <p>As @anky has suggested, a way to do this without knowing the column names nor the row index where your value of interest is, would be to read the file in a pandas dataframe using multiple column indexing.</p>
<p>For the provided example, knowing the column indexes at least, that would be:</p>
<pre><code>df = pd.read... | python|pandas|dataframe | 1 |
5,157 | 47,446,284 | Python: How do you make a variable which can be used as an index call to slice another variable? | <p>I am coming from a MATLAB background and moving over to Python. I am trying to figure out a way to set up a variable which is some vector which contains a range of indices which can then be used to slice some other array.</p>
<p>In MATLAB I would do this:</p>
<pre><code>A = [2,3,4,5,6; 9,4,3,2,1; 5,4,3,2,5]; %some... | <p>You need <code>slice</code>:</p>
<pre><code>>>> import numpy as np
>>> A = np.array([[2,3,4,5,6],[9,4,3,2,1],[5,4,3,2,5]])
>>> begin = 1
>>> end = 3
>>> s = slice(begin, end)
>>> A[:,s]
array([[3, 4],
[4, 3],
[4, 3]])
</code></pre> | python|arrays|matlab|numpy|indexing | 1 |
5,158 | 68,256,123 | Is there a better way of making sure that a coordinate is not out of range in an np.array? | <p>I want to make sure that when I iterate through coordinates (i, j) of a 2D np.array, and access "neighbors", that I am not accessing values that are out of the array's range. Is there a better way of doing it than what I do here?</p>
<p>I consider the following coordinates as neighbors:</p>
<ul>
<li>(i - 1... | <p>I implemented something like this in the end:</p>
<pre><code>import numpy as np
for (i, j), value in np.ndenumerate(arr):
neighbors = [
neighbor
for neighbor in [(i - 1, j), (i, j - 1), (i - 1, j - 1), (i - 1, j + 1)]
if neighbor[0] and neighbor[1] and neighbor[0] < arr.shape[0]
... | python|arrays|numpy | 0 |
5,159 | 68,339,938 | Create a Dataframe from a list and keep duplicate items | <p>I have a list of dataframes. Each dataframe within the list is unique - meaning that there are some shared, but different columns. I would like to create a single dataframe that contains all of the columns from the list of dataframes and will fill NaN if an element is not present. I have tried the following</p>
<pre... | <p>You need to use some params in pd.concat:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'a':[1,2,3],'x':[4,5,6],'y':[7,8,9]})
df2 = pd.DataFrame({'b':[10,11,12],'x':[13,14,15],'y':[16,17,18]})
print(pd.concat([df1,df2], axis=0, ignore_index=True))
</code></pre>
<p>Result:</p>
<pre><code> a x y ... | python|pandas | 1 |
5,160 | 68,437,240 | Obtains small array by cuting a bigger one in Python | <p>I'm today working with array. I'm trying to slice a big array which looks like :</p>
<pre><code>A = [[a(0;0), a(0;1), ..., a(0;n)],
[a(1;0), a(1;1), ..., a(1;n)],
[....., ....., ....., .....],
[a(m;0), ...., ....., a(m;n)],
[b(m+1;0), b(m+1,1), ..., b(m+1,n)],
[b(m+2;0), b(m+2,1), ..., b(m+... | <p>If your data is even, then simply chunk it with this:</p>
<pre class="lang-py prettyprint-override"><code>data = A
m = <your offset>
[data[idx: idx + m] for idx in range(0, len(data), m)]
# example:
data = [["a1"],["a2"],["b1"],["b2"],["c1"],["c2"]]
... | python|arrays|numpy|slice | 0 |
5,161 | 68,338,620 | python numpy adding rows to 2d empty array | <p>i want to add rows to an empty 2d numpy array through a loop :</p>
<pre><code>yi_list_for_M =np.array([])
M =[]
for x in range(6) :
#some code
yi_m = np.array([y1_m,y2_m])
yi_list_for_M = np.append(yi_list_for_M,yi_m)
</code></pre>
<p>the result is :</p>
<pre><code>[0. 0. 2.7015625 2.53... | <pre class="lang-py prettyprint-override"><code>yi_list_for_M = np.empty((0,2), int)
for x in range(6):
y1_m = x**2
y2_m = x**3
yi_list_for_M = np.append(yi_list_for_M, np.array([[y1_m, y2_m]]), axis=0)
</code></pre> | python|arrays|numpy | 1 |
5,162 | 59,470,464 | Importing TensorFlow onto Xcode: The active toolchain is not compatible with playgrounds | <p>I have macOS Catalina on MacBook Air 2014. I'm experiencing problems in importing TensorFlow on Xcode 11.3. </p>
<p>I downloaded a Swift tensor 0.6 release and Swift for TensorFlow development snapshot.
I opened it in macOS blank playground but it doesn't work. </p>
<p>The error:</p>
<blockquote>
<p>The active ... | <p>Maybe you can try the following:</p>
<ul>
<li><p>First of all, make sure that you have the December 23 (or later) development snapshot of the toolchain. It enables S4TF to work with Xcode's new build system.</p>
<p>(You can get it <a href="https://github.com/tensorflow/swift/blob/master/Installation.md#development... | swift|xcode|macos|tensorflow | 0 |
5,163 | 59,402,061 | Why is my .drop removing all values in my dataframe? | <p>I keep trying to use this line of code to remove the rows of data with NaN in a certain column but it keeps removing all rows:</p>
<pre><code>df = df.drop(df[(df.test_variable == 'NaN')].index)
</code></pre> | <p>To answer the question you're <em>really</em> trying to ask (how to drop rows containing NaNs), use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>DataFrame.dropna()</code></a> function:</p>
<pre><code>import pandas as pd
import ... | python|pandas | 0 |
5,164 | 59,052,814 | Comparing Overlap in Pandas Columns | <p>So I have four columns in a pandas dataframe, column A, B, C and D. Column A contains 30 words, 18 of which are in column B. Column C contains either a 1 or 2 (keyboard response to column B words) and column D contains 1 or 2 also (the correct response). </p>
<p>What I need to do is see the total correct for only t... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin()</code></a>:</p>
<pre><code>df.B.isin(df.A)
</code></pre>
<p>That will give you a boolean Series the same length as <code>df.B</code> indicating for each value in <code>df.B... | python|pandas | 0 |
5,165 | 59,456,901 | how to fill values in empty rows with condition in python | <p>I want to put values in empty/NaN with condition wrt existing table
Please find the attached </p>
<p><strong>Existing Data</strong></p>
<pre><code>import pandas as pd
col_names = ['Date', 'ID', 'Individual','Category','Age','DW','Gender']
my_df = pd.DataFrame(columns = col_names)
my_df['Date']=2112019,211201... | <p>You don't have a WT column, so we don't now what that is. However for this example I'll use the DW column as the aggregation column. You can change it to suit your needs.</p>
<pre><code>import pandas as pd
col_names = ['Date', 'ID', 'Individual','Category','Age','DW','Gender']
my_df = pd.DataFrame(columns = co... | python|pandas | 0 |
5,166 | 45,212,479 | Calculating cumulative sum for previous period in each cohort in pandas, python | <p>I am newbie in pandas and I am trying to build cohort analysis. I need column containing cumulative sum of values for previous periods for this cohort.
For example for this Data frame</p>
<pre>
Canceled
CohortGroup NewCustomers CancelPeriod
201... | <p>first forward fill your Dataframe and do groupby</p>
<pre><code>df = df.fillna(method='ffill')
df['TotalCancCust'] = df.groupby(['CohortGroup'])['CanceledCustomers'].cumsum()
</code></pre> | python|pandas|statistics|analytics | 0 |
5,167 | 45,057,978 | python performance problems using loops with big tables | <p>I am using python and multiple libaries like pandas and scipy to prepare data so I can start deeper analysis. For the preparation purpose I am for instance creating new columns with the difference of two dates. <br>
My code is providing the expected results but is really slow so I cannot use it for a table with like... | <p>Take away the loop, and apply the functions to the whole series.</p>
<pre><code>ZEIT_ANFANG = tableContent[6]['p_test_ZEIT_ANFANG'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))
ZEIT_ENDE = tableContent[6]['p_test_ZEIT_ENDE'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))
tableContent[6]['p... | python|python-3.x|pandas|chained-assignment | 4 |
5,168 | 44,921,911 | Shuffling the training dataset with Tensorflow object detection api | <p>I'm working on a logo detection algorithm using the Faster-RCNN model with the Tensorflow object detection api.
My dataset is alphabetically ordered (so there are a hundred adidas logo, then hundred apple logo etc.). And i would like it to be shuffled while training.</p>
<p>I've put some values in the config file:... | <p>I recommend shuffling the dataset prior to training. The way shuffling currently happens is imperfect and my guess at what is happening is that at the beginning the queue starts off empty and only gets examples that start with 'A' --- after a while it may be more shuffled, but there is no getting around the beginni... | tensorflow|queue|shuffle|object-detection | 1 |
5,169 | 45,178,480 | How to merge two pandas dataframes using a column as pattern and include columns of the left dataframe? | <p>Having the following Python code, was trying to use pd.merge but seems that key columns requires to be identical.
Trying to to something similar to SQL join with "like" operator from df.B with categories.Pattern.</p>
<p><strong>UPDATE</strong> with better data example.</p>
<pre><code>import pandas as pd
import num... | <p>By Creating a new function like:</p>
<pre><code>def lookup_table(value, df):
"""
:param value: value to find the dataframe
:param df: dataframe which constains the lookup table
:return:
A String representing a the data found
"""
# Variable Initialization for non found entry in list... | python|pandas | 1 |
5,170 | 45,224,889 | installing tensorflow in windows anaconda - and running using it using Spyder GUI | <p>I visited <a href="https://www.tensorflow.org/install/install_windows#common_installation_problems" rel="nofollow noreferrer">the tensorflow page</a> and followed instructions from <code>Installing with Anaconda</code> section. When I tried to validate my installation, I got below errors</p>
<pre><code>(C:\ProgramD... | <p><strong>Q1</strong>: Yes you need to activate the virtual environment to import tensorflow as you have installed tensorflow in virtual environment. </p>
<p><strong>Q2</strong>: Not sure why there are multiple instructions but this is normal and is built in in tensorflow. You can avoid these by building tensorflow y... | python|windows|tensorflow|anaconda|spyder | 2 |
5,171 | 57,225,716 | GradientTape losing track of variable | <p>I have a script that performs a Gatys-like neural style transfer. It uses style loss, and a total variation loss. I'm using the GradientTape() to compute my gradients. The losses that I have implemented seem to work fine, but a new loss that I added isn't being properly accounted for by the GradientTape(). I'm using... | <p>The first issue here is that GradientTape only traces operations on tf.Tensor objects. When you call tensor.numpy() the operations executed there fall outside the tape.</p>
<p>The second issue is that your first example never calls tape.watche on the image you want to differentiate with respect to.</p> | python-3.x|tensorflow|tensorflow2.0 | 2 |
5,172 | 57,167,760 | How to properly apply a function to a series using series.map() or series.apply() in pandas | <p>I am trying to apply a predefined function (myfunc) to a new series in my DataFrame using pandas. The function will check if the value in each index in old column (for each row) is bigger then it's previous one and return 1 if yes and 0 if no. </p>
<p>I have also tried series.apply() function and I am getting: acr... | <p>You can use the shift function to compare values in previous rows:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df2 = pd.DataFrame(
{
'US':[1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]
})
def myfunc1(x):
if x:
return 1
else:
return 0
df2['Higher Inflation - US'] = (df2... | python|pandas | 0 |
5,173 | 56,924,618 | Am I able to fix the headers in my DataFrame while still using Pandas html_read? | <p>I want to pull an HTML table into a Pandas dataframe, and html_read so far has been the easiest method. However, some of the headers are coming through a little funky, and I'm trying to avoid fixing them manually in Excel.</p>
<p>I also tried several BeautifulSoup tutorials, but was unable to pull the tables into a... | <p>This should help.</p>
<p>As @jottbe pointed out, one should try to avoid reading the url twice. </p>
<pre><code>dfs = pd.read_html(url)
df1 = dfs[1]
df2 = dfs[3]
df = df1.join(df2)
</code></pre>
<pre><code> Name POS GP MIN PTS FGM FGA FG% 3PM 3PA 3P% FTM FTA FT% REB AST STL BLK TO DD2 TD3 PER
0 James ... | html|python-3.x|pandas | 1 |
5,174 | 45,888,173 | Nested list (of strings) to matrix of float in python | <p>I wondered what would convert a large list, structured like <code>['12,-1', '0.01,3']</code> to an array like </p>
<pre><code>12 -1
0.01 3
</code></pre>
<p>The following code does this, but I don't think it is efficient:</p>
<pre><code>import numpy as nu
list1 = ['12,-1', '0.01,3']
pp= nu.zeros(s... | <p>The solution using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow noreferrer"><strong><em>numpy.split</em></strong></a> routine:</p>
<pre><code>import numpy as np
list1 = ['12,-1', '0.01,3']
result = np.split(np.array([float(i) for _ in list1 for i in _.split(',')]), ... | list|numpy | 0 |
5,175 | 45,745,932 | Update pandas dataframe columns based on index | <p>In pandas have a dataframe:</p>
<pre><code>df1 = pd.DataFrame({'Type':['Application','Application','Hardware'],
'Category': ['None','None','Hardware']})
</code></pre>
<p>I have the following index to retrieve rows where type contains "application" and Category contains 'None'.</p>
<pre>... | <p>Are you looking for this?</p>
<pre><code>df1.loc[(df1['Type'] == 'Application') & (df1['Category'] == 'None'), 'Category'] = 'New category'
Category Type
0 New category Application
1 New category Application
2 Hardware Hardware
</code></pre> | python|pandas|dataframe | 1 |
5,176 | 46,146,441 | Building a CMake library within a Bazel project | <p>I've written a module on top of a private fork off of TensorFlow that uses <a href="https://github.com/nanomsg/nanomsg" rel="noreferrer">nanomsg</a>. </p>
<p>For my local development server, I used <code>cmake install</code> to install nanomsg (to <code>/usr/local</code>) and accessed the header files from their in... | <p>As Ulf wrote, I think your suggested option 2 should work fine.</p>
<p>Regarding "can I identify if the cmake fails", yes: cmake should return with an error exit code (!= 0) when it fails. This in turn will cause Bazel to automatically recognize the genrule action as failed and thus fail the build. Because Bazel se... | tensorflow|build|cmake|bazel|nanomsg | 6 |
5,177 | 45,824,897 | Add Elements to array | <p>I want to create an empty array and add in a for loop multiple different values. Should I use append or concatenate for this? The code is nearly working.</p>
<pre><code>values=np.array([[]])
for i in range(diff.shape[0]):
add=np.array([[i,j,k,fScore,costMST,1]])
values=np.append([values,add])
</code></pre>
<p>... | <p>Use neither. <code>np.append</code> is just another way of calling <code>concatenate</code>, one that takes 2 arguments instead of a list. So both are relatively expensive, creating a new array with each call. Plus it is hard to get the initial value correct, as you have probably found.</p>
<p>List append is the... | python|arrays|numpy | 3 |
5,178 | 35,491,185 | orientation of normal surface/vertex vectors | <p>Given a convex 3d polygon (convex hull) How can I determine the correct direction for normal surface/vertex vectors? As the polygon is convex, by correct I mean outward facing (away from the centroid). </p>
<pre><code>def surface_normal(centroid, p1, p2, p3):
a = p2-p1
b = p3-p1
n = np.cross(a,b)
if... | <p>This solution should work under the assumption of a convex hull in 3d. You calculate the normal as shown in the question. You can normalize the normal vector with</p>
<pre><code>n /= np.linalg.norm(n) # which should be sqrt(n[0]**2 + n[1]**2 + n[2]**2)
</code></pre>
<p>You can then calculate the center point of y... | numpy|vector-graphics|normals | 1 |
5,179 | 35,651,553 | How to make data frame from python dictionary | <p>I have a python dictionary in below format.</p>
<pre><code>dict={'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]}
</code></pre>
<p>how to create a data frame such that</p>
<pre><code>a b c-----> column names or feature names
1 4 7
2 5 8
3 6 9
</code></pre> | <p>Simply call the <code>DataFrame</code> constructor:</p>
<pre><code>import pandas as pd
pd.DataFrame(dict)
</code></pre> | python|pandas | 0 |
5,180 | 50,751,135 | Iterating operation with two arrays using numpy | <p>I'm working with two different arrays (75x4), and I'm applying a shortest distance algorithm between the two arrays.</p>
<p>So I want to:</p>
<ul>
<li>perform an operation with one row of the first array with every individual row of the second array, iterating to obtain 75 values</li>
<li>find the minimum value, a... | <p>Here are two methods one using <code>einsum</code>, the other <code>KDTree</code>:</p>
<p><code>einsum</code> does essentially what we could also achieve via broadcasting, for example <code>np.einsum('ik,jk', A, B)</code> is roughly equivalent to <code>(A[:, None, :] * B[None, :, :]).sum(axis=2)</code>. The advanta... | python|arrays|numpy|iteration | 3 |
5,181 | 50,994,140 | Problems while plotting label vs datetime in a pandas column? | <p>I have the following pandas dataframe, which consist of datetime timestamps and user ids:</p>
<pre><code> id datetime
130 2018-05-17 19:46:18
133 2018-05-17 20:59:57
131 2018-05-17 21:54:01
142 2018-05-17 22:49:07
114 2018-05-17 23:02:34
136 2018-05-18 06:06:48
324 2018-05... | <p>Something like this?</p>
<p>X axis: date, Y axis: id</p>
<pre><code>from datetime import date
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
# set your data as df
# strip only YYYY-mm-dd part from original `datetime` column
df.datetime = df.datetime.apply(lambda x: str(x)[:1... | python|python-3.x|pandas|matplotlib|seaborn | 0 |
5,182 | 51,031,691 | tensorflow custom loss that are not in the form of sum of single sample errors | <p>I was working through <a href="http://stackabuse.com/tensorflow-neural-network-tutorial/" rel="nofollow noreferrer">here</a>. I am currently modifying the loss. Looking at,</p>
<pre><code> deltas=tf.square(y_est-y)
loss=tf.reduce_sum(deltas)
</code></pre>
<p>I am understanding this to be calculating the squ... | <p>I might be wrong with syntaxes ... but this should give you a general idea. Also, you can optimize it further by vectorization. I have simply put your loss function as it is.<br>
N is the batch size. </p>
<pre><code>def f(C, I, U, N):
loss = 0
for i in range(N):
sum_ = 0
for k in range(N):... | python|tensorflow|machine-learning | 2 |
5,183 | 20,711,838 | How can I approximate the periodicity of a pandas time Series | <p>Is there a way to approximate the periodicity of a time series in pandas? For R, the <code>xts</code> objects have a method called <code>periodicity</code> that serves exactly this purpose. Is there an implemented method to do so? </p>
<p>For instance, can we infer the frequency from time series that do not specify... | <p>This time series skips weekends (and holidays), so it really doesn't have a daily frequency to begin with. You could use <code>asfreq</code> to upsample it to a time series with daily frequency, however:</p>
<pre><code>aapl = aapl.asfreq('D', method='ffill')
</code></pre>
<p>Doing so propagates forward the last ob... | python|pandas | 5 |
5,184 | 20,390,227 | Do I underestimate the power of NumPy.. again? | <p>I don't think I can optimize my function anymore, but it won't be my first time that I underestimate the power of NumPy.</p>
<p>Given: </p>
<ul>
<li>2 rank NumPy array with coordinates</li>
<li>1 rank NumPy array with elevation of each coordinate</li>
<li>Pandas DataFrame with stations</li>
</ul>
<p>Function:</p>... | <p>My suggest is don't use DataFrame for the calculation, use numpy array only. Here is the code:</p>
<pre><code>dist, idx = tree.query(xy, k=8, eps=0, p=1)
columns = ["POINT_X", "POINT_Y", "Elev", "TEMP"]
px, py, elev, tmp = df[columns].values.T[:, idx, None]
tmp = np.squeeze(tmp)
one = np.ones_like(px)
m = np.conca... | python|arrays|numpy | 1 |
5,185 | 33,183,292 | Need Framework to handle Interactions between Redshift and python | <p>I am building a python application with a lot of interactions between Amazon Redshift and local python (sending queries to redshift, sending results to local etc...). My question is: what is the cleanest way to handle such interactions.</p>
<p>Currently, I am using <code>sqlalchemy</code> to load tables directly on... | <p>You can look at the blaze ecosystem for ideas and libraries you might find useful: <a href="http://blaze.pydata.org" rel="nofollow">http://blaze.pydata.org</a></p>
<p>The blaze library itself lets you write queries at a high, pandas-like level, and then it translates the query to redshift (using SQLAlchemy): <a hr... | python|pandas|amazon-s3|sqlalchemy|amazon-redshift | 3 |
5,186 | 66,445,068 | Faster way to create pandas dataframe with many rows | <p>I am reading hdf5 files with large amounts of data . I want to store it in a dataframe (it will contain around 1.3e9 rows). For the moment I am using the following procedure:</p>
<pre><code>df = pd.DataFrame()
for key in ['Column1', 'Column2', 'Column3']:
df[key] = np.array(h5assembly.get(key))
</code></pre>
<p>... | <p>Yes, it is expected that a DataFrame will take longer than Numpy arrays. This is due to various reasons and I won't list them all. Partly due to the may Numpy uses and frees up memory. Numpy operations are implemented in C, a compiled language giving performance benefits.</p>
<p>An interesting comparison between pan... | python|pandas|dataframe|hdf5 | 1 |
5,187 | 66,704,053 | Seaborn Line Plot for plotting multiple parameters | <p>I have dataset as below,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">index</th>
<th style="text-align: center;">10_YR_CAGR</th>
<th style="text-align: center;">5_YR_CAGR</th>
<th style="text-align: center;">1_YR_CAGR</th>
</tr>
</thead>
<tbody>
<tr>
<td styl... | <p>The way facets are typically plotted is by "melting" your <code>analysis_df</code> into id/variable/value columns.</p>
<ol>
<li><p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><strong><code>split()</code></strong></a> the <code>... | python|pandas|matplotlib|seaborn|facet-grid | 2 |
5,188 | 57,583,927 | What to use in place of pandas.Series.filter? | <h2>pandas -> cuDF</h2>
<p>Converting some python written for pandas to run on rapids</p>
<h3>pandas</h3>
<pre><code>temp=df_train.copy()
temp['buildingqualitytypeid']=temp['buildingqualitytypeid'].fillna(-1)
temp=temp.groupby("buildingqualitytypeid").filter(lambda x: x.buildingqualitytypeid.size > 3)
temp['build... | <p>We're still working on <code>filter</code> functionality in <code>cudf</code>, but for now the following approach will implement many <code>filter</code>-like needs:</p>
<pre><code>df_train = pd.DataFrame({'buildingqualitytypeid': np.random.randint(0, 4, 12), 'value': np.arange(12)})
temp=df_train.copy()
temp['buil... | pandas|rapids|cudf | 1 |
5,189 | 24,398,497 | Pandas: How to stack time series into a dataframe with time columns? | <p>I have a pandas timeseries with minute tick data:</p>
<pre><code>2011-01-01 09:30:00 -0.358525
2011-01-01 09:31:00 -0.185970
2011-01-01 09:32:00 -0.357479
2011-01-01 09:33:00 -1.486157
2011-01-01 09:34:00 -1.101909
2011-01-01 09:35:00 -1.957380
2011-01-02 09:30:00 -0.489747
2011-01-02 09:31:00 -0.34... | <p>I'd make sure that this is actually want you want to do, as the resulting df loses a lot of the nice time-series functionality that pandas has.</p>
<p>But here is some code that would accomplish it. First, a time column is added, and the index is set to just the date part of the DateTimeIndex. The <code>pivot</co... | python-2.7|pandas|time-series|dataframe | 1 |
5,190 | 73,056,782 | Adding legend of graph to data-frame plot | <p>I want to add a legend for the blue vertical dashed lines and black vertical dashed lines with label long entry points and short entry points respectively. The other two lines (benchmark and manual strategy portfolio) came from the dataframe.</p>
<p>How do I add a legend for the two vertical line styles?</p>
<p>Here... | <p>Answer: Seems like the easiest way is to replace the for loops:</p>
<pre><code> ax.vlines(x=blue_x_coords, colors="blue", ymin=bottom, ymax=top, linestyles="--", label="Long Entry Points")
ax.vlines(x=black_x_coords, colors="black", ymin=bottom, ymax=top, linestyles=&qu... | python|pandas|matplotlib | 0 |
5,191 | 73,035,839 | How to save the variables as different files in a for loop? | <p>I have a list of csv file pathnames in a list, and I am trying to save them as dataframes. How can I do it?</p>
<pre><code>import pandas as pd
import os
import glob
# use glob to get all the csv files
# in the folder
path = "/Users/azmath/Library/CloudStorage/OneDrive-Personal/Projects/LESA/2022 HY/All"
c... | <p>By “save” I think you mean store dataframes in variables. I would use a dictionary for this instead of separate variables.</p>
<pre><code>import os
data = {}
for f in csv_files:
name = os.path.basename(f)
# read the csv file
data[name] = pd.read_excel(f)
display(data[name])
print()
</code><... | python|pandas|dataframe | 2 |
5,192 | 73,052,176 | Efficient Pandas Row Iteration for comparison | <p>I have a large Dataframe based on market data from the online game EVE.
I'm trying to determine the most profitable trades based on the price of the buy or sell order of an item.
I've found that it takes quite a while to loop through all the possibilities and would like some advice on how to make my code more effici... | <p>Many thanks to @daniel.fehrenbacher for the explanation and suggestions.</p>
<p>In addition to his options, I've found a few myself using this article:
<a href="https://towardsdatascience.com/heres-the-most-efficient-way-to-iterate-through-your-pandas-dataframe-4dad88ac92ee#" rel="nofollow noreferrer">https://toward... | python|pandas|loops | 0 |
5,193 | 70,577,039 | Lists of PyTorch Lightning sub-models don't get transferred to GPU | <p>When using PyTorch Lightning on CPU, everything works fine. However when using GPUs, I get a <code>RuntimeError: Expected all tensors to be on the same device</code>.</p>
<p>It seems that the trouble comes from the model using a list of sub-models which don't get passed to the GPU:</p>
<pre class="lang-py prettyprin... | <p>Submodules contained in lists are not registered and can't be transformed as is.
You need to use <a href="https://pytorch.org/docs/stable/generated/torch.nn.ModuleList.html" rel="nofollow noreferrer">ModuleList</a> instead, i.e.:</p>
<pre><code>...
from torch.nn import ModuleList
...
class TorchModel(LightningModul... | python|pytorch|gpu|pytorch-lightning | 3 |
5,194 | 42,889,987 | Get max value in third dimension from an array of shape (10, 21, 2) to get a final array of (10,21) | <p>I have a state-value matrix as - </p>
<pre><code>in[]: q
out[]: array([[[ 1.78571429e-01, 4.00000000e-01],
[ 2.92307692e-01, 3.91304348e-01],
[ 3.93939394e-01, 4.21052632e-01],
[ 4.41176471e-01, 2.83916084e-01],
[ 1.48148148e-01, -8.08080808e-02],
[ 4.08450704e-01, 2.94117647e-... | <p>You can use <code>numpy.amax</code>, it returns the maximum of an array or maximum along an axis.</p>
<p>Example (your case):</p>
<p>In: <code>np.amax(np.array([[[1,2],[5,6]],[[10,11],[15,16]]]), 2)</code></p>
<p>Out:
<code>array([[ 2, 6], [11, 16]])</code></p> | python|arrays|numpy | 1 |
5,195 | 42,909,783 | Python pandas - select rows based on groupby | <p>I have a sample table like this:</p>
<p>Dataframe: df</p>
<pre><code>Col1 Col2 Col3 Col4
A 1 10 i
A 1 11 k
A 1 12 a
A 2 10 w
A 2 11 e
B 1 15 s
B 1 16 d
B 2 21 w
B 2 25 e
B 2 36 q
C 1 23 a
C 1 24 b
</code></pre>
<p>I'm trying to get all records/... | <pre><code>df['sz'] = df.groupby(['Col1','Col2'])['Col3'].transform("size")
df['rnk'] = df.groupby('Col1')['sz'].rank(method='min')
df['rnk_rev'] = df.groupby('Col1')['sz'].rank(method='min',ascending=False)
df.loc[ (df['rnk'] == 1.0) & (df['rnk_rev'] != 1.0) ]
Col1 Col2 Col3 Col4 sz rnk rnk_rev
3... | python|pandas|group-by | 4 |
5,196 | 27,385,948 | Get list of headers for a given element python | <p>I have a CSV file like below.</p>
<p><img src="https://i.stack.imgur.com/RvM4M.png" alt="Data.csv"> </p>
<p>I'm trying to get the list (not necessarily a Python list structure, but basically all the instances in whichever format) of headers when an ID (element from column1) is given as input, i.e., for example, if... | <p>If <code>Code</code> is your index then the following will do what you want:</p>
<pre><code>In [43]:
df[df.index == 'SFDT-09-04-0001'].dropna(axis=1).columns
Out[43]:
Index(['dID', 'cID', 'sID', 'Other_Data'], dtype='object')
</code></pre> | python|csv|pandas | 0 |
5,197 | 27,229,301 | Calculate 3D variant for summed area table using numpy cumsum | <p>In case of a 2D array <code>array.cumsum(0).cumsum(1)</code> gives the <a href="http://en.wikipedia.org/wiki/Summed_area_table" rel="nofollow noreferrer">Integral image</a> of the array.</p>
<p>What happens if I compute <code>array.cumsum(0).cumsum(1).cumsum(2)</code> over a 3D array? </p>
<p>Do I get a 3D extensi... | <p>Yes, the formula you give, <code>array.cumsum(0).cumsum(1).cumsum(2)</code>, will work. </p>
<p>What the formula does is compute a few partial sums so that the sum of these sums is the volume sum. That is, every element needs to be summed exactly once, or, in other words, no element can be skipped and no element ... | python|algorithm|numpy|data-structures|cumsum | 1 |
5,198 | 26,841,908 | Is it possible to optimize update of a pandas dataframe that involves only some rows? | <p>I have a pandas data frame. One of its columns (let's call it <code>col1</code>) contains nominal values (for example <code>A</code>, <code>B</code>, <code>C</code> and so on). I have also a dictionary that maps these nominal values into numeric values (for example: <code>my_dict = {'A':3, 'B':1, 'C':1}</code>). Now... | <p>Well you can use <code>loc</code> and change just the values <code>1</code> with mapping <code>C</code> with the newly mapped dictionary key of <code>C</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(['A','B','A','C','A','B','C','A','C'],columns=['col1'])
my_dict = {'A':3, 'B':1, 'C':1}
# by the way... | python|optimization|map|pandas | 1 |
5,199 | 26,637,715 | How to extract data from .csv file and create a plot? | <p>I have a .csv file with 24columns x 514rows of data. Each of these column represent different parameters and I wish to study the trends between different parameters.</p>
<p>I am using genfromtxt to import the data as a numpy array such that I can plot the values of two particular columns(e.g. column 9 against colum... | <blockquote>
<p>Also, I have been trying to figure out how to give each column a header in the .csv file. So instead of counting the column number, I can just call the name of that particular column when I do the plotting. Is there a way to do this?</p>
</blockquote>
<p>To give columns in your array names, you need ... | python|csv|numpy|genfromtxt | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.