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 |
|---|---|---|---|---|---|---|
355,300 | 72,915,174 | Python not recognizing pandas while using my user defined function from another file | <p>I am currently trying to create two files for a project, one that cleans and formats my raw data <code>cleanfile.py</code> with a function <code>clean(df1, df2)</code> which returns one joined clean dataframe, and another file <code>analysis.ipynb</code> where I can do analysis on said dataframe. I tried using the ... | <p>pandas is imported in <code>cleanfile</code> but not in current file.</p>
<p>just add:</p>
<pre><code>import pandas as pd
</code></pre>
<p>using star import <code>from cleanfile import *</code> is not recommended. It pollutes the namespace and bad for readability.</p> | python|pandas|dataframe|function|import | 0 |
355,301 | 72,935,952 | Python numpy array has weird truth conditions | <p>If I set up:</p>
<pre class="lang-py prettyprint-override"><code>board = np.array([[2., 0., 2.],[0., 2., 0.],[2., 0., 1.]])
</code></pre>
<p>Then <code>np.diagonal(board)</code> returns <code>array([2., 2., 1.])</code>, as you would expect. And <code>np.diagonal(board) == 1</code> returns <code>array([False, False, ... | <p>When you call <code>all()</code> on the diagonal array, it checks if all the elements are <code>True</code>. You provided a <code>float</code> array not <code>bool</code>. Everything non-zero is treated as <code>True</code>, so <code>all()</code> returns <code>True</code>. Then in pure Python, True == 1 (not just n... | python|arrays|numpy | 0 |
355,302 | 72,844,739 | Annotate points in Matplotlib | <p>I want to annotate points on a plot using the coordinates in the list <code>I5</code>. But running into an error. The expected output is attached.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
I5 = [[(0.5, -0.5), (1.5, -0.5)], [(0.5, -0.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -1.5)], [(0.5, -1.5),... | <pre><code>import numpy as np
import matplotlib.pyplot as plt
I5 = [[(0.5, -0.5), (0.5, -0.5)], [(0.5, -1.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -0.5)], [(1.5, -1.5), (1.5, -1.5)]]
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
N=3 #len(inv_r)+1
X = np.arange(0,N,1)
Y = -X
for i in range(0,len(I5)):
plt.anno... | python|numpy|matplotlib | 2 |
355,303 | 73,014,360 | Convert CNN-LSTM model to 1D-CNN model dimension error - `logits` and `labels` must have the same shape | <p>I have a CNN-LSTM model which I want to convert into a simple CNN model for results comparison. This is the original CNN-LSTM model:</p>
<pre><code> # define model CNN-LSTM
model = Sequential()
model.add(TimeDistributed(Conv1D(filters=16, kernel_size=2, activation='relu'),
... | <p>You actually need a 2D tensor with the shape <code>(batch_size, features)</code> and using a <code>flatten</code> layer on <code>None</code> dimensions will not work. Rather remove the last <code>TimeDistributed</code> layer and add a <code>GlobalMaxPool2D</code> (or <code>GlobalAvgPool2D</code>) layer and it will w... | python|tensorflow|keras|lstm|reshape | 1 |
355,304 | 73,066,417 | Pandas Pivot chart with filtering | <p>I have a data frame as shown below.It's name is 'df_IBIAS_mode1_FUN'</p>
<p><a href="https://i.stack.imgur.com/UlRH1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UlRH1.png" alt="enter image description here" /></a></p>
<p>I need to plot a pivot chart with index='Device_ID'', columns='Temp(deg)... | <p>You can use <code>['Supply[V]']</code> to access <code>Supply[V]</code> column</p>
<pre class="lang-py prettyprint-override"><code>df_IBIAS_mode1_FUN[df_IBIAS_mode1_FUN['Supply[V]'] == 2.5].pivot_table(index='Device_ID', columns='Temp(deg)', values='ibias_post_trim[MHz')
</code></pre> | python|pandas|plot|plotly | 1 |
355,305 | 73,171,287 | Pad the last dimension of a tensor with different lengths to a specific length | <p>I have a similar question, this one <a href="https://stackoverflow.com/q/42334646/9982458">TensorFlow - Pad unknown size tensor to a specific size?</a>. My question is more difficult though, and I didn't find any solutions can solve my question. My question is that what if the given unknown tensor have different siz... | <p>Have a look at <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/pad_sequences" rel="nofollow noreferrer">pad_sequences</a></p>
<p>It works as follow:</p>
<pre class="lang-py prettyprint-override"><code>sequence = [
[1],
[1, 2],
[1, 2, 3]
]
tf.keras.preprocessing.sequence.pad_sequences(sequence,... | python|tensorflow|tensor | 1 |
355,306 | 72,932,397 | Iterate and Compare through multiple Columns in Pandas | <p>I want to iterate through multiple columns which have the key word: Compliance with a column named <code>Requirements</code>. I want to make it very general so I can utilize it with a variation of excel files.</p>
<p>So I scanned through the columns with the word <code>Compliance</code>:</p>
<p>Then I want to compar... | <p>IIUC,</p>
<pre><code>df2 = df6.filter(like='Compliance')
pd.concat([df6['Requirement?'], df2[df2 == 'Empty']], axis=1)
</code></pre> | python|pandas | 0 |
355,307 | 72,987,271 | filter on value set intersection within a group | <p>Let's say I have a dataframe as follows:</p>
<pre><code>Group | Source | Name
___________________________
A | X | Jolly
A | X | Stone
A | X | Jolly
A | Y | Sand
B | X | Sand
B | X | Stone
B | Y | Stone
C | X | ... | <p>If I understand correctly, you can do that with the following.</p>
<pre><code>df[~df['Group'].isin(df[df[['Source','Name']].duplicated()]['Group'])]
</code></pre> | python|pandas | 1 |
355,308 | 72,987,064 | Convert 44710.37680 to readable timestamp | <p>I'm having a hard time converting what is supposed to be a datetime column from an excel file. When opening it with pandas I get 44710.37680 instead of 5/29/2022 9:02:36. I tried this peace of code to convert it.</p>
<pre><code>df = pd.read_excel(file,'Raw')
df.to_csv(finalfile, index = False)
df = pd.read_csv(fina... | <p>You can use <code>unit='d'</code> (for days) and substract 70 years:</p>
<pre><code>pd.to_datetime(44710.37680, unit='d') - pd.DateOffset(years=70)
</code></pre>
<p>Result:</p>
<pre><code>Timestamp('2022-05-30 09:02:35.520000')
</code></pre>
<p>For dataframes use:</p>
<pre><code>import pandas as pd
df = pd.DataFrame... | python|excel|pandas|datetime | 1 |
355,309 | 73,058,431 | Issue combining 5 minute time intervals into hourly time intervals | <p>This is my first time posting so excuse me if my post isn't the best...</p>
<p>I previously looked at this to combine my 5 minute intervals into hourly intervals and show the volumes per every hour.
<a href="https://stackoverflow.com/questions/66172153/combine-5-minute-timeframes-into-hourly">Combine 5 minute timefr... | <pre><code>>>> df.index = pd.to_datetime(df['datestamp'] + df['timestamp'])
>>> df.resample('H').det_vol.sum()
2017-06-01 13:00:00 1752
2017-06-01 14:00:00 1065
Freq: H, Name: det_vol, dtype: int64
</code></pre>
<p>You need to have the datetime in your index for resample to work.</p> | python|pandas|datetime | 0 |
355,310 | 72,907,199 | ValueError: setting an array element with a sequence while running NearestNeighbor | <p>I have pyspark dataframe like this:</p>
<pre><code>+------+---------------------------------------------------------------------+
|id |features |
+------+---------------------------------------------------------------------+
|2484 |[0.016910851, 0.02598... | <p><code>df.toPandas()</code> returns a column of lists. You need to convert this column of lists to a 2D array. When you do <code>df_collect['features'].apply(lambda x: np.array(x)).to_numpy()</code> you get an array of arrays which is not the same as a 2D array. So you need</p>
<pre><code>df_collect = df.toPandas()
f... | python|pandas|numpy|knn|nearest-neighbor | 1 |
355,311 | 73,021,455 | Calculate sum of distances between nodes of a graph passed as an array in a DataFrame | <p>Graph definition (The graph is fixed for the problem concerned):</p>
<p>N1 <---10---> N2 <---30---> N3 <---20---> N4</p>
<p>We assume that the distance of a node from itself will always be 0. The distance between two nodes will be the sum of their distances. The distance between two nodes is the va... | <p>One approach using <a href="https://networkx.org/documentation/stable/index.html" rel="nofollow noreferrer">networkx</a>:</p>
<pre><code>import networkx as nx
# init distances
distances = {("N1", "N2"): 10, ("N2", "N1"): 10, ("N2", "N3"): 30, ("N3&quo... | python|pandas|dataframe|graph | 2 |
355,312 | 73,130,919 | Pandas dataframe, how to access column name in UTF8 | <p>I have an ANSI encoded CSV file like below. I can import it as a dataframe with <code>df = pd.read_csv(ans, encoding='ansi', skipinitialspace=True)</code> and then access any column with <code>df['aÌ…']</code> etc.</p>
<p>The ANSI encoding is hard to read and I would rather use UTF8. But I don't know how to access c... | <p>You can access the columns by location rather than name.</p>
<p><a href="https://pythonhow.com/python-tutorial/pandas/Accessing-pandas-dataframe-columns-rows-and-cells/" rel="nofollow noreferrer">https://pythonhow.com/python-tutorial/pandas/Accessing-pandas-dataframe-columns-rows-and-cells/</a></p>
<p>In the tutoria... | python|pandas|unicode|columnname | 0 |
355,313 | 72,961,892 | Change column format of DF, where some columns are dicts | <p>I'm new to pandas and I need help. Below I described my DF, which I need to change.</p>
<pre><code> id title \
0 121852 {'en': 'Hard Fork'}
1 123209 {'en': 'Quarterly Public Meeting'}
2 122436 {'en': 'Luxy NFT Marketplace'}
3 122995 {... | <p>For columns with list in rows i would use pandas.explode</p>
<p>For columns with dict rows, use .apply(pandas.Series)</p>
<p>and then rename the columns with same name if u want use it (like 'id') or reformat the dicts when you get the parsed json</p>
<p>should look like this</p>
<pre class="lang-py prettyprint-over... | python|pandas|dataframe|python-requests | 0 |
355,314 | 73,115,367 | How to split a dataframe then merge to see matches? | <p>I need to find matches and mismatches of Level + Part for the Names. If the Part and the Level of a Name are the same for another Name, it is a match. What I'm thinking is, split the df to separate frames. One per name. then concat the frames together on a groupby(["Level", "Part"]). The problem ... | <p>You can use the fucntion <code>.duplicated()</code> which returns True if there are 2 identical rows:</p>
<pre><code>df = pd.DataFrame({'Name':["A","A","ABC","ABC","AAB","AAB"]
,'Level': [1,2,1,3,4,2]
,'Part':["Upper","Upper ... | python|pandas|data-science | 2 |
355,315 | 10,806,705 | Slice Array Given Range from another array in Python | <p>To be more clear, let me reword my question that I initially asked below.</p>
<p>I have a series of data points that rise and fall in amplitude as someone takes a step and then another step. Zero is when the foot is off the ground.</p>
<p>A simple example would look like this:</p>
<pre><code> data_array = (0,0,0... | <p>I don't understand the way you are trying to go about it, but can you use <a href="http://docs.python.org/library/functions.html#filter" rel="nofollow">filter</a>?:</p>
<pre><code>>>> data_array = (0,0,0,10,20,50,40,30,10,0)
>>> filter(lambda x: x>20,data_array)
(50, 40, 30)
</code></pre>
<p>... | python|arrays|numpy|slice | 1 |
355,316 | 10,511,646 | Installing `numpy` within a virtualenv in Ubuntu 11.10 | <p>I got the following exceptions when install <code>numpy</code> using <code>easy_install numpy</code>, could somebody help please? Whether I am using <code>pip</code> or <code>easy_install</code>, I got the same problems. It is hard to understand what's going wrong.</p>
<pre><code>non-existing path in 'numpy/core': ... | <p>Perhaps the GCC is not updated. I just did a <code>apt-get upgrade gcc</code> and <code>numpy</code> compiled successfully.</p> | python|numpy|package|virtualenv|pip | 8 |
355,317 | 3,230,067 | Numpy minimum in (row, column) format | <p>How can I know the (row, column) index of the minimum of a numpy array/matrix?</p>
<p>For example, if <code>A = array([[1, 2], [3, 0]])</code>, I want to get <code>(1, 1)</code></p>
<p>Thanks!</p> | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unravel_index.html" rel="noreferrer"><code>unravel_index</code></a>:</p>
<pre><code>numpy.unravel_index(A.argmin(), A.shape)
</code></pre> | python|arrays|numpy|minimum | 115 |
355,318 | 70,498,656 | Rearrange values in a Pandas DF Cell by some separated value value in alphabetical order | <p>I have the following df:</p>
<pre><code> ID Foods
0 100 Apple
1 101 Apple | Orange | Grape
2 102 Apples & Peanut Butter | Peanuts | Coffee
3 103 Grapes and Apples | Melon | Butter
4 104 Milk, Cookies | Cake | Cupcake
</code></pre>
<p>I want to be organize every cell by alphabetical, separated b... | <p>Just use <code>.str.split</code> to split by <code>|</code> (+ and whitespace, left or right), call <code>sorted</code> (which returns a new sorted list) on each split list, then join them back together:</p>
<pre><code>df['Foods'] = df['Foods'].str.split('\s*\|\s*').apply(sorted).str.join(' | ')
</code></pre>
<p>Out... | python|pandas | 0 |
355,319 | 70,470,937 | DataFrame merge for on specific columns | <p>I have a basic question on dataframe merge. After I merge two dataframe , is there a way to pick only few columns in the result.</p>
<p>For Example:</p>
<pre><code>left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'A': ['A0', 'A1', 'A2',... | <p>Sure, first filter necessary columns + columns used for join:</p>
<pre><code>result = pd.merge(left[['A','key1', 'key2']],
right[['C','key1', 'key2']],
on=['key1', 'key2'])
</code></pre>
<p>Or:</p>
<pre><code>keys = ['key1', 'key2']
result = pd.merge(left[['A'] + keys], right[['... | python-3.x|pandas | 2 |
355,320 | 70,537,249 | Filter in Pandas by logic "and" | <p>I have a dataframe as below:</p>
<p><a href="https://i.stack.imgur.com/TFS2u.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TFS2u.jpg" alt="enter image description here" /></a></p>
<p>I would like to take a result with filter city is San Francisco and score > 90, i wrote the code like below:</... | <p>Use regex, starts with in the str.contains</p>
<pre><code>df[(df['city'].str.contains('^[San]')) & (df['score'] > 90)]
</code></pre> | pandas | 2 |
355,321 | 70,666,877 | Alternative way of writing for loop and if in python when working with a dataframe to make it faster | <p>I have a data frame named 'plans_to_csv' looking like this:</p>
<p><a href="https://i.stack.imgur.com/Pm7mI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pm7mI.png" alt="enter image description here" /></a></p>
<p>I need to do the following analysis to realize what is the actual mode. But this t... | <p>You can shift the columsn and do comparisons. That will make use of vectorization and should be faster.</p>
<pre class="lang-py prettyprint-override"><code>selection = (plans_to_csv['mode'].shift(-1) == 'walk') & (plans_to_csv['type'].shift(-2)=='car interaction') & (plans_to_csv['person_id'] == plans_to_csv... | python|pandas | 1 |
355,322 | 70,710,709 | Multiplication of column doesn't work as expected pandas | <p>I have the code below where I'm approaching for creating a new column where it stores the multiplication of 'Date'
(6:7 is the month position) with 'Total Stock Owned'.</p>
<pre><code> import matplotlib as plt
import pandas as pd
data = pd.read_csv("C:\\users\\Hp\\Documents\\Datascience task\\Stock.cs... | <p>You forgot to convert to int:</p>
<pre><code>date = data['Date'].str[6:7].astype(int)
</code></pre>
<p>Output:</p>
<pre><code>date = data['Date'].str[6:7].astype(int)
stock = data['Total Stock Owned']
data['Incremenet of stock based on month'] = date * stock
print(data)
Total Stock Owned Date In... | python|pandas | 2 |
355,323 | 70,706,988 | seperate multi-valued column into new columns by not using str.split('',expand=true) | <p>I have below data in csv.</p>
<pre><code>dataCenter,customer,companyID,UID,uba
dc1,customer1,companyID1,uid1,"uba1,uba2,uba3,uba4"
dc2,customer2,companyID1,uid2,"ubaA"
dc3,customer3,companyID3,uid3,"uba1,uba4"
dc4,customer4,companyID4,uid4,"uba1,uba2,uba5,uba6,uba10"
</code></... | <p>If done want to use <code>str.split('',expand=True)</code> and no missing values is possible use list comprehension:</p>
<pre><code>a = pd.concat([a,pd.DataFrame([x.split(',') for x in a.pop('uba')],index=a.index).add_prefix('action')],axis=1)
print (a)
dataCenter customer companyID UID action0 action1 actio... | pandas | 1 |
355,324 | 70,586,315 | How to sample from large dataframe based on values in a column efficiently? | <p>I have a medium sized dataset of 220k product titles with their brands, I want to take a sample from this dataframe such as for every brand, I take at least one product and at most 10 products.</p>
<p>Here is my code currently : The idea is to group by brand than aggregating through <code>count</code>, then iteratin... | <p>You can build the conditional into a function <code>sample_brand_equally</code> and apply this function to the groups (they are dataframes as well) using <code>apply</code>:</p>
<pre><code>def sample_brand_equally(grp, n, random_state=42):
brand_count = grp.size
if brand_count>n:
sample_size = n
... | python|pandas | 1 |
355,325 | 70,527,001 | Groupby Agg Mean of DateTimeIndex with other agg functions | <p>I'm looking to groupby the following dataframe using agg function of count and sum but also wanted to get the average time difference in minutes between the DateTimeIndex of the dataframe.
When i use df.index i get the error TypeError: unhashable type: 'DatetimeIndex'</p>
<pre><code>data = df.groupby('letter').agg({... | <p>Please try np.timedelta</p>
<pre><code>data = df.reset_index().groupby('letter').agg({'letter': 'count', 'occurences' : 'sum', 'timestamp': lambda x: (x.diff().mean())/np.timedelta64(1, 'm')})
</code></pre> | python|pandas | 1 |
355,326 | 70,417,619 | How to resolve Boolean Series ReIndex warning | <p>I have a dataframe</p>
<pre><code> Unnamed: 0 game score home_odds draw_odds away_odds country league datetime
0 0 Sport Recife - Imperatriz 2:2 1.36 4.31 7.66 Brazil Copa do Nordeste 2020 2020-02-07 00:00:00
1 1 A... | <p>I think you can try change:</p>
<pre><code>n = df[['home_score']].agg(lambda x: x.str.count('-'), 1).ne(0).all(1)
o = df[['away_score']].agg(lambda x: x.str.count('-'), 1).ne(0).all(1)
</code></pre>
<p>to:</p>
<pre><code>n = df['home_score'].str.count('-').ne(0)
o = df['away_score'].str.count('-').ne(0)
</code></pre... | python|pandas|dataframe|user-warning | 1 |
355,327 | 70,607,198 | Concatenating strings across two rows in pandas dataframes | <p>I have a table like so after performing some data scraping on a pdf:</p>
<pre><code>index colA colB colC colD colE colF colG
-------------------------------------------------------------------
1 ABCD veryLongTextThatShouldNotCutOff 12 x x x x
2 ABCD veryLongText ... | <p>You could use the non NaN values in colA to set up a group and merge the colB. Then drop the NaN rows:</p>
<pre><code>group = df['colA'].notna().cumsum()
df['colB'] = df.groupby(group)['colB'].transform('sum')
df = df.dropna(subset=['colA'])
</code></pre>
<p>output:</p>
<pre><code> index colA ... | python|pandas | 3 |
355,328 | 70,721,139 | Pyplot how to plot math art | <p>How would one plot these circle structures:
<a href="https://blogs.scientificamerican.com/guest-blog/making-mathematical-art/" rel="nofollow noreferrer">https://blogs.scientificamerican.com/guest-blog/making-mathematical-art/</a></p>
<p>in pyplot? I tried this:</p>
<pre><code>x = np.arange(1,11)
def f(x):
retur... | <p>Take the first example in the reported link:</p>
<p><a href="https://i.stack.imgur.com/qmhE0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qmhE0.png" alt="enter image description here" /></a></p>
<p>So you have to do a for loop with <code>k</code> from 1 to <code>N = 14000</code>, in each iterat... | python|numpy|matplotlib|math|plot | 3 |
355,329 | 70,663,238 | Can the increase in training loss lead to better accuracy? | <p>I'm working on a competition on Kaggle. First, I trained a Longformer base with the competition dataset and achieved a quite good result on the leaderboard. Due to the CUDA memory limit and time limit, I could only train 2 epochs with a batch size of 1. The loss started at about 2.5 and gradually decreased to 0.6 at... | <p>Your model got fitted to the original training data the first time you trained it. When you added the validation data to the training set the second time around, the distribution of your training data must have changed significantly. Thus, the loss increased in your second training session since your model was unfam... | nlp|pytorch|training-data|transformer-model | 0 |
355,330 | 70,680,572 | How to pre-filter to a minimum number of rows per group before resampling without double-resampling? | <p>This is a mock of my actual use-case, suppose I have the following:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.arange(1, 32),
columns=['a'],
index=pd.date_range('2021-01-01', '2021-01-31'))
</code></pre>
<p>I'd like to pre-filter resampli... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> with a callable to filter the aggregated rows:</p>
<pre><code>df.resample('W')['a'].agg(['count', 'mean']).loc[lambda df: df['count'] >= 7, 'mean']
</code></pre> | python|pandas | 4 |
355,331 | 70,484,458 | Generate classes from values using dataframe in pandas | <p>For example, I have the list of values in a column: <code>10, 20, 30, 40, 50</code> and I want to get in another column something that looks like <code>10-20, 30-40, 40-50</code>.</p>
<p>Please how can this be done?</p> | <p>I think this does what you want. I'm assuming that given a list of values you want strings representing the ranges from each value to the next higher value.</p>
<pre><code># This is what you have
df = pd.DataFrame({'val': [10, 20, 30, 40, 50]})
# This adds the column you want
df = df.sort_values('val')
df['class'] ... | pandas|dataframe|numpy | 1 |
355,332 | 70,606,847 | Assigning True/False if a token is present in a data-frame | <p>My current data-frame is:</p>
<pre><code> |articleID | keywords |
|:-------- |:------------------------------------------------------:|
0 |58b61d1d | ['Second Avenue (Manhattan, NY)'] |
1 |58b6393b | ['Crossword Puzzles'] ... | <p>try</p>
<pre><code>df["trumpMention"] = df["keywords"].apply(lambda x: "Trump, Donald J" in x)
</code></pre> | python|pandas|dataframe|text|nlp | 4 |
355,333 | 70,721,652 | How to upsample a multi-index dataframe ensuring each grouping covers the same time range (provide custom starting and ending datetimes) | <p>Here is a dummy example to illustrate the problem.</p>
<p>I am interested in upsampling to the beginning of the each year (<code>AS</code>) and, for every country, I want to cover the period that goes from 1995 to the year 2000.</p>
<p>Imagine we had the following dataset:</p>
<pre class="lang-py prettyprint-overrid... | <p>I'm sure there is a better way, but here is one way to achieve this:</p>
<pre><code>def my_upsample(df):
# Get all periods
years = df.index.get_level_values(1)
years = pd.date_range(years.min(), years.max(), freq="as")
# Reindex and format
return (
df.unstack(level=0)
.... | python|pandas|multi-index | 3 |
355,334 | 70,384,543 | Retrieve dataset from a dictionary | <p>I have a function that splits a dataset in a non-iid setting. This function returns a dict of the labels:</p>
<pre><code>def noniid(dataset, clients, min, max, equal_amount=False):
len_dataset = len(dataset)
samples_per_client = int(len_dataset/clients)
idx = np.arange(len_dataset) #idx([0, 1, 2, ..., 59999])
... | <p>If you want to iterate through all the keys in the dictionary you can you the .keys() method the get all the keys. You can then use a loop to go through each key and obtain each set in the dictionary.</p> | python|dictionary|pytorch|dataset | 0 |
355,335 | 70,679,806 | Problems computing cdist of two columns in two different dataframes | <p>I am trying to compute the distance between vectors in two pandas dataframes using <code>cdist</code> from <code>scipy.spatial.distance</code>, but the output is all wrong and I can't pinpoint where is fails.</p>
<p>So, My original dataframes are of the type:</p>
<pre><code>df_sample =
... | <p>As mentioned in <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer">scipy.spatial.distance's docs</a>, XA and XB are supposed to be lists of the vectors of which you want to find the distance from one to the others. What you did in your code is m... | python|pandas|numpy|scipy | 1 |
355,336 | 70,541,980 | Can you remove measurements - g/kg/ml etc from a Pandas Dataframe? | <p>I am doing some pre processing for a data set on one particular column 'Title' I have already removed numbers and punctuation. But also want to remove measurements as well. The measurements are not in a separate column, they're in the title column.</p>
<pre><code> #Load data set
df = pd.read_csv (r'exampl... | <pre><code>df['Title'] = df['Title'].str.replace(r'\sg$|\skg$|\sml$', '')
</code></pre>
<p>as an example.
or more generally removing the last word will amount to:</p>
<pre><code>df['Title'] = df['Title'].str.replace(r'\s[a-z]+$', '')
</code></pre> | python|pandas|dataframe|jupyter-notebook|data-cleaning | 1 |
355,337 | 70,479,421 | ValueError: Must pass 2-d input. shape=(430, 430, 3) | <p>I want to save this as 3d array csv file with header as r,g,b but it is showing ValueError: Must pass 2-d input. shape=(430, 430, 3).</p>
<p>four_img_concat shape is (430,430,3).</p>
<pre><code>import pandas as pd
import numpy as np
ans=np.array(four_img_concat)
headers=np.array(['r','g','b'])
df=pd.DataFrame(ans)
d... | <p>As the error is indicating, you need to transform your array from 3-d to a 2-d. You can do this by using the<a href="https://numpy.org/doc/stable/reference/generated/numpy.reshape.html" rel="nofollow noreferrer"><code>reshape</code></a> function passing the total amount of pixels to one axis (<code>430*430</code>).<... | python|pandas|dataframe|numpy|csv | 1 |
355,338 | 70,627,324 | Pandas: New column with values greater than 0 and operate with these values | <p>I have a big dataframe with more than 2500 columns but the structure is very similar than this:</p>
<pre><code> A B C D E
0 1 0 8 0 0
1 0 0 0 0 5
2 1 2 3 0 0
3 0 2 0 1 0
</code></pre>
<p>I need to detect all the... | <p>You can use <code>apply</code> with a function and have to specify <code>axis=1</code> to apply the function row-wise. I have added a <code>get_diff</code> function without being 100% if that is exactly what you would need. I have also added an <code>assign</code> call to create a new dataframe with a new column nam... | python|pandas | 2 |
355,339 | 70,420,536 | How do I validate a value in a dataframe which is dependent on other value in that specific row? | <p>Suppose I have a .csv which follows this format:</p>
<blockquote>
<p>Name, Salary, Department, Mandatory</p>
<p>Rob, 5500, Aviation, Yes</p>
<p>Bob, 1000, Facilities, No</p>
<p>Tom, 6000, IT, Yes</p>
</blockquote>
<p>After exporting this to pandas/modin, I'd like to perform row-differentiated checks, where:</p>
<ol>... | <p>Depending on which API you're using, you can check out the <a href="https://pandera.readthedocs.io/en/stable/checks.html#wide-checks" rel="nofollow noreferrer">wide checks</a> for the object-based API or <a href="https://pandera.readthedocs.io/en/stable/schema_models.html#dataframe-checks" rel="nofollow noreferrer">... | pandas|pandera | 1 |
355,340 | 70,491,759 | How to convert object data type to float in pandas | <p>I have a data frame wherein a column is of "object" data type. I use <code>pd.to_numeric()</code> with <code>errors = 'coerce'</code> to convert this to "float" data type. However, the converted column appears as NaN for all entries. If I let <code>errors = 'ignore'</code>, none of the entries a... | <p><code>to_numeric</code> can only convert numeric-ish things. For example it can convert the string <code>'10'</code> into the number <code>10</code>, but it can't convert something like <code>'Male'</code> into a number.</p>
<hr />
<p>Instead use <a href="https://pandas.pydata.org/docs/reference/api/pandas.factorize... | python|pandas|object | 2 |
355,341 | 70,706,388 | Installing PyTorch on MacOS Big Sur | <p>I am trying to figure out how to go about installing PyTorch on my computer which is a macOS Big Sur laptop (version 11.6.2). So far, I have installed Python 3.10.1 via the Python website, and pip 21.3.1 was installed along with it. At the moment, I’m stuck trying to figure out how to install PyTorch using pip?</p>
... | <pre><code>pip3 install torch torchvision torchaudio
</code></pre>
<p>This command worked fine for me, you can find more information on the official website <a href="https://pytorch.org/" rel="nofollow noreferrer">here</a></p> | python|pip|pytorch|macos-big-sur | 1 |
355,342 | 70,586,039 | Convert win32com.client Range to Pandas Dataframe? | <p>I am writing some macros that call Python code to perform operations on ranges in Excel. It is much easier to do a lot of the required operations with pandas in Python. Because I want to do this while the spreadsheet is open (and may not have been saved), I am using the <code>win32com.client</code> to read in a rang... | <p>There are two parts to the operation: defining the spreadsheet range and then getting the data into Python. Here is the test data that I'm working with:</p>
<p><a href="https://i.stack.imgur.com/GHQmJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GHQmJ.jpg" alt="enter image description here" /><... | python|excel|pandas|win32com | 1 |
355,343 | 70,633,337 | Finding an Intersection between two lists or dataframes while enforcing an ordering condition | <p>I have two lists (columns from two separate pandas dataframes) and want to find the intersection of both lists while preserving the order, or ordering based on a condition. Consider the following example:</p>
<pre><code>x = ['0 MO', '1 YR', '10 YR', '15 YR', '2 YR', '20 YR', '3 MO', '3 YR',
'30 YR', '4 YR', '5 ... | <p>You could simply with list comprehensions:</p>
<pre><code>[this_name for this_name in x if this_name in y]
</code></pre>
<p>and</p>
<pre><code>[this_name for this_name in y if this_name in x]
</code></pre> | python|pandas|list|ordered-set | 1 |
355,344 | 70,661,474 | Pytorch: Extract value from tensor if it's a tensor | <p>I have a variable initialized at e.g var = 0, the algorithm changes this variable to a tensor type Int if some conditions are met, otherwise it will stay at zero. I want to just print the variable without the tensor wrapping, however, if I use:</p>
<pre><code>var = 0
if random.uniform(0, 1) < 0.5:
var = torch.... | <p>A very obvious solution would be to use <code>try</code></p>
<p>as in</p>
<pre><code>var = 0
if random.uniform(0, 1) < 0.5:
try:
var = torch.IntTensor(1)
except:
pass # Or Throw and exception or whatever your use case migth be
print (f' var: {var.item()}')
</code></pre>
<p>This will <em>try</... | python|pytorch | 0 |
355,345 | 70,538,379 | read in .txt file , transform into pandas dataframe, but spaces seperating value vary in number of spaces | <p>This script reads in a txt file and creates a df, but the 'sep' argument I want to handle values that may be seperated by 1 space or more, so when I run the script above I get many columns with NaN.</p>
<p>code:</p>
<pre><code>df = pd.read_csv(data_file,header = None, sep=' ')
</code></pre>
<p>example txt file</p>
<... | <p>You can use regex as the delimiter:</p>
<pre><code>pd.read_csv(data_file, header=None, delimiter=r"\s+", names='Col_a Col_b Col_c'.split(' '))
</code></pre>
<p>Or you can use <code>delim_whitespace=True</code> argument, it's faster than regex:</p>
<pre><code>pd.read_csv(data_file, header=None, delim_whites... | python|pandas | 2 |
355,346 | 70,488,318 | Pass a new activity as main activity to render first | <p>This is <strong>ClassifierActivity.java</strong> file which is rendering by default:</p>
<pre><code>package org.tensorflow.lite.examples.classification;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Typeface;
import android.media.ImageReader.OnImageAvailableListener;... | <p>All activities need to be defined in the <code>manifest</code>.</p>
<p>You are replacing the original <code>Activity</code> with the new one and now the old one is not defined. So you just need to add it back.</p>
<pre><code> <application
...
/>
<activity
android:name=&... | java|android|xml|android-studio|tensorflow | 0 |
355,347 | 70,546,285 | How can I find the second smallest output for my function? | <p>I used this function to find the biggest pullback $ wise for my data frame column with stock prices. I need help to figure out how to get the X following output. Basically the plan is to join those outputs into a new data frame to get the X biggest pullbacks within my data frame.</p>
<p><strong>Main question:</stron... | <p>The strategy u can use is to first find the biggest pullback, then exclude that range where that pullback is and then calculate the biggest pullback for all valid ranges that are left.</p>
<p>I made my own <code>maxdrop</code> function that works in a similar fashion as yours, except it only looks within specified b... | python|pandas|function|format | 1 |
355,348 | 70,651,990 | Pandas merge using date interval and compute sum | <p>I have two dataframes</p>
<p><code>master</code>df looks like below</p>
<pre><code>Pid sid Date_1 Date_2 Qty
1 101 1/1/2017 1/1/2018 200
1 102 1/2/2018 1/2/2019 150
2 101 3/3/2017 3/3/2018 300
2 102 9/9/2019 9/9/2020 1000
3 105 8/8/2018 11/11/2021 700
</code></pre>
<p>... | <p>Convert values to datetimes and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a>, filter by <code>date</code>s with aggregate <code>sum</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/re... | python|pandas|dataframe|numpy|merge | 1 |
355,349 | 70,502,453 | Doing Riemann Sum with Discrete Points in Python | <p>I have a dataset consisting of many points (around million~trillion), which maps
[x1, x2, x3] to a vector [y1, y2, y3]
I want to compute Riemann Sum of this function.</p>
<p>I don't know if this helps, but all x1, x2, x3 are bounded by [0,1].
Is there a Python module or a simple way for doing this?</p>
<p>Thank you ... | <p>Here's a simple program that computes the left Riemann sum. This assumes that the values given in the vector are sorted in increasing order of x-value.</p>
<pre class="lang-py prettyprint-override"><code>integral_value = 0
for i in range(len(x) - 1):
width = x[i + 1] - x[i]
# Replace with y[i + 1] for r... | python|pandas|numpy|scipy|integral | 0 |
355,350 | 70,459,068 | Could not load library cudart64_110.dll with tensor flow gpu installation | <p>W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
After this, there comes a traceback ... | <p>It could be that you need a Nvidia GPU, CUDA is the language NVIDIA uses.</p>
<p>You can check if you have one following these steps: Windows -> Task Manager.</p> | python|tensorflow|keras | 0 |
355,351 | 70,463,037 | Is there an alternative to Numba for functions that use many features not supported by Numba? | <p>I know Numba does not support all Python features nor all NumPy features.
However I really need to speed up the execution time of the following function, which is <em>block_reduce</em> available in the scikit-image library (I've not downloaded the whole package, I've just taken <em>block_reduce</em> and <em>view_as_... | <p>Have you tried running detailed profiling of your code? If you are dissatisfied with the performance of your program I think it can be very helpful to use a tool such as <a href="https://docs.python.org/3/library/profile.html#module-cProfile" rel="nofollow noreferrer">cProfile</a> or <a href="https://github.com/benf... | python|numpy|numba | 0 |
355,352 | 70,469,480 | How to accelerate my written python code: function containing nested functions for classification of points by polygons | <p>I have written the following NumPy code by Python:</p>
<pre><code>def inbox_(points, polygon):
""" Finding points in a region """
ll = np.amin(polygon, axis=0) # lower limit
ur = np.amax(polygon, axis=0) # upper limit
in_id... | <p>First of all, <strong>the algorithm can be improved to be much more efficient</strong>. Indeed, a polygon can be directly assigned to each point. This is like a <strong>classification of points by polygons</strong>. Once the classification is done, you can perform one/many <strong>reductions by key</strong> where th... | numpy|performance|python-2.7|numba|numexpr | 3 |
355,353 | 70,400,610 | Is it possible to implement a keras layer that always propagates a fixed vector to the other layers? | <p>I'm trying to develop a neural network architecture that has two inputs. However, I would like to fixate one of these vector inputs during training. I know that this seems to be nonsense for most of you, but I would like to know how to do this for testing a hypothesis.</p>
<p>It is clear that one way to do this woul... | <p>We can wrap the <code>tf.keras.backend.concatenate</code> function, which helps us concatenate the input vector and the fixed vector, in a <code>Lambda</code> layer, like,</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import numpy as np
# A function which concatenates a fixed vector
d... | python|tensorflow|machine-learning|deep-learning|neural-network | 1 |
355,354 | 70,422,288 | Generate excel file from list of nested dictionaries | <p>I have list like this(simplified version):</p>
<pre><code>data = [{'layer1': [{'idx': 'idx_102',
'size': 8 },
{'idx': 'idx_112',
'size': 25 },
{'idx': 'idx_142',
'size': 10 }]
},
{'layer2': [{'idx': 'idx_125',
'size': ... | <p>Use nested list with dict comprehensions:</p>
<pre><code>L = [{**{'layer': k}, **x} for d in data for k, v in d.items() for x in v]
df = pd.DataFrame(L)
print (df)
layer idx size
0 layer1 idx_102 8
1 layer1 idx_112 25
2 layer1 idx_142 10
3 layer2 idx_125 28
4 layer2 idx_258 21
5 ... | python|excel|pandas|dataframe | 0 |
355,355 | 70,442,533 | Pytorch DataLoader doesn't return batched data | <p>My dataset is composed of image patches obtained from the original image (face patches and random outside of face patches). Patches are stored in a folder with a name of an original image from which patches originate. I created my own DataSet and DataLoader but when I iterate over the dataset data is not returned in... | <p>You should return a one dimension higher <code>tensor</code> instead of a <code>list</code> of tensors in <code>__get_item__</code> function call. You can use <code>torch.stack(patches)</code>.</p>
<pre><code>def __getitem__(self, idx):
img_name = self.img_names[idx]
patch_dir = os.path.join(self.img_folder, i... | python|pytorch|dataset|pytorch-dataloader | 1 |
355,356 | 70,670,096 | How could I solve local variable referenced before assignment | <p>I was learning the tensorflow recently and found some project for practicing.</p>
<p>This is a project using CNN to recognized the numbers in verification code.</p>
<p>The traceback as below</p>
<pre><code>---------------------------------------------------------------------------
UnboundLocalError ... | <p>In your final if-else block, <code>train</code> is called only if <code>model_dir</code> does not exist. And inside the <code>train</code> function, <code>model.h5</code> file is loaded (and <code>model</code> variable is created) only if <code>model_dir</code> exists. This means that any time train function is call... | python|tensorflow|keras | 3 |
355,357 | 70,674,934 | Simple python function throws error when compiled using Numba UnsupportedError: Use of unknown opcode 'MAP_ADD' | <p>I have built a simple feature-normalisation function which I have used for machine learning projects in the past that I am looking to speed up the runtime using Numba. The function normalises grouped data by computing the distance of each value from the kth value in the group (when k=1, this is equivalent to distanc... | <p>Currently, numba does not support dict comprehensions. See <a href="https://numba.pydata.org/numba-doc/dev/reference/pysupported.html" rel="nofollow noreferrer">here</a></p> | python|numpy|numba | 2 |
355,358 | 70,526,889 | Convert Million to integer in Pandas | <p>I'm trying to change the scraped results in a column called "Outstanding". Currently, the numbers being scraped are coming out like 297.5M and I want them to be 297,500,000. I'm not sure quite how to do it but I know that if you put e5 instead of M, it would come out as 297500000. I tried this below but no... | <p>Example dataframe:</p>
<pre><code>data = pd.DataFrame([['297.5M']], columns=['Outstanding'])
>>> data
</code></pre>
<p><a href="https://i.stack.imgur.com/VXgdo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VXgdo.png" alt="enter image description here" /></a></p>
<p>Convert:</p>
<pre><co... | python|pandas | 2 |
355,359 | 70,664,776 | Equivalent of np.convolve in keras backend | <p>I have following function</p>
<pre><code>def pad_ones(arr):
return np.convolve(arr, [1, 1, 1], "same")
# for example:
# >>> pad_ones([0, 0, 0, 1, 0, 0])
# array([0, 0, 1, 1, 1, 0])
</code></pre>
<p>which I want to use to process one_hot encoded arrays. This currently throws an error in tenso... | <p>A simple way to replicate <code>np.convolve</code> with Tensorflow is using <code>tf.nn.conv1d</code>:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
original = tf.constant([0, 0, 0, 1, 0, 0], dtype=tf.float32)
x = tf.reshape(original, (1, tf.shape(original)[0], 1))
kernel = tf.constan... | python|numpy|tensorflow|keras|tf.keras | 1 |
355,360 | 70,570,497 | AttributeError: 'NoneType' object has no attribute 'summary' | <p>I am starting to learn how to implement neural networks with keras. However, I just now stumbled across this error. I don't know what I did wrong here. I am working alongside the youtube tutorials of Valerio: <a href="https://www.youtube.com/watch?v=TtyoFTyJuEY" rel="nofollow noreferrer">His vids on implementing an ... | <p>You're resetting <code>emb</code> to <code>None</code> after calling <code>_build()</code> which actually assigns the variable; this is true of other attributes, too. Instead default it to <code>None</code> first.</p>
<pre><code>self.emb = None
self.lstm = None
self.mpls = None
self.model = None
self._build()
</code... | python|python-3.x|tensorflow|keras|neural-network | 0 |
355,361 | 70,630,772 | Changing columns in pandas | <p><a href="https://i.stack.imgur.com/HSmDT.png" rel="nofollow noreferrer">Image containing the problem, click here</a></p>
<p>Please review the image</p> | <p>You can achieve this by using the function <a href="https://pandas.pydata.org/pandas-docs/version/1.0.0/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>melt()</code></a>, which to massage a DataFrame into a format where one or more columns are identifier variables (here <code>Campus</code>)... | python|pandas | 0 |
355,362 | 70,569,633 | How to treat pandas <NA> values in a series/list of numbers to summarize | <p>My question focus on the pandas way. Is the behaviour of pandas fixed defined in that situation?</p>
<p>I have a list/series of numbers and want to summarize them. I can do this with <code>sum()</code> or with simply <code>+</code> operator. The point is that sometimes there is a <code><NA></code> in such a li... | <p>You need to pass <code>skipna=False</code> to <code>sum</code>, because it's <code>True</code> by default:</p>
<pre><code>>>> df.iloc[0].sum(skipna=False)
<NA>
</code></pre> | pandas | 3 |
355,363 | 70,599,325 | How can I convert this dictionary into a Pandas dataframe? | <p>I have a dictionary that looks like this:</p>
<pre><code>{'NorthernRegion': {'date': '2021-12-31',
'state': PA,
'candySales': 500,
'grocerySales': 1500,
'electronicSales': 800,
...
},
{'date': '2021-12-30',
...
},
{'date': '2021-12-29',
...
},
...
}
</code></pre>
<p>It is a nested dictionary. I want the n... | <p>Each dictionary item needs a key and value, so assuming the complete structure of your dictionary looks something like the following:</p>
<pre><code>sample_dict = {'NorthernRegion': {'date': '2021-12-31',
'state': 'PA',
'candySales': 500,
'grocerySales': 1500,
'electronicSales': 800},
'SouthernRegion':{'date': '2021... | python|python-3.x|pandas|dataframe|dictionary | 3 |
355,364 | 70,522,566 | Split dataframe column at specific words | <p>One column in my dataframe is a long string. I want to split out portions of the string into its own column based on a few different words. What would be the best way of doing this? Example below of what the data in the column looks like, and what i want to pull out.</p>
<p>Original Data:</p>
<p>ABC - Company Name C... | <p>ended up finding a solution. this worked for me. not sure if this would lead to any exceptions (other than them just showing up in other locations) but it hasnt so far. no longer using week but capturing the number after other words/characters. I think I still had an issue with Joey's answer but it led to in the rig... | python|pandas | 1 |
355,365 | 70,567,490 | why plt.imshow(predict) shows a fully black image | <p>I set up a mechine learning model to predict a picture based on a given picture(using tensorflow). but when i use matplotlib, and use pyplot.imshow(predict), the picture showed is all black while the predict data is not all zero.</p>
<p>i am a freshman in python.any information would help a lot.
<a href="https://i.s... | <p>While plotting the image you can set the minimum and maximum value range for the imshow</p>
<pre><code>pyplot.imshow(predict,vmin=0, vmax=255)
</code></pre> | python|tensorflow|matplotlib | 0 |
355,366 | 70,552,150 | Using Python for loop to take rolling sum product | <p>I am trying to use a for loop to calculate the trailing sum product of a list of values, and a reverse counter. That is, at each iteration of the loop, the current value would be multiplied by 1, the previous value would be multiplied by 2, and so on back to n values, where n is the number of values between the star... | <p>As @JonClements suggested you may need simple</p>
<pre><code>(df['values'] * range(len(df), 0, -1)).sum()
</code></pre>
<p>without any <code>for</code>-loop</p>
<p>if you need partial result then you can get part of rows ie. <code>sub_df = df[:3]</code></p>
<pre><code>sub_df = df[:3]
(sub_df['values'] * range(len(su... | python|pandas|numpy | 0 |
355,367 | 70,651,969 | Tkinter - how to pull error messages from cmd on screen? | <p>I created a .exe file from my .py project. And when I try to save and output the .csv file on the desktop I get 'error 13 permission denied', because I have no admin privileges. Instead, I need to save a file to C:/Users/Public to make it work.
So, how do I make a pop-up window with this message using Tkinter, every... | <p>Thank you!
It worked!</p>
<pre><code>try:
df[rows:rows+500].to_csv(path_to_output_file + str(file_count) + '.csv', index=False, header=True, quoting=csv.QUOTE_NONNUMERIC)
except PermissionError:
messagebox.showinfo('Can\'t save a file', f'File can\'t be saved to {path_to_output_file} as you don\'t have admin... | python|pandas|tkinter|permission-denied | 0 |
355,368 | 70,394,918 | Can I make a Numpy array immutable? | <p>This post <a href="https://stackoverflow.com/a/5541452/6394617">https://stackoverflow.com/a/5541452/6394617</a></p>
<p>suggests a way to make a Numpy array immutable, using <code>.flags.writeable = False</code></p>
<p>However, when I test this:</p>
<pre><code>arr = np.arange(20).reshape((4,5))
arr.flags.writeable = ... | <p>This is a bug in <code>numpy.random.shuffle</code> in numpy versions 1.22 and earlier. The function does not respect the <code>writeable</code> flag of the input array when the array is one-dimensional.</p>
<p><code>numpy.random.Generator.shuffle</code> has the same issue, and <code>numpy.random.Generator.permuted</... | python|arrays|numpy|shuffle | 1 |
355,369 | 70,387,721 | Best way to convert a defaultdict(list) dictionary with list of dictionaries to a csv | <p>My default dict has an <strong>address key</strong> and has a list of dictionaries that match that key. I'd like to export this defaultdict to a csv file.</p>
<p>See below:</p>
<pre><code>Right now my structure looks like this defaultdict(list)
#As you can see 1 key with multiple matching dictionaries.
#And im jus... | <p>Your input data and output data do not match, so it's awfully difficult to tell how to transform things, but here is something that takes your defaultdict and converts it to a CSV file:</p>
<pre><code>import csv
dic1 = {'Address_2':
[
{'Address 1':
[
{'Name':'name', 'Addres... | python|json|pandas|parsing | 2 |
355,370 | 42,773,199 | Error in variable shift in pandas | <p>In the example below, the first apply works. The second throws "TypeError: ("Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'", u'occurred at index 0')"</p>
<pre><code>df = pd.DataFrame({'lag':[ 3, 5, 3, 4, 2, 3, 2, 3, 4, 3, 2, 2, 2, 3],
'A':[10,20,30,4... | <p>This is actually a tricky thing going on. I'll try to be succinct.</p>
<p>When you are using <code>apply</code> with <code>axis=1</code> you are iterating row by row. For each row, pandas handles it as a <code>pd.Series</code>. After your initial assignment, you put <code>NaN</code> values in the <code>df</code>... | python|pandas | 2 |
355,371 | 42,973,764 | Error in shape of logits in TensorFlow | <p>I am building an LSTM with TensorFlow and I think I am mis-defining my outputs because I am getting the following error: </p>
<pre><code>InvalidArgumentError (see above for traceback): logits and labels must have the same first dimension, got logits shape [160,14313] and labels shape [10]
[[Node: SparseSoftmax... | <p>Fixed by adding this line: </p>
<pre><code>rnn_outputs = rnn_outputs[:, num_steps-1, :]
</code></pre> | tensorflow|neural-network|deep-learning|recurrent-neural-network | 1 |
355,372 | 42,916,726 | Assigning value to new column ['E'] based on column ['A'] value using dataframes | <p>In the example below. I am trying to generate a column 'E' that is assigned either [1 or 2] depending on a conditional statement on column A. </p>
<p>I've tried various options but they throw a slicing error. (Should it not be something like this to assign a value to new column 'E'?</p>
<p>df2= df.loc[df['A'] == '... | <p>What about simply this?</p>
<pre><code>df['E'] = np.where(df['A'] == 'foo', 1, 2)
</code></pre> | python|pandas|dataframe | 3 |
355,373 | 42,960,304 | Basic StopAtStepHook & MonitoredTrainingSession usage | <p>I want to setup a distributed tensorflow model, but fail to understand how MonitoredTrainingSession & StopAtStepHook interact.
Before I had this setup:</p>
<pre><code>for epoch in range(training_epochs):
for i in range(total_batch-1):
c, p, s = sess.run([cost, prediction, summary_op], feed_dict={x: batch_... | <p>Every time a sess.run is executed, the counter is incremented. The problem here is that you are running more steps <code>(total_batch-1 x training_epochs)</code> than the number of steps specified in the hook <code>(200)</code>.</p>
<p>What you could do, even though I don't think it is a clean syntax is define <cod... | python|tensorflow | 2 |
355,374 | 42,611,889 | Accuracy does not increase in my ResNet on MNIST dataset | <p>I have built a ResNet model with <code>tensorflow</code> to classify MNIST digits. However, at training time, my accuracy does not change so much and stays around 0.1 even after 3-4 epochs, which corresponds to a random classifier (1 chance over 10 to make the right prediction).</p>
<p>I have tried changing activat... | <p>In fact, the problem came from the <code>from __future__ import division</code> which was missing. I did not insert it in my other scripts neither but it yet worked. Don't know why it is required in this script.</p> | python|tensorflow|deep-learning | 0 |
355,375 | 42,708,989 | Why do we use tf.name_scope() | <p>I've been reading the tutorials on TensorFlow where they have written</p>
<pre><code>with tf.name_scope('read_inputs') as scope:
# something
</code></pre>
<p>The example</p>
<pre><code>a = tf.constant(5)
</code></pre>
<p>and </p>
<pre><code>with tf.name_scope('s1') as scope:
a = tf.constant(5)
</code></... | <p>They are not the same thing.</p>
<pre><code>import tensorflow as tf
c1 = tf.constant(42)
with tf.name_scope('s1'):
c2 = tf.constant(42)
print(c1.name)
print(c2.name)
</code></pre>
<p>prints</p>
<pre><code>Const:0
s1/Const:0
</code></pre>
<p>So as the name suggests, the scope functions create a scope for the ... | tensorflow | 27 |
355,376 | 42,965,698 | Which sequence_length do we use for tf.nn.ctc_loss | <p>I generated a tensor for training a RNN, the input is of size <code>[batch_size, max_time_step, num_features]</code>, but as multiple training samples do not have the same <code>time_step</code>, I padded them with zeros at the end to match the training sample which has the the <code>max_time_step</code> for that pa... | <p>sequence_length is the latter: the batch size length vector.</p> | tensorflow | 3 |
355,377 | 42,619,180 | Tensorflow's API: seq2seq | <p>I have been following <a href="https://github.com/kvfrans/twitch/blob/master/main.py" rel="nofollow noreferrer">https://github.com/kvfrans/twitch/blob/master/main.py</a> tutorial to create and train a chatbot based on rnn using tensorflow. From what I understand, the tutorials was written on an older version of tens... | <p>I think <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/legacy_seq2seq/rnn_decoder" rel="nofollow noreferrer">this</a> is the one you need: </p>
<pre><code>tf.contrib.legacy_seq2seq.rnn_decoder
</code></pre> | python|machine-learning|tensorflow|recurrent-neural-network | 3 |
355,378 | 42,812,216 | pandas merge on date column issue | <p>I am trying to merge two dataframes on date column (tried both as type <code>object</code> or <code>datetime.date</code>, but fails to give desired merge output:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'amt': {0: 1549367.9496070854,
1: 2175801.78219801,
2: 1915613.1629125737,
3: 17... | <p>I think you need first convert both columns <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a> because need same <code>dtypes</code>:</p>
<pre><code>df1.month = pd.to_datetime(df1.month)
df2.month = pd.to_datetime(df2.month)
print (... | python|pandas|merge|data-manipulation | 15 |
355,379 | 42,828,310 | Why my 1 hidden layer autoencoder made with tensorflow does not work? | <p>I wanted to make an autoencoder with just 1 layer, which has 100 hidden units. And, I used MNIST datasets given by tensorflow.</p>
<p>But, it does not work. I don't know what the problem is.
When I debugged, my decoder layer just is filled with all 1's.</p>
<p>Is the back-propagation update does not working?
Or, s... | <p>Can you try something for me?
You have random uniform initialisation for your weights:
<a href="https://www.tensorflow.org/api_docs/python/tf/random_uniform" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/random_uniform</a></p>
<p>Can you try try to set the weights layer to have random un... | python|tensorflow|autoencoder | 0 |
355,380 | 42,871,723 | Python Pandas - Update row with dictionary based on index, column | <p>I have a dataframe with empty columns and a corresponding dictionary which I would like to update the empty columns with based on index, column: </p>
<pre><code>import pandas as pd
import numpy as np
dataframe = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [4, 6, 2], [3, 4, 1]])
dataframe.columns = ['x', 'y'... | <p>I could use a function as such but as far as the pandas library and a method for the DataFrame object I am not sure...</p>
<pre><code>def update_row_with_dict(dictionary, dataframe, index):
for key in dictionary.keys():
dataframe.loc[index, key] = dictionary.get(key)
</code></pre> | python-3.x|pandas|dictionary | 4 |
355,381 | 42,663,171 | How to convert a list of strings into a numeric numpy array? | <p>I want to be able to calculate the mean, min and max of <code>A</code>:</p>
<pre><code> import numpy as np
A = ['33.33', '33.33', '33.33', '33.37']
NA = np.asarray(A)
AVG = np.mean(NA, axis=0)
print AVG
</code></pre>
<p>This does not work, unless converted to:</p>
<pre><code>A = [33.33, 33.33, 33.33, 33.3... | <p>you want <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html" rel="noreferrer">astype</a></p>
<pre><code>NA = NA.astype(float)
</code></pre> | python|arrays|numpy|average | 12 |
355,382 | 42,655,675 | Get indices of strings in an array | <p>I have an array in numpy which looks like this:</p>
<pre><code>myarray = ['a', 'b', 'c', 'd', 'e', 'f']
</code></pre>
<p>I would like to return an array of indices for <code>'b', 'c', 'd'</code> which looks like this:</p>
<pre><code>myind = [1,2,3]
</code></pre>
<p>I need this indices array later to use it in a ... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow noreferrer"><code>np.searchsorted</code></a> -</p>
<pre><code>In [61]: myarray = np.array(['a', 'b', 'c', 'd', 'e', 'f'])
In [62]: search = np.array(['b', 'c', 'd'])
In [63]: np.searchsorted(myarray, s... | arrays|string|python-2.7|numpy | 1 |
355,383 | 43,011,081 | How to preserve order of insertion in SciPy Sparse Matrix COO_Matrix | <p>Hello SO python community,</p>
<p>I have a question about numpy sparse matrix COO format. It is as follows:</p>
<p>I have a <code>csv</code> file with 4 columns <code>a</code>,<code>b</code>,<code>c</code>,<code>d</code> and I need to form SciPy COO_Matrix from this csv file but I need to be able to preserve order... | <p>If you make a matrix in <code>coo</code> format directly, the order preserved, at least initially:</p>
<pre><code>In [165]: row=np.array([0,1,3,5,2,0])
In [166]: col=np.array([1,0,3,0,1,4])
In [170]: M = sparse.coo_matrix((np.ones(6,int),(row,col)))
In [171]: M
Out[171]:
<6x5 sparse matrix of type '<class 'n... | python|numpy|scipy | 2 |
355,384 | 42,785,976 | How to duplicate a field in Pandas | <p>Hi I have table like this in a DataFrame</p>
<p><a href="https://i.stack.imgur.com/ofJFb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ofJFb.png" alt="enter image description here"></a></p>
<p>I was wondering how I can duplicate the 'original id' field all the way down to the bottom?</p>
<p>T... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ffill.html" rel="nofollow noreferrer"><code>ffill</code></a>:</p>
<pre><code>df['original id'] = df['original id'].ffill()
</code></pre> | python|pandas | 1 |
355,385 | 42,776,420 | Using numpy.random.choice w/o replacement to draw items from a bag | <p>I'm still quite new to python, and am working through a problem for class. I feel like I'm really close to the solution, but my numbers still aren't coming out how I would expect from probability.</p>
<p>In the problem, we have a bag with two chips inside. We know one of the chips is white, and the other is either ... | <p>I the issue is not with any of the random number generation or the counting, but with your probability computation at the end.</p>
<p>The conditional probability of getting two white results given that the first result was white is <code>double_white / first_white</code> (simply divide the two counts). That's a sim... | python|numpy | 0 |
355,386 | 42,584,866 | Running an operation on one column based on content from another column in Pandas Dataframe | <p>I'm trying to convert the negative value of rows in column <code>'nominal'</code> where the corresponding value in column <code>'side'</code> is equal to 'B'. I don't want to lose any rows that are not converted. I've tried this below but getting raise <code>KeyError('%s not in index' % objarr[mask])</code></p>
<pr... | <p>Just use both conditions in a boolean index with <code>&</code>. </p>
<pre><code>df[(df.side == 'B') & (df.nominal < 0)]
</code></pre>
<p>or if you intend on modifying, </p>
<pre><code>df.loc[(df.side == 'B') & (df.nominal < 0), 'nominal']
</code></pre>
<p><strong>Example</strong></p>
<pre><co... | python|pandas|dataframe | 6 |
355,387 | 42,875,053 | Subplotting different column label in Python pandas | <p>I have a problem with filtering data from column so I have a question about it.</p>
<p>My df looks like this:</p>
<pre><code> TempHigh TempLow City
Date
2017-01-01 25 15 A
2017-01-02 23 14 A
2017-01-03 29 10 A
2017-01-01 22 13 ... | <p>You need to read basic documentation about <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="nofollow noreferrer"><code>Indexing and Selecting Data</code></a>.</p>
<pre><code>>>> df[df['City']=='A'].describe()
TempHigh TempLow
count 3.000000 3.000000
mean 25.666667 ... | python|pandas|matplotlib|dataframe|time-series | 0 |
355,388 | 42,630,259 | Applying an operation to a subset of the columns in a Dataframe in pandas | <p>Given a <code>DataFrame</code> such as:</p>
<pre><code> 0 1 2
0 'a' 6 7
1 'a' 8 9
</code></pre>
<p>Where the first column consists of strings and the other columns are integers. I want to apply multiplication by a constant to columns 1 and 2 only. That is, avoiding multiplying the strings as well. This ... | <p>Here is a bit more generic solution:</p>
<p>Data:</p>
<pre><code>In [200]: df
Out[200]:
A B C D
0 aaa 6 7.1 2001-01-01
1 bbb 8 9.2 2017-02-13
</code></pre>
<p>Let's find all numeric columns:</p>
<pre><code>In [201]: num_cols = df.columns[df.dtypes.map(lambda x: np.issubdtype(x, np.number)... | python|python-3.x|pandas|dataframe | 4 |
355,389 | 42,589,303 | Word2Vec word containing numeric values | <p>When I am adding sentences to Word2Vec model it seems to remove the words which end or start with numeric values, for example "ISO 9001" is returned as "ISO ", I've guessing it's something simple...</p>
<p>Thanks in advance.</p> | <p>I think you already answered your question in the tags you gave to this question. Most likely your tokenizer splits by blank spaces, and leaves out numbers. If you paste the tokenize code you use here we will be able to help you further. </p>
<p>Good luck!</p> | tensorflow|tokenize|word2vec | 0 |
355,390 | 42,746,827 | Error importing tensorflow in simple python code with import | <p>I am trying to run sample code in tensor flow with only one line - import tensorflow as tf. But it gives this error.</p>
<pre><code>Traceback (most recent call last): File "sample.py", line 1, in <module>
import tensorflow as tf File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/__i... | <p>Focus on this part:
"ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory"</p>
<p>The reason why this message is displayed because Tensorflow couldn't find the place where the Nvidia cuda library is installed. Try to install it properly along with the tensorflow.</p>
<p>If you a... | python|ubuntu|tensorflow | 0 |
355,391 | 42,633,534 | Numpy arrays - Convert a 3D array to a 2D array | <p>Having the following 3D array (9,9,9):</p>
<p>np.arange(729).reshape((9,9,9))</p>
<pre><code>[[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[ 18 19 20 21 22 23 24 25 26]
[ 27 28 29 30 31 32 33 34 35]
[ 36 37 38 39 40 41 42 43 44]
[ 45 46 47 48 49... | <p>You can firstly reshape the array to a 4d array, swap the second and third axises and then reshape it to 27 X 27:</p>
<pre><code>a.reshape(3,3,9,9).transpose((0,2,1,3)).reshape(27,27)
#array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 81, 82, 83, 84,
# 85, 86, 87, 88, 89, 162, 163, 164, 165, 166... | python|arrays|numpy | 2 |
355,392 | 42,815,780 | Parsing date with French month abbreviations | <p>I have a pandas dataframe with the date column containing dates with month abbreviations in French, such as:</p>
<pre><code>u'18-oct.-2015'
u'12-nov.-2015'
u'02-d\xe9c.-2015'
u'26-janv.-2016'
u'02-f\xe9vr.-2016'
u'31-mai-2016'
u'01-juin-2016'
</code></pre>
<p>What is the proper way of using <code>to_datetime</code... | <p>I suspect that you can just set your locale:</p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, 'fr_FR') # Windows may be a different locale name
# do your pandas read here
</code></pre>
<p>You might need to tell Pandas that that column is a datetime column... though it's also possible that you'll need... | python|pandas | 1 |
355,393 | 42,612,982 | Import error: Anaconda numpy (numpy and Anaconda already installed, virtualenv) | <p>I have a virtual environment my_env in which I installed Anaconda. When I type</p>
<pre><code>which python
</code></pre>
<p>I get:</p>
<pre><code>/user/pkgs/anaconda2/envs/my_env/bin/python
</code></pre>
<p>I have no errors importing numpy here:</p>
<pre><code>(my_env) user@hostname:~/my_dir$ python
Python 2.7... | <p>Your shell script doesn't care about having a <code>virtualenv</code> active (it starts in a clean environment). </p>
<p>Instead of <code>../python_program.py</code> you need to have the full executable path</p>
<pre><code> export PYTHON_ENV=/user/pkgs/anaconda2/envs/my_env
$PYTHON_ENV/bin/python ../python_progr... | python|numpy|sh | 2 |
355,394 | 42,869,544 | Dictionary of lists to dataframe | <p>I have a dictionary with each key holding a list of float values. These lists are not of same size. </p>
<p>I'd like to convert this dictionary to a pandas dataframe so that I can perform some analysis functions on the data easily such as (min, max, average, standard deviation, more).</p>
<p>My dictionary looks li... | <pre><code>d={
'key1': [10, 100.1, 0.98, 1.2],
'key2': [72.5],
'key3': [1, 5.2, 71.2, 9, 10.11, 12.21, 65, 7]
}
df=pd.DataFrame.from_dict(d,orient='index').transpose()
</code></pre>
<p>Then <code>df</code> is</p>
<pre><code> key3 key2 key1
0 1.00 72.5 10.00
1 5.20 NaN 100.10
2 ... | python|pandas | 64 |
355,395 | 42,859,309 | Iterate multiple Dataframe and write into excel spreadsheets within an excel xlsxwriter python | <p>I am working on writing multiple dataframes in excel spreadsheets within an excel file.
The dataframes generates using for loop , so in every iteration I get next available dataframe but I can not able to write every dataframe in spreadsheets.
I could only write the first dataframe in first spreadsheet.
Below is the... | <p>Simply move <code>writer.save()</code> outside of <code>for</code> loop:</p>
<pre><code>writer = pd.ExcelWriter('output.xlsx', engine='xlsxwriter')
workbook = writer.book
web_ClassID=df_stag["Web-Class ID"].unique()
for data_id, df in df_stag.groupby('Web-Class ID'):
for workbook_Id in web_ClassID:
if ... | python|excel|pandas|xlsxwriter | 3 |
355,396 | 42,847,396 | Fuzzy Wuzzy String Matching on 2 Large Data Sets Based on a Condition - python | <p>I have 2 large data sets that I have read into Pandas DataFrames (~ 20K rows and ~40K rows respectively). When I try merging these two DFs outright using pandas.merge on the address field, I get a paltry number of match compared to the number of rows. So I thought I would try to fuzzy string match to see if it impro... | <p>You could adapt your <code>fuzzy_match</code> function to take the id as a variable and use this to subset your choices before doing the fuzzy search (note that this requires applying the function over the whole dataframe rather than just the address column)</p>
<pre><code>def fuzzy_match(x, choices, scorer, cutoff... | python|pandas|fuzzy-comparison|fuzzywuzzy|large-data | 8 |
355,397 | 42,854,598 | Pandas DataFrame: set_index with inplace=True returns a NoneType, why? | <p>If I reset the index of my pandas DataFrame with "inplace=True" (following <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer">the documentation</a>) it returns a class 'NoneType'. If I reset the index with "inplace=False" it ... | <p>Ok, now I understand, thanks for the comments!</p>
<p>So inplace=True should return None <strong>and</strong> make the change in the original object. It seemed that on listing the dataframe again, no changes were present.</p>
<p>But of course I should not have <strong>assigned the return value</strong> to the data... | python|python-3.x|pandas|dataframe | 24 |
355,398 | 42,774,744 | How to get elements from a 2D numpy array with a list 2d indices using broadcasting? | <p>If I have a 2D numpy array that I want to extract elements using a list of row,col index pairs. </p>
<pre><code>xy = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
idx = np.array([[0, 0], [1, 1], [2, 2]])
</code></pre>
<p>The for loop solution:</p>
<pre><code>elements = list()
for i in idx:
elements.append(xy[i... | <pre><code> idy = zip(*idx)
output = xy[idy]
</code></pre> | python-2.7|numpy|array-broadcasting | 1 |
355,399 | 42,632,695 | Tips on how to optimize the inner function with a large for loop | <pre><code>def testing(min_quadReq, stepsize, max_quadReq, S):
y = np.arange(min_quadReq, max_quadReq, stepsize)
print("Y", y)
I_avg = np.zeros(len(y))
Q_avg = np.zeros(len(y))
x = np.arange(0, (len(S)))
debugger = 0
for i in range(0, len(y)):
I = np.array(S * (np.cos(2 * np.pi * y[i... | <p>Your loop produces one <code>I_avg</code> value for each element of <code>y</code>. For compactness I could write it as a list comprehension.</p>
<pre><code>In [61]: x=np.arange(4)
In [62]: y=np.arange(0,1,.2)
In [63]: [np.cos(2*np.pi*y[i]*x).sum() for i in range(y.shape[0])]
Out[63]:
[4.0,
-0.30901699437494745,... | python|numpy|optimization|signal-processing | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.