id stringlengths 7 11 | source stringclasses 1
value | category stringclasses 11
values | title stringlengths 15 214 | text stringlengths 70 30.5k | url stringlengths 57 160 | tags stringlengths 3 113 | created_at int64 1.22B 1.79B |
|---|---|---|---|---|---|---|---|
se_79883287 | stackoverflow | DATA_SCIENCE | Merging 2 dataframes using ffill, but finally only retaining the rows from the first dataframe | Merging 2 dataframes using ffill, but finally only retaining the rows from the first dataframe
Let's say I have a time series of truth values and a time series of "updating" predictions, but times are not in sync:
import pandas as pd
import numpy as np
truth = pd.DataFrame({"time": np.arange(0.,100.,10.), "truth": 0}... | https://stackoverflow.com/questions/79883287/merging-2-dataframes-using-ffill-but-finally-only-retaining-the-rows-from-the-f | python, pandas, dataframe, merge, ffill | 1,770,276,137 |
se_43387467 | stackoverflow | DATA_SCIENCE | How to remove seconds from datetime? | How to remove seconds from datetime?
I have the following date and I tried the following code,
df['start_date_time'] = [
"2016-05-19 08:25:00", "2016-05-19 16:00:00", "2016-05-20 07:45:00",
"2016-05-24 12:50:00", "2016-05-25 23:00:00", "2016-05-26 19:45:00"]
df['start_date_time'] = pd.to_datetime([df['start_da... | https://stackoverflow.com/questions/43387467/how-to-remove-seconds-from-datetime | python, pandas, datetime, dataframe | 1,492,073,004 |
se_61429279 | stackoverflow | DATA_SCIENCE | How to keep variable in memory - PyCharm | How to keep variable in memory - PyCharm
I'm running code quite frequently when working in PyCharm. Problem is that the entire code manipulates data temporarily stored in excel (we'll be moving this to the database once the program is up and running). Loading data takes time.
Is there a way in PyCharm to keep variabl... | https://stackoverflow.com/questions/61429279/how-to-keep-variable-in-memory-pycharm | python, pandas, pycharm, ide | 1,587,833,694 |
se_76487120 | stackoverflow | DATA_SCIENCE | How to correct this code to not raise a SettingWithCopyWarning? | How to correct this code to not raise a SettingWithCopyWarning?
I'm following along with this: https://www.kdnuggets.com/2021/01/cleaner-data-analysis-pandas-pipes.html
About halfway down, the author creates a function to remove outliers:
def to_category(df):
cols = df.select_dtypes(include='object').columns
f... | https://stackoverflow.com/questions/76487120/how-to-correct-this-code-to-not-raise-a-settingwithcopywarning | python, pandas, warnings | 1,686,892,474 |
se_63757556 | stackoverflow | DATA_SCIENCE | Heatmap of counts of every value in every column | Heatmap of counts of every value in every column
I have a dataframe that is like this:
| A | B | C | D |
|---|---|----|---|
| 1 | 3 | 10 | 4 |
| 2 | 3 | 1 | 5 |
| 1 | 7 | 9 | 3 |
Where A B C D are categories, and the values are in the range [1, 10] (some values might not appear in a single column)
I woul... | https://stackoverflow.com/questions/63757556/heatmap-of-counts-of-every-value-in-every-column | python, pandas, dataframe, seaborn | 1,599,332,502 |
se_58257812 | stackoverflow | DATA_SCIENCE | replace() takes no keyword arguments, in for loop | replace() takes no keyword arguments, in for loop
I'm trying to convert multiple columns of dollar amount into float, and wrote the following code
for column in wo.columns[14:21]:
column = (column.replace( '[\$,)]','', regex=True )
.replace( '[(]','-', regex=True ).replace('#NAME?','NaN', regex=Tr... | https://stackoverflow.com/questions/58257812/replace-takes-no-keyword-arguments-in-for-loop | python, pandas, for-loop, replace, typeerror | 1,570,369,230 |
se_65348297 | stackoverflow | DATA_SCIENCE | How to get the median of a column based on another column value using Pandas? | How to get the median of a column based on another column value using Pandas?
How can I get the median of ConvertedComp column for all Gender = 'Woman' from this Pandas dataframe (It only shows 'Man' because I'm only showing df.head(10)):
ConvertedComp
Gender
0
61000.0
Man
1
95179.0
Man
2
90000.0
Man
3... | https://stackoverflow.com/questions/65348297/how-to-get-the-median-of-a-column-based-on-another-column-value-using-pandas | python, pandas, dataframe | 1,608,238,871 |
se_79880701 | stackoverflow | DATA_SCIENCE | Python script for automating the extraction of document links from a comapany network and writing to an Excel file | Python script for automating the extraction of document links from a comapany network and writing to an Excel file
I am in the process of finalizing a database in XLSX format containing all the products of my company where I am an intern. In particular, I created a column where I insert one by one the links leading to... | https://stackoverflow.com/questions/79880701/python-script-for-automating-the-extraction-of-document-links-from-a-comapany-ne | python, excel, pandas, automation | 1,769,979,049 |
se_79879092 | stackoverflow | DATA_SCIENCE | Understanding list-like functions in transform and apply command in pandas | Understanding list-like functions in transform and apply command in pandas
In Series apply/transform, list-like methods behave as follows:
The method is first applied to individual values
If that fails, the entire Series is passed to the method
Here is a sample code to see Series's behaviour. First a single value is... | https://stackoverflow.com/questions/79879092/understanding-list-like-functions-in-transform-and-apply-command-in-pandas | python, pandas, dataframe | 1,769,735,599 |
se_79877379 | stackoverflow | DATA_SCIENCE | ETL on a Overcomplex Data Structure with pandas and pyspark | ETL on a Overcomplex Data Structure with pandas and pyspark
The question is: are the proposed methods for flattening a given dataframe efficient enough, or could they be further refined?
An example of a pandas input dataframe columns (it is a given, cannot be changed):
id1 (string)
id2 (string)
date_create (datetim... | https://stackoverflow.com/questions/79877379/etl-on-a-overcomplex-data-structure-with-pandas-and-pyspark | python, json, pandas, dataframe, pyspark | 1,769,538,107 |
se_49830786 | stackoverflow | DATA_SCIENCE | Why did Pandas stop parsing mm/dd/yyyy date format? | Why did Pandas stop parsing mm/dd/yyyy date format?
Pandas used to parse datetime strings in indexing and slicing for convenience, but it seems that it stopped parsing mm/dd/yyyy as a date format.
The following code examples all cause an error parsing datetime string:
Case 1:
import pandas as pd
#to_datetime method
pd... | https://stackoverflow.com/questions/49830786/why-did-pandas-stop-parsing-mm-dd-yyyy-date-format | python, pandas, date, datetime | 1,523,704,308 |
se_53773938 | stackoverflow | DATA_SCIENCE | Parsing data in Excel file to create data frame | Parsing data in Excel file to create data frame
I am analyzing data from Excel file. I want to create data frame by parsing data from Excel using Python. Data in my Excel file looks like as follows:
The first row highlighted in yellow contains match, which will be one of the columns in data frame that I wanted to cre... | https://stackoverflow.com/questions/53773938/parsing-data-in-excel-file-to-create-data-frame | python, pandas, parsing, dataframe | 1,544,765,183 |
se_79880250 | stackoverflow | DATA_SCIENCE | How do you control the printed representation of objects in a Pandas Series (or DataFrame)? | How do you control the printed representation of objects in a Pandas Series (or DataFrame)?
I am using Pandas 2.3. I have a Pandas Series with an object dtype. The objects are Bits instances from the bitstring library, or short lists of Bits; but I don't think that the exact object type is important. I have seen th... | https://stackoverflow.com/questions/79880250/how-do-you-control-the-printed-representation-of-objects-in-a-pandas-series-or | python, pandas, bitstring | 1,769,897,668 |
se_79879978 | stackoverflow | DATA_SCIENCE | Move time 1 hour back on range of rows in pandas | Move time 1 hour back on range of rows in pandas
I have a dataset with a 'Time' column; for 2 dates the time is incorrect and I need to move it back by 1 hour.
This is what my dataframe looks like:
Date Time
05.01.2026 17:00
06.01.2026 18:00
07.01.2026 18:00
08.01.2026 17:00
The time should be 17... | https://stackoverflow.com/questions/79879978/move-time-1-hour-back-on-range-of-rows-in-pandas | python, pandas, dataframe, datetime | 1,769,856,746 |
se_66174322 | stackoverflow | DATA_SCIENCE | Group by month Danfo.js | Group by month Danfo.js
My goal is to translate a line of code written in python's pandas to Danfo.js. The python code is the following:
ftest_raw_money_per_month = ftest_raw.groupby(ftest_raw['trans_date'].dt.strftime('%Y-%m'))['tran_amount'].sum().sort_index()
Where the input data ftest_raw is:
customer_id t... | https://stackoverflow.com/questions/66174322/group-by-month-danfo-js | javascript, pandas, danfojs | 1,613,142,868 |
se_78187026 | stackoverflow | DATA_SCIENCE | How to reverse the value of column in a dataframe? | How to reverse the value of column in a dataframe?
Given a dataframe with one column Name and two rows.
Input: Name
ABCD
XYZ
Output: Name
DCBA
ZYX
I have searched online and the solution is to reverse the row/column order. Kindly suggest how can I reverse the value in a column in a data... | https://stackoverflow.com/questions/78187026/how-to-reverse-the-value-of-column-in-a-dataframe | python, pandas, string, dataframe | 1,710,855,162 |
se_75158677 | stackoverflow | DATA_SCIENCE | reverse a string column in pandas dataframe in a specific order | reverse a string column in pandas dataframe in a specific order
I have this column in my dataframe, which is basically a date.
0 2023-01-01
1 2023-01-01
2 2023-01-01
3 2023-01-01
4 2023-01-01
...
1015 2023-01-17
1016 2023-01-17
1017 2023-01-17
1018 2023-01-17
10... | https://stackoverflow.com/questions/75158677/reverse-a-string-column-in-pandas-dataframe-in-a-specific-order | python, pandas, dataframe | 1,674,041,945 |
se_78810622 | stackoverflow | DATA_SCIENCE | Finding differences and concatenating the differences in pandas | Finding differences and concatenating the differences in pandas
I have two csv files with same column names like this:
File1: (df1)
column1 column2 column3 column4
ABC 100 020 030
DEF 200 040 050
GHI 300 001 002
File2: (df2)
column1 column2 ... | https://stackoverflow.com/questions/78810622/finding-differences-and-concatenating-the-differences-in-pandas | python, pandas, dataframe, csv | 1,722,328,900 |
se_78489915 | stackoverflow | DATA_SCIENCE | How to lemmatize text column in pandas dataframes using stanza? | How to lemmatize text column in pandas dataframes using stanza?
I read csv file into pandas dataframe.
My text column is df['story']. How do I lemmatize this column?
Should I tokenize before? | https://stackoverflow.com/questions/78489915/how-to-lemmatize-text-column-in-pandas-dataframes-using-stanza | pandas, nlp, tokenize, lemmatization, stanza | 1,715,862,890 |
se_78720804 | stackoverflow | DATA_SCIENCE | Split a pandas dataframe column into multiple based on text in those columns | Split a pandas dataframe column into multiple based on text in those columns
I have a pandas dataframe with a column.
id text_col
1 Was it Accurate?: Yes\n\nReasoning: This is a sample text
2 Was it Accurate?: Yes\n\nReasoning: This is a sample text
3 Was it Accurate?: No\n\nReasoning: This is a sample ... | https://stackoverflow.com/questions/78720804/split-a-pandas-dataframe-column-into-multiple-based-on-text-in-those-columns | python, python-3.x, pandas, dataframe | 1,720,441,022 |
se_78750943 | stackoverflow | DATA_SCIENCE | Split a pandas dataframe column into multiple based on text values | Split a pandas dataframe column into multiple based on text values
I have a pandas dataframe with a column.
id text_col
1 Was it Accurate?: Yes\n\nReasoning: This is a sample : text
2 Was it Accurate?: Yes\n\nReasoning: This is a :sample 2 text
3 Was it Accurate?: No\n\nReasoning: This is a sample: 1. t... | https://stackoverflow.com/questions/78750943/split-a-pandas-dataframe-column-into-multiple-based-on-text-values | python, python-3.x, pandas, dataframe | 1,721,060,587 |
se_79058570 | stackoverflow | DATA_SCIENCE | Pandas get first negative number from the bottom | Pandas get first negative number from the bottom
I have following df. In which I want to see the first negative number after the last outcome number. & in the "first negative from last " col "this should occur or rather anything to highlight that row. The "this should appear on the first negative after the last outcom... | https://stackoverflow.com/questions/79058570/pandas-get-first-negative-number-from-the-bottom | python, pandas, dataframe | 1,728,199,914 |
se_52790922 | stackoverflow | DATA_SCIENCE | How to change date format in python pandas from mm/dd/yyyy to dd-mmm-yyyy | How to change date format in python pandas from mm/dd/yyyy to dd-mmm-yyyy
I have a column of dates with the format mm/dd/yyyy and I want to change its format to dd-mmm-yyyy. How do I do this?
For example, how do I format the date 10/12/2018 to 12-Oct-2018.
Also I need to ensure it will not lose its properties. Like wh... | https://stackoverflow.com/questions/52790922/how-to-change-date-format-in-python-pandas-from-mm-dd-yyyy-to-dd-mmm-yyyy | python, pandas | 1,539,418,183 |
se_64801479 | stackoverflow | DATA_SCIENCE | How to combine two different trained ML models as one? | How to combine two different trained ML models as one?
I have trained two ml models based on two different datasets. Then I saved them as model1.pkl and model2.pkl . There are two user inputs(not input data for model) like x=0 and x=1 and if x=0 I have to go with model1.pkl for prediction else I have to go with model2... | https://stackoverflow.com/questions/64801479/how-to-combine-two-different-trained-ml-models-as-one | python, pandas, machine-learning, conditional-statements, pickle | 1,605,174,267 |
se_66660793 | stackoverflow | DATA_SCIENCE | Pandas dataframe with less number of columns to SQL Server Table | Pandas dataframe with less number of columns to SQL Server Table
I am trying to insert some data into a table in sql-server using sqlalchemy and the function df.to_sql.
The problem is that the dataframe doesn't have the same number of columns (it has less columns than the sql server table) as the table and for the col... | https://stackoverflow.com/questions/66660793/pandas-dataframe-with-less-number-of-columns-to-sql-server-table | python, sql-server, pandas, sqlalchemy | 1,615,917,583 |
se_55035369 | stackoverflow | DATA_SCIENCE | How to retain null/nan in one of the groupby columns while performing df.groupby | How to retain null/nan in one of the groupby columns while performing df.groupby
Lets say I have a dataframe that looks like this:
group_cols = ['Group1', 'Group2', 'Group3']
df = pd.DataFrame([['A', 'B', 'C', 54.34],
['A', 'B', np.nan, 61.34],
['B', 'A', 'C', 514.5],
... | https://stackoverflow.com/questions/55035369/how-to-retain-null-nan-in-one-of-the-groupby-columns-while-performing-df-groupby | python, pandas, dataframe, group-by | 1,551,927,558 |
se_22551403 | stackoverflow | DATA_SCIENCE | Python pandas Filtering out nan from a data selection of a column of strings | Python pandas Filtering out nan from a data selection of a column of strings
Without using groupby how would I filter out data without NaN?
Let say I have a matrix where customers will fill in 'N/A','n/a' or any of its variations and others leave it blank:
import pandas as pd
import numpy as np
df = pd.DataFrame({'m... | https://stackoverflow.com/questions/22551403/python-pandas-filtering-out-nan-from-a-data-selection-of-a-column-of-strings | python, pandas, dataframe | 1,395,381,859 |
se_78009793 | stackoverflow | DATA_SCIENCE | How can I apply a code to a zip file while also changing the filetype in the output zip folder? | How can I apply a code to a zip file while also changing the filetype in the output zip folder?
I have a code that I am trying to use on a zip file in python and I want the output to be another zip file, but with the files changed to .txt or .csv.
The code I have runs without error, but fails to change the file type a... | https://stackoverflow.com/questions/78009793/how-can-i-apply-a-code-to-a-zip-file-while-also-changing-the-filetype-in-the-out | python, pandas, jupyter-notebook, zip | 1,708,114,403 |
se_79071731 | stackoverflow | DATA_SCIENCE | How to identify nth row that satisfies condition | How to identify nth row that satisfies condition
I have a dataframe with months and sales. If somebody does 250 sales for 3 consecutive months, they get a bonus.
Once the bonus month is identified, the counter resets and starts to count the next 3 consecutive months with 250
if there is less than 250 sales, then the ... | https://stackoverflow.com/questions/79071731/how-to-identify-nth-row-that-satisfies-condition | python, pandas, dataframe, data-analysis | 1,728,500,892 |
se_11077023 | stackoverflow | DATA_SCIENCE | What are the differences between Pandas and NumPy+SciPy in Python? | What are the differences between Pandas and NumPy+SciPy in Python?
They both seem exceedingly similar and I'm curious as to which package would be more beneficial for financial data analysis. | https://stackoverflow.com/questions/11077023/what-are-the-differences-between-pandas-and-numpyscipy-in-python | python, numpy, scipy, pandas | 1,339,994,748 |
se_59009359 | stackoverflow | DATA_SCIENCE | How can I get unique words from a DataFrame column of strings? | How can I get unique words from a DataFrame column of strings?
I'm looking for a way to get a list of unique words in a column of strings in a DataFrame.
import pandas as pd
import numpy as np
df = pd.read_csv('FinalStemmedSentimentAnalysisDataset.csv', sep=';',dtype=
{'tweetId':int,'tweetText':str,'tweetDate... | https://stackoverflow.com/questions/59009359/how-can-i-get-unique-words-from-a-dataframe-column-of-strings | python, pandas, numpy, dataframe, bayesian-networks | 1,574,524,119 |
se_79069211 | stackoverflow | DATA_SCIENCE | Pandas Groupby Show Non-Matching Values | Pandas Groupby Show Non-Matching Values
I have the following dataframe:
data = [['123456ABCD234567', 'A'], ['8502', 'A'],
['74523654894WRZI3', 'B'], ['85CGNK6987541236', 'B'],
['WF85Z4HJ95R4CF2V', 'C'], ['VB52FG85RT74DF96', 'C'],
['WERTZ852146', 'D'], ['APUNGF', 'D']
]
df = pd.DataFrame(data, columns=... | https://stackoverflow.com/questions/79069211/pandas-groupby-show-non-matching-values | python, pandas, dataframe, group-by | 1,728,461,262 |
se_53982871 | stackoverflow | DATA_SCIENCE | Pandas : Reading first n rows from parquet file? | Pandas : Reading first n rows from parquet file?
I have a parquet file and I want to read first n rows from the file into a pandas data frame.
What I tried:
df = pd.read_parquet(path= 'filepath', nrows = 10)
It did not work and gave me error:
TypeError: read_table() got an unexpected keyword argument 'nrows'
I ... | https://stackoverflow.com/questions/53982871/pandas-reading-first-n-rows-from-parquet-file | python, pandas, dataframe, parquet | 1,546,220,723 |
se_79054556 | stackoverflow | DATA_SCIENCE | Python function for determining if selected file contains time series data does not work | Python function for determining if selected file contains time series data does not work
I am trying to create an application for classifying Time Series data. I created a function that is supposed to check whether a file contains time series data or not.
I uploaded a time series data from the following website to che... | https://stackoverflow.com/questions/79054556/python-function-for-determining-if-selected-file-contains-time-series-data-does | python, pandas, time-series | 1,728,049,065 |
se_59291205 | stackoverflow | DATA_SCIENCE | .xlsx downloading issue in python | .xlsx downloading issue in python
I am new to Python development.
I am developing a flask API in Python that will help to download one excel file in .xlsx format.
my code is generating the file in .xlsx format but when I downloading the report I am getting the error: "File format or file extensions are not valid. Ver... | https://stackoverflow.com/questions/59291205/xlsx-downloading-issue-in-python | python, pandas, flask, pandas.excelwriter | 1,576,085,610 |
se_53645882 | stackoverflow | DATA_SCIENCE | Pandas Merging 101 | Pandas Merging 101
How can I perform a (INNER| (LEFT|RIGHT|FULL) OUTER) JOIN with pandas?
How do I add NaNs for missing rows after a merge?
How do I get rid of NaNs after merging?
Can I merge on the index?
How do I merge multiple DataFrames?
Cross join with pandas
merge? join? concat? update? Who? What? Why?!
... and... | https://stackoverflow.com/questions/53645882/pandas-merging-101 | python, pandas, join, merge, concatenation | 1,544,078,475 |
se_61454850 | stackoverflow | DATA_SCIENCE | Failed to convert value(s) to axis units' - while creating a plot for a df | Failed to convert value(s) to axis units' - while creating a plot for a df
I am pretty new to python. I am trying to create a bar plot for data in 2 columns of a df.
product = df1['Product Name']
sales = df1['Total Sales']
df1.nlargest(5, 'Total Sales').plot.bar(xticks= df1['Product Name'])
gives me an error end... | https://stackoverflow.com/questions/61454850/failed-to-convert-values-to-axis-units-while-creating-a-plot-for-a-df | python, pandas, plot | 1,587,976,788 |
se_70074151 | stackoverflow | DATA_SCIENCE | Efficient way to insert similar rows (with only one column changing) right after each row in Numpy or Pandas | Efficient way to insert similar rows (with only one column changing) right after each row in Numpy or Pandas
Say I have a Pandas dataframe with 4 rows and 5 columns. For simplicity I will convert it into a Numpy array, which looks like this:
import numpy as np
A = np.array([[23, 43, 23, 110, 5],
[83, 32... | https://stackoverflow.com/questions/70074151/efficient-way-to-insert-similar-rows-with-only-one-column-changing-right-after | python, arrays, pandas, numpy, performance | 1,637,628,756 |
se_79681997 | stackoverflow | DATA_SCIENCE | Filter df where each row and item is unique | Filter df where each row and item is unique
I have a df where I would like to filter each row such that every row is unique via column values. For example, for my candy dataset below that is unfiltered:
CategoryA
SizeA
PriceA
CategoryB
SizeB
PriceB
CategoryC
SizeC
PriceC
M&M
Mini
2.00
Kisses
Reg
3.00
Skittles
M... | https://stackoverflow.com/questions/79681997/filter-df-where-each-row-and-item-is-unique | python, pandas, dataframe, filter | 1,751,029,566 |
se_79467071 | stackoverflow | DATA_SCIENCE | Adjacency matrix not square error from square dataframe with networkx | Adjacency matrix not square error from square dataframe with networkx
I have code that aims to generate a graph from an adjacency matrix from a table correlating workers with their manager. The source is a table with two columns (Worker, manager). It still works perfectly from a small mock data set, but fails unexpect... | https://stackoverflow.com/questions/79467071/adjacency-matrix-not-square-error-from-square-dataframe-with-networkx | python, pandas, dataframe, networkx, graph-theory | 1,740,497,238 |
se_79820376 | stackoverflow | DATA_SCIENCE | Export pandas.DataFrame.column.name attribute during pd.to_excel() export | Export pandas.DataFrame.column.name attribute during pd.to_excel() export
import numpy as np
import pandas as pd
a = np.array(["foo", "foo", "foo", "foo", "bar", "bar",
"bar", "bar", "foo", "foo", "foo"], dtype=object)
b = np.array(["one", "one", "one", "two", "one", "one",
"one", "two", "... | https://stackoverflow.com/questions/79820376/export-pandas-dataframe-column-name-attribute-during-pd-to-excel-export | python, excel, pandas, export-to-excel | 1,763,147,750 |
se_25140998 | stackoverflow | DATA_SCIENCE | Pandas : compute mean or std (standard deviation) over entire dataframe | Pandas : compute mean or std (standard deviation) over entire dataframe
Here is my problem, I have a dataframe like this :
Depr_1 Depr_2 Depr_3
S3 0 5 9
S2 4 11 8
S1 6 11 12
S5 0 4 11
S4 4 8 8
and I just want to calculate the mean over the full dataframe, as the following doesn't work :... | https://stackoverflow.com/questions/25140998/pandas-compute-mean-or-std-standard-deviation-over-entire-dataframe | python, pandas, dataframe, numpy, statistics | 1,407,248,063 |
se_77046121 | stackoverflow | DATA_SCIENCE | Python regular expressions to continuously extract multiple pieces of information from text data | Python regular expressions to continuously extract multiple pieces of information from text data
I have a dataset that has a col named plain_text in which we have a dumped log of conversations among several users in a group chat, the servers saves the information in a format like this:
a "timestamp" + "user name" + ":... | https://stackoverflow.com/questions/77046121/python-regular-expressions-to-continuously-extract-multiple-pieces-of-informatio | python, pandas, regex | 1,693,930,383 |
se_79874920 | stackoverflow | DATA_SCIENCE | Conversion from HuggingFace dataset to Pandas DF causing dropped 'string' columns | Conversion from HuggingFace dataset to Pandas DF causing dropped 'string' columns
I am attempting to convert a dataset loaded from HuggingFace into a pandas DF so I can process the data. However, despite having no null values (as many prior issues point to) , all non-numeric columns are being dropped in the da... | https://stackoverflow.com/questions/79874920/conversion-from-huggingface-dataset-to-pandas-df-causing-dropped-string-column | python, pandas, huggingface-datasets | 1,769,208,751 |
se_79836112 | stackoverflow | DATA_SCIENCE | Compare DataFrames by headers vs using merge | Compare DataFrames by headers vs using merge
I’m new to pandas and dataframes and am trying to understand two approaches:
Firstly, the setup:
import pandas as pd
# Example DataFrames
df1 = pd.DataFrame({
'id': [1, 2, 3],
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35]
})
df2 = pd.DataFrame({
... | https://stackoverflow.com/questions/79836112/compare-dataframes-by-headers-vs-using-merge | python, pandas, dataframe | 1,764,693,582 |
se_79844514 | stackoverflow | DATA_SCIENCE | Why is PintArray inaccessible? "AttributeError: module 'pint' has no attribute 'PintArray'." | Why is PintArray inaccessible? "AttributeError: module 'pint' has no attribute 'PintArray'."
I am fairly new to Python, and I must have missed something essential because I'm seeing broken functionality all over Pint. I'm starting to think it all comes down to PintArray is not available to m... | https://stackoverflow.com/questions/79844514/why-is-pintarray-inaccessible-attributeerror-module-pint-has-no-attribute | python, pandas, pint | 1,765,506,396 |
se_55954485 | stackoverflow | DATA_SCIENCE | Google Colaboratory : OSError: [Errno 5] Input/output error | Google Colaboratory : OSError: [Errno 5] Input/output error
I am using Google Colaboratory, and mounting Google Drive. When I access a csv file, it gets me the following error:
OSError: [Errno 5] Input/output error.
This did not happen before.
How can I access to the csv file as I used to?
I have tried this... | https://stackoverflow.com/questions/55954485/google-colaboratory-oserror-errno-5-input-output-error | python, python-3.x, pandas, google-colaboratory | 1,556,806,823 |
se_62560753 | stackoverflow | DATA_SCIENCE | Merge two dataframes based on partial startswith match | Merge two dataframes based on partial startswith match
I have two dataframe that I want to merge based on a partial match of start with (rows in df2.B that start with df1.A in the example below and the values of these columns are strings, which could be of any length).
I can do that the following way, but it is very s... | https://stackoverflow.com/questions/62560753/merge-two-dataframes-based-on-partial-startswith-match | python, pandas, string, join, merge | 1,593,019,620 |
se_79874335 | stackoverflow | DATA_SCIENCE | Creating new columns derived from existing column in pandas dataframe | Creating new columns derived from existing column in pandas dataframe
I work with Pandas, which is the project I'm currently working on.
This is the dataframe:
property_type place_with_parent_names region lat-lon area_m2 price_usd lat lon
0 apartment |Brasil|Alagoas|Maceió| Northeast -9.6443051,-35.7088... | https://stackoverflow.com/questions/79874335/creating-new-columns-derived-from-existing-column-in-pandas-dataframe | python, pandas, dataframe | 1,769,150,394 |
se_73268101 | stackoverflow | DATA_SCIENCE | Creating a ranking in Python from a given value by id | Creating a ranking in Python from a given value by id
I have this dataset:
dic = {'id':[1,1,1,1,1,2,2,2,2], 'sales': [100.00, 200.00, 300.00, 400.00, 500.00, 100.00, 200.00, 300.00, 400.00], 'year_month': [202201, 202202, 0, 202204, 202205, 202201, 202202, 202203, 0]}
df = pd.DataFrame(dic)
Output:
id sales ye... | https://stackoverflow.com/questions/73268101/creating-a-ranking-in-python-from-a-given-value-by-id | python, pandas, dataframe, rank | 1,659,881,109 |
se_79872672 | stackoverflow | DATA_SCIENCE | Using pivot with Pandas | Using pivot with Pandas
I have a Pandas dataframe which I need to both restructure, and modify slightly. I have a solution that works, but is naive and slow--I will post that below. Essentially, I have spatial data that I need to reorganise, as well as convert from UTM to lat/long, and do a small operation on some c... | https://stackoverflow.com/questions/79872672/using-pivot-with-pandas | python, pandas, dataframe, pivot | 1,768,985,974 |
se_77146492 | stackoverflow | DATA_SCIENCE | Pandas merge on inequality | Pandas merge on inequality
So I have been searching a pandas equivalent of this SQL query
SELECT * FROM table1
LEFT JOIN table2
ON table1.columnX>=table2.columnY
*Note that I am joining by an inequality condition, >=, not by matching columns.
But it seems panda's merge is only able to join by exact matches (like sele... | https://stackoverflow.com/questions/77146492/pandas-merge-on-inequality | python, sql, pandas, dataframe, join | 1,695,254,420 |
se_79873611 | stackoverflow | DATA_SCIENCE | Unbalanced diagonal matrix from a symmetric matrix | Unbalanced diagonal matrix from a symmetric matrix
I want to find the eigenvalues of a symmetric matrix.
When I do this in Python, I get an unbalanced diagonal matrix. The value of [0, 0] is much larger than the other eigenvalues.
Is it wrong?
How can I solve it?
import numpy as np
import pandas as pd
df1=pd.read_cs... | https://stackoverflow.com/questions/79873611/unbalanced-diagonal-matrix-from-a-symmetric-matrix | python, pandas, numpy, matrix, diagonal | 1,769,076,824 |
se_31528819 | stackoverflow | DATA_SCIENCE | Using Merge on a column and Index in Pandas | Using Merge on a column and Index in Pandas
I have two separate dataframes that share a project number. In type_df, the project number is the index. In time_df, the project number is a column. I would like to count the number of rows in type_df that have a Project Type of 2. I am trying to do this with pandas.merge().... | https://stackoverflow.com/questions/31528819/using-merge-on-a-column-and-index-in-pandas | python, python-2.7, pandas, merge | 1,437,441,444 |
se_18171739 | stackoverflow | DATA_SCIENCE | UnicodeDecodeError when reading CSV file in Pandas | UnicodeDecodeError when reading CSV file in Pandas
I'm running a program which is processing 30,000 similar files. A random number of them are stopping and producing this error...
File "C:\Importer\src\dfman\importer.py", line 26, in import_chr
data = pd.read_csv(filepath, names=fields)
File "C:\Python33\lib\s... | https://stackoverflow.com/questions/18171739/unicodedecodeerror-when-reading-csv-file-in-pandas | python, pandas, csv, dataframe, unicode | 1,376,222,785 |
se_79688933 | stackoverflow | DATA_SCIENCE | How can I create a column that is the result of replacing values in two or more other columns? | How can I create a column that is the result of replacing values in two or more other columns?
Consider the dataframe df:
import pandas as pd
df = pd.DataFrame({'Event1': ['Music', 'Something else 1', 'Theatre', 'Comedy'],
'Event2': ['Something else 2', 'Ballet', 'Something else 3', 'Something else 4']... | https://stackoverflow.com/questions/79688933/how-can-i-create-a-column-that-is-the-result-of-replacing-values-in-two-or-more | python, pandas, dataframe | 1,751,549,667 |
se_79688445 | stackoverflow | DATA_SCIENCE | Removing rows from pandas if they match multiple column of other row of same dataframe | Removing rows from pandas if they match multiple column of other row of same dataframe
I am trying to remove all the rows in which value of Total, first and second is equal to the row which is marked by label M within a netting DataFrame:
import pandas as pd
data = {
'netting': ['01', '01', '01', '01', '01', '02'... | https://stackoverflow.com/questions/79688445/removing-rows-from-pandas-if-they-match-multiple-column-of-other-row-of-same-dat | python, pandas, dataframe | 1,751,527,527 |
se_79866222 | stackoverflow | DATA_SCIENCE | Visualizing categorical features with severe Class Imbalance for ML: Absolute Counts vs Normalized Percentages? | Visualizing categorical features with severe Class Imbalance for ML: Absolute Counts vs Normalized Percentages?
I am performing Exploratory Data Analysis (EDA) on a medical dataset (Primary Biliary Cirrhosis) to select features for a multiclass classification model. My target variable is Stage (1, 2, 3, 4).
The Proble... | https://stackoverflow.com/questions/79866222/visualizing-categorical-features-with-severe-class-imbalance-for-ml-absolute-co | python, pandas, matplotlib, seaborn, visualization | 1,768,228,830 |
se_79870504 | stackoverflow | DATA_SCIENCE | Pandas rename() not working on MultiIndex columns with tuples | Pandas rename() not working on MultiIndex columns with tuples
I am working with a pandas DataFrame that has a MultiIndex (two levels) for columns. I am trying to rename specific columns using a dictionary of tuples, but the column names remain unchanged.
import pandas as pd
cols = pd.MultiIndex.from_tuples([
('Gr... | https://stackoverflow.com/questions/79870504/pandas-rename-not-working-on-multiindex-columns-with-tuples | python, pandas, dataframe, multi-index | 1,768,737,763 |
se_79870853 | stackoverflow | DATA_SCIENCE | ChainedAssignmentError when adding a conditional to a pandas dataframe | ChainedAssignmentError when adding a conditional to a pandas dataframe
I keep getting a ChainedAssignmentError when adding a conditional to my code. In this basic example I am checking to see if column "one" is an "e" and if so then set the "Match" column to 1.
The df is getting updated correctly, I am just getting t... | https://stackoverflow.com/questions/79870853/chainedassignmenterror-when-adding-a-conditional-to-a-pandas-dataframe | python, pandas, dataframe | 1,768,790,689 |
se_43214204 | stackoverflow | DATA_SCIENCE | How do I tell if a column in a pandas dataframe is of type datetime? How do I tell if a column is numerical? | How do I tell if a column in a pandas dataframe is of type datetime? How do I tell if a column is numerical?
I am trying to filter the columns in a pandas dataframe based on whether they are of type date or not. I can figure out which ones are, but then would have to parse that output or manually select columns. I w... | https://stackoverflow.com/questions/43214204/how-do-i-tell-if-a-column-in-a-pandas-dataframe-is-of-type-datetime-how-do-i-te | python, pandas, numpy, dataframe | 1,491,328,075 |
se_36222928 | stackoverflow | DATA_SCIENCE | Pandas OHLC aggregation on OHLC data | Pandas OHLC aggregation on OHLC data
I understand that OHLC re-sampling of time series data in Pandas, using one column of data, will work perfectly, for example on the following dataframe:
>>df
ctime openbid
1443654000 1.11700
1443654060 1.11700
...
df['ctime'] = pd.to_datetime(df['ctime'], unit='s')
df ... | https://stackoverflow.com/questions/36222928/pandas-ohlc-aggregation-on-ohlc-data | python, python-2.7, pandas, dataframe, resampling | 1,458,919,937 |
se_12589481 | stackoverflow | DATA_SCIENCE | Multiple aggregations of the same column using pandas GroupBy.agg() | Multiple aggregations of the same column using pandas GroupBy.agg()
Is there a pandas built-in way to apply two different aggregating functions f1, f2 to the same column df["returns"], without having to call agg() multiple times?
Example dataframe:
import pandas as pd
import datetime as dt
import numpy as np
pd.np.ra... | https://stackoverflow.com/questions/12589481/multiple-aggregations-of-the-same-column-using-pandas-groupby-agg | python, pandas, dataframe, group-by, aggregate | 1,348,599,926 |
se_64354584 | stackoverflow | DATA_SCIENCE | Python: Using Multiple Variables in WRDS CRSP Query | Python: Using Multiple Variables in WRDS CRSP Query
I would like to use multiple variables within a WRDS SQL query.
I am seeking to search the CRSP database by PERMNO and Date, return the stock price for a particular company on a particular day. I have a large DataFrame from which these variables will be retrieved and... | https://stackoverflow.com/questions/64354584/python-using-multiple-variables-in-wrds-crsp-query | python, sql, pandas, wrds | 1,602,682,753 |
se_65081257 | stackoverflow | DATA_SCIENCE | How can I remove a substring from a given String using Pandas | How can I remove a substring from a given String using Pandas
Recently I started to analyse a data frame and I want to remove all the substrings that don't contain
('Aparelho Celular','Internet (Serviços e Produtos)','Serviços Telefônicos Diversos','Telefonia Celular','Telefonia Comunitária ( PABX, DDR, Etc. )','Telef... | https://stackoverflow.com/questions/65081257/how-can-i-remove-a-substring-from-a-given-string-using-pandas | python, pandas, string, substring, contains | 1,606,770,860 |
se_79697772 | stackoverflow | DATA_SCIENCE | How do I compute group means in a pandas DataFrame when grouped by ranking? | How do I compute group means in a pandas DataFrame when grouped by ranking?
What I'd like to do is create a DataFrame with dates as indices, ranks as columns, and values pulled from scores. Since the ranking method guarantees uniqueness, I suppose I can melt/dropna/pivot to get what I want.
This approach feels kind of... | https://stackoverflow.com/questions/79697772/how-do-i-compute-group-means-in-a-pandas-dataframe-when-grouped-by-ranking | python, pandas, dataframe | 1,752,201,572 |
se_56684159 | stackoverflow | DATA_SCIENCE | clustering/grouping names with little or no anomalies into clusters in pandas | clustering/grouping names with little or no anomalies into clusters in pandas
I have a dataframe with names field as:
print(df)
names
--------------------------------
0 U.S.A.
1 United States of America
2 USA
4 US America
5 Kenyan Footbal League
6 Kenyan Football League
7 Kenya... | https://stackoverflow.com/questions/56684159/clustering-grouping-names-with-little-or-no-anomalies-into-clusters-in-pandas | python, pandas | 1,561,026,960 |
se_79821379 | stackoverflow | DATA_SCIENCE | Slow database table insert (upload) with Pandas to_sql. What is the fastest method? | Slow database table insert (upload) with Pandas to_sql. What is the fastest method?
End Objective
Download some data from the internet (about 5 GB in size)
Possibly convert some strings/datetimes
Upload to Postgres database
I have written some code which uploads some data to a Postgres database. "Upload" here me... | https://stackoverflow.com/questions/79821379/slow-database-table-insert-upload-with-pandas-to-sql-what-is-the-fastest-meth | python, pandas, postgresql, sqlalchemy, psycopg2 | 1,763,286,853 |
se_77375238 | stackoverflow | DATA_SCIENCE | TypeError: unhashable type: 'Series' - can't work out how to pass a one column df as a non-series object if even possible? | TypeError: unhashable type: 'Series' - can't work out how to pass a one column df as a non-series object if even possible?
So I have a dataframe and have written a function to add values in a new column dependent on a set of conditions.
there are two dataframes used for the code
the first being the merged_... | https://stackoverflow.com/questions/77375238/typeerror-unhashable-type-series-cant-work-out-how-to-pass-a-one-column-d | python, pandas, typeerror, series | 1,698,419,053 |
se_79867770 | stackoverflow | DATA_SCIENCE | SettingWithCopyWarning: DataFrame.iterrows using .loc - pandas views vs copy | SettingWithCopyWarning: DataFrame.iterrows using .loc - pandas views vs copy
(Similar questions with this warning always wind down to the same thing described in the docs; use .loc however I'm already doing that and the line that should be in the error to use .loc is hence suspiciously empty)
python version: 3.13.9
pa... | https://stackoverflow.com/questions/79867770/settingwithcopywarning-dataframe-iterrows-using-loc-pandas-views-vs-copy | python, pandas, dataframe | 1,768,396,258 |
se_77663162 | stackoverflow | DATA_SCIENCE | How to install Pandas when PIP fails due to metadata generation error? | How to install Pandas when PIP fails due to metadata generation error?
I am trying to install Pandas in a standalone installation of Python 3.12 and I keep getting an error saying "metadata-generation-failed." I am able to install Pandas in my Anaconda installation but I need this one to be totally separate because I... | https://stackoverflow.com/questions/77663162/how-to-install-pandas-when-pip-fails-due-to-metadata-generation-error | python, pandas, pip | 1,702,589,443 |
se_51827134 | stackoverflow | DATA_SCIENCE | Comparison between datetime and datetime64[ns] in pandas | Comparison between datetime and datetime64[ns] in pandas
I'm writing a program that checks an excel file and if today's date is in the excel file's date column, I parse it
I'm using:
cur_date = datetime.today()
for today's date. I'm checking if today is in the column with:
bool_val = cur_date in df['date'] #evalu... | https://stackoverflow.com/questions/51827134/comparison-between-datetime-and-datetime64ns-in-pandas | python, pandas, datetime, datetime64 | 1,534,179,158 |
se_79821337 | stackoverflow | DATA_SCIENCE | Not displaying DataFrame's name in Data Wrangler extension of VSCode, displaying "Data grid" | Not displaying DataFrame's name in Data Wrangler extension of VSCode, displaying "Data grid"
It is a while that I am using Data Wrangler extension in VS Code; it is very useful for analyzing datasets and filtering some columns to see the features. When I opened a dataframe in it, it used to show its name... | https://stackoverflow.com/questions/79821337/not-displaying-dataframes-name-in-data-wrangler-extension-of-vscode-displaying | pandas, dataframe, visual-studio-code, python-polars, data-wrangling | 1,763,280,173 |
se_79867312 | stackoverflow | DATA_SCIENCE | How to run multiple statistical distributions across all possible combinations of values in a column & assign the minimum to a new column? | How to run multiple statistical distributions across all possible combinations of values in a column & assign the minimum to a new column?
I am attempting to construct bins for a large dataset, such that the subset of data within each bin conforms well to an exponential distribution. The basic structure of the dat... | https://stackoverflow.com/questions/79867312/how-to-run-multiple-statistical-distributions-across-all-possible-combinations-o | python, pandas, dataframe, scipy, empirical-distribution | 1,768,336,406 |
se_79863218 | stackoverflow | DATA_SCIENCE | How to run Pyspark UDF separately over dataframe groups | How to run Pyspark UDF separately over dataframe groups
Grouping a Pyspark dataframe, applying time series analysis UDF to each group
SOLVED See below
I have a Pyspark process which takes a time-series dataframe for a site and calculates/adds features for anomaly detection. Window functions are used to compare leadi... | https://stackoverflow.com/questions/79863218/how-to-run-pyspark-udf-separately-over-dataframe-groups | python, pandas, dataframe, apache-spark, pyspark | 1,767,869,578 |
se_79751529 | stackoverflow | DATA_SCIENCE | splitting a data frame in a way like dealing cards | splitting a data frame in a way like dealing cards
I have a data frame of students sorted by grade that I want to split into 3 data frames, such that an even number of students per grade is in each of the 3 groups. I thought of it like dealing cards, you know passing one card to each of 3 people in turns, but would li... | https://stackoverflow.com/questions/79751529/splitting-a-data-frame-in-a-way-like-dealing-cards | python, pandas, dataframe | 1,756,604,833 |
se_79755156 | stackoverflow | DATA_SCIENCE | Using multiple masks based on ID | Using multiple masks based on ID
I have a dataframe df that consists of two columns: an id, and a date. The id is a number from 1-3 & is not unique; the date is a datetime object.
id, date
1, 2020-5-11
1, 2019-3-2
2, 2018-7-29
3, 2017-2-21
3, 2017-2-23
There also exists a corresponding list which contains the id with... | https://stackoverflow.com/questions/79755156/using-multiple-masks-based-on-id | python, pandas, dataframe | 1,756,941,497 |
se_79826123 | stackoverflow | DATA_SCIENCE | How to detect and remove inconsistent timestamps in a time-series dataset | How to detect and remove inconsistent timestamps in a time-series dataset
I’m working with a time-series dataset where each record is supposed to be logged at 1-minute intervals.
However, due to data quality issues, the dataset contains:
duplicated timestamps
missing timestamps
irregular gaps (e.g., jumps of 5–10 m... | https://stackoverflow.com/questions/79826123/how-to-detect-and-remove-inconsistent-timestamps-in-a-time-series-dataset | python, pandas, time-series, data-cleaning | 1,763,698,056 |
se_60154404 | stackoverflow | DATA_SCIENCE | Is there the equivalent of to_markdown to read data? | Is there the equivalent of to_markdown to read data?
With pandas 1.0.0 the use of .to_markdown() to show the content of a dataframe in this forum in markdown is going to proliferate. Is there a convenient way to load the data back into a dataframe? Maybe an option to .from_clipboard(markdown=True)? | https://stackoverflow.com/questions/60154404/is-there-the-equivalent-of-to-markdown-to-read-data | python, pandas | 1,581,351,772 |
se_42891466 | stackoverflow | DATA_SCIENCE | Select a List Slices of a Pandas Multiindex/Multicolumn DataFrame | Select a List Slices of a Pandas Multiindex/Multicolumn DataFrame
Say I have the following multicolumn Pandas DataFrame:
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', ],
['one', 'two', 'one', 'two', 'one', 'two', ]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['firs... | https://stackoverflow.com/questions/42891466/select-a-list-slices-of-a-pandas-multiindex-multicolumn-dataframe | python, pandas, dataframe, indexing | 1,489,953,178 |
se_67933621 | stackoverflow | DATA_SCIENCE | Element wise max comparison of two pandas dataframes | Element wise max comparison of two pandas dataframes
I have two dataframes df1 and df2.
df1 =
A1 B1 C1
0 1 2 0
1 4 2 1
2 2 1 5
df2 =
A2 B2 C2
0 2 1 5
1 1 3 2
2 2 2 4
And I wish to create a third dataframe which has the max values between the corresponding elements of the two dat... | https://stackoverflow.com/questions/67933621/element-wise-max-comparison-of-two-pandas-dataframes | python, pandas, dataframe | 1,623,399,766 |
se_79756625 | stackoverflow | DATA_SCIENCE | Using a column value to find the Column header name in Pandas | Using a column value to find the Column header name in Pandas
I have a pandas dataframe. I am trying to use the values in a given column (year) to find the relevant header name and add it to a new column (year_name). For example, if the dataframe looks like this (where the itemName column is the index):
itemName
20... | https://stackoverflow.com/questions/79756625/using-a-column-value-to-find-the-column-header-name-in-pandas | python, pandas, dataframe | 1,757,065,577 |
se_79865535 | stackoverflow | DATA_SCIENCE | Why pandas module is not found even though, it is already installed? | Why pandas module is not found even though, it is already installed?
I want to run a dummy code on python to test the pandas library. Even though there is pandas package in the pip list of the Python virtual environment, it still shows the error that says
"C:\Users\Youseng Taiheng\AppData\Local\Microsoft\WindowsApps\p... | https://stackoverflow.com/questions/79865535/why-pandas-module-is-not-found-even-though-it-is-already-installed | python, pandas | 1,768,141,669 |
se_66021881 | stackoverflow | DATA_SCIENCE | How to detect gaps between integer sequence in pandas? | How to detect gaps between integer sequence in pandas?
So I am trying to figure out a way to determine if there are gaps between invoice numbers in a data set:
Here's an example of the table/series
Invoice #
1001
1002
1003
1005
1010
1011
1012
So I have gaps between 1003 and 1005, 1005 and 1010
I would like to evaluat... | https://stackoverflow.com/questions/66021881/how-to-detect-gaps-between-integer-sequence-in-pandas | python, pandas | 1,612,330,715 |
se_21828398 | stackoverflow | DATA_SCIENCE | What is the difference between pandas agg and apply functions on groupby? | What is the difference between pandas agg and apply functions on groupby?
I can't figure out the difference between Pandas .aggregate and .apply functions.
Take the following as an example: I load a dataset, do a groupby, define a simple function,
and either user .agg or .apply.
As you may see, the printing statement ... | https://stackoverflow.com/questions/21828398/what-is-the-difference-between-pandas-agg-and-apply-functions-on-groupby | python, pandas, dataframe, group-by | 1,392,638,048 |
se_72276196 | stackoverflow | DATA_SCIENCE | Pandas Openpyxl error "<class 'openpyxl.styles.fills.Fill'> | Pandas Openpyxl error "<class 'openpyxl.styles.fills.Fill'>
I'm getting this error while loading a downloaded .xlsx file from a website
TypeError: expected "<class 'openpyxl.styles.fills.Fill'>
I saw some solutions here, but they are telling me to resave the file manually, which is not an option fo... | https://stackoverflow.com/questions/72276196/pandas-openpyxl-error-class-openpyxl-styles-fills-fill | python, pandas, openpyxl, xlsx | 1,652,799,112 |
se_68214567 | stackoverflow | DATA_SCIENCE | Speed up distance calculations in Python | Speed up distance calculations in Python
How can I speed up the execution of this line:
from geopy import distance
...
df['Km'] = df.apply((lambda row: distance.distance(row['coord_1'],row['coord_2']).km),axis=1)
where coord_1 and coord_2 are two large sets of coordinates?
distance.distance() is a geopy function. | https://stackoverflow.com/questions/68214567/speed-up-distance-calculations-in-python | python, pandas, geopy | 1,625,160,554 |
se_79434061 | stackoverflow | DATA_SCIENCE | Numpy array converts to truncated string when saving Pandas df to Dask | Numpy array converts to truncated string when saving Pandas df to Dask
I have a large Pandas dataset, each row of it's column "Samples" is a very long numpy array of int16 integers ([-14, -15, -16, -17, -18, -19, -20, -21, -22, ...). Due to my local machine lack of memory I'd like to use Dask to convert this pandas df... | https://stackoverflow.com/questions/79434061/numpy-array-converts-to-truncated-string-when-saving-pandas-df-to-dask | python, pandas, dataframe, numpy, dask | 1,739,384,343 |
se_79863627 | stackoverflow | DATA_SCIENCE | How should I be using Dask .compute() to perform relatively simple operations | How should I be using Dask .compute() to perform relatively simple operations
I'm trying to use Dask to do some relatively simple computations and operations that I was doing with Pandas but on a larger dataset. I have approximately 1500 .csv files that range in size from 1KB to 26MB. About 4 GB of data total.
Example... | https://stackoverflow.com/questions/79863627/how-should-i-be-using-dask-compute-to-perform-relatively-simple-operations | python, pandas, dataframe, dask | 1,767,896,011 |
se_52135459 | stackoverflow | DATA_SCIENCE | pandas read_csv remove blank rows | pandas read_csv remove blank rows
I am reading in a CSV file as a DataFrame while defining each column's data type. This code gives an error if the CSV file has a blank row in it. How do I read the CSV without blank rows?
dtype = {'material_id': object, 'location_id' : object, 'time_period_id' : int, 'demand' : int,... | https://stackoverflow.com/questions/52135459/pandas-read-csv-remove-blank-rows | python, pandas, dataframe, csv, blank-line | 1,535,878,953 |
se_79862797 | stackoverflow | DATA_SCIENCE | How can I convert .sto to .csv with pandas? | How can I convert .sto to .csv with pandas?
I have a .sto file from OpenSim that I would like to convert to a .csv file for data processing. According to the website, the header for these files looks like this:
Coordinates
nRows=153
nColumns=24
endheader
How can I convert this file to a standard .csv file using panda... | https://stackoverflow.com/questions/79862797/how-can-i-convert-sto-to-csv-with-pandas | python, pandas, dataframe | 1,767,823,721 |
se_79627856 | stackoverflow | DATA_SCIENCE | Find value in Dataframe column based on next rows | Find value in Dataframe column based on next rows
I have a Dataframe with 2 columns.
I want to compare the value of first column with some threshold for 5 iterations and if it exceeds that value, check the corresponding value of the another column
DF:
In the below example I need to check at what value of 'Inst' where ... | https://stackoverflow.com/questions/79627856/find-value-in-dataframe-column-based-on-next-rows | python, pandas, dataframe | 1,747,603,301 |
se_79731063 | stackoverflow | DATA_SCIENCE | How to find values appear the most | How to find values appear the most
I have a dataframe that has the number 6 in each row. Which will be my main number I would like to use
to find values that appear most often with the number 6 that has more than 2 of the same values. Here is my dataframe below,
import pandas as pd
df = pd.DataFrame([[1,2,4,5,6,8],
... | https://stackoverflow.com/questions/79731063/how-to-find-values-appear-the-most | python, arrays, pandas, dataframe, jupyter-notebook | 1,754,812,163 |
se_79803382 | stackoverflow | DATA_SCIENCE | Transform DataFrame containing ID pairs into a list of sets | Transform DataFrame containing ID pairs into a list of sets
I have a Pandas DataFrame with the following structure
left_id
right_id
a
b
c
a
x
y
I need to transform this into a list of sets, like
[
{'a', 'b', 'c'},
{'x', 'y'}
]
the first two rows should be combined as a single set, because row 1 has ... | https://stackoverflow.com/questions/79803382/transform-dataframe-containing-id-pairs-into-a-list-of-sets | python, pandas, dataframe, graph-theory | 1,761,703,052 |
se_57847495 | stackoverflow | DATA_SCIENCE | How to fix function with for loop not iterating. Recommendation system in Python | How to fix function with for loop not iterating. Recommendation system in Python
I'm working on a recommendation system with the python library Surprise.
I'm trying to make a function that iterates over the full list of movies and predicts their ranking value against a user id which is defined in when I call the funct... | https://stackoverflow.com/questions/57847495/how-to-fix-function-with-for-loop-not-iterating-recommendation-system-in-python | python, pandas, machine-learning, data-science, recommendation-engine | 1,567,999,344 |
se_30392099 | stackoverflow | DATA_SCIENCE | How to find the line that is generating a Pandas SettingWithCopyWarning? | How to find the line that is generating a Pandas SettingWithCopyWarning?
I have a large block of code that is, at some point somewhere, generating a setting with copy warning in pandas (this problem).
I know how to fix the problem, but I can't find what line number it is! Is there a way to back out the line number (a... | https://stackoverflow.com/questions/30392099/how-to-find-the-line-that-is-generating-a-pandas-settingwithcopywarning | python, pandas, warnings, chained-assignment | 1,432,284,030 |
se_79859541 | stackoverflow | DATA_SCIENCE | Reading in XML data in python | Reading in XML data in python
I am looking for some assistance with how to convert the below XML data into a dataframe.
I have managed to write a working code in R (XML package, code is messy) but then I realized it might even be easier in python. I have generated some fake data from my original dataset and played aro... | https://stackoverflow.com/questions/79859541/reading-in-xml-data-in-python | python, pandas, xml, dataframe | 1,767,417,786 |
se_57776015 | stackoverflow | DATA_SCIENCE | Error while reading csv file (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape | Error while reading csv file (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
I am trying to read a csv file in python(jupyter notebook) but getting an error. Below is the code:
import sys
import pandas as pd
import scipy
import numpy as np
import seabo... | https://stackoverflow.com/questions/57776015/error-while-reading-csv-file-unicode-error-unicodeescape-codec-cant-decode | python, pandas, csv, unicode, syntax-error | 1,567,530,206 |
se_79858187 | stackoverflow | DATA_SCIENCE | Pandas rolling window over a time period if some data might be missing within groups | Pandas rolling window over a time period if some data might be missing within groups
I have a dataset with a column of groups, dates, day of the week and some data columns. For each date in each group, I want to work out the same day average from the last 3 weeks (l3w - not including that week's data point). I've been... | https://stackoverflow.com/questions/79858187/pandas-rolling-window-over-a-time-period-if-some-data-might-be-missing-within-gr | python, pandas, dataframe, rolling-computation | 1,767,188,780 |
se_74239579 | stackoverflow | DATA_SCIENCE | Convert Pandas DataFrame from Wide to Long Format | Convert Pandas DataFrame from Wide to Long Format
Given this DataFrame:
person action_1 time_1 action_2 time_2
0 Tom run 2022-01-26 run 2027-01-26
1 Max stop 2020-11-16 run 2022-04-26
2 Bob run 2021-10-03 stop 2022-01-26
3 Ben run 2020-03-11 stop 201... | https://stackoverflow.com/questions/74239579/convert-pandas-dataframe-from-wide-to-long-format | python, pandas | 1,666,981,960 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.