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 |
|---|---|---|---|---|---|---|
367,900 | 71,654,471 | Pandas: Use column value to select the value from a different column to populate a new column | <p>I have this dataframe call quest:</p>
<pre><code> 0_score 1_score 2_score 3_score 4_score 5_score true_label
0 0.007512 0.264500 0.273147 0.218029 0.233726 0.003084 1
1 0.130695 0.289085 0.173402 0.144897 0.238129 0.023792 1
2 0.006896 0.130070 ... | <p>You can use <code>DataFrame.apply</code></p>
<pre><code>def label_score(row):
col_num = int(row['true_label'])
return row[f'{col_num}_score']
quest['true_label_score'] = quest.apply(label_score, axis=1)
</code></pre>
<p>If you want a solution based on the <code>scores</code> list you can do</p>
<pre><code>s... | python|pandas|lambda | 0 |
367,901 | 71,550,178 | How to compare strings from 2 dataframes, and create new column containing matching words? | <p>I have two datasets readed in Pandas dataframes.</p>
<p>categories_df:</p>
<pre><code>id category
0 foot
1 electricity
2 car moto
3 driving licence
</code></pre>
<p>sentences_df</p>
<pre><code>sentence_id sentence
0 I love football
1 Yesterday I didn't have elec
2 I only have a car... | <p>Assuming <code>categories_df</code> is an existing variable within this scope:</p>
<pre><code>def get_overlapping_categories(text):
overlapping_categories = []
tokens = text.split()
for c in categories_df["category"]:
if any([t in c.split() for t in tokens]):
overlapping_cat... | python|pandas | 1 |
367,902 | 71,710,269 | Reading data from a CSV file yields TypeError | <p>I have a csv file with the following data stored as uncov_users.csv: <code>2867,2978</code></p>
<p>I am trying to get the data from the CSV file and print it but I am getting an error. I need the data in separate variables so I am using the <code>for i,j</code> loop.</p>
<p>My Code:</p>
<pre><code>import numpy as np... | <p>Try this:</p>
<pre><code>import numpy as np
text = open("ucov_users.csv", "r")
text = ''.join([i for i in text]) \
.replace(" ", "\n")
x = open("ucov_users.csv", "w")
x.writelines(text)
x.close()
uncov_users = np.genfromtxt('ucov_users.csv', delimite... | python|python-3.x|numpy|csv | 1 |
367,903 | 71,530,516 | How do I make regex .findall() return all matches within for-loop as intended? | <p>I am trying to write a for-loop that iterates through individual rows. It uses regex to find a specific date identified by name. It then strips the date name, and saves the date itself as a list object for placement in an appropriate empty column.</p>
<p>My issue is that some rows have multiple dates of the same nam... | <p>was able to come up with a for-loop that does what I want. Thanks to everyone for your assistance!</p>
<pre><code>exit_note_date = []
for index, row in exit_note.iterrows():
x = row['Exit Note']
edmatch = re.findall(r'(Exit Date:.*?\d{2}/\d{2}/\d{4})', x)
if len(edmatch) > 0:
edstring = [exit_... | python|regex|pandas|for-loop | 0 |
367,904 | 71,474,732 | How to simplify data.table logic and make it doable in pandas? | <p>I have a dataframe with multiple columns with numerical values. I wanted to new columns which compare the values of other columns and assign its column name as label. I already understood its logic in r, but wondering how should I do this easily in python. Can anyone point me out how this can be done in python when ... | <p>This is actually really simple with pandas. Have a list of the columns to search in, and then use <code>idxmax</code> with <code>axis=1</code>:</p>
<pre><code># Filter out rows where `cnt` is less than or equal to 2
df = df[df['cnt'] > 2]
# Determine category for each row
search_cols = ['RECENT_MOV', 'RETIRED', ... | python|r|pandas|dataframe|data.table | 2 |
367,905 | 71,610,865 | How to show mean MPG and HP by manufacturer only in mtcars python dataset? | <p>im very new to using panda, and im trying to figure out how to do this problem. summarize: show the mean mpg and hp for each manufacturer. I have this code:</p>
<pre><code>mtcars = pd.read_csv('mtcars.csv')
list(mtcars)
mtcars.describe()
mtcars.rename(columns={"Unnamed: 0": "Make n Model"}, inp... | <p>I'll consider that the "Make n Model" is the manufacturer column in your dataframe. So to groupby manufacturer and take the means and output a newer dataframe with manufacturers as index you would have to do</p>
<pre><code>import pandas as pd
df = pd.read_csv(...)
df_grouped = df.groupby("Make n Mod... | python|pandas | 0 |
367,906 | 71,627,701 | Count Matches between two lists in python and return matches | <p>I am trying to add a count of all the matches between dataframes a & b</p>
<pre><code>df2['Count'] = len(set(a) & set(b))
df2.head(5)
</code></pre>
<p>But it only returns "0"</p>
<p>Data for a:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Result</th>
<th>Column1</th>... | <p>lets consider the dataframe</p>
<pre><code>df = pd.DataFrame([['a','c'],['a','b']])
</code></pre>
<p>Running <code>set(df)</code> results in <code>{0,1}</code> which is not the set of entries you want. What you need to do is get a flattened list of entries (see <a href="https://stackoverflow.com/questions/952914/how... | pandas|dataframe|count | 0 |
367,907 | 42,470,995 | Pandas - Extracting value to basic python float | <p>I'm trying to extract a cell from a pandas dataframe to a simple floating point number. I'm trying</p>
<pre><code>prediction = pd.to_numeric(baseline.ix[(baseline['Weekday']==5) & (baseline['Hour'] == 8)]['SmsOut'])
</code></pre>
<p>However, this returns</p>
<pre><code>128 -0.001405
Name: SmsOut, dtype: flo... | <p>Output is <code>Series</code> with one value, so then is more possible solutions:</p>
<ul>
<li>convert to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_numpy.html" rel="noreferrer"><code>to_numpy</code></a> and select first value by indexing</li>
<li>sel... | python|pandas | 6 |
367,908 | 42,438,987 | Dealing with SettingWithCopyWarning when assigning columns in Pandas | <p>I have a <code>DataFrame</code> which I want to extend with columns that contain data from the previous row.</p>
<p>This script does the job:</p>
<pre><code>#!/usr/bin/env python3
import numpy as np
import pandas as pd
n = 2
df = pd.DataFrame({'A': [1,2,3,4,5], 'B': [0,1,1,0,0]}, columns=['A', 'B'])
df2 = df[d... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow noreferrer"><code>copy</code></a>:</p>
<pre><code>df2 = df[df['B'] == 0].copy()
</code></pre>
<p>If you modify values in <code>df2</code> later you will find that the modifications do not propa... | python|pandas | 4 |
367,909 | 42,330,578 | Numpy: difference b/w A[:i][:j] and A[:i,:j] | <p>Why is there a difference in the following operations, How are they implemented in the library?</p>
<pre><code>print(prov_img[:19][:20].shape)
Output : (19, 1250)
print(prov_img[:19,:20].shape)
Output : (19, 20)
</code></pre> | <p><code>prov_img</code> is a 2d array here.</p>
<p>This code snippet is providing you the first 19 rows (0th row to 18th row) and 20 columns (0th column to 19th column) of <code>prov_img</code>:</p>
<pre><code>>>> prov_img[:19,:20].shape
(19, 20)
</code></pre>
<hr>
<p>Here, <code>prov_img[:19]</code> give... | python|python-3.x|numpy | 4 |
367,910 | 42,175,206 | Can I use scipy.curve fit in python when one of the fitted parameters changes the xdata input array values? | <p>This is my first time posting a question and I'm going to try to make it as clear as I can but feel free to ask questions.</p>
<p>I'm trying to fit a model to a curve using the scipy.curve_fit method as below:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as pyplot
import scipy
from scipy.optimize imp... | <p>I'll split this in two: conceptual and coding related</p>
<p>Conceptual:</p>
<p>Let's start by rephrasing your question. As it stands the answer is: Yes, obviously. Simply <em>absorb</em> the parameter-dependent change of <code>x</code> in the target function. But that won't solve your problem. What you really see... | python|numpy|scipy|least-squares|model-fitting | 0 |
367,911 | 42,447,316 | How to make order of parsed securities in Pandas-Datareader in original order? | <p>List of my securities is:</p>
<pre><code>tickers = ['TLW.L','WEIR.L','RMG.L','TSCO.L','STAN.L','CNA.L']
</code></pre>
<p>When I call pandas datareader to extract adj. close for each, I get a dataframe where all tickers are parsed in alphabetic order:</p>
<pre><code>hist_prices = web.DataReader(tickers, 'yahoo', ... | <p>You can use the <code>tickers</code> list in order to select your columns in a desired order:</p>
<pre><code>In [6]: from pandas_datareader import data as web
In [7]: hist_prices = web.DataReader(tickers, 'yahoo', '2016-01-01', '2016-01-08') \
.loc['Adj Close'] \
[... | python|pandas|dataframe|yahoo|datareader | 2 |
367,912 | 42,258,329 | Python - Calculate ongoing 1 Standard Deviation from linear regression line | <p>I have managed to get a linear regression line for time series data, much thanks to stackoverflow prior. So I have the following plots/line drawn over from python:</p>
<p><a href="https://i.stack.imgur.com/wX2h2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wX2h2.png" alt="Linear Regression Lin... | <p>IIUC you can do it this way:</p>
<pre><code>In [185]: x = np.arange(100)
In [186]: y = x*0.6
In [187]: plt.scatter(x, y, c='b')
Out[187]: <matplotlib.collections.PathCollection at 0xc512390>
In [188]: plt.scatter(x, y - np.std(y), c='y')
Out[188]: <matplotlib.collections.PathCollection at 0xc683940>
... | python|pandas|datetime|dataframe|linear-regression | 2 |
367,913 | 42,434,205 | How to move a row in pandas dataframe which have unordered index to the first row? | <p>I have a dataframe df like this:</p>
<pre><code>index col1 col2 col3
noun 1 1 1
verb 4 6 1
<s> 9 6 5
Adj 5 1 3
<end> 0 0 0
</code></pre>
<p>How to I move the row with index <code><s></code> to the first row, so I have something like this:</p>
<pre><co... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="noreferrer"><code>reindex</code></a> by <code>list</code> where prepend <code>value</code> and remove it by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="no... | python|pandas|numpy|dataframe | 8 |
367,914 | 42,242,546 | Pandas: sum values in some column | <p>I need to group elements and sum it with one column.</p>
<pre><code> member_id event_path event_duration
0 111 vk.com 1
1 111 twitter.com 4
2 111 facebook.com 56
3 111 vk.com 23
4 222 vesti.ru ... | <p>You need <code>groupby</code> with parameters <code>sort=False</code> and <code>as_index=False</code> with aggregation <code>sum</code>:</p>
<pre><code>df = df.groupby(['member_id','event_path'],sort=False,as_index=False)['event_duration'].sum()
print (df)
member_id event_path event_duration
0 111 ... | python|pandas|group-by|sum|aggregate | 3 |
367,915 | 42,189,659 | How to extract rows in a dataframe that do not exist in another | <p>I have two dataframes: </p>
<p>all_data:</p>
<pre><code> AID VID Freq
0 00016A3E 0127C661 1
1 00016A3E 0C05DA5D 2
2 00016A3E 0C032814 1
3 00016A3E 0BF6C78D 1
4 00016A3E 0A79DFF1 1
5 00016A3E 07BD2FB2 1
6 00016A3E 07... | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="noreferrer">merge(..., how='left', indicator=True)</a> together with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="noreferrer">query()</a> method:</p>
<pre>... | python|pandas|dataframe | 5 |
367,916 | 42,195,414 | how to add deterministic vector operations in PYMC3? | <p>how can deterministic vector operations be implemented in PYMC3? for example the model:</p>
<pre><code>M ~ Unif(-5, 5)
S ~ Unif(0, |1 / M|)
data ~ Normal(M, S)
</code></pre>
<p>M is mean of Gaussian observations and S is standard deviation. The standard deviation is assumed to be uniformly distributed in [0, |1/M|... | <p>I guess the problematic part of your model is <code>1/M</code>. Because this goes to infinity as M approach to 0. In fact in your example, the first proposed value for M is 0 (the mean of the lower and upper boundaries) hence the error of "no finite value" you are getting (the error comes from the variable S).</p>
... | python|numpy|theano|pymc|pymc3 | 1 |
367,917 | 42,477,251 | Pandas group by filter based on conditions | <p>I have a dataset quite similar to mentioned here
<a href="http://pandas.pydata.org/pandas-docs/stable/10min.html#grouping" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/stable/10min.html#grouping</a></p>
<pre><code>>>> df
A B C
0 foo one -1.735400
1 bar one -0.148... | <p>If I understand correctly, you could <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> the MuliIndex level and then use filtration. </p>
<pre><code>grpd.groupby(level='A').filter(lambda grp: (grp > 1000).all())
</code... | python|pandas|dataframe | 1 |
367,918 | 42,171,886 | Pandas converting all data to NaN after adding column values | <p>I'm trying to add column headers to the following set of data. As per specifications of the project, I cannot simply modify the file to add those headers manually.</p>
<p>Sample of the data that I'm working with:</p>
<pre><code>38.049133 0.224026 0.05398 -19.11 -20.03
38.352526 0.212491 0.05378 -18.35 -19.19... | <p>To fix your problem, use this line instead:</p>
<pre><code>df = pd.read_csv('file_name', header=None, names=dataColumns)
</code></pre>
<p><code>pd.read_csv</code> returns a DataFrame, so the above line should handle the entirety of the import (i.e. calling <code>pd.DataFrame</code> on the result of <code>pd.read_c... | python|pandas|nan | 1 |
367,919 | 42,391,598 | Expand Vector in Tensorflow and space elements with zeros | <p>I would like to space vector elements from each others and fill it with zeros:</p>
<pre><code> a = [1, 5, 7, ..., 3]
</code></pre>
<p>Space elements of a with two zeros:</p>
<pre><code> b = [1, 0, 0, 5, 0, 0, 7, 0, 0, ... , 3, 0, 0]
</code></pre>
<p>The number of zeros that I space the elements with should be ... | <p>Could you do it as explained <a href="https://stackoverflow.com/questions/37061808/how-does-tensorflow-indexing-work">in this post</a> (second example of the accepted answer)?</p>
<p>Basically I would first create <code>b</code> as a a vector of zeros, then compute the indices which point into <code>b</code> for a... | vector|tensorflow|expand | 2 |
367,920 | 42,172,204 | Replace value in any column in pandas dataframe | <p>In the dataframe below:</p>
<pre><code> T2MN T2MX RH2M DFP2M RAIN
6.96 9.32 84.27 5.57 -
6.31 10.46 - 5.63 -
- 10.66 79.38 3.63 -
0.79 4.45 94.24 1.85 -
1.45 3.99 91.71 1.17 -
</code></pre>
<p>How do I replace all the <code>-</code> with NaN's. I do not want t... | <p>Just <code>replace()</code> the string:</p>
<pre><code>In [10]: df.replace('-', 'NaN')
Out[10]:
T2MN T2MX RH2M DFP2M RAIN
0 6.96 9.32 84.27 5.57 NaN
1 6.31 10.46 NaN 5.63 NaN
2 NaN 10.66 79.38 3.63 NaN
3 0.79 4.45 94.24 1.85 NaN
4 1.45 3.99 91.71 1.17 NaN
</code></pre> | python|pandas | 5 |
367,921 | 42,470,319 | Output of Tensorflow LSTM-Cell | <p>I've got a question on Tensorflow LSTM-Implementation. There are currently several implementations in TF, but I use:</p>
<pre class="lang-py prettyprint-override"><code>cell = tf.contrib.rnn.BasicLSTMCell(n_units)
</code></pre>
<ul>
<li>where n_units is the amount of 'parallel' LSTM-Cells.</li>
</ul>
<p>Then to get ... | <p>I think the primary confusion is on the terminology of the LSTM cell's argument: <code>num_units</code>. Unfortunately it doesn't mean, as the name suggests, "the no. of LSTM cells" that should be equal to your time-steps. They actually correspond to the number of dimensions in the hidden state (cell state + hidden ... | python|tensorflow|output|lstm | 6 |
367,922 | 42,168,233 | How to separate rows of dataframe based on dynamic conditions using Python | <p>Weird issue I can't seem to wrap my head around and I know there's a better way to look at it, I'm just stuck. I need to grab chunks of this data based on the type. 1 through 4 go together in a sort of set, so I would want for example, rows 0 through 8, then 9 on. Each set would be entered as an entry in a database.... | <p>I'm assuming you'll be able to tell the sets apart because the type of the next one will be less than the earlier one. </p>
<p>You can add an extra temporary column that adds serial numbers of separated dataframes. Something like this : </p>
<pre><code>def separate_df(t):
res = pd.Series()
previous_df_no = 0... | python|pandas|numpy|dataframe | 2 |
367,923 | 42,372,006 | Map numbers to their percentiles | <p>I would like to <em>apply</em> the <em>result</em> of <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.percentile.html" rel="nofollow noreferrer"><code>numpy.percentile</code></a> to its argument, i.e., map every number in the input vector to its quantile.</p>
<p>E.g., if <code>v=np.array([1,2,3,... | <pre><code>(v > np.percentile(v, 50)).astype(int)
Out[93]:
array([0, 0, 1, 1])
</code></pre> | python|pandas|numpy|percentile | 3 |
367,924 | 42,513,039 | How to read multiple lines from csv into a single dataframe row with pandas | <p>I have a file that has a comment on the first the line, followed by two lines with the names of the headers slippted across them and a third line with the name of the index. The file looks like this:</p>
<pre><code># 3 5 <-- this is a comment indicating how many rows and column are matrix data
head1 head2 head3
... | <p>You can specify the <code>skiprows</code> keyword of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">read_csv</a> in order to create one data frame that contains all 3-value lines (by skipping the 2-valued ones) and then create another data frame which c... | python|csv|pandas | 9 |
367,925 | 42,509,823 | Obtain a submatrix of a NumPy ndarray using a generator expression | <p>I want to obtain a submatrix of a NumPy <code>ndarray</code> using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html" rel="nofollow noreferrer"><code>numpy.ix_</code></a> and a sequence of indexes from a generator expression. In the following toy example, why does this not work:</p>
<pre><... | <p>Focus just on the <code>ix_</code> step; here's the full error message:</p>
<pre><code>In [255]: ind = (i for i in range(0, 6, 2))
In [256]: np.ix_(ind, ind)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ip... | python|arrays|python-3.x|numpy | 1 |
367,926 | 42,520,470 | Parsing Complex Mathematical Functions in Python | <p>Is there a way in Python to parse a mathematical expression in Python that describes a 3D graph? Using other math modules or not. I couldn't seem to find a way for it to handle two inputs.</p>
<p>An example of a function I would want to parse is <a href="https://www.sfu.ca/~ssurjano/holder.html" rel="nofollow noref... | <p>It's not hard to write straight <code>numpy</code> code that evaluates this formula.</p>
<pre><code>def holder(x1, x2):
f1 = 1 - np.sqrt(x1**2 + x2**2)/np.pi
f2 = np.exp(np.abs(f1))
f3 = np.sin(x1)*np.cos(x2)*f2
return -np.abs(f3)
</code></pre>
<p>Evaluated at a point:</p>
<pre><code>In [109]: hol... | python|parsing|numpy|math|expression | 4 |
367,927 | 42,400,773 | Python Pandas Group By Error 'Index' object has no attribute 'labels' | <p>I am getting this error:</p>
<pre><code> 'Index' object has no attribute 'labels'
</code></pre>
<p>The traceback looks like this:</p>
<pre><code>Traceback (most recent call last):
File "<ipython-input-23-e0f428cee427>", line 1, in <module>
df_top_f = k.groupby(['features'])['features'].count(... | <p>Perhaps not the shortest, but a very straightforward approach would just be to construct a new DataFrame explicitly from the index and values. </p>
<pre><code>>>> grp_cnt = df.groupby(['features'])['features'].count()
>>> pd.DataFrame(dict(features=grp_cnt.index, count=grp_cnt.values))
count ... | python|pandas|dataframe | 9 |
367,928 | 42,156,296 | DropoutWrapper being non-deterministic across runs? | <p>In the beginning of my code, (outside the scope of a <code>Session</code>), I've set my random seed -</p>
<pre><code>np.random.seed(1)
tf.set_random_seed(1)
</code></pre>
<p>This is what my dropout definition looks like -</p>
<pre><code>cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=args.keep_prob, s... | <p>The answer was already provided in the comments, but no-one has written it explicitly yet, so here it is:</p>
<p><code>dynamic_rnn</code> will internally use <code>tf.while_loop</code>, which can actually evaluate multiple iterations in parallel (see documentation on <code>parallel_iterations</code>). In practice, ... | python|tensorflow | 4 |
367,929 | 69,826,030 | How to add a total value column for a Waterfall Chart in Plotly | <p>I'm trying to add a "total value" column in my waterfall chart but I'm not why I can't do it as this data is in my table. See my actual table:</p>
<pre><code>DealID Customer deal value (USD) Measure
Q1 SIEMENS AG $1.200.000 Relative
Q2 SIEMENS AG $800.000 ... | <p>Looking at the <a href="https://plotly.com/python/waterfall-charts/" rel="nofollow noreferrer">documentation</a>, I think that the <code>measure</code> argument for <code>go.Waterfall</code> expects <code>'relative', 'absolute', or 'total'</code>, in all lowercase letters.</p>
<p>I imported your DataFrame and ran yo... | python|pandas|dataframe|plotly|plotly-python | 1 |
367,930 | 69,928,177 | tf.contrib.training.HParams error in tensorflow 2 | <p>I am trying to use nmt-chatbot from <a href="https://github.com/daniel-kukiela/nmt-chatbot" rel="nofollow noreferrer">https://github.com/daniel-kukiela/nmt-chatbot</a> but while training the model with custom data I am getting the error, as I searched on google it is because in Tensorflow v2 the "contrib" ... | <p>You can see the fate of all the contrib API <a href="https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md#list-of-projects" rel="nofollow noreferrer">here</a>,also <a href="https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0" rel="nofollow nor... | python|tensorflow|artificial-intelligence|tensorflow2.0|chatbot | 0 |
367,931 | 69,803,444 | Unique keywords on the column | <p>I'm new to pandas and I have a question.</p>
<p>I have a dataframe like</p>
<pre><code>Code Keywords
A Real estate, loan, building, office, land, warehouse
B Real Estate Lease , Real Estate, building, Office, Warehouse, rental, Tenant, broker advisor, Real Estate Lease , Lease and rent
C Transpo... | <p>One way using <code>pandas.Series.str.split</code> with <code>explode</code>:</p>
<pre><code>m = df["Keywords"].str.split("\s*,\s*").explode()
m = m[~m.str.lower().duplicated(False)]
df["Keywords"] = m.groupby(m.index).apply(", ".join)
df = df.fillna("")
</code></pre... | python|pandas|dataframe | 1 |
367,932 | 69,964,622 | How to convert array(densevectors) into array? | <p>In the code below I am trying to implement weighted voting classifier using <code>EnsembleVoteClassifier()</code>.</p>
<pre><code>from mlxtend.classifier import EnsembleVoteClassifier
import copy
eclf = EnsembleVoteClassifier(clfs=[s1, s2], weights=[1,1],refit=False)
</code></pre>
<p>where s1 and s2 are PySpark pi... | <p>Which package are you using to obtain <code>DenseVector</code>?</p>
<p>Is it Spark ? If yes, according to the <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.linalg.DenseVector.html" rel="nofollow noreferrer">documentation</a>, <code>DenseVector</code> has a <code>toArray()</code> m... | python|arrays|pyspark|numpy-ndarray | 0 |
367,933 | 69,730,355 | Concanate cells from a column with respect to an indicator | <p>I have the following DataFrame:</p>
<p>import pandas as pd</p>
<pre><code>DataExe = [[2 , 1],
[4 , 1],
[7 , 2],
[9 , 3],
[10, 3],
[15, 3],
[19, 2],
[24, 2],
[27, 2],
[29, 2],
[37, 2],
[38, 2]]
D... | <p>You could use <code>groupby</code>+<code>transform</code>:</p>
<pre><code>DataExe['ColC'] = DataExe.groupby('Indicator')['ColA'].transform(lambda g: ','.join(map(str, g)))
</code></pre>
<p>Output:</p>
<pre><code> ColA Indicator ColC
0 2 1 2,4
1 4 1 ... | python|python-3.x|pandas | 1 |
367,934 | 69,764,112 | Shift values from two separate cells into one using Pandas | <p>I have a dataset, df, where I would like to combine certain values from separate columns into one 'cell':</p>
<p><strong>Data</strong></p>
<pre><code>hello hi ok bye
q122 q222 q422 q222
hi hi hi hi
</code></pre>
<p><strong>Logic</strong></p>
<pre><code>The first two rows are ... | <p>You need set second row (<code>[1]</code>) by empty strings and filter out first row by <code>[1:]</code>:</p>
<pre><code>#solution if default header
print (df)
0 1 2 3
0 hello hi ok bye
1 q122 q222 q422 q222
2 hi hi hi hi
df.columns = df.iloc[0] + '_' + df.iloc[1]
df.i... | python|pandas|numpy | 2 |
367,935 | 69,984,276 | Slice 2D array using mask | <p>Assume an array of</p>
<pre><code>0 = {ndarray: (4,)} [5 0 3 3]
1 = {ndarray: (4,)} [7 9 3 5]
2 = {ndarray: (4,)} [2 4 7 6]
3 = {ndarray: (4,)} [8 8 1 6]
</code></pre>
<p>I would like slice index where <code>epoch_label</code> is equal to zero</p>
<pre><code>[1 1 0 0]
</code></pre>
<p>From above, the index will be t... | <p>With</p>
<pre><code> In [242]: Nepochs = 4
...: epoch_com = [np.random.randint(10, size=4) for _ in range(Nepochs)]
...: epoch_com_arr=np.array(epoch_com)
...: epoch_label=np.random.randint(2, size=Nepochs)
...: mm=np.ma.masked_where(epoch_label == 0, epoch_label)
...: expected_output=np.where(epoch_com_arr[mm,... | python|numpy|mask | 0 |
367,936 | 69,676,782 | Is there a pandas split(expand=True) equivalent in Bigquery function? | <p>I'm trying to reproduce the following example in BigQuery :</p>
<p>Starting with the table :</p>
<pre><code>ROW VALUE
0 AAA
1 BBB
2 CCC ~ DDD
</code></pre>
<p>I want to... | <p>This is not a perfect solution, but to get part 1 and part 2 of split you could write:</p>
<pre><code>with tab1 as (
SELECT NULL as col1
UNION ALL
SELECT 'AAA' as col1
UNION ALL
SELECT 'BBB' as col1
UNION ALL
SELECT 'CCC ~ DDD'as col1
)
SELECT
col1,
SPLIT(col1, "~"... | pandas|dataframe|google-bigquery | 2 |
367,937 | 69,741,687 | How to create subelements of a NumPy Array by taking in consideration a criteria in Python? | <p>I am currently working on Python 3.8 with a NumPy object array and I try to extract some subelements from this NumPy Array respecting a criteria.</p>
<p>For example, if I take in consideration this NumPy Array :
<a href="https://i.stack.imgur.com/3SE7T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.c... | <p>There are several ways to approach this problem, one way I could think of is to directly use a comparision operator.</p>
<p>Example ( <a href="https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html" rel="nofollow noreferrer">Source: numpy docs</a> )</p>
<pre><code>a = np.array([[0, 0, 0], [0.3, 0.41, 0.... | python|arrays|numpy | -1 |
367,938 | 69,703,998 | How to use predictions based on a Date column | <p>I'm fairly new on python and ML. I have a simple table that contains a date column and a float value. I want to predict the future sales for a given period, let's say <code>2022-01</code>, I managed to obtain a prediction based on my data but the number of prediction values is equal to the number of given trained va... | <p>When you run <code>model.predict</code> you are running it on your <code>x_train</code> rather than your <code>test</code> - that's why your prediction values are equal to that number. You want to <code>fit</code> your model on your train data, and <code>predict</code> on your test data.</p> | python|pandas|machine-learning|scikit-learn|random-forest | 0 |
367,939 | 69,805,352 | Trying to see if a column equals another column | <p>I have a dataframe with some dummy variables and I wanted to see for a column with a df value of 1 has a value of a 0 to the right of that value within the same row. Here is an example of a dataframe and the columns that would return the rows I want. You can see that I would like to result in the the rows with index... | <p>One way using <code>pandas.DataFrame.shift</code>:</p>
<pre><code>res = test_df[(test_df.eq(0) & test_df.shift(axis=1).eq(1)).any(1)]
</code></pre>
<p>Output:</p>
<pre><code> 2018-02 2018-03 2018-04 2018-05 2018-06
1 0 1 1 0 1
2 0 1 1 0 ... | python|pandas | 0 |
367,940 | 69,850,924 | How to rearrange rows of a dataframe according to the values of a specific column | <p>I am working on a dataframe that has a column named <strong>season</strong>. Each season has many matches. The order of season is to be rearranged.
Season order is <code>2017,2008,2009,2010,2011,2012,2013,2014,2015,2016,2018,2019</code>.</p>
<p>I want to bring all the rows of the season 2017 after 2016 season rows.<... | <p>First idea is sorting by ordered categoricals with order by <code>list</code>:</p>
<pre><code>L =[2008,2009, 2010, 2011, 2012, 2013, 2014, 2015,2016,2017, 2018, 2019]
df['season'] = pd.Categorical(df['season'], ordered=True, categories=L)
df = df.sort_values(['season','match_id'], ignore_index=True)
</code></pre>
<... | python|pandas|indexing | 2 |
367,941 | 69,995,481 | Linear regression between two price with time series | <p>Do you know how to calculate linear regression between two points in time? For example between two prices for Amazon.
I am asking because all simple examples are with numbers on x axis and values on y axis and this solution from :</p>
<p><a href="https://stackoverflow.com/a/43594674/9403794">How to calculate the coo... | <p>The easiest then would be to choose a "goalpost" date, and create a feature time_elapsed for "The number of days since goalpost" and then you can easily do LS on that variable.</p>
<pre><code>goalpost = datetime.datetime(2021, 8, 31)
df["time_elapsed"] = (df.index - goalpost).dt.days
<... | python|numpy|linear-regression | 2 |
367,942 | 69,899,602 | Linear decay as learning rate scheduler (pytorch) | <p>I have read about <a href="https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.LinearLR.html" rel="nofollow noreferrer">LinearLR</a> and ConstantLR in the Pytorch docs but I can't figure out, how to get a linear decay of my learning rate. Say I have <code>epochs = 10</code> and <code>lr=0.1</code> the... | <p>The two constraints you have are: <code>lr(step=0)=0.1</code> and <code>lr(step=10)=0</code>. So naturally, <code>lr(step) = -0.1*step/10 + 0.1 = 0.1*(1 - step/10)</code>.</p>
<p>This is known as the polynomial learning rate scheduler. Its general form is:</p>
<pre><code>def polynomial(base_lr, iter, max_iter, power... | pytorch | 2 |
367,943 | 69,902,065 | pandas groupby and find most frequent value (mode) | <p>I have a datframe that looks like this</p>
<pre><code>user_id product_id created_at
1 100 2019-04-21 20:20:00
1 100 2019-04-23 00:10:00
1 200 2019-05-24 10:00:00
1 200 2020-06-24 10:10:24
2 100 2019-01-22 21:10:00
2 200 2019-04-25 2... | <p>You can calculate both <code>count</code> and <code>max</code> on dates, then sort on these values and drop duplicates (or use groupby().head()):</p>
<pre><code>s = df.groupby(['user_id','product_id'])['created_at'].agg(['count','max'])
s.sort_values(['count','max'], ascending=False).groupby('user_id').head(1)
</cod... | python|python-3.x|pandas|dataframe|numpy | 2 |
367,944 | 69,945,865 | Plotting contour lines between a certain range with an accuracy of contour lines to a certain decimal points | <p>I want to plot contour lines with an accuracy of seven to eight decimal points. I have used <code>ax.clabel(contour, inline= True, inline_spacing = -1,fmt = '%1.7f',fontsize=8)</code> to get 7 decimal points.
I am getting this kind of contour lines:
<a href="https://i.stack.imgur.com/oB0TW.png" rel="nofollow norefer... | <p>The simplest way will be to just set the <code>levels</code> keyword argument of <code>contour</code>:</p>
<pre><code>contour = plt.contour(X,Y,mod_G, levels = [0.99999999, 0.999999995, 1.0, 1.000000005, 1.00000001])
</code></pre>
<p>or whatever exact levels you want (note that every contour line drawn will have to ... | python|numpy|matplotlib|contour | 0 |
367,945 | 69,789,483 | How to get a value/row from pandas read_csv | <p>I am using a CSV file with news about crypto. My goal is to practice string manipulation and methods. The CSV looks something like this :</p>
<pre><code>publishdate headlinetext
20130504 COnSTELlATIon DaG iS nOW liStEd On kucoiN eXC?haNGE
20130511 ItA*lys cRypTOCUrREnCy BITgrAil suspeNds OpERatIOnS
20130511 ... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc()</code></a>, as in the example below, to extract the string related to the second row:</p>
<pre><code>news_headlines.iloc[1, 1]
</code></pre> | python|pandas | 1 |
367,946 | 69,752,807 | Differentiable affine transformation on patches of images in pytorch | <p>I have a tensor of object bounding boxes, e.g. with the shape of [10,4] which correspond to a batch of images e.g. with shape [2,3,64,64] and transformation matrices for each object with shape [10,6] and a vector that defines which object index belongs to which image.
I would like to apply the affine transformations... | <p>There are a few ways to perform differentiable crops in PyTorch.</p>
<p>Let's take a minimal example in 2D:</p>
<pre><code>>>> x1, y1, x2, y2 = torch.randint(0, 9, (4,))
(tensor(7), tensor(3), tensor(5), tensor(6))
>>> x = torch.randint(0, 100, (9,9), dtype=float, requires_grad=True)
tensor([[18.,... | python|pytorch|affinetransform | 1 |
367,947 | 69,822,571 | how to change data frame row to next row in pandas | <p>I am a noob python user and my purpose is got name and shift to next row</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({"1": ['Alfred', 'car', 'bike','Alex','car'],
"2": [np.nan, 'Ford', 'Giant',np.nan,'Toyota'],
"3": [pd.N... | <p>Idea is forward filling missing values by <code>Mark</code> column to <code>Name</code> column and then filter rows in same mask:</p>
<pre><code>df.columns = ["Transportation", "Mark", "BuyDate"]
m = df["Mark"].notna()
df["Name"] = df["transportation"].mask... | python-3.x|pandas | 2 |
367,948 | 69,826,600 | LSTM with multiple input features and multiple outputs | <p>Given 30 timestamps with each having 3 features, I want to predict one single output containing 4 different quantities.</p>
<p>I have an X_train and y_train of shape <code>(72600, 30, 3)</code> and <code>(72600, 4)</code> respectively.</p>
<p>where for X_train,</p>
<ul>
<li>72600 represents the number of samples</li... | <p>In your last <code>LSTM</code> layer, you will have to set the <code>return_sequences</code> parameter to <code>False</code> in order to get an 1D output:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(units = 50, return_seque... | python|tensorflow|keras|deep-learning|lstm | 3 |
367,949 | 69,687,794 | Unable to (manually) load cifar10 dataset | <p>First, I tried to load using:</p>
<pre><code>(X_train, y_train), (X_test, y_test) = datasets.cifar10.load_data()
</code></pre>
<p>But it gave an error:</p>
<pre><code>Exception: URL fetch failure on https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz: None -- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify f... | <p>I was having a similar CERTIFICATE_VERIFY_FAILED error downloading CIFAR-10. Putting this in my python file worked:</p>
<pre><code>import ssl
ssl._create_default_https_context = ssl._create_unverified_context
</code></pre>
<p>Reference: <a href="https://programmerah.com/python-error-certificate-verify-failed-certifi... | python|tensorflow|keras | 35 |
367,950 | 69,960,528 | How to create a dataset array of images? | <p>I'm was messing around with tensorflow, and I has made an image classifier on the mnist dataset. Now I'm trying to recreate that, but with my own dataset, but i'm having trouble just creating the array I want. For example-</p>
<pre><code>(X_train, y_train),(X_test, y_test)= mnist.load_data()
print(X_train.shape)
</c... | <p>This is what you should do</p>
<pre><code>import numpy as np, random
import matplotlib.image as plt
X_train=[]
print("Preparing the dataset...")
for i in range(100):
img=plt.imread(f"img/{random.randint(1,2)}.png")
X_train.append( img)
X_train = np.array(X_train)
print("Done..."... | python|arrays|tensorflow | 0 |
367,951 | 69,686,842 | How to iterate chosen operation through different csv files and output the result to new csv files | <p>I'm attempting to use the pandas and os to take CSV files from a chosen directory and delete specified rows iteratively, as they are produced in a form that I don't like. Following the iteration, I'd like the CSVs to be output with the same name+a suffix to indicate that the iteration has been performed.</p>
<p>I am... | <p>It is probably an error concerning the relative path of your files.</p>
<p>I presume your folder <code>Dummy/</code> is on the python projects path.
If the folder is found correctly, the correct relative path for any file inside of the folder should be <code>Dummy/filename</code>.</p>
<p>You can use <code>os.path.jo... | python|pandas|csv|for-loop | 1 |
367,952 | 69,948,496 | python: test for existence of any of multiple strings in a text field to set new column value | <p>have been trying for a good while now and cannot find an answer online, so... I'm sure someone can help.</p>
<p>I have a dataframe with a column that contains descriptive text, e.g.<br />
<code>"BALANCE SHRINKER - CORE"</code><br />
Each row has a different text value.</p>
<p>I need to check for the existe... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> to check if each row of 'textcolumn' contains any of the words, producing a boolean Series. Then use <a href="https://pandas.pydata.org/docs/reference/api/pandas... | python|python-3.x|pandas|dataframe | 2 |
367,953 | 69,694,005 | How to find a fixed interval of dates between several months in Pandas? | <p>I want to find a select set of dates between several months of several years, for example I want all the dates between (15/01/2018 to 14/02/2018) and (15/02/2018 to 14/03/2018) and so on until (15/11/2020 to 14/12/2020).</p>
<p>My data looks like</p>
<pre class="lang-py prettyprint-override"><code>
Date State... | <p>I'm not sure what your desired output is, but let's assume you're trying to do a grouby on the said custom date ranges. This can be done with combining <a href="https://pandas.pydata.org/docs/reference/api/pandas.cut.html" rel="nofollow noreferrer">cutting</a> the dataframe on the desired dates with <a href="https:/... | python|pandas|date | 0 |
367,954 | 69,716,379 | Combine lists from several columns into one nested list pandas | <p>Here is my dataframe:</p>
<pre><code>| col1 | col2 | col3 |
----------------------------------
[1,2,3,4] | [1,2,3,4] | [1,2,3,4]
</code></pre>
<p>I also have this function:</p>
<pre><code>def joiner(col1,col2,col3):
snip = []
snip.append(col1)
snip.append(col2)
snip.append(col3)
retu... | <p>Just <code>.apply</code> list on <code>axis=1</code>, it'll create lists for each rows</p>
<pre class="lang-py prettyprint-override"><code>>>> df['col4'] = df.apply(list, axis=1)
</code></pre>
<p><strong>OUTPUT:</strong></p>
<pre class="lang-py prettyprint-override"><code> col1 col2 ... | python|pandas | 4 |
367,955 | 69,742,811 | Loop over files | <p>I have a series of files named <code>file_0001.csv</code>, <code>file_0002.csv</code>, ... <code>file_1000.csv</code> etc. I need to read them iteratively by creating a list of the filenames and as</p>
<pre><code>import numpy as np
import pandas as pd
for fileName in files:
data = pd.read_csv("folder"... | <p>if you are trying to create the specific file names, you can loop over from 1 to 1000 and create filenames</p>
<pre><code>import numpy as np
import pandas as pd
for i in range(1,1001):
num = str(i)
filename = "file_" + num.zfill(4) + ".csv"
#data = pd.read_csv("folder" + f... | python-3.x|pandas|operating-system | 0 |
367,956 | 69,887,927 | create new column based on other columns | <p>I have this dataframe</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Found':['A','A','A','A','A','B','B','B'],
'Date':['14/10/2021','19/10/2021','29/10/2021','30/09/2021','20/09/2021','20/10/2021','29/10/2021','15/10/2021'],
'LastDayMonth':['29/10/2021','29/10/2021','29/10/2021... | <p>IIUC, for each <code>Found</code>, you check which is the <code>Mark</code> value at the last day of the month and you assign that value to <code>Mark_LastDayMonth</code>.</p>
<p>You can proceed the following:</p>
<pre><code># 1. Select last days
mark_last_day = df.loc[df.apply(lambda x: x['Date']==x['LastDayMonth']... | python|pandas|dataframe | 1 |
367,957 | 69,879,347 | Pandas cuts off empty columns from csv file | <p>I have the csv file that have columns with no content just headers. And I want them to be included to resulting DataFrame but pandas cuts them off by default. Is there any way to solve this by using read_csv not read_excell?</p> | <p>IIUC, you need <code>header=None</code>:</p>
<pre><code>from io import StringIO
import pandas as pd
data = """
not_header_1,not_header_2
"""
df = pd.read_csv(StringIO(data), sep=',')
print(df)
</code></pre>
<p><code>OUTPUT:</code></p>
<pre><code>Empty DataFrame
Columns: [not_header_1, ... | python|pandas|csv | 1 |
367,958 | 69,913,244 | how to loop through and match two date columns and extract the associated codes to a new list | <p>I have a pandas df with a code col and a date col (type: object) with 289k entries. each date have multiple codes, thus fx 10 rows with the same date and different codes in the next col and then 20 rows with a new date with new codes etc.. I also have an ndarray containing dates (type: str) with 103 entries. I want ... | <p>The rule is to avoid as much as possible any Python level loop on a dataframe.</p>
<p>But let us first look at your current codes:</p>
<pre><code>filtered_codes = []
for j in raw_data.Dates:
for q in reb_dates:
if j == q:
filtered_codes.append(raw_data.codes) # Oops !!
</code></pre>
<p>You ap... | python|pandas|numpy | 0 |
367,959 | 69,742,751 | python pandas dataframe set one column as key and rows as value | <p>I have a pandas dataframe and i wanted to convert into dictionary.</p>
<pre><code>email,account_no,cust_id
xyz,123,456
abc,789,654
nbc,345,907
</code></pre>
<p>From the df i wanted the email to be as key and other two column as value. Needed output like</p>
<pre><code>{xyz:[123,456],
abc:[789,654],
nbc:[345,907]}
</... | <p>Try:</p>
<pre><code>df.set_index('email').T.to_dict('list')
# output
{'xyz': [123, 456], 'abc': [789, 654], 'nbc': [345, 907]}
</code></pre> | python|pandas|dataframe | 4 |
367,960 | 69,800,728 | How to add a items from a list to a dataframe column in Python Pandas? | <p>I have list containing numbers <code>x =(1,2,3,4,5,6,7,8)</code>
I also have a <strong>DataFrame</strong> with 1000+ rows.
The thing I need is to assign the numbers in the list into a column/creating a new column, so that the rows 1-8 contain the numbers 1-8, but after that it starts again, so row 9 should contain n... | <p>Here are two possible ways (example here with 3 items to repeat):</p>
<h4>with numpy.tile</h4>
<pre><code>df = pd.DataFrame({'col': range(10)})
x = (1,2,3)
df['newcol'] = np.tile(x, len(df)//len(x)+1)[:len(df)]
</code></pre>
<h4>with <code>itertools</code></h4>
<pre><code>from itertools import cycle, islice
df = pd... | python|pandas|list | 1 |
367,961 | 69,854,112 | How to unpivot pandas dataframe | <p>I have a Pandas dataframe which looks as follows:
Starting Table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Kode</th>
<th>Country</th>
<th>Procedure</th>
<th>male</th>
<th>male</th>
<th>female</th>
<th>female</th>
</tr>
</thead>
<tbody>
<tr>
<td>Kode</td>
<td>Country</td>
<td>Proce... | <p>You'll likely want to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer">go with <code>melt</code></a> which is sort of the <em>opposite</em> of pivot.</p>
<ul>
<li>We specify the identifer variables: the first three columns</li>
<li>The rest of the column... | python|pandas|dataframe|pivot | 3 |
367,962 | 70,019,547 | Pandas dataframe conditional statement didn't give me what i expected | <p>I have a dataframe like this</p>
<pre><code>import numpy as np
import pandas as pd
lbl = [0, 1, 2, 3]
lbl2 = [0, 1, 2, 3, 4, 5]
label = lbl + lbl2
df = pd.DataFrame({"label":label})
#matching lbl and lbl2
pairs =[]
for i in range(3):
pair = (i,i+1)
pairs.append(pair)
</code></pre>
<p>when I hit... | <p>We get the expected result using this writing (setting up <code>num_old_lbl</code> to 3) :</p>
<pre class="lang-py prettyprint-override"><code>>>> (df.index > (num_old_lbl - 1)) & (df['label'] == pairs[1][1])
0 False
1 False
2 False
3 False
4 False
5 False
6 True
7 False
8 ... | python|pandas|conditional-statements | 1 |
367,963 | 69,781,501 | using list of word in function pandas extract | <p>I have list of word to search in dataframe with regex. I try to another way to use function extract without writing all the list in braket. Any idea plz?</p>
<pre><code>df["description"].str.extract("(SECTION.?\dRADÔME|PROFONDEUR ET TAB|PRINCIPAL GAUCHE|PRINCIPAL DROIT|PLAN FIXE VERTICAL|PLAN FIXE HOR... | <p>Use a list of words and create a pattern to use with extract:</p>
<pre><code>words = [r'SECTION.?\dRADÔME',
'PROFONDEUR ET TAB',
'PRINCIPAL GAUCHE',
'PRINCIPAL DROIT',
'PLAN FIXE VERTICAL',
'PLAN FIXE HORIZONTAL',
'MOTEUR',
'KARMAN',
'HÉLICE',
'... | python|pandas|string|list | 2 |
367,964 | 70,010,236 | Force notebook to not display dataframe when changing it | <p>I am creating a Jupyter notebook that i want to be more readable.
When changing the dataframes, they are automatically displayed in the notebook.
For instance:</p>
<pre><code>df.drop(['street','address','district'], axis = 1)
</code></pre>
<p>Displays the whole dataframe after the change. Is it possible to avoid thi... | <p>The syntax you used is "Calling" the DataFrame.
Instead, you should assign the value, <strong>try something like:</strong></p>
<pre><code>df = df.drop(['street','address','district'], axis = 1)
</code></pre> | python|pandas|dataframe|jupyter-notebook|jupyter | 2 |
367,965 | 69,812,283 | How can I compare two lists and m python. - Capture the different value | <p>I am trying to compare two lists in python, one of them is a response from a rest request that I stored in a list and the other is obtained through a csv file.
I need to compare them and capture the values that do not exist in the first list that is obtained from the csv that is smaller than the second list that is ... | <p>If you have numpy installed, you can also use the <a href="https://numpy.org/doc/stable/reference/generated/numpy.setdiff1d.html" rel="nofollow noreferrer">setdiff1d</a> function, which returns the unique values in the first 1D numpy array that are not in the second array.</p>
<pre class="lang-py prettyprint-overrid... | python|pandas|list|csv | 1 |
367,966 | 69,860,567 | How to Read CSV from url in pandas? - error tokenizing data | <p>How can I download this following file in python? I have no issue doing this in R. I believe this issue is the last row in the file which will change. How can I change the code to work?</p>
<pre><code>import pandas as pd
url = "https://ark-funds.com/wp-content/uploads/funds-etf-csv/ARK_INNOVATION_ETF_ARKK_HOLD... | <p>You should better download the csv file first by using the <a href="https://docs.python-requests.org/en/latest/user/quickstart/" rel="nofollow noreferrer">requests module</a>.
Then you can read the file from the download directory by passing the file path instead of the URL (<em>pd.read_csv(download_path)</em>).</p> | python|pandas | 0 |
367,967 | 69,731,131 | Calculate sum of donation money based on value in other column in pandas | <p>I'm trying to calculate the monetary sum of campaign contribution data from the real estate industry.</p>
<pre><code>realestate_counter = 0
realestate_donations = 0
for row in range(df.shape[0]): #for each row in the dataframe
if 'realestate' in df.iloc[row]['Occupation']:
realestate_donations = realesta... | <p>This is a slimmed down example but should get you what you want</p>
<pre><code>df = pd.DataFrame({'occupation':['real estate','real estate','real estate','banker','baker'], 'donation':range(11,16)})
occupation donation
0 real estate 11
1 real estate 12
2 real estate 13
3 banker ... | python|pandas|dataframe|data-cleaning | 2 |
367,968 | 69,986,870 | pandas datetime doesn't convert the dates properly in python | <p>i have a dataframe data</p>
<pre><code>d=pd.DataFrame({"dat":["01-06-68", "01-06-57","14-02-80","01-01-04","07-11-20"],
"j":[34,2,1,7,8]})
</code></pre>
<p>i want to convert the dat column to "YYYY-MM-DD" format which is ... | <p>Solution with replace in callable for test last digits and then use <code>%Y</code> for match years in YYYY format:</p>
<pre><code>f = lambda x: '19' + x.group() if int(x.group()) > 22 else '20' + x.group()
d.dat = d.dat.str.replace('(\d+)$', f, regex=True)
d.dat = pd.to_datetime(d.dat, format='%d-%m-%Y')
print ... | python|pandas | 4 |
367,969 | 69,872,668 | Why I can pass an array as input to a lambda function that uses numpy but I cant pass it to a lambda function without numpy? | <p>Starting from these two lambda functions</p>
<pre><code>import numpy as np
relu = (lambda x: np.maximum(0, x),
lambda x: 1 if x > 0 else 0)
</code></pre>
<p>Obviously the two functions work correctly when I pass a single number, but when I pass an array/list relu[0] works but not relu[1].</p>
<pre><code>... | <p>You can, if you make sure <code>x</code> is an array using <code>np.asarray()</code> an then use <code>np.where()</code>:</p>
<pre><code>relu = (
lambda x: np.maximum(0, np.asarray(x)),
lambda x: np.where(np.asarray(x) > 0, 1, 0),
)
relu[0]([-1, 0, 1, 2])
# array([0, 0, 1, 2])
relu[1]([-1, 0, 1, 2])
# arr... | python|arrays|function|numpy|lambda | 0 |
367,970 | 69,700,518 | Fill empty numpy array inside for loop | <p>I have a 2-D numpy array X with shape (100, 4). I want to find the sum of each row of that
array and store it inside a new numpy array x_new with shape (100,0). What I've done so far
doesn't work. Any suggestions ?. Below is my approach.</p>
<pre><code>x_new = np.empty([100,0])
for i in range(len(X)):
array = np... | <p>Using the <code>sum</code> method on a 2d array:</p>
<pre><code>In [8]: x = np.arange(12).reshape(3,4)
In [9]: x
Out[9]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [10]: x.sum(axis=1)
Out[10]: array([ 6, 22, 38])
In [12]: x.sum(axis=1, keepdims=True)
Out[12]:
array([[ 6],
... | python|arrays|numpy | 1 |
367,971 | 69,902,692 | Exporting Table from a pdf file | <p>I need to export the table from the pdf and select the particular columns.
I have managed to export by the "tabulate","tabula", however it is not exporting in the proper format. In the original file, there are 5 columns, but after exporting I get 3 columns totally because first three columns are ... | <p>Try this:</p>
<pre><code>dfs = read_pdf(file, pages="all", pandas_options={'header':None})
</code></pre> | python|pandas|dataframe|tabulate | 0 |
367,972 | 69,885,515 | How to expand and create the following dataset in Pandas | <p>I have a dataset that looks like this:</p>
<p><a href="https://i.stack.imgur.com/oN2sn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oN2sn.png" alt="enter image description here" /></a></p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({
'weekstart':['01-Jan-18','08-Jan-1... | <ol>
<li>Convert to datetime</li>
<li>Use <code>pd.date_range</code> to create a column of all dates between "weekstart" and "weekend"</li>
<li>Use <code>explode</code> to split into individual rows.</li>
</ol>
<pre><code>df["weekstart"] = pd.to_datetime(df["weekstart"])
df["... | python|pandas|explode|expand | 1 |
367,973 | 43,127,029 | Mask based on two different Pandas Dataframes? | <p>Suppose I have two pandas dataframes:</p>
<pre><code>In [1]: dates = pd.date_range('20170101',periods=6)
df1 = pd.DataFrame(np.empty([len(dates),2]),index=dates,columns=['foo','bar'])
df1['foo'].loc[0:2] = 'A'
df1['bar'].loc[0:3] = 'A'
df1['foo'].loc[2:6] = 'B'
df1['bar'].loc[3:6] = 'B'
df2 = pd.DataFrame(np.random... | <p>One option is to concatenate the two data frames and assign a key to each one, transform the resulting data frame to long format, and then calculate the max grouped by the key and the column names:</p>
<pre><code>(pd.concat([df1, df2], keys=["one", "two"], axis=1)
.stack(level=1).groupby(level=1)
.apply(lambda g:... | python|pandas|dataframe|group-by|mask | 2 |
367,974 | 43,106,535 | Create column of truth values | <p>I have a data frame which looks like this:</p>
<pre><code> date people_count
0 30/03/17 6
1 31/03/17 4
2 1/04/17 7
3 2/04/17 9
</code></pre>
<p>How can you create a new column which indicates if the date is a weekend(<strong>1</strong>), or if the date is a weekday(<strong>0</strong>)?</p>... | <p>First, you may have to specify the date format -- I get</p>
<pre><code>In [31]: pd.DatetimeIndex(df['date'])
Out[31]: DatetimeIndex(['2017-03-30', '2017-03-31', '2017-01-04', '2017-02-04'], dtype='datetime64[ns]', name='date', freq=None)
</code></pre>
<p>from your input and I don't think that's what you wanted. O... | python|pandas|numpy | 2 |
367,975 | 43,076,540 | Replace values in subarray based upon dynamic condition in Numpy | <p>I have a Python Numpy array that is a 2D array where the second dimension is a subarray of 3 elements of integers. For example:</p>
<pre><code>[ [2, 3, 4], [9, 8, 7], ... [15, 14, 16] ]
</code></pre>
<p>For each subarray I want to replace the lowest number with a 1 and all other numbers with a 0. So the desired ou... | <p>You can specify the <code>axis</code> parameter to calculate a 2d array of <em>mins</em>(if you keep the dimension of the result), then when you do <code>a == a.minbyrow</code>, you will get trues at the minimum position for each sub array:</p>
<pre><code>(a == a.min(1, keepdims=True)).astype(int)
#array([[1, 0, 0]... | python|arrays|numpy | 1 |
367,976 | 43,194,242 | How to launch Bitfusion Ubuntu 14 TensorFlow AMI on AWS? | <p>I just subscribed to the <a href="https://aws.amazon.com/marketplace/pp/B01EYKBEQ0?qid=1491252672217&sr=0-1&ref_=srh_res_product_title" rel="nofollow noreferrer">Bitfusion Ubuntu 14 TensorFlow</a> with a g2.2xlarge EC2 instance type. I got the confirmation email that I am subscribed, and I can see it listed ... | <p>Answering my own question.</p>
<p>It turns out that by default, a private account has a limit of 0 for g2.2xlarge instances. I put in a request to increase my limit to 1, and within 6 hours my request was granted. Now when I went through the same process to launch the AMI it actually shows up in my instances.</p>
... | amazon-web-services|tensorflow|amazon-ami | 1 |
367,977 | 43,150,107 | Faster way to build text file in python | <p>I have two 3d numpy arrays, call them a and b, 512x512x512. I need to write them to a text file:</p>
<pre><code>a1 b1
a2 b2
a3 b3
...
</code></pre>
<p>This can be accomplished with a triple loop:</p>
<pre><code>lines = []
for x in range(nx):
for y in range(ny):
for z in range(nz):
lines.ap... | <p>You could use <code>np.stack</code> and reshape the array to (-1, 2) (two columns) array, then use <code>np.savetxt</code>:</p>
<pre><code>a = np.arange(8).reshape(2,2,2)
b = np.arange(8, 16).reshape(2,2,2)
np.stack([a, b], axis=-1).reshape(-1, 2)
#array([[ 0, 8],
# [ 1, 9],
# [ 2, 10],
# [ 3,... | python|numpy | 4 |
367,978 | 43,442,450 | Pandas: Count Distinct Combinations of two columns and add to Same Dataframe | <p>Need help in adding the unique combination of two columns to the same dataframe in pandas.
I want that "nos" column.</p>
<pre><code>Input:
id acct_nos name
1 1a one
1 1a two
2 2b three
3 3a four
3 3b five
3 3c six
3 3d seven
</code></pre>
<p>Here is the outp... | <p>You can use <code>groupby.transform</code> with <code>nunique()</code> function to count the number of unique elements per <em>id</em>:</p>
<pre><code>df['nos'] = df.groupby("id")['acct_nos'].transform("nunique")
df
</code></pre>
<p><a href="https://i.stack.imgur.com/be9ri.png" rel="noreferrer"><img src="https://i... | python|pandas|count|size|aggregation | 10 |
367,979 | 43,439,453 | Using multiple GPU for one dataset at once instead of splitting dataset in tensorflow | <p>I know when training DNN, usual way to use multiple GPU is to split dataset and assign each divided dataset to each GPU.</p>
<p>However, is there a way to use multiple GPU for faster calculation for undivided, whole dataset? I mean when GPU is used for training network, matrix multiplications are parallelized insid... | <p>You're trying to do something like <a href="https://static.googleusercontent.com/media/research.google.com/zh-CN//archive/large_deep_networks_nips2012.pdf" rel="nofollow noreferrer">model parallelism</a>. It's a little hacky to do that in tensorflow. </p>
<p>One way to parallelize matmul with two GPU cards. <code>A... | parallel-processing|tensorflow|deep-learning|gpu | 0 |
367,980 | 43,043,271 | ROC curve for binary classification in python | <p>I am tying to plot an ROC curve for Binary classification using <code>RandomForestClassifier</code> </p>
<p>I have two numpy arrays one contains predicted values and one contains true values as follows:</p>
<pre><code>In [84]: test
Out[84]: array([0, 1, 0, ..., 0, 1, 0])
In [85]: pred
Out[85]: array([0, 1, 0, ...... | <p>You need probabilities to create ROC curve.</p>
<pre><code>In [84]: test
Out[84]: array([0, 1, 0, ..., 0, 1, 0])
In [85]: pred
Out[85]: array([0.1, 1, 0.3, ..., 0.6, 0.85, 0.2])
</code></pre>
<p>Example code from scikit-learn examples:</p>
<pre><code>import matplotlib.pyplot as plt
from sklearn.metrics import ro... | numpy|machine-learning|scikit-learn|ipython | 14 |
367,981 | 43,164,417 | Using a numpy array of length less than pandas dataframe to fill in pandas dataframe | <pre><code>df = pd.DataFrame(index=pd.date_range('2017-01-01', '2017-01-10', freq='D'), columns=['test'])
vals = np.array([1.0, 2.0])
df['test'] = vals
</code></pre>
<p>I get this error:
ValueError: Length of values does not match length of index</p>
<p>Any way I can fix it? This error is arising because lenght of ... | <p>You can assign to just the first rows like this:</p>
<pre><code>df['test'][:len(vals)] = vals
</code></pre> | python|pandas|numpy | 2 |
367,982 | 43,262,397 | Python Pandas DataFrame JSON converter in List Error | <p>I have a DataFrame where in some columns I have Json data, like this</p>
<pre><code> A Ferry_values
Ferry {"0": 3.4796488185359, "1": 0, "2": 0, "3": 4.4588689023021,
"4":0, "5":0,"6": 2.3752536905642, "7": 3.7376712853646, "8": 0}
</code></pre>
<p>Using in Python:</p>
<p... | <p>Ok, the problem is that the </p>
<pre><code> json.loads
</code></pre>
<p>doesn't return list as ordered in Json data.</p>
<p>The correct script is:</p>
<pre><code> import json
from collections import OrderedDict
string = '{"1": 3.4796488185359, "2": 0, "3": 0, "4": 4.4588689023021, "5":
0, "6"... | python|json|list|pandas|dataframe | 1 |
367,983 | 43,355,877 | ValueError: List argument 'values' to 'ConcatV2' Op with length 0 shorter than minimum length 2 | <p>I am fairly new to TF and started to learn it with TF tutorials.
I have just simply copied the Swivel model from TF site, and try to run it but,
I am getting an error message:<br>
<i>Traceback (most recent call last):</p>
<p>File "C:\Users\jhan\Desktop\tensorflow prac\swivel\swivel.py", line 362, in
tf.app.run... | <p>I can't quite tell where the bug is but:</p>
<p>Have a look around the code the error is saying that <code>l2_losses</code> is empty. drop a <code>print</code> statement just before this line, to check the value of l2_losses:</p>
<pre><code>print(l2_losses) # new print statement
l2_loss = tf.reduce_mean(tf.concat(... | tensorflow | 1 |
367,984 | 43,268,403 | What's difference between concatenated and sequential models in keras? | <p>I tried to solve XOR task with different approaches. The first one with using of sequential model:</p>
<pre><code>result = Sequential()
result.add(Dense(2, input_shape=(2,), activation='sigmoid'))
result.add(Dense(1, input_shape=(2,), activation='sigmoid'))
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
resul... | <p>the second model is more complex than the first model, maybe you should train for more steps.</p>
<p>here is my code, the acc is simple_acc: 0.7923, complex_acc: 0.7244. you can fine-tune it yourself.</p>
<pre><code>#coding: utf-8
import numpy as np
from keras.layers import Input,Dense,merge
from keras.models impo... | tensorflow|keras | 1 |
367,985 | 43,115,442 | Mean of timedeltas when resampling in pandas | <p>Given this dataframe:</p>
<pre><code>df = pd.DataFrame(pd.to_timedelta(['00:00:02','00:00:05','00:00:10','00:00:15','00:00:05']))
df.index = pd.to_datetime(['20/02/2017 12:42:10','20/02/2017 12:43:10','20/02/2017 12:45:10','20/02/2017 12:45:10','20/02/2017 12:45:10'])
df.columns = ['time']
df
Out[232]:
... | <p>You can first convert timedeltas to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.total_seconds.html" rel="nofollow noreferrer"><code>total_seconds</code></a> (floats), <code>resample</code> and use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.... | python|pandas | 1 |
367,986 | 43,293,061 | Getting error 'Too Many Values To Unpack' while looping over tensors; unable to use tf.train.batch | <p>When I initialize my Neural Net:</p>
<pre><code>print('Checking the Training on a Single Batch...')
with tf.Session() as sess:
# Initializing the variables
sess.run(tf.global_variables_initializer())
# Training cycle
for epoch in range(epochs):
batch_i = 1
for batch_features, batch_... | <p><code>ValueError:</code> caused by statement</p>
<pre><code>for batch_features, batch_labels in (input_data, input_labels):
</code></pre>
<p>you needs </p>
<pre><code>for batch_features, batch_labels in zip(input_data, input_labels):
</code></pre>
<p>instead. <code>(input_data, input_labels)</code> results in tu... | python|image-processing|tensorflow|neural-network | 1 |
367,987 | 43,324,829 | Tensorflow - Restoring model fail with message " Attempting to use uninitialized value" | <p>I am really new to the TensorFlow so bear with me plz even if this question is a total nonsense...</p>
<p>I have a code which</p>
<p>1) defines the network like</p>
<pre><code>x = tf.placeholder(tf.float32, shape=[None, 784], name='input')
y_ = tf.placeholder(tf.float32, shape=[None, 10], name='reference')
...
fc... | <p>I think what might help is <strong><em>not</em></strong> running <code>tf.train.import_meta_graph()</code>.
The import from <code>.meta</code> file will create a new graph as specified in the file, which you do not need as you just built your own graph.</p>
<p>Just say:</p>
<pre><code>saver = tf.train.Saver()
wit... | model|tensorflow|restore|checkpoint | 0 |
367,988 | 43,084,260 | elements of list in row | <p>i have few polygons and distance of some points from those polygons. i tried to write in a csv by pandas where distance between each point and polygon will come in separate rows. i got this: </p>
<pre><code>poly total inside outside dist
1000 2 0 2 [16015,5678]
1100 1 0 1 [5267]
</code... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>str.len</code></a> for get length of <code>lists</code> which are repeated by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferre... | python|csv|pandas | 1 |
367,989 | 43,258,854 | count all possible 2-grams in each row | <p>Let's say I have a csv file like this (in reality I have more than a 100+ different services possible) : </p>
<pre><code>user_id, services
user_1, "s1,s2,s1,s4,s2,s3,s2"
user_2, "s2,s3,s2,s1,s4"
</code></pre>
<p>and I would like to have eventually this, mostly using python and pandas if possible : </p>
<pre><code... | <p>Recreating your data (but having split the service column in different columns)</p>
<pre><code>import pandas as pd
df = pd.DataFrame()
df['user_id'] = [1,2]
df['s1'] = [0, 1]
df['s2'] = [1, 1]
df['s3'] = [1,0]
</code></pre>
<p>Then we can combine:</p>
<pre><code>cols = list(df)[1:]
for c1, c2 in itertools.permuta... | python|csv|pandas|n-gram | 1 |
367,990 | 43,038,142 | Min, Max, Mean Duration Time csv | <p>I'm trying to subtract two columns in a CSV to create a 3rd column "Duration"
<strong>End-Time</strong> - <strong>Start_time</strong></p>
<p>Each row corresponds to a User Id as well.</p>
<p>I can create a csv file with just the Duration column but i rather redirect it back to the original csv.</p>
<p>The format ... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer"><code>to_csv</code></a> for write file to <code>csv</code>:</p>
<pre><code>df = pd.read_csv("start_stop_sessions.csv", parse_dates=['time_x','time_y'])
df['Duration'] = df['time_y... | python|csv|pandas|time | 2 |
367,991 | 43,418,578 | Using numpy.min to get minimum value in a float64 type numpy array but got error 'numpy.float64' object cannot be interpreted as an index | <p>I was trying to get the minimum value between tr_loss and val_loss using <code>numpy.min</code>. </p>
<pre><code>np.min(np.min(tr_loss), np.min(val_loss))
</code></pre>
<p>The tr_loss and val_loss are numpy arrays that returned from <code>model.fit</code> in keras.</p>
<pre><code>'tr_loss': [0.84579472304284575, ... | <p>When comparing two elements, <a href="https://numpy.org/doc/stable/reference/generated/numpy.minimum.html" rel="nofollow noreferrer"><code>numpy.minimum</code></a> should be used instead of <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.min.html" rel="nofollow noreferrer"><code>numpy.min</co... | python|arrays|numpy | 0 |
367,992 | 43,458,281 | Using Pandas, how do I use if/then logic against two columns to fill in another column? | <p>I have a master spreadsheet with the following:</p>
<pre><code>ClientID Region Number Value
61661 AMER 38150
1212 EMEA 2012
6543 AMER 38800
3115 LA 40121
3119 AMER 1000
</code></pre>
<p>What I want to do is add a new column to answer the question "... | <p>use nested <code>np.where</code></p>
<pre><code>import numpy as np
isin = df.Region.isin(['AMER', 'LA'])
nv = df['Number Value'] > 31000
df['New Column'] = np.where(isin & nv, 'High', np.where(isin & ~nv, 'Low', ''))
print(df)
ClientID Region Number Value New Column
0 61661 AMER 381... | python|pandas | 1 |
367,993 | 43,092,454 | How to add new nodes / neurons dynamically in tensorflow | <p>If I want to add new nodes to on of my tensorflow layers on the fly, how can I do that?</p>
<p>For example if I want to change the amount of hidden nodes from 10 to 11 after the model has been training for a while. Also, assume I know what value I want the weights coming in and out of this node/neuron to be.</p>
<... | <p>Instead of creating a whole new graph you might be better off creating a graph which has initially more neurons than you need and mask it off by multiplying by a non-trainable variable which has ones and zeros. You can then change the value of this mask variable to allow effectively new neurons to act for the first ... | python|machine-learning|tensorflow|neural-network|artificial-intelligence | 5 |
367,994 | 43,274,423 | Use sklearn's FunctionTransformer with string data? | <p>I'm using sklearn's FunctionTransformer to preprocess some of my data, which are date strings such as "2015-01-01 11:09:15".</p>
<p>My customized function takes a string as input, but I found out that FunctionTransformer cannot deal with strings as in the source code it didn't implement fit_transform. Therefore, th... | <p>Seems as if the <code>validate</code> parameter is what you are looking for:
<a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.FunctionTransformer.html" rel="noreferrer">http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.FunctionTransformer.html</a></p>
<p>Here an e... | python|pandas|machine-learning|scikit-learn | 6 |
367,995 | 43,291,830 | I want to find the first quartile in which the mentioned condition is satisfied but i am facing this error | <pre><code>x=[ ]
for i,row in enumerate (df3['GDP']):
if((df3.iloc[i]<df3.iloc[i-1]) & (df3.iloc[i+1]<df3.iloc[i])):
x.append(i)
print(x)
</code></pre>
<blockquote>
<p></p>
</blockquote>
<p>It is showing this
ERROR The truth value of a Series is ambiguous. Use a.empty, a.bool()... | <p>IIUC:<br>
You want the ordinal positions of where the <code>'GDP'</code> values were greater than the last one and less then the next one.</p>
<p>Consider the dataframe <code>df3</code></p>
<pre><code>np.random.seed([3,1415])
df3 = pd.DataFrame(dict(GDP=np.random.randint(10, size=15)))
print(df3)
GDP
0 0... | python|pandas | 0 |
367,996 | 43,263,017 | Variables with dynamic shape TensorFlow | <p>I need to create a matrix in TensorFlow to store some values. The trick is the matrix has to support dynamic shape.</p>
<p>I am trying to do the same I would do in numpy: </p>
<pre><code>myVar = tf.Variable(tf.zeros((x,y), validate_shape=False)
</code></pre>
<p>where <code>x=(?)</code> and <code>y=2</code>. But t... | <p>If you know the shape out of the session, this could help.</p>
<pre><code>import tensorflow as tf
import numpy as np
v = tf.Variable([], validate_shape=False)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(v, feed_dict={v: np.zeros((3,4))}))
print(sess.run(v, fee... | python|numpy|tensorflow|tflearn | 1 |
367,997 | 43,335,125 | x axis dataframe variables not seen clearly using matplotlib | <p>Below is my dataframe:</p>
<pre><code>login_data_df_jan_weekly
Out[22]:
login_time login_counts
2010-01-03 1010
2010-01-10 2917
2010-01-17 3022
2010-01-24 2851
2010-01-31 3196
</code></pre>
<p>I am trying to plot it using <strong>matplotlib.pyplot.subplots()</strong></p>
<pre><code> import matplotlib.pyp... | <p>Is this what you are looking for?</p>
<pre><code>plt.xticks(rotation=45)
</code></pre>
<p>This basically rotates x-axis label by 45 degrees and you would be able to see them clearly.</p> | python|pandas|matplotlib | 0 |
367,998 | 72,405,529 | Pandas Profiling Import Error: cannot import name 'soft_unicode' from 'markupsafe' | <p>I have an issue with getting started with pandas profiling.</p>
<p>I tried loading pandas profiling, but upon installation this error pops up:</p>
<blockquote>
<p>ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following d... | <p>This is an unfortunate case where things break down when your package code is being used by other software as a dependency, and you cannot foresee/test all use cases.</p>
<p>This worked for me:</p>
<pre class="lang-python prettyprint-override"><code>!pip uninstall markupsafe
!pip install markupsafe==2.0.1
</code></p... | python|pandas|profiling | 1 |
367,999 | 72,470,445 | capture instances of a column value where its seen more than once | <p>I have the following data frame:</p>
<pre><code>id_1 id_2 id_3 id_4 id_5
0133 11 kelly AA-1 1
2119 22 Wade AA-2 1
3903 33 John BB-1 1
3903 33 John BB-2 1
3903 33 John BB-3 1
5133 44 Emily C-1 1 ... | <p>You can try something like:</p>
<pre><code>df.groupby('id_1').nth(1).reset_index()[['id_4','id_5']]
</code></pre>
<p>Then you can convert it to JSON.</p> | json|python-3.x|pandas|dataframe | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.