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 |
|---|---|---|---|---|---|---|
376,900 | 27,555,510 | Python Pandas read_csv issue | <p>I have simple CSV file that looks like this:</p>
<pre><code>inches,12,3,56,80,45
tempF,60,45,32,80,52
</code></pre>
<p>I read in the CSV using this command:</p>
<pre><code>import pandas as pd
pd_obj = pd.read_csv('test_csv.csv', header=None, index_col=0)
</code></pre>
<p>Which results in this structure:</p>
<pr... | <p>from the documentation of the function:</p>
<pre><code>names : array-like
List of column names to use. If file contains no header row, then you
should explicitly pass header=None
</code></pre>
<p>so, apparently: </p>
<pre><code>pd_obj = pd.read_csv('test_csv.csv', header=None, index_col=0, names=range(5))
</code>... | python-2.7|csv|pandas | 3 |
376,901 | 27,766,874 | What happens to `for i in range()` when iterator is overwritten in nested while loop? | <p>What happens to <code>for i in range()</code> when iterator is overwritten in nested while loop? For example, why do the following snippets give different output? When I change the name of the variables <code>i</code> and <code>j</code> inside the while loop, the snippet behaves as I expected. However, when the wh... | <p>Your terminology is slightly wrong. In a for loop you have no access to an iterator. The iterator is kept hidden, behind the scenes. The following looping structures are equivalent. </p>
<pre><code>for i in range(10):
print(i)
it = iter(range(10)):
while True:
try:
i = next(it)
except StopItera... | python|numpy|nested | 2 |
376,902 | 27,801,379 | iPython Notebook not printing Dataframe as table | <p>I'm trying to print a df in ipython notebook but it doesn't print it as a table. </p>
<pre><code>data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions', 'Lions', 'Lions'],
'wins': [11, 8, 10, 15, 11, 6, 10, 4],
'los... | <p><code>set_printoptions</code> has been replaced by <code>set_options</code> in the more recent versions of <em>pandas</em>, try to use:</p>
<pre><code>pandas.set_option('display.notebook_repr_html', True)
</code></pre>
<p>Also do not use <code>print</code>, simply state <code>football</code> or <code>display(footb... | python|pandas|dataframe|ipython-notebook | 10 |
376,903 | 61,348,016 | What does DataFrame.select_dtypes(exclude=['object']) actually do? | <p>I'm learning data science with the help of an online course. While learning about filtering specific datatype from a DataFrame object in Pandas, I came across this line of code:</p>
<pre><code>df = df.select_dtypes(exclude=['object'])
</code></pre>
<p>The purpose of the module was to show how to get only numeric d... | <p>So basically, it will select all the columns except the columns with data type object.</p>
<h2>References:</h2>
<ul>
<li><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>pandas.DataFrame.select_dtypes</code></a></li>
<li><a href="https://panda... | python|pandas|dataframe|data-science | 1 |
376,904 | 61,558,769 | Softmax Cross Entropy implementation in Tensorflow Github Source Code | <p>I am trying to implement a Softmax Cross-Entropy loss in python. So, I was looking at the implementation of Softmax Cross-Entropy loss in the GitHub Tensorflow repository. I am trying to understand it but I run into a loop of three functions and I don't understand which line of code in the function is computing the ... | <p>When you follow the call stack for this function, you eventually find <a href="https://github.com/tensorflow/tensorflow/blob/8fe9e086d7193f0bfe55a2fe5cbe3c191fc522aa/tensorflow/python/ops/nn_ops.py#L3542" rel="nofollow noreferrer">this</a>:</p>
<pre class="lang-py prettyprint-override"><code>cost, unused_backprop =... | python|tensorflow|bazel|softmax|cross-entropy | 2 |
376,905 | 61,434,662 | lag shift a long table in pandas | <p>I have a pandas dataframe that looks like the following: </p>
<pre><code>ticker, t, shout_t shout_tminus
A 2010-01-01 22
A 2010-01-02 23
A 2010-01-03 24
B 2010-01-01 44
B 2010-01-02 55
B 2010-01-03 66
C 2010-01-01 1... | <p>All you need is to add a <code>groupby('ticker')</code>:</p>
<pre><code>df['shout_tminus'] = df.sort_values(['ticker', 't']) \
.groupby('ticker') \
['shout_t'].shift()
</code></pre>
<p>Result:</p>
<pre><code>ticker t shout_t shout_tminus
A 2010-01-01 ... | python|pandas | 1 |
376,906 | 61,491,414 | How to search in dataframe by the list in python pandas | <p>I do have a dataframe and the list. </p>
<p>Dataframe: </p>
<pre><code>sg_name sg_id
abcd sg-123
efgh sg-234
ijkl sg-345
mnop sg-654
qrst sg-765
uvwx sg-875
</code></pre>
<p>List is </p>
<pre><code>prob = ['abcd','kjahgdf','qrst','kjahs','uvwx','kjhg', 'kjog', 'ijkl']
</code></pre>
<p>If the v... | <p>IIUC, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a></p>
<pre><code>only = df.loc[df['sg_name'].isin(prob), 'sg_id'].tolist()
</code></pre> | python|pandas|list|dataframe | 1 |
376,907 | 61,528,406 | Applying Function to Rows of a Dataframe in Python | <p>I have a dataframe and within 1 of the columns is a nested dictionary. I want to create a function where you pass each row and a column name and the function json_normalizes the the column into a dataframe. However, I keep getting and error 'function takes 2 positional arguments, 6 were given' There are more than 6 ... | <p>Just pass your column using axis=1</p>
<pre><code>df.apply(lambda x: fix_row_(x['my_column']), axis=1)
</code></pre> | python|pandas|function | 1 |
376,908 | 61,569,177 | Python, Take Multiple Lists and Putting into pd.Dataframe | <p>I have seen a variety of answers to this question <a href="https://stackoverflow.com/questions/30522724/take-multiple-lists-into-dataframe">(like this one)</a>, and have had no success in getting my lists into one dataframe. I have one header list (meant to be column headers), and then a variable that has multiple r... | <p>Given</p>
<pre><code>list1 = ['Rank', 'Athlete', 'Distance', 'Runs', 'Longest', 'Avg. Pace', 'Elev. Gain']
list2 = (['1', 'Jack', '57.4 km', '4', '21.7 km', '5:57 /km', '994 m'],
['2', 'Jill', '34.0 km', '2', '17.9 km', '5:27 /km', '152 m'],
['3', 'Kelsey', '32.6 km', '2', '21.3 km', '5:46 /km', '141 m'])
<... | python|pandas | 1 |
376,909 | 61,545,331 | How to change specific column to rows without changing the other columns in pandas? | <p>I have dataframe like this:</p>
<pre><code> Date ID Age Gender Fruits
1.1.19 1 50 F Apple
2.1.19 1 50 F Mango
2.1.19 1 50 F Orange
1.1.19 2 75 M Grapes
4.1.19 3 2... | <pre><code>pd.get_dummies(df, columns=['Fruits'], prefix='', prefix_sep='')
</code></pre>
<p>Update</p>
<pre><code>pd.get_dummies(df, columns=['Fruits'], prefix='', prefix_sep='').groupby('Date').max()
</code></pre> | python|pandas|group-by | 4 |
376,910 | 61,318,209 | Obtain the standard deviation of a grouped dataframe column | <p>I am trying to obtain the (sample) standard deviation of a column's values, grouped by another column in my dataframe.</p>
<p>To be concrete, I have something like this:</p>
<pre><code> col1 col2
0 A 10
1 A 5
2 A 5
3 B 2
4 B 20
2 B 40
</code></pre>
<p>And I ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <code>lambda function</code>:</p>
<pre><code>df['std']=df.groupby('col1')['col2'].transform(lambda x: x.std(skipna=True, ddof=1))
print... | python|pandas|numpy|pandas-groupby | 1 |
376,911 | 61,603,962 | Function not returning proper values (Python) | <p>I have a function below that should return standardized outputs based on numeric ranges:</p>
<pre><code>`def incident(count):
if count['incident_ct']<= 4:
val = 1
elif count['incident_ct']>4 & count['incident_ct']<= 13: # 25 to 50%
val = 2
elif count['incident_ct'] >13 & count['inciden... | <p>Let us try use <code>pd.cut</code></p>
<pre><code>pd.cut(intersections['incident_ct'],bins=[4,13,31,100,..],labels=[1,2,4,8,16])
</code></pre>
<p>Fix your code </p>
<pre><code>def incident(count):
... if count['incident_ct']<= 4:
... val = 1
... elif count['incident_ct']>4 and count['inciden... | python|pandas|if-statement | 1 |
376,912 | 61,318,147 | Image classification - how to make my results clearer? | <p>The Python code uses Tensor Flow and Keras to classify images of cars. 0 = not a car. 1 = a car. I am a bit confused about the results. My data set contains 1513 jpg images.The results don't seem to show 1513 readings? Furthermore, the results are not in order. For example the results go "0 0 0 0 1 0 0 0 " When in R... | <p>in your case, you are trying to do binary classification with one hot matrix for the label. compile your model using <code>categorical_crossentropy</code> instead of <code>binary_crossentropy</code> because your label in one hot form.</p>
<p>For better model, I suggest you to change the last layer using <code>1</co... | python|tensorflow|keras | 0 |
376,913 | 61,361,391 | How to convert a sql query to Pandas Dataframe and PySpark Dataframe | <pre><code>SELECT county, state, deaths, cases, count (*) as count
FROM table
GROUP BY county, state, deaths, cases
HAVING count(*)>1
</code></pre>
<p>I get the below data from the above query through <strong>SQL</strong>. What i want is convert this SQL Query in both</p>
<ul>
<li><p><em>Pandas</em></p>
</li>
<li... | <p>It will go like this:</p>
<pre><code>df = (spark
.table("table_name")
.groupBy(["county", "state", "deaths", "cases"])
.agg(F.count("*").alias("count_rows"))
.filter("count_rows > 1")
)
</code></pre>
<p>Also,... | python|sql|pandas|pyspark|databricks | 0 |
376,914 | 61,284,394 | Appending Multi-index column headers to existing dataframe | <p>I'm looking to append a multi-index column headers to an existing dataframe, this is my current dataframe.</p>
<pre><code>Name = pd.Series(['John','Paul','Sarah'])
Grades = pd.Series(['A','A','B'])
HumanGender = pd.Series(['M','M','F'])
DogName = pd.Series(['Rocko','Oreo','Cosmo'])
Breed = pd.Series(['Bulldog','Po... | <p>IIUC, you can do:</p>
<pre><code>newlevel = ['People']*4 + ['Dogs']*3 + ['Schools']*2
df.columns = pd.MultiIndex.from_tuples([*zip(newlevel, df.columns)])
</code></pre>
<p><strong>Note</strong> <code>[*zip(newlevel, df.columns)]</code> is equivalent to</p>
<pre><code>[(a,b) for a,b in zip(new_level, df.columns)]
... | python|python-3.x|pandas|dataframe | 1 |
376,915 | 61,513,099 | Identify and extract OHLC pattern on candlestick chart using plotly or pandas? | <p>I'm using the Ameritrade API and pandas/plotly to chart a simple stock price on the minute scale, I'd like to use some of the properties of the produced chart to identify and extract a specific candlestick pattern.</p>
<p>Here I build my dataframe and plot it as a candlestick:</p>
<pre><code>frame = pd.DataFrame({... | <p>Not sure about <code>Candlestick</code>, but in pandas, you could try something like this. <em>Note: I assume the data have 1 row for each business day already and is sorted.</em> The first thing is to create a column named red with True where the condition for a red candle as described in you question is True:</p>
... | python-3.x|pandas|plotly|finance|candlestick-chart | 0 |
376,916 | 61,605,116 | How can I write a function for empty cell in CSV file in Python? | <p>I am writing some programming using CSV file in Python. It will have some empty cells also. So when it reads empty cells, it should pass that cell and print the next cell. I have written this code:</p>
<pre><code>number = 1
while number < 50:
if data.D2[number] == "nan":
pass
else:
print ... | <p>Replace</p>
<p><code>if data.D2[number] == "nan":</code></p>
<p>with:</p>
<p><code>if data.D2[number] == "":</code></p> | python|python-3.x|pandas|numpy|csv | 0 |
376,917 | 61,430,590 | Set Multi-Index DataFrame values for each inner DataFrame | <p>I have a (very) large multi-indexed dataframe with a single boolean column. for example: </p>
<pre><code>bool_arr = np.random.randn(30)<0
df = pd.concat(3*[pd.DataFrame(np.random.randn(10, 3), columns=['A','B','C'])],
keys=np.array(['one', 'two', 'three']))
df['bool'] = bool_arr
df.index.rename(['Ind... | <p>you can <code>groupby.transform</code> the 'bool' column to get the third value with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.nth.html" rel="nofollow noreferrer"><code>nth</code></a>, then get the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/a... | python|pandas|dataframe | 1 |
376,918 | 61,410,970 | Get a frequency table for a column of lists | <p>Suppose I have the DataFrame where I have a column of lists.</p>
<pre><code>df = pd.DataFrame({'A': [['a', 'b', 'c'], ['b'], ['c'], ['a', 'b']]})
</code></pre>
<p>with the output</p>
<pre><code>Index A
0 ['a', 'b', 'c']
1 ['b']
2 ['c']
3 ['a', 'b']
</code></pre>
<p>How do I get a frequency ... | <p><code>map</code> to tuples, lists are not hashable as the error suggests:</p>
<pre><code>df.A.map(tuple).value_counts().rename_axis('A').reset_index(name='Count')
A Count
0 (a, b, c) 1
1 (a, b) 1
2 (b,) 1
3 (c,) 1
</code></pre> | python|pandas|python-2.7|dataframe | 2 |
376,919 | 61,531,627 | Tensorflow resume training with MirroredStrategy() | <p>I trained my model on a Linux operating system so I could use <code>MirroredStrategy()</code> and train on 2 GPUs. The training stopped at epoch 610. I want to resume training but when I load my model and evaluate it the kernel dies. I am using Jupyter Notebook. If I reduce my training data set the code will run but... | <p><code>new_model.evaluate()</code> and <code>compile = True</code> when loading the model were causing the problem. I set <code>compile = False</code> and added a compile line from my original script.</p>
<pre><code>mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
new_model =... | python|tensorflow|machine-learning|jupyter-notebook|multi-gpu | 0 |
376,920 | 61,293,508 | Count how many rows are needed to add up to a value | <p>I have a Dataframe</p>
<pre><code>Acc_Name gb
ABC 76
DEF 67
XYZ 50
RES 43
FEG 22
HTE 0
DGE 0
</code></pre>
<p>The sum of GB column is 258 and its 80% is 206.4</p>
<p>I want the count, how many rows if summed from top are less th... | <p>You want <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a> for this:</p>
<pre><code>df.gb.cumsum().lt(206.4).sum()
# 3
</code></pre>
<p>To do it all in one go:</p>
<pre><code>df['gb'].cumsum().div(df['gb'].sum()).le(... | python|pandas | 3 |
376,921 | 61,213,493 | PyTorch LSTM for multiclass classification: TypeError: '<' not supported between instances of 'Example' and 'Example' | <p>I am trying to modify the code in this <a href="https://github.com/bentrevett/pytorch-sentiment-analysis/blob/master/2%20-%20Upgraded%20Sentiment%20Analysis.ipynb" rel="nofollow noreferrer">Tutorial</a> to adapt it to a multiclass data (I have 55 distinct classes). An error is triggered and I am uncertain of the roo... | <p>The <code>BucketIterator</code> sorts the data to make batches with examples of similar length to avoid having too much padding. For that it needs to know what the sorting criterion is, which should be the text length. Since it is not fixed to a specific data layout, you can freely choose which field it should use, ... | python|pytorch|lstm|multiclass-classification | 6 |
376,922 | 61,596,245 | Problem regarding translation googletrans library | <p>I am kinda of new in this domain, and i have a couple of questions. But let`s discuss the subject first :D So i got an csv file which i want to translate. I used the following code </p>
<pre><code>pip install contractions
pip install googletrans
import pandas as pd
import os
import from google.colab import drive... | <p>try providing src and dest parameters in translate method.</p>
<pre><code>from googletrans import Translator
t = Translator()
t.translate(word, src='en', dest='fr').text
</code></pre>
<p>or you might runout of number of request allowed on a single day. ( nearly 850 request can be made )</p> | python|python-3.x|pandas|google-translate|google-translation-api | 0 |
376,923 | 61,198,401 | np.where multiple condition on multiple columns | <p>I have a 2D array and a working code with np.where() condition on one column. I need to enhance this code by adding one more condition by adding an extra filter.</p>
<p>for an array like this:</p>
<pre><code>array([[ 1, 2, 3],
[ 11, 22, 33],
[101, 202, 303],
[100, 200, 303],
[111... | <p>Using logical_and explicitly, then recasting to 'not' is another possibility.</p>
<pre><code>w = np.logical_and(a[:, 2] == 303, a[:, 1] == 200)
a[~w]
array([[ 1, 2, 3],
[ 11, 22, 33],
[101, 202, 303],
[111, 222, 333]])
</code></pre> | python-3.x|numpy|numpy-ndarray | 2 |
376,924 | 61,606,799 | Plotting Results from For Iteration | <p>I am new to <code>python</code> and I want to ask how to plot a figure from <code>for</code> loop iteration? </p>
<p>Here is the code!</p>
<pre><code>import numpy as np #numerical python
import matplotlib.pyplot as plt #python plotting
from math import exp #exponential math directory
T_initial = 293
T_reference = ... | <p>You can plot the data like this:</p>
<pre><code>for i in T_reference:
R1_refe = R1_initial*exp(Beta*((1/i)-(1/T_initial)))
Rs = (R2_initial/(R2_initial+ R1_refe)) - (R4_initial/(R3_initial+R4_initial))
Vo = Vin*Rs
Vo_round = round(Vo, 3)
plt.scatter(i, Vo_round)
plt.show()
</code></pre>
<p>Is t... | python|numpy|matplotlib | 1 |
376,925 | 61,386,530 | How to sum over a Pandas dataframe conditionally | <p>I'm looking for an efficient way (without looping) to add a column to a dataframe, containing a sum over a column of that same dataframe, filtered by some values in the row. Example:</p>
<p>Dataframe:</p>
<pre><code>ClientID Date Orders
123 2020-03-01 23
123 2020-03-05 10
123 ... | <p>I'll assume your dataframe is named <code>df</code>. I'll also assume that dates aren't repeated for a given <code>ClientID</code>, and are in ascending order (If this isn't the case, do a groupby sum and sort the result so that it is).</p>
<p>The gist of my solution is, for a given ClientID and Date. </p>
<ol>
<l... | python|pandas|sum|conditional-statements|data-science | 1 |
376,926 | 61,314,443 | What's the best way to compute row-wise (or axis-wise) dot products with jax? | <p>I have two numerical arrays of shape (N, M). I'd like to compute a row-wise dot product. I.e. produce an array of shape (N,) such that the nth row is the dot product of the nth row from each array. </p>
<p>I'm aware of numpy's <code>inner1d</code> method. What would the best way be to do this with jax? jax has <cod... | <p>You can try <a href="https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.einsum.html" rel="nofollow noreferrer">jax.numpy.einsum</a>. Here the implementaion using numpy einsum</p>
<pre><code>import numpy as np
from numpy.core.umath_tests import inner1d
arr1 = np.random.randint(0,10,[5,5])
arr2 = np.random.... | numpy|linear-algebra|jax | 2 |
376,927 | 61,183,553 | How to count the most popular value from multiple value pandas column | <p>i have such a problem:</p>
<p>I have pandas dataframe with shop ID and shop cathegories, looking smth like that:</p>
<pre><code> id cats
0 10002718 182,45001,83079
1 10004056 9798
2 10009726 17,45528
3 10009752 64324,17
4 1001107 44607,83520,76557
... .... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><code>Series.explode</code></a... | python|pandas | 1 |
376,928 | 61,260,207 | Selectively multiply elements of a dataframe for a number on the basis of the matching between index and columns | <p>Suppose we have a dataframe df of dimension nxn with two different index level, identical for rows and columns. I need to multiply selectively some elements of df on the basis of the matching between the index of rows and the index of columns.</p>
<p>here an example to clarify the question:</p>
<pre><code>df = pd.... | <p>This is rather manual, but will do:</p>
<pre><code>offsets = [i + (df.columns.get_level_values(i).values[:,None] != df.index.get_level_values(i).values)
for i in range(2)]
# output:
df.mul(offsets[0]*2 + offsets[1])
</code></pre>
<p>Output:</p>
<pre><code> A B C
1 2 ... | python|pandas|dataframe | 3 |
376,929 | 61,511,651 | Using a function to create a data-frame column | <p>I have a dataframe called <code>df</code> that looks like:</p>
<pre><code> dept ratio higher lower
date
01/01/1979 B 0.522576565 2 1
01/01/1979 A 0.940614079 2 2
01/01/1979 C 0.873957946 0 1
01/01/1979 B 0.087828824 0 2... | <p>It's rather straight-forward:</p>
<pre><code>counts = df.groupby('dept')['dept'].transform('count')-1
df['compared'] = (df['higher']-df['lower'])/counts
# to avoid possible division by zero warning
# also to match `counts>0` condition
# use this instead
# df.loc[counts>0,'compared'] = df['higher'].sub(df['l... | python|pandas | 2 |
376,930 | 61,456,826 | How to plot a resampled pandas series? | <p>I have a simple dataframe, just <code>date</code> column and <code>amount</code> column:</p>
<pre><code> local_date amount
48 2020-01-01 30.00
464 2020-01-01 1.49
465 2020-01-01 22.45
469 2020-01-01 7.49
472 2020-01-01 19.17
473 2020-01-01 49.37
475 2020-01-01 7.72
481 2020-01-01 59.98
482 2... | <p>I would go this way.</p>
<p>Data</p>
<p>Coerce Date to datetime</p>
<pre><code>df['local_date']=pd.to_datetime(df['local_date'])
</code></pre>
<p>Groupby date and calculate sum of amount per date</p>
<pre><code>df.groupby(df.index.date)['amount'].sum().reset_index().plot()
</code></pre> | python|pandas | 0 |
376,931 | 61,533,060 | How do I apply the "coin changing problem" to a pandas dataframe? | <p>The following problem is often called by several names, and has plenty of literature available. Unfortunately, I'm a little new to Python, and could use a little help applying the solution to my case. </p>
<p>I have a pandas dataframe containing ~40,000 rows, so optimization is probably a factor. The dataframe cont... | <p>When you have your amounts (that add up to 11.72) as a list, for example obtained as a result of:</p>
<pre><code>def subset_sum(numbers, target, partial=[]):
s = sum(partial)
if s == target:
return partial
if s > target:
return None # if we reach the number why bother to continue
... | python|pandas|dataframe | 0 |
376,932 | 61,536,921 | why i am geeting an attribute error in pandas? | <pre><code>from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
np.random.seed(0)
iris = load_iris()
print(iris)
df = pd.DataFrame(iris.data, columns = iris.feature_names)
df.head()
df['species'] = pd.categorical.from_codes(iris.target, iri... | <p>You need to write it with a capital C:</p>
<pre><code>df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
</code></pre> | python|pandas | 0 |
376,933 | 61,314,193 | Pandas Drop function for two columns not working | <p>I am trying to drop two columns using Pandas Drop function. However, I am receiving error.
FYI I have printed column names of the data-frame. Why am I receiving such error?</p>
<p>In [284]:
Fulldf.columns</p>
<pre><code>Out[284]:
Index(['PID', 'YearBuilt', 'YearRemodel', 'VeneerExterior', 'BsmtFinTp',
... | <p>You are mixing single quotes and double-quotes. Can you try this?</p>
<pre><code>print(f"Total number of input variables to preprocess: {Fulldf.drop(['SalePrice', 'PID'], axis=1).shape[1]}")
</code></pre> | python|pandas|dataframe|data-analysis|drop | 3 |
376,934 | 61,584,934 | predicting own image with model trained with MNIST dataset | <p>I trained a model with the keras mnist dataset for handwriting digit recognition and it has an accuracy of 98%. But when it comes to my own image, the performance is poor. I suppose it has something to do with the preprocessing of my own image.
here's how I try to convert the image to 28*28 size.</p>
<pre><code>im... | <p>Try using opencv for reading the image.</p>
<pre><code>import cv2
image = cv2.imread(f'screenshots/screenshot0.png',0)
image = cv2.resize(image, (28,28))
data = np.asarray(image)/255.0
</code></pre> | tensorflow | 0 |
376,935 | 61,262,816 | Numpy: Insert value in 2d with 2 x 1d using fancy indexing | <p>I would like to fancy indexing given an array with row / column indices.
I have an array with column numbers (column index) which I have extracted from an <code>argmax</code> function, </p>
<p>With this, I would like to turn a zero 2D matrix into 1 (or True) for the index correspond to this column index. The rows g... | <p>It would sound a bit naive, but intuitively, I would find all possible combination of indices first.</p>
<pre><code>matrix1 = np.zeros((5, 10))
row = np.array([0,1,2,3,4])
column = np.array([9,9,2,3,9,2,1,3,3,1])
index = np.stack(np.meshgrid(row,column), -1).reshape(-1,2)
matrix1[index[:,0], index[:,1]] = 1
</cod... | python|arrays|numpy|matrix|indexing | 1 |
376,936 | 61,259,014 | Pandas Multiple String Columns to a List of Integers | <p>I have a dataframe <code>df</code> like this where both columns are <code>object</code>.</p>
<pre><code> +-----+--------------------+--------------------+
| id | col1 | col2 |
+-----+--------------------+--------------------+
| 1 | 0,1,4,0,1 | 1,2,4,0,0 ... | <p>I think you want:</p>
<pre><code>(df['col1'] + ',' + df['col2']).apply(lambda row: [int(s) for s in row.split(',')])
</code></pre>
<p>Output:</p>
<pre><code>0 [0, 1, 4, 0, 1, 1, 2, 4, 0, 0]
dtype: object
</code></pre> | python|pandas | 5 |
376,937 | 61,351,625 | Is there a faster alternative to np.where for determining indeces? | <p>I have an array like this:</p>
<p><code>arrayElements = [[1, 4, 6],[2, 4, 6],[3, 5, 6],...,[2, 5, 6]]</code></p>
<p>I need to know, for example, the indices where an arrayElements is equal to 1.</p>
<p>Right now, I am doing:</p>
<p><code>rows, columns = np.where(arrayElements == 1)</code></p>
<p>This works, but... | <p>So you are generating thousands of arrays like this:</p>
<pre><code>In [271]: [(i,np.where(arr==i)[0]) for i in range(1,7)]
Out[271]:
[(1, array([0])),
(2, array([1, 3])),
(3, array([2])),
(4, array([0, 1])),
(5, array([2, 3])),
(6, array([0, 1, 2, 3]))]
</code>... | python|numpy | 3 |
376,938 | 61,299,440 | Binary Logistic Regression - do we need to one_hot encode label? | <p>I have a logistic regression model which I created referring this <a href="https://stackoverflow.com/questions/56907971/logistic-regression-using-tensorflow-2-0">link</a></p>
<p>The label is a Boolean value (0 or 1 as values).</p>
<p>Do we need to do one_hot encode the label in this case?</p>
<p>The reason for as... | <p>In case of binary logistic regression, you don't required one_hot encoding. It generally used in multinomial logistic regression.</p> | tensorflow|machine-learning|label|one-hot-encoding | 1 |
376,939 | 61,230,762 | With ResNet50 the validation accuracy and loss is not changing | <p>I am trying to do image recognition with <code>ResNet50</code> in Python (<code>keras</code>). I tried to do the same task with <code>VGG16</code>, and I got some results like these (which seem okay to me):
<a href="https://i.stack.imgur.com/Sq1Ju.png" rel="nofollow noreferrer">resultsVGG16</a> . The training and va... | <p>There is no mistake in your Model but this might be the issue with <code>ResNet</code> as such, because there are many issues raised, <a href="https://github.com/fchollet/deep-learning-models/issues/96" rel="nofollow noreferrer">1</a>,<a href="https://github.com/keras-team/keras/issues/8672" rel="nofollow noreferrer... | python|tensorflow|keras|resnet|conv-neural-network | 4 |
376,940 | 61,298,195 | how to expand 2-dim arrays by using maclaurin series? | <p>I am trying to feed the pixel vector to the convolutional neural network (CNN), where the pixel vector came from image data like cifar-10 dataset. Before feeding the pixel vector to CNN, I need to expand the pixel vector with maclaurin series. The point is, I figured out how to expand tensor with one dim, but not ab... | <p>If I understand correctly, each <code>x</code> in the provided computational graph is just a scalar (one channel of a pixel). In this case, in order to apply the transformation to each pixel, you could:</p>
<ol>
<li>Flatten the 4D <code>(b, h, w, c)</code> input coming from the convolutional layer into a tensor of ... | python|tensorflow | 3 |
376,941 | 61,414,126 | Accelerate assigning of probability densities given two values in Python 3 | <p>For some of my research, I need to assign a probability density given a value, a mean, and a standard deviation, except I need to do this about 40 million times, so accelerating this code is becoming critical to working in a productive fashion. </p>
<p>I have only 10 values to test (values = 10x1 matrix), but I wan... | <p>You can avoid the inner loop as <code>scipy.stats.truncnorm</code> can be defined as a vector of random variables i.e.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from scipy.stats import truncnorm
all_probabilities = []
a, b = 0, np.inf
error = 0.05
for row in all_means:
alpha, bet... | python|numpy|scipy | 1 |
376,942 | 61,421,190 | how to check string contains any word from dataframe colum | <p>i am trying to find pandas column all the cell value to particular string how do I check it?</p>
<p>there is one dataframe and one string, want to search entire df column into string, it should return matching elements from column</p>
<p>looking for solution like in MySQL </p>
<pre><code>select * from table where... | <p>Finally I did this using "import pandasql as ps"</p>
<pre><code>query = "SELECT area,office_type FROM my_df_main where 'asasa sdsd sachapir street sdsds ffff' like '%'||area||'%'"
tmp_df = ps.sqldf(query, locals())
</code></pre> | python|pandas | 0 |
376,943 | 61,285,327 | Is it possible to shorten individual columns in pandas dataframes? | <p>I am working with a 1000x40 data frame where I am fitting each column with a function.
For this, I am normalizing the data to run from 0 to 1 and then I fit each column by this sigmoidal function,</p>
<pre><code>def func_2_2(x, slope, halftime):
yfit = 0 + 1 / (1+np.exp(-slope*(x-halftime)))
return yfit
#... | <p>This has to do with the use of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.values.html" rel="nofollow noreferrer">pd.Series.values</a>, which will give you an <code>np.ndarray</code> instead of a <code>pd.Series</code>.</p>
<p>A conservative change to your code would move the u... | python|pandas | 0 |
376,944 | 61,236,354 | How to drop duplicates in csv by pandas library in Python? | <p>I've been looking around tried to get examples but can't get it work the way i want to.</p>
<p>I want to dedupe by 'OrderID' and extract duplicates to seperate CSV.
Main thing is I need to be able to change the column which I want to dedupe by, in this case its 'Order ID'. </p>
<p>Example Data set:</p>
<blockquot... | <p>You can achieve this by creating a new dataframe with value_counts(), merging and than filtering.</p>
<pre><code># value_counts returns a Series, to_frame() makes it into DataFrame
df_counts = df['OrderID'].value_counts().to_frame()
# rename the column
df_counts.columns = ['order_counts']
# merging original on col... | python|pandas | 1 |
376,945 | 61,497,090 | How to slice starting from negative to a positive index or the opposite | <p>Numpy cannot perform the following indexing:</p>
<pre><code>a = np.arange(10)
a[-2: 2]
</code></pre>
<p>I'm doing it in a not very elegant way at the moment, is there a trick or oneliner to get that?</p>
<p>EDIT: Notice that I don't know if I'm facing this scenario in my code, it does happen sometimes, so I'm lo... | <pre><code>In [71]: slicer(np.arange(10),-2,2)
Out[71]: array([8, 9, 0, 1])
</code></pre>
<p>It looks like <code>np.r_</code> does the kind of 'roll' that you want:</p>
<pre><code>In [72]: np.arange(10)[np.r_[-2:2]] ... | python|numpy | 2 |
376,946 | 61,218,313 | can I inherit *everything* from pandas (methods, functions, read_csv, etc etc etc etc) | <p>suppose I create a class with my own custom functions. I also want this class to inherit everything from Pandas. </p>
<pre><code>class customClass(pandas.Dataframe):
def my_func(x,y):
return x+y.
</code></pre>
<p>instantiating</p>
<pre><code>a = customClass()
</code></pre>
<p>typing "a." + tab I se... | <p>See the <a href="https://pythonspot.com/pandas-read-csv/" rel="nofollow noreferrer">Python tutorial</a></p>
<p>The most important thing to notice for your specific question is that <code>read_csv</code> is <em>not</em> a method of <code>DataFrame</code>. When you use that method, you call</p>
<pre><code>pd.read_c... | python|pandas|oop|decorator | 0 |
376,947 | 61,436,313 | Vectorized column-wise regex matching in pandas | <h1>Part I</h1>
<p>Suppose i have a data set df like below:</p>
<pre><code>x | y
----|--------
foo | 1.foo-ya
bar | 2.bar-ga
baz | 3.ha-baz
qux | None
</code></pre>
<p>I want to filter the rows where y contains x exactly in the middle (not beginning nor end, i.e. matching the pattern '^.+\w+.+$', hitting row ... | <p>Is this the way you wanted? Pretty much replicated what you did in R:</p>
<pre class="lang-py prettyprint-override"><code>>>> from numpy import vectorize
>>> from pipda import register_func
>>> from datar.all import f, tribble, filter, grepl, paste0, mutate, sub, as_numeric
[2021-06-24 17:... | r|regex|pandas|dplyr|vectorization | 1 |
376,948 | 68,611,927 | How to define loss function in Tensorflow [Optimization problem]? | <p>I'm trying to define a loss function and experiencing difficulties with that. Maybe someone can help me.</p>
<p>I have N data points for <code>x_i</code> and <code>y_i</code> and I want to fit a straight line (for simplicity) under the following condition:</p>
<p><a href="https://i.stack.imgur.com/hvfvu.png" rel="no... | <p>It sounds like you are using Tensorflow 1.x API since you mentioned using <code>tf.placeholder</code> and <code>sess.run</code>, so I have provided the solution using the Tensorflow 1.x API from Tensorflow 2.x. If you want to run in Tensorflow 1.x, just remove <code>compat.v1</code>.</p>
<pre><code> tf_x = tf.com... | python|tensorflow|optimization|regression|loss-function | 1 |
376,949 | 68,762,000 | How to sort a Python DataFrame by second element of list | <p>So the title is a bit confusing but essentially, I have a Dataframe with two columns, one for the the character ("c") and one for the character's coordinates ("loc"). I would like to sort the dataframe by the Y coordinate. So far i have managed to sort the dataframe by the X cooridate using the s... | <p>Use <code>key</code> parameter in <code>sort_values</code>:</p>
<pre><code>df.sort_values(by ='loc', key=lambda x: x.str[1])
</code></pre>
<p>Output:</p>
<pre><code> c loc
0 i [1, 2]
2 d [4, 2]
1 a [3, 3]
3 m [3, 5]
</code></pre> | python|pandas|dataframe|sorting | 3 |
376,950 | 68,634,789 | Why does xarray DataArray only contain NaNs after combining it with a xarray DataSet? | <p>I want to create daily histograms from a pandas Dataframe (df) and export them to xarray to combine it with another Dataset (data). When I create the DataArray I can access it without problems, but once I combine it with the Dataset the array I added only consists of nan-entries. I think I made sure that all coordi... | <p>Oh ok, the problem was with the spatial coordinates apparently. This fixed it:</p>
<pre><code>longitude=(['longitude'], data.longitude.values),
latitude=(['latitude'], data.latitude.values),
</code></pre> | python|pandas|nan|python-xarray | 0 |
376,951 | 68,809,160 | How to apply a predefined function to entire dataframe without grouping | <p>I am using pandas to get some summary reporting on percentage difference comparing with <code>new_conversions</code> vs. <code>old_conversions</code></p>
<p>input table: <code>df</code></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">version</th>
<th style="text... | <p>Is it what you expect?</p>
<pre><code>conv = round((df['new_conversions'].sum() - df['old_conversions'].sum())
/ df['old_conversions'].sum(), 3)
df2 = pd.DataFrame({'conversion_diff': [conv]}, index=['All')
out = pd.concat([df1, df2])
</code></pre>
<pre><code>>>> out
conversion_diff
... | pandas|dataframe|aggregate | 0 |
376,952 | 68,621,972 | How to remove the name "Queryset" from queryset data that has been retrieved in Django Database? | <p>we all know that if we need to retrieve data from the database the data will back as a queryset but the question is How can I retrieve the data from database which is the name of it is queryset but remove that name from it.</p>
<p>maybe I can't be clarified enough in explanation so you can look at the next example t... | <p>You don't have to change it from a Queryset to anything else; <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame" rel="nofollow noreferrer">pandas.DataFrame</a> can take any Iterable as data. So</p>
<pre><code>df = pandas.DataFrame(djangoapp.models.Model.object... | django|pandas|django-queryset | 3 |
376,953 | 68,550,740 | Python pandas regex from google sheets | <p>i am trying to covert a google sheet regextract to python, either with using pandas or re.</p>
<p>new Google sheet column:</p>
<pre><code>=ArrayFormula(REGEXEXTRACT(F2,"([A-Z]+\-[0-9]+)"))
</code></pre>
<p>I am not sure how to apply it to the entire column, here was my attempt which resulted in error</p>
... | <p><code>re</code> is package from <code>python</code> and if you would like do within <code>pandas</code></p>
<pre><code>df["newcol"] = df["oldcol"].str.extract(r'([A-Z]+\-[0-9]+)')
</code></pre> | python|pandas | 3 |
376,954 | 68,752,184 | Dataframe replace string with a word and set other rows as NULL using Python pandas | <p>I have a dataframe in python, want to replace Fri as this friday and the rest of the rows in that colume as NULL
<a href="https://i.stack.imgur.com/kt62l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kt62l.png" alt="enter image description here" /></a></p>
<p>Use this code will replace all the r... | <p>try via <code>map()</code>:</p>
<pre><code>df['date']=df['date'].map({'Fri':this_firday})
</code></pre>
<p>OR</p>
<p>via <code>loc</code>:</p>
<pre><code>df.loc[(df['date'] == 'Fri'), 'date'] = this_firday
df.loc[(df['date'] != 'Fri'),'date']=float('NaN')
</code></pre>
<p>OR</p>
<p>you can also use <code>np.where()<... | python|python-3.x|pandas|dataframe | 1 |
376,955 | 68,775,920 | I want to produce a loop to find groupby mean for multiple columns | <p>I'm working with the following dataframe, called 'data':</p>
<pre><code>print (data)
local_authority data_2016 data_2017 data_2018
0 Hartlepool 1 4 8
1 Hartlepool 3 6 7
2 Hartlepool 4 8 5
3 Tower Hamlets ... | <pre><code>data.groupby('local_authority').mean()
</code></pre>
<p>should do it</p> | python|numpy|loops | 1 |
376,956 | 68,671,110 | Decode and convert Marketo API response to DataFrame | <p>I have been stumped by this problem for 2 days and any help would be appreciated. I can't seem to find a way to decode/convert a response I am getting back from the Marketo API into a Pandas dataframe. Any help would be greatly appreciated. These are the steps I am taking and the sample responses:</p>
<p><stron... | <p>First, the step you already finished is decoding the string:</p>
<pre><code>data = res.content.decode()
</code></pre>
<p>Split the data on the <code>\n</code>'s:</p>
<pre><code>data = data.split()
</code></pre>
<p>For each line, split the comma-separated elements:</p>
<pre><code>data = [elem.split(',') for elem in d... | python|pandas | 1 |
376,957 | 68,745,794 | Model decay in pandas data frame | <p>I have the following pandas data frame:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">user</th>
<th style="text-align: left;">day</th>
<th style="text-align: right;">value</th>
<th style="text-align: right;">value_cumulative</th>
</tr>
</thead>
<tbody>
<tr>
<t... | <p>Managed to solve this with a function that implements a simple loop of the following type for decay_v1:</p>
<pre><code> decay_v1 = value.copy()
# Replace all values except the first one, which is our starting point.
for i in range(1, len(value)):
decay_v1[i] = value[i] + 0.1 * decay_v1[i-1]
</code></pre>... | python|pandas|dataframe | 1 |
376,958 | 68,814,092 | Create sparse dataframe from a pandas dataframe with list values | <p>I have a pandas Dataframe of id, dates, and payments arranged like below. dates are recorded in months and correspond to the payments of the same index in the row.</p>
<pre><code>ID Dates payments
A ['02-2010','05-2010'] [45,50]
B ['02-2010','04... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>
# transform dates, payments to python list
#from ast import literal_eval
#df["Dates"] = df["Dates"].apply(literal_eval)
#df["payments"] = df["payments"].apply(literal_eval)
df = df.explode(["Dates", "... | python|pandas|dataframe | 2 |
376,959 | 68,547,647 | Is there a way to delete unused files from PyTorch to run a light version of it? | <p>Hi I am trying to upload a zip archive of required libraries to run my project on AWS Lambda. Since the size of the zipped PyTorch library exceeds the size limit of AWS Lambda, I am looking to decrease the number of files I upload from the library.</p>
<p>I have a trained neural network and I need PyTorch just to ca... | <p>a walk around would be using Lambda support for EFS. You could prestage your dependencies to a folder structure in EFS and then point the lambda to run there. You should then be able to import the pytorch and any other packages you place as subdirectories under the working directory.</p> | python|amazon-web-services|aws-lambda|neural-network|pytorch | 0 |
376,960 | 68,468,985 | Specify single bar label color in simple pandas/matplotlib “barh” plot with one column | <p>I want to change the label color of a single bar label in a pandas plot but somehow end up changing all label colors:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 150
columns = ["Foo"]
data = [10.0, 201, 279]
index=["Item 1", "Item 2"... | <p><code>ax.bar_label</code> returns a list of <code>Text</code> instances for the labels corresponding to heights of bars, we can store these <code>Text</code> instances in a variable then use indexing to select the <code>Text</code> instance for which you wish to change the color</p>
<pre><code>tboxes = ax.bar_label(... | python|pandas|matplotlib | 1 |
376,961 | 68,593,730 | Replacing values in one array with corresponding values in another array, using Numpy | <p>This has probably been asked before but I couldn't find anything. Is there a efficient way to replace entries in one array with another conditionally?</p>
<p>For example, lets say I have 2 images (3d arrays - (x,y,3)).
Lets say I want to replace the pixel value in the first array with the one in the second array, so... | <p>np.where might work:</p>
<pre><code>arr1 = np.where(arr1 == some_given_rgb_trio, arr1, arr2)
</code></pre>
<p>Example with gradient images:</p>
<pre><code>a = np.linspace(0, 255, 256*256*3).reshape(256,256,3).astype(np.uint8)
b = np.rot90(a,1)
c = np.where(a < (50,50,50), a, b)
plt.imshow(c)
plt.show()
</code>... | python|arrays|numpy | 0 |
376,962 | 68,869,434 | Create an pandas column if a string from a list matches from another column | <p>I have a pandas dataframe which is similar to the follow but a lot bigger and complicated.</p>
<pre><code>import pandas as pd
d = {'weight': [70, 10, 65, 1], 'String1': ['Labrador is a dog',
'Abyssinian is a cat',
'German Shepard is a dog',
'pigeon is a bird']}
df = pd.DataFrame(data=d)
df
</code></pre>
<p>Output</p... | <p>Here is one way to do it which leverages the built-in <a href="https://docs.python.org/3/library/functions.html#next" rel="nofollow noreferrer"><code>next</code></a> function and its <code>default</code> argument:</p>
<pre class="lang-py prettyprint-override"><code>In [7]: df["animal"] = df["String1&q... | python|pandas | 2 |
376,963 | 68,519,118 | Custom GAN training loop using tf.GradientTape returns [None] as gradients for generator while it works for discriminator | <p>I am trying to train a GAN. Somehow the gradient for the generator returns None even though it returns gradients for the discriminator. This leads to <code>ValueError: No gradients provided for any variable: ['carrier_freq:0'].</code> when the optimizer applies the gradients to the weights (in this case just a singl... | <p>I think this is because you have not called the generator inside the <code>GradientTape()</code>. As discriminator has been called twice (within <code>with tf.GradientTape(persistent=True) as tape:</code>, you should call <code>generator</code> as well. (say such as <code>generator(noise, training=True)</code>. This... | python|tensorflow|deep-learning|generative-adversarial-network|gradienttape | 1 |
376,964 | 68,490,483 | Pandas to BigQuery upload fails due to InvalidSchema error | <p>I'm using Pands to_gbq to append a dataframe to a big query table as I have done successfully in the past using this (I only explicitly declared one field in the schema so it would recognize it as a date, otherwise it forced it to be a string):</p>
<pre><code>schema = [{'name': 'Week', 'type': 'DATE'}]
def load_to_... | <p>Pandas has different data types than bigquery. Specifically, while bigquery supports <a href="https://cloud.google.com/bigquery/docs/schemas#standard_sql_data_types" rel="nofollow noreferrer"><code>DATE, DATETIME, TIME, and TIMESTAMP</code></a>, <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/times... | python|pandas|dataframe|google-bigquery | 1 |
376,965 | 68,669,062 | Pandas read_xml and SEPA (CAMT 053) XML | <p>Recently I wanted to try the newly implemented xml_read function within pandas. I thought about testing the feature with SEPA camt-format xml. I'm stuck with the functions parameters, as I'm unfamiliar with the lxml logic. I tried pointing to the transactions values as rows ("Ntry" tag), as I thought this ... | <p>The bank statement is not a shallow xml, thus not very suitable for pandas.read_xml (as indicated in the <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_xml.html" rel="nofollow noreferrer">documentation</a>).</p>
<p>Instead I suggest to use <a href="https://pypi.org/project/sepa/" rel="nofollow nor... | python-3.x|pandas|xml|xml-parsing | 1 |
376,966 | 68,473,592 | Bert using transformer's pipeline and encode_plus function | <p>when I use:</p>
<pre><code>modelname = 'deepset/bert-base-cased-squad2'
model = BertForQuestionAnswering.from_pretrained(modelname)
tokenizer = AutoTokenizer.from_pretrained(modelname)
nlp = pipeline('question-answering', model=model, tokenizer=tokenizer)
result = nlp({'question': question,'context': context})
</c... | <p>The reason for getting an error in the second code is that the input data does not fit in the pytorch tensor. For this you have to set truncation flag as True when calling the tokenizer. Thus, when data that will not fit in the tensor arrives, it only takes as much as it fits. i.e:</p>
<pre><code>tokenizer = AutoTok... | python|nlp|bert-language-model|huggingface-transformers|nlp-question-answering | 0 |
376,967 | 68,748,648 | Read Excel file in python with the same format as the Excel file | <p>I would like to read an Excel file in Python, with the data in the exact same format as the Excel file.</p>
<p>I have an Excel file with some columns with an int format i.e 2,000. Others with float format, i.e 1,999.52. And another column with dates in "long format", i.e 12-31-2020 is written as Thursday, ... | <p>Probably the easiest way to do what you want is to read the data normally, then save it back to the original data type at the end.</p> | python|python-3.x|excel|pandas|openpyxl | 1 |
376,968 | 68,513,467 | Create a for Loop on a multiple regression utilizing Pandas (StatsModels) | <p>I am performing a multiple regression for 50 states to determine the life expectancy per state based on several variables. Currently I have my dataset filtered to only Maine, and I want to know if there is a way to create a For Loop to go through the whole State Column and perform a regression for each state. This... | <pre><code>###### Assuming rest of your code is ok I am sharing a strategy for the loop and storing model outputs:
pd.set_option('display.max_columns', None)
state_modelfit_summary = {}
states = df['State'].unique() # As you only need to loop once for each state
for st in states:
dfME = df[(df['State'] == st)] ... | python|pandas|for-loop|linear-regression | 0 |
376,969 | 68,603,949 | Python: Apply function every 100 rows of large dataframe | <p>I have a large dataset of approximately 25,000 rows. I am trying to extract elevation data for every one of my observations. However, I can only make 100 requests at a time. This means that I need approximately 250 splits to make individual requests!</p>
<p>I was wondering if there is an efficient way of doing this?... | <p>You could create a series that only increments every 100 values and use that to group the dataframe. I'm using a smaller example to fit on screen and showing a few processing options.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({"FOO":list(range(50))})
# using each group
for id... | python|pandas|dataframe|for-loop|split | 1 |
376,970 | 68,774,521 | Concatenate large data frames horizontally | <p>I have multiple (15) large data frames, where each data frame has two columns and is indexed by the date. All the data frames are approximately the same length and span the same date range. I would like to merge them horizontally (so no new rows are added). I tried <code>df_final = pd.concat(frames, axis = 1)</code>... | <p>If the data is aligned, you can try using the <code>ignore_index=True</code> parameter. This will skip the step of aligning the data. If the data is not aligned, I doubt you can increase much the speed…</p> | python|pandas|dataframe | 1 |
376,971 | 68,554,897 | Getting the index of datetime function within Numpy Python | <p>The code down below finds the index of <code>newdates</code> within <code>Setups</code> with the <code>init_location</code> function. Then I increment the index by one to get the next date. But I cannot add to the <code>init_location</code> function. How would I be able to do that and get the expected value?</p>
<pr... | <p>becuase <code>init_location</code> is a tuple, you cannot add "1" directly . Instead use the following format.</p>
<pre><code>print("init location: ", Setups[init_location],"Address right after: ",Setups[init_location[0]+1])
</code></pre> | arrays|python-3.x|numpy|datetime|indexing | 0 |
376,972 | 68,498,083 | Recursively update the dataframe | <p>I have a dataframe called <strong>datafe</strong> from which I want to combine the hyphenated words.</p>
<p>for example input dataframe looks like this:</p>
<pre><code>,author_ex
0,Marios
1,Christodoulou
2,Intro-
3,duction
4,Simone
5,Speziale
6,Exper-
7,iment
</code></pre>
<p>And the output dataframe should be like:... | <p>Another option:</p>
<p><strong>Given/Input:</strong></p>
<pre><code> author_ex
0 Marios
1 Christodoulou
2 Intro-
3 duction
4 Simone
5 Speziale
6 Exper-
7 iment
</code></pre>
<p><strong>Code:</strong></p>
<pre><code>import pandas as pd
# read/open file or ... | pandas|dataframe|recursion|data-processing | 1 |
376,973 | 68,651,869 | How to find if two dots on a graph intersect | <p>I'm working on a project where there are four turtles in the middle of a circle, and they each follow a random path until one of them gets out. The last part is that if two or more turtles bump into each other, they go two steps back towards the center. I have everything except that, and I'm not sure how to proceed.... | <pre><code>turtles = [(x, y), (x1, y1), (x2, y2), (x3, y3)]
for index, turtle1 in enumerate(turtles):
for index2, turtle2 in enumerate(turtles):
if index == index2:
continue
if turtle1 == turtle2:
pass # go tow steps to the middle
</code></pre> | python|numpy|graphing | 0 |
376,974 | 68,777,915 | Get CSV values on a pandas rolling function | <p>I am trying to get a csv output of values for a given window in a rolling method but I am getting an error <code>must be real number, not str</code>.</p>
<p>It appears that the output must be of numeric type.
<a href="https://github.com/pandas-dev/pandas/issues/23002" rel="nofollow noreferrer">https://github.com/pan... | <p>Something like this?</p>
<pre class="lang-py prettyprint-override"><code>>>> df['running_csv'] = pd.Series(df.rolling(min_periods=1, window=3)).apply(lambda x:x.a.values)
>>> df
a running_csv
0 1 [1]
1 2 [1, 2]
2 3 [1, 2, 3]
3 4 [2, 3, 4]
4 5 [3, 4, 5]
5 6 [4, 5, 6]
6 ... | python|pandas|rolling-computation | 2 |
376,975 | 68,529,741 | how to find the difference between two dataFrame Pandas | <p>I have two <code>dataFrame</code>, both of them have <code>name</code> column, I want to make new <code>dataframe</code> of <code>dataframeA</code> have and <code>dataframeB</code> don't have</p>
<pre><code>dataframeA
id name
1 aaa
2 bbbb
3 cccc
4 gggg
dataframeB
id name
1 ddd
... | <p>If I understand correctly, ou can <strong>merge</strong> the two dataframes</p>
<pre><code>import pandas as pd
merged_df = pd.merge(dataframe_a, dataframe_b, on='name')
</code></pre> | python|pandas | 0 |
376,976 | 68,469,659 | In filtering a pandas dataframe on multiple conditions, is df[condition1][condition2] equivelant to df[(condition1) & (condition2)]? | <p>Say you have a pandas dataframe df with columns <code>df['year']</code>, <code>df['fish']</code>, and <code>df['age']</code>. In practice (in pandas version 0.22.0), it appears that</p>
<p><code>df[df['year']<2000][df['fish']=='salmon'][df['age']!=50]</code></p>
<p>yields results identical to</p>
<p><code>df[(df[... | <h3 id="why-you-should-not-do-dfcondition1condition2-cob2">Why you should not do df[condition1][condition2]</h3>
<p>You should go with the second approach. In addition to the greater readability of the second version, the first approach can lead to warnings as the dataframe that is returned by the first selection opera... | python|pandas|dataframe|subset | 1 |
376,977 | 68,676,799 | Is session really needed in tensorflow2? | <p>I'm so confused why it remains keeping the session in tf2 as said by the official eager mode has so many beneficial. Also sometimes I'm not sure whether to use session or not, and keep making bugs in tf programming, sometimes adding session just trying luck.</p> | <p>Tensorflow 2 does not require session.</p>
<p>Every v1.Session.run call should be replaced by a Python function.</p>
<ul>
<li>The feed_dict and v1.placeholders become function arguments.</li>
<li>The fetches become the function's return value.</li>
<li>During conversion eager execution allows easy debugging with sta... | tensorflow|session | 0 |
376,978 | 68,802,392 | Using `multiprocessing' in PyTorch on Windows got errors-`Couldn't open shared file mapping: <torch_13684_4004974554>, error code: <0>' | <p>I am currently running a PyTorch code on Windows10 using PyCharm. This code firstly utilised <code>DataLoader</code> function (`num_workers'=4) to load training data:</p>
<pre><code>train_loader = DataLoader(train_dset, batch_size, shuffle=True,
num_workers=4, collate_fn=trim_collate)
<... | <p>Use as above <code>num_workers=0</code>
and for error expected long datatype but got Int stead.
apply <code>criterion(outputs_t.float(), target_t.flatten().type(torch.LongTensor))</code></p> | python|windows|pytorch|multiprocessing | 2 |
376,979 | 68,646,140 | Cleanup phone numbers in dataframe column using a regex to fit a standard format | <p>I need to convert the values in my DataFrame column filled with mobile numbers that have different formats to follow one single format using RegEx.</p>
<p>There are 5 formats in the table and I want them all to follow the first format:</p>
<ol>
<li>+63xxxxxxxxxx #correct format</li>
<li>63xxxxxxxxxx #add '+'</li>... | <p>Here is a simple pipeline that does the job:</p>
<pre><code>df['fixed_mobile'] = (df['mobile']
.str.replace('\s+', '', regex=True) # remove unwanted characters
.str.extract('^(?P<prefix>\+63)?0?(?P<number>\d+)') # extract prefix/number
... | python|regex|pandas | 3 |
376,980 | 68,723,484 | Selecting values from pandas rows | <p>Hello I want to make a for loop that will get all the values from each row and dump it into a list.
I want the list to overwrite on the same variable.</p>
<p>I made something like this but there is now way i can figure out how to print or append only row values.</p>
<pre><code>rows_count = len(df.index)
for i in ra... | <p>You can reach the expected output using <code>values</code> :</p>
<pre class="lang-py prettyprint-override"><code>rows_count = len(df.index)
for i in range(rows_count):
extracted_row = df.iloc[[i]].values[0].tolist()
print(extracted_row)
if i == 1:
break
</code></pre>
<p>Output :</p>
<pre><code>... | python|pandas|dataframe|rows | 1 |
376,981 | 68,781,250 | Numerical input and binary classification | <p>I'm still learning deep learning with tensorflow and i had moved within LSTM a bit. I under stabd LSTM regression and did couple of models there. Now, I'm trying to to reach a regression like but classification where i want to classify labels value as greater then or less then. I have tried couple of existing codes ... | <p>First of all, what's the point of writing a machine learning model to solve a problem, which can be solved perfectly with one line of code.</p>
<p>If it's just an experiment,</p>
<ol>
<li><p>Get rid of the LTSM layers as suggested by Hakan, the inputs are random floating-point numbers with no relation between them. ... | python|tensorflow|lstm | 1 |
376,982 | 68,536,339 | Numpy returns unexpected results of analytical function | <p>When I try to compute <code>d_j(x)</code>, defined below, the algorithm based on Numpy results in unexpected values. I believe it has something to do with numerical precision, but I'm not sure how to solve this.</p>
<p>The function is:</p>
<p><img src="https://latex.codecogs.com/gif.latex?d_j%28x%29%20%3D%20sin%28%5... | <p><strong>TL;DR:</strong> The problem comes from <strong>numerical instabilities</strong>.</p>
<p>First of all, here is a simplified code on which the exact same problem appear (with different values):</p>
<pre class="lang-py prettyprint-override"><code>x = np.arange(0, 50, 0.1)
plt.plot(np.sin(x) - np.sinh(x) - np.co... | python|numpy|floating-point | 7 |
376,983 | 68,736,907 | Add empty row after every unique column value | <p>Im trying to add empty row after every unique <code>Salary</code> column value (Excpect duplicated values without empty row).</p>
<p>Current input :</p>
<pre><code> Name Country Department Salary
0 John USA Finance 12000
1 John Egypt Finance 12000
2 Jack France Marketing ... | <p>IIUC:</p>
<p>try appending empty dataframe by iterating over <code>groupby()</code>:</p>
<p>Since I grouped by 'Department' but you can also groupby 'Salary' or aother column according to your need</p>
<pre><code>l=[]
for x,y in df.groupby('Department',sort=False):
l.append(y)
l.append(pd.DataFrame([[float('... | python|pandas | 2 |
376,984 | 68,662,552 | Sorting Box Plots by Median using Plotly Graph Objects | <p>I'm pretty much a beginner in plotly/pandas/data but I'm trying to make this graph and no matter what I search up, I can't find any attributes that are compatible with dictionaries. The data I'm using is the Time series download speed for 9 different software. I am trying to display the box plot descending by their ... | <ul>
<li>taken a different approach to data preparation
<ol>
<li>pair columns, calculate means</li>
<li>create new dataframe from these paired column means</li>
</ol>
</li>
<li>order columns of this data preparation based on their medians</li>
<li>create box plots in same order as ordered columns</li>
<li>found two pro... | python|pandas|dataframe|plotly|plotly.graph-objects | 1 |
376,985 | 68,784,586 | why is df.fillna() only filling some rows and the first column | <p>Trying to fill all empty spots rows and columns with [], however fillna() will only do some rows and the first column. My code has worked in previous runs so I'm not sure what happened.</p>
<pre><code> df = df.fillna(value = "[]")
print(df[['keywords']])
df.to_csv(r'C:\Users\user\dfexport.csv', ... | <pre><code>import pandas as pd
import numpy as np
# initialize list of lists
data = [['tom', 10], ['',''], []]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age'])
df.replace('', np.nan, inplace=True)
df = df.fillna(value = "[]")
print(df)
</code></pre> | python|pandas|dataframe|export-to-csv|fillna | 0 |
376,986 | 68,628,523 | How to filter for NaN when it is a float type | <p>I want to filter column 1 so that it only returns NaN values. For some reason, NaN is a float type while everything else such as apple and duck are strings.</p>
<p>I've tried these lines below and it doesn't work because NaN is not null but is a float.</p>
<pre><code>filtered_df = df[df['1'].isna()]
</code></pre>
<p... | <p>df[df.A1.isnull()]</p>
<p>For Pandas DataFrame, this code works, but change the column names to start with an alphabet. Also remove the square bracket around the column name, A1</p> | python|pandas|dataframe | 0 |
376,987 | 68,476,608 | Finding low appearance count values | <p>I'm looking at a column full of repetitive numbers. I want to find the numbers that occur less than twice and change the original number into 5000.</p>
<p>I've tried:
<code>df['Count'] = df['Count'].map(lambda x: 5000 if df['Count'][df['Count']==x].count()<2)</code>
and this is giving me a syntax error.</p>
<p><c... | <p>try running this on the count column</p>
<pre><code>df['Count'] = df['Count'].where(df['Count'] > 2, 5000)
</code></pre>
<p>Anywhere where count is <code>< 2</code> will be replaced with 5000.</p> | python|pandas | 0 |
376,988 | 68,467,603 | While loop crashes inconsistently when generating random numbers with constraint | <ol>
<li><p>Start with a vector, vector0</p>
</li>
<li><p>Initialize a while loop that generates another random vector, vector1</p>
</li>
<li><p>Use the dot product to calculate the angle between them</p>
</li>
<li><p>If the angle theta between vector0 and vector1 is too large, keep re-making vector1 until it's small e... | <p>Here's a method for generating a random vector without needing to check if it's within the required angle:</p>
<pre><code>import numpy as np
import math
max_phi = np.pi/8
v1 = np.array([1, 1, 1])
phi = np.random.rand()*max_phi
psi = np.random.rand()*2*np.pi
# rotate v1 in the plane created by v1 and [0, 0, 1]
# u... | python|numpy|random|while-loop|crash | 0 |
376,989 | 68,557,136 | count frequency of values | <p>someone could help me please, I'm new to python.</p>
<p>I want to count the number of occurrences for each element in a row.</p>
<p>For example, for column A and row 0 I would like to get the following result: the number of times 10 appears = 1, and 20 = 2.</p>
<p>for column A and row 2, the desired result is: 15 = ... | <p>Are you looking for something like this</p>
<pre><code>import collections
def lst_count(lst):
lst_counter = []
for val in lst:
if type(val) == type([]):
lst_counter.append(list((collections.Counter(val).items())))
else:
lst_counter.append(list(collections.Counter([val... | python|pandas|dataframe | 0 |
376,990 | 68,532,241 | pandas merge two dataframes based on nearest coordinates | <p>I have two dataframes which are made up of columns <code>x</code>,<code>y</code>,<code>val</code> where (<code>x</code> and <code>y</code> are the Cartesian coordinate of the data point)
eg.</p>
<pre><code>df1
x y val
----------
0 0 1.1
1 1 1.2
0 5 1.3
</code></pre>
<pre><code>df2
x y val
-----... | <p>You could use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer"><code>cdist</code></a> from <code>scipy</code>:</p>
<h3 id="solution-zaz8">Solution:</h3>
<pre><code>import numpy as np
from scipy.spatial.distance import cdist
output = pd.DataFr... | python|pandas|dataframe|data-science | 2 |
376,991 | 68,753,432 | The recursive function in python stops at step 2500 even if the limit is 100000 | <pre><code>from PIL import Image
import numpy as np
import time
import sys
sys.setrecursionlimit(10**6)
print(sys.getrecursionlimit())
start_time=time.time()
im=Image.open("Capturecasa.png")
data=np.asarray(im,dtype=np.uint8)
back=np.zeros(4,dtype=np.uint8)
back=data[1000][200]
def recursiv(i,j,k):
global... | <ul>
<li>There doesn't appear to be any advantage to implementing this function recursively?</li>
<li>If you find yourself changing the recursion limit (or another similar system limit), it's good to stop and ask yourself whether you may be approaching the whole problem in an unfortunate way. Sometimes changing the sys... | python|numpy|recursion | 0 |
376,992 | 68,830,350 | Recursive loop over pandas dataframe | <p><strong>Input:</strong></p>
<pre><code>| Company | Employee Number |
|---------|-----------------|
| 1 | 12 |
| 2 | 34, 12 |
| 3 | 56, 34, 78 |
| 4 | 90 |
</code></pre>
<p><strong>Goal:</strong></p>
<p>Find all employee numbers for an employee in all co... | <p>Here's how I would approach this (explanations in the comments):</p>
<pre><code># Replace NaN in df["Employee Number"] with empty string
df["Employee Number"] = df["Employee Number"].fillna("")
# Add a column with sets that contain the individual employee numbers
df["EN_... | python|pandas|dataframe|recursion | 1 |
376,993 | 68,732,260 | How do I fix this error "The process cannot access the file because it is being used by another process"? | <p>This is the snippet of the code which throws the error:</p>
<pre><code>writer=pd.ExcelWriter('C:\\Users\\aji/Curve.xlsx',engine='openpyxl')
if os.path.exists('C:\\Users\\aji/Curve.xlsx'):
os.remove('C:\\Users\\aji/Curve.xlsx')
</code></pre>
<p>I got this error message:</p>
<pre><code>PermissionError: [Win... | <p>I don't think you're writing to the file properly. As a result, <em>your writer</em> has the file open.</p>
<p>According to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.ExcelWriter.html?highlight=pandas%20excelwriter#pandas.ExcelWriter" rel="nofollow noreferrer">the documentation</a>:</... | python|pandas|windows|error-handling|file-permissions | 0 |
376,994 | 68,606,157 | How can I select columns in a Pandas DataFrame by datatype? | <p>I have a pandas dataframe of a standard shape:</p>
<pre><code> A B C D E................φ
1-Int NaN Str Obj Datetime NaN..........Mixed Obj (like currency)
2-NaN Float Str Obj Datetime Category..........NaN
3-Int Float NaN Datetime Category......Mixed Obj
. . . . . ... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>select_dtypes</code></a> to get only the columns in a dataframe that match a specific type. For example, to get just the float columns you'd use:</p>
<pre><code>df.select_dtypes(incl... | python|pandas|dataframe | 2 |
376,995 | 36,351,774 | Style of error bar in pandas plot | <p>I'd like to plot line chart with error bar with the following style.</p>
<p><a href="https://i.stack.imgur.com/FvXIR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FvXIR.png" alt="enter image description here"></a></p>
<p>However, pandas plot draws error bars with only vertical line.</p>
<pre>... | <p>You can change the capsize inline when you call <code>plot</code> on your <code>DataFrame</code>, using the <code>capsize</code> kwarg (which gets passed on to <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.errorbar" rel="nofollow noreferrer"><code>plt.errorbar</code></a>):</p>
<pre><code>pd.Da... | pandas|matplotlib|plot | 10 |
376,996 | 36,300,577 | Pandas Group By Sum Keep Only One of Index as Column | <p>I have a data frame that looks like this:</p>
<pre><code>import pandas as pd
group = ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B']
df = {'population': [100,200,300,400,500,600,700,800],
'city_name': ['Chicago', 'Chicago', 'New York', 'New York', 'Chicago', 'New York', 'Chicago', 'New York'],
}
df = pd.DataFra... | <p>I think you need add parameter <code>level=1</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> for reseting only second level of <code>multiindex</code>:</p>
<pre><code>total.reset_index(level=1, inplace=True)
prin... | python|pandas | 4 |
376,997 | 36,567,672 | Python: error with numpy.asarray while coloring a graph | <p>I am dealing with a series of graphs which may not be fully connected, e.g. there may be isolated clusters of nodes here and there.</p>
<p>Based on the number of shortest paths that pass through each node, I want to give each node a color coming from <code>cmap='jet'</code>. </p>
<p>Code block:</p>
<pre><code>#Gi... | <p>Your <code>my_shortest_paths</code> is actually a list and by <code>my_shortest_paths[n] for n in nodes</code>, you are using node's name as the index of your list, which caused your problem.</p>
<p>I think you can just use <code>n_color = numpy.asarray([num_short_paths[n] for n in nodes])</code> instead.</p> | python|numpy|matplotlib|colors|networkx | 1 |
376,998 | 36,332,147 | Calculating and creating percentage column from two columns | <p>I have a df (<code>Apple_farm</code>) and need to calculate a percentage based off values found in two of the columns (<code>Good_apples</code> and <code>Total_apples</code>) and then add the resulting values to a new column within Apple_farm called 'Perc_Good'.</p>
<p>I have tried:</p>
<pre><code>Apple_farm['Perc... | <p>I think you need convert <code>string</code> columns to <code>float</code> or <code>int</code>, because their <code>type</code> is <code>string</code> (but looks like numbers):</p>
<pre><code>Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(float)
Apple_farm['Total_apples'] = Apple_farm['Total_apples'].... | python|string|pandas|dataframe|percentage | 11 |
376,999 | 36,395,931 | pandas: fill multiple empty dataframes | <p>I'm declaring multiple empty dataframes as follows:</p>
<pre><code>variables = pd.DataFrame(index=range(10),
columns=['P1', 'P2', 'P3'],
dtype='float64')
Q1 = pd.DataFrame(index=range(10),
columns=['P1H1', 'P1H2'],
dtype='fl... | <p>Use a <code>for</code> loop:</p>
<pre><code>for df in (variables, Q1):
df.fillna(0, inplace=True)
</code></pre> | python|pandas|dataframe | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.