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 |
|---|---|---|---|---|---|---|
353,000 | 69,821,857 | Iris dataset not showing "Species" column | <p>I am working with numpy and pandas on Python to learn how to work on dataframes.</p>
<p>I'm coding on Collaboratory and I have loaded the Iris dataset but for some reason, there is no "Species" column in my dataframe. Maybe I've loaded it in an incorrect fashion? I'd appreciate help on the matter.</p>
<p>I... | <p>Try:</p>
<pre><code>import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(data=np.c_[iris['data'], iris['target']],
columns= iris['feature_names'] + ['target']).astype({'target': int}) \
.assign(species=lambda x: x['target'].map... | python|pandas|dataframe|dataset|iris-dataset | 4 |
353,001 | 69,787,101 | How to "unroll" time intervals in a dataframe? | <p>I have a dataframe:</p>
<pre><code>df1 = pd.DataFrame(
[['2011-01-01','2011-01-03','A'], ['2011-04-01','2011-04-01','A'], ['2012-08-28','2012-08-30','B'], ['2015-04-03','2015-04-05','A'], ['2015-08-21','2015-08-21','B']],
columns=['d0', 'd1', 'event'])
</code></pre>
<pre class="lang-none prettyprint-override... | <p>We can <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html" rel="noreferrer"><code>set_index</code></a> to <code>event</code> then create <a href="https://pandas.pydata.org/docs/reference/api/pandas.date_range.html" rel="noreferrer"><code>date_range</code></a> per row, then <a href=... | python|pandas | 7 |
353,002 | 69,801,841 | How to use GPT-J for paraphrasing | <p>Could anyone point me to direction how to use GPT-J model for text paraphrasing . As generating text is easy, but paraphrasing?
Do I need to fine tune on paraphrasing dataset? Or could I just use few shot training?</p> | <p>GPT-J is very good at paraphrasing content. In order to achieve this, you have to do 2 things:</p>
<ul>
<li>Properly use few-shot learning (aka "prompting")</li>
<li>Play with the top p and temperature parameters</li>
</ul>
<p>Here is a few-shot example you could use:</p>
<pre><code>[Original]: Algeria rec... | huggingface-transformers|gpt | 0 |
353,003 | 69,957,536 | rewriting loops functions in numpy without using for or while | <p>I'm trying to reproduce the following functions using the numpy library, I want to produce an equivalent definition without using the keywords for or while. Im guessing you need to use broadcasting, newaxis, and reshape from numpy. but im new to numpy and doing loops without using "for" or "while"... | <p>Focusing on the</p>
<pre><code>y[i,j,k] = (x1[i,j,k]+4)*(4*x2[j,k] - 4)
</code></pre>
<p>That means <code>y</code> and <code>x1</code> have same shape. <code>x2</code> has the same last 2 dimensions. We can reshape <code>x2</code> to have a new leading dimension <code>x2[None,...]</code></p>
<pre><code>y = (x1+4... | python|numpy|loops | 0 |
353,004 | 69,851,555 | Append function does not add anything to the panda dataframe | <p>I have the following code:</p>
<pre><code>import arcpy
from arcpy import env
import pandas as pd
#setting workspace
env.workspace = r"C:\Users\4_projects\211104\Network.gdb"
env.overwriteOutput = True #existing output will be overwritten
buchs = r"buchs"
rows = arcpy.SearchCursor(buchs)
shapeN... | <p>Pandas <code>DataFrame.append()</code> has to be assigned to a variable, otherwise it does append the other dataframe, but never assigns it and it's gone as soon as the appending finishes, so just add <code>df1 = </code> in front of the append:</p>
<pre><code> df1 = df1.append(df2, ignore_index=True)
</code></pre... | python|pandas|dataframe|arcpy | 1 |
353,005 | 69,693,232 | Converting integer date value to Datetime in Python | <p>I have a dataframe with tickers, returns, and dates in the format, for example, of "20200101". I'm trying to convert these values to Datetime values. However, when I attempt the following:</p>
<pre><code>fin_data['DATE'] = pd.to_datetime(fin_data['DATE'])
</code></pre>
<p>The output is recognizing the date... | <p>Specify the format:</p>
<pre><code>fin_data = pd.DataFrame({'DATE': [20200101]})
pd.to_datetime(fin_data['DATE'], format='%Y%d%m')
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>0 2020-01-01
Name: DATE, dtype: datetime64[ns]
</code></pre> | python|pandas|datetime | 1 |
353,006 | 69,806,408 | Is sigmoid function only applicable after dense() layer? | <p>I am making a network which is similar to SE-Net(<a href="https://github.com/titu1994/keras-squeeze-excite-network/blob/master/se.py" rel="nofollow noreferrer">https://github.com/titu1994/keras-squeeze-excite-network/blob/master/se.py</a>)
using keras, but quite different with it.</p>
<p>Suppose that I want to make ... | <p>you can for sure experiment sigmoid as an activation for cnn layers too but the reason why sigmoid is not used with cnn layers are:</p>
<p><strong>1. Sigmoid function is monotonic but it's derivative is not therefore there is a possibility that your training can be stuck</strong></p>
<p><strong>2. Sigmoid range:[0,1... | tensorflow|keras|tf.keras | 1 |
353,007 | 69,928,988 | Why am I getting an empty dataframe? | <p>Here is my initial dataframe:</p>
<pre><code> df.head()
Unnamed: 0 Unnamed: 0.1 Unnamed: 0.1.1 Unnamed: 0.1.1.1 Unnamed: 0.1.1.1.1 date time game score home_odds draw_odds away_odds country league
0 0 0 0.0 ... | <p>As suggested in the comments, you could try like this:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
def clean(df: pd.DataFrame) -> pd.DataFrame: # fix type hint
# df = harmonize_game(df)
# df = numerical_scores(df)
# df = coerce_columns(df)
# df = strip_strings(df)
... | pandas|dataframe|export-to-csv | 1 |
353,008 | 69,899,342 | Boolean marker every time a string changes in a column, by group | <p>I have the following dataframe:</p>
<pre><code>data = {'unit': {59: 'unit1',
662: 'unit1',
680: 'unit1',
725: 'unit1',
709: 'unit1',
703: 'unit1',
653: 'unit1',
807: 'unit4',
825: 'unit4',
778: 'unit4',
816: 'unit4',
822: 'unit4',
849: 'unit4',
820: 'unit4',
754: 'unit4',
1031: 'unit3',... | <p>Compare shifted values and then set <code>False</code> for first values by <code>unit</code> use if performance is important, here <code>groupby</code> is not necessary:</p>
<pre><code>df["Vector Changed"] = (df["Vector"].shift()
.ne(df['Vector'])
... | python|pandas|pandas-groupby | 1 |
353,009 | 69,733,972 | Putting 2×2 matrices in ndarray without using "for" | <p><strong>Numpy</strong><br></p>
<p>First, I define "x" and function "example" below:</p>
<pre><code>import numpy as np
x=np.arange(1,4,1)
def example(d):
return 2*d
</code></pre>
<p>In this simple case, if I put "x" into "example",</p>
<pre><code>y=example(x)
</code></pre>
... | <p>not following but:</p>
<pre><code>
import numpy as np
x=np.arange(1,4,1)
def example(d):
return 2*d
y=example(x)
print(y)
def example2(d):
matrix=np.array([[d,0],[0,d]], dtype= object)
return matrix
y2=example2(x)
print('\n___________________________')
print(y2)
</code></pre>
<p>gives:</p>
<pr... | python|numpy|numpy-ndarray | 1 |
353,010 | 69,729,694 | Getting a float error when trying to access first value from a dictionary in a Pandas DataFrame | <p>I have a DataFrame where one column contains a dictionary. I am trying to return the first value from the dictionary by using apply and a lambda function but I keep getting an error related to floats. This is confusing because I have a dictionary not a float that I am trying to iterate through.</p>
<p>Error message ... | <p>It might help to show the ouput for
<code>all_addr['street address'].apply(lambda x: type(x))</code>. Also, <code>.apply()</code> is pretty slow for just getting values out of a column so <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer">... | python|pandas|dataframe|dictionary|lambda | 0 |
353,011 | 69,711,943 | Translate Excel if condition from Excel to Python | <p>I'm trying to translate a If statement from excel to python.</p>
<p>I know that for excel, If statement we have:</p>
<p><code>IF(logical_test, [value_if_true], [value_if_false])</code></p>
<p>For IFERROR statement we have:</p>
<p><code>IFERROR(value, value_if_error)</code></p>
<p>OR function:</p>
<p><code>The OR fun... | <p>Something like this (if we talk about pandas DataFrame):</p>
<pre class="lang-py prettyprint-override"><code>df['whatever'] = np.where(
(df['AM'] == 0) | (df['AM'].isna()) | (df['AM'] == " ") | (df['DK'] != ' ') | (df['AM'] == ""),
"ZZZ",
df['AM']
)
</code></pre>
<p>I used l... | excel|pandas|dataframe|numpy|python-3.9 | 1 |
353,012 | 69,869,642 | find different values in two dataframes exported to and imported from the same CSV | <p>I have a <code>df_final</code> pandas v1.3.4 dataframe and am exporting it to a CSV file so I don't need to repeat the dataframe building step every time I do an analysis. <code>df_final</code> will be a 13000 x 91 dataframe, but I am testing the process on a smaller 689x91 dataframe first.</p>
<p>I would like to c... | <p>Maybe there are some special characters which CSV messed up. try to write in .pkl file, you'll get 100% same data.</p>
<pre><code>import pickle
# write into pickle file
pickle.dump(df, open("df.pkl", 'wb'))
# then read it
df_new = pickle.load(open("df.pkl", 'rb'))
</code></pre> | python|pandas|dataframe|csv|comparison | 1 |
353,013 | 69,792,025 | UnknownError: OSError: image file is truncated (30 bytes not processed): | <p>I'm trying to train a model. I have almost 150 classes and I'm using ImageDataGenerator to augment my dataset. I'm also using model checkpoints and csvlogger to save the weights. It gives me an error at a certain point in the first epoch when I start my training. The images I'm using are grayscale images if that hel... | <p>I have had similar problems with finding defective image files. The ImageDataGenerator uses PIL. The generator did not detect an error in the image file if it had it would have printed a warning message. So I suggest you try using something other than PIL to detect defective image files. Try using cv2 I have found i... | python|tensorflow|keras|conv-neural-network|image-preprocessing | 0 |
353,014 | 69,995,520 | Pandas: How to filter repeated values of an axis? | <p>Let's assume that we've got a dataframe composed of the following variables, among others:</p>
<pre><code>Institution (name of the university)
Country (name of the country of the institution)
Year (integer, year in which that university was scored)
World_rank (integer, position in the world rank)
Alumni_employment (... | <p>For simplicity, let's use the following dataframe:</p>
<pre><code>df = pd.DataFrame({'institution': ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
'alumni_employment': [10, 20, 10, 30, 20, 5, 20]})
</code></pre>
<p>To get institutions with the same 'alumni_employment', use groupby. Then, filter to eliminate the ones in gro... | python|pandas|dataframe|filter | 2 |
353,015 | 69,941,333 | Python count of string values in a row of a data frame | <p>Suppose I have a pandas data frame <code>df</code> with three columns and each column contains string values of either "a" or "b"</p>
<pre><code>Col1 Col2 Col3
a b a
b b a
a a a
b a a
b b b
a a b
</code></pre>
<p>I want to count the number of times ... | <p>We can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>pd.value_counts</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply</code></a></p>
<p... | python|pandas|dataframe|count|row | 0 |
353,016 | 69,946,027 | A loop to find min values based on another column value, and merge into 1 dataframe? | <p>Imagine a dataframe like this:</p>
<pre><code>import pandas as pd
list ={'Security ID':['3e09ax', 'we9lkl', 'as42we','as5322', 'ot24tas', 'c34ci46a8'],
'Industry':['Airplanes', 'Airplanes', 'Oil', 'Oil', 'Housing', 'Trucking'],
'Amount outstanding':[33, 31, 39, 21, 29, 29]}
df = pd.DataFrame(list... | <p>IIUC, you want <code>groupby</code> and <code>transform</code>:</p>
<pre><code>output = df[df['Amount outstanding']==df.groupby('Industry')['Amount outstanding'].transform(min)]
>>> output
Security ID Industry Amount outstanding
1 we9lkl Airplanes 31
3 as5322 Oil ... | python|pandas | 2 |
353,017 | 69,992,019 | Trying to use transform in pandas but it is giving me some error | <p>I a trying to get the sum of two numbers by using groupby and transform in pandas library but It is giving some garbage value, can someone guide me on how to solve this:
my data looks like this:</p>
<pre><code>SKU Fees
45241 6.91
45241 6.91
55732 119.05
55732 137.98
</code></pre>
<p>I have tried using th... | <pre><code>df['Fees'] = df['Fees'].astype(float)
df.groupby(['sku'])['Fees'].sum()
# Computes the sum
df.groupby(['sku'])['Fees'].transform('sum')
# Computes the sum but using 'transform' duplicates the value for each row
</code></pre> | python|pandas|jupyter-notebook|transform|add | 0 |
353,018 | 69,787,772 | Fast/vectorized iterating and updating of numpy 2D array | <p>This question is quite close to my heart as I have been doing something like this for almost 2 years and always wondered if there is a vectorized way of modifying large array/dataframe when row <code>i</code> depends upon row <code>i-1</code>, i.e., when recursion sounds mandatory. I am very keen to hear if there ar... | <p>I got 3-4x improvement by using <code>numba</code>, another 2x (in total 6-8x) by caching compiled function.</p>
<p>I had to decrease size of <code>x</code>, <code>y</code>, and <code>z</code> due to small RAM on my PC.</p>
<pre><code>import numba as nb
import numpy as np
@nb.jit(nopython=True, cache=True)
def bott... | python|performance|vectorization|numpy-ndarray | 1 |
353,019 | 43,456,149 | groupby, count and average in numpy, pandas in python | <p>I have a dataframe that looks like this:</p>
<pre><code> userId movieId rating
0 1 31 2.5
1 1 1029 3.0
2 1 3671 3.0
3 2 10 4.0
4 2 17 5.0
5 3 60 3.0
6 3 110 4.0
7 ... | <p>Drop <code>movieId</code> since we're not using it, groupby <code>userId</code>, and then apply the aggregation methods:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'userId': [1,1,1,2,2,3,3,3,4,4,5,5,5],
'movieId':[31,1029,3671,10,17,60,110,247,10,112,3,39,104],
'ratin... | python-3.x|pandas|numpy|jupyter | 5 |
353,020 | 43,224,310 | Convert output of tf.nn.top_n into a sparse matrix | <p>As the title states, I'm trying to extract the highest n elements per row from a matrix in tensorflow, and store the result in a sparse Tensor.</p>
<p>I've been able to extract the indices and values with tf.nn.top_n, but the indices don't follow the convention required by tf.SparseTensor. </p>
<p>Specifically, tf... | <p>This is doable with a bit of modular arithmetic. Here's an example that works on matrices, although it would be possible to loop over more axes.</p>
<pre><code>import tensorflow as tf
def slices_to_dims(slice_indices):
"""
Args:
slice_indices: An [N, k] Tensor mapping to column indices.
Returns:
An i... | python|matrix|indexing|tensorflow|sparse-matrix | 3 |
353,021 | 43,301,509 | Combine two tables only when 3 similar values using pandas python | <p>I need to combine two different data sets only when 3 columns have the same value, for example: </p>
<p>df1</p>
<pre><code> iso3_o iso3_d year value1 value2
pak tza 2000 123 456
lby vnm 2000 435 148
can jpn 2001 983 095
... | <p>IIUC we can rename columns in one DF so that we have the same column names for "joining" columns in both DFs. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer">DataFrame.merge()</a> will merge <code>on the intersection of the columns by default</cod... | python|pandas|dataframe | 3 |
353,022 | 43,405,861 | How do you do a Slice (use ix, loc, iloc) operation on a Pandas Object excluding some specified indexes | <p>Many <code>ix</code>, <code>loc</code>, <code>iloc</code> operation you specify indexes which you want to choose. I want do the opposite. There are few columns I want to exclude and select the rest. How do I do this. I.e., specify the indices which needs excluded than included.</p>
<p>E.g. some pseudo code</p>
<pr... | <p>You can either <code>drop</code> OR select the ones you want:</p>
<pre><code>df.drop(df.columns[[1, 2]], axis=1, inplace=True)
# drop by Name
df1 = df1.drop(['D', 'E'], axis=1)
## Select the ones you want
df1 = df[['a','d']]
</code></pre>
<p>There's also a new <a href="http://pandas.pydata.org/pandas-docs/stable... | python|pandas|dataframe | 1 |
353,023 | 43,305,502 | Iterative euclidean distance calculation between consecutive points (x,y tuples) which belongs to a list of lines | <p>I have a dataframe which contains Lines, PointID, X and Y coordinates; each line contains a group of points with X,Y coordinates:</p>
<pre><code>LINE Point ID X coordinate Y Coordinate
A 1 1 2
A 2 2 2
A 3 3 ... | <p>You could use <code>shift()</code> to find the <code>X</code> and <code>Y</code> coordinates of the previous point for every point in <code>LINE</code>. Then calculate distances between this point and previous point:</p>
<pre><code>import pandas as pd
import numpy as np
data = """
LINE PointID X ... | python|pandas|scipy|geopandas | 6 |
353,024 | 43,233,969 | sorting dataframe by string values | <p>I have dataframe which looks like this:</p>
<pre><code>Name Net Worth
A 100M
B 200M
C 5M
D 40M
E 10B
F 2B
</code></pre>
<p>I would like to sort it by values in Net Worth column, what would be most optimal way to sort values lie this? M means million and B means billion so 10B would be the ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow noreferrer"><code>replace</code></a>, create new sorted <code>Series</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html" rel="nofollow noreferrer... | python|pandas|dataframe | 2 |
353,025 | 43,074,435 | unpack(unstack) an input (placeholder) with one None dimension in tensorflow | <p>I am trying to use LSTM with inputs with different time steps (different number of frames). The input to the rnn.static_rnn should be a sequence of tf (not a tf!). So, I should convert my input to sequence. I tried to use tf.unstack and tf.split, but both of them need to know exact size of inputs, while one dimensio... | <p>As explained in <a href="https://stackoverflow.com/questions/39446313/using-tf-unpack-when-first-dimension-of-variable-is-none">here</a>, <code>tf.unstack</code> does not work if the argument is unspecified and non-inferrable. </p>
<p>In your code, after transpositions, <code>x1</code> has the shape of <code>[ n_st... | python|tensorflow | 1 |
353,026 | 43,219,962 | not able to load the image dataset into python using tflearn | <p>i am not able to load an image dataset into python using tflearn
it is showing me an error...</p>
<pre><code>TypeError: image_preloader() got an unexpected keyword argument 'categorical_lables'
</code></pre>
<p>following is the code..</p>
<pre><code>from __future__ import division, print_function, absolute_im... | <p>Maybe check the spelling on <code>categorical_labels</code>.</p> | python|machine-learning|tensorflow|tflearn | 2 |
353,027 | 43,185,659 | pandas dataframe to key value pair | <p>What is the best way to convert following pandas dataframe to a key value pair</p>
<p>Before :</p>
<pre><code>datetime name qty price
2017-11-01 10:20 apple 5 1
2017-11-01 11:20 pear 2 1.5
2017-11-01 13:20 banana 10 5
</code></pre>
<p>After :</p>
<pre><cod... | <p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html" rel="noreferrer"><code>to_dict</code></a>:</p>
<pre><code>d = df.drop('datetime', axis=1).to_dict(orient='records')
print (d)
[{'qty': 5, 'price': 1.0, 'name': 'apple'},
{'qty': 2, 'price': 1.5, 'name':... | pandas | 13 |
353,028 | 43,157,292 | Getting "TypeError: float() argument must be a string or a number" with pandas plot() | <p>I am going thru simple pandas tutorial. And I am trying to plot DataFrame indexed by dtype='datetime64[ns]', however, when I try to plot, I assume the matplotlib attempts to convert the date to float, which raises an exception.</p>
<pre><code>>>> df.index
DatetimeIndex(['2012-01-01', '2012-01-02', '2012-01... | <p>The tutorial is plotting the numbers in colmn 2, not the date in column 1:</p>
<p>Date</p>
<p>2012-01-01 <strong>35</strong></p>
<p>2012-01-02 <strong>83</strong></p>
<p>2012-01-03 <strong>135</strong></p>
<p>....</p>
<p>Thus your plot is missing something, check your input again ...</p> | python|python-2.7|pandas|matplotlib | 1 |
353,029 | 43,150,019 | Remove Words Less Than 4 Characters from Pandas Series | <p>I am trying to remove all words with less than 4 characters from each scalar value in a Pandas Series. What is the best way to do it? Here is my failed attempt:</p>
<pre><code>df['text'] = df['text'].str.join(word for word in df['text'].str.split() if len(word)>3)
</code></pre>
<p>I receive the following error ... | <p>Using regex with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.findall.html" rel="noreferrer"><code>.str.findall</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.join.html" rel="noreferrer"><code>.str.join</code></a> appears to be fast... | python|pandas|parsing|nlp | 8 |
353,030 | 43,166,788 | Pandas Pyplot Multiple Markers, same line | <p>I have a df:</p>
<pre><code>time c_1 c_2 c_3
t1 v1 NaN t1
t2 v2 NaN NaN
t3 v3 t3 NaN
t4 v4 NaN NaN
t5 v5 t5 NaN
t6 v6 NaN t6
</code></pre>
<p>How do you:</p>
<ol>
<li>Use matplotlib.pyplot to plot a line (t1, c_1)</li>
<li>And... | <p>Assume you have this dataframe:</p>
<pre><code> c_1 c_2 c_3 time
0 0.548814 NaN 1.0 1
1 0.715189 NaN NaN 2
2 0.602763 3.0 NaN 3
3 0.544883 NaN NaN 4
4 0.423655 5.0 NaN 5
5 0.645894 NaN 6.0 6
</code></pre>
<p>If the following plot is what you're after</p>
<p><a h... | python|python-2.7|pandas|matplotlib | 2 |
353,031 | 43,095,882 | how to create a numpy list of names from names of numpy files | <p>I have a set of numpy files, they are in one folder.
I need to create a numpy list where I can put in every line some details about each file'name:</p>
<p>Example:
The file name:</p>
<pre><code>AES_Trace=300001_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f... | <p>This seems to be the basic idea.</p>
<pre><code>from pathlib import Path
import re
p = Path('c:/scratch/sample')
for fileName in p.iterdir():
print (fileName.name)
print (' '.join(re.findall('=([0123456789abcdef]{2,})', fileName.name)))
</code></pre>
<p>Output from this script was:</p>
<pre><code>AES_Tra... | python|numpy | 0 |
353,032 | 43,256,822 | Getting an array from collections ordereddict for the maximum key, values | <pre><code>d = collections.OrderedDict()
d
{'A': array([[ 29.503],
[ 31.829],
[ 13.078],
...,
[ 43.227],
[ 53.028],
[ 43.928]]),
'B': array([[ 28.738],
[ 68.151],
[ 49.02 ],
...,
[ 296.73 ],
[ 107.052],
[ 87.845]]),
'C': array([... | <p>Something like this:</p>
<pre><code>np.array(list(d.keys()))[np.hstack(d.values()).argmax(axis=1)]
#array(['A', 'B', 'C', 'B', 'B', 'B'],
# dtype='<U1')
</code></pre> | python|arrays|numpy | 2 |
353,033 | 43,213,880 | Using 'datetime64[ns]' format for extraction from pandas dataframe | <p>I have a dataframe which has elements as:</p>
<pre><code>df1[1:4]
Sims
2014-01-02 [51, 53, 51, 3...
2014-01-03 [56, 48, 64, ...
2014-01-04 [57, 45, 47, ...
</code></pre>
<p>The sims are list of 500 elements each.</p>
<p>I have another dataframe as:</p>
<pre><code>df2[1:4]
... | <p><code>df1[df2['Date']]</code> -type indexing tends to error in my experience if you are trying to index on rows instead of columns. The problem is presumably that you let <code>pandas</code> guess over which axis you whish to slice, and this doesn't always pan out as desired.</p>
<p>You could try using a more expli... | python|pandas | 2 |
353,034 | 43,396,855 | Sum of previous rows values | <p>how I can sum previous rows values and current row value to a new column?
My current output:</p>
<pre><code>index,value
0,1
1,2
2,3
3,4
4,5
</code></pre>
<p>My goal output is:</p>
<pre><code>index,value,sum
0,1,1
1,2,3
2,3,6
3,4,10
4,5,15
</code></pre>
<p>I know that this is easy to do with Excel, but I'm lookin... | <p>use <code>cumsum</code></p>
<pre><code>df.assign(sum=df.value.cumsum())
value sum
index
0 1 1
1 2 3
2 3 6
3 4 10
4 5 15
</code></pre>
<p>Or</p>
<pre><code>df['sum'] = df.value.cumsum()
df
value sum
index
0 ... | python|pandas|dataframe | 18 |
353,035 | 43,415,177 | sparse_softmax_cross_entropy_with_logits results is worse than softmax_cross_entropy_with_logits | <p>I implement classic image classification problem with tensorflow, I have 9 classes, first I use <code>softmax_cross_entropy_with_logits</code> as classifier and train network, after some steps it gives to about 99% train accuracy,</p>
<p>Then test the same problem with <code>sparse_softmax_cross_entropy_with_logits... | <p>I found the problem, thanks to @mrry for helpful comment, actually I mistake about calculation of accuracy, in fact, "sparse_softmax" and "softmax" has the same loss(or cost) for input logits,</p>
<p>for computation accuracy, I change </p>
<p><code>correct_pred = tf.equal(tf.argmax(self.score_,1), tf.argmax(y,1))<... | python|tensorflow|deep-learning|softmax | 3 |
353,036 | 43,366,464 | How to visualize text in tensorboard? | <p>I'm working on imdb Large Movie review dataset in tensorflow. Is there any possibility, so that I can visualize the text in the dataset. Like word count, length of the review, mean, variance, etc. using tensorboard.? </p> | <p>As of release 1.2.0 there is now a <a href="https://www.tensorflow.org/api_docs/python/tf/summary/text" rel="nofollow noreferrer"><code>tf.summary.text</code></a> method.</p> | tensorflow|deep-learning|sentiment-analysis|lstm|tensorboard | 1 |
353,037 | 43,215,329 | How to turn a CSV file with several key value pairs a row into a dataframe with keys as columns | <p>I am trying to use panda to convert a csv.
I have *.csv file look like:</p>
<pre><code>header1,value1,header2,value2,header3,value3,header4,value4
header2,value2,header3,value3
header1,value1,header2,value2
header1,value1,header3,value3,header4,value4
</code></pre>
<p>I would like to have a new csv like: ... | <p>Load data without headers to keep it all in your dataframe:</p>
<pre><code>df=pd.read_csv('foobar.txt', sep=',', header=None)
</code></pre>
<p>Then reshape it as a seriesbut keep the level 0 index to get row numbering from the original csv: </p>
<pre><code>s = df.stack()
s.index = s.index.droplevel(-1)
s
Out[92]... | python|csv|pandas | 0 |
353,038 | 43,064,947 | Python - read numpy array from file | <p>I have an input file formatting as follow:</p>
<pre><code>* 1 *
[[1.0 2.0 3.0 4.0] [ 5.0 6.0 7.0 8.0]] [1.5 2.5 3.5]
* 2 *
[[8.0 7.0 6.0 5.0] [ 1.0 2.0 3.0 4.0]] [4.5 5.5 6.5]
</code></pre>
<p>Sizes of matrix and vector are not known. I would like to get the number inside stars, the matrix and the vector into 3 d... | <p>As i found a solution, i share it in case someone needs to deal with the same problem.</p>
<p>I change <code>vect</code> from <code>numpy.array</code> to <code>[]</code>.
Then i append each vector in <code>vect</code> one at a time.
Finally, i cast <code>vect</code> to a <code>numpy.array</code>.</p>
<p>Here the l... | python|numpy | 0 |
353,039 | 43,043,513 | numpy - get random integers as floats | <p>So in a fixedpoint iteration, I've changed the way the matrix is initialised from</p>
<pre><code>def init(M,N):
return 2.5*np.ones([M,N])
</code></pre>
<p>to</p>
<pre><code>def init(M,N):
return nprnd.randint(1,6,[M,N])
</code></pre>
<p>where</p>
<pre><code>import numpy as np
import numpy.random as nprnd
</c... | <p>You can just do an explicit cast using <code>astype</code>:</p>
<pre><code>nprnd.randint(1,6,[M,N]).astype("float")
</code></pre> | python|numpy|casting | 7 |
353,040 | 43,243,549 | Subtract two columns of lists in pandas | <p>I have a dataframe with two columns of 1D lists of the same size, and I would like to form a third column with the difference of these vectors. Conceptually:</p>
<pre><code>df['dV'] = df['v1'] - df['v2']
</code></pre>
<p>So that if <code>df['v1']</code> looks like:</p>
<pre><code>0 [0.2, 0.1, 0.0]
1 [0.5, -0.4,... | <p>If you want to change <code>ndarray</code> to <code>list</code> just do <code>list(df['dV'])</code>
Broadcasting errors happen usually when arrays have different size. Are you sure their shapes are equal? You can use <code>.shape</code> to get that information. You can read more about broadcasting <a href="https://d... | pandas|numpy | 2 |
353,041 | 43,062,613 | How to randomly select rows from a data set using pandas? | <p>I have a data set with 36k rows. I want to randomly select 9k rows from it using pandas. How do I accomplish this task?</p> | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="noreferrer"><code>sample</code></a> - <code>9k</code> or <code>25%</code> rows:</p>
<pre><code>df.sample(n=9000)
</code></pre>
<p>Or:</p>
<pre><code>df.sample(frac=0.25)
</code></pre>
<p>Another ... | pandas|scikit-learn|data-science | 14 |
353,042 | 43,344,969 | match string in txt file and get the number next to it python | <p>i have a directory which has around 100 txt files.</p>
<p>this is how my txt file looks</p>
<pre><code>...............some text...............
('Doc accuracy ', 0.936046511627907, ' No of corrections ', 11)
http://10.x.x.1/link
...............some text...............
('FinalSpreadSheet_len', 172)
Done processing f... | <p>Since you already got a list with all files in a directory and assuming you stored the names inside a list called <code>filenames_list</code>, this code will work.</p>
<p>For each <code>filename</code> inside a <code>filename_list</code>, this code will:</p>
<ol>
<li><code>open</code> the file</li>
<li><code>read<... | python|pandas | 1 |
353,043 | 43,164,320 | Calculating monthly price gains using 2 separate DateFrames in Pandas Python | <p>I am trying to calculate the price gain of user’s share market transactions.</p>
<p>I have 2 DataFrames:</p>
<p>the first has purchase data. This is called ‘buys’. Sample below.</p>
<pre><code>Acceptance_Date Symbol Username Volume
01-Jan-2017 FB John 423
01-Jan-2017 FB Lucy ... | <p>Here's what I would do:</p>
<p>First pivot your market table so you have symbols as indices and dates as columns:</p>
<pre><code># assuming you are using close-to-close returns
market_pivot = market.pivot_table(index='Symbol', columns='Date', values='Close')
</code></pre>
<p>Second, define a function to get retur... | python|pandas|datetime | 0 |
353,044 | 72,239,073 | Panda dataframe replace() method for row numbers | <p>I need to replace some values in a column with a specific value using the row numbers list of the required values as an array like following array.Can I use <code>dataframe.replace()</code> for that?</p>
<pre><code>row_numbers = [ 4, 7, 15, 18, 49, 60, 78, 80]
</code></pre> | <p>You can use <code>loc</code></p>
<pre class="lang-py prettyprint-override"><code>df.loc[row_numbers, 'col'] = 3
</code></pre>
<p>in case your index is not number</p>
<pre class="lang-py prettyprint-override"><code>df['col'].iloc[row_numbers] = 3
</code></pre> | python|pandas | 0 |
353,045 | 72,354,629 | tensorflow python framework.errors_impl.UnimplementedError: Graph execution error: | <p>I have a problem while executing the model.fit() line in my python program. I got the following error on executing it. (Sorry for the bad format, I am new here). I don't know, where exactly I messed up with the code</p>
<p>Would be grateful for the suggestions!</p>
<blockquote>
<p>*2022-05-23 22:30:40.647915: W tens... | <p>I was able to reproduce the issue with <a href="https://www.kaggle.com/datasets/chetankv/dogs-cats-images" rel="nofollow noreferrer">Cats-vs-Dogs</a> dataset.
The error is caused due to the following line</p>
<pre><code>y_train_labels.append(str(img_label))
</code></pre>
<p>Replacing the above line with the followi... | python|numpy|tensorflow|keras|training-data | 0 |
353,046 | 72,453,063 | Retrieve a lot of data from Yahoo finance | <p>I have a csv file which contains the ticker symbols for all the stocks listed on Nasdaq. Here is a <a href="https://www.nasdaq.com/market-activity/stocks/screener" rel="nofollow noreferrer">link</a> to that csv file. One can download it from there. There are more than 8000 stocks listed. Following is the code</p>
<p... | <p>You can use <code>yf.download</code> to download all tickers asynchronously::</p>
<pre><code>tick_pd = pd.read_csv('nasdaq_screener_1654024849057.csv', usecols=[0])
df = yf.download(tick_pd['Symbol'].tolist(), period='max')
</code></pre>
<p>You can use <code>threads</code> as parameter of <code>yf.download</code>:</... | python|pandas|yfinance | 2 |
353,047 | 72,332,647 | NumPy: How to make a 2-dim data array containing both x inputs and f(x) outputs (using example of kinematics) | <p>Trying to make a simple kinematics array (for fun!) where</p>
<ol>
<li>You're prompted for an int input tmax that determines t = [0, tmax]</li>
</ol>
<p>So this would mean that if you input tmax = 5, the time interval would be t = [0, 5] seconds</p>
<ol start="2">
<li>You're prompted for a float input jerkc (third d... | <p>The special thing about NumPy arrays is that you can do calculations with it. This means that the if you multiply 2 arrays, the result array will contain the values of those arrays multiplied with eachother.<br />
As in this example:</p>
<pre class="lang-py prettyprint-override"><code>>>> array1=array([1,2,... | python|arrays|numpy|numpy-ndarray | 0 |
353,048 | 72,291,980 | How to recode/ map shared columns for dataframe stored in a dictionary? | <p>I want to recode the 'Flavor' field, which both data sets share.</p>
<p>I successfully stored the data as data frames in a dictionary, but the names assigned (for ex. 'df_Mike') are strings and not callable/ alterable objects.</p>
<p>Do let me know where I'm going wrong and explain why.</p>
<pre><code>name = ['Mike'... | <p>You are iterating over the keys in the dictionary. If you want to iterate over the values, you can use <a href="https://docs.python.org/3.7/library/stdtypes.html?highlight=dict%20values#dict.values" rel="nofollow noreferrer"><code>dict.values()</code></a>. For example:</p>
<pre><code>for df in d.values():
df.map... | python|python-3.x|pandas|dataframe|dictionary | 0 |
353,049 | 72,457,508 | Aggregate functions on a 3-level pandas grupby object | <p>I want to make a new df with simple metrics like mean, sum, min, max calculated on the Value column in the df visible below, grouped by ID, Date and Key.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>ID</th>
<th>Key</th>
<th>Date</th>
<th>Value</th>
<th>x</th>
<th>y</th>... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>DataFrame.drop_duplicates</code></a> with <a href="https://pandas.pydata.org/docs/user_guide/groupby.html#named-aggregation" rel="nofollow noreferrer">named aggregation</a>:</... | python|pandas|dataframe | 1 |
353,050 | 72,225,756 | TensorFlow optimisation during running model speed up Predict | <p>I want to disable a computation of several filters during Predict call with Tensorflow 2 and Keras.</p>
<p>Do i have to modify the source code of Tensorflow to achieve that ?</p> | <p>Short answer: No, you don't have to modify the Tensorflow source code.</p>
<p>Long answer with example detailled <a href="https://stackoverflow.com/a/61639160/6299772">here</a>.</p> | tensorflow|keras|optimization|predict | 0 |
353,051 | 72,283,433 | Pandas Groupby - Append lists | <p>My pandas DataFrame has a column with <code>lists dtype</code>. I'd like to <code>Group By</code> and aggregate the DataFrame and append the lists.</p>
<p>Here's a sample DataFrame:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'id': [1, 1, 2],
'cat': ['A','A','B'],
... | <p>A simple way would be to aggregate the <code>lst</code> column using <code>sum</code> and <code>v</code> using <code>mean</code>:</p>
<pre><code>df.groupby(['id', 'cat'], as_index=False).agg({'lst': 'sum', 'v': 'mean'})
</code></pre>
<hr />
<pre><code> id cat lst v
0 1 A [l0, l1, l2, l3,... | python|pandas | 2 |
353,052 | 72,147,631 | (Pandas, Python) Selecting indices of a parent DF based on shared column values with a child DF | <p>(I recently asked this question on r/learnpython (<a href="https://www.reddit.com/r/learnpython/comments/uifnc5/pandas_selecting_indices_of_a_parent_df_based_on/" rel="nofollow noreferrer">here</a>), but didn't get any feedback, so am re-posting it verbatim here. Hope that is okay!)</p>
<p>Suppose I have a DataFram... | <p>One option is to use <code>MultiIndex.map</code>:</p>
<pre class="lang-py prettyprint-override"><code>cols = ['x1','x2']
X['A'] = X.set_index(cols).index.map(Y.set_index(cols)['A']).fillna(0).astype(int)
</code></pre>
<p>Another option is left-merge on two columns:</p>
<pre class="lang-py prettyprint-override"><code... | python|pandas|dataframe | 2 |
353,053 | 72,291,704 | Is it possible to auto-size the subsequent input of a layer following torch.nn.Flatten within torch.nn.Sequential in PyTorch? | <p>If I have the following model class for example:</p>
<pre><code>class MyTestModel(nn.Module):
def __init__(self):
super(MyTestModel, self).__init__()
self.seq1 = nn.Sequential(
nn.Conv2d(3, 6, 3),
nn.MaxPool2d(2, 2),
nn.Conv2d(6, 16, 3),
nn.MaxPoo... | <p>PyTorch (>=1.8) has <a href="https://pytorch.org/docs/stable/generated/torch.nn.LazyLinear.html" rel="nofollow noreferrer">LazyLinear</a> which infers the input dimension.</p> | python|machine-learning|neural-network|pytorch | 2 |
353,054 | 72,230,659 | Pandas : Create new column based on text values of other columns | <p>My dataframe looks like this:</p>
<pre class="lang-python prettyprint-override"><code> id text labels
0 447 glutamine synthetase [protein]
1 447 GS [protein]
2 447 hepatoma [indication]
3 447 NaN ... | <p>Use <code>df.explode</code> with <code>Groupby.agg</code> and <code>df.pivot</code>:</p>
<pre><code>In [417]: out = df.explode('labels').groupby(['id', 'labels'])['text'].agg(','.join).reset_index().pivot('id', 'labels').reset_index().droplevel(0, axis=1).rename_axis(None, axis=1)
In [423]: out.columns = ['id', 'in... | python|pandas|dataframe | 1 |
353,055 | 72,180,278 | Why is the branched output of Tensorflow model yielding only from 1 branch? | <p>I'm a Tensorflow beginner and I'm trying to reproduce the TF Classification by Retrieval model as explained <a href="https://blog.tensorflow.org/2022/01/on-device-one-shot-learning-for-image.html" rel="nofollow noreferrer">here</a> using Python since the blog provides the code in C++.</p>
<p>The model architecture s... | <p>So after looking around, referring to this <a href="https://github.com/keras-team/keras/issues/7362#issuecomment-335366278" rel="nofollow noreferrer">thread</a>, the "correct" way to use TF operation (in my case is <code>tf.nn.embedding_lookup</code> and <code>tf.reduce_max</code>) is by wrapping them in a... | python|tensorflow|data-retrieval|embedding-lookup | 0 |
353,056 | 72,365,410 | how to retrieve data from json file using python | <p>I'm doing api requests to get json file to be parsed and converted into data frames. Json file sometimes may have empty fields, I am posting 2 possible cases where 1st json fill have the field I am looking for and the 2nd json file has that field empty.</p>
<p>1st json file:</p>
<pre><code>print(resp2)
{
"en... | <p>Why not create a new dict based on whether there's value for <code>metadata</code> or not?</p>
<p>Here's an example (this should work with both response types):</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
def find_value(response: dict, key: str) -> str:
result = []
try:
... | python|json|pandas | 1 |
353,057 | 72,433,204 | dropping rows from dataframe when column contains a decimal value | <p>I have a dataframe with the column <code>SimTime</code>, which has values like</p>
<pre><code>SimTime
0
2
4
4.4
6
6.4
8
</code></pre>
<p>I only want to keep values which are integers and I am using the following snippet, however, I'm unable to see any changes in the dataframe.</p>
<pre><code>df=df.drop(df.index[(df[... | <p>You can compare values converted to integers in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>df1 = df[df.SimTime==df.SimTime.astype(int)]
</code></pre>
<p>Your solution is with compare by <c... | python|pandas|dataframe | 0 |
353,058 | 72,181,798 | why does nested loop start from 0 and how to change it to start from where it had left? | <p>I want to generate a code that will write 20 rows from each of two different dataframes. Therefore, I created something like below. Everything works fine except nested loop (u) starts from 0 each time. Can you help me how to fix it to start from where it left, please?</p>
<pre><code> for t, row in results_table1.ite... | <p>You can initialize u outside of your loop increment u and use as index to the second dataframe.</p>
<pre><code>u = 0
for t, row in results_table1.iterrows():
f.write(" & ".join([str(x) for x in row.values]) + " \\\\\n")
if t > 0 and t % 20 == 0:
for i in range(0,20):
... | python|pandas|loops|datatable | 0 |
353,059 | 72,364,590 | How to Plot a plot with multiple values? | <p>Could anyone help me?</p>
<p>I need to draw a plot from the dataframe but I have no idea how to draw it. So my ideal plot look like this, which means each x-axis provides multiple values(and they absolutely can't be covered by each other).
<a href="https://i.stack.imgur.com/TltzV.jpg" rel="nofollow noreferrer"><img ... | <p>With the toy dataframe you provided, here is one way to do it:</p>
<pre class="lang-py prettyprint-override"><code># Prepare data for plotting
new_df = pd.concat(
[
pd.DataFrame(
{
"x": [i + j * 10 - 1 for i in range(1, len(df[col]) + 1)],
"value... | python|pandas | 1 |
353,060 | 72,363,468 | How to order sentences based on pairwise probabilities? | <p>I'm generating pairwise sentence order probabilities in the following way:</p>
<pre><code>import itertools
import random
import numpy as np
import tensorflow as tf
from transformers import BertTokenizer, TFBertForNextSentencePrediction
np.set_printoptions(suppress=True)
cache_dir = '/path/to/cache/dir'
pretrained_... | <p>The output probabilities represent how likely it is that the first sentence is followed by the second one.</p>
<p>The two probabilities sum to 1 since this is a binary problem, and they represent the probability of answering "no" to the question (first value) and the probability of answering "yes"... | python|nlp|huggingface-transformers | 0 |
353,061 | 72,293,129 | How to save pandas dataframe rows as seperate files with the first row fixed for all? | <p>I have a DataFrame with multiple columns and rows. The rows are student names with marks and the columns are marking criteria. I want to save the first row (column names) along with each row in seperate files with the name of the student as the name file.</p>
<p>Example of my data:</p>
<div class="s-table-container"... | <p>Just note that you have to have a unique name to save a file. Otherwise files with the same name will overwrite each other.</p>
<pre><code># `````````````````````````````````````````````````````````````````````````
### create dummy data
column1_list = ['John Doe','John Doe','Not John Doe','special ß ß %&^ charac... | python|pandas|dataframe | 1 |
353,062 | 72,166,657 | Displaying images from each class of a batched tensorflow dataset | <p>I'm doing an assignment creating a cv model with 6 different classes.</p>
<p>I've loaded my dataset as per this example:</p>
<p><a href="https://keras.io/examples/vision/image_classification_from_scratch/" rel="nofollow noreferrer">https://keras.io/examples/vision/image_classification_from_scratch/</a></p>
<p>but no... | <p>In the example below, I am visualizing the dataset with five classes. I’m plotting five images of five classes from the dataset.</p>
<pre><code>import random
# Selecting a random batch from train_ds
# Note that if a particular batch doesn’t have all the classes (six in this case, then we only print the existing clas... | tensorflow|keras|computer-vision | 0 |
353,063 | 72,255,562 | Cannot import name 'dtensor' from 'tensorflow.compat.v2.experimental' | <p>I am new to TensorFlow for a school project, although am having problems trying to run TensorFlow on my Windows 10 machine. Code runs fine on my MacOS machine.
Any help is greatly appreciated</p>
<pre><code>Traceback (most recent call last):
File "c:\Users\Fynn\Documents\GitHub\AlpacaTradingBot\ai.py", l... | <p>This can be caused by an incompatibility between your <code>tensorflow</code> and your <code>keras</code> versions. In particular I see this with <code>tensorflow==2.6.0</code> and <code>keras==2.9.0</code>, though I would not be surprised if other versions can cause this as well.</p>
<p>Either update your <code>ten... | python|python-3.x|tensorflow|machine-learning|keras | 16 |
353,064 | 72,249,659 | Converted model (from h5 to tflite) doesn't work with tflite_flutter plugin | <p>I'm new to tensorflow, I created a simple tflite model from <a href="https://teachablemachine.withgoogle.com/" rel="nofollow noreferrer">Teachable Machine</a> and it worked great in flutter app with tflite_flutter plugin.</p>
<p>Then I had to change the model with a pretrained .h5 model. I converted .h5 model to .tf... | <p>I used convolution layers and lstm layers in training. Some operations in those layers don't have TensorFlow Lite equivalents and convertion from .h5 to .tflite is not possible without <a href="https://www.tensorflow.org/lite/guide/ops_compatibility" rel="nofollow noreferrer">TensorFlow Lite and TensorFlow operator ... | flutter|tensorflow|tensorflow-lite | 0 |
353,065 | 72,167,934 | Pandas json_normalize converts column of int values to float whan one of values is NaN | <p>I have noticed a behaviour that I don't quite understand.</p>
<p>I am doing a conversion of a list of dataclass items into a dataframe.
When all values are not-None, everything works as expected:</p>
<pre><code>from dataclasses import dataclass
from dataclasses import asdict
from pandas import json_normalize
@datac... | <p>You can cast the <code>id</code> column as <a href="https://pandas.pydata.org/docs/user_guide/integer_na.html" rel="nofollow noreferrer">nullable integer data type</a>.</p>
<pre class="lang-py prettyprint-override"><code>>>> df['id'] = df['id'].astype('Int64') # note the capital "I"
>>> ... | python|pandas|json-normalize | 1 |
353,066 | 72,482,760 | Fixing a coulmn in a datafram by a conditon (pandas) | <p>I have a data set of purchase:</p>
<pre><code>ORDER_ID | BIN | PURCHASE AMOUNT
1 383218 56.43
2 nan 46
3 3212 56
</code></pre>
<p>My Task:</p>
<blockquote>
<p>Check on the formatting of the credit card bin data is 6 digits, and if needed, add leading zeros, which may have been ... | <pre><code>df['BIN'] = (df['BIN']
.fillna(0) # to remove nan
.astype(int) # to remove decimals
.astype(str) # to convert to stirng
.str.zfill(6) # to zero fill the rows
)
</code></pre> | python|pandas | 0 |
353,067 | 72,290,130 | Python re, how to capture 12"" / 14"" | <p>I need to capture patterns like this one:</p>
<pre><code>12"" / 14""
</code></pre>
<p>in</p>
<pre><code>"Factory SP1 150 12"" / 14"""
</code></pre>
<p>The numbers change (always 2 digits), the rest doesn't.<br />
Note that the double quotes at the ends of the string ... | <p>You can use <code>r'\d{2}""\s*/\s*\d{2}""'</code> as regex:</p>
<pre><code>s = '"Factory SP1 150 12"" / 14"""'
re.findall(r'\d{2}""\s*/\s*\d{2}""', s)
</code></pre>
<p>output:</p>
<pre><code>['12"" / 14""']
</code></pre>
<p>Be ... | python|pandas|python-re | 1 |
353,068 | 72,279,689 | Keeping track of running total whilst subtracting values at certain timestamps | <p>I have a DataFrame like so:</p>
<pre class="lang-py prettyprint-override"><code> time_start pred time_end_floor xyz
0 2022-05-06 12:00:00 26 NaT NaN
1 2022-05-06 13:00:00 16 NaT NaN
2 2022-05-06 14:00:00 10 2022-05... | <p>The exact expected output is unclear (do you need a shift?), but you can use:</p>
<pre><code>df['sum'] = df['pred'].cumsum().sub(df['xyz'].fillna(0, downcast='infer').cumsum())
</code></pre>
<p>unless you want 26+16+10 for all the NaN values? Here as sum2</p>
<pre><code>s = df['pred'].cumsum()
df['sum2'] = s.sub(df[... | python|pandas|dataframe|numpy|time-series | 1 |
353,069 | 72,244,542 | Using numpy.where function with multiple conditions but getting valueError | <p>So I have a dataframe with multiple columns with numbers in them. It looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>H</th>
<th>C</th>
<th>T</th>
<th>P</th>
<th>R</th>
</tr>
</thead>
<tbody>
<tr>
<td>300</td>
<td>200</td>
<td>500</td>
<td>0.3</td>
<td></td>
</tr>
<tr>
<t... | <p>You should use bitwise <code>&</code> and parantheses, rather than <code>and</code>.</p>
<pre><code>df['R'] = numpy.where((df['H'] > df['T']) & (df['P'] > 0),
df['C'] / df['T'] - 1, 0)
</code></pre> | python|pandas|numpy | 1 |
353,070 | 72,387,698 | How to calculate mean cycle wise in python | <p><a href="https://i.stack.imgur.com/1kihb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1kihb.png" alt="enter image description here" /></a></p>
<p>How can I calculate cycle-wise average (mean for values circled in red) only for true conditions (cycle value 1) for other column DCUL13.LC01? Is the... | <p>You can aggregate mean for consecutive <code>1</code> create by cumulative sum and filtered with inverted mask by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>df = pd.DataFrame({'col' : rang... | python|pandas|dataframe|numpy | 1 |
353,071 | 72,155,199 | Changing string to integer in Pandas | <p>The data set had "deaths" as object and I need to convert it to the INTEGER. I try to use the formula from another thread and it doesn't seem to work.</p>
<pre><code>******Input:******
data.info()
*****Output:*****
data.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1270 entries, 0 to 1271
... | <p>If you have nulls (np.NaN) in the column it will not convert to int type.
You need to deal with nulls first.</p>
<p>1 Either replace them with an int value:</p>
<pre><code>df.deaths = df.deaths.fillna(0)
df.deaths = df.deaths.astype(int)
</code></pre>
<p>2 Or drop null values:</p>
<pre><code>df = df[df.deaths.notna(... | python|pandas | 0 |
353,072 | 72,432,171 | Pandas NA values list | <p>I was trying to remove <strong>b'NA'</strong> from default pandas na_values. They are defined in <strong>pandas._libs.parsers</strong>. I did it by importing the list and:</p>
<pre class="lang-py prettyprint-override"><code>from pandas._libs.parsers import _NA_VALUES
disable_na_values = [b"NA"]
my_default... | <p>The reason you see a list of byte strings is because you are importing the wrong variable. You should use STR_NA_VALUES instead, which give you a set. From this set you can easily remove the items you don't want by subtracting. See below:</p>
<pre><code>from pandas._libs.parsers import STR_NA_VALUES
disable_na_v... | python|pandas | 0 |
353,073 | 72,365,099 | How to combine dataframe rows, and combine their string column into list? | <p>Say I have a Pandas dataframe:</p>
<pre><code>index name A
0 one a
1 two a
2 one b
3 two a
</code></pre>
<p>How can I merge rows with identical 'name' so that the new column A is a list of all the A associated with each 'name'? So, the output would be:</p>
<pre><code... | <p>This will group by the name column and set all of the values in a to a unique list</p>
<pre><code>import pandas as pd
import numpy as np
df.groupby(['name'])['A'].apply(lambda x : np.unique(list(x))).reset_index()
</code></pre> | python|python-3.x|pandas|dataframe | 0 |
353,074 | 72,274,616 | How to copy tables from a pdf file to excel file, except the headers using python | <p>I have extracted Tables from a pdf file to an excel(xlsx) file using python. Now I want All the data except the headers to appear in the excel file. What changes should I make to the code. I am attaching the code below for you.</p>
<p>The code:-</p>
<pre><code>import camelot
import PyPDF2
import pandas as pd
# PDF ... | <p>I have no Santander Bank Statement to test, but I am almost sure you will manage to adjust it to your needs:</p>
<pre><code>import camelot
import pandas as pd
# PDF file to extract tables from
file = r"C:/Users/mahma_dv2pq9y/Downloads/santander.pdf"
# extract all the tables in the PDF file
tables = c... | python|python-3.x|pandas|python-3.7|pypdf2 | 0 |
353,075 | 72,188,250 | Pandas, arithmetic operation on grouped data | <p>let say I have a pandas data frame and already grouped as</p>
<pre><code>grp=df.groupby(['a','b' ]).sum()
</code></pre>
<p><a href="https://i.stack.imgur.com/C3qRk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C3qRk.png" alt="enter image description here" /></a></p>
<p>now I would like to calcul... | <p>You can use <code>xs</code> to a select particular level of a MultiIndex:</p>
<pre class="lang-py prettyprint-override"><code>out = df.xs(1, level=1) / df.xs(0, level=1)
</code></pre>
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code> aaaa
P 1 0.022727
</code></pre> | python|pandas|multi-index | 2 |
353,076 | 72,245,324 | Python Pandas how to get f-string to work in an url | <p>I am getting an error of <code>urllib.error.HTTPError: HTTP Error 404: Not Found.</code> I feel like f-string should work for the url but it is not how would I fix this?</p>
<pre><code>import pandas as pd
stockslist = ['f','goog', 'aapl']
for s in stockslist:
url = f'https://finance.yahoo.com/quote/{s}/'
pr... | <p>you have to parse html first then read it</p>
<p>try it:</p>
<pre><code> import pandas as pd
import requests
stockslist = ['f','goog', 'aapl']
for s in stockslist:
print(s)
url = f'https://finance.yahoo.com/quote/{s}/'
html = requests.get(url).content
tablelist = pd.rea... | python|pandas | 3 |
353,077 | 72,342,559 | Unexpected behavior after conda force reinstall | <p>After downgrading numpy from version 1.22.4 to 1.19.5 with the following command-</p>
<pre><code>conda install numpy==1.19.5 --force-reinstall
</code></pre>
<p>Python behaves unexpectedly. For example, <code>pip list</code> and <code>conda list</code> both show that the version of numpy remains <strong>1.22.4</str... | <p>Occasionally, I have found that Python can conflict with packages, especially with bigger frameworks, as fully uninstalling it can be difficult. That's the beauty of virtual Python environments, you are able to just create a new one for specific versions, and not have to deal with multiple versions on your native Py... | python|numpy|anaconda|conda | 2 |
353,078 | 72,318,075 | Is numpy rng thread safe? | <p>I implemented a function that uses the numpy random generator to simulate some process. Here is a minimal example of such a function:</p>
<pre><code>def thread_func(cnt, gen):
s = 0.0
for _ in range(cnt):
s += gen.integers(6)
return s
</code></pre>
<p>Now I wrote a function that uses python's sta... | <p><strong>TL;DR</strong>: as pointed out by @MichaelSzczesny, the main problem appear that you use processes which operate on a copy of the same RNG object having the same initial state.</p>
<hr />
<p>Random number generator (RNG) objects are initialized with an integer called a seed which is modified when a new numbe... | python|multithreading|numpy|random|thread-safety | 2 |
353,079 | 72,353,661 | comparing Pandas dataframes by header uring regex | <p>I have two dataframes let's call them df1 and df2, which columns with slightly different headers which I need to compare.
For example</p>
<pre><code>df1 = pd.Dataframe('0001_baseline':[1,2,3], '0002_baseline':[1,2,3])
df1 = pd.Dataframe('0001_w2':[1,2,3], '0002_w2':[1,2,3])
</code></pre>
<p>I need to do the ratio of... | <p>You can start by making the columns have identical elements (just the numbers and no strings). Here's how you would do it with regex:</p>
<pre><code>import re
import pandas as pd
df1 = pd.DataFrame({'0001_baseline':[1,2,3], '0002_baseline':[1,2,3]})
df2 = pd.DataFrame({'0001_w2':[1,2,3], '0002_w2':[1,2,3]})
namesRe... | python|regex|pandas|dataframe|nsregularexpression | 0 |
353,080 | 72,371,607 | How to index/slice 3D numpy array | <p>I'm relatively new to python/numpy. I have a 3D numpy array of TxNxN. It contains a sequence of symmetrical NxN matrices. I want convert it to a 2D array of TxM (where M = N(N+1)/2). How can I do that? I can certainly use 3 loops, but I thought there probably better ways to do that in python/numpy.</p> | <p>It seems that you want to get the upper triangle or lower triangle of each symmetric matrix. A simple method is to generate a mask array and apply it to each 2D array:</p>
<pre><code>>>> e
array([[[0, 1, 2, 3],
[1, 2, 3, 0],
[2, 3, 0, 1],
[3, 0, 1, 2]],
[[1, 2, 3, 4],
... | python|arrays|numpy|indexing | 1 |
353,081 | 72,485,157 | Pandas more time efficient flatten | <p>In this <a href="https://stackoverflow.com/questions/72462008/pandas-json-normalize-list-of-dictionaries-into-specified-columns">question</a> I got help with flatten of each row in a column of a dataframe.</p>
<pre><code>[{'first_open_time': {'int_value': '1652796000000', 'set_timestamp_micros': '1652792823456000'}}... | <p>You can use nested list and dict comprehension:</p>
<pre><code>data = [[{'first_open_time': {'int_value': '1652796000000', 'set_timestamp_micros': '1652792823456000'}}, {'User_dedication': {'string_value': '1', 'set_timestamp_micros': '1653137417352000'}}, {'User_activity': {'string_value': '1', 'set_timestamp_micro... | python|pandas|flatten|json-flattener | 1 |
353,082 | 72,426,424 | filter pandas DataFrame column list with other list | <p>Input DataFrame :</p>
<pre><code>data = { "id" : ['[1,2]','[2,4]','[4,3]'],
"name" : ['a','b','c'] }
df = pd.DataFrame(data)
filterstr = [1,2]
</code></pre>
<p>Expected Output:</p>
<pre><code>id name
[1,2] a
[2,4] b
</code></pre>
<p>Tried Code :
<code>df1 = df[df.id.m... | <p>Taking exactly what you've given:</p>
<pre><code>data = { "id" : ['[1,2]','[2,4]','[4,3]'],
"name" : ['a','b','c'] }
df = pd.DataFrame(data)
filterstr = [1,2]
</code></pre>
<p>I do:</p>
<pre><code>df['id'] = df['id'].apply(eval) # Convert from string to list.
output = df[df.id.map(l... | python|pandas|dataframe | 1 |
353,083 | 72,208,324 | Implementing a partial pivot If condition for Gaussian Elimination in Python | <p>I've figured out how to code a function such that you can row reduce and solve linear algebra problems, the only issue I'm running into is setting up the if condition that does the partial pivoting when the constant that is used to row reduce is equal to 0. I've attempted it below and the logic makes sense but am st... | <p>One issue is this code:</p>
<pre><code> for i in range (nr-1):
M[r][i]=M[r+1][i] # line 1
M[r+1][i] = M[r][i] # line 2
const = M[r][r] # line 3
</code></pre>
<p>The line I've commented as <code>line 2</code> simply undoes the work of <code>line 1</code>. If you're att... | python|arrays|numpy | 0 |
353,084 | 72,480,610 | how to convert all json files of directory to text files in python? | <p>I want to convert all json files of directory to text files through this command: but I got error. How can I change it?</p>
<pre><code>import pandas as pd
df = pd.read_json(r"/media/New Volume/a3d/pdb/json_parser/ *.json ")
df.to_csv(r"/media/New Volume/a3d/pdb/json_parser/ *.txt ", index = False... | <pre><code>import os
import pandas as pd
# Get the list of json files, which are in the folder:
str_address = r"/media/New Volume/a3d/pdb/json_parser/"
lst_files = [i for i in os.listdir(str_address) if i.endswith(".json")]
# Loop through the json files
for file_ in lst_files:
df = pd.read... | python|pandas | 1 |
353,085 | 72,275,631 | Giving two inputs to as single model and concatenating them | <p>I have a model that takes one image as input and it works fine. now I want to give one more transformed image with the same dimensions as the first one as input to the model. The model should learn from both images. The below code shows an error: "<strong>init</strong>() takes 2 positional arguments but 3 were ... | <p>You've mentioned that 2 input images have the same size, so no need to pass 2 values on model instantiating (<code>model = MyNet(input_dim)</code>).</p>
<p>But <code>forward</code> then requires 2 inputs in your case it looks ok</p>
<pre class="lang-py prettyprint-override"><code># init passing only single value `in... | image-processing|deep-learning|pytorch | 0 |
353,086 | 72,359,348 | add values based on row value | <p>I have a code that creates csv files after certain operations with original dataframe:</p>
<pre><code>import pandas as pd
timetable = pd.read_excel('timetable.xlsx')
data = {"stop_id": timetable['stop_id'], "arrival_time": timetable['arrival_time'], 'route_id': timetable['route_id']}
df = pd.D... | <p>quite self explanatory:</p>
<pre><code>import pandas as pd
df = pd.read_excel('timetable.xlsx', converters={'stop_id':int,'route_id':int})
# grouping by stop_id & arrival_time, also joining route_id to the sorted list, counting size of each stop_id group
# all ends up in multi-index dataframe, .reset_index a... | python|pandas | 1 |
353,087 | 72,318,147 | How to add sub-headers to the pandas Dataframe in the loop in python? | <p>I have the empty data frame, with the header of the Data frame indicating the groups. Example,</p>
<pre><code>df = pd.DataFrame(columns=['group1', 'group2', 'group3', 'group4', 'group5', 'group6'])
</code></pre>
<p>Now, I want add the sub-headers to each empty column in loop, because the original data frame is long.... | <pre class="lang-py prettyprint-override"><code>groups = [f"group{i+1}" for i in range(6)]
conditions = [f"condition{i+1}" for i in range(2)]
df = pd.DataFrame(columns=pd.MultiIndex.from_product([groups, conditions]))
</code></pre> | python|python-3.x|pandas|dataframe | 1 |
353,088 | 72,355,315 | How to group data by count of columns in Pandas? | <p>I have a CSV file with a lot of rows and different number of columns.</p>
<p>How to group data by count of columns and show it in different frames?</p>
<p>File CSV has the following data:</p>
<pre><code>1 OLEG US FRANCE BIG
1 OLEG FR 18
1 NATA 18
</code></pre>
<p>Because I have different number of colums in each row... | <p>since pandas doesn't allow you to have different length of columns, just don't use it to import your data. Your goal is to create three seperate <code>df</code>, so first import the data as lists, and then deal with it and its differents lengths.</p>
<p>One way to solve this is read the data with <code>csv.reader</c... | python|pandas|csv | 1 |
353,089 | 72,334,322 | Pandas groupby agg: summing string prices per order ID taking into account item quantity | <p>How do you put the rows with the same order_id such that all their corresponding rows add up to form the resulting Dataframe? (in this case quantity & item price should be added with the corresponding order_id before it, and the choice_description & item_name should be added in their "str" format a... | <p>I'm new to Pandas too, so learning by answering.</p>
<p>With test data as:
<a href="https://i.stack.imgur.com/j8THX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j8THX.png" alt="enter image description here" /></a></p>
<p>You can also do:</p>
<pre><code>import pandas as pd
df = pd.read_csv('./te... | python|pandas|dataframe|pandas-groupby | 0 |
353,090 | 72,152,796 | Error converting dbf to Pandas dataframe using simpledbf | <p>I am attempting to convert a dbf file (from an ESRI shapefile) to pandas dataframe but receive this error:</p>
<blockquote>
<p>ValueError: year 0 is out of range</p>
</blockquote>
<p>I am using the following code:</p>
<pre class="lang-py prettyprint-override"><code>from simpledbf import Dbf5
faunadbf = Dbf5('Listed... | <p>One way to get the records from the dbf files with the <code>00000</code> date fields already set to <code>NaN</code> is to use the <code>dbf</code> library<sup>1</sup>:</p>
<pre><code>table = dbf.Table(
'Listed_Fauna.dbf',
default_data_types={'D':(datetime.date, lambda: float('NaN'))
)
table... | python|pandas|dbf | 1 |
353,091 | 72,166,592 | python pandas read json gzip file from s3 | <p>I'm trying this in <code>aws lambda</code>. When an exception occurs, message e is printed.(refer below code)</p>
<p>But there is no exception message. so I can't figure out what the problem is.</p>
<pre><code>import boto3
import gzip
import pandas as pd
s3 = boto3.resource('s3')
response = s3.Object(bucket, 't... | <p>I use gzip like this:</p>
<pre><code>obj =boto3.resource('s3').Object(bucket, key)
data = gzip.decompress(obj.get()['Body'].read())
df = pd.dataframe(data)
</code></pre> | pandas|aws-lambda|gzip|python-3.8 | 0 |
353,092 | 72,337,522 | How to get distinct rows from pandas dataframe? | <p>I am having trouble with getting distinct values from my dataframe.. Below is the code i currently use, in line 25(3rd of vier()) is the issue: I would like to show the top 10 fastest drivers based on their average heat(go-kart heat) time.</p>
<p><strong>Input:</strong></p>
<pre><code>HeatNumber,NumberOfKarts,KartNu... | <p>You group the datas by Drivername and HeatNumber. See the HeatNumbers, one of them is 411 and another is 408. Because of that pandas understand they are exactly different. If you equals them, they will be one.</p> | python|pandas|dataframe|filter|distinct-values | 0 |
353,093 | 50,462,322 | How is this Python function read? | <p>Wikipedia has the following example code for <a href="https://en.wikipedia.org/wiki/Softmax_function" rel="nofollow noreferrer">softmax</a>.</p>
<pre><code>>>> import numpy as np
>>> z = [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0]
>>> softmax = lambda x : np.exp(x)/np.sum(np.exp(x))
>>> ... | <p>A lambda expression is like an <a href="https://en.wikipedia.org/wiki/Anonymous_function" rel="nofollow noreferrer">anonymous function</a>. In this context, the line</p>
<pre><code>softmax = lambda x : np.exp(x)/np.sum(np.exp(x))
</code></pre>
<p>is equivalent to</p>
<pre><code>def softmax(x):
return np.exp(x... | python|numpy | 1 |
353,094 | 50,398,003 | vectorized way to change numpy array values based on another array | <p>Is there is a vectorized (or better) way of setting values to certain
data points of numpy array based on another way other than this way?</p>
<pre><code>import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
pos = np.array([[1, 2], [2, 0]])
for p in pos:
i,j = p
data[i,j] = 20
print(data... | <p>With later versions of Python you can create a list within a comprehension by unpacking another iterable. We then pass that list to do slice assignment.</p>
<p>The way we are accessing (slicing) is done via <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing" rel="nofoll... | python|python-3.x|pandas|numpy | 3 |
353,095 | 50,259,551 | Add Valus of a List of Tuple if Their Corresponding First Elements are within a Specific Range | <p>Here is my list of tuples:</p>
<pre><code>list=[(8.0056, 1.0), (8.0269, 0.6666666666666666), (8.0302, 1.0), (8.0426, 0.3333333333333333), (8.0492, 1.0), (8.0766, 0.6666666666666666), (8.0817, 0.3333333333333333), (8.1297, 1.0), (8.137, 0.3333333333333333), (8.1778, 1.0), (8.1858, 1.0), (8.1948, 1.0), (8.2044, 0.333... | <p>One line is tough, but two is doable</p>
<pre><code>>>> label, data = np.array(the_list).T
>>> np.bincount((8 + 0.4 * np.arange(12)).searchsorted(label), data, 12)
array([ 0. , 17.66666667, 8.33333333, 4.66666667, 6. ,
4.66666667, 5.66666667, 0.66666667, 2. , 0.... | list|numpy|sum|tuples|conditional-statements | 2 |
353,096 | 50,415,960 | Duplicate dataframe depending on elements on a collection | <p>I need to "duplicate" the elements of a <code>DataFrame</code> as many times as elements in a collection (let's say a list to simplify it). It might be hard to explain by words, so I will show my code:</p>
<pre><code>In [1]: data = {char: [] for char in 'abcd'}
In [2]: n = 3
In [3]: properties = [i for i in range(1... | <h3><code>concat</code></h3>
<p>Are you looking to <code>concat</code> <code>df</code> with itself?</p>
<pre><code>df = pd.concat(
[df] * len(properties), ignore_index=True
).assign(property=np.repeat(properties, len(df)))
</code></pre>
<hr />
<h3><code>reindex</code> + <code>tile</code></h3>
<pre><code>df = df.... | python|pandas | 3 |
353,097 | 50,637,310 | Python : switching values in panda dataframe | <p>I just want to switch correct to false and false to correct in my panda data frame, doing what I have written below changes everything to correct. How do I fix this?</p>
<p>a.loc[(a["outcome"] == 'correct') 'outcome'] = 'false' and ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> by dictionary and if some another values out of <code>dict</code> add <code>fillna</code>:</p>
<pre><code>a = pd.DataFrame({'outcome':['correct','correct','false', 'val']})
print... | python|pandas | 1 |
353,098 | 50,389,954 | Tensorflow failed to use gpu: libnvidia-fatbinaryloader.so.396.26 not found | <p>I need helping on setting up tensorflow with GPU, however got error while trigging tensorflow job with gpu:</p>
<pre><code>ImportError: libnvidia-fatbinaryloader.so.396.26: cannot open shared object file: No such file or directory
</code></pre>
<p>I already have nvidia driver verison 396, cuda tool kit 9 and cudnn... | <p>It seems that 2 nvidia drivers versions are conflicting <code>396.24</code> and <code>396.26</code></p>
<p>When you update the drivers, the corresponding cuda library is not always updated.</p>
<p>You can reinstall libcuda</p>
<pre><code>sudo apt-get purge libcuda1-*
sudo apt-get install libcuda1-396
</code></pre... | tensorflow | 1 |
353,099 | 50,258,986 | API stops working after a while | <p>I wrote an API that takes a directory as an input and it will load every text file (.txt) inside that folder (and its sub-folders) into a Postgres DB.</p>
<p>The API works for a few files (around 3) but when it gets down to "reading" the fourth file, regardless of the file, the program crashes. I even separated the... | <p>Change the server from Tornado to Paste, the API was able to load all the files into the database without any issues.</p>
<pre><code>if __name__ == '__main__':
apiR2A.run( server='paste', host='0.0.0.0', port=3000, reloader=False)
</code></pre> | python|linux|postgresql|pandas|bottle | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.