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 |
|---|---|---|---|---|---|---|
21,000 | 60,402,499 | sklearn, Keras, DeepStack - ValueError: multi_class must be in ('ovo', 'ovr') | <p>I trained a set of DNNs and I want to use them in a deep ensemble. The code is implemented in TF2, but the package deepstack works with Keras as well. The code looks something like this</p>
<pre><code>from deepstack.base import KerasMember
from deepstack.ensemble import DirichletEnsemble
dirichletEnsemble = Dirich... | <p>The documentation for <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html" rel="nofollow noreferrer">roc_auc_score</a> indicates the following:</p>
<pre><code>roc_auc_score(
y_true,
y_score,
*,
average='macro',
sample_weight=None,
max_fpr=None,
mu... | scikit-learn|deep-learning|tensorflow2.0|ensemble-learning | 1 |
21,001 | 60,609,072 | How to create a scatter plot using Pandas, with specific data from a column, and not all of the data in a column | <p>I am currently using </p>
<pre><code>df.plot.scatter(x='Ice_cream_sales', y='Temperature')
</code></pre>
<p>However, I want to be able to only use the ice cream sales that equal to $5, and the temperatures that are precisely at 90 degrees. </p>
<p>How would I go about using the specific values that I'm interested... | <p>The easiest way to do this is to create a dataframe of the subset of values you are interested in.</p>
<p>Say you have a dataframe df with columns 'Ice_cream_sales','Temperature'</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
# Here we subset your dataframe where the temperature is 90, which w... | python|pandas|dataframe|scatter-plot | 1 |
21,002 | 72,750,437 | How can I make a heatmap from a repetitive dataframe? | <p>I've got a df that has three columns, one of them has a repetitive pattern, the df looks like this</p>
<pre><code>>>> df
date hour value
0 01/01/2022 1 0.267648
1 01/01/2022 2 1.564420
2 01/01/2022 ... 0.702019
3 01/01/2022 2... | <pre><code>import seaborn as sns
import matplotlib.pyplot as plt
df.date = pd.to_datetime(df.date)
df['month'] = df.date.dt.month
pivot = df.pivot_table(columns='month', index='hour', values='value', aggfunc='median')
sns.heatmap(pivot.sort_index(ascending=False))
plt.show()
</code></pre>
<p>Output:</p>
<p><a href="... | python|pandas|plotly | 1 |
21,003 | 72,691,396 | Adding counts from one dataframe to another dataframe on corresponding row | <p>I would like to count the number of record in <strong>dataframe2</strong> and add the count to the corresponding rows in <strong>dataframe1</strong>.</p>
<h4>The first one (df1)</h4>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Road</th>
<th>RoadNo</th>
<th>Count</th>
</tr>
</thead>
<tbod... | <p>You could first count the values from <code>df2</code> for all <code>Road</code> and <code>RoadNo</code> pairs and then join the resulting data frame to <code>df1</code>:</p>
<pre class="lang-py prettyprint-override"><code>
df1 = pd.DataFrame(data={"Road":["A", "A", "B", "... | python|sql|pandas|dataframe | 1 |
21,004 | 72,802,951 | Python exclude zero while ranking | <p>Please help to create ranking that excludes values = 0, null, NaN for the below df,</p>
<p>Input:</p>
<pre><code>df = pd.DataFrame(data={'Group1': ['A', 'A', 'A',
'B', 'C','D'],
'Group2': ['A1', 'A2', 'A3',
'B1', 'B2','D1']... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rank.html" rel="nofollow noreferrer"><code>df.rank</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> with <a href="https://pandas.pydata.org/docs/... | python|pandas|dataframe|ranking | 1 |
21,005 | 59,713,145 | Fill dataframe is column name match | <p>I have a df <code>df1</code> with N columns fill with value, another <code>df2</code> empty with M columns (M > N).
I have 2 lists representing all the columns name of <code>df1</code> and the matching columns name in the source <code>df2</code>, ordered. </p>
<p>Ex : <code>list1[0] -> list2[0]</code></p>
<p>I ... | <p>Idea is <code>rename</code> columns names by <code>dict</code> created by zip of columns and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="noreferrer"><code>DataFrame.reindex</code></a> by columns names of second DataFrame:</p>
<pre><code>df = df1.re... | python|pandas|dataframe|rename | 5 |
21,006 | 61,998,771 | Best way to compare excel and text file for same data | <p>How do I do the following in Python: for me to compare a text file and excel file to see if they contain the same data? I have the following code (bottom) setup where it looks for just the model and if it is in the text file, it prints out the model, brand and type is in there but sometimes there are multiple same m... | <p>Turn the contents of your text file into a dataframe, then check if they are equal to each other. You can adapt something like this:</p>
<pre><code>df = pd.DataFrame({"Brand": ["Toyota","Honda",0,"Nissan"],
"type": ["sedan", "SUV", 0, "sedan"],
"model": ["Camry", "CR-V", 0, "Altima"]})
... | python|excel|pandas | 1 |
21,007 | 57,912,025 | Cumulative variable calculation which is reset under a given condition, for each ID - Pandas | <p>I want to create a cumulative variable based on a non-cumulative variable. This variable should be reset when the value of Y equals 1 (but the reset will start from the row below).
I want to do that for each ID in the data frame.</p>
<p>Data illustration:</p>
<pre><code>ID X Non_cum Y
A .. 0 0
A .. ... | <p>You can group by <code>ID</code> and cumsum of <code>Y</code> (with shift):</p>
<pre><code>groups = df.groupby(['ID'])
df['Y_block'] = groups['Y'].shift(fill_value=0)
df['Y_block'] = groups['Y_block'].cumsum()
df['Cum'] = df.groupby(['ID','Y_block'])['Non_cum'].cumsum()
</code></pre>
<p>Output (<code>Cum</code> ... | pandas | 1 |
21,008 | 58,017,573 | Pandas HDFStore: append fails when min_itemsize is set to the maximum of the string column | <p>I'm detecting the maximum lengths of all string columns of multiple dataframes, then attempting to build a HDFStore:</p>
<pre><code>import pandas as pd
# Detect max string length for each column across all DataFrames
max_lens = {}
for df_path in paths:
df = pd.read_pickle(df_path)
for col in df.columns:
... | <p>HDF stores strings in UTF-8, and thus you need to encode the strings as UTF-8 and then find the maximum length.</p>
<pre><code>a_pandas_string_series.str.encode('utf-8').str.len().max()
</code></pre> | pandas|python-3.7|hdf5|pytables|hdfstore | 0 |
21,009 | 54,817,993 | Get index of value (with conditions) | <p>I tried different options but I always return to the <code>.get_loc</code> function. I got a big data frame and need to find the row index of a value <code>nearest</code> or <code>backfill</code>. The df looks like this:</p>
<pre><code> Date Product Price
0 1/1 NEG 3
1 1/1 NEG ... | <p>welcome to Stackoverflow!</p>
<p>I'm not a fan of using .get_loc() so here's an alternative method to get what you want.</p>
<pre><code>import pandas as pd
num = 3.4
# New dataframe fit_criteria for conditions (df['Date']=='1/1') & (df['Product']=='NEG')
fit_criteria = df.loc[(df['Date']=='1/1') & (df['P... | python|python-3.x|pandas|dataframe|pandas-groupby | 0 |
21,010 | 54,739,388 | Should the random noise given to a GAN kept constant? | <p>I am working on a Generative Adversarial Network ( GAN ). At every step, in the training, I call a method <code>generate_noise</code> which returns a tensor of some random noise.</p>
<pre><code># Generates noise of normal distribution
def generate_noise( shape : tuple ):
noise = tf.random_normal( shape )
re... | <p>No, the noise should <strong>not</strong> be constant during training. For a given latent noise vector a GAN can generate only a single image. If you keep the noise constant, the GAN can only produce <strong>one image</strong>.</p>
<p>The only case where you would want the noise to be constant would be if you wante... | python-3.x|tensorflow|neural-network|generative-adversarial-network | 2 |
21,011 | 55,060,888 | Torchtext AttributeError: 'Example' object has no attribute 'text_content' | <p>I'm working with RNN and using Pytorch & Torchtext. I've got a problem with building vocab in my RNN. My code is as follows:</p>
<pre class="lang-py prettyprint-override"><code>TEXT = Field(tokenize=tokenizer, lower=True)
LABEL = LabelField(dtype=torch.float)
trainds = TabularDataset(
path='drive/{}'.forma... | <p>This problem arises when the fields are not passed in the same order as they are in the csv/tsv file. Order must be same. Also check if no extra or less fields are mentioned than there are in the csv/tsv file..</p> | neural-network|nlp|pytorch|recurrent-neural-network|torchtext | 3 |
21,012 | 49,711,519 | Image segmentation training set labeling | <p>I am new to pytorch and Deep learning. I am trying to do image segmentation.
But , I am stuck at how to label training set images.</p>
<p>Can anyone please help me ?</p>
<p>This is one of my training image</p>
<p><a href="https://i.stack.imgur.com/XhFdy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.im... | <p>There is discussions <a href="https://www.reddit.com/r/computervision/comments/5jxhtc/image_segmentation_labelling_tool/" rel="nofollow noreferrer">here</a> about segmentation tools for image labeling. You may find it useful.</p> | python-3.x|computer-vision|deep-learning|pytorch | 0 |
21,013 | 67,483,626 | Setup Tensorflow 2.4 on Ubuntu 20.04 with GPU without sudo | <p>I have access to a virtual machine with Ubuntu 20.04 setup and GPUs. Sysadmins already installed latest Cuda drivers, but unfortunately that's not enough to use GPUs in Tensorflow, as each version of TF can be very picky when it comes to the particular set of Cuda Toolkit + CuDNN versions. I don't have sudo rights, ... | <p>Instructions to setup Tensorflow 2.4.x (tested for 2.4.1) on an Ubuntu 20.04 environment without admin rights. It is assumed that a sysadmin already installed the latest Cuda drivers. It consists of install Cuda 11.0 toolkit + CuDNN 8.2.0.</p>
<p>Instructions below will install CUDA 11.0 (tested to work for Tensorfl... | python|tensorflow|ubuntu|ubuntu-20.04 | 6 |
21,014 | 67,352,757 | How to debug error in Jupyter Notebook Using Python libraries for ML | <p>I'm doing modeling using python libraries in jupyter notebook. I'm done with the pre-processing stage and attempting to build my first machine learning models (ANN; artificial neural network, and decision tree). I've been trying to understand how to fix these error for a while, and the only possible cause I've seen ... | <p>It seems to me like your are not feeding the correct data structure to the models. Please refer to this link
<a href="https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html#sklearn.neural_network.MLPClassifier.fit" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules... | python|pandas|numpy|machine-learning|jupyter-notebook | 0 |
21,015 | 67,311,819 | How to use pandas to sort data in an excel file. and sort through duplicates | <p>I am trying to filter data using panda.</p>
<pre><code>df_c = pd.read_csv (r'C:\Users\User\Documents\Research\output-mutations.csv')
df_c.drop_duplicates(subset = ["FILENAME", "CHAIN", "MUTATION_CODE"],
keep = False, inplace = True)
df_c.to_csv (r'C:\Users\User\Docu... | <p>You can use <code>groupby</code> and <code>apply</code> instead of <code>drop</code>.</p>
<pre><code>df = df.groupby(by=[ "FILENAME", "CHAIN"],as_index=False).apply(lambda x: ";".join(x["MUTATION_CODE"]))
df.columns = ["FILENAME", "CHAIN", "MUTATION_CO... | python|pandas | 0 |
21,016 | 67,241,258 | how to replace a lengthy white space to Nan in a column under Object format? in python | <p>I have a dataframe with two columns, one of the columns contains of many blank cells. I tried all the method that I could think of to drop those rows,but none worked.</p>
<p>for example:</p>
<pre><code>FGS_data[FGS_data['Ins ISIN code']==''] = np.nan
FGS_data[FGS_data['Ins ISIN code']!='']
nan_value = float("Na... | <h3><a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a></h3>
<pre><code>FGS_data[~FGS_data['Ins ISIN code'].str.contains(r'^\s*$')]
</code></pre>
<hr />
<pre><code> Ins ISIN code Quantity
51 JP3970300004 30500.0
1... | python|pandas|replace|data-cleaning | 0 |
21,017 | 59,929,424 | compute session duration on an e-commerce dataset python | <p>I work on an <em>e-commerce</em> dataset in <code>python pandas</code> like this:</p>
<pre><code>Timestamp
2019-10-23 08:18:14 UTC
2019-10-23 08:18:17 UTC
2019-10-23 08:18:27 UTC
2019-10-15 04:09:18 UTC
2019-10-15 04:10:14 UTC
SessionId
1
1
1
2
2
</code></pre>
<p>I would li... | <p>Here is an example of how you might do this:</p>
<pre><code>import pandas as pd
# dummy data
df = pd.DataFrame({
'Timestamp': ['2019-10-23 08:18:14', ' 2019-10-23 08:18:17', ' 2019-10-23 08:18:27', ' 2019-10-15 04:09:18', ' 2019-10-15 04:10:14'],
'SessionId': [1, 1, 1, 2, 2]
})
df.Timestamp = pd.to_datetim... | python|pandas|dataframe | 2 |
21,018 | 60,238,098 | Blas GEMM launch failed when using TensorFlow GPU with Keras | <p>Pretty self-explanatory. Like countless people before and probably after me, I have a <code>Blas GEMM launch failed</code> error message when trying to call <code>model.fit()</code>.</p>
<p>This is the output of <code>nvidia-smi</code> <strong>before</strong> calling <code>model.compile()</code>:</p>
<pre><code>+-... | <p>I had the same problem. I saw many answer and used many suggested code to solve this problem but anything help me.</p>
<p>For me the problem was the usage of GPU so I limit the memory used by my GPU with the following code:</p>
<pre><code>gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
# Restri... | python|tensorflow|keras | 0 |
21,019 | 60,046,567 | How/where to go for a stock market index (aggregate) API or other method to accessing | <p>I'm attempting to install a stock market gauge displaying the S&P 500, NASDAQ, and DJIA composite indices; however, I'm not sure where to find sources to gather the three together. Otherwise, I think I could bring it in one at a time as the following:</p>
<pre><code>yahoo_url = "http://finance.yahoo.com/q?s=^G... | <p>List the indexes you want
<code>indexes = ['^DJI', '^GSPC', '^IXIC']</code></p>
<p>Query yahoo finance for them</p>
<p><code>df = web(indexes, 'yahoo', start='2010-01-01')</code></p>
<pre><code>>>> df.columns
MultiIndex([('Adj Close', '^DJI'),
('Adj Close', '^GSPC'),
('Adj Close'... | python|pandas-datareader | 1 |
21,020 | 65,154,394 | How do I create a confusion matrix to evaluate the model? | <p>I am following <a href="https://youtu.be/_xcFAiufwd0" rel="nofollow noreferrer">This Tutorial</a> for Music Genre Classifier. And now I want to visualize the predictions made on test set using confusion matrix. How do I go about creating it? Do I just predict using <code>model.predict()</code> command and add it in ... | <p>Given that the model was trained properly you need to do the following:</p>
<pre><code>from sklearn.metrics import confusion_matrix
y_pred = model.predict(X_test)
y_pred = np.argmax(y_pred, axis=1)
conf_mat = confusion_matrix(y_test, y_pred)
</code></pre>
<p>First, get the prediction (probability vector because yo... | python|tensorflow|classification|confusion-matrix|evaluate | 1 |
21,021 | 65,153,358 | Count unique values single column pandas | <p>Hi I have the following dataframe and I want to count the number of times that each year repeats</p>
<pre><code>df = pd.DataFrame({'year':[1958,1963,1958,1963],'title':['a','g','z','e']})
</code></pre>
<p>How can I group by the year and count how many times each year is? I would create an additional column with the ... | <p>Check with <code>value_counts</code></p>
<pre><code>out = df['year'].value_counts()
</code></pre> | pandas|count|pandas-groupby | 2 |
21,022 | 65,485,062 | Slicing numpy arrays | <pre><code>mean = [0, 0]
cov = [[1, 0], [0, 100]]
gg = np.random.multivariate_normal(mean, cov, size = [5, 12])
</code></pre>
<p>I get an array which has 2 columns and 12 rows, i want to take the first column which will include all 12 rows and convert them to columns. What is the appropriate method for sclicing and h... | <p>The problem is that your array <code>gg</code> is not two- but three-dimensional. So, what you need is in fact the first column of each stacked 2D array. Here is an example:</p>
<pre><code>import numpy as np
x = np.random.randint(0, 10, (3, 4, 5))
x[:, :, 0].flatten()
</code></pre>
<p>The colon in slicing means &qu... | arrays|numpy | 0 |
21,023 | 65,140,662 | Python dataframe group by index level rather than index names | <p>I'm having a multi-indexed dataframe. I understand that groupby(level=0) means groupby the first index, then how can I group the data by the first two indices using this method?<br />
I tried groupby(level=0 and 1), and it did not work.</p> | <p>Use list like:</p>
<pre><code>df.groupby(level=[0,1])
</code></pre>
<p>Also if want use aggregate function like <code>sum</code>, <code>mean</code>, <code>max</code>, <code>min</code>:</p>
<pre><code>df.groupby(level=[0,1]).sum()
</code></pre>
<p>is possible simplify to:</p>
<pre><code>df.sum(level=[0,1])
</code></p... | python|pandas|dataframe | 1 |
21,024 | 65,482,777 | How to convert .model to .tflite? | <p>I am currently working on a face mask detection project. I do not know machine learning much but here is my problem statement. I have to run my project on Raspberry Pi, so I decided to convert my model to tflite in order to increase the FPS. I trained and created my model in this line 'model.save("mask_detector... | <p>TFLite currently supports TensorFlow models only. (The issue is probably due to usinbg <code>res10_300x300_ssd_iter_140000.caffeemodel</code>). Is there a way get a SavedModel or Keras model in TensorFlow first?</p> | python|tensorflow|machine-learning|computer-vision|tensorflow-lite | 0 |
21,025 | 65,181,851 | Tensorflow get variance of loss function values | <p>Is there any way to get variance(standard deviation) of [batch_size x 3] loss in tensor flow??</p>
<p>I have a loss function like (batch_size = 60) :</p>
<pre><code>Lx = tf.sqrt(tf.square(tf.subtract(lossx, poses_x)))
</code></pre>
<p>and it has 3 dimension for each (print(Lx)):</p>
<pre><code>Lx Tensor("Sqrt:0... | <p>Add all axes:</p>
<pre><code>meanx, varx = tf.nn.moments(Lx, axes=[0, 1])
</code></pre> | python|tensorflow | 1 |
21,026 | 65,127,493 | Group Pandas rows by ID and forward fill them to the right retaining NaN when it appears on all the rows with the same ID | <p>I have a Pandas DataFrame that I need to:</p>
<ul>
<li>group by the ID column (not in index)</li>
<li>forward fill rows to the right with the previous value (multiple columns) only if it's not a NaN (<code>np.nan</code>)</li>
</ul>
<p>For each ID categorical value and each metric column (see the <code>aX</code> colu... | <p>One idea is use <code>min_count=1</code> to <code>sum</code>:</p>
<pre><code>df = my_df.groupby("id").sum(min_count=1)
print (df)
a1 a2 a3 a4
id
1 100.0 NaN 80.0 90.0
20 NaN NaN 100.0 30.0
</code></pre>
<p>Or if need first non missing value is possible use <... | pandas|pandas-groupby|aggregate|nan | 1 |
21,027 | 49,897,968 | Convert Numpy to DataFrame | <p>I am having <code>4D Numpy</code> array with shape <code>(202, 64, 64, 3)</code>, so the first dimension would be the index for the image, and the last 3 dimensions are the actual image.</p>
<p>Then i am having '2D Numpy' array with shape '(202,1)' contains the labels for each image</p>
<p>I want to create a panda... | <p>The following works for me on a randomly generated test set of size (50,20,20,3). I'm making two assumptions here:</p>
<p>1) Your data is called datalist</p>
<p>2) the indices aren't actually stored in the matrix (I'm having trouble visualizing a 4D matrix in my head)</p>
<pre><code>Y = np.arange(datalist.shape[0... | python|pandas|numpy | 0 |
21,028 | 64,116,613 | output of model.summary() is not as expected tensorflow 2 | <p>I've defined a complex deep learning model, but for the purpose of this question, I'll use a simple one.</p>
<p>Consider the following:</p>
<pre><code>import tensorflow as tf
from tensorflow.keras import layers, models
def simpleMLP(in_size, hidden_sizes, num_classes, dropout_prob=0.5):
in_x = layers.Input(sha... | <p>There is nothing wrong in model summary in Tensorflow 2.x.</p>
<pre><code>import tensorflow as tf
from tensorflow.keras import layers, models
def simpleMLP(in_size, hidden_sizes, num_classes, dropout_prob=0.5):
in_x = layers.Input(shape=(in_size,))
hidden_x = models.Sequential(name="hidden_layers"... | python|python-3.x|keras|tensorflow2.0 | 0 |
21,029 | 63,949,708 | Group by a column then filtered out the earliest date rows into a new dataframe | <p>I have a dataframe like below:</p>
<pre><code>product_id date status
1 2018-09-11 G
1 2016-01-11 B
1 2018-02-11 P
2 2019-06-12 P
2 2020-10-11 P
3 2019-07-21 G
3 2016-09-... | <p>Your dates are in YYYY-MM-DD order, the <a href="https://en.wikipedia.org/wiki/ISO_8601" rel="nofollow noreferrer"><code>ISO-8601</code></a> definition. So you can simply sort on it:</p>
<pre><code>print (df.sort_values("date").drop_duplicates("product_id").sort_index())
product_id dat... | python|pandas|dataframe|pandas-groupby | 1 |
21,030 | 46,679,948 | tensorflow session run feed_dict - to zip or not to zip | <p>what's the difference (in Tensorflow) between running session like this:</p>
<pre><code>sess.run(train_op, feed_dict={X: trainingDataX,Y: trainingDataY})
</code></pre>
<p>and like this:</p>
<pre><code>for (x, y) in zip(trainingDataX, trainingDataY):
sess.run(train_op, feed_dict={X: x, Y: y})
</code></pre>
<p... | <p>In the first case, you are feeding the data in batch mode whereas in the second case you are feeding data one by one.</p> | tensorflow | 0 |
21,031 | 63,055,870 | Why am I losing data after I perform asfreq | <p>So I got a data set of approximative 6000 cells in my excel. In the objective to determine some patterns I would ike to define that this dataset is a minutely frequently one but after a asfreq('T') I lose a big part of my datatset why ?<a href="https://i.stack.imgur.com/YfLnx.png" rel="nofollow noreferrer">dataset</... | <p>Pandas is filling in <code>NaN</code> for the rows that you don't have values for. If you do <code>.head(10)</code> you'll see that your original values are still there</p> | pandas|frequency | 0 |
21,032 | 62,998,314 | Sentiment Analysis with Logistic regression using sklearn | <p>I am trying to do sentiment analysis with sklearn.
Following is my code-</p>
<pre><code>products=pd.read_csv("amazon_baby.csv")
products.head(3)
name review rating
0 Planetwise Flannel Wipes These flannel wipes are OK, but... | <p>It worked with small modification in code-</p>
<pre><code>count_Vect = CountVectorizer().fit(X_train)
X_train_vectorized=count_Vect.transform(X_train)
model = LogisticRegression()
model.fit(X_train_vectorized,y_train)
predictions=model.predict(count_Vect.transform(X_train))
</code></pre> | pandas|logistic-regression|sklearn-pandas|countvectorizer | 0 |
21,033 | 68,011,592 | word frequency in a pdf | <p>I found this code on git hub and I can't get it to work. The point is to convert the pdf to .txt then list all the words with frequency of occurrence. I'm beginning to learn python but I'm not very good yet. I am getting this tracebac</p>
<pre><code> Traceback (most recent call last):
File "C:\python38\Keywor... | <p>Python3 has two different <em>string</em> types. <code>bytes</code> and <code>str</code>. Different API will work on different types. The error is telling you that <code>re</code> wants to deal with <code>str</code> not <code>bytes</code>. The line <code>text = text.encode('ascii','ignore').lower()</code> turns y... | python|python-3.x|regex|pandas|pdf | 1 |
21,034 | 67,916,749 | Pandas create new category based on position-column without for loop | <p>One of my columns indicates the x-distance of a person looks like this:</p>
<pre><code>x_distance = [0.01, 0.321, 2.576, 0.41, 2.11, 2.62]
</code></pre>
<p>I want to create a column, that creates a new category, if there is a value in x_distance greater than 2.5 without using a for-loop (pay attention to the order o... | <p>I suppose you have a dataframe <code>df</code> with a column <code>x_distance</code>:</p>
<pre><code>>>> df["x_distance"].gt(2.5).cumsum()
0 0
1 0
2 1
3 1
4 1
5 2
Name: x_distance, dtype: int64
</code></pre> | python|pandas|dataframe | 1 |
21,035 | 61,273,175 | selecting rows of one dataframe using multiple columns of another dataframe in python, pandas | <p>I want to pick only <strong>rows</strong> from df1 where both values of columns A and B in df1 match values of columns A and B in df2 so for example if df 1 and df2 are as follow:</p>
<pre><code>df1
A B C
1 2 3
4 5 6
6 7 8
df2
A B D E
1 2 6 8
2 3 7 9
4 5 2 1
</code></pre>
<p>the result will be a subset of df1 ro... | <p>Use:</p>
<pre><code>df = pd.merge(df1, df2[["A", "B"]], on=["A", "B"], how="inner")
print(df)
</code></pre>
<p>This prints:</p>
<pre><code> A B C
0 1 2 3
1 4 5 6
</code></pre> | python|pandas | 2 |
21,036 | 61,427,247 | Finding the minimum value based on another column in pandas | <p><a href="https://i.stack.imgur.com/D0cX6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D0cX6.png" alt="dataframe df"></a></p>
<p>I have to find the channel type that has the minimum value of sales among all 3 channels (Hotel,Cafe or restaurant) of dataframe df(snapshot attached).So output would... | <p>Change your last line </p>
<pre><code>print(df1.idxmin())
</code></pre> | pandas|group-by|minimum | 0 |
21,037 | 68,761,372 | Pytorch Scheduler: how to get decreasing LR epochs | <p>I'm training a network in pytorch and using <code>ReduceLROnPlateau</code> as scheduler.
I set <code>verbose=True</code> in the parameteres and my scheduler prints something like:</p>
<blockquote>
<p>Epoch 159: reducing learning rate to 6.0000e-04.</p>
<p>Epoch 169: reducing learning rate to 3.0000e-04.</p>
<p>E... | <p>I think the scheduler doesn't take track of this (at least I didn't see anything like this in the <a href="https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#ReduceLROnPlateau" rel="nofollow noreferrer">source code</a>), but you can just keep track of this in your training loop.</p>
<p>Whenever t... | pytorch|scheduler | 1 |
21,038 | 53,350,677 | How to do a "element by element in-place inverse" with pytorch? | <p>Given is an array <code>a</code>:</p>
<pre><code>a = np.arange(1, 11, dtype = 'float32')
</code></pre>
<p>With numpy, I can do the following:</p>
<pre><code>np.divide(1.0, a, out = a)
</code></pre>
<p>Resulting in:</p>
<pre><code>array([1. , 0.5 , 0.33333334, 0.25 , 0.2 ,
0.166666... | <p>Pytorch follows the convention of using <code>_</code> for in-place operations.
for eg</p>
<pre><code>add -> add_ # in-place equivalent
div -> div_ # in-place equivalent
etc
</code></pre>
<p>Element-by-element inplace inverse.</p>
<pre><code>>>> a = torch.arange(1, 11, dtype=torch.float32)
>&... | python|python-3.x|numpy|pytorch | 10 |
21,039 | 52,928,523 | Pandas float64 to float 32 ,then the data changes | <p>I have a csv file containing some float data.
the code is simple</p>
<pre><code>df = pd.read_csv(my_csv_vile)
print(df.iloc[:2,:4]
600663.XSHG 000877.XSHE 600523.XSHG 601311.XSHG
2016-01-04 09:31:00 49.40 8.05 22.79 21.80
2016-01-04 09:32:00 49.55 8.03 22.79 ... | <p>Many decimal floating point numbers can not be accurately represented with a float64 or float32. Review e.g. <a href="https://floating-point-gui.de/basic/" rel="nofollow noreferrer">The Floating-Point Guide</a> if you are unfamiliar with that issue.</p>
<p>Pandas <a href="https://pandas.pydata.org/pandas-docs/stabl... | python|pandas|numpy | 4 |
21,040 | 53,283,423 | Detecting bad information (python/pandas) | <p>I am new to python and pandas and I was wondering if I am able to have pandas filter out information within a dataframe that is otherwise inconsistent. For example, imagine that I have a dataframe with 2 columns, (1) product code and (2) unit of measurement. The same product code in column 1 may repeat several times... | <p>First you want some mapping of product code -> unit of measurement, ie the ground truth. You can either upload this, or try to be clever and derive it from the data assuming that the most frequently used unit of measurement for product code is the correct one. You could get this by doing </p>
<pre><code>truth_mappi... | python|pandas | 1 |
21,041 | 65,807,322 | How to print particular column data as user input column names in python? | <p>I have the following table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
<th>Column5</th>
<th>Column6</th>
</tr>
</thead>
<tbody>
<tr>
<td>aa</td>
<td>0</td>
<td>22</td>
<td>33</td>
<td>5</td>
<td>7</td>
</tr>
<tr>
<td>bb... | <p>user should enter columns in comma seperated manner like below:</p>
<pre><code>x=input("Enter the required columns:").split(',')
Enter the required columns:a,b
df[['Column1']+x]
df
</code></pre> | python|pandas|input | 0 |
21,042 | 63,357,858 | Pandas Plot floating bar chart | <p>I am trying to create a bar chart where the upper and lower bound of each bar could be above or below zero. Hence the boxes should "float" depending on the data. I'm also trying to use <code>pandas.plot</code> function as it makes my life way easier in the real application.</p>
<p>The solution I've devised... | <p>To create the plot via pandas, you could create an extra column with the height. And use <code>df.plot(..., y=df['Height'], bottom=df['Lower'])</code>:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df_data = {'Category': ['London', 'Paris'... | python|pandas|matplotlib | 3 |
21,043 | 63,573,737 | Pandas - Create a new column (Branch name) based on another column (City name) | <p>I have the following Python Pandas Dataframe (8 rows):</p>
<pre>
City Name
New York
Long Beach
Jamestown
Chicago
Forrest Park
Berwyn
Las Vegas
Miami
</pre>
<p>I would like to add a new Column (Branch Name) based on City Name as below:</p>
<pre>
City Name Branch Name
New York New York
Long Beach ... | <p>You can use <code>.map()</code>. City names not in the dictionnary will be kept.</p>
<pre><code>df["Branch Name"] = df["City Name"].map({"Long Beach":"New York",
"Jamestown":"New York",
... | python|pandas|dataframe|city | 0 |
21,044 | 63,596,704 | DeepDiff among Rows | <p>i have this data frame</p>
<pre><code>import pandas as pd
from deepdiff import DeepDiff
df = pd.DataFrame({'col_new': ['a','b','c,d','d'],
'col_old': ['a','e','d','d'],
'col_val': [True,False,False,True]})
print(df)
col_new col_old col_val
0 a a True
1 b... | <p>For me working apply function by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> for scalar processing, but only for <code>False</code> rows matched by inverted mask by <code>~</code>:</p>
<pre><code>mask = df[... | python|pandas | 2 |
21,045 | 63,731,496 | pandas data frame error issued in the python code given below | <pre><code>import pandas as pd
import quandl
df=quandl.get("WIKI/GOOGL")
df=df[['Adj.Open','Adj.High','Adj.Low','Adj.Close','Adj.Volume']]
df['HL_PCT']=(df['Adj.High']-df[Adj.Close])/df[Adj.Close]*100`
df['DL_PCT']=(df['Adj.Close']-df[Adj.Open])/df[Adj.Open]*100
df=df[['Adj.Close','HL_PCT','DL_PCT','Adj.Volu... | <p>I am not sure from the image you provided but it seems that your column names are with a space, i.e. 'Adj. Volume'</p> | python-3.x|pandas|quandl | 0 |
21,046 | 71,874,772 | Getting index and dtypes when getting a list from a column | <p>I have a dataframe with two columns and I have a statement that I want to fill with the dataframe column values, so I can return a list will all the statements.</p>
<p>I have the following dataframe:</p>
<pre><code>d = {'col1': ['john', 'leo', 'maria', 'zack'], 'col2': ['14','13','45','2']}
df = pd.DataFrame(data=d,... | <pre><code>import pandas as pd
d = {'col1': ['john', 'leo', 'maria', 'zack'], 'col2': ['14','13','45','2']}
df = pd.DataFrame(data=d, index=[0, 1, 2, 3])
df['stt'] = df.apply(lambda x: f"Hello my name is {x['col1']} and I am {x['col2']} years old.", axis=1)
print(df['stt'].tolist())
</code></pre>
<p>Output:... | python|pandas | 0 |
21,047 | 72,049,635 | Pandas: Get indices rows of that match group-by value_count | <p>I want to get the row indices for values that meet my search criteria.</p>
<p>Consider this data:</p>
<pre><code>df = pd.DataFrame({'group': ['A', 'A', 'B', 'B', 'A'],
'item': ['BIOS', 'BIOS', 'Memory', 'Disk', 'BIOS'],
'val': [1, 2, 1, 2, 3]})
</code></pre>
<p>I can get the val... | <p>You can use <code>groupby</code> in place of <code>value_counts</code>:</p>
<pre><code>df.groupby(['group', 'item']).filter(lambda g: len(g)>1).index
</code></pre>
<p>variant:</p>
<pre><code>mask = df.groupby(['group', 'item'])['val'].transform('size').gt(1)
df.index[mask]
</code></pre>
<p>output:</p>
<pre><code>... | python|pandas | 2 |
21,048 | 71,888,669 | How can you save a keras model in 64bit format? | <p>how can you save a keras model in 64bit format?
<a href="https://stackoverflow.com/questions/67187646/can-i-make-my-keras-tensorflow-model-use-float64-double-internally">This</a> is able to 'put tensorflow' in 64bit 'mode' for the current runtime. But I've found that even just saving the model & reloading it is ... | <p>What is the purpose of the requirements when you are using an optimizer larger than e-07?</p>
<p><strong>[ Sample ]:</strong></p>
<pre><code>import os
from os.path import exists
import tensorflow as tf
import h5py
"""""""""""""""""... | tensorflow|keras | -2 |
21,049 | 71,826,575 | How to tackle a dataset that has multiple same date values | <p>I have a large data set that I'm trying to produce a time series using ARIMA. However
some of the data in the date column has multiple rows with the same date.</p>
<p>The data for the dates was entered this way in the data set as it was not known the exact date of the event, hence unknown dates where entered for the... | <p>With the following toy dataframe:</p>
<pre class="lang-py prettyprint-override"><code>import random
import time
import pandas as pd
df = pd.DataFrame(
{
"date": [
"2016-01-01",
"2015-01-01",
"2013-01-01",
"2014-... | python|pandas|dataframe|time-series | 1 |
21,050 | 55,457,045 | Dropout layer directly in tensorflow: how to train? | <p>After I created my model in Keras, I want to get the gradients and apply them directly in Tensorflow with the tf.train.AdamOptimizer class. However, since I am using a Dropout layer, I don't know how to tell to the model whether it is in the training mode or not. The <em>training</em> keyword is not accepted. This i... | <p>Keras layers inherit from tf.keras.layers.Layer class. Keras API handle this internally with <code>model.fit</code>. In case Keras Dropout is used with pure TensorFlow training loop, it supports a training argument in its call function.</p>
<p>So you can control it with</p>
<pre><code>dropout = tf.keras.layers.Dro... | python|tensorflow|keras|generative-adversarial-network|dropout | 1 |
21,051 | 56,566,200 | Transform column of dictionaries into a single pandas DataFrame | <p>I have a dataframe that looks similiar to this:</p>
<pre><code> data
0 [{'v': 10, 'n': 'metric2'}]
27 [{'v': 20, 'n': 'metric1'}, {'v': 56, 'n': 'metric3'}]
51 [{'v': 20, 'n': 'metric3'}]
89 [{'v': 10, 'n': 'metric2'}]
</code></pre>
<p>I'... | <p>There is a bad performance solution with multiple <code>apply</code>, if you have a relative big data , you should using the method provided by <a href="https://stackoverflow.com/a/56566303/7964527">cs95</a></p>
<pre><code>s.apply(pd.Series).stack().apply(pd.Series).set_index('n',append=True).v.unstack('n').sum(lev... | python|pandas|dataframe|dictionary | 3 |
21,052 | 56,623,087 | Find unique combination of pandas column out of list and another column | <p>I have a DataFrame like this:</p>
<pre><code>df = pd.DataFrame({'number': [['233182801104', '862824274124', '278711320172'], ['072287346459', '278058853506'], ['233182801104', '862824274124'], None, ['123412341234']], 'country':[None, 'France', 'USA', None, 'Germany'], 'c':np.random.randn(5), 'd':np.random.randn(5)... | <p>Try this</p>
<pre><code>data = []
for i in df.itertuples():
for j in i[1]:
data.append( (j,i[2]) )
df2 = pd.DataFrame( data, columns =['code' , 'country_final']
</code></pre>
<p>OR you can condense it as :</p>
<pre><code>df2 = pd.DataFrame( [ (j,i[2]) for i in df.itertuples() for j in i[1] ], columns... | python|pandas | 0 |
21,053 | 67,078,752 | How to invert axis of a pillow image | <p>Seaborn offers the possibility to invert the axis of an image. I would like to do the same with PIL. Here is my code.</p>
<pre><code># Imports
import seaborn as sns; sns.set_theme()
import matplotlib.pyplot as plt
import numpy as np
import numpy as np; np.random.seed(0)
from PIL import Image
import random
# Arrays
... | <p>I think you just want to flip it:</p>
<pre><code> im_flipped = im.transpose(method=Image.FLIP_LEFT_RIGHT)
</code></pre> | python|numpy|opencv|python-imaging-library|seaborn | 1 |
21,054 | 47,428,530 | pandas apply returning NaN | <p>I have a json which I am converting to a dictionary and then I am creating a dataframe using certain key-value pairs present in the dictionary</p>
<pre><code># json
a = """{
"cluster_id": 3,
"cluster_observation_data": [[1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8, 1]],
"cluster_observation_label": [0... | <p>You need to pass axis, like:</p>
<pre><code>train.loc[:, 'center_dist'] = train.loc[:, ['cluster_observation_data']].apply(distance_from_center, 1)
</code></pre>
<p>The reason is that you want to apply function to each list inidividualy. <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFr... | python|pandas | 2 |
21,055 | 68,055,368 | Problem with SSD MobileNet V2 FPNLite 320x320 conversion for Coral AI TPU | <p>I'm trying to run Tensorflow model lite on Rasperry PI with Coral TPU.
Model is SSD Mobile Net 2. It works fine on PC after conversion either fully quantized or with float I/O.
However when I run it on Coral TPU I got a lot of wrong result. Usually it is false positive class 0 (mapped to person).
Could somebody help... | <p>The accuracy quantized SSD model is slightly lowered than the float model, you can probably try the efficient-det model: <a href="https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker/object_detector" rel="nofollow noreferrer">https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker/object_det... | python|tensorflow|tensorflow-lite|google-coral|tensorflow-model-garden | 0 |
21,056 | 68,337,488 | Count consecutive strings per column with groupby and cumcount (pandas) | <p>I have a <code>df</code> which looks like the following:</p>
<pre><code>df = pd.DataFrame({"child": ["A", "B", "C", "D", "E", "D", "A"],
"birth": ["2000-07-29", "2000-08-03", &quo... | <p>Here's one way to solve:</p>
<pre><code>df = (
df_new.set_index(['parent', 'birth'])
.join(
df_new.groupby('parent')
.apply(lambda x: x.groupby('birth')['child'].agg('count').cumsum()),
rsuffix='count')
.reset_index()
)
</code></pre>
<p>OUTPUT:</p>
<pre><code> parent birth c... | python|pandas|dataframe | 3 |
21,057 | 59,307,823 | Can i have mutliple labels for a single image in an image classification scenario | <p>If I am building a model where I need to predict the vehicle, color of it, and make of it, then can I use all the labels for a single image and build my model around it.</p>
<p>Like for a single image of a vehicle which is a car (car1.jpg) will have labels like - Sedan(Make), Blue(Color) and Car(Type of vehicle). C... | <p>You can have a single model with multiple outputs. As you seem interested with image processing, detection models for example (like SSD, RFCN, etc.) have multiple outputs, one for classes, one for box coordinates. Take a look a the page 3 of <a href="https://arxiv.org/pdf/1611.10012.pdf" rel="nofollow noreferrer">th... | tensorflow|deep-learning|conv-neural-network|pytorch|multilabel-classification | 1 |
21,058 | 59,136,411 | Creating columns according to date column given in a .csv file | <p>I have a .csv file which has 5 columns, out of which there is a column which has a date mentioned in it 'date_value' and I need to change the other 2 columns 'day_of_week' and 'day_of_week_name' according to the date mentioned. Eg:</p>
<pre><code>A
date_key date_level date_value day_of_week day_of_week_... | <p>You should be able to convert the date to a <code>datetime</code> object. You can then use the <code>.weekday()</code> function to get the weekday:</p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime
days = {
0: "Monday",
1: "Tuesday",
2: "Wednesday",
3: "Thursday",
... | python|pandas|csv|date | 0 |
21,059 | 57,145,526 | Pandas: Matching string using fuzzywuzzy and retrieve the value of other column | <p>I am having a dataframe <code>df</code> as follows.</p>
<pre><code>33KV Feeder 11KV Feeder Circle_name Codes
Shree Gopal SPS 33ShreeGopal_DPS
Jai Balaji LRS Jai_Balajilaji_LRS
Mithapur-1 SPS ... | <p>Ok so I have found a solution for this. I have just tweaked the <code>match_feeder</code> as follows</p>
<pre><code>match_feeder = process.extractOne(feeder_input,data['Name of the 11Kv Feeder'],scorer=fuzz.token_sort_ratio)
</code></pre>
<p>Also I have changed the following when <code>if</code> statement is start... | python|pandas | 0 |
21,060 | 57,145,872 | Pandas Index example with repeated entries using hypothesis | <p>I want to generate a <code>pandas.Index</code> with repeated entries, like this.</p>
<pre><code>>>> pd.Index(np.random.choice(range(5), 10))
Int64Index([3, 0, 4, 1, 1, 3, 4, 3, 2, 0], dtype='int64')
</code></pre>
<p>So I wrote the following strategy:</p>
<pre><code>from hypothesis.extra.pandas import ind... | <p>If the resulting index does not have to have any particular distribution then one way to get what you need is to use <code>integers</code> strategy and use <code>unique</code> parameter of <code>indexes</code> strategy to produce duplicates if needed:</p>
<pre><code>import hypothesis.strategies as st
st_idx = inde... | python|pandas|python-hypothesis | 1 |
21,061 | 45,904,464 | Merging DataFrames and staying only with not matching entries | <p>I have two DataFrames:</p>
<pre><code>dfA = pd.DataFrame([['A', 'B', 'C', 'D'], ['A1', 'B1', 'C1', 'D1'], ['A2', 'B2', 'C2', 'D2'], ['A', 'B3', 'C3', 'D3'], ['A', 'B', 'C4', 'D5']], columns = ['AA', 'BB', 'CC', 'DD'])
AA BB CC DD
0 A B C D
1 A1 B1 C1 D1
2 A2 B2 C2 D2
3 A... | <p>I think you are looking for this , merging and removing rows that has index that is merged. </p>
<pre><code>dfA.drop(pd.merge(dfA,dfB,on=['AA','BB'],right_index=True).index)
</code></pre>
<p>Output:</p>
<pre>
AA BB CC DD
1 A1 B1 C1 D1
2 A2 B2 C2 D2
</pre> | python|pandas|dataframe | 2 |
21,062 | 46,090,070 | Check for a value from one dataframe exists in another | <p>I have 2 dataframes.</p>
<pre><code>df1
id marks
1 100
2 200
3 300
df2
name score flag
'abc' 100 T
'zxc' 300 F
</code></pre>
<p>What I am looking for is the from the first row of my df1,
check the corresponding column <code>score</code> in my df2 , and get the Flag of that.</p... | <h1>First Row</h1>
<p><strong>Option 1</strong></p>
<p>You can use <code>df.isin</code>:</p>
<pre><code>first_flag = df2[df2.score.isin([df1.marks[0]])].flag
print(first_flag)
0 T
</code></pre>
<p>To get the values, use <code>.values.tolist()</code>:</p>
<pre><code>print(first_flag.values.tolist())
['T']
</code... | python|pandas|dataframe | 1 |
21,063 | 50,944,285 | Changing string in Pandas while keeping variable | <p>My data in Pandas (df['case']) contains two ways of referring to an amount of money in USD:</p>
<ul>
<li>He payed USD500 for the PC.</li>
<li>He payed USD 500 for the PC.</li>
<li>The transaction was done in USD and in EUR.</li>
</ul>
<p>The difference is in the Blank. I would now like to replace 'USD ' with 'USD'... | <p>Use</p>
<pre><code>(?i)USD\s+(?=\d)
</code></pre>
<p><strong>Details</strong></p>
<ul>
<li><code>(?i)</code> - enable case insensitive search</li>
<li><code>USD</code> - a literal <code>USD</code></li>
<li><code>\s+</code> - 1+ whitespace chars</li>
<li><code>(?=\d)</code> - (a positive lookahead making sure) the... | python|regex|pandas | 1 |
21,064 | 66,552,278 | Using Python dictionary to filter unique matches in a pandas df | <p>I have a df like so:</p>
<pre><code>df = DataFrame({'CODE': ['AB12', 'AB12', 'CD12', 'CD12', 'CD14', 'CD14'], 'DATE': ['2021-02-01', '2021-03-06', '2021-02-01', '2021-03-06', '2021-02-01', '2021-03-06'], 'VALUE':[0,4,5,5,0,0]})
CODE DATE VALUE
AB12 2021-02-01 0
AB12 2021-03-06 4
CD12 2021-02-... | <p>Try <code>merge</code>:</p>
<pre><code>df.merge(pd.DataFrame(my_filter), on=['CODE','DATE'])
</code></pre>
<p>Output:</p>
<pre><code> CODE DATE VALUE
0 AB12 2021-02-01 0
1 CD12 2021-03-06 5
2 CD14 2021-03-06 0
</code></pre> | pandas|filtering | 1 |
21,065 | 66,410,151 | ValueError: Input 0 of layer bidirectional_1 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (13, 64) | <p>I have made a model and have got this error (it is a kaggle notebook), this is the error:</p>
<pre><code> ValueError: Input 0 of layer bidirectional_1 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (13, 64)
<ipython-input-25-f223adf5c5a7> in <module>
... | <p>Usually the expected dimension in such model is 3.
(time x batch x features). You provided a 2d.</p> | python|python-3.x|tensorflow|machine-learning|tensorflow2.0 | 1 |
21,066 | 66,653,654 | splitting column into multiple columns | <p>I have a dataframe containing one column. I want to split it into multiple columns</p>
<pre><code>106
B-PER
I-PER
I-PER
B-PER
I-PER
I-PER
I-PER
B-PER
B-PROPH
109
B-PER
B-PER
I-PER
B-PER
I-PER
B-PER
I-PER
B-PER
I-PER
B-PROPH
116
B-PER
I-PER
I-PER
B-PER
B-PER
B-PER
B-PER
</code></pre>
<p>I want to split this column in... | <p>Use:</p>
<pre><code>#test numeric values
m = df.A.astype(str).str.isnumeric()
#repeat only numeric values to groups
df['g'] = df.A.where(m).ffill()
#filter out rows without numeric (because repeated)
df = df[~m]
#reshape
df1 = df.set_index([df.groupby('g').cumcount(), 'g'])['A'].unstack(fill_value='')
print (df1)
... | python|pandas | 2 |
21,067 | 66,489,441 | Get a list of all sites on Tableau Server using Tableau Server Client into a pandas dataframe | <p>I am trying to get all the site names on the Tableau server using Tableau's Tableau Server Client Lib for Python. The query output is a list and each item in it is also a list. Here is my code:</p>
<pre><code>all_sites= []
with server.auth.sign_in(tableau_auth):
all_sites, pagination_item = server.sites.get()
... | <p>I tested the following code successfully.</p>
<pre><code>all_sites= []
all_sites, pagination_item = server.sites.get()
data = []
for site in all_sites:
data.append([site.id, site.name, site.content_url, site.state])
df = pd.DataFrame(data)
df.columns = ['id', 'name', 'content_url', 'state']
print(df)
</code></pr... | python|pandas|dataframe|tableau-api | 1 |
21,068 | 73,055,559 | How to do an advanced multiplication with panda dataframe | <p>I have a dataframe1 of 1802 rows and 29 columns (in code as df) - each row is a person and each column is a number representing their answer to 29 different questions.</p>
<p>I have another dataframe2 of 29 different coefficients (in code as seg_1).</p>
<p>Each column needs to be multiplied by the corresponding coef... | <p>Proper encoding of the coefficients as a Pandas frame makes this a one-liner</p>
<pre><code>df_person['Answer'] = (df_person * df_coeffs.values).sum(1)
</code></pre>
<p>and circumvents slow <code>for</code>-loops. In addition, you don't need to remember the number of rows in the given table <code>1802</code> and can... | pandas|dataframe|loops|for-loop | 0 |
21,069 | 72,985,694 | Days between dates into minimum non-date measurement | <p>I have a column that represents the number of days from an event until today.</p>
<pre><code>daysSeries = pd.Series([2, 13,29,31,91,180,367,725],dtype=int64)
</code></pre>
<p>I am trying to figure out a way to represent this as a string such that it shows the rounded number of days / weeks / months / years. However... | <p>I did it without the round, it's much easier that way:</p>
<pre><code>import pandas as pd
def lowest_str(days: int) -> str:
if days >= 365:
return f'{days // 365} Years'
if days >= 30:
return f'{days // 30} Months'
if days >= 7:
return f'{days // 7} Weeks'
return ... | python|pandas | 1 |
21,070 | 70,413,094 | What is the appropriate way of outputting dataframe results from a function? | <p>I am pretty new to python and pandas and I am trying to create a function that will read four datasets and combine them into one dataframe. I can get the results I need if I do not try to wrap this all in a function, but I plan to create a similar dataframe for another four datasets, so I believe the function will b... | <p>You're trying to pass a variable that doesn't exist to a function. <code>crime = Crime2020(crime)</code> should be <code>crime = Crime2020()</code> as the variable is being created inside the function and is not being passed from outside.</p>
<p>On a side note it is better convention to use capitalized naming for cl... | python|pandas|dataframe|jupyter-notebook | 1 |
21,071 | 51,180,423 | Is there a bug with PyTorch training for large batch sizes, or with this script? | <p>I am following <a href="https://lelon.io/blog/2018/02/08/pytorch-with-baby-steps" rel="nofollow noreferrer">this PyTorch tutorial</a> by Joshua L. Mitchell. The grand finale of the tutorial is the following PyTorch training script. One element, the batch size, I have parameterized in the first line of the script, ... | <p>Sorry I just realized this was a dumb question. I am doing far fewer updates -- by a factor of 1,024. That's why the accuracy is much lower. I could adjust the learning rate but there is clearly a <a href="https://stats.stackexchange.com/questions/164876/tradeoff-batch-size-vs-number-of-iterations-to-train-a-neur... | python|image-processing|gpu|gpgpu|pytorch | 5 |
21,072 | 51,945,917 | k-hot encode values from multiple columns | <p>I have the <code>pandas.DataFrame</code>:</p>
<pre><code>| | col_1 | col_2 | col_3 | col_4 |
|:--|:------|:------|:------|:------|
| 0 | 1 | 2 | NaN | NaN |
| 1 | 3 | 4 | 5 | 6 |
| 2 | 2 | 6 | NaN | NaN |
</code></pre>
<p>I have to convert values (1, 2, 3, 4, 5, 6) to colu... | <p>One approach with <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> -</p>
<pre><code>In [67]: df
Out[67]:
0 1 2 3
0 1.0 2.0 NaN NaN
1 3.0 4.0 5.0 6.0
2 2.0 6.0 NaN NaN
In [68]: constant_set = [1, 2, 3, ... | python|pandas|numpy | 2 |
21,073 | 35,833,593 | Install NumPy for Python 3.5 | <p>I am using python 3.5 and I am trying to install NumPy but when I try to install from command prompt using command: pip install numpy</p>
<p>I get a whole lot of errors. The main error though seems to be at the end: error: Unable to find vcvarsall.bat</p>
<p>I have also tried downloading the numpy binaries from <a... | <p>An easy way to obtain numpy, scipy, pandas, ... is to install anaconda.
Anaconda will automatically download and install the latest modules.
<a href="https://www.continuum.io/downloads" rel="noreferrer">https://www.continuum.io/downloads</a></p>
<p>I hope this will help you along.</p> | python-3.x|numpy | 6 |
21,074 | 35,868,674 | pandas read_sql to return last row's date | <p>I'm trying to use pandas to read_sql table and return only the last date to me.</p>
<pre><code>pandas.read_sql('sqltable', con=engine)['Date'].tail(1)
</code></pre>
<p><strong>this returns</strong></p>
<pre><code>#Index # Date
2589 2016-03-07
Name: Date, dtype: datetime64[ns]
</code></pre>
<p>But If I do this:... | <p>I used <code>pandas.DatetimeIndex</code> to solve my problem. </p>
<pre><code>ddd = pandas.read_sql('sqltable', con=engine)['Date'].tail(1).values
fff = pandas.DatetimeIndex(ddd).date[0]
print(fff)
</code></pre>
<p>output</p>
<pre><code>2016-03-07
</code></pre> | python|pandas | 0 |
21,075 | 37,367,524 | pandas change a specific column value of duplicate rows | <p>Using the example here <a href="https://stackoverflow.com/questions/23667369/drop-all-duplicate-rows-in-python-pandas">Drop all duplicate rows in Python Pandas</a></p>
<p>Lets say I don't want to drop the duplicates but change the value of the data in one of the columns in the subset.</p>
<p>So as per the example,... | <p>You could use <code>cumcount</code> and do something like</p>
<pre><code>>>> c = df.groupby(["A","C"]).cumcount()
>>> c = c.replace(0, '').astype(str)
>>> df["A"] += c
>>> df
A B C
0 foo 0 A
1 foo1 1 A
2 foo 1 B
3 bar 1 A
</code></pre>
<p>This works becaus... | python|pandas|duplicates | 3 |
21,076 | 37,320,320 | Creating batches from custom dataset of images in Tensorflow | <p>I'm reading a list of .jpg images from disk, and I wanted to split it in several batches. But I got a ValueError while trying to create the first batch.</p>
<p>Here is my code:</p>
<pre><code>import tensorflow as tf
import os
images_list = []
for i in range(6):
image = tf.read_file("{0}.jpg".format(i))
i... | <p>Your error message is not linked to TensorFlow at all (you can see that the ValueError was not thrown by TensorFlow). </p>
<p>If you look at the <a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/io_ops.html#batch" rel="nofollow">doc</a>, you can see that <code>tf.train.batch()</code> returns a list... | python|tensorflow | 4 |
21,077 | 37,396,440 | how to copy and paste sql query in pandas read_Sql | <p>I'm new to python and am trying to run sql code in python and have the results in a pandas dataframe. I'm using the following code and the code runs when i have a simple sql query. But when I try to run a super long and complex query with proper formatting in sql, it fails. Can I use any module/option so python reco... | <blockquote>
<p><code>r = """ Select distinct NPI,
practice_code=RIGHT('000'+CAST(newcode AS VARCHAR(3)),3),
SRcode,
StandardZip,
Zipclass,
CountySSA,
PrimaryCountySSA,
PrimaryCounty,
PrimaryCountyClass,
Lat_Clean,
L... | python|sql-server|pandas | 2 |
21,078 | 37,177,688 | Subsetting 2D array based on condition in numpy python | <p>I have a numpy 2D array of size 3600 * 7200. I have another array of same shape which I want to use as a mask.</p>
<p>The problem is that when I do something like this:</p>
<pre><code>import numpy as np
N = 10
arr_a = np.random.random((N,N))
arr_b = np.random.random((N,N))
arr_a[arr_b > 0.0]
</code></pre>
<p>T... | <p>You can use np.where to preserve the shape:</p>
<pre><code>np.where(arr_b > 0.0, arr_a, np.nan)
</code></pre>
<p>It will take the corresponding values from arr_a when arr_b's value is greater than 0, otherwise it will use np.nan.</p>
<pre><code>import numpy as np
N = 5
arr_a = np.random.randn(N,N)
arr_b = np.r... | python|numpy | 2 |
21,079 | 42,052,239 | Struggle with iterrows using python pandas | <p>I have a dataframe mixed state and region together.
Those value have [edit] means states in US. </p>
<pre><code> RegionName
0 Alabama[edit]
1 Auburn [1]
2 Florence
3 Jacksonville [2]
4 Livingston [2]
5 Montevallo [2]
6 Troy [2]
7 Tuscaloosa [3][4]
8 Tuskegee [5]
9 Alaska[edit]
</code></... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow noreferrer"><code>mask</code></a>, for select last six chars <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="nofollow noreferrer">indexing with str</a>:</p>
<pre><... | python|pandas | 3 |
21,080 | 31,218,624 | How to get a dataframe index based on subselection | <p>I have a dataframe (<code>szen_df</code>) and select a portion of the dataframe which I assign to another dataframe (<code>orb_df</code>). When I try and get the index of the subselected dataframe it still has the whole index of the original dataframe. I would like to get the level 0 index of the new dataframe. eg.<... | <p>Here is one way to do it. First <code>reset_index(level='pos')</code> to break down the multi-level index and then use <code>set_index('pos', append=True)</code> to rebuild the multi-level index.</p>
<pre><code>import pandas as pd
import numpy as np
# simulate your data
np.random.seed(0)
multi_index = pd.MultiInde... | python|pandas | 1 |
21,081 | 31,490,247 | is 0.0000 different from null in pandas? | <p>I have a data frame with a few values as NaN and a few as 0.0000.
When i do</p>
<pre><code>pd.isnull(df);
</code></pre>
<p>I see that it returns TRUE only for NaN but not for 0.0000.</p>
<p>In my dataset, I need to ignore all NaN and 0.0000. I can do it other ways, but I am a bit confused as to how null is defin... | <p>NULLs are used to signify <em>missing data</em>. In Python we normally use <code>None</code> to signal such a situation. Since <em>numeric</em> <code>numpy</code> arrays (an underlying datastructure in a dataframe) cannot hold <code>None</code> values, Pandas uses <code>NaN</code> as NULLs instead.</p>
<p>As such t... | python|pandas | 2 |
21,082 | 64,467,172 | New column values based on conditions | <p>I have a data set like this.</p>
<pre><code>df = pd.DataFrame({"A" :[1,1,3,4], "B": [1,3,2,2]})
</code></pre>
<p>I want to create a new column which is C with type 1 if A = 1 & B =(1,3)
I used <code>.loc</code> and my code is</p>
<pre><code>df.loc[(df['A'] == 1)&(df['B'] == 1), 'C'] = 'ty... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p>
<pre><code>In [1517]: import numpy as np
In [1518]: df['C'] = np.where(df.A.eq(1) & df.B.isin([1,3]), 'type 1', np.nan)
In [1519]: df
Out[1519]:
A B C
0 1 1 t... | python|pandas|dataframe | 3 |
21,083 | 49,054,927 | numpy cumsum( ) not working? | <p>Here is my code:</p>
<pre><code>import numpy as np
a = [4,6,12]
np.cumsum(a)
print(a)
</code></pre>
<p>Instead of getting <code>[4,10,22]</code>, I am still getting <code>[4,6,12]</code>. I am confused. So if <code>cumsum()</code> is not the way to do accumulation sum, what I should do then? Thanks.</p> | <p>The <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.cumsum.html" rel="nofollow noreferrer">docstring of <code>numpy.cumsum</code></a> says:</p>
<blockquote>
<p>Return the cumulative sum of the elements along the given axis.</p>
</blockquote>
<p>So that means it returns a new array. It... | python|arrays|numpy|sum | 2 |
21,084 | 49,271,153 | How to get a placeholder from a list of placeholders using a placeholder in Tensorflow? | <p>I have a list of placeholders as follows:</p>
<pre><code>input_vars = []
input_vars.append(tf.placeholder(shape=[None, 5], dtype=tf.float32, name="place0"))
input_vars.append(tf.placeholder(shape=[None, 5], dtype=tf.float32, name="place1"))
input_vars.append(tf.placeholder(shape=[None, 5], dtype=tf.float32, name="p... | <p>You just need to reshape your output from tf.gather as explained in <a href="https://stackoverflow.com/questions/48272017/determining-variable-rank-with-unknown-shape-in-tensorflow">this</a> answer:</p>
<pre><code>l_in = tf.layers.dense(inputs=tf.reshape(helpme, shape=[-1,5]), units=64, activation=tf.nn.relu, train... | tensorflow | 1 |
21,085 | 58,943,299 | Return the 6th largest value in a row from Python Datagrame | <p>I'm looking to return the 6th largest row value across 10 columns in a df into a new column, in this case, called "6th_largest". In many of the cases throughout the df there could be more than one row that share the 6th largest value. It doesn't matter if it's one or several, I only need to return the actual 6th la... | <p>Use, rank:</p>
<pre><code>df_actual['6th Largest'] = df_actual.where(df_actual.rank(axis=1) == 6).dropna(axis=1)
</code></pre>
<p>Output:</p>
<pre><code> 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 6th Largest
0 0 1 2 3 4 5 6 7 8 9 5
1 1 2 3 4 5 ... | python|pandas|dataframe | 2 |
21,086 | 70,305,851 | How to read time column in pandas and how to convert it into milliseconds | <pre><code>I used this code to read excel file
df=pd.read_excel("XYZ.xlsb",engine='pyxlsb',dtype={'Time':str})
This is just to show what i am getting after reading excel file.
import pandas as pd
import numpy as np
data = {'Name':['T1','T2','T3'],
'Time column in excel':['01:57:15', '00:30:00', '05:00:0... | <p>try dividing the microsecond of the datetime by 1000</p>
<pre><code>def get_milliseconds(dt):
return dt.microsecond / 1000
</code></pre> | pandas|datetime|timedelta|xlsb | 0 |
21,087 | 70,142,779 | Pandas dataframe merge rows based on overlap and intervals | <p>I am failly new with Pandas and I have a question about how to properly merge rows within my pandas datafame, based on the values of its columns.</p>
<p>I have a dataframe, <code>df1</code>, which contains the following:</p>
<pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame(data=[["shoe",... | <p>Here's an attempt:</p>
<pre><code>def consolidate(sdf):
low_high_sorted = sdf[['low', 'high']].sort_values(['low', 'high'])
grouping = pd.Series(0, index=low_high_sorted.index)
group, group_max = 0, low_high_sorted.high.iat[0]
for i, low, high in low_high_sorted.iloc[1:, :].itertuples():
if l... | python|pandas|dataframe | 1 |
21,088 | 70,038,044 | Install Python3.7 with Numpy natively on M1 Mac | <p>I need to Install Python3.7 to support Spark 2 on an M1 Mac.</p>
<p>I can get Python3.7 installed using pyenv, but when I try to install any of the data science libs, like numpy, I get failure: <code>ModuleNotFoundError: No module named '_ctypes'</code></p>
<p>This seems to be related to libffi. Looking through the ... | <p>Use <strong>miniconda</strong> to install things: see <a href="https://stackoverflow.com/a/68228696/9423009">this post</a>.</p>
<p>Miniconda is an open source version of the conda package/environment manager, as an alternative to pyenv + brew.</p>
<p>It will install ARM native versions of python by default, as well ... | python|numpy|apple-m1|pyenv | 1 |
21,089 | 56,198,665 | delete first column when exported excel or csv file in python | <p>let's say, I exported my file in excel</p>
<p><strong>statement Export</strong> </p>
<pre><code>ln[] = writer = pd.ExcelWriter("df2018.xlsx")
writer = pd.ExcelWriter("df2018.xlsx", index = false)
df2018.to_excel(writer)
writer.save()
out[] =
row0 (blank) kanwil jan 2018 feb 2018 janfeb 2018
row1 0 ... | <p>I believe you need specify parameter <code>index=False</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html" rel="nofollow noreferrer"><code>DataFrame.to_excel</code></a>:</p>
<pre><code>pd.ExcelWriter("df2018.xlsx")
df.to_excel(writer, index = False)
</code></... | python|pandas|spreadsheet-excel-writer | 3 |
21,090 | 56,328,974 | Reading a stacked heading excel sheet using Python | <p>I have an excel sheet where the headings (TradeDate, Value) are stacked on top of each other separated by a type(ABS, MBS), an example of the format:</p>
<pre><code>ABS,
TradeDate,Value
2019-01-21,21
2019-01-22,22
MBS,
TradeDate,Value
2019-01-21,11
2019-01-22,12
2019-01-23,13
</code></pre>
<p>How can I load this i... | <p>This might be a bit overengeneering, but couldn't find a more easy solution:</p>
<pre><code># Mask all the rows which have a date
m = df[0].str.match('([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))')
# Create an equal indicator on each row which has a date, but stops when value changes so we can groupby
df['ind... | python|excel|pandas | 1 |
21,091 | 56,164,988 | Wrong output while adding two columns in pandas | <p>I have been trying to add up the columns but it's resulting in the wrong output.
ex: 1+2=3
but i am getting 12 instead.</p>
<pre><code>0 NaN
1 20
2 10
3 NaN
4 NaN
5 20
6 10
7 20
8 020
</code></pre>
<p>code used:</p>
<pre><code>df.x+df.y
</code></pre> | <p>Values are strings, so instead <code>sum</code> are joined together.</p>
<p>Solution is convert them to numeric:</p>
<pre><code>s = df.x.astype(float)+df.y.astype(float)
</code></pre>
<p>If not working first solution because some data are not numeric, try <a href="http://pandas.pydata.org/pandas-docs/stable/refer... | python|pandas|dataframe | 3 |
21,092 | 55,982,115 | plotting multiple contour plots on the same figure | <p>I am trying to make multiple contourf plots using the same figure: I want to display each contour as one color and then plot legend for each color</p>
<p>When I try, all the two countours ends up as the same color showing no difference at all</p>
<pre><code>proj = ccrs.PlateCarree()
fig, axarr = plt.subplots( figs... | <p>It sounds to me that both pskw and shift will be plotted on the same nodes, identified by lon and lat. This means that the second contourf call will simply hide the first one.</p>
<p>With this in mind, there are a few possibilities:</p>
<ul>
<li>use contourf for the first call and contour for the second one</li>
<... | python|numpy|matplotlib | 0 |
21,093 | 64,653,293 | How to order 3 columns in series? python pandas | <p>I have the following dataframe:</p>
<pre><code>df = {names:["CARL","HERMES","LEO"], srv:[234,123,44], mx_l1:[10,12,8], mx_l2:[20,8,10], mx_l3:[12,23,11], label:["street","city","apto"]}
</code></pre>
<p>but the length columns(mx_l1,mx_l2,mx_l3) must go vert... | <p>IIUC, this is what you want:</p>
<pre><code>df = (
df.melt(
id_vars=["names", "srv", "label"],
value_vars=["mx_l1", "mx_l2", "mx_l3"],
value_name="max_length",
)
.sort_values(["names", "srv",... | python|pandas | 1 |
21,094 | 40,290,929 | pandas iterate rows and then break until condition | <p>I have a column that's unorganized like this;</p>
<pre><code>Name
Jack
James
Riddick
Random value
Another random value
</code></pre>
<p>What I'm trying to do is get only the names from this column, but struggling to find a way to differentiate real names to random values. Fortunately the names are all together, a... | <p>Find index of row containing 'Random value':</p>
<pre><code>index_split = df[df.Name == 'Random value'].index.values[0]
</code></pre>
<p>Save your random values column for use later if you want:</p>
<pre><code>random_values = df.iloc[index_split+1:,].values[0]
</code></pre>
<p>Remove random values from the Names... | excel|loops|pandas|dataframe|list-comprehension | 1 |
21,095 | 40,098,142 | Taking fast screenshot Winapi and Opencv | <p>I need to take very fast screenshots of a game for an OpenCV project I am working on. I can use PIL easily for example:</p>
<pre><code>def take_screenshot1(hwnd):
rect = win32gui.GetWindowRect(hwnd)
img = ImageGrab.grab(bbox=rect)
img_np = np.array(img)
return cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)... | <p>I'll just show the code that works for me.</p>
<pre><code>import time
import win32gui
import win32ui
import win32con
import win32api
import numpy as np
import cv2
def window_capture():
hwnd = 0
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompa... | python|opencv|numpy|winapi | 0 |
21,096 | 40,138,380 | 'DataFrame' object is not callable | <p>I'm trying to create a heatmap using Python on Pycharms. I've this code:</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
data1 = pd.read_csv(FILE")
freqMap = {}
for line in data1:
for item in line:
if not item in freqMap:
fr... | <p>You are reading a csv file but it has no header, the delimiter is a space not a comma, and there are a variable number of columns. So that is three mistakes in your first line.</p>
<p>And data1 is a DataFrame, freqMap is a dictionary that is completely unrelated. So it makes no sense to do data1[freqMap].</p>
<p>I... | python|pandas|matplotlib|dataframe | 2 |
21,097 | 39,461,904 | How to understand the convolution parameters in tensorflow? | <p>When I reading the chapter of "Deep MNIST for expert" in tensorflow tutorial.</p>
<p>There give below function for the weight of first layer. I can't understand why the patch size is 5*5 and why features number is 32, are they the random numbers that you can pick anyone or some rules must be followed? and ... | <p>The patch size and the number of features are network hyper-parameters, therefore the are completely arbitrary.</p>
<p>There are rules of thumb, by the way, to follow in order to define a working and performing network.
The kernel size should be small, due to the equivalence between the application of multiple smal... | tensorflow|conv-neural-network | 1 |
21,098 | 39,446,313 | Using tf.unpack() when first dimension of Variable is None | <p>I'm feeding in a dynamic shaped Tensor using: </p>
<p><code>x = tf.placeholder(tf.int32, shape=[None, vector_size])</code></p>
<p>I need to turn this into a list of Tensors that have <code>shape=[1, vector_size]</code> using <code>x_list = tf.unpack(x, 0)</code></p>
<p>But it raises a <code>ValueError</code> beca... | <p>I don't think you can <code>unpack</code> a tensor with the argument <code>num</code> unspecified and non-inferrable. As their <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/array_ops.html#unpack" rel="noreferrer">documentation</a> says:</p>
<blockquote>
<p>Raises ValueError if <code>num</code... | python|tensorflow|machine-learning | 19 |
21,099 | 39,606,534 | sqlalchemy / pandas - How do I create an sqlalchemy `selectable` to pass to pd.read_sql? | <p>I'm completely new to sqlalchemy, and I've been trying to better understand how <code>pd.read_sql</code> can be used.</p>
<p>I've succesfully run the following:</p>
<pre><code>import sqlalchemy as sa
import pandas as pd
df = pd.DataFrame( index=range(10,30), data=np.random.rand(20, 10) )
eng = sa.create_engine('sq... | <p>Getting the table in 3 different ways. (Not sure what the differences are).</p>
<p>then using the <code>.select()</code> method on that table and the <code>.where</code> on that result gets what I want.</p>
<pre><code>import sqlalchemy as sa
eng = sa.create_engine('sqlite:///test.db')
# First way to load table
m =... | python|pandas|sqlalchemy | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.