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 |
|---|---|---|---|---|---|---|
365,200 | 50,181,448 | filling dataframe column with values from another dataframe meeting certain criteria | <p>i have two dataframes:</p>
<p>prices </p>
<pre><code>date price currency rate
13-04-2018 34 EUR
14-04-2018 23 USD
15-04-2018 64 PLN
</code></pre>
<p>exchange_rates </p>
<pre><code>date currency rate
13-04-2018 EUR 4
13-04-2018 USD 3
13-04... | <pre><code>import pandas as pd
prices = <ur prices dataset>
exchange_rates = <ur exchange rates dataset>
output = pd.merge(prices, exchange_rates, on=["date", "currency"], how="inner")
print(output)
</code></pre> | python|pandas|dataframe | 0 |
365,201 | 49,942,180 | Python: ValueError: could not convert string to float: 'Service Industries Journal' | <p>I just started to code with Python.</p>
<p>I am doing some analysis on a database of papers extracted from the Scopus database. I downloaded the database in .csv and then performed some analyses and filtering on it. After the initial analyses I saved the file in .xlsx which is the current format of the database.<br... | <p>I think you should enumerate the <code>String</code> values in <code>journals_count['Journal']</code> into <code>[1, 2, 3, ...]</code>. After that map those values to your <code>journals_count['Journal']</code> with <code>xticks</code>.</p>
<pre><code>x = np.arange(len(journals_count['Journal']))
plt.xticks(x, jour... | python|pandas|matplotlib | 0 |
365,202 | 50,191,506 | Numpy Where () with All() on a 2D matrix | <pre><code>A= np.random.randint(5, size=(25, 4, 4))
U= np.unique(A, axis =0 )
results = np.where((A==U[0]).all(axis=-1))
</code></pre>
<p>Using this Where function matches individual rows, I would like to match the entire 4x4 array not just individual rows.</p>
<p>here are example results:
(array([ 1, 97, 97, 97, 97]... | <pre><code>np.where((A.reshape(A.shape[0],-1) == U[0].reshape(-1)).all(axis=1))
</code></pre>
<p>Let's see an example</p>
<pre><code>>>> A = np.random.randint(5, size=(25, 4, 4))
>>> A[:3,...]
array([[[0, 2, 0, 1],
[1, 0, 3, 0],
[4, 1, 1, 2],
[0, 1, 0, 0]],
[[1, 3, 2,... | numpy|where | 0 |
365,203 | 50,003,978 | repeat a pandas method after every N rows | <p>Here is list of tasks imported imported from kaggle homepage in pandas dataframe.</p>
<pre><code>import pandas as pd
df=pd.read_csv('https://s3.amazonaws.com/todel162/kaggle_unicode1.txt', encoding='utf8', sep='`', header=None)
sample=df.head(5).T
sample.columns=['task_name', 'task_description', 'task_date', 'task_... | <p>Simpliest is use <code>MultiIndex</code>, but unfortunately data are not repeat for each 5 rows:</p>
<pre><code>df.index = [df.index // 5, df.index % 5]
sample = df.unstack()
sample.columns=['task_name', 'task_description', 'task_date', 'task_prize', 'task_teams']
</code></pre>
<hr>
<pre><code>print (sample.head(... | python|pandas | 2 |
365,204 | 50,217,417 | What is wrong with my CNN? | <p>I really don't understand what is wrong with my model. Sometimes it gives me excellent results, but in other cases results are just absurd. During training, from one moment to another it gives absurd results. I tried model with 3 dropout layers and without them, and get same strange results. Here's my model definiti... | <p><strong>Decrease Kernel and Pool Sizes</strong></p>
<p>From just glancing over your architecture I would say that it's worth trying much smaller values for the pooling and conv filters. The network would have to find a pattern while looking at 100 values at the same time. To put this in perspective, when convolutio... | tensorflow|deep-learning|keras|convolutional-neural-network | 2 |
365,205 | 49,889,153 | How to retrieve intermediary state in TensorFlow RNN | <p>I am running an RNN on a signal in fixed-size segments. The following code allows me to preserve the final state of the previous batch to initialize the initial state of the next batch. </p>
<pre><code>rnn_outputs, final_state = tf.contrib.rnn.static_rnn(cell, rnn_inputs, initial_state=init_state)
</code></pre>
<p... | <p>In tensorflow the only thing that is kept after returning from a call to <code>sess.run</code> are variables. You should create a variable for the state, then use <code>tf.assign</code> to assign the result from your RNN cell to that variable. You can then use that Variable in the same way as any other tensor.</p>
... | tensorflow|rnn | 1 |
365,206 | 50,183,540 | numpy array to Colored table or image? | <p>I have the following numpy array :</p>
<pre><code> ([[ 0, 0, 0, 0, 0, 0, 27, 541, 1296, 10000],
[ 0, 0, 0, 0, 1, 44, 355, 1998, 3272, 10000],
[ 0, 0, 0, 2, 18, 209, 1069, 3239, 4670, 10000],
[ 0, 0, 0, 10, 96, ... | <p>Would this be a satisfactory result?</p>
<pre><code>import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="white")
cmap = sns.color_palette("Greys", 8)
f, ax = plt.subplots(figsize=(10, 10))
ax = sns.heatmap(x, cmap=cmap, vmax=10000, vmin=0,
square=True, linewidths=.5, cbar_kws={"shri... | python|numpy|matplotlib | 4 |
365,207 | 50,167,809 | Pandas vs JSON library to read a JSON file in Python | <p>It seems that I can use both pandas and/or json to read a json file, i.e.</p>
<pre><code>import pandas as pd
pd_example = pd.read_json('some_json_file.json')
</code></pre>
<p>or, equivalently,</p>
<pre><code>import json
json_example = json.load(open('some_json_file.json'))
</code></pre>
<p>So my question is, wha... | <h2>It Depends.</h2>
<p>When you have a single JSON structure inside a json file, use <code>read_json</code> because it loads the JSON directly into a DataFrame. With <code>json.loads</code>, you've to load it into a python dictionary/list, and <em>then</em> into a DataFrame - an unnecessary two step process.</p>
<p>Of... | python|json|pandas | 9 |
365,208 | 50,066,217 | Can't submit training job gcloud ml | <p>I get this error when I try to submit my training job. </p>
<pre><code>ERROR: (gcloud.ml-engine.jobs.submit.training) Could not copy [dist/object_detection-0.1.tar.gz] to [packages/10a409168355064d603079b7c34cdd7010a13b181a8f7776751e9110d66a5bdf/object_detection-0.1.tar.gz]. Please retry: HTTPError 404: Not Found
<... | <p>Terrible fix but something which worked for me - just remove $variable format completely.</p>
<p>Here is an example:</p>
<pre><code>!gcloud ai-platform jobs submit training anurag_card_fraud \
--scale-tier basic \
--job-dir gs://anurag/credit_card_fraud/models/JOB_20210401_194058 \
--master-image-uri gcr... | tensorflow|gcloud|google-cloud-ml | 0 |
365,209 | 49,795,825 | Skip nan and shift elements in a pandas dataframe row | <p>I have a dataframe like this [![Dataframe looks like this][1]: <a href="https://i.stack.imgur.com/R7GmM.png" rel="nofollow noreferrer">https://i.stack.imgur.com/R7GmM.png</a>
Now I want to skip nan's and so that data shift towards left i.e. [![formatted dataframe should be like this] [1]: <a href="https://i.stack.im... | <p>Here is one method:</p>
<p>Starting from your dataframe named <code>df</code>:</p>
<pre><code> A B C D
0 a NaN c NaN
1 b NaN b a
2 c NaN NaN d
3 d a b c
</code></pre>
<p>apply these line:</p>
<pre><code>shifted_df = df.apply(lambda x: pd.Series(x.dropna().values), axis=1)... | python|pandas|dataframe | 3 |
365,210 | 49,891,116 | Python: How do I parallelize a job that compares two lists? | <p>I have two lists and need to compare and calculate element by element. As these lists get larger, performance is suffering. Someone recommended breaking one of the lists into N sections and running the comparison in parallel. How do I run these in parallel?</p>
<pre><code>key={}
#compare each list, element by elem... | <p>Assuming you actually do need to compare the cartesian product (every element in <code>list1</code> against every element in <code>list2</code>, as opposed to just comparing each element in <code>list1</code> with the corresponding element in <code>list2</code>), the easiest way is to just replace your outer loop wi... | python|pandas|parallel-processing | 0 |
365,211 | 49,880,700 | Tensorflow OMP: Error #15 when training | <p>I am training my neural network using tensorflow on CentOS HPC. However I got this error at start of the training process:</p>
<p><i> OMP: Error #15: Initializing libiomp5.so, but found libiomp5.so already initialized.
OMP: Hint: This means that multiple copies of the OpenMP runtime have been linked into the progr... | <p>I had a similar issue on macOS with the same error message (<a href="https://stackoverflow.com/questions/53014306/error-15-initializing-libiomp5-dylib-but-found-libiomp5-dylib-already-initial/58869103#58869103">see this question</a>) and found the following reasons:</p>
<p><strong>Problem:</strong></p>
<p>I had a ... | python|tensorflow|parallel-processing|openmp | 7 |
365,212 | 49,977,766 | What data treatment/transformation should be applied if there are a lot of outliers (identified via boxplot)? | <p>I referred to this <a href="https://machinelearningmastery.com/quick-and-dirty-data-analysis-with-pandas/" rel="nofollow noreferrer">post</a> and used <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.boxplot.html" rel="nofollow noreferrer">pandas boxplot</a> to plot my numerical predi... | <blockquote>
<p>You may cap all the outliers which are being 3-SD (Standard
Deviations) away to a certain value and continue with analysis.</p>
</blockquote>
<pre><code>df[ df > value_greater_than_SDaway ] = value_to_be_replaced_with
</code></pre> | python|pandas|machine-learning|data-cleaning|outliers | 0 |
365,213 | 49,931,623 | Keras MobileNet example yields different answers on different computers | <p>I have a very simple example with the Keras MobileNet implementation trying to classify a minivan. I run the same code on two different computers and get different results, not just slightly different but different enough that the classifications are not the same. </p>
<p>(note that Tensorflow=1.7.0 and Keras=2.1.5... | <p>So I don't quite understand what is going on here, but the error appears to have gone away once I did some more preprocessing of the input, which makes me think that maybe I had different PIL versions of numpy versions or something.</p>
<p>I added these lines</p>
<pre><code>img = img.convert("RGB")
</code></pre>
... | python|tensorflow|keras|precision | 0 |
365,214 | 50,082,528 | Unmatched ''"' when when decoding 'string' error in reading json file into pandas dataframe | <p>I am trying to load a amazon review data into pandas dataframe, which is a JSON file , using the pd.read_json(), I am getting the following error <code>Unmatched ''"' when when decoding 'string'.</code> I am using jupyter notebook</p>
<p>Data format:</p>
<pre><code>{"reviewerID": "AGL65XWV7MH3C", "asin": "B003FMUV... | <p>I just had the same error and after trying every possible solution the simple fix was to remove the empty line at the end of the file.</p>
<p>Leaving an empty line at the end of a file is a common convention but seems to choke pandas for some reason,</p> | python|pandas|jupyter-notebook | 2 |
365,215 | 50,018,149 | Numpy: Uniform way of retrieving `dtype` | <p>If I have a numpy array <code>x</code>, I can get its data type by using <code>dtype</code> like this:</p>
<pre><code>t = x.dtype
</code></pre>
<p>However, that obviously won't work for things like lists. I wonder if there is a standard way of retrieving types for lists and numpy arrays. In the case of lists, I gu... | <p>If you really want to do it that way you will probably have to use <code>np.asarray</code>, but I'm not sure that's the most solid way of dealing with the problem. If the user forgets to add <code>.</code> and gives <code>[1, 0, 0]</code> then you will be creating integer outputs, which most definitely does not make... | python|numpy | 2 |
365,216 | 49,800,045 | Python: Fast way of MinMax scaling an array | <p>I use the following way to scale an n-dimensional array between 0 and 1:</p>
<p><code>x_scaled = (x-np.amin(x))/(np.amax(x)-np.amin(x))</code></p>
<p>But it's very slow for large datasets. I have thousands of relatively large arrays which I need to process. Is there a faster method to this in python?</p>
<p>Edit:... | <p>It's risky to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ptp.html" rel="nofollow noreferrer"><code>ptp</code></a>, i.e. max - min, as it can in theory be 0, leading to an exception. It's safer to use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.... | python|numpy|machine-learning|scikit-learn|data-analysis | 4 |
365,217 | 64,064,590 | Two tables can be merged when if two key columns has different values? | <p>I have two data pandas frames.</p>
<p>Dataframe1</p>
<pre><code>-----------------------
id | name | updatedat
-----------------------
1 | p1 | 2015-05-05
2 | p2 | 2015-04-29
3 | p3 | 2015-05-07
</code></pre>
<p>Dataframe2</p>
<pre><code>------------------------
id | name | updatedat
-----------------... | <p>Try with</p>
<pre><code>out = df1.merge(df2, on = 'id').query('name_x!=name_y')
</code></pre> | pandas | 1 |
365,218 | 63,995,077 | How to compare open and close price variables in this dataframe? | <p>I have a dataframe which has open, high, low, close and date of each minute for over 5 years. I want to calculate a new column and want to compare (close - open) close price (of that minute) with the open price of that day (9:15am). How do I do that?</p>
<p>Below is the screenshot of the file. In <code>J</code> col... | <p>Just use <code>groupby</code> and <code>transform</code>. Note that this assumes that your data is sorted (e.g., the first value of each group is the open price).</p>
<pre><code>import pandas as pd
import datetime
# sample date
df1 = pd.DataFrame({'ticker': ['A']*5,
'date': pd.date_range('2020-0... | pandas | 1 |
365,219 | 64,084,262 | How to make a custom metric available to TFMA/Beam? | <p>I have created a custom Keras metric, similar to the demo implementation below:</p>
<pre><code>import tensorflow as tf
class MyMetric(tf.keras.metrics.Mean):
def __init__(self, name='my_metric', dtype=None):
super(MyMetric, self).__init__(name=name, dtype=dtype)
def update_state(self, y_true, y_pr... | <p>You need to specify the module so that TFX knows where to find your MyMetric class. One way of doing this is to specify it as part of the metric specs:</p>
<p><code>from tensorflow_model_analysis import config</code></p>
<p><code>metric_config = [config.MetricConfig(class_name='MyMetric', module='mymodule.mymetric')... | tensorflow|apache-beam|metrics|tfx|tensorflow-model-analysis | 2 |
365,220 | 63,802,260 | pandas not sorting as expected | <p>I have a pandas dataframe I am trying to sort, which contains a int column (encoded target) which I sort like so:</p>
<pre><code>some_set.encoded_target = train_set.encoded_target.astype(int) # last but one column
some_set.sort_values(by='encoded_target', ascending=True)
print(some_set)
</code></pre>
<p>and this giv... | <p>One thing need to remember is to assign it back</p>
<pre><code>some_set = some_set.sort_values(by='encoded_target', ascending=True)
</code></pre> | python|pandas | 2 |
365,221 | 63,901,347 | pandas read feather ArrowInvalid | <p>When I'm trying to read a feather file I got this Error:</p>
<blockquote>
<p>ArrowInvalid: Column 0: In chunk 0: Invalid: Buffer #1 too small in array of type int64 and length 14712: expected at least 117696 byte(s), got 3450</p>
</blockquote> | <p>This file was created with another pyarrow version. I had version <code>0.17.0</code> and file was created by version <code>1.0.0</code>. So updating my pyarrow to new version solved the problem.</p> | python|pandas|feather | 4 |
365,222 | 64,058,390 | How can I round up an entire column to the next 10? | <p>I'm really struggling to organise my data into 'bins' in Jupyter Notebook. I need the Length column to be rounded UP to the next 10 but I can only seem to round it up to the nearest whole number. I would really appreciate some guidance. Thanks in advance. :)</p>
<pre><code>IN[58] df2['Length']
OUT[58] 0 541.56
... | <p><strong>Sample</strong></p>
<pre><code>print (df2)
Length
0 541.56
1 541.73
2 482.22
3 500.00 <- whole number for better sample
</code></pre>
<p>You can use integer division, mutiple by <code>10</code> and convert to integers and add 10 if modulo is not <code>0</code>:</p>
<pre><code>s = (df2['Length'] //... | pandas|csv | 1 |
365,223 | 64,012,560 | Merge columns from several dataframes with specific values with Pandas | <p>I have 7 dataframes with only "OK" and "KO" values, and the only column that connects everything is the ID.</p>
<pre><code>df1:
ID, Name, Address, Email
1, OK, OK, OK
2, OK, KO, OK
3, OK, OK, KO
df2:
ID Job, Credit_Card, Driving_License_Number
1, OK, OK, OK
2, KO, KO, OK
3, OK, OK, OK
</code></p... | <p>Let's merged them first on <code>ID</code>, then do a matrix multiplication:</p>
<pre><code>merged = df1.merge(df2, on='ID').set_index('ID')
(merged.eq('KO') @ (merged.columns + (', '))).str[:-2]
</code></pre>
<p>Output:</p>
<pre><code>ID
1
2 Address, Job, Credit_Card
3 ... | python|pandas|pandasql | 1 |
365,224 | 63,979,985 | Transfrom file.txt content into a df in pandas | <p>I woul need help in order to transform a file content into a pandas dataframe.</p>
<p>here is the file :</p>
<pre><code>>OK0100087.1
0 375
376 750
751 1000
>OK0100088.1
0 87766
>OK0100089.1
0 66778
>OK0100090.1
0 47519
47520 73733
</code></pre>
<p>and the idea is that I would like to change this file con... | <p>You can prepare your data so it's easy to load to the dataframe.</p>
<pre><code>import pandas as pd
records = []
with open('f.txt', 'r') as f:
idx = None
for line in f.readlines():
if line.startswith('>OK'):
idx = line.strip()[1:]
else:
start, end = line.strip().s... | python|pandas | 1 |
365,225 | 63,783,525 | Assign values to df using another df in a different format | <p>I have two dataframes:</p>
<pre><code>d = {'year': [1990, 1991], 'org': ['EU', 'EU'], 'UK': [1, 1], 'Croatia': [-9, 1], 'Germany': [1,1]}
df1 = pd.DataFrame(data=d)
df1
year org UK Croatia Germany
0 1990 EU 1 -9 1
1 1991 EU 1 1 1
d = {'year': [1990, 1991], 'country1': ['Isr... | <p>Let us try <code>dot</code> then <code>merge</code></p>
<pre><code>s = df1.loc[:,'UK':]
s.eq(1).dot(s.columns+',').str[:-1]
df1['New'] = s.eq(1).dot(s.columns+',').str[:-1]
df2 = df2.merge(df1[['year','New']])
newdf2 = df2.mask(df2=='EU',df2.New,axis=0).drop('New',1)
newdf2
Out[249]:
year country1 ... | python|pandas | 1 |
365,226 | 63,965,418 | get rows by date regardless of format of date in pandas | <p>I have data as follows:</p>
<pre><code>Col1,ColDate
a,2020-09-11 08:43:00
b,2020-09-12 09:43:00
c,13-09-2020 09:43:00
d,09/16/2020 10:43:00
e,09/19/2020 12:43:00
f,09/12/2020 15:43:00
</code></pre>
<p>Intention is to get all rows between 11th sep and 13th sept, regardless of the format. In pandas</p>
<p>I am trying ... | <p>You can try this,</p>
<pre><code> df[pd.to_datetime(df['ColDate']).dt.strftime('%d-%m-%Y').between('11-09-2020','13-09-2020')]
Col1 ColDate
0 a 2020-09-11 08:43:00
1 b 2020-09-12 09:43:00
2 c 13-09-2020 09:43:00
5 f 09/12/2020 15:43:00
</code></pre>
<p>but its really hard to say whic... | python-3.x|pandas | 3 |
365,227 | 63,777,516 | Finding Duplicates In a column Except 0 in Pandas | <p>I have a Dataframe with Position varying starting from 0.
So I have to check whether the Position is having duplicate values except 0.As 0 can be present multiple times in my case.</p>
<pre><code>if df['Position'].duplicated().any():
print("Duplicate Positions found..Positions should be unique..Exiting")
... | <p>You can chain mask by test for not <code>0</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ne.html" rel="nofollow noreferrer"><code>Series.ne</code></a>:</p>
<pre><code>df = pd.DataFrame({'Position':[0,1,2,0]})
if (df['Position'].duplicated() & df['Position'... | python|pandas | 1 |
365,228 | 63,905,895 | Pandas - Expand table based on different email with same key from another table | <p>I have a quick one that I am struggling with.</p>
<p>Table 1 has a lot of user information in addition to an email column and a unique ID column.
Table 2 has only a unique ID column and an email column. These emails can be different from table 1, but do not have to be.</p>
<p>I am attempting to merge them such that ... | <p>IIUC, you can try <code>pd.concat</code> with a boolean mask using <code>isn</code> for <code>df2</code> , with <code>groupby.ffill</code>:</p>
<pre><code>out = pd.concat((df1,df2[df2['id'].isin(df1['id'])]),sort=False)
out.update(out.groupby("id").ffill())
out = out.sort_values("id")#.reset_inde... | python|pandas|join|merge | 3 |
365,229 | 64,061,308 | How to count specific values of a pandas dataframe column attribute | <p>In my pandas dataframe I have a column named "crashhour" which have two values that is offtime and picktime. How to take only the values of offtime.
Below is the code of Column value count.</p>
<pre><code>a=df.crashhour.value_counts()
</code></pre>
<p>And this is the output-</p>
<pre><code>offtime 1963... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.loc.html" rel="nofollow noreferrer"><code>Series.loc</code></a>:</p>
<pre><code>var = a.loc['offtime']
</code></pre> | python|pandas|csv|count | 1 |
365,230 | 64,122,792 | Building libtensorflowlite.so without any error, but share file is close to empty (KB) | <p>When building a libtensorflowlite.so followed by the official <a href="https://www.tensorflow.org/lite/guide/build_arm64" rel="nofollow noreferrer">tutorial</a>
, but the built share file is empty even bazel build without error shown.</p> | <p>After some tests, I found the problem is bazel version is not correct.
Even following the official web recommend installing the bazel and tensorflow, shown as following</p>
<p><a href="https://i.stack.imgur.com/sr71x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sr71x.png" alt="enter image descr... | tensorflow|tensorflow-lite | 0 |
365,231 | 63,922,236 | Max value on 2D array and make the rest zero based on a condition | <p>I use this to select the max value in place of a row in a 2D numpy and make the rest of the values zero</p>
<pre><code>max_row_value_2D = a * (a >= np.sort(a, axis=1)[:, [-1]]).astype(int)
</code></pre>
<p>I use this to select the max value in place of a column in a 2D numpy and make the rest of the values zero</... | <p>Seems that this works.</p>
<pre><code>if (~dist_on_skel_row.any(axis=0)).any():
for empty_index in (np.where(~dist_on_skel_row.any(axis=0))[0]):
dist_on_skel_row[:, empty_index] = dist_on_skel_column[:, empty_index]
</code></pre> | python|arrays|numpy | 0 |
365,232 | 63,909,035 | Pandas conversion to Int64 with missing values | <p>Note that I’m using panda 1.1.2 and numpy 1.19.2</p>
<h2>non-working scenario</h2>
<p>I have a <code>provider_frame['NEQ']</code> series containing <code>pd.NA</code> datas among numerical values. The type of the series is <code>object</code>.</p>
<p>When reading <a href="https://pandas.pydata.org/docs/reference/api... | <p>Here is a way to convert string versions of numbers to Int64:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'x': ['10', '20', None, '40']}) # list of strings + None
df['x'] = pd.to_numeric(df['x'], downcast='float', errors='raise').astype('Int64')
print(df)
x
0 10
1 20
2 <NA>
3 40
</... | pandas|type-conversion|missing-data | 0 |
365,233 | 63,959,182 | Python Split a list into sublists of given lengths | <p>I am currently trying to extract data from a single column pandas dataframe into 8 lists containing 12 float values each in order to make a heatmap (96 datapoints in a 12 x 8 matrix).</p>
<p>I have my elements in list in a list ( extracted from a csv file, provided here to show it looks):</p>
<pre><code>my_list = da... | <p>This is a simple solution to plot the heatmap with your data. No need to split the array in a loop.</p>
<pre><code>df = data['Abs 590 nm'].values.reshape(8,12)
ax = sns.heatmap(df)
</code></pre>
<p><a href="https://i.stack.imgur.com/A3b3o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A3b3o.png" ... | pandas|nested-lists | 2 |
365,234 | 63,855,162 | How to groupby part of a column name, and aggregate mean? | <p>I can take an average of two columns, and return it as a new column, but I can't figure out how to do it for all the columns in the specific convention that raw data has. The goal is to average A1 & D1, ..., A12 & D12 etc..</p>
<p>I tried different iterations of what's below but it doesn't work if I don't sp... | <ul>
<li>As noted in the comments, <code>column.startswith('A') and column.startswith('D')</code> will never be true.</li>
<li>A solution in the comments was close, but the slicing was not in the correct location, and it was the mean of all the columns, not just <code>A</code> and <code>D</code>.</li>
<li><code>[1:]</c... | python|pandas|mean|calculated-columns | 2 |
365,235 | 64,003,033 | Increase the radius of polygon geometries in geopandas | <p>I have a bunch of polygons in the shape of a pie in a geopandas df under geometry as seen below and I am looking at increasing the radius from x to y of the polygons.</p>
<p><a href="https://i.stack.imgur.com/IahUN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IahUN.png" alt="enter image descrip... | <p>Have a look at the <code>shapely.affinity.scale</code> method.
With this you can scale your geometry in x and y direction according to your desire!
<a href="https://shapely.readthedocs.io/en/latest/manual.html#shapely.affinity.scale" rel="nofollow noreferrer">Shapely affinity scale</a></p> | python|geopandas|shapely | 0 |
365,236 | 63,967,330 | Replacing selected values from a dataframe column with the difference between previous row values | <p>I am trying to replace few zeros in one of the columns of pandas dataframe with the difference between values in the previous two columns in the same row.</p>
<pre><code> A B C
0 10 12 -2
1 6 3 0
2 5 18 0
3 3 11 -8
</code></pre>
<p>I want to replace the zeros in colum... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>mask = df['C'].eq(0)
df.loc[mask, 'C'] = df.loc[mask, 'A'] - df.loc[mask, 'B']
</code></pre> | python|python-3.x|pandas|dataframe | 1 |
365,237 | 63,795,150 | python pandas multi index how to move rows down? | <p>Hey I am trying to make a dataframe ready for exportation into latex and I can't figure out how to change the order of my dataframe manually, i can sort it etc, but i can't get it to show the specific order i require:</p>
<pre><code> Hyper-parameter H-parameter values ... | <p>Nevermind, After more than an hour of searching i made this post, and 10 minutes later i found the answer. using the example at the bottom of my question:</p>
<pre><code>df.reindex([2,1,3], level=0)
df
a
number color
2 red 3
blue 4
1 red 1
blue 2
3 red 5
... | python|pandas|multi-index | 3 |
365,238 | 63,973,998 | How to combine certain column values together in Python and make values in the other column be the means of the values combined? | <p>I have a Panda dataframe where one of the columns is a sequence of numbers('sequence')many of them repeating and the other column values('binary variable') are either 1 or 0.</p>
<p>I have grouped by the values in the sequences column which are the same and made the column values in the binary variable be the % of ... | <p>It seems like you want to group the table twice and take the mean each time. For the second grouping, you need to create a new column to indicate the group.</p>
<p>Try this code:</p>
<pre><code>import pandas as pd
# sequence groups for final average
grps = {(1,4):[1,4],
(5,6):[5,6]}
# initial data
df = pd.... | pandas|dataframe|pandas-groupby | 0 |
365,239 | 63,860,741 | Tensorflow shared library error; ImportError: libcuda.so.1: cannot open shared object file: No such file or directory | <p>I think there is a problem with my cudatoolkit version ie. 10.0.130. I don't understand this error message. I want to use Gradcam (heatmap generator) on the x-ray image. It is the same code from AI for Medicine by deeplearning.ai, I want to run it on my machine and I am trying to create a REST API for this model.</p... | <p>The problem was python 3.7 in my virtual env. I downgraded to python 3.6.5 and everything seems alright.</p> | keras|python-3.7|tensorflow2.0 | 0 |
365,240 | 64,037,815 | Filtering rows containing two specific words | <p>I am trying to filter all rows containing two words: <code>mom</code> and <code>dad</code>.</p>
<pre><code>Family
My mom is a teacher.
My dad is a policeman.
Both my mom and dad are retired.
</code></pre>
<p>My expected output would be</p>
<pre><code>Both my mom and dad are retired
</code></pre>
<p>as it contains ... | <p>Try <code>str.contains</code> with regex <code>(?=.*mom)(?=.*dad)</code>, which will match a string that contains both <code>mom</code> and <code>dad</code> (this is done by using two look ahead assertions <code>?=</code>, i.e. assert the string matches both <code>.*mom</code> and <code>.*dad</code>):</p>
<pre><code... | python|pandas | 2 |
365,241 | 63,871,980 | How can I make clusters of time frame? | <p>I have a Pandas Dataframe of Time.</p>
<pre><code>0 2020-08-01 23:59:59
1 2020-08-01 23:59:49
2 2020-08-01 20:52:17
3 2020-08-01 19:02:34
4 2020-08-01 18:38:06
</code></pre>
<p>I want to add a column where I want to index by making a cluster. For eg. as follows:</p>
<pre><code>0 2020-08-01 23:59:59... | <p><code>kmeans</code> assumes that you know the number of clusters.</p>
<p>If you want a method that determines the number of clusters algorithmically, you can e.g. use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html" rel="nofollow noreferrer">DBSCAN</a> which forms a cluster whe... | python|pandas|scikit-learn | 0 |
365,242 | 64,010,428 | Getting "return self._engine.get_loc(casted_key)" error while working with pandas library | <p>I wanted to try this snippit of code I found on the Internet,</p>
<pre><code>from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import clear_output
from six.moves impor... | <blockquote>
<p>This may not be the root cause of your error, but I came across this
post when getting the same error.</p>
</blockquote>
<ul>
<li>For me the root cause was purely a tired error on my part where I had
referred to a <code>requests.get</code> call that was not assigned correctly.</li>
<li>The program did n... | python|pandas|tensorflow | 0 |
365,243 | 63,797,622 | Saving a file name as a input variable | <p>very new to python so sorry for the silly question</p>
<p>I've created a user input interface</p>
<pre><code>fn=input()
#Where the user will input version32 for instance so effectively
fn=Version32
</code></pre>
<p>I've then imported a template word document using docx, which has been heavily modified based upon us... | <p>IIUC, you can do this using f-string:</p>
<pre><code>output.save(rf"C:\Users\XXX\XXX\XXX\{fn}.docx")
</code></pre> | python|python-3.x|pandas|jupyter-notebook | 2 |
365,244 | 63,936,631 | Pandas combining one column's values with same index into list | <p>I have a Pandas DF as below, and I'm struggling with printing it in a good looking format...
Could someone please show me how to combine those two values from same column values?</p>
<pre><code>data = {'Animal':['DOG','CAT','CAT','BIRD'],
'Color':['WHITE','BLACK','ORANGE','YELLOW']}
df = pd.DataFrame(data)
d... | <p>use <code>groupby</code> and <code>to_string</code></p>
<pre><code>print(df.groupby('Animal')['Color'].agg(', '.join).to_string())
Animal
BIRD YELLOW
CAT BLACK, ORANGE
DOG WHITE
</code></pre> | python|pandas|dataframe | 0 |
365,245 | 63,948,265 | Generate random vectors with a given (numerical) distribution matrix | <p>I'm trying to come up with a fast and smart way of generating random vectors from a distribution matrix, much like what is being discussed here:
<a href="https://stackoverflow.com/questions/4265988/generate-random-numbers-with-a-given-numerical-distribution">Generate random numbers with a given (numerical) distribut... | <p>You could use inverse transform sampling. Compute a cumulative distribution on your p matrix, sample a single random vector of size the height of the matrix, then return the largest index along each row of the cumulative matrix. In code:</p>
<pre><code>p = np.array([[0.2, 0.4, 0.4],[0.1, 0.7, 0.2],[0.44, 0.5, 0.06]]... | python|numpy|optimization|pytorch | 1 |
365,246 | 63,887,301 | How to use min function in creating DataFrame calculated columns in Python? | <pre><code>x=[[2,3],[1,8],[5,6]]
df_a=pd.DataFrame(x,columns=['a','b'])
df_a["Diff"]=min(df_a['a'],0)-min(df_a['b'],0)
</code></pre>
<p>I am trying to create a calculated column based on min function, but getting error as</p>
<pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.boo... | <p>If <code>min</code> is the Python's <code>min</code> function, I don't think it takes a Pandas series. You can use Pandas' <code>clip</code>:</p>
<pre><code>df_a['Diff'] = df_a['a'].clip(upper=0) - df_a['b'].clip(upper=0)
</code></pre> | python|pandas|dataframe | 0 |
365,247 | 63,791,925 | Python: Conditional Substraction | <p>My goal is to calculate the thickness [m] of each layer for each id, based on the depth [m] of each layer. The following is a dataframe similar to mine.</p>
<pre><code>eID = [1,1,1,2,2,3,3,3,3]
depth = [0.35,1.5,3.0,0.75,2.0,0.2,0.8,1.7,3.5]
dictex ={"id":eID,"depth [m]":depth}
dfe = pd.DataFrame... | <p>If values are sorted per groups use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.diff</code></a> with replace first values per groups by <a href="http://pandas.pydata.org/pandas-docs/stable/referenc... | python|pandas|conditional-statements | 0 |
365,248 | 63,914,662 | IndexingError: Too many indexers for Python filter | <p>I was following the <a href="https://www.youtube.com/watch?v=Lw2rlcxScZY" rel="nofollow noreferrer">tutorial: Python Pandas Tutorial (Part 4): Filtering - Using Conditionals to Filter Rows and Columns</a>. At around time 11.30, the author made a filter. I tried to do the same with sample data:</p>
<pre><code> id ... | <p>IIUC you filter another DataFrame, <code>dfx</code> instead <code>df</code> and then change column name <code>TYPE</code> to <code>TYP</code>:</p>
<pre><code>mask =(df['VALUE']>0)
df = df.loc[mask, ['ITEM_ID', 'TYP']]
print (df)
ITEM_ID TYP
0 SLM607 O
1 SLM607 O
2 SLM607 O
3 SLM607 O
4 887643 O
5... | python|pandas|filter | 0 |
365,249 | 64,104,245 | Not able to plot numpy dataset using seaborn.kdeplot() | <p>I am using seaborn to plot my dataset.
<strong>(i) Here is my first part of the code which shows the plot in the link below the code:</strong></p>
<pre><code>data = np.random.multivariate_normal([0,0],[[5,2],[2,2]],size=2000)
data = pd.DataFrame(data,columns=['x','y'])
for col in 'xy':
plt.hist(data[col],density... | <p><strong>In the second part of the code</strong></p>
<p>Make this change:</p>
<pre><code>sns.kdeplot(data=data,x='x',y='y')
</code></pre> | python-3.x|pandas|numpy|seaborn | 0 |
365,250 | 64,044,428 | Sample_weights Keras model - IndexError: too many indices for array | <p>I have a rather unbalanced dataset, where I would like to weigh some data differently than others in order to implement my neural network with Keras.<br />
I found out that I can use sample_weights for that.</p>
<p>My code looks like this:</p>
<pre><code>sample_weight = np.ones(shape=(len(y_train),))
sample_weight[y... | <p>The error might be caused by the difference in dimension of the y_train and sample_weight. Here's an idea for troubleshooting:</p>
<ol>
<li>Print and check the length of y_train (<code>len(y_train)</code>) and see if the returned shape is what you expect</li>
<li>Print and check the length of sample_weight (<code>le... | python|pandas | 1 |
365,251 | 64,077,677 | Rolling up each columnar value in a matrix | <p>Here is the data.</p>
<pre><code> day_value = {
'android':[1,0,0,0,0,0,1],
'iphone':[0,1,0,1,0,0,0],
'web':[0,1,1,0,1,0,0],
}
device_rollup = {
'overall':['iphone','android','web'],
'mobile':['iphone','android'],
}
rollup_l7 = {
'overall': 6,
'mobile': 4,
}
</... | <p>I think I figured out the answer.</p>
<pre><code>overall = sum([x | y | z for x,y,z in zip(day_value['android'], day_value['iphone'],day_value['web'])])
mobile = sum([x | y for x,y in zip(day_value['android'], day_value['iphone'])])
rollup_l7 = {'overall':overall, 'mobile':mobile}
print(rollup_l7)
</code></pre> | python|pandas|rollup | 2 |
365,252 | 64,014,197 | Python Pandas - cannot access df with applied filter | <p>I am working on the file with some df, but somehow, i can't access df with applied filter (i want to see data for only specific country - Poland)</p>
<p>I thought that maybe python don't read header as they are, but when i typed df.columns it showed me this name of the column in the list</p>
<p><a href="https://i.st... | <p>If I understand correctly, this should work:
Instead of :</p>
<pre><code>test = file.loc[file.loc['Country Name'] == 'Poland']
</code></pre>
<p>do this:</p>
<pre><code>test = file.loc[file['Country Name'] == 'Poland']
</code></pre>
<p>Through the 'loc' function, you will be selecting the rows, and through the column... | python|pandas | 0 |
365,253 | 64,013,163 | Unknown string format pd.to_datetime in Python. Having issues trying to convert this format to a datetime format | <p>My column headers in my DF are of the following format --></p>
<pre><code>df_weather.columns
['Max-09-23', 'Min-09-23', 'Max-09-24', 'Min-09-24', 'Max-09-25',
'Min-09-25', 'Max-09-26', 'Min-09-26', 'Max-09-27', 'Min-09-27',
'Max-09-28', 'Min-09-28', 'Max-09-29', 'Min-09-29', 'Max-09-30',
'Mi... | <p>An option might be to replace the "Min" / "Max" with a specific year and create a datetime index from the result:</p>
<pre><code>import pandas as pd
# let's create a dummy df...
cols = ['Max-09-23', 'Min-09-23', 'Max-09-24', 'Min-09-24', 'Max-09-25',
'Min-09-25', 'Max-09-26', 'Min-09-26',... | python|pandas|datetime|python-datetime|python-dateutil | 0 |
365,254 | 64,081,367 | Slicing a tensor with a tensor of indices and tf.gather | <p>I am trying to slice a tensor with a indices tensor. For this purpose I am trying to use <code>tf.gather</code>.
However, I am having a hard time understanding the <a href="https://www.tensorflow.org/api_docs/python/tf/gather" rel="nofollow noreferrer">documentation</a> and don't get it to work as I would expect it ... | <p>You can use :</p>
<pre><code>downsampled_activations =tf.gather(activations , tf.squeeze(ids) ,axis = 1)
downsampled_activations.shape # [1,120,4]
</code></pre>
<p>In most cases, the tf.gather method needs 1d indices, and that is right in your case, instead of indices with 3d (1,1,120), a 1d is sufficient (120,). T... | python|tensorflow | 2 |
365,255 | 64,084,014 | Python - Web scraping | <p>I am new to python and am trying to scrape data from the following site. Although this code worked for a different site i cannot get it to work for nextgen stats. anyone have any thoughts as to why? below is my code and the error i am getting</p>
<pre><code>import pandas as pd
import numpy as np
import html5lib
u... | <p>Pandas <code>pandas.read_html</code> is not capable of parsing dynamically loading html tables.</p>
<p>This <a href="https://nextgenstats.nfl.com/stats/receiving/2020/2" rel="nofollow noreferrer">page</a> is fetching that table data using an API call</p>
<p>You can use this below code to fetch and parse the API resp... | python|pandas|dataframe | 1 |
365,256 | 46,695,979 | Pandas - How to get list of | <p>(I am learning Pandas, so please explain solution)</p>
<p>My data looks like this:</p>
<pre><code>Category currency sellerRating Duration endDay ClosePrice
0 Music/Movie/Game US 3249 5 Mon 0.01 0.01
1 Music/Movie/Game US 3249 5 Mon 0.01 0.01
2 Music/Mov... | <p>Use groupby and then apply the sort keeping only top k values</p>
<pre><code>top = 10
df.groupby('Category', group_keys=None).apply(lambda x: x.sort_values('ClosePrice')[:top])
</code></pre>
<p>Since you ask for an explanation of the solution, I'll try.</p>
<p>By using <a href="https://pandas.pydata.org/pandas-do... | python|pandas|pandas-groupby | 0 |
365,257 | 46,799,892 | Save tf.summary.image with Estimator API | <p>at the moment I trying to get a little bit more familiar with the TF Estimator API. I'm working/learning with the example from this <a href="https://medium.com/onfido-tech/higher-level-apis-in-tensorflow-67bfb602e6c0" rel="nofollow noreferrer">blog entry</a>.</p>
<p>Now I have the problem that I'm not able to save ... | <p>You shouldn't have to add a hook. Just add the <code>tf.summary.image</code> call anywhere in your <code>model_fn</code>/<code>input_fn</code> and the estimator should automatically add a summary hook for all summaries created.</p> | python|tensorflow | 1 |
365,258 | 46,694,359 | Read External SQL File into Pandas Dataframe | <p>This is a simple question that I haven't been able to find an answer to. I have a .SQL file with two commands. I'd like to have Pandas pull the result of those commands into a DataFrame. </p>
<p>The SQL file's commands are as such, with the longer query using today's date.</p>
<pre><code>SET @todaydate = DATE(NOW(... | <p>I have a solution that might work for you. It should give you a nice little <code>pandas.DataFrame</code>.</p>
<p>First, you have to read the query inside the sql file. Then just use the <code>pd.read_sql_query()</code> instead of <code>pd.read_sql()</code></p>
<p>I am sure you know it, but here is the doc for the f... | python|pandas|dataframe|path|mysql-python | 34 |
365,259 | 46,814,477 | match strings in list and DF column and put into new DF column | <p>using python, pandas</p>
<p>I have a dataframe with three columns and about a million rows. The third column contains strings. I want to select a subset of these strings that match the strings in a list and put them in a fourth column. </p>
<p>Here is an example of a string from the dataframe:</p>
<pre><code>"BW ... | <p><code>str.extractall</code> expects a regex pattern as a parameter. You can make this regex with </p>
<pre><code>'|'.join(reviews_list)
</code></pre>
<p>But some characters need to be escaped to be used with regex, so import <code>re</code> and use <code>re.escape</code> like this:</p>
<pre><code>[re.escape(item)... | python|list|pandas|dataframe | 1 |
365,260 | 46,665,705 | Convert Pandas Column to DateTime With Rare Date Format | <p>I have one column on my dataframe that follows this date format:</p>
<p>17 MAY2016</p>
<p>I've tried to follow this reference: <a href="http://strftime.org/" rel="nofollow noreferrer">http://strftime.org/</a> and pandas.to_datetime reference: <a href="http://pandas.pydata.org/pandas-docs/version/0.20/generated/pan... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> only:</p>
<pre><code>df = pd.DataFrame({'date':['17 MAY2016']})
df['date'] = pd.to_datetime(df['date'])
print (df)
date
0 2016-05-17
</code></pre>
<p>I... | python|pandas|datetime|dataframe|string-to-datetime | 2 |
365,261 | 46,831,130 | Add dataframe vector to dataframe table | <p>This should be obvious but I cannot make it work.</p>
<p>I have a pandas dataframe <code>A</code> with column and index names:</p>
<pre><code>A = pd.DataFrame([[10, 20], [4, 5], [20, 30]],
columns = ['col1', 'col2'],
index = ['row1', 'row2', 'row3'])
col1 col2
row1 10... | <p>You need create <code>Series</code> from <code>B</code> by selecting by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> or
<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow... | python|pandas|dataframe | 2 |
365,262 | 46,703,083 | Unsupported operand type(s) for -: 'str' and 'float' when building a bar chart | <p>Previously, I was asking to <a href="https://stackoverflow.com/questions/46701899/get-week-numbers-on-multiple-year-that-is-ready-for-plotting-in-pandas">get week numbers on multiple year that is ready for plotting</a>, and based on jezrael's answer I did this:</p>
<pre><code>sheet2['device_create_week'] = sheet2['... | <p>Here is my answers based on your orignal code:
use the <code>plt.xticks()</code> to make the <code>str</code> type work</p>
<pre><code>Xweek_str=data1.device_create_week.tolist()
x = range(len(Xweek_str))
rcParams['figure.figsize'] = (10, 6)
rcParams['figure.dpi'] = 150
fig = plt.figure()
plt.bar(x,data1.device_cr... | python|pandas|matplotlib|dataframe | 6 |
365,263 | 46,995,864 | pandas groupby timeseries data according to function result | <p>I am analyzing power systems time series data, and I am trying to find the contiguous data points that go beyond a certain threshold value.</p>
<p>I am currently using excel formula row by row manually to do this, but I as I am trying to search more efficient methods I realized that this could be done in python pan... | <ul>
<li>Create a mask where less than <code>3</code></li>
<li>Cumulative sum to create groups where greater than or equal to <code>3</code></li>
<li>filter the <code>df</code> by the mask, then <code>groupby</code></li>
<li>Use <code>agg</code> to pass several functions at once</li>
<li>Rename columns</li>
</ul>
<hr>... | python|pandas|pandas-groupby | 3 |
365,264 | 46,930,201 | Pandas to_datetime is not formatting the datetime value in the desired format (dd/mm/YYYY HH:MM:SS AM/PM) | <p>I have the datetime values in the following format</p>
<pre><code> 2017-09-11 01:18:38
2017-09-11 01:34:30
2017-09-11 05:03:57
2017-09-11 09:55:48
2017-09-11 09:59:10
2017-09-11 12:09:05
</code></pre>
<p>I have to display the values in the format dd/mm/YYYY HH:MM:SS AM/PM:</p>
<pre><code> 1... | <p>Given a <strong>string column</strong>, use <a href="http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_datetime</code></a> to convert it to a datetime object column.</p>
<p>Given an <strong><em>already existing</em> datetime column</strong>, us... | python|pandas|datetime|datetime-format | 8 |
365,265 | 46,944,189 | Object Detection on KITTI (strange aspect ratio) | <p>I am trying to train any object detector on the KITTI dataset which has a strange aspect ratio ~370 height and 1240 width. I am not able to get good detections after starting a fine tuning of any of the models in the model zoo. I have taken the sample coco configs and simply changed the image resizer arguments to ... | <p>My problem was with the TFRecord file. The bounding boxes coordinates and labels had the wrong key so the network was being trained on "empty" images with no bounding boxes. This also explained why my error was converging to 0 because the network's weights were just being squashed by the regularization with no los... | tensorflow|object-detection | 1 |
365,266 | 46,694,163 | getting top words from the tf-idf sparse matrix (highest tf-idf value) | <p>I have a list of size 208 (208 arrays of sentences), that looks like:</p>
<pre><code>all_words = [["this is a sentence ... "] , [" another one hello bob this is alice ... "] , ["..."] ...]
</code></pre>
<p>I want to get the words with the highest tf-idf values.
I created a tf-idf matrix:</p>
<pre><code>from skle... | <p>Had a similar issue but found this at <a href="https://towardsdatascience.com/multi-class-text-classification-with-scikit-learn-12f1e60e0a9f" rel="nofollow noreferrer">https://towardsdatascience.com/multi-class-text-classification-with-scikit-learn-12f1e60e0a9f</a>, just change the X and y inputs based on your dataf... | python|feature-extraction|tf-idf|sklearn-pandas | 3 |
365,267 | 46,771,727 | Insert index in Dataframe | <p>This is my <strong>dataframe</strong> df :</p>
<pre><code>df = pd.DataFrame({'a': [0.671399,0.446172,0.614758],
'b' : [ 0.101208 ,-0.243316 ,0.075793],
'c':[-0.181532 ,0.051767, -0.451460]})
a b c
0 0.671399 0.101208 -0.181532
1 ... | <p>Using <code>join</code></p>
<pre><code>In [2794]: s = pd.Series(data=[-0.335485, -1.166658, -0.385571,-1.166658 ],
index=[0,1,2,3])
In [2795]: df.join(pd.DataFrame({'e': s}), how='outer')
Out[2795]:
a b c e
0 0.671399 0.101208 -0.181532 -0.335485
1 0.44... | python|pandas|dataframe | 2 |
365,268 | 46,803,072 | In Python Pandas, how to use like R dplyr mutate_each | <p>In Python Pandas, I want to add columns by executing multiple aggregate functions on multiple columns like R dplyr mutate_each.
For example, Can Python Pandas realize the same processing as the following R script?</p>
<pre><code>R dplyr :
iris %>%
group_by(Species) %>%
mutate_each(funs(min, max, mean)... | <p>With Pandas, this can be accomplished in a more lenghty way. </p>
<p>First, let's prepare the data:</p>
<pre><code>import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
iris_data = load_iris()
iris = pd.DataFrame(iris_data.data, columns = [c[0:3] + c[6] for c in iris_data.feature_names])
ir... | python|r|pandas|dplyr | 1 |
365,269 | 46,908,174 | Merge two columns into one keeping hierarchical structure using pandas or excel writer | <p>I need to collapse two columns into one preserving hierarchical structure of the rest either using pandas or pandas and excel writer. I need to transform this:</p>
<pre><code>df = pd.DataFrame({'A': [ 'p', 'p', 'q'], 'B': ['x', 'y', 'z'], 'C': [1, 2, 3]})
df
A B C
0 p x 1
1 p y 2
2 q z 3
... | <p>It seems you need:</p>
<pre><code>df1 = df.stack().drop_duplicates().reset_index(drop=True).to_frame(name='A')
print (df1)
A
0 p
1 x
2 y
3 q
4 z
</code></pre>
<p>Detail:</p>
<pre><code>print (df.stack())
0 A p
B x
1 A p
B y
2 A q
B z
dtype: object
print (df.stack().drop_dupl... | excel|pandas | 0 |
365,270 | 46,677,935 | No gradients provided in tensorflow (mean_squared_error) | <p>I'm trying to build a simple net of 2 input neurons (+1 bias) going into 1 output neuron to teach it the "and"-function. It's based on the mnist-clissification example, so it might be overly complex for the task, but it's about the general structure of such nets for me, so please don't say "you can just do it in num... | <p>I've made few slight modifications to your code which enable learning the <code>and</code> function:</p>
<p>1) change your <code>train_data</code> to float32 representation.</p>
<pre><code>train_data = np.asarray(np.reshape([[0,0],[0,1],[1,0],[1,1]],[4,2]), dtype=np.float32)`
</code></pre>
<p>2) Remove relu activ... | python|tensorflow|neural-network|artificial-intelligence | 2 |
365,271 | 46,950,112 | How to increase the font size of the bounding box in Tensorflow object detection module? | <p>I have increased the font size to 30 from the default size 24 inside the draw_bounding_box_on_image() in visualization_utils.py</p>
<p>font = ImageFont.truetype('arial.ttf', 30)</p>
<p>But still the font size is not getting changed.</p>
<p><a href="https://i.stack.imgur.com/MOTuP.png" rel="nofollow noreferrer"><i... | <pre><code>i found the issue.
On Mac we need to give the full path.
ImageFont.truetype('/Library/Fonts/Arial.ttf', 30)
</code></pre>
<p>Also, we can put the .ttf file in the current folder and use</p>
<pre><code> ImageFont.truetype('./Arial.ttf', 30)
</code></pre> | tensorflow|object-detection | 5 |
365,272 | 46,829,684 | Using inception v4 in retrain example | <p>I am trying to adapt the example retrain script ( <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retraining/retrain.py" rel="noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retraining/retrain.py</a> ) to use the Inception V4 model. <... | <p>I'm working through the same thing currently.</p>
<p>Try to add <code>:0</code> to the end of your <code>bottleneck_tensor_name</code> and your <code>resized_input_tensor_name</code>.</p>
<p>If you'll notice in <a href="https://github.com/tensorflow/hub/blob/master/examples/image_retraining/retrain.py" rel="nofoll... | python|tensorflow | 5 |
365,273 | 47,057,452 | Is it possible to install the CPU and GPU versions of tensorflow at the same time | <p>I am using <code>nvidia-docker</code> to access GPUs from a docker container. However, not all of our machines have GPUs and I would like to automatically fall back to the CPU version when GPUs are not available. </p>
<p>Do I have to build separate docker images--one for CPU and one for GPU--or is it possible to in... | <p>The GPU version of tensorflow fails to load in the container when started using normal <code>docker</code> (as opposed to <code>nvidia-docker</code>) because the library <code>libcuda.so.1</code> is missing. We managed to use the same image for different hosts in three steps:</p>
<ol>
<li>Link the library stub <cod... | docker|tensorflow | 2 |
365,274 | 46,877,482 | Extracting value from column A if column B is true | <p>Given a dataframe of currencies:</p>
<pre><code>Pair | Amount
EUR/USD| 100,000
USD/EUR| 200,000
USD/JPY| 50,000
</code></pre>
<p>If <code>Pair</code> is, for example, <code>"USD/EUR"</code>, how would I extract <code>Amount</code> into a new column, such that:</p>
<pre><code>Pair | Amount |Dollars
EUR/USD| 1... | <pre><code>import numpy as np
df.assign(Dollars=np.where(df['Pair']=='USD/EUR',df['Amount'],0))
Out[383]:
Pair Amount Dollars
0 EUR/USD 100,000 0
1 USD/EUR 200,000 200,000
2 USD/JPY 50,000 0
</code></pre>
<p>EDIT : </p>
<pre><code>df.assign(Dollars=np.where(df['Pair'].isin(['U... | python|pandas | 7 |
365,275 | 46,826,617 | Create Dummy Variables with Loop in Python | <p>I'm trying to create a bunch of new Binary variables just for some columns that contain a certain word (and I want to name these new binary variables <code>BINARY_ +column name</code>), I'm trying to do it in this was way but it doesn't work:</p>
<pre><code># create empty list
List_of_dummy_names = []
# word
stri... | <p>In your case, <code>col</code> looks like some kind of a collection. You probably want to do this:</p>
<pre><code>List_of_dummy_names.append('BINARY_'+string)
</code></pre> | python|pandas|loops|dummy-variable | 0 |
365,276 | 46,776,079 | np.polyfit how to get lists into a 2D array for y input | <p>I generated latitude, longitude, and altitude data for a satellite orbit. Now, I want to do a polynomial fit for my data in order to interpolate. <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.polyfit.html" rel="nofollow noreferrer">numpy.polyfit()</a> will only take a 2D array for the y-... | <p>It turns out <code>lonAltMatrix = [list(a) for a in zip(lon, alt)]</code> works to create a 5x2 matrix.</p>
<p>For np.polyfit() the number of rows for the y-coordinate must match the length of the x-coordinate.</p> | python|arrays|python-2.7|numpy|multidimensional-array | 0 |
365,277 | 46,904,931 | .bash_profile read in the terminal but not in PyCharm | <p>very simple python run through in Terminal python, but failed in PyCharm. Based on the message, the PATH I defined in the .bash_profile is not passed in PyCharm. How do I let PyCharm know these PATH?</p>
<p>The correct result in Terminal Python:
<a href="https://i.stack.imgur.com/wZDkG.png" rel="nofollow noreferrer... | <p>This is what worked for me for a somewhat similar scenario:</p>
<ul>
<li>I copied .bash_profile into .bashrc </li>
<li>In Pycharm's Terminal settings, make sure that the 'Shell integration' option is not checked </li>
<li>I left 'Shell path' to only have the path to bash (no further
--rcfile arguments required)</li... | python|bash|pycharm|tensorflow | 0 |
365,278 | 47,034,867 | how to replace a cell in a pandas dataframe | <p>After forming the below python pandas dataframe (for example)</p>
<pre><code>import pandas
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pandas.DataFrame(data,columns=['Name','Age'])
</code></pre>
<p>If I iterate through it, I get</p>
<pre><code>In [62]: for i in df.itertuples():
...: print( i.Index... | <p>Hope you are looking for where for conditional replacement i.e </p>
<pre><code>def wow(x):
return x ** 10
df['new'] = df['Age'].where(~(df['Name'] == 'Alex'),wow(df['Age']))
</code></pre>
<p>Output : </p>
<pre>
Name Age new
0 Alex 10 10000000000
1 Bob 12 12
2 Cla... | python-3.x|pandas | 3 |
365,279 | 47,012,474 | Bernoulli random number generator | <p>I cannot understand how Bernoulli Random Number generator used in numpy is calculated and would like some explanation on it. For example:</p>
<pre><code>np.random.binomial(size=3, n=1, p= 0.5)
Results:
[1 0 0]
</code></pre>
<p>n = number of trails</p>
<p>p = probability of occurrence</p>
<p>size = number of exp... | <blockquote>
<p>I am asking on how the algorithm works to produce the numbers. – WhiteSolstice 35 mins ago</p>
</blockquote>
<h3>Non-technical explanation</h3>
<p>If you pass <code>n=1</code> to the Binomial distribution it is equivalent to the Bernoulli distribution. In this case the function could be thought of s... | numpy|statistics | 21 |
365,280 | 33,000,660 | Converting Pandas Timestamp to just the time (looking for something faster than .apply) | <p>So if I have a timestamp in pandas as such:</p>
<pre><code>Timestamp('2014-11-07 00:05:00')
</code></pre>
<p>How can I create a new column that just has the 'time' component?</p>
<p>So I want </p>
<pre><code>00:05:00
</code></pre>
<p>Currently, I'm using <code>.apply</code> as shown below, but this is slow (my ... | <p>You want <code>.dt.time</code> see the <a href="http://pandas.pydata.org/pandas-docs/version/0.15.2/basics.html#dt-accessor" rel="noreferrer">docs</a> for some more examples of things under the <code>.dt</code> accessor.</p>
<pre><code>df['date_time'].dt.time
</code></pre> | python|datetime|pandas | 11 |
365,281 | 33,036,885 | How to merge column data of the same value and sum its specific data | <p>How can I merge column data of the same value and sum its specific data (in this case based of the DATE column)</p>
<p>For Example: <code>df</code> includes:</p>
<pre><code>78 79 80 DATE
8.99 7.99 6.99 201107
3.5 2.5 1.5 201107
5.48 4.48 3.48 201108
4.04 3.04 2.04... | <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html#pandas.DataFrame.groupby" rel="nofollow"><code>groupby</code></a> on 'DATE' column and then call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html#pandas.DataFrame.sum" rel="nof... | python|excel|pandas | 4 |
365,282 | 32,707,482 | Remove rows where values appear in all columns in Pandas | <p>Here is a very simple dataframe:</p>
<pre><code>df = pd.DataFrame({'col1' :[1,2,3],
'col2' :[1,3,3] })
</code></pre>
<p>I'm trying to remove rows where there are duplicate values (e.g., row 3)</p>
<p>This doesn't work,</p>
<pre><code>df = df[(df.col1 != 3 & df.col2 != 3)]
</code></pre>
<... | <p>If I understand your question correctly, I think you were close. </p>
<p>Starting from your data:</p>
<pre><code>In [20]: df
Out[20]:
col1 col2
0 1 1
1 2 3
2 3 3
</code></pre>
<p>And doing this: </p>
<pre><code>In [21]: df = df[df['col1'] != df['col2']]
</code></pre>
<p>Returns:<... | python|pandas | 1 |
365,283 | 32,860,057 | ndarray concatenate error | <p>I wish to concatenate the following arrays:</p>
<pre><code>a=np.array([[1,2],[1],[2,3,4]])
b=np.array([[20,2]])
np.concatenate((a,b),axis=0)
</code></pre>
<p>but I get the following error:</p>
<pre><code>ValueError Traceback (most recent call last)
<ipython-input-40-42253... | <p>Check the dtype, ndim and shape of <code>a</code>: you'll find that those are <code>numpy.object</code>, 1 and <code>(3,)</code>, respectively. This is because array <code>a</code> contains lists of different lengths, so each list is treated as an object, and <code>a</code> is a one dimensional array of objects. I d... | python|numpy | 3 |
365,284 | 32,682,928 | Loading arrays from numpy npz files in python | <p>I usually save data in npz files in python. How to write a function which loads the npz file and automatically creates arrays which are present in the <code>.npz</code> file. For example, say there are three arrays <code>A</code>, <code>B</code>, and <code>C</code> in a file named <code>some_data.npz</code>.</p>
<p... | <p>If you want to create names store the arrays in a <code>dict</code>:</p>
<pre><code>a1 = np.array([1,2,3])
a2 = np.array([4,5,6])
a3 = np.array([7,8,9])
np.savez("test", A=a1,B=a2,C=a3)
a = np.load("test.npz")
d = dict(zip(("data1A","data1B","data1C"), (a[k] for k in a)))
print(d)
{'data1A': array([4, 5, 6]), 'dat... | python|python-2.7|numpy | 7 |
365,285 | 32,892,932 | Create the Oriented Bounding-box (OBB) with Python and NumPy | <p>I've almost translated into the Python this <a href="https://hewjunwei.wordpress.com/2013/01/26/obb-generation-via-principal-component-analysis/" rel="nofollow">example</a></p>
<p>My listing is</p>
<pre><code>import numpy
a = numpy.array([(3.7, 1.7), (4.1, 3.8), (4.7, 2.9), (5.2, 2.8), (6.0,4.0), (6.3, 3.6), (9.7... | <p>He does not fully explain how he gets the center and the final bounding box, but I think this should work:</p>
<pre><code>%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
a = np.array([(3.7, 1.7), (4.1, 3.8), (4.7, 2.9), (5.2, 2.8), (6.0,4.0), (6.3, 3.6), (9.7, 6.3), (10.0, 4.9), (11.0, 3.6),... | python|numpy | 9 |
365,286 | 32,805,497 | Reading binary file of doubles written in Java with ObjectOutputStream in Python with numpy.fromfile | <p>I've written an array of doubles in binary format to a file using the ObjectOutputStream's writeDouble() function in Java. When I try to read this file on Python using numpy.fromfile, it doesn't give me the same values. When I try to move around in bits using seek(), it still doesn't help.</p>
<p>If I do the same p... | <p>Almost the same, but now no metadata is added to the file:</p>
<pre><code>OutputStream os = new FileOutputStream("data.bin");
DataOutputStream dos = new DataOutputStream( os );
for (int i = 1; i <= 10; i++) {
dos.writeDouble(arr[i]);
}
</code></pre> | java|python|numpy | 1 |
365,287 | 32,840,035 | pandas groupby not working for 3 columns | <p>I am trying to calculate Sum of column d in group by result of column a,b,c.</p>
<p>Although I have 2 different values in column c but still it is not coming as part of same group resulting sum is not calculated properly.</p>
<p>Please suggest.
Code I am using is :</p>
<pre><code>s = df.groupby(['a','b','c'])['d... | <p>After changing datatype of column c from object to int and it worked.</p>
<p>Now b is still object , so looking for why it is working after changing c only.</p> | python|pandas | 1 |
365,288 | 38,555,880 | groupby DataFrame with new column representing the group | <p>I have a DataFrame with a timestamp column</p>
<pre><code>d1=DataFrame({'a':[datetime(2015,1,1,20,2,1),datetime(2015,1,1,20,14,58),
datetime(2015,1,1,20,17,5),datetime(2015,1,1,20,31,5),
datetime(2015,1,1,20,34,28),datetime(2015,1,1,20,37,51),datetime(2015,1,1,20,41,19),
datetime(2015,1,1,20,49,4),datetime(2015,1,1... | <p>Use <code>.transform()</code> on your <code>groupby</code> object with an <code>itertools.count</code> iterator:</p>
<pre><code>from datetime import datetime
from itertools import count
import pandas as pd
d1 = pd.DataFrame({'a': [datetime(2015,1,1,20,2,1), datetime(2015,1,1,20,14,58),
dat... | python|pandas | 1 |
365,289 | 38,767,154 | Python TypeError in Numpy polyfit ufunc did not contain loop with matching signature types | <p>This has been asked before so apologies for asking again, I have followed the suggested solutions provided in <a href="https://stackoverflow.com/questions/36637428/typeerror-ufunc-subtract-did-not-contain-a-loop-with-signature-matching-types?noredirect=1&lq=1">these</a> <a href="https://stackoverflow.com/questio... | <p>I solved this (I hope), I created new lists by iterating through each of the vals range and slopes list, turning each of the objects contained in each into floats. I had done that already inside my for loop so I should have just done that earlier.</p> | python|numpy | 1 |
365,290 | 38,613,043 | Pandas: checking if a string contains at least two words from a list | <p>I am using the fast, vectorized <code>str.contains</code> method in <code>Pandas</code> to check whether each row in my dataframe contains <strong>at least one word</strong> from my <code>list_word</code>. </p>
<pre><code>list_words='foo ber haa'
df = pd.DataFrame({'A' : ['foo foor', 'bar bar', 'foo hoo', 'bar haa... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferrer"><code>concat</code></a> with <code>list comprehension</code>:</p>
<pre><code>#changed ber to bar
list_words='foo bar haa'
df = pd.DataFrame({'A' : ['foo foor', 'bar bar', 'foo hoo', 'bar haa',
... | python|pandas | 4 |
365,291 | 38,601,573 | Set specific cell of multi-indexed Pandas DataFrame | <p>I have a DataFrame (df_test) with row labels ('letters') and column names ('numbers') which can be grouped by row labels.</p>
<pre><code>>>> letters = ['a','a','a','a','a','b','b','b','c','c','c','c']
>>> n = {'numbers': [0,1,2,3,4,0,1,2,0,1,2,3]}
>>> df_test = pd.DataFrame(n, index=lett... | <p>Because @piRSquared's answer didn't work with my DataFrame for reasons still unknown, this is what I ended up going with.</p>
<pre><code>>>> letters = ['a','a','a','a','a','b','b','b','c','c','c','c']
>>> n = {'numbers': [0,1,2,3,4,0,1,2,0,1,2,3]}
>>> df_test = pd.DataFrame(n, index=lette... | python|pandas|dataframe | 0 |
365,292 | 38,806,750 | Make console-friendly string a useable pandas dataframe python | <p>A quick question as I'm currently changing from R to pandas for some projects:</p>
<p>I get the following print output from <code>metrics.classification_report</code> from <code>sci-kit learn</code>:</p>
<pre><code> precision recall f1-score support
0 0.67 0.67 ... | <p>Assign it to a variable, <code>s</code>:</p>
<pre><code>s = classification_report(y_true, y_pred, target_names=target_names)
</code></pre>
<p>Or directly:</p>
<pre><code>s = '''
precision recall f1-score support
class 0 0.50 1.00 0.67 1
class 1 0.00 0... | python|pandas|dataframe | 2 |
365,293 | 38,531,503 | Pandas - dataframe.apply(lambad x: x is np.nan) does not work | <p>So basically a column in dataframe has Nan and float, I want to use apply to calculate the value in the column. If the value is nan, then return else, calculate.</p>
<p>But looks like x is np.nan in lambda does not give me the right answer. here is an example</p>
<pre><code>In[6]: df = pd.DataFrame({'A':[np.nan,np... | <p>First things first. To get what you want:</p>
<pre><code>df.A.isnull()
</code></pre>
<p>Secondly, <code>np.nan</code> is not comparable. By design <code>np.nan == np.nan</code> is False.</p>
<p>To get around this, pandas and numpy have specific functions to test if it is null. You could:</p>
<pre><code>df.A.a... | python|python-2.7|numpy|pandas | 5 |
365,294 | 38,830,423 | Groupby and any() | all() | <p>I have the following <code>pd.DataFrame</code></p>
<pre><code>In [155]: df1
Out[155]:
ORDER_ID ACQ DATE UID
2 3 False 2014-01-03 1
3 4 True 2014-01-04 2
4 5 False 2014-01-05 3
6 7 True 2014-01-08 5
7 8 False 2014-01-08 5
9 10 False 2014-0... | <p>You need first use condition and then add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.all.html" rel="nofollow"><code>all</code></a>:</p>
<pre><code>print (df1.groupby('UID').filter(lambda x: (x.ACQ == False).all()))
ORDER_ID ACQ DATE UID
2 3 False 2014-01-03 ... | python|pandas | 3 |
365,295 | 38,641,162 | Sklearn PCA returning an array with only one value, when given an array of hundreds | <p>I wrote a program intended to classify an image by similarity: </p>
<pre><code>for i in g:
fulFi = i
tiva = []
tivb = []
a = cv2.imread(i)
b = cv2.resize(a, (500, 500))
img2 = flatten_image(b)
tivb.append(img2)
cb = np.array(tivb)
iab = trueArray(cb)
print "Image: ... | <p>If <code>n_components=2</code>, <code>RandomizedPCA</code> will only keep a maximum of 2 components (see the documentation <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.RandomizedPCA.html" rel="nofollow">here</a>). Try increasing this to allow more components to be selected; this sh... | python|numpy|scikit-learn|transform|pca | 2 |
365,296 | 38,523,596 | Tensorflow + Matplotlib animation | <p>I am trying to implement the Game of Life using tensorflow and use matplotlib.animation to depict the animation. Although the image gets displayed but it is not animating for some reason. Below is the code I am using:</p>
<p>Ref: <a href="http://learningtensorflow.com/lesson8/" rel="nofollow">http://learningtensorf... | <p>When you are displaying the image, you are displaying the static image not the animation. You need to remove this line, as stated in the tutorial:</p>
<pre><code>plot = plt.imshow(X, cmap='Greys', interpolation='nearest')
</code></pre>
<p><code>Hint: you will need to remove the plt.show() from the earlier code to ... | python|animation|matplotlib|tensorflow|conways-game-of-life | 1 |
365,297 | 38,663,121 | Pandas: select rows from columns using Regex | <p>I want to extract rows from column <code>feccandid</code> that have a H or S as the first value:</p>
<pre><code> cid amount date catcode feccandid
0 N00031317 1000 2010 B2000 H0FL19080
1 N00027464 5000 2009 B1000 H6IA01098
2 N00024875 1000 2009 A5200 S2IL08088
3 ... | <p>Why not just use <code>str.match</code> instead of extract and negate?</p>
<p>ie <code>df[df['col'].str.match(r'^(S|H)')]</code></p>
<p>(I came here looking for the same answer, but the use of extract seemed odd, so I found the docs for <code>str.ops</code>.</p>
<p>W</p> | regex|pandas | 5 |
365,298 | 38,636,482 | Solving simultaneous equations in python | <p>I have following test program. My query is two folded: (1) Some how the solution is giving zero and (2) Is it appropriate to use this <code>x2= np.where(x > y, 1, x)</code> kind of conditions on variables ? Are there any constrained optimization routines in Scipy ? </p>
<pre><code>a = 13.235
b = 70.678
def sys... | <p>First up, your <code>system</code> function is an identity, since you <code>return X</code> instead of <code>return f</code>. The return should be the same shape as the <code>X</code> so you had better have </p>
<pre><code>f = np.array([2*x2 - y - a, 3*x2 + 2*y- b])
</code></pre>
<p>Next the function, as written h... | python|python-3.x|numpy | 1 |
365,299 | 38,580,927 | The comments argument of genfromtxt in numpy | <p>I am learning the I/O functions of genfromtxt in numpy.
I tried an example from the user guide of numpy. It is about the comments argument of genfromtxt.</p>
<p><strong>Here is the example from the user guide of numpy:</strong></p>
<pre><code>>>> data = """#
... # Skip me !
... # Skip me too !
... 1, 2
..... | <p>Try below. First, dont use <code>"\"</code>. Second, why are you using <code>.BytesIO()</code> use <code>StringIO()</code></p>
<pre><code>import numpy as np
from StringIO import StringIO
data = """#
# Skip me !
# Skip me too !
1, 2
3, 4
... | python|python-3.x|numpy|genfromtxt | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.