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 |
|---|---|---|---|---|---|---|
19,000 | 52,616,959 | How to change a value in a dataframe/series in python | <p>I was trying to look up the tickers for Nasdaq 100 companies and got it from wikipedia</p>
<pre><code>nasdaq100 = pd.read_html('https://de.wikipedia.org/wiki/NASDAQ-100')[4][0][1:]
print(nasdaq100)
</code></pre>
<p>Which gives me:</p>
<pre><code>1 ATVI
2 ADBE
3 ALXN
4 ... | <p>If you're looking to use the same function across a whole series, you can do that with <code>.apply</code>:</p>
<pre><code>nasdaq100.apply(lambda x: x.split(",")[0])
1 ATVI
2 ADBE
3 ALXN
4 ALGN
5 GOOG
6 AMZN
</code></pre> | python|pandas|dataframe|replace|series | 0 |
19,001 | 52,817,298 | Pandad - KeyError : Column not in index | <p>I have a pandas Dataframe that has a list of columns in a groupby function. I get an error</p>
<pre><code>KeyError : "['Type1'] not in index"
</code></pre>
<p>Given below is the code that throws the error</p>
<pre><code>temp_v1 = temp_df.groupby(level, as_index = False).sum()[[level, 'Type1', 'Type2','Type3', 'Ty... | <p>I guess problem is string column <code>Type1</code>:</p>
<pre><code>level = 'F'
temp_df = pd.DataFrame({
'Type1':list('abcdef'),
'Type2':[4,5,4,5,5,4],
'Type3':[7,8,9,4,2,3],
'Type4':[1,3,5,7,1,0],
'Type5':[5,3,6,9,2,4],
'col':[5,3,6,9,2,4],
'F':list('a... | python-3.x|pandas|pandas-groupby | 2 |
19,002 | 52,553,666 | CSV results overwrites the values | <p>I was somewhat able to write and execute the program using BeautifulSoup. My concept is to capture the details from html source by parsing multiple urls via csv file and save the output as csv.</p>
<p>Programming is executing well, but the csv overwrites the values in 1st row itself.</p>
<p>input File has three ur... | <p>Open the output file in append mode as suggested <a href="https://stackoverflow.com/questions/17530542/how-to-add-pandas-data-to-an-existing-csv-file">in this post</a> with the modification that you add header the first time:</p>
<pre><code>from os.path import isfile
if not isfile("output.csv", "w"):
df.to_csv... | python|pandas|beautifulsoup | 0 |
19,003 | 46,413,379 | Partition a column based on keywords in Pandas | <p>I have an excel file that I have read into python as a dataframe as shown. </p>
<pre><code> Store List
Ralphs bag1
apple
pear
Ralphs bag2
toilet paper
Albertsons bag3
magazines
paper
</code></pre>
<p>I am att... | <p><strong>Setup</strong></p>
<pre><code>df
Store List
0 Ralphs bag1
1 Ralphs apple
2 Ralphs pear
3 Ralphs bag2
4 Ralphs toilet paper
5 Albertsons bag3
6 Albertsons magazines
7 Albertsons paper
</code></pre>
<hr>
<p... | python|string|pandas|dataframe | 1 |
19,004 | 46,392,026 | numpy.polyfit giving error for covariance matrix | <p>This is the code:</p>
<pre><code>p=[1,2,3,4]
q=[4,5,6,7]
z,n=numpy.polyfit(p,q,1,cov=True)
</code></pre>
<p>It gives me this message:</p>
<blockquote>
<p>4 z,n=np.polyfit(p,q,1,cov=True)</p>
<p>C:\Users\Rekha\Anaconda3\lib\site-packages\numpy\lib\polynomial.py in polyfit(x, y, deg, rcond, full, w, cov)</... | <p>The error is saying precisely what the problem is: you do not have enough data point to <strong>estimate the covariance matrix</strong> (and <strong>not</strong> to perform the fit).</p>
<pre><code>import numpy as np
p = [1, 2, 3, 4]
q = [4, 5, 6, 7]
z = np.polyfit(p, q, 1, cov=False)
print(z)
</code></pre>
<p>O... | python|numpy | 0 |
19,005 | 46,404,243 | Is pyspark streaming suitable for machine learning/ scientific computing? | <p>I am new to spark and have to write a streaming application that has to perform tasks like fast fourier transformations and some machine learning stuff like classification/regression with svms etc. I want to do this in pyspark, because of python's huge variety of modules like numpy, scikit-learn etc. My question is,... | <p>Pyspark is used to run program/code/algorithm in spark, which are coded in python language.</p>
<p>For machine leaning, spake has MLlib library packages.</p>
<p>For streaming purpose, spark has Spark streaming lib packages</p>
<p>You can explore Storm as well for real time streaming.</p> | python|numpy|pyspark|spark-streaming | 0 |
19,006 | 58,226,316 | Tensorflow.js: Tensor disposed error when using tanh or sigmoid, but not relu activation function | <p>In TensorFlow.js, I created a sequential neural network with 3 dense layers that works when I set the activation function to 'relu', but when I try 'tanh' or 'sigmoid' it throws the error, "Error: Tensor is disposed". </p>
<p>I did a model summary to verify that changing the activation function didn't change the st... | <p>The issue is not related to the activation layer. Most probably that you are re-using a tensor that was already disposed in a <code>tf.tidy</code> callback.</p>
<p>Here is a simple sequential model using <code>tanh</code> and <code>sigmoid</code> activation layers</p>
<pre><code>const model = tf.sequential({
l... | tensorflow|neural-network|tensorflow.js|activation-function | 0 |
19,007 | 69,096,620 | Read CSV and create new CSV with only specified columns and subset or rows based on specific values | <p>I have a CSV file with 5 columns:</p>
<pre><code>Student Id, Course Id, Student Name, Course Name, GPA
12,112 , John,Math, 3.7
11,111 , Mohammed,Astronomy, 3.89
10,100 , Peter,Java Programming, 3.5
9,99 , Lisa,Cooking, 4.0
</code></pre>
<p>Using Python 3.8 I need to read that file and create a new CSV file with fewe... | <p>Try this:</p>
<pre><code>import pandas as pd
dta = pd.read_csv('test.csv')
# removing the white space from column names:
dta.columns = dta.columns.str.strip()
# removing the tailing white space from all records in all columns:
for col in dta.columns:
# checking if column is string:
if dta[col].dtype == o... | pandas|csv|python-import|export-to-csv|python-3.8 | 1 |
19,008 | 69,201,630 | How to select unique values of column A in each group B and get sum of values in column C for these unique values | <p>I have posts dataframe and authors dataframe</p>
<p>I need to calculate favCount of the authors of posts in each day</p>
<pre><code> posts_columns = ["postId", "authorId", "date"]
posts = [("1", "1", "2020-10-10"),
("2", "... | <p>Considering <code>df1</code> as Posts and <code>df2</code> as Authors dataframes</p>
<pre class="lang-py prettyprint-override"><code>result = df1.merge(df2, how= 'inner').drop_duplicates(subset=['date','authorId'])
final = result.groupby([result.date])['favCount'].sum()
</code></pre> | pandas|dataframe|apache-spark|pyspark|apache-spark-sql | 2 |
19,009 | 68,881,666 | Interesting Pandas dataframe problem: how to drop duplicates (inverse) over two columns - for each row with a common attribute? | <p>After filtering out the inverse duplicates, I have to count how many actual duplicates there are. Here is my (working example) code, it's too slow though, for 90 000+ rows.. using iterrows:</p>
<pre><code>import pandas as pd
data = {'id_x':[1,2,3,4,5,6],
'ADDICTOID_x':['BFO:0000023', 'MF:0000016', 'BFO:000002... | <p>Maybe there is a shorter way, but I can think of merging the <code>df</code> with its inverese self, and then leaving only the lines without a previous match. So instead of your loop do:</p>
<pre><code>dcp = dcp.merge(dcp[['id_x', 'PMID', 'ADDICTOID_x', 'ADDICTOID_y']].rename({'id_x': 'inv_id', 'ADDICTOID_x': 'inv_y... | python|pandas|dataframe|duplicates|drop | 0 |
19,010 | 68,950,551 | Understanding of .loc in Pandas to save variables in specific cell of a dataframe | <p>I don't understand the behaviour <code>.loc</code> or <code>.at</code>, when I want to save a variable in a specific cell of a dataframe. Can somebody help me to understand, please?</p>
<p>My failing working example:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
print(pd.... | <p>When you have an ndarray on the right side, Pandas will not treat it like any Python object that can be inserted into the DataFrame. Instead you run into a code path that tries to set multiple values at multiple locations from that array, hence the error message pointing out <code>when setting with an ndarray</code>... | python|arrays|pandas|dataframe|numpy | 1 |
19,011 | 68,901,243 | merge_asof in pandas on multiple columns | <p>df1</p>
<pre><code>,date,symbol,eps,epsEstimated,time,revenue,revenueEstimated,year,date_minus_1month,quarter
0,2021-07-30,JCI,0.83,0.83,bmo,6341000000.0,6256450000.0,2021,2021-06-30,Q2
1,2021-04-30,JCI,0.52,0.49,bmo,5594000000.0,5581850000.0,2021,2021-03-30,Q1
2,2021-01-29,JCI,0.43,0.4,bmo,5341000000.0,5268660000.0... | <p>Try pass to <code>by</code></p>
<pre><code>pd.merge_asof(a, b, by = 'symbol',
left_on=['date'], right_on=[ 'acceptedDate'],
direction='nearest')
</code></pre> | python|pandas|merge | 1 |
19,012 | 68,913,074 | How do I Perform an API Call for each Item in a List | <p>I'm trying to get Price data for each company in a list of tuples <code>[(company_name, symbol)]</code>. In this instance I am using the TD Ameritrade API.</p>
<p>Also, I am having the same problem with Reddit. The only difference is I am trying to retrieve all the comments for each post 'id'. But, with the Reddit c... | <p>The way you tried to extract a list of IDs is wrong, just do something like:</p>
<pre><code>IDs = df["id"].values.tolist()
</code></pre> | python|pandas|dataframe|reddit | 0 |
19,013 | 71,512,891 | Convert Category to Numerical Labels in Python/Pandas | <p>I have a data frame as below:</p>
<pre><code>df = pd.DataFrame({'Item':['A1','B1','C1','D1'],'Category':['A','A','C','B']})
df
Item Category
0 A1 A
1 B1 A
2 C1 C
3 D1 B
</code></pre>
<p>I would like to manually cluster them i.e. Category A will belong to Cluster 1, C will belong to... | <p>With <code>groupby</code>:</p>
<pre><code>df["Cluster"] = df.groupby("Category", sort=False).ngroup()+1
>>> df
Item Category Cluster
0 A1 A 1
1 B1 A 1
2 C1 C 2
3 D1 B 3
</code></pre> | python|pandas | 2 |
19,014 | 42,351,740 | Tensorflow, feeding Estimator.fit(batch) | <p>Could you provide an example of using the high-level API Estimators with placeholders and feeding batches like for a basic use:</p>
<pre><code>for step in xrange(max_steps):
batch_of_inputs,batch_of_targets= get_batch_from_disk(step)# e.g.batches are stored as list where step is and index of the list
feed_... | <p>I don't think whether estimators are really meant to be used with placeholders. They use the concept of <code>input_fn</code> which is properly described <a href="https://www.tensorflow.org/get_started/input_fn" rel="nofollow noreferrer">here</a>.</p>
<p>If you realy need to use a placeholder you might use a <a hre... | python|tensorflow|neural-network | 0 |
19,015 | 42,495,930 | Tensorflow OOM on GPU | <p>i'm training some Music Data on a LSTM-RNN in Tensorflow and encountered some Problem with GPU-Memory-Allocation which i don't understand: I encounter an OOM when there actually seems to be just about enough VRAM still available.
Some background:
I'm working on Ubuntu Gnome 16.04, using a GTX1060 6GB, Intel Xeon E... | <p>I resolve this issue by reducing <code>batch_size=52</code>
Only to reduce memory use is to reduce batch_size. </p>
<blockquote>
<p>Batch_size depends on your gpu graphics card, size of VRAM, Cache memory etc.</p>
</blockquote>
<p>Please prefer this <a href="https://stackoverflow.com/questions/39076388/tensorflo... | tensorflow|out-of-memory|gpu|vram | 9 |
19,016 | 43,222,878 | iterate over pandas dataframe and update the value - AttributeError: can't set attribute | <p>I am trying to iterate over a pandas dataframe and update the value if condition is met but i am getting an error.</p>
<pre><code>for line, row in enumerate(df.itertuples(), 1):
if row.Qty:
if row.Qty == 1 and row.Price == 10:
row.Buy = 1
AttributeError: can't set attribute
</code></pre> | <p>First iterating in pandas is possible, but very slow, so another vectorized solution are used.</p>
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iterrows.html" rel="noreferrer"><code>iterrows</code></a> if you need iterating:</p>
<pre><code>for idx, row in d... | python|pandas|dataframe | 53 |
19,017 | 72,386,538 | What is the Regex expression for substituting every second occurrence of a word in a string? | <p>The string is as below,</p>
<pre><code>LOCATION AQI CATEGORY RANGE Dhaka a 251 VERY UNHEALTHY 195-306 Chittagong b 122 CAUTION 82-162 Gazipur c 237 VERY UNHEALTHY - Narayanganj c 335 EXTREMELY UNHEALTHY - Sylhetc c 159 UNHEALTHY - Khulna c DNA DNA - Rajshahi c 156 UNHEALTHY - Barisal c 192 UNHEALTHY - Savar DNA DNA ... | <p>You can use <code>regex</code> to parse your string:</p>
<pre><code>import pandas as pd
import re
s = """LOCATION AQI CATEGORY RANGE Dhaka 172 UNHEALTHY Chittagong 125 CAUTION Gazipur 178 UNHEALTHY Narayanganj 174 UNHEALTHY Sylhetc 129 CAUTION Khulna DNA DNA Rajshahi 118 CAUTION Barisal 118 CAUTION S... | python-3.x|regex|pandas|dataframe | 1 |
19,018 | 72,460,537 | How to create histogram of sales depending on day of week in Python? | <p>I have DataFrame in Python Pandas like below:</p>
<pre><code>day_of_week| sales
-----------|------
4 | 140
6 | 500
3 | 234
... | ...
</code></pre>
<p>Create histogram of sales depending on day of week. To be hones I do not understand how to make such a histogram and how to interpret... | <p>Suppose the DataFrame looks like this. You can draw a bar plot to visualize the sales for each day.</p>
<pre><code>days_of_week=[1,2,3,4,6,7,5]
sales_per_day = [140,43,23,45,67,89,700]
df=pd.DataFrame({"days_of_week":days_of_week,"sales_per_day":sales_per_day})
# Added red trend line
plt.figure(f... | python|pandas|matplotlib|time-series|histogram | 0 |
19,019 | 45,637,190 | How to make a Hierarchical filter in pandas? | <p>I have a DataFrame df, and I tried <code>ddf = df.describe()</code>, and got result like below.</p>
<p>I want to make a report based on this,</p>
<p>so I want to separate the mean/max/min and put them in my Word doc.</p>
<p>I tried many ways but unless I flat the ddf, I can not filter it based on <code>item</code... | <p>You are very close - use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html" rel="nofollow noreferrer"><code>Index.get_level_values</code></a>:</p>
<pre><code>#select by position - second level of MultiIndex
dmean = ddf.loc[ddf.index.get_level_values(1) == 'mean']
#sel... | python|pandas | 2 |
19,020 | 62,532,334 | Conditional column using threshold values | <p>I have a table set up as follows:</p>
<pre><code>Name ScoreA ScoreB
Jimmy 0.95 0.95
Claire 0.95 0.75
</code></pre>
<p>What I would like to do is is have an output column that returns 1 if both scores are above 0.9, returns 0 if both scores are below 0.8 and returns 2 if both sco... | <p>Using numpy <a href="https://numpy.org/doc/1.18/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>select</code></a>:</p>
<pre><code>df['0/1/2'] = np.select([(df.ScoreA<.8)&(df.ScoreB<.8), (df.ScoreA>.9)&(df.ScoreB>.9)], [0,1], 2)
</code></pre>
<p>Result:</p>
<pre><code> N... | python|pandas|dataframe|if-statement|conditional-statements | 1 |
19,021 | 54,593,371 | An issue with the sequence of datetime column in Python | <p>After concatenating many files into one big file, the sequence of the datetime column did not follow the original files.</p>
<p>I have many .csv files of meteorological data. One day one file. Interval 5 minutes. The original files use this datetime format: 24.03.2016 18:35. </p>
<p>I concatenatedd all files using... | <p>Solution should be simplify for added parameters to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a>, last convert index to custom format by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.strf... | python|pandas|datetime | 1 |
19,022 | 54,305,136 | How do I plug transpose of a pivoted dataframe into np.corrcoef method? | <p>Need to compute weekly success rate correlations</p>
<p>I've got weekly success rates for each sales person, as shown below:
<img src="https://i.ibb.co/NV84B6S/df.png" alt="DataFrame">.</p>
<p>This dataframe has been pivoted as follows:
<img src="https://i.ibb.co/PM8KJbt/pv.png" alt="Pivoted DataFrame">.</p>
<p>N... | <p><strong>UPDATE</strong>
<code>weekly_pivot['Success Rate'].corr()</code> worked just fine. </p> | python|pandas|dataframe | 0 |
19,023 | 54,338,970 | Check if value in a column exists in URL using lamda function | <p>I have a dataframe that has 2 columns. One is the URL and other is the username.</p>
<pre><code>+----------------------------------------+---------------+
| URL | Username |
+----------------------------------------+---------------+
| johnsmith/stackoverflow.com/?=abc | ... | <p>Assuming your data is clean, a list comprehension is relatively efficient:</p>
<pre><code>df['exists'] = [x in y for x, y in zip(df['Username'], df['URL'])]
</code></pre>
<p>You can use <code>apply</code> but with worse performance:</p>
<pre><code>df['exists'] = df.apply(lambda row: row['Username'] in row['URL'],... | python|string|pandas|dataframe|lambda | 2 |
19,024 | 54,557,082 | Can accuracy_score and precision_score be equal? | <p>I am trying to build a logistic regression model in python 3 using sklearn library.</p>
<p>Let's stick to below short versions going forward,</p>
<p>dv - dependent variable </p>
<p>idv - independent variable</p>
<p>Now I have idv1, idv2, idv3, idv4, idv5, idv6, idv7, idv8 & idv9.</p>
<p>Out of which idv6 to... | <p>Precision = True Positive / (True Positive + False Positive)</p>
<p>Accuracy = (True Positive + True Negative) / (True Positive + False Positive + True Negative + False Negative)</p>
<p>Therefore, if there are no negative predictions, these two values will be equal.</p> | python|scikit-learn|logistic-regression|sklearn-pandas | 2 |
19,025 | 73,704,077 | Dataframe selection using values from another dataframe | <p>I have this dataframe:</p>
<pre><code>studyarea_pcdn
POSTCODE Number of meters
0 NE4 9UP 41
1 NE4 9UN 32
2 NE4 9UL 29
3 NE4 9EN 27
4 NE4 9DY 25
5 NE4 9ED 22
6 NE4 9EL 18
7 NE4 9EE 13
8 NE4 9UJ 11
9 NE4 9DX 6
10 NE4 9EA 4
</code></pre>
<p>The... | <p>This is really just an inner merge, then a <code>.loc</code> filter on the absolute value of the differences.</p>
<pre><code>df = pd.DataFrame({'POSTCODE': ['NE4 9UP',
'NE4 9UN',
'NE4 9UL',
'NE4 9EN',
'NE4 9DY',
'NE4 9ED',
'NE4 9EL',
'NE4 9EE',
'NE4 9UJ',
'NE4 9DX',
'NE4 9EA'],
'Number of meters... | python|pandas | 2 |
19,026 | 73,725,148 | Iterating over torch tensor | <p>What is the best and fastest way to iterate over Tensor. It is confusing why do I get tensor instead of value..</p>
<p>got this :</p>
<pre><code> [ x for x in t]
Out[122]: [tensor(-0.12), tensor(-0.11), tensor(0.68), tensor(0.68), tensor(0.17)]
</code></pre>
<p>but expected this behavior :</p>
<pre><code> [ x fo... | <p>With numpy everything is simpler because <code>np.arrays</code> are just a collection of numbers always stored on CPU. Therefore, if you iterate over an <code>np.array</code> you get these <code>float</code> numbers.<br />
However, in PyTorch, tensors store not only numbers but also their gradients. Additionally, Py... | python|pytorch|iteration|tensor | 2 |
19,027 | 52,041,764 | How estimator of tensorflow load specific steps of model instead of latest one? | <p>We can save many checkpoints of model using Estimator and <code>RunConfig</code>.</p>
<p><code>classifier</code> eval will use the latest step <code>200</code> by default,
<strong>can I load <code>ckpt-1</code></strong>?</p>
<pre><code>my_checkpointing_config = tf.estimator.RunConfig(
save_checkpoints_secs = ... | <p>Both <code>tf.estimator.Estimator.evaluate</code> and <code>tf.estimator.Estimator.predict</code> have a <code>checkpoint_path</code> argument. You should be able to supply the path to <code>model.ckpt-1</code> here to use this checkpoint for evaluation.</p>
<p>Note that this argument was added in a fairly recent T... | tensorflow | 9 |
19,028 | 52,443,519 | FutureWarning: .loc or [] with missing label, suggests to use .reindex() | <p>My input dataframe has <code>Date</code> in quarter format and <code>Rate</code>. There are missing quarter in <code>Date</code>. Now I am trying to compute the <code>Update</code> based on logic that if 3rd last quarter row is available then pick this Rate otherwise pick the last row Rate. My current code looks lik... | <p>The problem is that in preparation for what <code>np.where</code> may or may not need, <code>df.loc[df.index - 3]</code> gets evaluated for all values of <code>df.index - 3</code>. The warning message is a good one and suggests that you should use <code>df.reindex(df.index - 3)</code> instead.</p>
<pre><code>df1['... | python|pandas | 0 |
19,029 | 60,345,730 | Data Manipulation Function not passing test runs | <p>I am working on the following problem and wrote my code to solve it. However, it does not pass the test run and I cannot figure out why. Here is the problem:</p>
<p>A company stores login data and password hashes in two different containers:</p>
<p>DataFrame with columns: Id, Login, Verified.
Two-dimensional NumPy... | <p>By doing 'inplace=True' inside the function, you will be able to modify the id_name_verified as a global variable.</p>
<pre class="lang-py prettyprint-override"><code>def login_table(id_name_verified, id_password):
id_name_verified.drop(['Verified'],axis=1,inplace=True)
id_name_verified['Password']=id_passwo... | python-3.x|pandas|numpy | 0 |
19,030 | 72,766,074 | How to show last occurence of a certain value in a Pandas column? | <p>Let's say I have this DataFrame</p>
<pre><code> time status
0 10:00 On
1 10:01 Off
2 10:02 Off
3 10:03 Off
4 10:04 On
5 10:05 Off
6 10:06 Off
7 10:07 Off
8 10:08 Off
9 10:09 On
10 10:10 Off
</code></pre>
<p>I want to add a column that shows the... | <p>you could try something like this:</p>
<pre><code>df['last_on']= df.time.where(df.status=='On').shift().ffill()
</code></pre> | pandas|dataframe | 3 |
19,031 | 72,548,030 | Getting Numerical Frequency Table for a Dataframe? | <p>i would like to know, how can i do the following. My input table is as follows</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Sr No</th>
<th>Data</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John Apple Android</td>
</tr>
<tr>
<td>2</td>
<td>John Apple Microsoft Ryan</td>
</tr>
<tr>
<... | <p>Try:</p>
<ol>
<li><code>extractall</code> the names from each row</li>
<li>Get all the devices from each row by replacing the names</li>
<li><code>merge</code> the data to map each name with the corresponding device</li>
<li><code>crosstab</code> to get the frequency table</li>
</ol>
<pre><code>columns = ["John... | python|pandas|frequency-distribution | 0 |
19,032 | 59,581,506 | Get rows from dataframe with multicolumn conditions | <p>It will be easy to show what I want then explain it. Consider the following dataframe:</p>
<pre><code>dr = {'mac':[1, 3, 2, 4, 1, 2], 's': ['aa', 'aa', 'c', 'd', 'ee', 'f']}
d = pd.DataFrame(data=dr)
</code></pre>
<p>Desiable output is:</p>
<pre><code> mac s
0 1 aa
4 1 ee
</code></pre>
<p>I... | <p>IIUC <code>filter</code> with <code>isin</code> </p>
<pre><code>out=d.groupby('mac').filter(lambda x : pd.Series(['aa','ee']).isin(x['s']).all())
Out[62]:
mac s
0 1 aa
4 1 ee
</code></pre> | python|pandas|dataframe | 7 |
19,033 | 59,674,748 | Pandas columns to rows with values | <p>I have a pandas DataFrame <code>df</code> like -</p>
<pre><code>fileName obj1 obj2 obj3 obj4
file_01.jpg 1 1 1
file_02.jpg 1 1
file_03.jpg 1 2 1
</code></pre>
<p><strong>Expected output</strong>: </p>
<pre><code>variable value
obj1 2
obj2 4
obj3 ... | <p>You can use column wise sum:</p>
<pre><code>(
df.set_index('fileName')
.sum(0)
.to_frame('value')
.rename_axis('variable')
.reset_index()
)
variable value
0 obj1 2
1 obj2 4
2 obj3 2
3 obj4 1
</code></pre> | python|pandas | 2 |
19,034 | 61,915,869 | Obtaining model of ResNet50 which cannot be obtained with the include_top attribute | <p>I am using ResNet50 model for feature extraction. I have two models initialized in the following way: </p>
<pre><code>from tensorflow.keras.applications import ResNet50
model1=ResNet50(weights="imagenet", include_top=False)
model2=ResNet50(weights="imagenet", include_top=True)`
</code></pre>
<p>Now when I plot t... | <p>You can generate a new keras model from the ResNet input and the output of the global average pooling (GAP) layer. In order to get the output of the GAP layer you need to extract this using the get_layer method. You can do this for any layer by finding the layer name with model.summary()</p>
<pre><code>model1=ResNe... | tensorflow|keras|resnet|imagenet | 2 |
19,035 | 61,616,428 | Finding the percentile in pandas column | <p>Data-</p>
<pre><code>df=pd.DataFrame({'city':['abc','abc','abc','abc','abc','abc'],'zone':['AA','AA','CC','CC','DD','DD'],'date':['1/1/2020','1/2/2020','1/1/2020','1/2/2020','1/1/2020','1/2/2020'],'D':[22,33,32,76,44,66]})
</code></pre>
<p>Now I want to search through for a particular city and date and find the 10... | <p>you can use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#transformation" rel="nofollow noreferrer"><code>groupby.transform</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.quantile.html" rel="nofollow noreferrer"><code>quantile</code><... | python|pandas | 0 |
19,036 | 61,848,918 | Pandas remove particular int values in comma separated column values | <p>I have a dataframe with column values separated by comma. I want to remove certain values from those values.</p>
<p>My dataframe looks like this:</p>
<pre><code> col1 col2
0,1,0,2,30,10,20 0,0,2,3,10,20
0,0,0,1,0,210,30 0,0,20,20,20,0,0,0
</code></pre>
<p>I want to remove 0,1,2 from column</p>
... | <p>Use list comprehension with specified values for remove in list:</p>
<pre><code>def mysub(r):
return [','.join(z for z in str(y).split(',')
if z not in ['0','1','2']) for y in r]
df = df.apply(mysub)
print (df)
col1 col2
0 30,10,20 3,10,20
1 210,30 20,20,20
</code></pre>
<p>For ... | python|pandas | 1 |
19,037 | 57,917,971 | How to Add counter at the end of unique rows given three different unique columns | <p>I'm adding the counter to the end of the unique rows but unable to do.I have 4 columns namely "ID", "Name","Amount".The problem I'm facing is that i want to add counter at the end of unique row "Id" column but make sure that i am also considering other unique rows as well. </p>
<p>This is the data frame i am using.... | <p>First filter only duplicated values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</code></a>, filter them with <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="... | python|pandas | 1 |
19,038 | 58,076,296 | How to export tensorflow_hub module to use it in an installer | <p>I'm working on a app that use a tensorflow module, currently i load tensorflow like this</p>
<pre><code>module_path = 'https://tfhub.dev/deepmind/biggan-deep-128/1'
tf.reset_default_graph()
module = hub.Module(module_path)
inputs = {k: tf.placeholder(v.dtype, v.get_shape().as_list(), k)
for k, v in modul... | <p>It's not exactly documented anywhere, but it <a href="https://github.com/tensorflow/hub/blob/25a740b3564db8ad70ea512b1ce090aafa6a9cce/tensorflow_hub/compressed_module_resolver.py#L41" rel="nofollow noreferrer">looks like</a> appending <code>?tf-hub-format=compressed</code> to a <code>https://tfhub.dev/deepmind/bigga... | python|python-3.x|tensorflow|tensorflow-hub | 1 |
19,039 | 58,056,275 | Remove first x characters from a few column headers | <p>I have created a sparse matrix dataframe which has taken the values in a list and set them as column headers. A number of rows contain headers for example "000 bank". I want to remove the "000 " so it is just 'bank' for example. </p>
<pre><code>000 bank 000 claim 000 confirmed 000 debit 000 delete 000 fre... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace</code></a> with <code>^</code> for start of string:</p>
<pre><code>df.columns = df.columns.str.replace('^000 ','')
</code></pre>
<p><strong>Sample</strong>:</p>
... | python|pandas|dataframe|nlp|tf-idf | 2 |
19,040 | 54,993,384 | AIY image classification project on ubuntu | <p>(venv) nvidia@tegra-ubuntu:~/tensorflow-for-poets-2$ IMAGE_SIZE=128
(venv) nvidia@tegra-ubuntu:~/tensorflow-for-poets-2$ ARCHITECTURE='mobilenet_0.25_128_quantized'
(venv) nvidia@tegra-ubuntu:~/tensorflow-for-poets-2$ ARCHITECTURE="mobilenet_0.25_128_quantized"</p>
<p>(venv) nvidia@tegra-ubuntu:~/tensorflo... | <p>Make sure to adjust the input image resolution in your 'label_image' script.</p>
<p>It might be adjusted to be using the full resolution model be default with an input size of 224x224. This should fix your dimension error. :)</p>
<p>Fix this:</p>
<pre><code>def read_tensor_from_image_file(file_name,
... | ubuntu|tensorflow | 0 |
19,041 | 54,791,863 | Select Pandas dataframe rows based on 'hour' datetime | <p>I have a pandas dataframe 'df' with a column 'DateTimes' of type datetime.time.</p>
<p>The entries of that column are hours of a single day:</p>
<pre><code>00:00:00
.
.
.
23:59:00
</code></pre>
<p>Seconds are skipped, it counts by minutes.</p>
<p>How can I choose rows by hour, for example the rows between 00:00:... | <p>Here a working example of what you are trying to do:</p>
<pre><code>times = pd.date_range('3/6/2012 00:00', periods=100, freq='S', tz='UTC')
df = pd.DataFrame(np.random.randint(10, size=(100,1)), index=times)
df.between_time('00:00:00', '00:00:30')
</code></pre>
<p>Note the index has to be of type DatetimeIndex.</... | python|pandas|datetime | 6 |
19,042 | 54,801,182 | Pandas - match two columns from two data frames and create new column in df1 | <p>I have two data frames</p>
<p>df1</p>
<pre><code>Srlno id image
1 3 image1.jpg
2 3 image2.jpg
3 3 image2.jpg
</code></pre>
<p>df2</p>
<pre><code>Srlno id image
1 1 image1.jpg
2 2 image2.jpg
3 3 image3.jpg
</code></pre>
<p>I want to match both the data frames b... | <p>Another solution with <code>dict(zip())</code></p>
<pre><code>df1['newids']=df1.image.map(dict(zip(df2.image,df2.id)))
print(df1)
Srlno id image newids
0 1 3 image1.jpg 1
1 2 3 image2.jpg 2
2 3 3 image2.jpg 2
</code></pre> | python|pandas|dataframe | 6 |
19,043 | 49,599,533 | Asymmetric slicing python | <p>Consider the following matrix: </p>
<pre><code>X = np.arange(9).reshape(3,3)
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
</code></pre>
<p>Let say I want to subset the following array</p>
<pre><code>array([[0, 4, 2],
[3, 7, 5]])
</code></pre>
<p>It is possible with some indexin... | <p>For arrays with <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer"><code>NumPy's advanced-indexing</code></a>, it would be -</p>
<pre><code>X[row, np.asarray(col)[:,None]].T
</code></pre>
<p>Sample run -</p>
<pre><code>In [9]: X
Out[9]:
ar... | python|numpy|vectorization|slice|dask | 4 |
19,044 | 49,514,039 | how to insert values from csv into sqlite3 using python | <p>i have a python code that read from csv file using <strong>pandas</strong> and then create a file sqlite3 called <strong>rduDB.db</strong>.</p>
<pre><code> date temperaturemin temperaturemax
0 2007-01-13 48.0 69.1
1 2007-01-19 34.0 54.0
2 2007-01... | <p>You can simply use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow noreferrer">DataFrame.to_sql()</a> method:</p>
<pre><code>import sqlite3
conn = sqlite3.connect('c:/temp/test.sqlite')
#...
df.to_sql('rduWeather', conn, if_exists='append', index_label=... | python|pandas|dataframe|sqlite|readfile | 1 |
19,045 | 73,489,538 | cannot fit the model using data loaded from tfds ImageFolder | <p>I am trying to use <code>VGG16</code> in a model but I got an error when calling <code>fit</code>.</p>
<pre><code>ValueError: Input 0 of layer "sequential_1" is incompatible with the layer: expected shape=(None, 363, 360, 3), found shape=(363, 360, 3)
</code></pre>
<p>I am using <code>tfds</code> to load i... | <p>You seem to have forgotten to set the batch size:</p>
<pre><code>history = model.fit(train_ds.batch(32), epochs=100,)
</code></pre>
<p><code>builder.as_dataset</code> constructs a <code>tf.data.Dataset</code>, so you need to call <code>train_ds.batch(your_batch_size)</code>. See <a href="https://www.tensorflow.org/d... | python|tensorflow|keras|tensorflow-datasets|vgg-net | 1 |
19,046 | 73,288,781 | Is advanced indexing available across n-dimensions in TensorFlow? | <p>In PyTorch, we can use standard Pythonic indexing to apply advanced indexing across n-dimensions.</p>
<p><code>preds</code> is a <code>Tensor</code> of shape <code>[1, 3, 64, 64, 12]</code>.</p>
<p><code>a</code>, <code>b</code>, <code>c</code>, <code>d</code> are 1-dimensional <code>Tensor</code>s of the same lengt... | <p>Yes, <a href="https://www.tensorflow.org/api_docs/python/tf/gather_nd" rel="nofollow noreferrer"><code>gather_nd</code></a> can do that</p>
<pre><code>t = tf.random.uniform(shape=(1,3,64,64,12))
# i_n = indices along n-th dim
i_1 = tf.constant([0,0,0,0,0,0,0,0,0])
i_2 = tf.constant([0,1,2,1,2,2,1,0,0])
i_3 = tf.con... | python|tensorflow|tensorflow2.0 | 2 |
19,047 | 73,219,405 | Pandas: Reindex/merge or re-allocate time series (of different time stamps) without interpolation | <p>I have two pandas dataframes of different time series stamps, and I want to merge them together. The first dataframe is data from model and called <code>df_model</code> and the second one is observation which is called <code>df_obs</code>. Brief examples of <code>df_model</code> and <code>df_obs</code> are like belo... | <p>You can try this:</p>
<ol>
<li>Add a columnt in both dataframes (or two temporal dataframes) showing if it morning or afternoon:</li>
</ol>
<pre class="lang-py prettyprint-override"><code>from datetime import time
df_obs['morning'] = df_obs.hourtime.astype('datetime64')\
.apply(lambda x: x.time() < time(12,0... | pandas|dataframe|merge|time-series|reindex | 1 |
19,048 | 67,456,889 | DIsplaying column name along with column index | <p>I want the column index to be displayed along with the column names. Looking at the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.info.html#pandas.DataFrame.info" rel="nofollow noreferrer">docs</a> for <code>df.info()</code>, using <code>verbose=True</code> should help but it isn't.</p>
<pre... | <p>You can create frame out of column names:</p>
<pre class="lang-py prettyprint-override"><code>df.columns.to_frame(index=False, name='cols')
</code></pre>
<p>OUTPUT:</p>
<pre class="lang-py prettyprint-override"><code> cols
0 a
1 b
2 c
</code></pre> | python|pandas|dataframe | 2 |
19,049 | 67,591,863 | Encoding and decoding with utf-8 returns UnicodeError | <p>I am both enconding and decoding with utf-8 but still I get a UnicodeError.</p>
<pre><code>import pandas as pd
df.to_csv('myfile.csv', index=False, encoding='utf-8')
</code></pre>
<p>Then, in another .py, same project</p>
<pre><code>import pandas as pd
with open(file, 'r') as f:
csv = pd.read_csv(f, encoding='ut... | <p>Ok, found it. Makes a lot of sense now.</p>
<pre><code>with open(file, 'r', encoding='utf-8') as f:
csv = pd.read_csv(f)
</code></pre> | python|pandas|encoding|utf-8 | 0 |
19,050 | 59,923,152 | Create a TimeSerie using an index and values from different TimeSeries, with different indices | <p>I want to create a DataFrame or TimeSerie using an index of an existing TimeSerie and the values from another TimeSerie with different time indices. The TimeSeries look like; </p>
<pre><code> <class 'pandas.core.series.Series'>
DT
2018-01-02 172.3000
2018-01-03 174.5500
2018-01-04 173.4700
2018-01-05... | <p>My idea is to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> twice:</p>
<pre class="lang-py prettyprint-override"><code>second_ts.reindex(first_ts.index, method='ffill').drop_duplicates().reindex(first_ts.index)
... | python|pandas|dataframe|time-series | 1 |
19,051 | 60,045,692 | Jupyter Notebook Truncates Python Output | <pre><code>import pandas as pd
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
data = pd.read_csv(...)
data.columns
</code></pre>
<p>Given the code above I am expecting to see a complete list of the 668 c... | <p>Because you are changing Pandas pretty print, not how Python itself is truncating output.</p>
<p>For example: <em>display.max_rows and display.max_columns sets the maximum number of rows and columns displayed when a frame is pretty-printed. Truncated lines are replaced by an ellipsis.</em>
<a href="https://pandas.p... | pandas|jupyter-notebook | 2 |
19,052 | 60,180,386 | Pytorch Tensorboard SummaryWriter.add_video() Produces Bad Videos | <p>I’m trying to create a video by generating a sequence of 500 matplotlib plots, converting each to a numpy array, stacking them and then passing them to a SummaryWriter()'s add_video(). When I do this, the colorbar is converted from colored to black & white, and only a small number (~3-4) of the matplotlib plots ... | <p>According to pytorch <a href="https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter.add_video" rel="nofollow noreferrer">docs</a>, the video tensor should have shape (N,T,C,H,W), which I think it means: batch, time, channels, height and width. You said your tensor has shape (B... | video|pytorch|tensorboard | 1 |
19,053 | 65,202,511 | Weird tick spacing when plotting with time on x-axis | <p>I'm plotting a <code>pandas</code> time series, which work OK when plotting the timestamps on the x-axis...</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
ts = pd.date_range("2020-01-01", "2020-01-02", freq='15T', closed="left")
vals = np.ran... | <p>Use matplotlib and format xaxis:</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.dates as mdates
plt.plot(ts, vals)
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)
</code></pre>
<p><a href="https://i.stack.imgur.com/3AcQp.jpg" rel="nofollow noreferrer"><img src="h... | python|pandas|matplotlib | 0 |
19,054 | 65,368,684 | How do I convert strings in a column into numbers which I can use later, in a dataframe? | <p>I have a dataset consisting of 382 rows and 4 columns. I need to convert all the names in to numbers. The names do repeat here and there, so I can't just randomly give numbers.
So, I made a dictionary of the names and the corresponding values. But now, I am not able to change the values in the column.
This is how I ... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow noreferrer">df.applymap()</a> works on each item in a dataframe:</p>
<pre><code>test_df.applymap(lambda x: dict_to_replace[x])
</code></pre> | python|python-3.x|pandas|dataframe | 0 |
19,055 | 65,221,919 | Filter dataframe A based on columns from dataframe B | <p>I have two dataframes where dataframe A has much more columns than dataframe B, what i would like to do is filter dataframe A by using dataframe B as reference and obtain a new dataframe A with the same amount of columns that dataframe A has. For example:</p>
<pre><code>df_A = pd.DataFrame(np.random.randn(150, 17), ... | <p>Use filter.</p>
<pre><code>df_A.filter(df_B.columns)
</code></pre>
<p>Or</p>
<pre><code>df_A[df_B.columns]
</code></pre> | python|pandas|dataframe | 0 |
19,056 | 65,328,224 | Applying rotation transform to a set of four coordinates of a rectangle in TensorFlow | <p>I want to rotate a rectangle for which I have the coordinates of the four vertices. I am doing this by creating a rotation matrix from the rotation angle and use that to transform the original rectangle coordinates. However, I don't have just one rotation matrix and one rectangle, but many.</p>
<p>My rotation tenso... | <p>You can use tf.matmul for batch multiplication. But you have to reshape:</p>
<pre><code>a = tf.random.uniform([10, 2, 2])
b = tf.random.uniform([10, 4, 2])
a = a[:, tf.newaxis, ...]
b = b[..., tf.newaxis]
c = tf.matmul(a, b)
c = tf.squeeze(c)
</code></pre> | tensorflow|tensor | 1 |
19,057 | 49,933,909 | Table canot be formatted to my ideal shape | <p>Table canot be formatted to my ideal shape.I wrote codes,</p>
<pre><code>#coding:utf-8
import scipy as sp
import scipy.stats
import pandas as pd
import numpy as np
data = df.loc[:, :].tolist()
ans = sp.stats.kruskal(data)
</code></pre>
<p>df variable has data like</p>
<pre><code>10min 20min 30min 40min 50min 60m... | <p>You need to <code>df.values</code> which is Numpy representation of NDFrame. See <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html" rel="nofollow noreferrer">here</a> for details.</p>
<pre><code>>>> df.values.tolist()
[[6L, 7L, 9L, 15L, 21L, 30L], [2L, 4L, 7L, 9L,... | python|pandas | 0 |
19,058 | 64,012,604 | How can I turn a pandas.core.series.Series into a Dataframe? | <p>How can I turn this pandas.core.series.Series into a dataframe?</p>
<p>At the moment it looks like this:</p>
<pre><code>A [0.18, 0.14, 0.22]
B [0.82, 0.78, 0.86]
C [0.03, 0.01, 0.04]
D [0.17, 0.13, 0.2]
</code></pre>
<p>I'd like to create a Dataframe with three columns called "V1", "V2&quo... | <p>Let us do</p>
<pre><code>out = pd.DataFrame(s.tolist(), index = s.index)
</code></pre> | python|pandas|dataframe | 2 |
19,059 | 46,670,499 | Compute the mean of the interval around the exact hour in a dataframe | <p>I have a dataframe with timestamps as index, the data has a frequency of 10 minutes. </p>
<p>I can't find a way to compute the mean in a interval from <code>h - 30min</code> to <code>h + 30min</code>, where <code>h</code> are all the exact hours (o'clock hours). </p>
<pre><code>In[1]: date_index = pd.date_range('2... | <p>Not sure about the exact expected output here but you can first resample the data every half and hour and find rolling mean to get the mean of 1.5 Hrs period.</p>
<pre><code>df.resample('30T').mean().rolling(3, center = True).mean()
Data
2015-12-01 00:00:00 NaN
2015-12-01 00:30:00 0.419649
2015-12-01 01:00:00 ... | python|pandas | 3 |
19,060 | 46,780,563 | Why do I get a series inside an apply/assign function in pandas. Want to use each value to look up a dict | <p>I have a dict of countries and population:</p>
<pre><code>population_dict = {"Germany": 1111, .... }
</code></pre>
<p>In my df (<code>sort_countries</code>) I have a column called 'country' and I want to add another column called 'population' from the dictionary above (matching 'country' with 'population')... | <p>Note that <code>x["country"]</code> is a <code>Series</code>, albeit a single element one, this cannot be used to index the dictionary. If you want just the value associated with it, use <code>x["country"].item()</code>.</p>
<p>However, a better approach tailor made for this kind of thing is using <code>df.map</cod... | python|pandas|dataframe|lambda | 2 |
19,061 | 63,260,092 | Tensorflow : Extract value from string tensor | <p>I have a tensor -
tf.Tensor(b'ISIC_2637011', shape=(), dtype=string)</p>
<p>How do I extract value from here?</p> | <p>If you want to get the value of tf.string tensor you can use :</p>
<pre><code>s = tf.constant("You're")
st_value = ''.join ([chr(char) for char in tf.strings.unicode_decode(s,
input_encoding='UTF-8').numpy()])
</code></pre> | tensorflow | 1 |
19,062 | 63,181,951 | How to get Graph (or GraphDef) from a given Model? | <p>I have a big model defined using Tensorflow 2 with Keras.
The model works well in Python. Now, I want to import it into C++ project.</p>
<p>Inside my C++ project, I use <code>TF_GraphImportGraphDef</code> function.
It works well if I prepare <code>*.pb</code> file using the following code:</p>
<pre><code> with op... | <p>The protocol buffers file generated by <a href="https://www.tensorflow.org/api_docs/python/tf/saved_model/save" rel="noreferrer"><code>tf.saved_model.save</code></a> does not contain a <a href="https://github.com/tensorflow/tensorflow/blob/v2.3.0/tensorflow/core/framework/graph.proto" rel="noreferrer"><code>GraphDef... | python|c++|tensorflow|keras|model | 5 |
19,063 | 62,980,677 | Why am I getting "HTTPError: HTTP Error 404: Not Found" for the following code? | <pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="darkgrid")
mum = sns.load_dataset("EE770_Mumbai")
sns.relplot(x="Hour of the year", y="RH(%)", data=mum)
</code></pre> | <p><code>seaborn.load_dataset</code> is documented here: <a href="https://seaborn.pydata.org/generated/seaborn.load_dataset.html" rel="nofollow noreferrer">https://seaborn.pydata.org/generated/seaborn.load_dataset.html</a></p>
<p>In summary, it loads a sample dataset from here: <a href="https://github.com/mwaskom/seabo... | python|pandas|numpy|seaborn | 1 |
19,064 | 67,688,982 | Create a colored bar plot using pandas by grouping using multiple columns | <p>I have the following Pandas code.</p>
<pre><code>import pandas as pd
DATA=pd.DataFrame({'Sex': ["M", "M", "F", "F","F","F","M"], 'Support': ['N', 'Y', 'Y', 'N',"Y","Y","N"]})
data=DATA.groupby(['Support','Sex']).size(... | <p>Something like:</p>
<pre><code>from operator import methodcaller
import matplotlib.pyplot as plt
# replace the letters with words
df = df.replace({"M": "Male", "F": "Female", "N": "No", "Y": "Yes"})
# turn df into desired format for g... | python|pandas|seaborn | 1 |
19,065 | 61,600,211 | Pyspark, prophet, pandas UDF - [8906 rows x 3 columns] of type <class 'pandas.core.frame.DataFrame'>. For column literals, use ' | <p>I am sorry if this is a stupid question, but I am stuck and have tried every suggestion for resolving similiar issue.</p>
<p><strong>I am trying to scale a facebook prophet model using pyspark and PandasUDF</strong> similiar to <a href="https://stackoverflow.com/questions/61509033/forecasting-with-facebook-prophet-... | <p>The output of the grouped map is stored in results, not the UDF itself. Drop your inner UDF function and get your results from <code>results</code>:</p>
<pre class="lang-py prettyprint-override"><code>@pandas_udf(mySchema, PandasUDFType.GROUPED_MAP)
def forecast(df):
model = Prophet(
growth="linear",
... | python|pandas|dataframe|apache-spark|pyspark | 0 |
19,066 | 61,488,860 | Generate a new column in pandas - conditionaly increase integer count | <p>I would like to have a dataframe of pandas like following:
<a href="https://i.stack.imgur.com/gh8Le.png" rel="nofollow noreferrer">Required Dataframe</a></p>
<p>Column A - according to these values i would like to generate a new variable - Column B.</p>
<p>All the time, when the values change, it should be "Step_(... | <p>One option is to create some global variables to track the value and the step and reference/update those inside the function that you use with <code>pandas.Series.apply</code> like so:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(dict(
A = [0,0,0,44.67,44.67,0,0,35.49,35.49,35.49,0]
))
step = 0
value ... | python-3.x|pandas|conditional-statements|calculated-columns | 1 |
19,067 | 68,634,200 | TypeError: Implicit conversion to a NumPy array is not allowed. Please use `.get()` to construct a NumPy array explicitly. - CuPy | <p>I would like to use the numpy function <code>np.float32(im)</code> with CuPy library in my code.</p>
<pre><code>im = cupy.float32(im)
</code></pre>
<p>but when I run the code I'm facing this error:</p>
<pre><code>TypeError: Implicit conversion to a NumPy array is not allowed. Please use `.get()` to construct a NumPy... | <p>You need to add <code>.get()</code> to <code>im</code> inside the brackets:</p>
<pre><code>im = cupy.float32(im.get())
</code></pre> | python|numpy|typeerror|cupy | 4 |
19,068 | 53,026,120 | Timeseries with multiple columns, each with duplicate entries. How to handle in pandas | <p>Have the following dataframe with duplicate values in the Date and UID columns:</p>
<pre><code>Date UID Score
2018-08-31 A 5
2018-08-31 B 3
2018-08-31 C 4
2018-05-31 A 4
2018-05-31 C 2
2018-05-31 A 4
2018-05-31... | <p>I think your only problem is the order in your group by. Try:</p>
<pre><code>#Recreating your frame
df = pd.DataFrame( [['2018-08-31', 'A', '5'],['2018-08-31','B',3],
['2018-08-31','C',4],
['2018-05-31','A',4],
['2018-05-31','C',2],
['2018-05-31','A',4],
['2018-05-31','B',1],
['2018-05-31','A',3],
['20... | python|pandas|dataframe|duplicates|time-series | 1 |
19,069 | 53,054,812 | How to generate random dates between date range inside pandas column? | <p>I have df that looks like this</p>
<pre><code>df:
id dob
1 7/31/2018
2 6/1992
</code></pre>
<p>I want to generate 88799 random dates to go into column <code>dob</code> in the dataframe, between the dates of <code>1960-01-01</code> to <code>1990-12-31</code> while keeping the format <code>mm/dd/yyyy</code>... | <p>I would figure out how many days are in your date range, then select 88799 random integers in that range, and finally add that as a timedelta with <code>unit='d'</code> to your minimum date:</p>
<pre><code>min_date = pd.to_datetime('1960-01-01')
max_date = pd.to_datetime('1990-12-31')
d = (max_date - min_date).day... | python|python-3.x|pandas | 7 |
19,070 | 53,078,960 | Can Euler be better than Runge-Kutta for some functions? | <p>I'm trying to solve exercises from Steven Strogatz's Non-Linear Dynamics and Chaos. In exercise 2.8.3, 2.8.4, and 2.8.5, one is expected to implement the Euler method, improved Euler method, and Runge-Kutta (4th order) method respectively for the initial value problem dx/dt = -x; x(0) = 1 to find x(1). </p>
<p>Anal... | <p>You are doing only <code>n-1</code> integration steps of step size <code>h=1/n</code>, thus you compute </p>
<pre><code>exp(-(n-1)/n)=1/e*exp(1/n)
</code></pre>
<p>which has the approximate value</p>
<pre><code>1/e + 1/e*1/n
</code></pre>
<p>The reported error values are exactly that, <code>-h/e</code>, which i... | numpy|numerical-methods|differential-equations|runge-kutta | 3 |
19,071 | 65,767,557 | Plotly Choropleth map successfully loads in Jupyter, but not Dash browser | <p>I have been able to successfully create a custom shapefile Choropleth map using plotly and geopandas. It loads successfully in my Jupyter window. The following image is what the map looks like when running in Jupyter.</p>
<p><a href="https://i.stack.imgur.com/Cm9LY.png" rel="nofollow noreferrer">Successfully rendere... | <p>I'm working on a very similar problem and when I converted from jupyter to dash I do not recall having to change the process of the geojson. But don't reject that possibility yet. The fact that it isn't producing any errors from the geojson is likely indicative of an error in how you build your layout. So the first ... | python|plotly|geojson|plotly-dash|geopandas | 0 |
19,072 | 63,727,256 | Create new column showing count of missing values | <p>Below is script for a simplified version of the df in question:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'id' : [1,1,1,1,2,2,2,2,3,3,3,3],
'feature' : ['cd_player', 'sat_nav', 'sub_woofer', 'usb_port','cd_player', 'sat_nav', 'sub_woofer', 'usb_port','cd_... | <p>you can <code>map</code> the column feature with the result of <code>groupby.sum</code> by feature where the column feature_value is equal (<code>eq</code>) to 0.</p>
<pre><code>df['no_value_count'] = df['feature'].map(df['feature_value'].eq(0)
.groupby(df['feature']).sum()... | python|pandas | 3 |
19,073 | 53,476,694 | how to subtract one column by another excluding flag in pandas | <p>I have following dataframe in pandas</p>
<pre><code> code time_diff diff_flag quantity
123 0 zero 0.45
124 5 less than 6 0.80
125 8 no issue 0.78
126 18 no issue 2.78
127 28 no issue ... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p>
<pre><code>m = df['diff_flag'].isin(['zero','less than 6'])
df['new_diff'] = np.where(m, 'Data Error', df['time_diff'] - 6)
</code></pre>
<p>Or:</p>
<pre><code>m1 = df['t... | python|pandas | 1 |
19,074 | 72,090,384 | Groupby and convert the first value to NaN | <p>My df</p>
<pre><code> id date dummy
0 A 2019Q1 1
1 A 2019Q2 0
2 A 2019Q3 0
3 B 2019Q1 1
4 B 2019Q2 1
5 B 2019Q3 0
</code></pre>
<p>How can I groupby id and then convert the earliest value to NaN?</p>
<p>output</p>
<pre><code> id date dummy
0 A 2019Q1 NaN
1 A 2... | <p>Use a boolean mask (assuming each rows are already sorted for each group):</p>
<pre><code>df.loc[~df['id'].duplicated(), 'dummy'] = np.nan
print(df)
# Output
id date dummy
0 A 2019Q1 NaN
1 A 2019Q2 0.0
2 A 2019Q3 0.0
3 B 2019Q1 NaN
4 B 2019Q2 1.0
5 B 2019Q3 0.0
</code></pre>
<p>O... | python|pandas|dataframe | 2 |
19,075 | 72,043,095 | How to iterate over a pandas dataframe using a list | <p>I have the following <code>pandas</code> dataframe</p>
<pre><code>import pandas as pd
foo = pd.DataFrame({'source': ['tomato', 'carrots', 'cheese'],
'tomato': [0.7, 0.4, 0.8],
'carrots': [0.15,0.3,0.1],
'cheese': [0.15,0.3,0.1... | <p>Maybe you could use <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow noreferrer"><strong><code>zip</code></strong></a>:</p>
<pre><code>In [1]: import pandas as pd
In [2]: foo = pd.DataFrame({
...: 'source': ['tomato', 'carrots', 'cheese'],
...: 'tomato': [0.7, 0.4, 0.8],
... | python|python-3.x|pandas | 2 |
19,076 | 55,247,437 | Add new rows in a df depending on another df and conditions with pandas | <p>I have some issues in order to create a new data frame depending on 2 dataframes informations.
Here is a <code>dataframe1</code>:</p>
<pre><code>species seq_names value
dog seq_C 0.67
cat seq_F 1.4
cat seq_E 0.4
dolphin seq_F 0.7
dolphin seq_A 1.9
frog seq_A 0.8... | <pre><code>import pandas as pd
df = pd.read_csv('test')
df2 = pd.read_csv('test.csv')
df2 = df2.rename(columns={'col1' : 'species'})
print(df)
# species seq_names value
# 0 dog seq_C 0.67
# 1 cat seq_F 1.40
# 2 cat seq_E 0.40
# 3 dolphin seq_F 0.70
# 4 dolphin seq_A 1... | python|pandas | 2 |
19,077 | 55,484,147 | How To create Multiple Columns From Values of The Same Column? | <p>I Have A DataFrame , & I Want to Create New Columns Based o The Values of The Same Column , And At Each of This Column I want The Values To Be The Sum of repetition of <strong><em>Plate</em></strong> over the Time.</p>
<p>So I have This DataFrame:</p>
<pre><code> Val_Tra.Head():
... | <p>This is more like a <code>get_dummies</code> problem </p>
<pre><code>s=df.dropna().EURO.astype(int).astype(str).str.get_dummies().add_prefix('EURO')
df=pd.concat([df,s],axis=1,sort=True)
df
Out[259]:
Plate EURO EURO0 EURO6
2013-11-0100:00:00 ... | python-3.x|pandas|dataframe|merge|multiple-columns | 0 |
19,078 | 56,771,881 | Concat two dataframes wit common columns | <p>I have two dataframes with same columns. Only one column has different values. I want to concatenate the two without duplication.</p>
<pre class="lang-py prettyprint-override"><code>df2 = pd.DataFrame({'key': ['K0', 'K1', 'K2'],'cat': ['C0', 'C1', 'C2'],'B': ['B0', 'B1', 'B2']})
df1 = pd.DataFrame({'key': ['K0', 'K... | <p><code>pd.merge</code> will do the job</p>
<pre><code>pd.merge(df1,df2, on=['key','cat'])
</code></pre>
<p><strong>Output</strong></p>
<pre><code> key cat B_x B_y
0 K0 C0 A0 B0
1 K1 C1 A1 B1
2 K2 C2 A2 B2
</code></pre> | python|pandas | 5 |
19,079 | 66,781,973 | Type error with strings converted as Series | <p>I want to create a new column <code>"HQ_LOC"</code> in the <code>excel</code> dataframe, that takes as a value the strings <code>j</code> from <code>wharton['conm']</code></p>
<pre><code>xls = excel[(excel['prowess_compustat_h1b'] == 1) | (excel['compustat_h1b'] == 1)]
excel['HQ_LOC'] = pd.Series([])
for ... | <p>The error is self explained, you cann't append str type to series type. To do what you want, you could use:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
xls = pd.DataFrame({'coname': ['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo']})
wharton = pd.DataFrame({'conm': ['lama', 'hippo', 'ti... | python|pandas|dataframe|typeerror | 0 |
19,080 | 66,829,418 | Automated way to round number based on precision of error | <p>I have a script that generates a large table of values and the corresponding errors. The errors calculated always have 1 significant figure but of varying precision (eg error1 = 1e-5 error2 = 1e-1). I was wondering if there an automated logical way of rounding of the values in the table based on the precision of the... | <p>Have you tried looking at python's decimal class?
Take a look at this extensive read regarding rounding numbers in python, it contains all the information you need to solve your issue:
<a href="https://realpython.com/python-rounding/" rel="nofollow noreferrer">https://realpython.com/python-rounding/</a></p> | python|numpy|math|scipy|rounding | 0 |
19,081 | 47,522,209 | Matrix QR factorization algorithms | <p>I've been trying to visualize QR decomposition in a step by step fashion, but I'm not getting expected results. I'm new to numpy so it'd be nice if any expert eye could spot what I might be missing:</p>
<pre><code>import numpy as np
from scipy import linalg
A = np.array([[12, -51, 4],
[6, 167, -68],
[-4, 24, -41... | <p>NumPy is designed to work with homogeneous multi-dimensional arrays, it is not specifically a <em>linear algebra</em> package. So by design, the <code>*</code> operator is <em>element-wise</em> multiplication, not the matrix product.</p>
<p>If you want to get the matrix product, there are a few ways:</p>
<ol>
<li>... | python|numpy|linear-algebra | 1 |
19,082 | 47,133,011 | How to check if the condition is true for the next n minutes | <p>I have a list of time intervals with a column of conditions as shown</p>
<p>Intervals:</p>
<pre><code>Time Count Bool Hit
2013-01-02 11:03:00 50 0 NaN
2013-01-02 11:10:00 63 0 NaN
2013-01-02 11:11:00 128 1 NaN
2013-01-02 11:12:00 283 0 NaN
2013-01-02 11:13:00 110 ... | <p>Could you be a little more specific about the rule you're trying to create? </p>
<p>You enter <code>1</code> into the <code>Hit</code> column even though entries from the next 5 minutes after that record have <code>0</code>s in <code>Bool</code>. Did you mean <strong>last 5 minutes</strong>?</p> | python|pandas|time-series|resampling | 0 |
19,083 | 47,087,463 | Creating table python | <p>I have a data set in excel. A sample of the data is given below. Each row contains a number of items; one item in each column. The data has no headers either.</p>
<pre><code>a b a d
g z f d a
e
dd gg dd g f r t
</code></pre>
<p>want to create a table which should look like below. It should count the items in ea... | <p>Use <code>get_dummies</code> + <code>sum</code>:</p>
<pre><code>df = pd.read_csv(file, names=range(100)).stack() # setup to account for missing values
df.str.get_dummies().sum(level=0)
a b d dd e f g gg r t z
0 2 1 1 0 0 0 0 0 0 0 0
1 1 0 1 0 0 1 1 0 0 0 1
2 0 0 0 0 1 ... | python|pandas | 1 |
19,084 | 59,449,545 | Invalid frequency: SM-15 in pandas.Series.dt.to_period | <p>I'm trying and unable to cast dates to half-month periods. I don't know whether this is a pandas bug or not, so I'm posting here using the issue format.</p>
<h2>Code Sample</h2>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
# Create column, cast to datetime
a = ['2018-04-01', '2018-04-06', '... | <p>Looking at the sample from the <a href="https://pandas-docs.github.io/pandas-docs-travis/user_guide/timeseries.html" rel="nofollow noreferrer">docs</a> that is not how you use <code>SM</code> when the input is a series.</p>
<p>I'm still not sure who to use <code>to_period</code>; however this does get the expected ... | python|pandas|datetime | 1 |
19,085 | 56,878,984 | Can you weight certain datapoints less than others when training a model? | <p>Say, for example, I'm trying to make a classifier to classify a sentence as good or bad. I have a data set of 50% <code>good</code> and 50% <code>bad</code>. I would prefer to have a false positive and wrongly classify them as good than than wrongly classify them as bad. </p>
<p>Is there any way to achieve this and... | <p>Use weighted cross entropy.<br>
In binary cross entropy [-(p)log(q) -(1-p)log(1-q)],<br>
-(p)log(q) term is for judging true data true (1 to 1)<br>
and -(1-p)log(1-q) term is for judging false data false. (0 to 0)<br>
So, if you want to have false positive rather than false negative,<br>
you can weight heavily -(p)l... | tensorflow|machine-learning|neural-network|classification | 0 |
19,086 | 56,954,256 | How to exclude the total row (margins) from styling (subset) in a pandas pivot table | <p>I have a .pivot_table with margins = True.</p>
<p>I want to run .style.bar and .style.background_gradient on it but the problem is that margins (column totals) are also formatted and set to the maximum value so it looks non-descriptive.</p>
<p>I had a few ideas on how to solve this, however, none are working so fa... | <p>You have to be a bit more explicit, but you can accomplish what you need with <code>get_level_values</code> and a <code>pd.IndexSlice</code></p>
<hr>
<pre><code>u = df.index.get_level_values(0)
(df.style.background_gradient(
subset = pd.IndexSlice[u[:-1], 'large'],
cmap = sns.light_palette('red', as_cmap = Tr... | python|pandas|formatting|pivot-table|margins | 6 |
19,087 | 57,163,934 | How to download data from mysql connection | <p>After making a connection with mysql library, i'd like to dowload all the database from the connection in my local space (tranforming them into pandas dataframe).</p>
<p>Here's my code:</p>
<pre><code> import MySQLdb
import pandas as pd
conn = MySQLdb.connect(host='host' , user='datbase', passwd='passw... | <p>Just use </p>
<pre><code>query = ' SELECT * FROM pro '
df = pd.read_sql(query , conn)
</code></pre>
<p>And <code>df</code> should already be your desired dataframe.</p> | mysql|python-3.x|pandas|database-connection | 1 |
19,088 | 45,974,637 | Date range comparisons in a pandas dataframe | <p>I have two panda data frames in python. dataframe1 contains the sample data.</p>
<pre><code> lat long tep height altitude date_time
40.007647 116.319781 0 83 39688.535613 2008-08-20 12:51:17
40.007632 116.319878 0 119 39688.535637 2008-08-20 12:51:19
40.007... | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_asof.html" rel="nofollow noreferrer">merge_asof</a> can help you here</p>
<pre><code>pd.merge_asof(df1, df2, left_on='date_time', right_on='Start_Time')
</code></pre>
<p>results in:</p>
<blockquote>
<pre><code> lat long tep he... | python|pandas|date|dataframe | 1 |
19,089 | 50,897,051 | subset based on row counts | <p>I have following dataset with shape: <code>(118, 2)</code></p>
<p>I want to subset data. My goal here is to subset data in such a way that I do not have to repeat the following:</p>
<pre><code>removeTotal[['Firms', 'IndustrySsize']][:8]
removeTotal[['Firms', 'IndustrySsize']][8:16]
removeTotal[['Firms', 'IndustryS... | <p>Just using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow noreferrer">numpy.split</a>:</p>
<pre><code>In [59]: np.split(df, range(8, df.shape[0], 8))
Out[59]:
[ Firms IndustrySsize
index
1 3598185 0-4
2 998953 5-9
3 6085... | pandas|numpy|subset | 0 |
19,090 | 50,852,725 | a function similar to numpy.take that indexes the out parameter | <p>In the <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.take.html" rel="nofollow noreferrer">documentation</a> of <code>numpy.take</code>, it is stated that <code>a</code> is indexed according to <code>indices</code> and <code>axis</code>, then the result is optionally stored in the <code>o... | <p>You can use swapaxes like so:</p>
<pre><code>>>> A = np.arange(24).reshape(2,3,4)
>>> out = np.empty_like(A)
>>> I = [2,0,1]
>>> axis = 1
>>> out.swapaxes(0, axis)[I] = A.swapaxes(0, axis)
>>> out ... | python|numpy|numpy-indexing | 1 |
19,091 | 50,930,300 | Training Error in PyTorch - RuntimeError: Expected object of type FloatTensor vs ByteTensor | <p>A minimal working sample will be difficult to post here but basically I am trying to modify this project <a href="http://torch.ch/blog/2015/09/21/rmva.html" rel="nofollow noreferrer">http://torch.ch/blog/2015/09/21/rmva.html</a> which works smoothly with MNIST. I am trying to run it with my own dataset with a custom... | <p>As far as I can tell, it seems that as you commented the <code>normalize</code> / <code>transforms.Normalize</code> operations applied to your dataset, your images don't have their values normalize to <code>float</code> between <code>[0, 1]</code>, and are instead keeping their <code>byte</code> values between <code... | python|image|pytorch|tensor|convolutional-neural-network | 2 |
19,092 | 66,722,077 | What is the most efficient way to create multiple subplots with `statsmodels.api.qqplot()`? | <p>Currently this code block generates 8x1 subplots. I want the code block to generate 2x4 subplots in the most efficient way. Please help!</p>
<pre><code>from sklearn.preprocessing import LabelEncoder
import statsmodels.api as sm
import pandas as pd
# load the dataset
url = 'https://raw.githubusercontent.com/jbrownle... | <p><strong>Edit</strong>:</p>
<p>To plot only the first 7 qq-plots:</p>
<pre class="lang-py prettyprint-override"><code>fig, axes = plt.subplots(ncols=4, nrows=2, sharex=True, figsize=(4*3, 2*3))
for k, ax in zip(df.columns, np.ravel(axes)):
if k >= 7:
ax.set_visible(False)
else:
sm.qqplot(df... | python|pandas|for-loop|matplotlib|statsmodels | 2 |
19,093 | 66,481,902 | Pandas column select rows regex numbers after a specific word | <p>I am trying to extract "Purchase Id: XXXXXXXX" for the following rows in a pandas dataframe but I am not sure of the correct regex expression to select starts with Purchase Id and ends after the digits.</p>
<p>What I have now:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Des... | <p>Try this to match any number of digits after <code>Product Id: </code>:</p>
<pre><code>df['Description'].str.extract('(Purchase Id: \d+)')
</code></pre>
<p>or this to match 8 characters after <code>Product Id: </code>:</p>
<pre><code>df['Description'].str.extract('(Purchase Id: .{8})')
</code></pre>
<p>Output:</p>
<... | regex|pandas | 1 |
19,094 | 66,630,606 | tensorflow-addons.image error, wrong input? | <p>How do I use <code>translate</code> in <code>tensorflow_addons.image</code>?
I tried the following with no success</p>
<p>(Versions: <code>tensorflow: 2.4.1</code>, <code>tensorflow-addons: 0.12.1</code>, <code>python: 3.8.8</code>)</p>
<pre><code>import tensorflow as tf
import numpy as np
from tensorflow_addons.ima... | <p>I was able to execute above code in this combination <code>tensorflow: 2.4.1, tensorflow-addons: 0.12.1 and python: 3.7.10</code>. You will be success.</p>
<pre><code>import sys
import tensorflow as tf
import numpy as np
import tensorflow_addons as tfa
from tensorflow_addons.image import translate as tfa_translate
p... | python|numpy|tensorflow|tensorflow2.0 | 1 |
19,095 | 66,669,112 | Gensim Tfidf model is returning empty weights list | <p>I am extracting tweets of Donald Trump and I want to use <code>tfidf</code> with <code>gensim</code> to get the weight of each token. But the last code section is returning an empty result</p>
<pre><code>import pandas as pd
df=pd.read_csv("/content/trumptweets.csv")
df=df.to_string()
from nltk.tokenize im... | <p>First, you need to apply the whole trained corpus within the tfidf model.
Second, you are getting an empty list because of the default value of the parameter <code>smartirs=nfc</code> in <code>models.tfidfmodel</code>. See the official API documentation <a href="https://radimrehurek.com/gensim/models/tfidfmodel.html... | python|pandas|dictionary | 0 |
19,096 | 66,426,486 | Pandas_ta - NoneType object has no attribute copy | <p>I use pandas_ta to calculate indicators such as RSI, MACD, EMA CROSS.
Unfortunately, there seems to be a problem with the closing price data.</p>
<p>I was passing ndarray and it didn't work so I changed it to a simple list and the result was the same.</p>
<p>Moreover, these arguments work with TaLib, but give more o... | <p>The answer is to provide pd.Series() not a list or ndarray. Problem solved.
In my opinion the error should inform about it</p> | python|pandas | 0 |
19,097 | 73,141,022 | Pandas dataframe : Group all columns in one with duplicated date | <p>I have a dataframe in Python 3.9 / Pandas</p>
<pre><code>d = {'date': ['01/01/2022', '02/01/2022','03/01/2022','04/01/2022'], 'room1': [10,11,27,65], 'room2': [5,6,8,9], 'room3': [21,25,41,22], 'room4': [14,21,54,13]}
df_test = pd.DataFrame(data=d)
df_test
</code></pre>
<p>OUTPUT</p>
<p><a href="https://i.stack.imgu... | <p>make use of the pd.melt</p>
<pre><code>df.melt(id_vars='date', var_name='rooms').sort_values('date')
</code></pre>
<pre><code>
date rooms value
0 01/01/2022 room1 10
4 01/01/2022 room2 5
8 01/01/2022 room3 21
12 01/01/2022 room4 14
1 02/01/2022 room1 11
5 02/01/2022 room2 6
... | python|python-3.x|pandas|dataframe|group-by | 2 |
19,098 | 72,938,658 | How to convert each element in a frequency column into a new dataframe row? | <p>So, I have this dataframe in which there is an ID column, a TEXT column and a TOKEN column with the 3 most frequent words in the TEXT</p>
<pre><code>ID TEXT TOKEN
sentence1 Emma Woodhouse , handsome , clever , and rich ... [(emma, 2), (woodhouse, 2), (hands... | <p>Let us <code>explode</code> and expand the <code>TOKEN</code> column into new dataframe, then <code>join</code> back with original dataframe</p>
<pre><code>s = df.explode('TOKEN', ignore_index=True)
pd.DataFrame([*s.pop('TOKEN')], columns=['WORD', 'FREQ']).join(s)
</code></pre>
<hr />
<pre><code> WORD FREQ ... | python|pandas|dataframe|nlp | 1 |
19,099 | 51,464,322 | I want to fill the missing values in my z matrix with the mean of all the values of the z matrix | <p>I'm want to fill missing data in columns with the means of their respective columns and using the code below:</p>
<pre><code>#Data Preprocessing
#Importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Importing dataset
dataset = pd.read_csv('Book1.csv')
x = dataset.iloc[:, :-2]... | <p>Apparently, you are using a single <code>Imputer</code> instance to impute both <code>x</code> (2D) and <code>z</code> (1D) arrays. You should have created separate imputers for both variables: </p>
<pre><code>imputer_x = Imputer()
imputer_z = Imputer()
imputer_x.fit(x[:,1:3])
imputer_z.fit(z[:])
x[:, 1:3] = imput... | python|pandas|machine-learning | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.