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 |
|---|---|---|---|---|---|---|
11,100 | 67,790,503 | pivot table with if else condition pandas | <p>i have a table :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>project</th>
<th>location</th>
<th>category</th>
<th>lifecycle</th>
<th>ftecount>3</th>
<th>bpssscore</th>
</tr>
</thead>
<tbody>
<tr>
<td>abc</td>
<td>Bangalore</td>
<td>s</td>
<td>Incre</td>
<td>41</td>
<td>3.98</td>
<... | <p>You could use <code>pd.get_dummies()</code> to achieve the one-hot encoding results, and <code>lambda()</code> function to filter if score is > 3 or not.</p>
<pre><code>df = pd.DataFrame({
'project': ['abc', 'Sys', 'Syst' ,'EPS', 'foss', 'opc'],
'location': ['Bangalore' ,'Bangalore', 'Chennai', 'Bangalor... | python|pandas|dataframe|numpy|machine-learning | 1 |
11,101 | 67,687,448 | How to make an index for a dimension dependent on indices for other dimensions in numpy? | <p>I have a 3D numpy array (<code>A</code>) and I would like to make a 2D array (<code>B</code>) out of it using the following algorithm.</p>
<p>For every index along the first and second dimension I have a value of the index for the third dimension. This mapping can be represented as a 2D array. For example:</p>
<pre>... | <p>I would do smth like:</p>
<pre><code>import numpy as np
A = np.arange(60).reshape(3, 4, 5)
Z = np.random.randint(0, A.shape[-1], size = A.shape[:-1])
B = np.empty(A.shape[:-1])
idx0 = np.arange(A.shape[0]).repeat(A.shape[1])
idx1 = np.arange(A.shape[1]).reshape(1, -1).repeat(A.shape[0], axis = 0).flatten()
idx2 = Z... | python|arrays|numpy|numpy-ndarray | 0 |
11,102 | 67,856,542 | Pandas get year out of date column | <p>I have a dataframe that contains a column named <code>start_year</code>.</p>
<p>It has a lot of styles written inside it and I need it to be written only by here.
For example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">start_year in table</th>
<th style="te... | <p>try via <code>extract()</code> and <code>fillna()</code>:</p>
<pre><code>val=df['start_year in table'].str.extract('(-?[0-9]+)').fillna('2021')
df['start_year as I need']=df['start_year in table'].str.extract('(\d{4})').fillna(val)
</code></pre>
<p>If <code>-</code> sign was not initially present in <strong>'start_... | python|pandas|string|dataframe | 1 |
11,103 | 61,430,647 | How to find dataframe after it is generated in a for-loop using dictionary values? | <p>I want to create a function that creates 3 data frames then takes the element wise-average of the three. The data frames are generated from a loop using a dictionary that was defined in an earlier step, like this:</p>
<pre><code># extracting and organizing data
def density_dataP(filenames):
datasets = ["df_1", ... | <p>In your example, "df_1" is a string in the list <code>datasets</code>, not a variable. If you want to access by name, then you would want <code>datasets</code> to be a dict with a key of <code>df_1</code>, etc. and the value a dataframe.</p>
<p>But you don't need to name items here because all you want is an averag... | python-3.x|pandas | 0 |
11,104 | 53,116,243 | Problems with PyInstaller | <p>I would like to bundle an application into an executable using PyInstaller. I am having issues because of the <code>geopandas</code> library. Currently my script <code>throwaway.py</code> contains only the following import:</p>
<p><code>import geopandas</code></p>
<p>However running <code>pyinstaller throwaway.py<... | <p>This <code>pyinstaller -y -d --clean throwaway.py</code> works for me.</p>
<p><a href="https://i.stack.imgur.com/qSrsg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qSrsg.png" alt="enter image description here"></a></p>
<p>Also, check this <a href="https://stackoverflow.com/questions/51662773/... | python|pyinstaller|geopandas | 2 |
11,105 | 53,321,573 | How do I hide the GPU from one tf::Session() in a multi-session scenario? | <p>I have a C++ program that makes use of two different classifiers running in separate <code>tensorflow::Session</code>s. One of these models needs to run on the GPU, while the second is very small and I'd like for it to run on the CPU.</p>
<p>I tried creating the sessions using:</p>
<pre><code>auto options = tensor... | <p>An easy workaround would be to temporarily set <code>CUDA_VISIBLE_DEVICES=-1</code> using <code>putenv("CUDA_VISIBLE_DEVICES=-1");</code> and reset it after creating the session. </p>
<pre><code>std::string str_tmp = "CUDA_VISIBLE_DEVICES=";
str_tmp += getenv("CUDA_VISIBLE_DEVICES");
putenv("CUDA_VISIBLE_DEVICES=-1... | c++|tensorflow | 1 |
11,106 | 65,791,117 | Problem with calculation od days from date in DataFrame in Python Pandas | <p>I have DataFrame like below:</p>
<pre><code>df = pd.DataFrame({"data" : ["02.01.2020"]})
df["data"] = pd.to_datetime(df["data"])
</code></pre>
<p>And list of special dates:</p>
<pre><code>special_date = pd.to_datetime(["04.01.2020", "01.01.2020"], dayfirst=... | <p>You can simply use the <code>-</code> sign operator:</p>
<pre><code>df = pd.DataFrame({"data" : ["02.01.2020"]})
df["data"] = pd.to_datetime(df["data"],dayfirst=True)
special_date = pd.to_datetime(["04.01.2020", "01.01.2020"], dayfirst=True)
df['col1'] = ab... | python|pandas|dataframe|date | 0 |
11,107 | 65,694,579 | Pivot table while maintaining the index of the row | <p>I have following dataframe,</p>
<pre><code>df = pd.DataFrame({'col1': ["ip", "state", "ip", "state", "jobs", "ip", "state", "status"],
'col2': ["10-0-11-99", "running","10-0-11-19", "... | <p>I believe the simplest and straight forward way to do it is to loop over your <code>df</code> with simple logic, so we don't need worry about index:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col1': ["ip", "state", "ip", "state", "jobs", "ip", ... | python|pandas|dataframe | 1 |
11,108 | 65,741,571 | Numpy: multiplying (1/2)^k for each row of np.array for each array in a list | <p>Suppose I have the following list of array</p>
<pre><code>dat = [np.array([[1,2],[3,4]]), np.array([[5,6]]), np.array([[1,2],[7,8],[2,3]]), np.array([[1,2],[3,4]])]
</code></pre>
<p>Now, for each elements in the list, I want to multiply the row of the array with (1/2)^k where k is the (index + 1) for each row.</p>
<... | <p>No, unfortunately not. As you have a list of np.arrays with different shapes, only way to process that list is using a for loop. You could use list comprehension, but it is more or less the same thing. (It uses for loop)</p>
<pre class="lang-py prettyprint-override"><code>dat = [e * (1/2)**np.arange(1, e.shape[0]+1)... | python|python-3.x|numpy|numpy-ndarray|numpy-einsum | 2 |
11,109 | 65,492,537 | Pandas calculate percent growth over rows | <p>I've created the following pandas dataframe and try to calculate the growth in % between the years given in Col2:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Jan</th>
<th>Feb</th>
<th>Mrz</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>2019<... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pct_change.html" rel="nofollow noreferrer"><code>pct_change</code></a> with <code>groupby</code></p>
<pre><code>u = (df[['Col1']].join(df.drop("Col2",1).groupby('Col1').pct_change()
.mul(100).round())
... | python|pandas | 2 |
11,110 | 63,606,332 | Is there a way to use the rolling function to compute statistics on multiple columns in Python? | <p>I am working on a large dataset in which I am computing a rolling window calculation based on time. I need to find the slope, y-intercept and r2 between two columns (co2d and co).</p>
<p>Based on this code:</p>
<pre><code>df.rolling('20s', min_periods=2).insert_function_here()
</code></pre>
<p>I am looking for a wa... | <ul>
<li>Use <code>.apply</code> to apply <code>.rolling</code> and use <code>.agg</code> for some custom function.</li>
<li>This can be used to make a column-wise calculation with <code>axis=1</code>, or row-wise with <code>axis=0</code></li>
</ul>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
im... | python|pandas|numpy|data-science | 0 |
11,111 | 63,669,458 | How to convert values of one column into column headers and other column values into rows? | <p>This is how my df looks like.</p>
<pre><code> A B C D E F
xyz abc aa 100 qq brc,pqr,lmn
xyz abc bb 150 qq lmn,brc,ppq
xyz abc cc 80 qq lmn,pqr
abc pqr cc 99 qq pqr,brc,lmn
abc pqr aa 180 qq brc... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>DataFrame.join... | python|pandas|dataframe | 1 |
11,112 | 71,869,665 | Extract values from different columns in Python | <p>I am looking for a more Pythonic way to extract values from columns, that comes in pairs of two. Here is my solution so far, but I am looking for a faster (possible without iteration???) way.</p>
<pre><code>>>> import pandas as pd
>>> data = {
... "Home Team": ["A", "B&... | <p>Solution with create <code>MultiIndex</code> by split columns names by space and then reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> with filter <code>Team</code>s:</p>
<pre><code>df.columns = df.co... | python-3.x|pandas | 2 |
11,113 | 55,247,931 | Context expansion for speech frames in tensorflow or keras | <p>Assume I have a tensor of shape [batch_size, T, d] where
T is number of frames for a speech file and d is the dimension of MFCC. Now I would like to expand the context for the left and right frames like this function in numpy:</p>
<pre><code>def make_context(feature, left, right):
'''
Takes a 2-D numpy feature arra... | <p>You can use <code>tf.map_fn</code> and <code>tf.py_func</code> to implement this function in tensorflow. <code>tf.map_fn</code> can be used to handle every element in batch. <code>tf.py_func</code> can apply this function to element. For example:</p>
<pre><code>import tensorflow as tf
import numpy as np
def make_c... | tensorflow|keras | 0 |
11,114 | 55,309,176 | How to correct Numpy and TPOT array shapes error? | <p>I'm trying to pass a <code>feature</code> and <code>label</code> numpy array into <code>train_test_split</code>. The features are a single column (datetime dtype converted to integer). There are 900 observations in the <code>labels</code> array.</p>
<p><code>features.shape</code> returns <code>(1101, 1)</code></p>
... | <p>Turns out TPOT cannot solve multi label regression problems at this time, that was my problem passing in a a label size of <code>(101, 900)</code> isn't going to work. If this is reduced to a single column the code works fine.</p> | python|pandas|numpy|scikit-learn|train-test-split | 1 |
11,115 | 56,446,645 | Beam Search Decoder Tensorflow 2.0 | <p>I am looking to implement a sequence to sequence neural net with attention and beam search in Tensorflow 2.0 alpha. While the tutorials on their website have been very useful, I am having trouble figuring out the best way to implement beam search since the contrib library is deprecated - can anyone point me in the r... | <p>Few of the Tensorflow 1.x APIs are moved to different APIs in Tensorflow 2.x.
Tf.contrib is one such library which partly moved to Tensorflow addons.</p>
<p>For the <code>tf.contrib.seq2seq.BeamSearchDecoder</code> is moved to <code>tfa.seq2seq.BeamSearchDecoder in TFv2.x.</code></p>
<pre><code>tfa.seq2seq.BeamSearc... | tensorflow | 0 |
11,116 | 66,870,707 | pandas percent of group by two columns | <p>i am looking for a solution to get in the result like the column "result percent of colA". as example, the value represents the percentage of cats (colB) in the month januar (colA), compared to cats and dogs in januar.</p>
<pre><code>import pandas as pd
# set up dataframe
df_ex = pd.DataFrame({'colA':['20... | <p>You can divide column by sum of <code>colC</code> per <code>colA</code> with same size like original with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a>:</p>
<pre><code>df_ex['perc']... | python|pandas | 2 |
11,117 | 66,897,438 | Calculating with conditions over a mask on numpy without loop | <p>I have a numpy array x</p>
<pre><code>x = np.array([[10, 20, 30], [40, 50, 60]])
</code></pre>
<p>and I have a mask m</p>
<pre><code>m = np.array([[True, False, True], [False, True, False]])
</code></pre>
<p>I would like to calculate with conditions as follows:</p>
<pre><code>y = 10*x[i, j] if m[i, j] == True else 2... | <p>Try this:</p>
<pre><code>x[m] *= 10
x[~m] *= 2
print(x)
</code></pre>
<p>Output:</p>
<pre><code>array([[100, 40, 300],
[ 80, 500, 120]])
</code></pre> | python|numpy | 2 |
11,118 | 47,299,378 | Correctly loading a model to resume training (meta graph, ckpts) | <p>I'm having trouble loading a model to <strong>resume</strong> training.
I'm using a simple two-layered-NN (Fully connected) on a cifar data set for practice. </p>
<h1>NN Setup:</h1>
<pre><code>#full_connected_layers
import tensorflow as tf
import numpy as np
#input _-> hidden ->
def inference(data_sam... | <p>I usually did this sequence of operations:</p>
<ol>
<li><p>Initialize</p></li>
<li><p>Restore</p></li>
</ol>
<p>This translates to this kind of code:</p>
<pre><code>saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.restore(sess, tf.train.latest_checkpoin... | python|tensorflow|deep-learning | 6 |
11,119 | 47,198,593 | How to Improve the model accuracy in face detection using MTCNN with tensorflow | <p>I am doing face detection using tensorflow with MTCNN detection. successfully I got the face detection and found the number of detected faces. In the detection module some of the faces have not detected.
How can I resolve that and How do I want to improve the model accuracy or confidence score.</p>
<p>I am thinking... | <p>There are few ways that I am aware of which you can use to improve your model accuracy:</p>
<ol>
<li><p>First, you need to identify if you are laking accuracy in your training or in your testing set. If you are getting less accuracy in your training set then you should change the hyperparameters or add more layers ... | python|opencv|tensorflow|deep-learning | 1 |
11,120 | 47,370,914 | Comparing two numbers lists with each other in Python | <p>I have a data frame (possibly a list):</p>
<pre><code>A = ['01', '20', '02', '25', '26']
B = ['10', '13', '14', '64', '32']
</code></pre>
<p>I would like to compare list 'a' with list 'b' in the following way:</p>
<p><a href="https://i.stack.imgur.com/AESr0.png" rel="nofollow noreferrer"><img src="https://i.stack... | <p>You can perform a couple of string slicing operations and then merge on the common digit.</p>
<pre><code>a
A
0 01
1 20
2 02
3 25
4 26
b
B
0 10
1 13
2 14
3 64
4 32
a['x'] = a.A.str[-1]
b['x'] = b.B.str[0]
b['B'] = b.B.str[1:]
m = a.merge(b)
</code></pre>
<p>You could also do this in a single ... | python|pandas | 1 |
11,121 | 68,332,827 | unknown number of columns into one | <p>I have data frame contains unknown number of columns like below.</p>
<pre><code> Start End 0 1 2 3 4 5 6 ...
7/5/2021 22:04 7/6/2021 6:26 E1234 H5511 T3333 H2222
7/5/2021 16:35 7/5/2021 16:35 T3456 (Tafresh)
7/5/2021 ... | <p>Let's try <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> + <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.droplevel.html" rel="nofollow noreferrer"><code>droplevel</code></a> + <a href="https://pandas... | python|pandas | 2 |
11,122 | 68,154,629 | How to convert results from sunset and sunrise data using astral package into a dataframe? | <p>I'm trying to find a way to convert my results I got from calculating the dawn and dusk times from a certain time interval using the <code>astral</code> package at a certain city into a dataframe. The problem is that once I got the results of the sunrise and sunset information, I have a hard time converting it into ... | <p>You can use list comprehension from <code>x</code>:</p>
<pre><code>pd.DataFrame([sun(city.observer, date=z) for z in x])
</code></pre>
<p>Output:</p>
<pre><code> dawn sunrise noon \
0 2020-12-09 15:16:... 2020-12-09 15:54:... 2020-12-09 20:03:...
1 2020-12-10 15:17:.... | python|pandas|dataframe|date|datetime | 1 |
11,123 | 59,335,969 | Delimiter string splitting | <p>I have a dataset which has some values delimited by '\n' and some values delimited by '\n\n'. I have written some code that works for each case separately but I was wondering if there is a method to include both of these delimiters so it splits them whether there is '\n' or '\n\n'. In the current setting it is throw... | <p>You can use regex with Pandas split:</p>
<pre><code>temp[[1,4]] = temp[1].str.split('\n+', expand = True)
</code></pre>
<p>This splits if there’s at least one <code>\n</code>.</p> | python|numpy|dataframe|delimiter | 2 |
11,124 | 59,354,467 | Why am I recieving key error after slicing my data? | <p>I have a code that slices data and then suppose to calculte different indices according to the columns.</p>
<p>My code worked well but today I had to slice differently the data and since then I get keyerror whenever I try to compute the indices.</p>
<p>unfortinatly I can't share my original data but I hope this co... | <p>Try changing the last line to:</p>
<pre><code>filter_plants['NDVI']=(filter_plants[801.03]-filter_plants[680.75])/(filter_plants[801.03]+filter_plants[680.75])
</code></pre> | python|pandas | 1 |
11,125 | 57,043,538 | Covert list of lists to dataframe | <p>Although I am quite experienced in <code>pandas</code> I always find that I miss some basic things.</p>
<p>Specifically, I do the following:</p>
<pre><code>data = [[1, 2, 3, 3, 4], [1, 1, 1, 2, 1], [5, 6, 7, 8, 9]]
data = np.array(data)
names = ['A', 'B', 'C']
df = pd.DataFrame(data=data, columns=names)
print(... | <p>You may need adding T </p>
<pre><code>df = pd.DataFrame(data=data.T, columns=names)
df
Out[509]:
A B C
0 1 1 5
1 2 1 6
2 3 1 7
3 3 2 8
4 4 1 9
</code></pre> | python|pandas|numpy | 3 |
11,126 | 51,063,631 | How to create correctly an estimator with TensorFlow | <p>I would want to create a neural network with Python and I have some problems with the estimator.</p>
<p>First, I read some <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/EstimatorSpec" rel="nofollow noreferrer">documentation</a> about estimators specification, and I think I created my estimators t... | <p>You have given the Estimator an <code>EstimatorSpec</code> directly and it isn't correct.</p>
<p><code>model_fn</code> should be a function which returns an instance of <code>EstimatorSpec</code>.
This function will be called later on. As a result it is complaining that what you have give is not callable.</p>
<p><... | python|tensorflow|tensorflow-estimator | 1 |
11,127 | 50,852,672 | Python: Assign value to a new column in Pandas as list using other columns | <p>I have below pandas dataframe:</p>
<pre><code>Name1 Name2 Score1 Score2
Bruce Jacob 3 4
Aida Stephan 0 1
</code></pre>
<p>I want to create a new column in the dataframe "list_score" which is a list of score 1 and 2</p>
<p>Expected result:</p>
<pre><code>Name1 Name2 Score1 S... | <p>Use <code>zip</code> with convert tuples to lists:</p>
<pre><code>df['list_score'] = [list(x) for x in zip(df['Score1'], df['Score2'])]
</code></pre>
<p>Or:</p>
<pre><code>df['list_score'] = list(map(list, zip(df['Score1'], df['Score2'])))
print (df)
Name1 Name2 Score1 Score2 list_score
0 Bruce Jacob ... | python|pandas | 3 |
11,128 | 66,598,619 | How to use UDF(user defined function) on spark structured streaming? | <p>I have made a little search. <a href="https://stackoverflow.com/questions/40006395/applying-udfs-on-groupeddata-in-pyspark-with-functioning-python-example">this answer</a> tells me that I can use UDF on GroupedData, it works and I can handle those rows and columns in GroupData with my own function.</p>
<p>According ... | <p>In Spark 3 you can use the <code>applyInPandas</code> instead, without explicit <code>@pandas_udf</code> (see <a href="https://spark.apache.org/docs/latest/api/python/user_guide/arrow_pandas.html#grouped-map" rel="nofollow noreferrer">documentation</a>):</p>
<pre><code>def g(df):
#whatever user-defined code
wo... | pandas|apache-spark|spark-structured-streaming | 0 |
11,129 | 57,661,133 | How can a histogram be transformed into a variety of predefined constituent histograms? | <p>Let's say I want to make a meal that has a specific nutritional composition from a variety of ingredients:</p>
<pre><code>meal = a * ingredient_1 + b * ingredient_2 + c * ingredient_3
</code></pre>
<p>A little like how a Fourier transform can transform a waveform into a composition of sine waves, how could a meal ... | <p>I guess you want something like this:</p>
<pre><code>#A
a1=df.loc[df.index.values.tolist()[1:],'calories'].tolist()
a2=df.loc[df.index.values.tolist()[1:],'carbs'].tolist()
a3=df.loc[df.index.values.tolist()[1:],'fat'].tolist()
A=np.array([a1,a2,a3])
#B
b1=df.loc[df.index.values.tolist()[0],'calories'].tolist()
b2=... | pandas|dataframe|histogram|fft | 1 |
11,130 | 57,563,806 | Filtering rows in DataFrame with a numeric value OR NaN in column | <p>I want to remove all rows with a numeric value of less than 15 in a column, but I want to retain those rows if the value is NaN. How do I this?</p>
<p>This line removes all rows with values less than 15, but it <strong>also</strong> removes all NaN rows: </p>
<pre><code>df2 = df[(df['columnA'] >= 15)]
</code><... | <p>I believe what you are looking for is <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.isnull.html" rel="nofollow noreferrer">pandas.isnull</a>:</p>
<pre><code>import pandas as pd
df2 = df[(df['columnA'] >= 15) | pd.isnull(df['columnA'])]
</code></pre> | python|pandas | 6 |
11,131 | 70,870,302 | Create lambda function to apply to select df columns | <p>I have the following df:</p>
<pre><code>id header1 header2 diabetes obesity hypertension/high blood pressure. . .
1 metabolism diabetes no no no
2 heart issue heart disease None None None
3 obesity diabetes yes no no
4 ... | <p>First create disease column index and disease names series (the latter is used to capture "hypertension").</p>
<p>Then simply apply a function that first counts the "yes" answers and searches for disease names among the "yes" answers</p>
<pre><code>headers = ['header1', 'header2']
disea... | python|pandas|dataframe|lambda | 1 |
11,132 | 38,034,782 | Tensor Flow all predictions are 0 | <p>I'm running the following code for TensorFlow and all the probabilities are <code>NaN</code> and all the predictions are <code>0</code>. The accuracy works, however. I have no idea how to debug this. Any and all help is appreciated.</p>
<pre><code>x = tf.placeholder("float", shape=[None, 22])
W = tf.Variable(tf.zer... | <p>The issue stems from this line in your code:</p>
<pre><code>W = tf.Variable(tf.zeros([22, 5]))
</code></pre>
<p>Initializing your weights to zero is a common mistake when defining a neural network. <a href="http://cs231n.github.io/neural-networks-2/#init" rel="nofollow noreferrer">This article</a> explains the rea... | python|machine-learning|tensorflow|prediction | 5 |
11,133 | 37,715,038 | How to get pandas.read_csv not to perform any conversions? | <p>For example, the values in '/tmp/test.csv' (namely, <code>01</code>, <code>02</code>, <code>03</code>) are meant to represent <em>strings</em> that happen to match <code>/^\d+$/</code>, as opposed to integers:</p>
<pre><code>In [10]: print open('/tmp/test.csv').read()
A,B,C
01,02,03
</code></pre>
<p>By default, <c... | <p><code>df = pd.read_csv('temp.csv', dtype=str)</code></p>
<p>From the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer">docs</a>:</p>
<pre><code>dtype : Type name or dict of column -> type, default None
Data type for data or columns. E.g. {‘a’: np.float64, ‘b’:... | pandas | 11 |
11,134 | 37,727,097 | List of dictionary in python as HTML Table format | <p>I have list of dictionary as the below format</p>
<pre><code>[{'duration': 0.7, 'project_id': 3, 'resource': u'Arya Stark', 'activity': u'Development'},
{'duration': 0.9, 'project_id': 4, 'resource': u'Ned Stark', 'activity': u'Development'},
{'duration': 2.88, 'project_id': 7, 'resource': u'Robb Stark', 'activity'... | <p>IIUC Here is a solution using <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="noreferrer"><code>pandas</code></a>:</p>
<pre><code>import pandas as pd
dict_data = [{'duration': 0.7, 'project_id': 3, 'resource': u'Arya Stark', 'activity': u'Development'},
{'duration': 0.9, 'project_id': 4, 'reso... | python|python-2.7|pandas|openerp|list-processing | 13 |
11,135 | 37,735,403 | is there pandas.filter for values (not row or column labels)? | <p>Right now I have to do the following:</p>
<pre><code>ix=None
for ixi in [res[col].str.contains('string') for col in res.columns]:
if ix is not None:
ix = ix | ixi
else:
ix = ixi
res[ix]
</code></pre>
<p>Here is the notebook:</p>
<p><a href="https://gist.github.com/denfromufa/12379b62ef6eec... | <p>you can use <code>sum(axis=1)</code>:</p>
<pre><code>In [59]: res[res.sum(axis=1).str.contains('e|A')]
Out[59]:
ca cb cc
rb dmv enw fox
rc gpy hqz irA
</code></pre>
<p>or <code>apply()</code> in conjunction with <code>.str.contains()</code> and <code>any()</code>:</p>
<pre><code>In [51]: res[res.ap... | python|performance|numpy|pandas|dataframe | 1 |
11,136 | 31,300,333 | Pandas dataframe: propagate True values if timestamp is identical | <p>Best described by an example. Input is</p>
<pre><code> ts val
0 10 False
1 20 True
2 20 False
3 30 True
4 40 False
5 40 False
6 40 False
7 60 True
8 60 False
</code></pre>
<p>desired output is</p>
<pre><code> ts val
0 10 False
1 20 True
2 20 True
3 30 True
4 ... | <p>You can use <code>groupby</code> on column 'ts', and then <code>apply</code> using <code>.any()</code> to determine whether any of <code>val</code> is <code>True</code> in the cluster/group.</p>
<pre><code>import pandas as pd
# your data
# =====================
print(df)
Out[58]:
ts val data
0 10 Fals... | python|pandas|dataframe | 3 |
11,137 | 47,841,525 | Concatenate cross tab values with dataframe? | <p>I have a dataframe <code>df</code> of the following type:</p>
<pre><code>ID Result Other_val
1 A y
2 B x
2 A x
3 C abc
</code></pre>
<p>After using <code>pd.crosstab(df.ID, df.Result)</code>, I get a crosstab like this:</p>
<pre><code>Result A B C
ID
1 1 0 0
2 1 ... | <p>I think what you're looking for is <code>pd.crosstab([df.ID, df.Other_val], df.Result)</code>, because you need to group ID and Other_val.</p>
<pre><code>In [5]: pd.crosstab([df.ID, df.Other_val], df.Result)
Out[5]:
Result A B C
ID Other_val
1 y 1 0 0
2 x 1 1 0
3 abc ... | python|pandas|dataframe|data-manipulation | 3 |
11,138 | 49,069,195 | What input does neural network need for making predictions? | <p>I have a <em>very</em> beginner question. I have fitted a model, that predicts a stock price. What input does the neural network need to make a prediction? If I have a batch size of 30, do I need to feed in 29 last known prices?
By the way, here is my code:</p>
<pre><code> # First step, import libraries.
import ... | <p>Like Maximilian wrote in his comment, the input that your network takes for predictions should have the same shape as the input it took during training. In this case, we cant tell for sure what that is, because there's no training going on in your code; it looks like you're loading a model that's already trained wit... | python|tensorflow|neural-network|keras | 0 |
11,139 | 48,910,956 | Pandas `agg` to list, "AttributeError / ValueError: Function does not reduce" | <p>Often when we perform <code>groupby</code> operations using pandas we may wish to apply several functions across multiple series.</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>groupby.agg</code></a> seems the nat... | <p>After much investigation, I have discovered this is a bug, which will be fixed in a future release of pandas.</p>
<p>The offending code in <a href="https://github.com/pandas-dev/pandas/blob/0.22.x/pandas/core/groupby.py" rel="nofollow noreferrer">0.22.x groupby.py</a>, notice the <code>isinstance(res, list)</code>:... | python|pandas|group-by|pandas-groupby | 2 |
11,140 | 70,220,261 | How to add text to a graph in python | <p>I am trying to add text inside the below graph using figtext() but the written code below does not work. I appreciate any help. <a href="https://i.stack.imgur.com/e25E6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e25E6.png" alt="enter image description here" /></a></p>
<pre><code>import numpy ... | <p>The problem, as I think, is in <em>x</em> and <em>y</em> coordinates that you used.</p>
<p>Coordinates in <em>plt.figtext</em> (without transformation) are in <strong>figure</strong>
coordinates, i.e. floats between <em>0</em> and <em>1</em>.
This detail looks another way in <em>plt.text</em>, where the default is
<... | python|python-3.x|numpy|matplotlib|scipy.stats | 1 |
11,141 | 70,158,120 | Loop through nested dictionary | <p>I have nested dictionary which look like this:</p>
<pre><code>{
'location': {0: 'London', 1: 'London', 2: 'London', 3: 'London', 4: 'London', 5: 'London', 6: 'London'},
'attraction': {0: 'museum', 1: 'museum', 2: 'museum', 3: 'museum', 4: 'museum', 5: 'museum', 6: 'museum'},
'name': {0: 'London Museum', 1: 'British... | <p>You need to specify <code>orient=records</code> in <code>to_dict()</code>:</p>
<pre><code>>>> df.to_dict("records")
[{'location': 'London',
'attraction': 'museum',
'name': 'London Museum',
'rate': 4.6,
'totalRates': 13873,
'tag': 'Muzeum',
'address': '150 London Wall',
'description'... | python|pandas|dataframe|dictionary|django-context | 3 |
11,142 | 70,357,564 | PyTorch with GPU is not working but working fine with CPU | <p>My codes were working fine before but suddenly they stop working, without any error or warning.
this is the setting they were working fine.</p>
<p><a href="https://i.stack.imgur.com/kCEJw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kCEJw.png" alt="enter image description here" /></a></p>
<p>Af... | <p>I have the same type of problems, but with RTX 3060. I think the problem is the torch version.</p>
<p>Using torch == 1.11.0, I can move tensors to GPU, but with pastest versions can't do this.</p>
<pre><code>Torch Geometric don't use torch=1.11.0 at the time I'm writing.
NVIDIA GeForce RTX 3060 with CUDA capability... | pytorch|gpu | 0 |
11,143 | 56,068,564 | How to interpolate hourly data at second values? | <p>I have following pandas dataframe <strong>df</strong> :</p>
<pre><code> L_Time U_Time Eval_Time L_Flux U_Flux
2018-05-01 04:30:00 2018-05-01 05:30:00 2018-05-01 05:23:45 100 200
2018-05-01 07:30:00 2018-05-01 08:30:00 2018-05-01 07:44:11 100 200
<... | <p>You can just do your own interpolation as it is between just 2 columns. Your data seems incorrect though, as you are asking to extrapolate in the second row. Regardless the following will give you an answer</p>
<pre><code>df = pd.DataFrame(data={'L_Time':['2018-05-01 04:30:00','2018-05-03 07:30:00'],
'U_Time':[... | python|pandas | 2 |
11,144 | 56,021,340 | Search for text contained in any row of a pandas DataFrame | <p>I have the following <code>DataFrame</code></p>
<pre><code>pred[['right_context', 'PERC']]
Out[247]:
right_context PERC
0 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 0.000197
1 San Pedro xxxxxxxxxxxx 0.572630
2 zxxxxxxxxxxxxxxxxxxxxxxxxxxx 0.572630
3 ... | <h1><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> & <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.upper.html" rel="nofollow noreferrer"><code>str.upper</code>... | python|pandas|dataframe | 2 |
11,145 | 56,090,573 | How to parse this log using python regex and export to excel with pandas (optional)? | <p>I have a log file in the below format. For each line I need to capture 3rd column e.g <code>0102b69880c4b330</code>, corresponding message <code>DM_FT_INDEX_T_INIT_INDEX_AGENT_MSG</code> and their respective counts (please see the output). I thought using regular expressions makes solution easier for me.</p>
<p><st... | <p>Starting with the input data as text:</p>
<pre><code>txt = """
2019-05-05T00:05:11.507245 12090[12090] 0102b69880c4b330 [DM_FT_INDEX_T_INIT_INDEX_AGENT_MSG] info: Attempting to status Index Agent Instance host-address_9200_IndexAgent
2019-05-05T00:05:11.759829 12090[12090] 0102b69880c4b330 [DM_FT_INDE... | python|regex|pandas|python-re | 1 |
11,146 | 56,125,207 | Python and Pandas: apply per multiple columns | <p>I am new to python and I was successful in using apply in a dataframe to create a new column inside a dataframe.</p>
<pre><code>X['Geohash']=X[['Lat','Long']].apply (lambda column: geohash.encode(column[0],column[1],precision=8), axis=1)
</code></pre>
<p>this is calling the geohash function with the latitudes and ... | <p>You can do this by creating an "empty" dataframe with 20 columns, and then using df.columns[i] to loop through your other dataframes - something like this:</p>
<pre><code>output = pd.DataFrame({i:[] for i in range(20)})
</code></pre>
<p>This creates an empty dataframe with all the columns you wanted (numbered). </... | pandas|multiple-columns|apply | 1 |
11,147 | 56,041,988 | Sorting datetime objects by hour to a Pandas dataframe, then visualize to histogram with Matplotlib | <p>I need to sort viewers by hour to a histogram. I have some experience using Matplotlib to do that, but <b>I can't find out what is the most pragmatic way to sort the dates by hour.</b></p>
<p>First I read the data from a JSON file, then store the two relevant datatypes in a pandas Dataframe, like this:</p>
<pre cl... | <pre><code>df = pd.read_json('data/data.json')
df['time'] = pd.to_datetime(df['time'])
#timedelta is a more appropriate data type for session_duration
df['session_duration'] = pd.to_timedelta(df['session_duration'], unit='s')
# Example filtering
df_short_duration = df[df['session_duration'].dt.total_seconds() <= 6... | python|pandas|matplotlib|data-science|data-analysis | 1 |
11,148 | 64,780,787 | Percentage differences between rows with matching column values with pandas | <p>I'm looking for a pandas expression that will find the margin of victory in percentage terms between the two candidates by finding the candidate with the greater amount of votes, finding what percentage of the county votes they have and then subtracting the lesser of the two candidates' vote total percentage to find... | <p>Here is a very awkward solution, but it works. The function <code>do_county</code> processes one county at a time.</p>
<pre><code>def do_county(data):
return (data.set_index('CANDIDATE').sort_values('VOTES') \
/ data['VOTES'].sum())\ # Normalize
.diff().tail(1) # Take the diff between... | python|pandas|dataframe | 0 |
11,149 | 39,695,461 | Finding value of another attribute given an attribute | <p>I have a CSV that has multiple lines, and I am looking to find the <code>JobTitle</code> of a person, given their name. The CSV is now in a DataFrame <code>sal</code> as such:</p>
<pre><code>id employee_name job_title
1 SOME NAME SOME TITLE
</code></pre>
<p>I'm trying to find the <code>JobTitl... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>sal[sal.employee_name == 'name']
</code></pre>
<p>If need select only some column, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas... | python|csv|pandas | 2 |
11,150 | 39,672,915 | Function on each row of pandas DataFrame but not generating a new column | <p>I have a data frame in pandas as follows:</p>
<pre><code> A B C D
3 4 3 1
5 2 2 2
2 1 4 3
</code></pre>
<p>My final goal is to produce some constraints for an optimization problem using the information in each row of this data frame so I don't want to generate an output a... | <p><code>.apply</code> will attempt to convert the value returned by the function to a pandas Series or DataFrame. So, if that is not your goal, you are better off using <code>.iterrows</code>:</p>
<pre><code># In pseudocode:
for row in df.iterrows:
constrained = Computation(row)
</code></pre>
<hr>
<p>Also, your... | function|pandas|dataframe | 1 |
11,151 | 39,655,397 | Calculate z-score in data bunch but excluding N.A | <p>So I got this bunch of data with N.A. values in them:</p>
<p><a href="http://i.stack.imgur.com/XVlKo.jpg" rel="nofollow">Data Dump</a></p>
<p>So how do I get the z-score of each column while excluding the N.A. values? Such that the z-score output looks like this?</p>
<p><a href="http://i.stack.imgur.com/S5XiW.jpg... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>replace</code></a> first <code>N.A.</code> to <code>NaN</code> and convert values to <code>float</code>:</p>
<pre><code>df = df.replace({'N.A.': np.nan}).astype(float)
for col in df.colu... | python|pandas | 2 |
11,152 | 44,054,629 | reading a txt file and use some specific portion of it to get an array | <p>I am trying to read a txt file that is a mix of string and float
like this:</p>
<pre><code>n_rows=55; #This describes the mask array below, not the experiment!!
n_cols=32;
# Note that 'columns' run down and rows run across!
mask = [
/*RC1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 ... | <p>Your regular expression is not correct. You need to escape '*' and instead of [0-31] you need [0-9]+, i.e. one or more digits. For example,</p>
<pre><code>import re
import numpy as np
def get_line(filename):
pattern = re.compile('^/\* *[0-9]+ *\*/(.*)')
with open(filename, 'r') as file:
for lin... | python|numpy | 1 |
11,153 | 44,057,142 | Broadcasting numpy matrices using arrays of indices | <p>I have these numpy objects:</p>
<pre><code>>>> x = np.matrix([[1],[2],[3]])
>>> i = ([1,2],0)
>>> y = np.matrix([[4],[5]])
</code></pre>
<p>When I do <code>x[i]</code> I get as I expect:</p>
<pre><code>>>> x[i]
matrix([[2],
[3]])
</code></pre>
<p>However, when I try to... | <p>Don't use <code>numpy.matrix</code>. It's terrible. It causes so many weird incompatibilities and has so many inconsistencies, including this one.</p>
<p>Use <code>numpy.array</code>. With arrays, <code>x[i]</code> is one-dimensional, and assigning a one-dimensional <code>y</code> of equal shape to <code>x[i]</code... | python|numpy|array-broadcasting | 1 |
11,154 | 69,483,288 | Create multiindex columns based on column names and positions | <p>I have a pandas dataframe with column names like:</p>
<pre><code>id name ... class maths_marks1 maths_marks2 eng_marks1 eng_marks2
</code></pre>
<p>Now I want to create Multiindex columns like: first column is <code>id</code> so it remains as is, then <code>maths</code> and <code>eng</code> in level0 while <code>mar... | <p>Prepend <code>student_data_</code> in each col which is not contain '_' and split columns to convert them as <code>MultiIndex</code>:</p>
<pre><code>df.columns = ['student_data_' + col if '_' not in col else col
for col in df.rename(columns={'id': '_id'}).columns]
df.columns = df.columns.str.rsplit... | python|pandas | 1 |
11,155 | 69,654,858 | Problem in sorting a column of a dataframe | <p>I am trying to put in order a column of a dataframe using the following step</p>
<p><code> data_crian = data_crian.sort_values(by = 'Flp_CO')</code></p>
<p>But I get this message everytime I try to run it:</p>
<p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(... | <p>I created a simple csv file with one column:</p>
<p><a href="https://i.stack.imgur.com/GDPBi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GDPBi.png" alt="enter image description here" /></a></p>
<p>Here is the code:</p>
<pre><code>import pandas as pd
import numpy as np
import os
filename = os.... | python|pandas|dataframe|sorting | 0 |
11,156 | 69,516,118 | Pandas compare Object columns | <p>I have two Object columns that contain a list of numbers that I create on panda from 2 CSV files.
I want to compare between two of them and add a new column that will give me the number of identical numbers.</p>
<p>For example:
Table 1:
<a href="https://i.stack.imgur.com/cUgoN.png" rel="nofollow noreferrer">Numbers ... | <p>table1:</p>
<pre><code>df1 = pd.DataFrame({
'a':1, 'b':2, 'c':3, 'd':4
}, index=range(1))
</code></pre>
<p>table2:</p>
<pre><code>df2 = pd.DataFrame({
'a':[1, 2, 2, 2],
'b':[2, 4, 3, 1],
'c':[3, 5, 6, 3],
'd':[4, 7, 7, 5],
}, index=['01/01/2021', '02/01/2021', '03/02/2021', '04/02/2021'])
</cod... | python|pandas|compare | 0 |
11,157 | 53,891,743 | Pandas- increment (Year, Month) multiindex and Year & Month columns | <p>With a dataframe <code>df</code> like:</p>
<pre><code> YEAR MONTH VALUE
(2017,1) 2017 1 1
(2017,2) 2017 2 1
(2017,3) 2017 3 1
</code></pre>
<p>How can I automatically generate new incremental rows onto the dataframes such as:</p>
<pre><code> ... | <p>You can try this</p>
<pre><code>import dateutil.relativedelta
last_row = df.iloc[-1]
last_value = last_row['VALUE'] # or change it
last_date = datetime.datetime(last_row['YEAR'], last_row['MONTH'], 1)
t = [last_date + dateutil.relativedelta.relativedelta(months = k + 1) for k in range(12)]
df1 = [{'YEAR' : k.yea... | python-3.x|pandas|datetime|dataframe|multi-index | 1 |
11,158 | 65,974,978 | Pyspark Dataframe udf dependent on previous index value | <p>Assuming I have a pandas dataframe like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Val1</th>
<th>Val2</th>
<th>Val 2 Greater than prev</th>
</tr>
</thead>
<tbody>
<tr>
<td>2020-11-13</td>
<td>4</td>
<td>5</td>
<td>NaN</td>
</tr>
<tr>
<td>2020-11-14</td>
<td>6</td>... | <p>You can use the window function <code>lag</code> to compare val2 with the previous row:</p>
<pre><code>from pyspark.sql import functions as F, Window
df.show()
+----------+----+----+
| Date|Val1|Val2|
+----------+----+----+
|2020-11-13| 4| 5|
|2020-11-14| 6| 9|
+----------+----+----+
df2 = df.withColu... | pandas|dataframe|apache-spark|pyspark|apache-spark-sql | 0 |
11,159 | 65,988,281 | How to Avoid Precision Errors While Creating Numpy Arrays? | <p>I have to get certain precision in my code. However, I think due to summing up of errors in long arrays, it accumulates on a bigger error. Would you identify why element 38260 is not equal to 5.6?</p>
<pre><code>import numpy as np
xmin = -377
xmax = 345
spacing = 0.01
a = np.arange(xmin,xmax,spacing)
print('{0:.25... | <p>You can avoid the error accumulation by creating an <code>np.int32</code> to begin with, then dividing it into your float-value range:</p>
<pre><code>import numpy as np
xmin = -37700 # times 100
xmax = 34500 # times 100
spacing = 1 # times 100
b = np.arange(xmin, xmax, spacing) # np.int32 array - no loss of... | python|numpy|precision | 3 |
11,160 | 66,326,733 | Returna value in Pandas by index row number and column name? | <p>I have a DF where the index is equal strings.</p>
<pre><code>df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],
index=['a', 'a', 'a'], columns=['A', 'B', 'C'])
>>> df
A B C
a 0 2 3
a 0 4 1
a 10 20 30
</code></pre>
<p>Let's say I am trying to access the value in... | <p>Try with <code>iat</code> with <code>get_indexer</code></p>
<pre><code>df.iat[0,df.columns.get_indexer(['B'])[0]]
Out[124]: 2
</code></pre> | python|pandas | 0 |
11,161 | 52,621,834 | How to move Nan values to end in all columns | <p>I have a df like this,</p>
<pre><code>A B C
a NaN NaN
b NaN NaN
c NaN NaN
NaN a NaN
NaN b NaN
NaN c NaN
NaN NaN a
NaN NaN b
NaN NaN c
</code></pre>
<p>desired_output,</p>
<pre><code>A B C
a a a
b b b
c c c
NaN NaN NaN
NaN NaN NaN
NaN NaN Na... | <p>You can use a bit changed <a href="https://stackoverflow.com/a/44559180">justify</a> function:</p>
<pre><code>def justify(a, invalid_val=0, axis=1, side='left'):
"""
Justifies a 2D array
Parameters
----------
A : ndarray
Input array to be justified
axis : int
Axis along ... | python|pandas|dataframe | 2 |
11,162 | 52,470,344 | How to extract specific data from multiindex dataframe (Yahoo stock data) | <p>Could someone give me a quick/clear lesson on grabbing specific data points in the multiindex dataframe below? I've been looking at tutorials all day, but none have been very helpful. This should be simple for someone who knows Pandas.</p>
<p>How can I do the following:</p>
<ol>
<li><p>Extract the 'close' of 'AA... | <p>IIUC,</p>
<ol>
<li><em>Extract the 'close' of 'AAPL' on the last date of the dataframe</em></li>
</ol>
<p>Just get the maximum date by doing <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.max.html" rel="nofollow noreferrer"><code>df.index.max()</code></a> and choose AAPL/close</p>
<p... | python|pandas|multi-index | 0 |
11,163 | 68,984,545 | How do I convert the generated python list numbers into a tensorflow dataset for onward feeding into an Artficial neural network model on colab | <pre><code>import random
import numpy as np
import pandas as pd
minWallThickness = 0.250
maxWallThickness = 0.375
minCurrentFlowRate = 320.0 #m3/HR
maxCurrentFlowRate = 600.0 #m3/HR
mycurrentFlRTList=[]
mywallTkList=[]
for x in range(5):
wallThickness= round(random.uniform(minWallThickness, maxWallThickness), 4)... | <p>If i understood properly what yout want.
You could use the function <code>from_tensor_slices</code>.
You can see more about that <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow noreferrer">here</a>.</p>
<pre><code>dataset = tf.data.Dataset.from_tensor_slices(mywallTkList)
</code></... | tensorflow|google-colaboratory|tensorflow-datasets | 0 |
11,164 | 69,128,538 | How to pass objects to numpy dot function | <p>Suppose I have defined my object:</p>
<pre><code>import numpy as np
class myTensor:
def __init__(self,data):
self.data=np.array(data)
self.parent=[]
</code></pre>
<p>How can I pass 'myTensor' as inputs to np.dot? For example:</p>
<pre><code>t1=myTensor([1,2])
t2=myTensor([3,4])
</code></pre>
<p>N... | <p>check the tutorial on how to write custom array container: <a href="https://numpy.org/devdocs/user/basics.dispatch.html" rel="nofollow noreferrer">https://numpy.org/devdocs/user/basics.dispatch.html</a></p>
<pre><code>from numbers import Number
import numpy as np
HANDLED_FUNCTIONS = {}
class Mytensor():
def ... | python|numpy | 2 |
11,165 | 44,503,857 | Summing rows in Python Dataframe | <p>I just started learning Python so forgive me if this question has already been answered somewhere else. I want to create a new column called "Sum", which will simply be the previous columns added up.</p>
<pre><code>Risk_Parity.tail()
VCIT VCLT PCY RWR IJR XLU EWL
Date ... | <p>Use <code>sum</code> with the parameter <code>axis=1</code> to specify summation over rows</p>
<pre><code>Risk_Parity['Sum'] = Risk_Parity.sum(1)
</code></pre>
<p>To create a new copy of <code>Risk_Parity</code> without writing a new column to the original</p>
<pre><code>Risk_Parity.assign(Sum= Risk_Parity.sum(1)... | python|pandas|dataframe|sum | 5 |
11,166 | 60,978,059 | How to convert a 2 column pandas dataframe to datetime? | <p>I have a pandas dataframe that has 2 columns: The first column is the minutes, and the second column is the seconds. It looks like this:</p>
<pre><code> min s
0 0 0
1 0 1
2 0 2
3 0 3
4 0 4
5 0 5
6 0 6
7 0 7
8 0 8
9 0 9
10 0 10
11 0... | <p>I believe because you just have time only columns, you should avoid using datetime and use timedelta instead.</p>
<p>I would try something like this:</p>
<pre><code>import pandas as pd
df=pd.DataFrame({"minute":[0,1,2,3,4,5],"second":[30,40,50,60,10,20]})
df['time'] = df.agg('{0[minute]}:{0[second]}'.format, axis=... | python|pandas | 0 |
11,167 | 60,864,893 | How to replace a word in a column, which is present in the pandas dataframe by another word in the same column? | <p><a href="https://i.stack.imgur.com/tXRNu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tXRNu.png" alt="This is how the Route Name column looks like in CSV file "></a></p>
<p>I have placed this in the <strong>df1</strong> data frame in my code.</p>
<p>I have modified this row by converting ever... | <p>First we create a dictionary for your string replacements and placing a word boundry <code>\b</code> before and after them. you could build this up easier but i've hard coded it.</p>
<p>we then pass it as an argument in replace</p>
<pre><code>repl_dict = {r'\bdel\b' : 'delhi',
r'\bvara\b' : 'varanasi',... | python|python-3.x|pandas | 0 |
11,168 | 71,632,032 | Why is my neural network having trouble predicting the next value of a sin wave? | <p>Why is my neural network not able to predict the next number for a sin wave?</p>
<p>I don't know if I need a better loss function or what the issue is. It seems to optimize for about 500 steps and then it just flounders with predictions that look nothing like a wave.</p>
<p>The input to the model is 120. That's 120 ... | <p>Your model has two main problems: one is mechanical and one is theoretical.</p>
<ol>
<li><p>Your loss (and accompanying architecture) do not model the problem appropriately. You are effectively attempting to train a regression problem (R^n -> R), but you're framing it as a classification problem (R^n -> Z^m). ... | python|pytorch|torch | 0 |
11,169 | 71,479,298 | How can i create Dataframe with help of two list and a variable which is under a loop | <p>I have a variable whose name is Strike, in Strike variable values regularly change because it is under a loop.</p>
<p>This is my Dataframe
<a href="https://i.stack.imgur.com/su9Zx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/su9Zx.png" alt="enter image description here" /></a>
code example -</p... | <p>IIUC you could use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer"><code>DataFrame</code></a> constructor directly with a <a href="https://numpy.org/doc/stable/reference/generated/numpy.reshape.html" rel="nofollow noreferrer"><code>reshape</code></a>d numpy ... | python|pandas|list|dataframe|var | 0 |
11,170 | 42,442,869 | No module named layers | <p>I'm using tensorflow 1.0.0 and I want to access the tensorflow.layers module. The module seems to exist:</p>
<pre><code>In [12]: dir(tensorflow.layers)
Out[12]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'_allowed_symbols',
'average_pooling1d',
'average_pooling2d',
'average_pooling3... | <p>Something is wrong with your installation or workspace:</p>
<ul>
<li>Make sure you don’t have a directory called ‘tensorflow” in your Python Path. </li>
<li>Install again the official tensorflow distro <code>pip install —upgrade —ignore-installed tensorflow)</code></li>
<li>Make sure you are using the right tensorf... | python|tensorflow | 1 |
11,171 | 69,901,369 | Create a dataframe in Pyspark using random values from a list | <p>I need to convert this code into PySpark equivalent. I can not use pandas to create the dataframe.</p>
<p>This is how I create the dataframe using Pandas:</p>
<pre><code>df['Name'] = np.random.choice(["Alex","James","Michael","Peter","Harry"], size=3)
df['ID'] = np.r... | <pre><code>names = np.random.choice(["Alex","James","Michael","Peter","Harry"], size=3)
id = np.random.randint(1, 10, 3)
fruits = np.random.choice(["Apple","Grapes","Orange","Pear","Kiwi"], size=3)
columns = ['Name', 'ID... | python|pandas|apache-spark|pyspark|apache-spark-sql | 1 |
11,172 | 72,288,020 | How to Enable Mixed precision training | <p>i'm trying to train a deep learning model on <strong>vs code</strong> so i would like to use the <strong>GPU</strong> for that. I have <strong>cuda 11.6</strong> , <strong>nvidia GeForce GTX 1650</strong>, <strong>TensorFlow-gpu==2.5.0</strong> and <strong>pip version 21.2.3</strong> for <strong>windows 10</strong... | <p>The above error suggests that it does not accept fp16=True/bf16=True in non-GPU mode. Perhaps Cuda 11.6 might be an issue here which has stability issues.</p>
<p>Test with Cuda 11.2 and CudNN 8.1 . If that does not work you can go with fp16=False parametre.</p>
<p>Ref - <a href="https://www.tensorflow.org/install/s... | tensorflow|gpu|half-precision-float|automatic-mixed-precision | 0 |
11,173 | 72,455,071 | adding in an array as a single element of Pandas Dataframe? | <p>I would like to put an array as a single element of a pandas Dataframe. I am searching for the indices using two conditions, so my syntax is something like</p>
<pre><code>element=list([a, b])
df.loc[(col1=='a')&(col2=='b'),'col3']=element
</code></pre>
<p>From reading other stack exchange posts and from past ex... | <p>If you try and assign a list to a DataFrame, Pandas will check that the list is the same length as the number of rows, that is the error you are seeing. To assign a list to a DataFrame you will need to provide a list of lists, with the outer list being the same length as the DataFrame and the inner list being the da... | python|pandas|dataframe | 0 |
11,174 | 50,326,774 | identifying feature type in a dataset : categorical or bag of words | <p>I am trying to identify the type of feature in a dataset which can be either categorical/bag of words/ floats. </p>
<p>However I am unable to reach to a accurate solution to distinguish between categorical and bag of words due to following reasons.</p>
<ol>
<li>Categorical data can either be object or float. Count... | <p>Well you're confused between those two terms:</p>
<p><strong>Categorical</strong> Data is the kind of data which can be categorized between different categories especially more than two classes or multi-class. Search for 20 Newsgroup Dataset.</p>
<p>Whereas,
<strong>Bag of Words</strong> is a <strong>technique</st... | python|pandas|machine-learning | 1 |
11,175 | 50,301,685 | How to extract string from dataframe after regex matching | <p>Want to extract city name from the address which appear after zip code from pandas dataframe.
Given:
<code>10 rue des Treuils BP 12 33023, Bordeaux France</code>
I want to extract <code>Bordeaux</code> from column of dataframe.</p>
<p>City name is always first after the comma , but it is not guaranteed to be one wo... | <blockquote>
<p><em>United States will be fixed string which can be stripped off as on
exact match</em></p>
</blockquote>
<hr>
<p>My solution is to <strong>remove the country name</strong>, which will leave us with the <strong>city name</strong> only.<br>
This approach seems to be easier since country names are f... | python|regex|pandas | 1 |
11,176 | 45,326,824 | Using `rank` on a pandas DataFrameGroupBy object | <p>I have some simple data in a dataframe consisting of three columns [id, country, volume] where the index is 'id'.</p>
<p>I can perform simple operations like:</p>
<pre><code>df_vol.groupby('country').sum()
</code></pre>
<p>and it works as expected. When I attempt to use rank() it does not work as expected and th... | <p>You can add column by <code>[]</code> - function is call only for column <code>Volume</code>:</p>
<pre><code>df_vol.groupby('country')['volume'].rank()
</code></pre>
<p>Sample:</p>
<pre><code>df_vol = pd.DataFrame({'country':['en','us','us','en','en'],
'volume':[10,10,30,20,50],
... | python|pandas | 5 |
11,177 | 62,661,307 | how to format date format in pandas | <p>I use python and pandas to get yahoo stock market date and save to a local csv file.</p>
<pre><code>DailyPrice = pd.read_csv(file, index_col=0)
print(DailyPrice.tail())
Date
2020-05-27 86.480003 84.370003 86.300003 86.180000 1917600.0
2020-05-28 87.849998 86.059998 86.870003 86.690002 1... | <p>I guess it is the same question as this <a href="https://stackoverflow.com/questions/16176996/keep-only-date-part-when-using-pandas-to-datetime">one</a></p>
<pre><code>df['Date'] = df['Date'].dt.date
</code></pre>
<p>It should work</p> | python|pandas|datetime|format | 0 |
11,178 | 62,793,045 | Dynamically normalise 2D numpy array | <p>I have a 2D numpy array "signals" of shape (100000, 1024). Each row contains the traces of amplitude of a signal, which I want to normalise to be within 0-1.</p>
<p>The signals each have different amplitudes, so I can't just divide by one common factor, so I was wondering if there's a way to normalise each... | <p>Adding a little benchmark to show just how significant is the performance difference between the two solutions:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import timeit
arr = np.arange(1024).reshape(128,8)
def using_list_comp():
return np.array([s/np.max(s) for s in arr])
def using... | python|arrays|numpy|normalization | 4 |
11,179 | 62,578,816 | Pandas sliding window with step size | <p>Is there any fast way to have an overlapping sliding windows with step size in Pandas? I'm trying to get aggregate metrics (like mean, standard deviation, percentiles, ecc.) along each column in a window of 60 seconds and step size 1 (windows can overlap).</p>
<p>I'll write a minimal example to explain what I want.<... | <p>What you're looking for (in this example, at least) is called rolling mean:</p>
<pre><code>tmp.rolling(2).mean()
==>
0
0 NaN
1 1.5
2 2.5
3 3.5
4 4.5
</code></pre>
<p>If you looking for a larger window and less results, as in the second example above, do the following:</p>
<pre><code>df = pd.DataFrame(r... | python|pandas|dataframe | 0 |
11,180 | 62,855,643 | Make piece of code efficient for big data | <p>I have the following code:</p>
<pre><code>new_df = pd.DataFrame(columns=df.columns)
for i in list:
temp = df[df["customer id"]==i]
new_df = new_df.append(temp)
</code></pre>
<p>where <code>list</code> is a list of customer id's for the customers that meet a criteria chosen before. I use the <code>t... | <p><code>list</code> is a type in Python. You should avoid naming your variables with built-in types or functions. I simulated the problem with 3 million rows and a list of customer id of size 100000. It took only a few seconds using isin.</p>
<pre><code>new_df = df[ df['customer id'].isin(customer_list) ]
</code></pre... | python|pandas|performance | 1 |
11,181 | 62,729,044 | Splitting strings into two different columns pandas | <p>I have a below data frame called df. It has location column and it is a list separated by a comma.</p>
<p><a href="https://i.stack.imgur.com/8TQe1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8TQe1.png" alt="enter image description here" /></a></p>
<p>Expected output</p>
<p>I need to split the ... | <p>Create list by using the <code>tolist()</code>. Create datframe using <code>pd.DataFrame</code></p>
<p>Say sample data is:</p>
<pre><code>df=pd.DataFrame({'text':[['122 Grenfell Street', 'Adelaide CBD', '5000 Adelaide', 'Australia']]})
</code></pre>
<p>Extract list elements into columns:</p>
<pre><code>df[['Street',... | python-3.x|pandas | 1 |
11,182 | 73,758,004 | python get next x elements of numpy array remembering index of the last get | <p>I had a problem, and I solved it by creating a class:</p>
<pre class="lang-py prettyprint-override"><code>class ArrayIter:
def __init__(self, array):
self.array = array
self.index = 0
def __getitem__(self, n):
res = self.array[self.index: self.index + n]
self.index += n
... | <p>Try generators:</p>
<pre><code>a = np.arange(20)
it = iter(a)
def get(n):
for _ in range(n):
yield next(it)
print(list(get(2)))
print(list(get(3)))
print(list(get(10)))
print(list(get(1)))
# [0, 1]
# [2, 3, 4]
# [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
# [15]
</code></pre>
<p>Details: <a href="https://stac... | python|arrays|numpy | 0 |
11,183 | 73,749,044 | Removig backlashes from get request json in Flask | <p>How can I remove the backlashes in my json response fetched from my API?</p>
<pre><code>client = pymongo.MongoClient('cred')
result = client['db']['Todo'].find(
filter=filter,
projection=project
)
json_response = json.dumps(list(result), default=json_util.default)
dog = json.loads(json_response)
df = pd.DataFra... | <p>Okay, when I fetch my response in my app the backlashes does not really matter, but I was concerned because in my browser I saw them and I thought that would lead to a wrong data fetching</p> | python|pandas|flask | 0 |
11,184 | 71,126,239 | scraping pdf files multiple pages from url | <p>I want to scrape the information on this PDF in python. I'm not sure where to start because it isn't organized at all. I'm used to scraping HTML. I tried converting it to HTML and that didn't really help.</p>
<p>How would you try to scrape this PDF? Here is a link to the PDFs (any will work, they're all similar): <a... | <p>It is organized - it's in a "table" - <a href="https://github.com/jsvine/pdfplumber#extracting-tables" rel="nofollow noreferrer">pdfplumber</a> works well for this.</p>
<p><a href="https://i.stack.imgur.com/ZrCCJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZrCCJ.jpg" alt="pdfplumber ... | python|pandas | 0 |
11,185 | 71,256,560 | Group Data into Clusters Based on DataFrame Columns | <p>I have a dataframe (df) similar to this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Node_Start</th>
<th>Node_End</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.0</td>
<td>208.0</td>
</tr>
<tr>
<td>1.0</td>
<td>911.0</td>
</tr>
<tr>
<td>800.0</td>
<td>1.0</td>
</tr>
<tr>
<td>3.0</td>
<td>800... | <p>This looks to be a directed graph. Python has a nice module that deals with graphs: <code>NetworkX</code>. And your problem seems to be about finding connected components.</p>
<p>So we could first build a graph (for the purposes of the problem, directedness is immaterial, so we drop that attribute here) where the no... | python|pandas|dataframe|graph-theory | 1 |
11,186 | 71,223,605 | How do you pick a certain min number in Python? | <p>I'm running a program which corrects responses to tests. There are 23 questions and each correct answer is given a + 1. My code sums these scores up for these 23 questions and creates a separate column (totalCorrect) which prints the final score out of 23. I have attached a screenshot of a portion of this column <a ... | <pre><code>df['earnedAmount'] = (0.3 * df['totalNumCorrect']).clip(0, 6)
</code></pre>
<p><code>0.3 * df['totalNumCorrect']</code> simply calculates the full amount, which is a Series (or dataframe column).</p>
<p><code>.clip</code> then limits the values to be between 0 and 6. 6 is of course 0.3 * 20, the maximum amou... | python|pandas | 0 |
11,187 | 71,257,533 | How to sum two curves with different array binning | <p>Let's say I have two dataframes A and B. In both, the first column is the frequency and the second column is the luminosity. A and B have different lengths, the frequencies start and end are different, as well as the values of each frequency (different binning).</p>
<p>I want an array where the first column is the f... | <p>I will show how to aggregate <code>df2</code> on the frequencies from <code>df1</code>. Should be easy to extend to multiple dfs</p>
<p>You can use <code>pd.cut</code> and a <code>groupby</code>.</p>
<p>We start by defining the bins for frequency based on <code>df1</code>:</p>
<pre><code>bins = pd.IntervalIndex.from... | python|arrays|pandas|dataframe | 0 |
11,188 | 71,254,352 | Select rows in a data frame based on the date range | <p>I have a list of dictionaries:</p>
<pre><code>mylist=
[{'Date': '10/2/2021', 'ID': 11773, 'Receiver': 'Mike'},
{'Date': '10/2/2021', 'ID': 15673, 'Receiver': 'Jane'},
{'Date': '10/3/2021', 'ID': 11773, 'Receiver': 'Mike'},
...
{'Date': '12/25/2021', 'ID': 34653, 'Receiver': 'Jack'}]
</code></pre>
<p>I want to selec... | <p>One option you have is to change the Date column to the index of the Dataframe, once that is set to the index python will recognize it as a date field and you can use a df.loc to find the data between specified dates.</p>
<pre><code>df = pd.DataFrame(mylist)
df.set_index('Date')
df.loc['10/3/2021':'11/3/2021']
</cod... | python|pandas|list|dataframe | 1 |
11,189 | 52,400,354 | How to understand the np.argwhere function? | <pre><code>Signature: np.argwhere(a)
Docstring:
Find the indices of array elements that are non-zero, grouped by element.
</code></pre>
<h2>Examples</h2>
<pre><code>>>> x = np.arange(6).reshape(2,3)
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.argwhere(x>1)
array([[0, 2],
[1,... | <p>In each row the first entry is the row index and the second entry is the column index of the entries of x that satisfy the condition. </p>
<p>For example:
2 is greater than 1
so the first row of argwhere gives you <code>[0, 2]</code>
pointing to the position of 2 in x. </p> | numpy | 4 |
11,190 | 52,126,780 | Changing a derived field to float and getting the average of the derived field | <p>I have a dataframe called <code>FP</code> with 13 columns, derived a new field called <code>price/sqm</code>, and dropped 10 columns.</p>
<pre><code>FP['price/sqm'] = FP['price'] / FP['floor_area_sqm']
FP = FP.loc[:,['year', 'town', 'type', 'price/sqm']]
</code></pre>
<p>The dataframe has 700,000 rows and looks so... | <p>I think this will work for you because you to transform the results according to indexing of dataframe </p>
<pre><code>FP['avg_price/sqm'] = FP.groupby(['year', 'town', 'type'])['price/sqm'].transform(lambda x:x.mean())
</code></pre> | python|pandas|dataframe|pandas-groupby | 0 |
11,191 | 60,655,539 | How calculing the difference for each begin and end - Pandas Python | <p>I would like to calcul the difference for each begin/end in a new df, here is my df:</p>
<pre><code> Flag Timestamp
begin 2019-10-21 07:48:26.740378
end 2019-10-21 07:48:28.449916
begin 2019-10-21 07:48:37.306045
end 2019-10-21 07:48:41.689466
begin 2019-10-21 07:57:59.223986
... | <p>Idea is create 2 column DataFrame by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html" rel="nofoll... | python|pandas|timestamp | 7 |
11,192 | 60,641,037 | Problem when importing Excel File with Pandas | <p>I'm new to python and was hoping someone could help me out.</p>
<p>I imported an excel file using pandas just to play around with. However when I try do any additional analysis or coding on the data it is only using the header row of the excel file.</p>
<p>Here's one of the codes I used:</p>
<pre><code>import pa... | <p>you can pass only the string <code>'C:\Users\at0789\Documents\Test File.xlsx'</code>
And you don't have to print the df, only call it, like that</p>
<pre><code>import pandas as pd
df = pd.read_excel('C:\Users\at0789\Documents\Test File.xlsx')
df
</code></pre> | python|excel|pandas | 0 |
11,193 | 60,547,227 | Pivoting a table with duplicate entries in Pandas | <p>Is there a way to pivot the User's Character Height and Weight Table table (A) with pandas to (B)? I have tried using unstack but it doesn't seem to work.</p>
<p>(A) User's Character Height and Weight Table</p>
<pre><code>+---------------------------------------------+
| USER_ID Category Height Weight... | <p>I would try to split the problem:</p>
<ul>
<li>first convert Height and Weight column to floating point values</li>
<li>produce the Green, Blue and Red column by pivoting the dataframe with an auxilliary column</li>
<li>produce the type_color column with <code>unstack</code></li>
<li>concatenate the above column an... | python|pandas|pivot-table | 2 |
11,194 | 60,569,207 | Using join on a dictionary of dataframes by datetime | <p>I have a dictionary of dataframes which have two columns 'Time' (datetimeformat) and another column which is different for each dataframe. The Time/Value entries are variable.</p>
<p>I want to join all of the dataframes to a master time dataframe which has 1 minute increments for the entire time range using the 'T... | <p>Change your for loop to </p>
<pre><code>for tag in tags:
df_man_data = df_man_data.join(df_dic[tag].set_index('Time'), on = 'Time',how = 'left')
</code></pre>
<p>.join() returns a new dataframe and assigning that new, joined dataframe to df_man_data each loop should capture all of your new columns of data iter... | python|pandas | 0 |
11,195 | 60,424,573 | Faster way to iterate over dictionary and dataframe together? | <p>I have a dictionary and a DataFrame with same keys/columns.
The DataFrame, however, is missing some data, which I will fill in using the dictionary.
This is a minimal example and my dataset is much larger. </p>
<pre class="lang-py prettyprint-override"><code>mydict = {'one': ['foo', 'bar'], 'two': ['foo', 'bar']}
m... | <p>Try this and it should give you what you want.</p>
<pre><code># Fill the values using your dictionary
for k, v in mydict.items():
mydf[k] = v
# Drop the columns you don't want
mydf.drop(columns=['foo','bar'], inplace=True)
</code></pre>
<p>And you will get this:</p>
<pre><code> one two
0 foo foo
1 ... | python|pandas|loops|dictionary|iteration | 0 |
11,196 | 60,392,816 | Is it possile to convert a nested list of tuples to an numpy array? | <p>I have a nested list of tuples:</p>
<pre><code>tuple_list = [[(0, 0.022190866145025672),
(1, 0.03713307553569147),
(2, 0.03329292095418187),
(3, 0.013397487788645558),
(4, 0.012968754425823006),
(5, 0.02303938132767878),
(6, 0.5055000245070915),
(7, 0.02148198409145118)],
[(0, 0.027141399289287292),
... | <p>Hi I have done this in traditional for loop way:</p>
<p>Yes you can convert tuple into list by using <code>list()</code>
method</p>
<pre><code> tuple_lists =[[(0, 0.022190866145025672),
(1, 0.03713307553569147),
(2, 0.03329292095418187),
(3, 0.013397487788645558),
(4, 0.012968754425823006),
(5, 0.02303... | python|numpy | 1 |
11,197 | 72,580,392 | converting a numpy string array to numpy float array | <p>I'm reading a csv file to dict. I want the key to be string, and the value to be an array of a float, like this:</p>
<pre><code>"A":array[5.19494526e-02 1.17357977e-01 5.19494526e-02]
</code></pre>
<p>but I'm getting this:</p>
<pre><code>"A":array['5.19494526e-02 1.17357977e-01 5.19494526e-02... | <p>I think the issue is that in the line <code>y = np.asarray(x, dtype=np.float32)</code>, the variable <code>x</code> is an array of length one containing multiple space-separated substrings that can each be converted to a float. However, the string itself cannot be converted to float.</p>
<p>You can try replacing tha... | python|arrays|numpy|csv | 0 |
11,198 | 72,587,079 | TypeError: __init__() got an unexpected keyword argument 'Veriler' | <p>I have unexpected keywords argument error in the below codes. Where is my missing point or mistake?</p>
<pre class="lang-py prettyprint-override"><code>Veriler = pd.DataFrame(Veriler = Veriler_modeled, columns = selected_columns)
TypeError: __init__() got an unexpected keyword argument 'Veriler'
</code></pre> | <p>Maybe you can try <code>data</code> instead of <code>Veriler</code> in parameters</p> | python|pandas|typeerror | 0 |
11,199 | 32,402,533 | Sorting Data using Pandas Dataframes in Python | <p>I have a dataframe that I am trying to sort in a certain way. </p>
<p>The input: </p>
<pre><code>CompanyName count assignee_name CallType recvd_dttm
Company3 4 Jill Machine1 8/28/2015 13:46
Company3 4 Jill Machine1 8/27/2015 13:26
Company3 ... | <pre><code># convert datetime string to pd.timestamp
df['recvd_dttm'] = pd.to_datetime(df['recvd_dttm'], format='%m/%d/%Y %H:%M')
def func(g):
temp = g[g['recvd_dttm'] == g['recvd_dttm'].max()].iloc[0]
temp['assignee_name'] = g['assignee_name'].value_counts().index[0]
return temp.drop('CompanyName')
df.gr... | python|sorting|pandas|count|dataframe | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.