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 |
|---|---|---|---|---|---|---|
13,800 | 66,593,664 | How to keep groups in pandas groupby when value is consective 1 for 4 times | <p>I want to groupby my dataframe and check if in each column value of flag column remains 1 consecutively equal or greater than 2 rows in group then keep this group if group count is less than for consecutive 1 remove from dataframe</p>
<pre><code>dataframe1=pd.DataFrame({'x1':[5,678,78,89,4,5,6,5],'x2':[555,555,555... | <p>Find the consecutive differences in flag in each group. If NaN, make it zero. Sum up the difference and if equal or less than 2, pick it up.</p>
<pre><code> s=dataframe1[dataframe1['flag'].eq(1)]#Filter 1s
s[s.groupby('x2')['flag'].transform(lambda x: (x.diff().fillna(0).eq(0).sum())).ge(2)]#Filter the consecutiv... | python-3.x|pandas|numpy|pandas-groupby | 1 |
13,801 | 66,438,279 | Different results in DFT and FFT (python)? | <p>I'm using FFT to perform some transformations in my PhD thesis. Since I need the Fourier transform to be in certain frequencies, I thought of programming my own DFT (I cannot use FFT since its frequencies are fixed by sample number and rate).</p>
<p>But I encounter differences between the output of both algorithms.<... | <p>I have followed Eq.1 in <a href="https://en.wikipedia.org/wiki/Discrete_Fourier_transform" rel="nofollow noreferrer">this Wikipedia</a> about DFT and the result is similar with both methods in scipy; fft and dft. Here is the code:</p>
<pre class="lang-py prettyprint-override"><code>from scipy.fft import fft, fftshif... | python|numpy|scipy|fft|dft | 0 |
13,802 | 66,500,143 | "ERROR: Could not find a version that satisfies the requirement tensorflow" on Raspberry Pi | <p>I have been trying to install Tensorflow on my Raspberry Pi but I always get the same error:</p>
<pre><code>ERROR: Could not find a version that satisfies the requirement tensorflow==2.2.0
ERROR: No matching distribution found for tensorflow==2.2.0
</code></pre>
<p>The Raspberry Pi is running on Ubuntu-20.04 64-bit,... | <p>You may not be installing the correct version of Tensorflow. Raspberry Pi runs on an ARM CPU "armhf" and not regular x86 or amd64 or even arm64. To install correct version of tensorflow in RPi, do</p>
<pre><code>sudo apt install libatlas-base-dev
</code></pre>
<p>and then,</p>
<pre><code>pip3 install tenso... | python|tensorflow|pip|raspberry-pi|ubuntu-20.04 | 1 |
13,803 | 57,694,178 | Nesting a dictionary within another dictionary, grouping by values in a Pandas Dataframe | <p>In this previous question: <a href="https://stackoverflow.com/questions/57693128/nesting-a-counter-within-another-dictionary-where-keys-are-dataframe-columns/57693171?noredirect=1#comment101831679_5769317">Nesting a counter within another dictionary where keys are dataframe columns</a> , @Jezrael showed me how to ne... | <p>Use nested dictionary comprehension:</p>
<pre><code>d = {k: {k1: v1.value_counts().to_dict() for k1, v1 in v.groupby('ID')['Code']}
for k, v in df.groupby('SuperID')}
print (d)
{'E1': {'E1023': {'b': 3, 'a': 1}, 'E1024': {'c': 2, 'b': 1}},
'E2': {'E1025': {'a': 2}, 'E102... | python-3.x|pandas|dictionary|pandas-groupby | 2 |
13,804 | 70,406,770 | Is calling fit() supposed to keep the model's weights? | <p>At the moment, I'm using a custom generator which isn't written as a class, just as a function. To reset my generator and shuffle its contents for a new epoch I just have to call it again.</p>
<p>So, to train new epochs, I'm calling <code>model.fit()</code> after restarting my generators like this:</p>
<pre><code>ba... | <p>You can customise the fit() method: <a href="https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit/" rel="nofollow noreferrer">https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit/</a></p>
<p>But I don’t think you should be generating a dataset and fitting every single epoch.</p>
<... | python|tensorflow|keras | 0 |
13,805 | 51,451,493 | Pandas: Create New Dataframe that Counts Number of Times Keywords / Phrases From List Occur in One Column | <p>I have the following word list: </p>
<p>list = ['clogged drain', 'right wing', 'horse', 'bird', 'collision light']</p>
<p>I have the following data frame (notice spacing can be weird): </p>
<pre><code>ID TEXT
1 you have clogged drain
2 the dog has a right wing clogged drain
3... | <p>I would start by reformatting the <code>TEXT</code> column to get rid of your funny spacing, using <code>str.split()</code> and <code>str.join()</code>. Then, use <code>str.contains</code> for each of your keywords, and get the sum of the boolean values that are outputted (It will return <code>True</code> if your ke... | list|pandas|search|count|frequency | 0 |
13,806 | 51,872,670 | Fitting with a gaussian | <p>I have some problems when trying to fit data from a text file with a gaussian. This is my code, where cal1_p1 is an array containing 54 values. </p>
<pre><code>%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
cal1=np.loadtxt("C:/Users/Luca/Desktop/G3/X_ra... | <p>The problem is that the Gaussian is normalised, while your data are not. You need to fit an amplitude as well. That is easy to fix, by adding an extra parameter <code>a</code> to your function:</p>
<pre><code>x = np.arange(854, 908)
def gauss(x, sigma, m, a):
return a * np.exp(-(x-m)**2/(2*sigma**2))/(sigma*np... | python|numpy | 1 |
13,807 | 51,776,314 | how to concatenate all rows of a column of a data frame in pandas without group by | <p>I have a dataframe like this</p>
<p>Have been on it 12 days along with 60 mg prozac 4+ years on that. ... | <p>If all you want is to produce a list of all the values (unique or not) in a column in your Pandas dataframe, the easier method would be to use the <code>.tolist()</code> method. </p>
<p>So, <code>dfsent['sentences'].tolist()</code> would produce the desired output. </p> | python|pandas|dataframe|concatenation | 6 |
13,808 | 51,936,010 | Read access table into dataframe | <p>I'm trying to read an Access table into a pandas dataframe and am a relative newbie. The name of the file/table are:</p>
<ol>
<li>Name of MS Access file: test.mdb</li>
<li>table Name: MA MEMBERSHIP COMBINED CAP REPORT</li>
</ol>
<p>I've trying the pandas_access package w/o luck. Code I tried is below:</p>
<pre>... | <p>As a start, use your actual database, and bracket the table name:</p>
<pre><code>df = mdb.read_table("BlueCap MA txt files 2018.mdb", "[MA MEMBERSHIP COMBINED CAP REPORT 2018]")
</code></pre> | python|pandas|ms-access | 1 |
13,809 | 36,096,890 | Show xticks with specified interval on pandas DataFrame | <p>When I plot the folowing DataFrame named <code>df</code>, I got this figure.</p>
<pre><code>df = pd.DataFrame([[1 for _ in range(20)]]).T
df.index = ["{}:00:00".format(x) for x in range(20)]
df.plot()
</code></pre>
<p><a href="https://i.stack.imgur.com/OdWu9.png" rel="nofollow noreferrer"><img src="https://i.stack... | <p>Your index is a bunch of strings, not actual dates.</p>
<p>If you use dates, pandas can smarter about what it tells matplotlib to do:</p>
<pre><code>df = pandas.DataFrame({'A': range(20)}, index=pandas.date_range('2012-01-01', freq='1H', periods=20))
df.plot()
</code></pre>
<p><a href="https://i.stack.imgur.com/S... | python|pandas|matplotlib | 0 |
13,810 | 36,032,148 | how does python operator overloading works | <p>I can understand that some langurage allows user to do some operator overloading. I know this in C++ area first. But c++ also has some restrictions on operator overloading and I think that's reasonable. </p>
<p>but when I come to python pandams library. I'm start to confused.</p>
<p>Take a look at my code at <a ... | <p>You can overload operators if you create your own classes and add a <code>__eq__</code> method to them.</p>
<pre><code>class MyClass(object):
def __eq__(self, other):
# compare self with other, return whatever you need
</code></pre>
<p>This will be invoked whenever you compare your type with <code>sel... | python|pandas|operator-overloading | 3 |
13,811 | 31,414,306 | Inserting data from dataframe into numpy array | <p>I am inserting data from a dataframe <code>df</code> with 55 rows into a numpy array <code>matrix_of_coupons_and_facevalues</code> with a shape of (55,60). I am doing this using the code below. However, I get the error <code>IndexError: index 55 is out of bounds for axis 0 with size 55</code>. <code>months_to_maturi... | <p>For any future visitors, here's what happened:</p>
<p>A DataFrame's index serves to label each row uniquely, so when you delete a row, that index is removed and you have a "gap" in the index. This is very good when you have a meaningful index. But, when you just want the index to number your rows, it's not what y... | python|numpy|pandas | 2 |
13,812 | 64,391,296 | Geopandas install problem: InvalidSpecError | <p>I'd created a new environment and wanted to install geopandas and its dependencies. However, I get the following error message when I do this:</p>
<pre><code>(C:\Program Files\Anaconda3) C:\WINDOWS\system32>activate py37_SWS
(py37_SWS) C:\WINDOWS\system32>conda install geopandas
Fetching package metadata ....... | <p>I've fixed the issue. Created a new python 3.7 environment and installed all geopandas dependencies and geopandas from pip wheels. Followed this tutorial: <a href="https://www.hatarilabs.com/ih-en/how-to-install-python-geopandas-on-anaconda-in-windows-tutorial" rel="nofollow noreferrer">https://www.hatarilabs.com/ih... | python|conda|geopandas | 0 |
13,813 | 47,581,808 | Fill Down a value in Pandas once it has occurred | <p>I am fairly new to Pandas and I am struggling to fill down a value once it has occurred. This is hard to explain, so I will show an example. This is the output of my code at the moment.</p>
<pre class="lang-none prettyprint-override"><code>Cont_No Mnth Short Reset Outst Total Default
6293 1 249.... | <p>This is a good solution for <code>cummax</code>:</p>
<pre><code>df['Default'] = df.groupby('Cont_No')['Default'].cummax()
</code></pre>
<p>Output:</p>
<pre><code> Cont_No Mnth Short Reset Outst Total Default
0 6293 1 249.17 1 249.17 747.51 0
1 6293 2 249.17 0 498.3... | python|pandas | 2 |
13,814 | 49,102,589 | Python - For loop If statment not evaluating | <p>I am trying to create a new column in the dataframe that will have the following logic:</p>
<p>If column A is greater than zero, then use column A. Otherwise, use column B. When I run the function, it only looks like the else clause is true. However, there are values clearly greater than zero in column A. I feel li... | <p>Iterating through rows will work, though it is far faster to use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html" rel="nofollow noreferrer">numpy.where()</a></p>
<pre><code>data_all['New Column'] = np.where(data_all['Column A'] > 0, data_all['Column A'], data_all['Column B']... | python|pandas|loops | 2 |
13,815 | 58,958,640 | Python dataframe - counting number of positive return days | <p>I have a dataset that looks like:</p>
<pre><code>print(portfolio_all[1])
Date Open High ... Close Adj Close Volume
0 2010-01-04 4.840000 4.940000 ... 4.770000 4.513494 9837300
1 2010-01-05 4.790000 5.370000 ... 5.310000 5.024457 25212000
2 2010-01-0... | <ul>
<li>you can just use <code>.shift</code> functio to shift column by one value.</li>
</ul>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({'Close':[1,2,3,2,1,3]})
print(df)
print("count",(df.Close - df.Close.shift(1) > 0).sum())
</code></pre>
<p>*output:</p>
<pre><code... | python|pandas | 2 |
13,816 | 70,086,784 | Iterate through multiple columns of dataframe that contain the same substring | <p>Consider the following Data Frame:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Index</th>
<th>foo</th>
<th>String A</th>
<th>bar</th>
<th>String B</th>
</tr>
</thead>
<tbody>
<tr>
<td>First</td>
<td>15</td>
<td>nan</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>Second</td>
<td>0</td>
<td>... | <p>In order to maintain use of your original for loop you could do the following:</p>
<pre><code>for idx, val in enumerate(df):
if 'String' in val:
print(val)
</code></pre> | python|pandas | 0 |
13,817 | 56,327,213 | How does python map works with torch.tensor? | <p>I am now in python so I am trying to understand this line from <a href="https://pytorch.org/tutorials/beginner/nn_tutorial.html" rel="nofollow noreferrer">pytorch tutorial</a>.</p>
<pre><code>x_train, y_train, x_valid, y_valid = map(
torch.tensor, (x_train, y_train, x_valid, y_valid)
)
</code></pre>
<p>I under... | <p><code>map</code> works on a single the same way it works on list/tuple of lists, it fetches an element of the given input regardless what is it.</p>
<p>The reason why <a href="https://pytorch.org/docs/stable/torch.html#torch.tensor" rel="nofollow noreferrer"><code>torch.tensor</code></a> works, is that it <em>accep... | python-3.x|pytorch|fast-ai | 4 |
13,818 | 56,087,400 | Will pd.series do sorting of the dictionary keys? | <p>I am using Jupyter notebook as provide by Jake Vaderplas, " Python Data Science Handbook", and its says : data can be a dictionary, in which index defaults to the sorted dictionary keys</p>
<p>But when I run the code, the output is not sorted for dictionary keys. What m I missing here?</p>
<p>In :</p>
<pre><code>... | <p>First to make you clear, pandas series are not <code>sorted</code> by default. But if you want to make a series which should be <code>sorted</code> by index,</p>
<pre><code>sr = pd.Series({2:'a', 1:'b', 3:'c'}).sort_index()
sr
</code></pre>
<p>Output:</p>
<pre><code>1 b
2 a
3 c
</code></pre>
<p>This wil... | pandas|series | 2 |
13,819 | 64,827,719 | Time series with missing data | <p>Below you can find a dataset. There are 20 missing values in the time series, represented by NaN. Could you please show me how to write a python-3 script to get your best estimates of the NaN values?</p>
<p>Notice that you need to account for the fact that dates and times are not equally spaced, so you cannot just t... | <p>The interpolate method fills NAs with a linear estimate by default, but it can be setup to use datetime. The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html" rel="nofollow noreferrer">docs are here</a>. Below is an example using a few rows of your data:</p>
<pre>... | python-3.x|pandas|dataframe | 0 |
13,820 | 64,954,981 | Extract list of indices from pandas dataframe for first and last match | <p>Given the following data:</p>
<pre class="lang-py prettyprint-override"><code># example data
dt = pd.DataFrame(
{
"idx": [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4],
},
).assign(val=lambda x: range(len(x)))
</code></pre>
<p>I'd like to extract the following list:</p>
<pre><code>[0, 2, 3, 6,... | <p>groupby is not the worst option here</p>
<pre><code>dt.groupby('idx').agg(['first','last'])
</code></pre>
<p>produces</p>
<pre><code>
val
first last
idx
1 0 2
2 3 6
3 7 9
4 10 13
</code></pre> | python|pandas | 1 |
13,821 | 65,020,061 | Using .loc and shift() to add one to a serialnumber | <p>I'm trying to add two dataframes using concat with axis = 0, so the columns stay the same but the index increases. One of the dataframes contains a specific columns with a serial number (going from one upwards - but not necessarily in sequence eg. 1,2,3,4,5, etc.)</p>
<pre><code>import pandas as pd
import numpy as n... | <p>One idea is create arange by number od missinng values add maximal value and <code>1</code>:</p>
<pre><code>a = np.arange(c['Serial Number'].isna().sum()) + c['Serial Number'].max() + 1
c.loc[c['Serial Number'].isna(), 'Serial Number'] = a
print (c)
index Name Serial Number
0 0 A 1.0
1 1... | pandas|concat|shift|.loc | 1 |
13,822 | 64,794,588 | Count all values of an array that are between 0 and 1 | <p>Is there an effective way to count all the values in a numpy array which are between 0 and 1?</p>
<p>I know this is easily countable with a for loop, but that seems pretty inefficient to me. I tried to play around with the <code>count_nonzero()</code> function but I couldn't make it work the way I wanted.</p>
<p>Gr... | <p>One quick and easy method is to use the <code>logical_and()</code> function, which returns a boolean mask array. Then simply use the <code>.sum()</code> function to sum the <code>True</code> values.</p>
<p>Example:</p>
<pre><code>import numpy as np
a = np.array([0, .1, .2, .3, 1, 2])
np.logical_and(a>0, a<1... | python|python-3.x|numpy | 3 |
13,823 | 39,921,607 | How to make a custom activation function with only Python in Tensorflow? | <p>Suppose you need to make an activation function which is not possible using only pre-defined tensorflow building-blocks, what can you do?</p>
<p>So in Tensorflow it is possible to make your own activation function. But it is quite complicated, you have to write it in C++ and recompile the whole of tensorflow <a hre... | <p><strong>Yes There is!</strong></p>
<p><strong>Credit:</strong>
It was hard to find the information and get it working but here is an example copying from the principles and code found <a href="https://github.com/tensorflow/tensorflow/issues/1095" rel="noreferrer">here</a> and <a href="https://gist.github.com/harpone... | python|tensorflow|neural-network|deep-learning|activation-function | 85 |
13,824 | 39,867,061 | Pandas: get first 10 elements of a series | <p>I have a data frame with a column <code>tfidf_sorted</code> as follows:</p>
<pre><code> tfidf_sorted
0 [(morrell, 45.9736796), (football, 25.58352014...
1 [(melatonin, 48.0010051405), (lewy, 27.5842077...
2 [(blues, 36.5746634797), (harpdog, 20.58669641...
3 [(lem, 35.1570832476), (rottensteiner, 30.8800...
... | <p>IIUC you can use:</p>
<pre><code>from itertools import chain
#flat nested lists
a = list(chain.from_iterable(df['tfidf_sorted']))
#sorting
a.sort(key=lambda x: x[1], reverse=True)
#get 10 top
print (a[:10])
</code></pre>
<p>Or if need top 10 per row add <code>[:10]</code>:</p>
<pre><code>df['tfidf_sorted'] = df... | python|list|python-2.7|pandas|indexing | 3 |
13,825 | 44,234,139 | how to loop over pandas dataframe? | <p>I have a python function which works on sequence of coordinates (trajectory data). It requires data to be in the following format.</p>
<pre><code>#items = [Item(x1, y1), Item(x2, y2), Item(x3, y3), Item(x4, y4)]
items = [Item(0.5, 0.5), Item(-0.5, 0.5), Item(-0.5, -0.5), Item(0.5, -0.5)]
</code></pre>
<p>It is als... | <p>Gourpby return ((gkeys), grouped_dataframe)<br>
Modify your codes to following:</p>
<pre><code>for g in df.groupby('vid'):
vid = g[0]
g_df = g[1]
bbox = [ g_df['x'].min(), g_df['y'].min(), g_df['x'].max(), g_df['y'].max() ]
spindex.insert(vid, bbox)
</code></pre> | python|loops|pandas|numpy|dataframe | 1 |
13,826 | 44,120,889 | pandas: IndexError while iterating over DataFrame column | <p>So, I have this DataFrame and I'm trying to iterate over one of its columns:'Party', and it looks like this:</p>
<pre><code> Year President Party Value
0 1920 Woodrow Wilson Democratic NaN
1 1921 Warren G. Harding Republican 0.127172
... | <p>This code should give you the desired output</p>
<pre><code>df = pd.DataFrame({'year': [1920,1921,1922,1923,1924,1925,1926],
'pres': ['jon doe1','jon doe2','jon doe3','jon doe4','jon doe5','jon doe6','jon doe7'],
'party': ['dem','repub','dem','repub','dem','repub','repub'],
'value': [18.61, 17.60, 18.27... | python|pandas | 0 |
13,827 | 44,084,456 | Is it possible to compile tensorflow in Mac? | <p>So I started to build tensorflow in Mac and the thing is that it doesn't seem possible to build tensorflow in Mac OS platform. </p>
<p>After following instructions in <a href="https://www.tensorflow.org/install/install_sources" rel="nofollow noreferrer">here</a>, I get this package directory.</p>
<p><a href="https... | <p>It seems like there are no options but to install tensorflow with <strong>pip</strong>. So I just created a new virtual machine and installed <strong>ubuntu 16.04</strong> to use it as my docker host. By doing so, I can create a new docker container which can now link and execute the linux library.</p> | tensorflow | 0 |
13,828 | 69,383,004 | Pandas DataFrame - Getting first two rows in each group | <p>I have dataframe of below structure. Its grouped and sorted by first two columns. I want to have first two rows in each group. How i can get that?</p>
<p><a href="https://i.stack.imgur.com/9qwV0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9qwV0.png" alt="enter image description here" /></a></p... | <p>Use <code>groupby_head</code>:</p>
<pre><code>>>> df
open
AVN 20210929 119
20210928 110
20210927 120
PSMC 20210929 270
20210928 265
20210927 260
>>> df.groupby(level=0).head(2)
open
AVN 20210929 119
20210928 110
PSMC 2021092... | pandas|dataframe | 0 |
13,829 | 41,127,001 | Transform with unique value a column in dataframe with pandas | <p>I have the following dataframe : </p>
<pre><code>datas = [['RAC1','CD0287',1.52,1.40,1.45,1.51], ['RAC1','CD0695',2.08,1.40,1.45,1.51], ['RAC1','ADN103-1',2.01,1.40,1.45,1.51], ['RAC3','CD0258',1.91,1.38,1.43,1.45], ['RAC3','ADN103-3',1.66,1.38,1.43,1.45], ['RAC8','CD0558',1.32,1.42,1.48,1.53], ['RAC8','ADN103-8... | <p>It's helpful to think about what the nature of your different columns is. In this case your "Plate" and "Sample" columns really seem more like index information. So first I turned the "Plate" column into the index to make it easier to slice the dataframe:</p>
<pre><code>import pandas as pd
import numpy as np
datas... | python|pandas|dataframe | 2 |
13,830 | 54,126,065 | How to get the most frecuent categories of a column and store the rest's count in another column | <p>Imagine i have the following dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col1': ['a','b','c','d','e','f','g','h','i','j','k','l'], 'col2': [1,1,1,2,2,3,3,3,4,5,5,6]})
col1 col2
0 a 1
1 b 1
2 c 1
3 d 2
4 e 2
5 f 3
6 ... | <pre><code>def check_top(row, df_top):
"""create extra mask column called top3
it will be used to filter out col2 values"""
if row.col2 in df_top:
row['top3'] = True
else:
row['top3'] = False
return row
def update_cols(row):
"""update col2 and col3 values depending on top3 valu... | python|python-3.x|pandas|dataframe | 1 |
13,831 | 53,968,167 | Adding a new level to a dataframe | <p>I have created a dataframe that looks as follow:</p>
<pre><code>df=
id var0 var1 var2 var3 var4 ... var137
5171 10.0 2.8 0.0 5.0 1.0 ... 9.4
5171 40.9 2.5 3.4 4.5 1.3 ... 7.7
5171 60.7 3.1 5.2 6.6 3.4 .... | <p>You describe a <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer">cumulative count</a>:</p>
<pre><code>df['uniq_id'] = df.groupby('id').cumcount()
</code></pre>
<p>You can add it to the index by</p>
<pre><code>df.set_index(['id', '... | python|pandas|dataframe|multi-index | 2 |
13,832 | 38,329,428 | Changing the format of a column of Data frame from Str to Date in specific format | <p>I have two data frames which I have to merge on Date.
but the type of data isn't same. They are Date and of str format.</p>
<pre><code>print(visit_data.iloc[0]['visit_date'])
2016-05-22
type(visit_data.iloc[0]['visit_date'])
Out[40]: datetime.date
print(holiday_data.iloc[0]['visit_date'])
1/1/2016
type(holiday_d... | <p>If you want it to return as a <code>datetime</code> object, you could do this:</p>
<pre><code>import datetime
holiday_data['visit_date'] = holiday_data['visit_date'].apply(lambda x:
datetime.datetime.strptime(x,'%m/%d/%Y'))
</code></pre>
<p><strong>EDIT :</strong></p>
<p>To ... | python|python-2.7|pandas|merge | 0 |
13,833 | 52,688,699 | How can I store data into a Dataframe variable within a loop statement? | <pre><code>I write:
sortstocks['stockCode']=myStock
sortStocks['ratio']=ratio
</code></pre>
<p>It doesn't work. More code as blow:</p>
<pre><code> for idx, myStock in enumerate(stockList):
close=history(myStock, ['close'], 500, '1d', False, 'pre' )
if len(close)>499:
....
if (MA10Yest... | <p>If your code above is a correct copy of the code you've run, then the error is in a typo in the 3rd last line:</p>
<pre><code>sortstocks['stockCode']=myStock
</code></pre>
<p>should be:</p>
<pre><code>sortStocks['stockCode']=myStock
</code></pre>
<p>(with capital 'S' for ..Stocks)</p> | python|pandas|dataframe | 1 |
13,834 | 46,279,591 | using multiple separate neural nets on the same tensor-flow import | <p>I have built a generic python class for interacting with trained neural networks that are saved using "tf.saved_model.builder.SavedModelBuilder".</p>
<p>when I inherit from the class once with a given neural net, everything works correctly. however, when i inherit once more with a second neural net with different a... | <p>Use different graphs for different nets.</p>
<p>You can do something like:</p>
<pre><code>def __init__(self, netName, inputName, outputName):
self.graph = tf.Graph()
# opens a tensorflow session to use continously
# use self.graph as graph the the session
self.session = tf.Session(config=config, gr... | python|tensorflow|tensorflow-serving | 2 |
13,835 | 46,587,579 | Python math module grad | <p>I am trying to use the basic sin, cos, arctan, etc function from numpy, but I want to use gradians. I have search the doc without success, and search for other python modules without luck. Any suggestion on a python module i could use?</p>
<p>Or a function that will work. I have tried different methods to convert g... | <p>This one should be fine !</p>
<pre><code>def gradFromRad(rad):
return 200*rad/math.pi
def radFromGrad(grad):
return math.pi*grad/200
</code></pre> | python|numpy|trigonometry|gon | 4 |
13,836 | 46,200,969 | How to group all labels (index) which shares at least one "1" in the same column? | <p>Grouping Rules:</p>
<ul>
<li>has at least one "1" in the same column</li>
<li>shares any number of rows in common (see example)</li>
</ul>
<p>For example:</p>
<pre><code> c0 c1 c2 c3
A 1 0 0 1
B 0 0 1 0
C 0 0 0 1
D 0 1 1 0
E 0 1 0 0
</code></pre>
<p>Expected output:</... | <p>Here is a solution with networkx.</p>
<pre><code>import networkx as nx
a = np.where(df.T, df.index, '').sum(axis=1)
g = [list(x) for x in a if len(x) > 1]
G = nx.Graph(g)
list(nx.connected_components(G))
[{'B', 'D', 'E'}, {'A', 'C'}]
</code></pre> | python|pandas|numpy | 5 |
13,837 | 58,471,547 | Mapping and slicing column values | <p>I have a visit_start_time column which is in this format: "31/08/2019 20:36"</p>
<p>I want to create a <code>Visit_date</code> column which includes just the date of the visit, for example <code>31/08/2019</code>.</p>
<p>I tried to use map function and split just the string.</p>
<pre><code>active_visits_St... | <p>ok guys i solved this using this code:</p>
<pre><code>active_visits_StpNshp['visit_date'] = active_visits_StpNshp['visit_date'].map(lambda x: x.split(' ')[0])
</code></pre>
<p>the map method return the Series object i just had to reasign it.</p> | python|pandas | 0 |
13,838 | 58,349,200 | I don't know why python is throwing this error | <p>I'm trying to create a program which plots the velocity of a ball in freefall versus that of a ball with exposure to a drag force such that F_drag = -Cv^2 where C is a constant (m*g)/100. My inputs are 5 for m, 5 for tf, and 0.1 for dt.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib i... | <p>In your second while loop you should be using <code>i2</code> as the index variable. Since during the first iteration of the loop, <code>t2[i]</code> is really <code>t2[50]</code>, but at that time, <code>t2</code> only has one element, so the index is out of bounds. </p>
<pre><code>import numpy as np
import matplo... | python|arrays|numpy|physics | 0 |
13,839 | 68,935,602 | Got the Error: ValueError: Cannot convert non-finite values (NA or inf) to integer | <p>I applied this code:</p>
<pre><code># Counting genre_id
def genre_id_count(x):
if x == 'no_genre_id':
return 0
else:
return x.count('|') + 1
# filling NA in place of null values
train['genre_ids'].cat.add_categories('no_genre_id').fillna('no_genre_id', inplace=True)
test['genre_ids'].cat.add... | <p>The reason why your code does not work is the following: when you apply <code>train['genre_ids'].cat.add_categories('no_genre_id')</code> then this method returns a new pandas series. You apply <code>.fillna('no_genre_id', inplace=True)</code> to this new series. As you set <code>inplace=True</code>, this new series... | python|pandas|numpy | 0 |
13,840 | 69,148,226 | Finding the closest value of median value in duplicated rows of dataframe | <p>I have a DataFrame which contains more than 2000 rows.</p>
<p>Here is a part of my DataFrame:</p>
<pre><code>In [2]: df
Out[2]:
A B C D
0 a b -1 3.5
1 a b -1 52
2 a b -1 2
3 a b -1 0
4 a b 0 15
5 a c -1 1612
6 a c 1 ... | <p>Try this following one-liner with <code>groupby</code> and <code>tranform</code> with <code>lambda</code>:</p>
<pre><code>>>> df['Next_Med'] = df.sort_values([*'ABC']).groupby([*'ABC'])['D'].transform(lambda x: x == min(x, key=lambda y: abs(y - x.median()))).astype(int).reset_index(drop=True)
>>> d... | python|pandas|dataframe|median | 0 |
13,841 | 68,966,403 | AWS Deep Learning AMI with Python3.9 | <p>I tried using the formal AWS Deep Learning AMI.
It is published here: <a href="https://aws.amazon.com/marketplace/pp/prodview-d5wlsowr2cimk" rel="nofollow noreferrer">https://aws.amazon.com/marketplace/pp/prodview-d5wlsowr2cimk</a>
(currently version 49.0)</p>
<p>My problem is that it uses <code>Python3.7</code> whi... | <p>You can't use the the DLAMI virtual environment out of the box, yet you can create a new python virtual environment which imports all its content.</p>
<p>For example, you can edit <code>PYTHONPATH</code> and <code>LD_LIBRARY_PATH</code>:</p>
<pre><code>export PYTHONPATH=$PYTHONPATH:/home/ec2-user/anaconda3/envs/<... | amazon-web-services|tensorflow|python-3.9 | 0 |
13,842 | 44,754,881 | Merge dataframes that have indices that one contains another (but not the same) | <p>For example df1 has shape <code>(533, 2176)</code>, indices such as <code>Elkford (5901003) DM 01010</code>, df2 has shape <code>(743, 12)</code>, indices such as <code>5901003</code>; the number in the bracket of indices of df1 will match that of df2. And as the shape has shown some indices don't match at all. And ... | <p><strong>file1.csv</strong>:</p>
<pre><code>,col_1,col_2
5901001,a,-1
5901002,b,-2
5901003,c,-3
5901004,d,-4
5901005,e,-5
5901006,f,-6
5901007,g,-7
5901008,h,-8
5901009,i,-9
5901010,k,-10
</code></pre>
<p>Here <code>df1.shape = (10, 2)</code>.</p>
<p><strong>file2.csv</strong>:</p>
<pre><code>,col_3
Elkford (Part... | python|pandas|dataframe|indexing|merge | 0 |
13,843 | 60,920,083 | Python: multiplying fixed array by element wise second array | <p>Example code:</p>
<pre><code>import numpy as np
a = np.arange(1,11)
b = np.arange(1,11)
b[:] = 0
b[3] = 10
b[4] = 10
print(a, b)
[ 1 2 3 4 5 6 7 8 9 10] [ 0 0 0 10 10 0 0 0 0 0]
</code></pre>
<p>I am attempting to multiply b by element-wise a-array such that my resulting array is the following:</p>
... | <p>It looks like you want the <a href="https://en.wikipedia.org/wiki/Convolution" rel="nofollow noreferrer"><code>convolution</code></a> of both arrays:</p>
<pre><code>np.convolve(a,b)[:len(a)+1]
# array([ 0, 0, 0, 10, 30, 50, 70, 90, 110, 130, 150])
</code></pre> | python|numpy | 1 |
13,844 | 61,076,948 | Reading a csv file in using pandas csv_read in a for loop | <p>I am using Macbook with MAC OS X catalina and the latest anaconda installation.</p>
<p>I have a list of files I want to be read in a folder I have with many files. The list of files are contained in an excel sheet in the following format. </p>
<p><a href="https://i.stack.imgur.com/NOR8Y.png" rel="nofollow noreferr... | <p>This would be a work around:</p>
<pre><code>filelist = pd.read_excel("/Users/XXX/Documents/test/list.xlsx")
DF = []
for i in range(len(filelist)):
file = str(filelist[i])
df = pd.read_csv(file, index_col=None, header=0)
DF.append(df)
#combine all files
DF = pd.concat(DF, axis=0, ignore_index=True)
</co... | python|excel|pandas|csv|for-loop | 0 |
13,845 | 71,638,833 | How do i use medical codes to determine what disease a person have using jupyter? | <p>I'm currently trying to use a number of medical codes to find out if a person has a certain disease and would require help as I tried searching for a couple of days but couldn't find any. Hoping someone can help me with this. Considering I've imported excel file 1 into df1 and excel file 2 into df2, how do I use exc... | <p>You can use <code>merge</code> and <code>pivot_table</code></p>
<pre><code>out = (
df1.melt('Patient', var_name='Diagnosis', value_name='Medical Code').dropna()
.merge(df2, on='Medical Code').assign(dummy=1)
.pivot_table('dummy', 'Patient', 'Primary Diagnosis', fill_value=0)
.add_prefix('Pos... | python|excel|pandas|jupyter-notebook|jupyter | 2 |
13,846 | 71,749,309 | Concatenate strings only if they aren't NA values | <p>I'm trying to concatunate 4 string variables in a pandas dataframe. The dataframe is something like this:</p>
<pre><code>Morada 1 Morada 2 Localidade Postal Code
RUA DOS QUATRO CAMINHOS VEREDA 2 N 14 4DTO SUL CANIDELO 4400-501
RUA DOS QUATRO CAMINH... | <p>You could combine the <code>DataFrame</code> using a lambda like my example below:</p>
<pre><code>df['combined'] = df.apply(lambda row: ' '.join(row.dropna().astype(str)), axis=1)
</code></pre>
<p>This will create a new column for you with combined strings joined, ignoring missing values.</p> | python|pandas | 0 |
13,847 | 71,765,960 | Applying operations on multiple column values and storing in another dataframe | <p>There is a dataframe with about 10 columns and the need is to divide columns with one another and store the result in another dataframe column.</p>
<p>Dataframe looks like -</p>
<pre><code> c1 c2 c3 c4 c5 c6 c7 c8 c9 c10
0 10 100 200 300 400 500 600 700 800 900
1 11 110 210 31... | <p>Based on the result you displayed, you tried to divide col6 by col1, col7 by col2 and so on.</p>
<p>You can achieve this using this command:</p>
<pre><code>pd.DataFrame(df[['c6', 'c7', 'c8', 'c9', 'c10']].values / df[['c1', 'c2', 'c3', 'c4', 'c5']].values, columns=['col1', 'col2', 'col3', 'col4', 'col5'])
</code></p... | python|pandas|dataframe | 0 |
13,848 | 71,673,911 | Sum up values present in vertical Dataframe in Horizontal DataFrame and create new column in Horizontal Dataframe | <p>I am having dataframe <code>idf</code> as below. I have another Dataframe <code>df</code></p>
<pre><code>idf
Output-
feature_name idf_weights
2488 kralendijk 11.221923
3059 night 11.221923
1383 ebebf 11.221923
</code></pre>
<pre><code>df
Output-
message Number ... | <p>One way to do it is to convert idf to a dictionary first, like that:</p>
<pre><code>words_weights = dict(idf[['feature_name', 'idf_weights']].values)
{'kralendijk': 11.221923, 'night': 11.221923, 'ebebf': 11.221923}
</code></pre>
<p>then just split the message col, get corresponding value for each word from dict an... | python-3.x|pandas|dataframe | 0 |
13,849 | 71,710,302 | Problem with uploading CSV file in python | <p>I have some problem with uploding excel data in python.</p>
<p><strong>Excel</strong>:</p>
<p><img src="https://i.stack.imgur.com/LSWix.png" alt="image" /></p>
<p><strong>Code</strong> used to upload:</p>
<pre><code>import pandas as pd
from google.colab import files
#uploaded = files.upload()
import io
df2 = pd.read... | <p>If you have a csv-file <code>file.csv</code></p>
<pre><code>0,0
2,0
4,0
1,1.732051
3,1.732051
</code></pre>
<p>then</p>
<pre><code>df = pd.read_csv("file.csv", index_col=0)
</code></pre>
<p>does produce</p>
<pre><code>df =
0.1
0
2 0.000000
4 0.000000
1 1.732051
3 1.732051
</code></pre... | python|pandas|csv|file|uploading | 0 |
13,850 | 42,351,499 | How to convert string back to list using Pandas | <p>I have a txt file with some data and one of the columns is like this:</p>
<pre><code>['BONGO', 'TOZZO', 'FALLO', 'PINCO']
</code></pre>
<p>In order to load the file I use the pandas function <code>to_csv</code>.</p>
<p>Once the dataframe is loaded it looks like the content is ok but then I realize that the item w... | <p>You can use <code>ast.literal_eval</code> as :</p>
<pre><code>>>> import ast
>>> a = "['BONGO', 'TOZZO', 'FALLO', 'PINCO']"
>>> print ast.literal_eval(a)
>>> ['BONGO', 'TOZZO', 'FALLO', 'PINCO']
</code></pre> | python|string|list|pandas|char | 14 |
13,851 | 43,208,245 | Change CSV before importing it to pandas | <p>I have an issue with a CSV files I am trying to import in pandas. The structure of the file is as follow:</p>
<ul>
<li>first character of the file is a single quote;</li>
<li>last character of the file is a single quote;</li>
<li>every line of the CSV start with a double quotes, end with a double quote followed by ... | <p>The <code>pd.read_csv</code> methods first argument is either a file name or a stream. </p>
<p>You can read the file manually and manipulate the stream before handing it to pandas.</p>
<pre><code>sio = StringIO("id,category,value\n1,beer,2.40\n2,wine,6.40\n3,$$$Theawsomestuff$$$###,166.00"
pd.read_csv(sio)
id ... | python|csv|pandas|quotes|double-quotes | 1 |
13,852 | 43,076,454 | Feeding image features to tensorflow for training | <p>Is it possible to feed image features, say SIFT features, to a convolutional neural network model in Tensorflow? I am trying a tensorflow implementation of <a href="http://richzhang.github.io/colorization/" rel="nofollow noreferrer">this project</a> in which a grayscale image is coloured. Will image features be a be... | <p>You can feed tensorflow neural net almost anything.
If you have extra features for each pixel, then instead of using one channel (intensity) you would use multiple channels.</p>
<p>If you have extra features, which are about whole image, you can make separate input a merge features at some upper layer. </p>
<p>As ... | machine-learning|tensorflow | 0 |
13,853 | 43,319,855 | How do i move data from one column to another on values that aren't equal in pandas? | <p>I have two columns in one data frame 'first name' and 'preferred name'. If the preferred name is different to first name, I want to move that value to first name. e.g.:</p>
<pre><code> First Name Preferred Name
1 David Dave
2 John John
3 Sarah Sarah
4 Elizabeth Liz
... | <p>slightly impatient, so i did it the 'ugly' way. queried the data for indices where names are different, and then added them on those values</p>
<pre><code>name_index = df[df['first name'] != df['preferred name']]
df.ix[name_index,'first name'] = df.ix[name_index,'preferred name']
</code></pre> | python|pandas | 0 |
13,854 | 72,153,927 | Merge 2 dataframes with same column headers creating subheaders | <p>I have 2 dataframes to do with Covid-19</p>
<pre><code>df_infect
Dates Australia Bahamas .......
1/22/20 0 0 .......
1/23/20 0 1 .......
</code></pre>
<p>and</p>
<pre><code>df_death
Dates Australia Bahamas .......
1/22/20 ... | <p>You can merge on <code>Dates</code> with appropriate suffixes; then split the column names to create MultiIndex columns:</p>
<pre class="lang-py prettyprint-override"><code>out = pd.merge(df_infect, df_death, on='Dates', suffixes=('_infected','_dead')).set_index('Dates')
out.columns = out.columns.str.split('_', expa... | python|python-3.x|pandas|dataframe|pandas-merge | 2 |
13,855 | 72,281,678 | Unable to download CIFAR-10 dataset | <p>I am attempting to run a GoogLeNet code, but when I run it, for some reason it says</p>
<pre><code>[INFO] loading CIFAR-10 data...
[INFO] compiling model..
</code></pre>
<p>but when my friend runs the same code, his shows</p>
<pre><code>[INFO] loading CIFAR-10 data...
Downloading data from https://www.cs.toronto.edu... | <p>Have you looked at the local datasets ⁉️</p>
<p><strong>[ Local datasets ]:</strong></p>
<pre><code>C:\Users\Jirayu Kaewprateep\.keras\datasets
</code></pre>
<p><strong>[ Sample ]:</strong></p>
<pre><code>import os
from os.path import exists
import tensorflow as tf
import tensorflow_datasets as tfds
""&q... | python|tensorflow|conv-neural-network | 1 |
13,856 | 72,315,220 | Adding values in columns from 2 dataframes | <p>I have 2 dataframes as below, some of the index values could be common between the two and I would like to add the values across the two if same index is present. The output should have all the index values present (from 1 & 2) and their cumulative values.</p>
<pre><code> Build
2.1.3.13 2
2.1.3.1 ... | <p>You can try <code>merge</code> with <code>outer</code> option or <code>concat</code> on columns</p>
<pre class="lang-py prettyprint-override"><code>out = pd.merge(df1, df2, left_index=True, right_index=True, how='outer').fillna(0)
# or
out = pd.concat([df1, df2], axis=1).fillna(0)
out['sum'] = out['Build'] + out['R... | python|pandas|dataframe | 4 |
13,857 | 50,256,571 | Column Names in Pandas (Python) | <p>Python : Pandas : Data Frame : Column Names</p>
<p>I have large number of columns and column names are also very large. I would like to see few columns and rows but view becoming restricted to size of column names. How can I temporarily see dataframe in Python without column names (just display data )</p> | <p>Convert DataFrame to numpy array:</p>
<pre><code>print (df.values)
</code></pre>
<p>But maybe here is possible select values of columns by positions first by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a>:</p>
<pre><code>p... | python|pandas | 2 |
13,858 | 50,437,311 | Reading a JSON File into a dataframe WITHOUT using the json module | <p>I have a large json file that I need to read into a pandas dataframe <em>without using the json module</em>. Here is a link to the file <a href="https://www.dropbox.com/s/i5hurs2qjk4z8af/Melbourne_bike_share.json?dl=0" rel="nofollow noreferrer">melbourne_bike_share.json</a>. I didn't know what to cut out to make a m... | <p>I think you are looking for something like this:</p>
<pre><code>import pandas as pd
df = pd.read_json('Melbourne_bike_share.json', typ='series')
pd.DataFrame(data=df['data'])
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 155 7C09387D-9E6C-4B42-9041-9A98B88F54BB 155 1428899388 880594 14539455... | json|python-3.x|pandas|dataframe | 1 |
13,859 | 45,472,410 | ValueError during Combine (Concat) operations of two Pandas DataFrames to glue additional columns | <p>I have two data frames as shown below (showing only a couple rows. here). When I do the following:</p>
<pre><code>pd.concat([df1,df2],axis=1)
</code></pre>
<p>I get the following error that is a ValueError as noted below. I have provided the two data frames that I am combining below to be able to replicate my issu... | <p>I realize the issue now. I had duplicate indices on both my dataframes (that really did not show in the example above). My index in both data frames was "Sample_ID" and I really want those duplicate rows in my data. Therefore, here is what I ended up doing for both the data frames, df1 and df2, one at a time before ... | python|pandas | 0 |
13,860 | 45,581,122 | Using the function 'math.radians()' cannot convert the series to <class 'float'> | <p>This is my code,why the error occurs?</p>
<p><img src="https://i.stack.imgur.com/Dc7by.jpg" alt="This is my code,why the error occurs?"></p> | <p>You are trying to use a function designed for floats to accept series.</p>
<p>Change your d = radians(c) to</p>
<pre><code>d = c.map(radians)
</code></pre>
<p>To apply the radians function to every value in the c series.</p> | python|pandas|math | 1 |
13,861 | 62,696,182 | How to modify groupby() in python | <p>I hope you are safe and having a good time. In the below code snippet, I am trying to create a timeline graph that depicts an overall trend. I thought of process like:</p>
<ul>
<li>Form a dataframe using groupby() to calculate the actual rate [check below code]</li>
<li>plot the data frame using iplot()</li>
</ul>
<... | <p>Try using the seaborn library:</p>
<pre><code>import seaborn as sns
sns.lineplot(x="year", y="rate", hue="disease", data=actual_rate1)
</code></pre> | python|pandas|matplotlib|plotly | 0 |
13,862 | 62,540,351 | I am unable to set the xticks of my lineplot in Seaborn to the values of the coresponding hour | <p>I tried a lot of diffent methods but I can't get a reasonable xtick labeling. This is the code I wrote.</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib
import datetime
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
#Line of Code just for importing the... | <p>Since I do not have access to your data, I created fake one in order to have some data to work with. You can just use your <code>df</code>.<br />
Check this code:</p>
<pre><code>import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
N = 1440
ti... | python|pandas|matplotlib|seaborn|visualization | 4 |
13,863 | 62,522,836 | create new column based on next closest ranking pandas | <p>I have a list of products that are for sale on a subscription basis. the prices vary per region (about 15 regions). I'm trying to find the next closest priced product available on that day (not the cheapest on that day). My data looks like this</p>
<pre><code>data = [['29/10/20', 400, 300, 2, 1],
['29/10/20'... | <p>EDIT: (2-July-2020). The OP wanted the output, so that if there are duplicate prices, then the nearest price cannot be the same.</p>
<p>See new solution below which has added <code>np.where</code> and <code>bfill()</code></p>
<pre><code>import pandas as pd
import numpy as np
data = [['29/10/20', 400, 300, 2, 1],
... | python|pandas | 1 |
13,864 | 62,696,836 | Numpy array equality boolean | <p>The following two approaches should yield an identical result, but it seems they do not:</p>
<p><strong>Approach 1</strong>:</p>
<pre><code>#Generate an array with 12 annual fractions corresponding to each month
ann_frac = np.arange(1,13,1).reshape([12,1])
ann_frac = ann_frac[:,0]/12
</code></pre>
<p>Output:</p>
<pr... | <p>I think you are comparing arrays with different dimensionality. What I guess you want is</p>
<pre><code>ann_frac = np.arange(1,13,1).reshape([12,1])
ann_frac1 = ann_frac[:,0]/12
i = np.arange(1,13,1)
ann_frac2 = (i/12).reshape([12,1])
ann_frac3 = (i/12).reshape(12)
</code></pre>
<p>and the correct comparison should ... | python|arrays|numpy|random|numpy-ndarray | 0 |
13,865 | 62,630,035 | Split numpy array based on arbitrary values contained in it | <p>I’d like to split this (numpy) array:</p>
<p><code>[ 4 0 1 3 2 3 8 10 11 4 12 13 15 14 4 16 18 19 17 4 20 21 23 22]</code></p>
<p>into something like this:</p>
<p><code>[[0 1 3 2] [8 10 11] [12 13 15 14] [16 18 19 17] [20 21 23 22]]</code></p>
<p>The first number <code>4</code>, indicates how many subsequent numbers... | <p>I don't know if numpy has something for your problem.</p>
<p>This is simple solution but probably for big list it may not be so efficient</p>
<pre><code>data = [4, 0, 1, 3, 2, 3, 8, 10, 11, 4, 12, 13, 15, 14, 4, 16, 18, 19, 17, 4, 20, 21, 23, 22]
results = []
while data:
number = data.pop(0)
results.append... | python|arrays|list|numpy|split | 0 |
13,866 | 54,270,291 | Find Duplicates in One Column, Compare Another Column, Modify a Third Column in DataFrame | <p>Rather than explain this in a use case agnostic way I will provide the columns names as this is much clearer.</p>
<p>I have three columns: PlayerName, Salary, Position.</p>
<p>An example:</p>
<pre><code>PlayerName, Salary, Position
Joe, 3000, FWD
Joe, 4500, FWD
Bill, 3200, CNT
Bill, 2000, CNT
Jill, 1200, GRD
Jill... | <p>You say that there are always 2 duplicate entries, so you can simply use <code>idxmax</code> + <code>loc</code>:</p>
<pre><code>m = df.groupby('PlayerName')['Salary'].idxmax()
df.loc[m, 'Position'] = 'CPT' + df.loc[m, 'Position'].map(' ({})'.format)
</code></pre>
<p></p>
<pre><code> PlayerName Salary Position... | python|pandas | 2 |
13,867 | 73,683,611 | PyTorch model output different dimension when using DataParallel | <p>I implemented my PyTorch model with DataParallel for multi-GPU training. However, it seems that the model doesn't consistently output the right dimension. In the training loop, it seems that the model gave the correct output dimension for the first two batches, but it failed to do so for the third batch and caused a... | <p>It seems like you are left with only one sample for the last batch. Try setting <code>drop_last=True</code> in your <a href="https://pytorch.org/docs/stable/data.html?highlight=dataloader#torch.utils.data.DataLoader" rel="nofollow noreferrer"><code>Dataloader</code></a>: This will discard the last "not-full&quo... | python|parallel-processing|pytorch|gpu|multi-gpu | 1 |
13,868 | 73,549,350 | Practices for a fast drop_duplicates() in Dask | <p>I read CSV files from an AWS bucket using Dask. I want to drop duplicates from a big data-frame.</p>
<p>The number of partitions is 755,286 and the number of tasks is 1,510,572.</p>
<p>I'm wondering what could be a faster way to drop duplicates from the data-frame.</p>
<p>Here's my code:</p>
<pre><code>df = dd.read_... | <p>The suggestion in @Kevin Kho's comment might help even if there are duplicates across partitions: a combination of <code>map_partitions</code> and <code>pd.drop_duplicates</code> can potentially trim down the content of each partition.</p>
<p>If the data is shuffled across partitions in a way that requires a lot of ... | python|pandas|amazon-web-services|amazon-s3|dask | 0 |
13,869 | 73,714,163 | Pandas dataframe consider multiple columns to an aggregate function for each group | <pre><code>import pandas as pd
from functools import partial
def maxx(x, y, take_higher):
"""
:param x: some column in the df
:param y: some column in the df
:param take_higher: bool
:return: if take_higher is True: max(max(x), max(y)), else: min(max(x), max(y))
""... | <p>You can use apply</p>
<pre><code>def maxx(gdf,take_higher):
if take_higher:
return(max(max(gdf.x),max(gdf.y)))
else:
return(min(max(gdf.x),max(gdf.y)))
df.groupby(df.cat).apply(lambda g:maxx(g,take_higher=False))
# do both aggregation in one call
df.groupby(df.cat).apply(lambda g:p... | pandas|dataframe|group-by|aggregate | 1 |
13,870 | 73,616,963 | "RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation" when there's actually no in-place operations | <p>I am working on some paper replication, but I am having trouble with it.</p>
<p>According to the log, it says that <code>RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation.</code> However, when I check the line where the error is referring to, it was just a simple prope... | <p>In-place operation means the assignment you've done is modifiying the underlying storage of your Tensor, of which <code>requires_grad</code> is set to True, according to your error message.</p>
<p>That said, your <code>param.pdfvec[self.key]</code> is not a leaf Tensor, because they will be updated during back-propa... | python|pytorch | 2 |
13,871 | 71,229,988 | Getting `ValueError: `logits` and `labels` must have the same shape, received ((None, 1) vs ())` error | <p>I'm trying to train my model and receiving this error when I call the <code>fit()</code> method.
Any ideas on why is this failing to run?</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import tensorflow as tf
df = pd.read_csv('labeled_tweets_processed.csv')
labels = df.pop('class')
dataset ... | <p>Maybe try something like this:</p>
<pre><code>import pandas as pd
import tensorflow as tf
df = pd.DataFrame(data = {'texts': ['Some text', 'Some text', 'Some text', 'Some text', 'Some text'],
'class': [0, 0, 1, 1, 1]})
labels = df.pop('class')
dataset = tf.data.Dataset.from_tensor_slices(... | python|pandas|numpy|tensorflow|keras | 1 |
13,872 | 71,416,702 | Reshape dimensions in a tiff file | <p>I am working on a code that would take my tif file of dimension [5,1024,1024,3] to reorder it to produce dimension of [5, 3, 1024, 1024]. [5,1024,1024,3] shows the dimension of [nplane x nY x nX x nchannels]. The goal is to get [nplane x nchannels x nY x nX ] or [5, 3, 1024, 1024] I am not sure what is the problem. ... | <p><code>np.transpose(data, (0, 3, 1, 2))</code> will move the data around so that the 4th axis is between the first two.</p> | python|numpy|reshape|tiff | 0 |
13,873 | 71,316,086 | Python - Filter out rows from dataframe based on match on columns from another dataframe | <p>I have the 2 dataframes as below:</p>
<p><a href="https://i.stack.imgur.com/B9alG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B9alG.png" alt="enter image description here" /></a></p>
<p>Based on the values of df2, if df1 rows matches ALL the conditions of df2, then remove it from df1.
Expected... | <pre><code>for i in range(len(df2)):
for j in range(len(df1)):
if (df2['book'][i] == "[NULL]" or df2['book'][i] == df1['book'][i]
and df2['business'][i] == "[NULL]" or df2['business'][i] == df1['business'][i]
and df2['product'][i] == "[NULL]" or df2['product'][... | python-3.x|pandas|dataframe | 0 |
13,874 | 71,160,484 | pandas: fillna with data from another dataframe, based on the same ID and keeping all values | <p>I want to fillna of df1, using df2, based on same colorID while keeping all rows and columns of df1.</p>
<p>df1=</p>
<pre><code>colorID age flower
red1 12 sun
red2 na sun
green 23 hydro
red3 na hydro
yellow 3 sun
red4 na hydro
</code></pre>
<p>df2=</p>
<pre><code>colorID a... | <p>You can pass a <code>DataFrame</code> to the fillna function after setting the <code>index</code> of both the <code>DataFrame</code>s to the common field - <code>colorID</code></p>
<pre><code>df1 = df1.set_index('colorID')
df2 = df2.set_index('colorID')
df1 = df1.fillna(df2)
# age flower
#colorID
#... | python|pandas|fillna | 1 |
13,875 | 52,078,235 | Storing multi-dimensional attributes (columns) in pandas DataFrame | <p>What is the best way of storing items with several entries (fixed length) in a <code>pandas</code> <code>DataFrame</code> column? I’m thinking of something like a 3D position vector. For example, if my <code>DataFrame</code> is storing data about a bunch of physical objects, it could look like this:</p>
<pre><code>... | <p>I like this</p>
<pre><code>d = pd.concat([
df[['mass', 'type']],
pd.DataFrame(df.pos.tolist(), df.index, ['x', 'y', 'z']),
pd.DataFrame(df.vel.tolist(), df.index, ['x', 'y', 'z'])
], axis=1, keys=['Scalar', 'Position', 'Velocity'])
d
Scalar Position Velocity
mass type ... | python|pandas|numpy | 9 |
13,876 | 52,413,152 | How can I make my program to use multiple cores of my system in python? | <p>I wanted to run my program on all the cores that I have. Here is the code below which I used in my program(which is a part of my full program. somehow, managed to write the working flow).</p>
<pre><code>def ssmake(data):
sslist=[]
for cols in data.columns:
sslist.append(cols)
return sslist
def ... | <p>Your code has all what is needed to run on multi-core processor using more than one core. But it is a mess. I don't know what problem you trying to solve with the code. Also I cannot run it since I don't know what is <code>DBSCAN</code>. To fix your code you should do several steps.</p>
<p>Function <code>scorecal()... | python-3.x|pandas|multiprocessing|pool|dbscan | 2 |
13,877 | 52,175,020 | Pandas DataFrame do something if a value is string | <p>I have a table with a column named 'Amount'. The cell values are mixture of numbers such as 1, 100, and 1000, and strings such as '(1000)' and '(999)' which indicates a negative value. How would I change the strings of negative values to numbers, like -1000 and -999?
I don't know how to apply conditions on panda dat... | <p>Simply use <code>strip</code>. Although in your question, it is ambiguous if the values in parenthesis contain negative symbols or if the parenthesis need to be replaced with a negative symbol. If it is the latter you will need a regular expression here.</p>
<p></p>
<pre><code>df.Amount.astype(str).str.strip('()... | python|string|pandas|dataframe|numbers | 1 |
13,878 | 60,628,105 | Set Pandas Column to NumPy Array | <p>Let's say that I have a NumPy Array:</p>
<pre><code>x = np.array([0, 1, 1, 3, 4, 0, 5, 2, 2, 1])
</code></pre>
<p>and a Pandas DataFrame:</p>
<pre><code>df = pd.DataFrame({'start': [2, 5, 1, 0, 0], 'stop': [6, 9, 4, 3, 2]})
# start stop
# 0 2 6
# 1 5 9
# 2 1 4
# 3 0 3
# 4 ... | <p>You can do like this.</p>
<pre><code>>>> x = np.array([0, 1, 1, 3, 4, 0, 5, 2, 2, 1])
>>> df = pd.DataFrame({'start': [2, 5, 1, 0, 0], 'stop': [6, 9, 4, 3, 2]})
>>> df['sequence'] = [x[df['start'][idx]:df['stop'][idx]] for idx in range(len(df))]
>>> df
# start stop seque... | python|arrays|pandas|numpy|dataframe | 0 |
13,879 | 60,557,383 | python: grouping or splitting up time series data based on conditions | <p>I work a lot with time series data at my job and I have been trying to use python--specifically pandas--to make some of the work a little faster. I have some code that reads through data in a <code>DataFrame</code> and identifies segments where specified conditions are met. It then separates those segments into indi... | <p>Welcome to Stack Overflow.</p>
<p>I think your code can be simplified as such:</p>
<pre><code># Get the subset that fulfills your conditions
df_conditioned = df.query('Temp > 23 and Temp < 30').copy()
</code></pre>
<pre><code># Check for discontinuities by looking at the indices
# I created a new column ca... | python|pandas|time-series|pandas-groupby|itertools | 1 |
13,880 | 72,738,298 | pandas pivot_table write to excel outputs empty sheet | <p>It's just so strange.</p>
<p>The pivot_table is definitely not empty. When I print it out it shows everything without problem. But when I try to write it to_excel with ExcelWriter(or just to_excel), it gives me an almost empty sheet(with values only and nothing else).</p>
<p>Here's my code:</p>
<pre><code>result = d... | <p>I've figured it out myself. I just need to convert the <code>pivot_table</code> <code>to_records</code> and turn it to dataframe once again before export it <code>to_excel</code>, and the output is perfect.
Simply change the codes like this:</p>
<pre><code>pd.DataFrame(result.to_records()).to_excel(writer,sheet_name... | python|pandas|pivot|pivot-table|export-to-excel | 0 |
13,881 | 32,279,013 | SQL Alchemy - Deferring Multiple Groups | <p>I'm trying to un-defer multiple groups in a sql alchemy query. Some of the columns I want aren't coming through once I include another group to un-defer. Both groups work when I un-defer individually--but it appears the second group is being read and not the first. Does anyone know if it's possible to un-defer multi... | <p>Ok if there are no takers....my workaround was to create two separate data frames by having two of the same queries with one of each group being undeferred. I merged them on a consistent column and I'm moving on with my life :)</p> | python|pandas|sqlalchemy | 1 |
13,882 | 32,217,532 | Why does the image values not change based on threshold | <p>I am using an ndarray from numpy to represent a grey-scale image. I am trying to change some pixel values to either black or white depending on a threshold. The first implementation is as follows:</p>
<pre><code> bwImage = image #ndArray
for h in range(image.shape[0]):
for w in range(image.shape[1])... | <h2>Method 1</h2>
<p>I tried your first snippet of code without the print statements and it works just fine (using cv2 version 3.0.0, numpy 1.9.2). Two things to note however are that</p>
<ol>
<li><code>bwImage = image</code> does not copy the image, it just creates another pointer to image -> all modifications to <... | python|opencv|numpy | 2 |
13,883 | 32,211,904 | Python numpy 3D array to 2D array (removing dimensions) | <p>I have a numpy array <code>Z</code> such that:</p>
<pre><code>Z.shape
#Out[1]:
(138, 112, 123)
</code></pre>
<p>How do I transform <code>Z</code> into a new array <code>NewZ</code>, such that:</p>
<pre><code>NewZ.shape
#Out[2]:
(138, 112)
</code></pre>
<p>?</p> | <p>Removing a dimension means removing information, so you'll have to decide on a rule for projecting the original data down into a lower number of dimensions.</p>
<p>Suppose we have</p>
<pre><code>import numpy as np
Z = np.random.random((138, 112, 123))
</code></pre>
<p>Here are two examples, both yielding a <code>... | python|numpy|multidimensional-array | 2 |
13,884 | 32,261,304 | dict comprehension for nested lists to filter values of multiple variables | <p>I have a working example of dict comprehension on a list I iterate over: This generates various indicators (selections), separating the rows of my data into cases (which are not exclusive, by the way).</p>
<p>For context: This is done to count cases for specific rows (criterion defined by a column) when I aggregate... | <p>You should prefer an explicit for loop:</p>
<pre><code>for name in items.keys():
monthly_summaries[name].append(dfs[name].groupby(['LopNr','year','month']).sum()
.astype(int, copy=False)
# rather than
[monthly_summaries[name].append(dfs[name].groupby(['LopNr','year',... | python|select|dictionary|pandas|nested | 0 |
13,885 | 40,717,156 | Binarize integer in a pandas dataframe | <p>I have a pandas dataframe and want to add a new column. For all values in 'number' which are smaller than 15 I want to add 1, for all values which are greater, 0. I tried different methods, but I don't receive the desired result.Especially, because I have problems with the structure. Here is what I wanna do:</p>
<p... | <pre><code>In [6]: (df['number'] < 15).astype(int)
Out[6]:
0 1
1 0
2 1
3 0
4 0
5 1
6 0
7 1
8 0
Name: number, dtype: int32
In [7]: df['binary'] = (df['number'] < 15).astype(int)
In [8]: df
Out[8]:
number binary
0 12 1
1 89 0
2 12 1
3 56 0... | python|pandas|numpy|binary | 14 |
13,886 | 61,649,747 | Python: combining str.contains and df.groupby successfully in pandas | <p>I am quite a new programmer and I am really struggling with a project that I am working on. I have a movie data list where I'm trying to show the top 10 scores of a movie under a given movie genre. </p>
<p>Here is what I have so far:</p>
<pre class="lang-py prettyprint-override"><code>import pandas
from pandas imp... | <p>I believe you need filter DataFrame first by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with mask and then group by column <code>Genre</code>:</p>
<pre><code>mask = IMDB['Genre'].str.contains("Comedy")
r... | python|pandas|dataframe|pandas-groupby|partial | 0 |
13,887 | 61,888,816 | How to plot a bar plot of 2 categorical columns using matplotlib or seaborn | <p>This might be a simple task but I am new to plotting in python and is struggling to convert logic into code. I have 2 columns like below. 0 mean not churned and 1 means churned. gender is an object column and churned is a category column</p>
<pre><code>gender|churned
--------------
male |0
male |1
female |0
fem... | <p>You can table it:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'gender':['male','male','female','female','female','male'],
'churned':[0,1,0,1,1,1]})
pd.crosstab(df['churned'],df['gender']).plot(kind="bar",stacked=True)
</code></pre>
<p><a href="https://i.stack.imgur.com/g71C9.png" rel="nof... | python|pandas|matplotlib|plot|seaborn | 2 |
13,888 | 62,039,668 | My model keeps predicting the same face, how can i fix it? | <p>I trained a model with a CNN and used it with opencv for real-time face recognition on a webcam. I had some problems with the model, like I got 100% accuracy when it was training and I knew something must have went wrong, and another problem is that when it predicts on webcam images it only gives me one label no mat... | <p><strong>Binary classes</strong></p>
<p>So the crux of the issue comes from how we choose to represent our model. Specifically in these lines:</p>
<pre><code>classifier.add(Dense(units = 1, activation = 'sigmoid'))
</code></pre>
<p>and</p>
<pre><code>training_set = train_datagen.flow_from_directory('dataset/train... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
13,889 | 61,874,668 | Python: Writing a numpy array to txt file | <p>I have some data in an array with 5 columns and a lot of rows.</p>
<p>I want to save this in a txt file by doing:</p>
<pre><code>for i in range(rows):
with open ('datos_practica.txt','a') as f:
line=str(data[i,:])
f.write(line)
f.write('\n')
</code></pre>
<p>But instead of getting prin... | <p>Use this code instead:</p>
<pre><code>np.savetxt("array.txt", np.array(your array))
</code></pre> | python|numpy|fwrite | 3 |
13,890 | 61,926,146 | Python: Convert matrices to permutations table | <p>Given a set of ids, I need to get the values from a matrix (time A & B) for each id combination, and create a dataframe appending the values for all the permutations.</p>
<p>I have been able to do it by creating the permutations dataframe and then iterating through it while looking & filling the values. How... | <p>Here you go:</p>
<pre><code># drop set_index('id') if `id` is already index
(pd.concat([timeA.set_index('id').stack().to_frame(name='A'),
timeB.set_index('id').stack().to_frame(name='B')], axis=1)
.rename_axis(index=['id_start','id_end'])
.query('id_start != id_end')
.reset_index()
)
</code></pr... | python|pandas|numpy|dataframe|matrix | 0 |
13,891 | 61,836,317 | Convert pandas dataframe column labels from float to integer | <p>I have the following snippet of the pandas <strong>dataframe</strong> 'GDP', where the column labels are floats. </p>
<pre><code>3 2013.0 2014.0 2015.0
4 NaN NaN NaN
5 3.127550e+09 NaN NaN
6 1.973134e+10 1.999032e+10 2.029415e+10
7 ... | <p>Convert only numeric columns, here it means all columns after first 4. column and join together:</p>
<pre><code>GDP.columns = GDP.columns[:4].tolist() + GDP.columns[4:].astype(int).astype(str).tolist()
</code></pre>
<p>And then:</p>
<pre><code>years = np.arange(2006, 2016).astype(str)
GDP = GDP[np.append(['Countr... | python|string|pandas|dataframe|int | 2 |
13,892 | 61,784,860 | Why can I not reproduce a nd array manually? | <p>I'm confused about these data structures. </p>
<p>From a GIS system, I use a function to extract the meta data (8 different fields)</p>
<pre><code>myList = FeatureClassToNumPyArray(...)
myList = [('a', 'b', 'c'...) ('aa', 'bb', 'cc'...) ..] # 8 fields
print (type(myList ))
print (myList.shape)
print (myList.siz... | <p>Not sure how to do this, but the comment by juanpa.arrivillaga should be marked as the answer. </p>
<p><em>Again, why do you expect print(something) to produce a string that is valid python source code to produce that object? That is your fundamental assumption that is wrong. That is what you are missing. print(rep... | python|numpy-ndarray | 0 |
13,893 | 58,169,413 | Pandas File Not Found Error -- Worked Yesterday | <p>Yesterday I imported an sas file into Pandas, and was able to successfully poke around the data. This morning, I received a file not found error, although I did not move any files. </p>
<p>I triple-checked the path and it was correct. Then I tried placing a copy of the file on my desktop and redirecting read comman... | <p>Unless that you have a folder named <code>Dropbox</code> inside your project directory, I suggest you use the full path of your file:</p>
<p><code>/home/<username>/Dropbox/Thesis Fall 2017/Data Analysis/epcg17.xpt</code></p>
<p><strong>OR</strong></p>
<p><code>~/Dropbox/Thesis Fall 2017/Data Analysis/epcg17... | python|pandas | 1 |
13,894 | 57,776,828 | using rsplit on pandas dataframe column to separate based on second instance of a delimiter | <p>I have a column of a pandas dataframe that I would like to split and expand into a new dataframe based on the second instance of a delimiter. I was splitting based on the last instance of the delimiter, but unfortunately there are a handful of instances in ~80k rows that have 4 '_' instead of 3.</p>
<p>For example,... | <p>Since your data seems to be fairly well defined, you can extract on the second instance of the delimiter using a regular expression.</p>
<pre><code>df['gene'].str.extract(r'(?:[^_]+_){2}(.*)')
</code></pre>
<p></p>
<pre><code> 0
0 foo_blabla
1 bar
</code></pre>
<p>You can generalize this to b... | python|python-3.x|pandas|dataframe | 3 |
13,895 | 34,359,598 | Load .csv with unknown delimiter into Pandas DataFrame | <p>I have many .csv files that are to be loaded into pandas data-frames, there are at a minimum two delimiters comma and semi colon, and I am unsure of the rest of the delimiters. I understand that the delimeter can be set using</p>
<pre><code>dataRaw = pd.read_csv(name,sep=",")
</code></pre>
<p>and</p>
<pre><code>d... | <p>There is actually an answer in pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer">documentation</a> (at least, for pandas 0.20.1)</p>
<blockquote>
<p><strong>sep</strong> : str, default ‘,’</p>
<p>Delimiter to use. If sep is None, the C engine cannot automati... | python|csv|pandas|delimiter | 8 |
13,896 | 34,207,694 | replace each column of pandas dataframe with each value of array | <p>df is like this,</p>
<pre><code> A B C
0 NaN 150 -150
1 100 NaN 150
2 -100 -150 NaN
3 -100 -150 NaN
4 NaN 150 150
5 100 NaN -150
</code></pre>
<p>Another array is array([1, 2, 3])</p>
<p>I want to replace non-null value in each column with each value in array, and the result will be,</p>
<p... | <p>How about:</p>
<pre><code>>>> (df * 0 + 1) * arr
A B C
0 NaN 2 3
1 1 NaN 3
2 1 2 NaN
3 1 2 NaN
4 NaN 2 3
5 1 NaN 3
</code></pre> | python|pandas | 1 |
13,897 | 34,070,646 | Create Columns on DataFrame with parsed list values | <p>I have a dataframe like:</p>
<pre><code>OMDB_AWARDS OMDB_GENRE
1 Oscar |Drama|
2 Emmy |Sci-Fi|Comedy|
1 Emmy |Comedy|
</code></pre>
<p>How can I create dynamically the new columns as shown below?</p>
<pre><code>OMDB_AWARDS OMDB_GENRE OMDB_GENRE_DRAMA OMDB_GENRE_Comedy OMDB_GENRE_Sci-Fi ... | <p>A very simple way would be:</p>
<pre><code>df['OMDB_GENRE_DRAMA'] = df.OMDB_GENRE.apply(lambda x: 1 if 'Drama' in x else 0)
</code></pre>
<p>and repeat for all genres. If you have many genres, you could take list of the genre names and do something like:</p>
<pre><code>genres = ['Drama', 'Comedy', ..]
for genre i... | python|python-2.7|pandas|dataframe | 1 |
13,898 | 34,159,060 | Permission denied when trying to install pandas with pip | <p>I am trying to install the Python pandas package from the Windows command line with pip:</p>
<pre><code>pip install pandas
</code></pre>
<p>but I get the following errror. I also downloaded the wheel version from here <a href="https://pypi.python.org/pypi/pandas/0.17.0/#downloads" rel="nofollow">https://pypi.pytho... | <p>I faced a similar problem trying to install pandas on azure.</p>
<p>The following worked:</p>
<pre><code>python -m pip install --user pandas
</code></pre> | python|windows|pandas|permissions|pip | 4 |
13,899 | 36,924,170 | Plot pandas dataframe with varying number of columns along imshow | <p>I want to plot an image and a pandas bar plot side by side in an iPython notebook. This is part of a function so that the dataframe containing the values for the bar chart can vary with respect to number of columns. </p>
<p>The libraries</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplo... | <p>You just need to specify your axes object in your <code>DataFrame.plot</code> calls.</p>
<p>In other words: <code>faces.plot(kind='bar', ax=ax_r)</code></p> | python|pandas|matplotlib | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.