new pandas data frame fill from continous scrape, column names known - pandas

I scraped data like :
for row in stat_table.find_all("tr"):
for cell in row.find_all('td'):
print(cell.text)
the output looks like this :
1
2019-10-24
31-206
MIL
#
HOU
W (+6)
0
16:35
1
3
.333
0
2
etc.
I created a columns variable:
columns = ['G','Date', 'Age','Team',"at","Opp",'Score','Starter','MP','FG','FGA','FG%','3P','3PA',"3P%",
'FT','FTA','FT%','ORB','DRB','TRB','AST','STL','BLK','TOV','PF','PTS',"GmSC","+/-"]
I would like to read in the output and create a new pandas data frame with those columns. Any idea how I can read that in?

The way I would do it is split your text so that it becomes a list in your for loop and append it to a list of lists(body):
header = [**your column names**]
body = [] # list of lists
for row in stat_table.find_all("tr"):
for cell in row.find_all('td'):
body.append(cell.text.split(' ')) # splitting on space
Then, make sure header and the lists within body are of equal length and:
df = pd.DataFrame(data=body, columns=header)

Related

create n dataframes in a for loop with an extra column with a specific number in it

Hi all I have a dataframe like that shown in the picture:
I am trying to create 2 different dataframes with the same "hour", "minute", "value" (and value.1 respectively) columns, by adding also column with number 0 and 1 respectively). I would like to do it in a for loop as I want to create n dataframe (not just 2 shown here).
I tried something like this but it's not working (error: KeyError: "['value.i'] not in index"):
for i in range(1):
series[i] = df_new[['hour', 'minute', 'value.i']]
series[i].insert(0, 'number', 'i')
can you help me ?
thannks
from what I have understood you want to make value.i to show value.1 or value.2
for i in range(1):
# f is for the format so can interpret i as variable only
series[i] = df_new[['hour','minute',f'value.{i}']]

How to make dataframe from different parts of an Excel sheet given specific keywords?

I have one Excel file where multiple tables are placed in same sheet. My requirement is to read certain tables based on keyword. I have read tables using skip rows and nrows method, which is working as of now, but in future it won't work due to dynamic table length.
Is there any other workaround apart from skip rows & nrows method to read table as shown in picture?
I want to read data1 as one table & data2 as another table. Out of which in particular I want columns "RR","FF" & "WW" as two different data frames.
Appreciate if some one can help or guide to do this.
Method I have tried:
all_files=glob.glob(INPATH+"*sample*")
df1 = pd.read_excel(all_files[0],skiprows=11,nrows= 3)
df2 = pd.read_excel(all_files[0],skiprows=23,nrows= 3)
This works fine, the only problem is table length will vary every time.
With an Excel file identical to the one of your image, here is one way to do it:
import pandas as pd
df = pd.read_excel("file.xlsx").dropna(how="all").reset_index(drop=True)
# Setup
targets = ["Data1", "Data2"]
indices = [df.loc[df["Unnamed: 0"] == target].index.values[0] for target in targets]
dfs = []
for i in range(len(indices)):
# Slice df starting from first indice to second one
try:
data = df.loc[indices[i] : indices[i + 1] - 1, :]
except IndexError:
data = df.loc[indices[i] :, :]
# For one slice, get only values where row starts with 'rr'
r_idx = data.loc[df["Unnamed: 0"] == "rr"].index.values[0]
data = data.loc[r_idx:, :].reset_index(drop=True).dropna(how="all", axis=1)
# Cleanup
data.columns = data.iloc[0]
data.columns.name = ""
dfs.append(data.loc[1:, :].iloc[:, 0:3])
And so:
for item in dfs:
print(item)
# Output
rr ff ww
1 car1 1000000 sellout
2 car2 1500000 to be sold
3 car3 1300000 sellout
rr ff ww
1 car1 1000000 sellout
2 car2 1500000 to be sold
3 car3 1300000 sellout

Looping through csv files and creating a DataFrame that summarize info by locating text in columns

The script that I have so far (see below) does that:
1: looping through a folder and convert .xlsx in .csv.
2: looping through the csv list and populate a dataframe with data extracted from each one of them.
3: append a new column that is populated with the filename.
import pandas as pd
import numpy as np
cwd = os.path.abspath('')
files = os.listdir(cwd)
df = pd.DataFrame()
for file in files:
if file.endswith('.csv'):
df1 = pd.read_csv(file, header = None,encoding='latin1')
df1 = df1.assign(Filename= os.path.basename(file))
df = df1.append(df,ignore_index=False)
What I want to do now is while still in the 'file' loop;
The 1st column (will be named Pozo): where dataframe column number 1 contains 'Pozo:', extract the value from the same row but column 3.
To populate the second column a search for text 'MD' has to be done inside the first column (column 0) of the dataframe and has to be populated with all the values below the row where text is found inside this same column.
The outcome looks like the joined picture now. The image show what I want to extract from it (in red in the searched text, and in yellow the values to extract)
What I want is to take the dataframe shown in the image and 'clean it' like so:
Pozo
MD
Filename
First
NWI-RC-176 calidad
0.00
NWIRC-176-22_SPT_Offline_OutRun_QC.csv
Second
NWI-RC-176 calidad
5.00
NWIRC-176-22_SPT_Offline_OutRun_QC.csv
[...]
enter image description here
Thanks for helping me !!
see if this helps
Choose the value from column 3, where column 1 has 'POZO', and assign to variable
var_pozo = df.at[df[df['1'] == 'Pozo:'].index[0],'3']
var_pozo
to choose all values below where MD Is found, we first find that row
then choose all rows from below that index and assign to another DF (md_df)
then find a first null value and exclude that from the md_df
# all rows from DF where MD is found are selected and assigned to md_df
md_df = df[df[df['0'] == 'MD'].index[0]:].reset_index()
# find the first null value and select all rows above the null
md_df = md_df[:md_df[md_df['0'].isnull()].index[0]]['0'].reset_index()
md_df
We add the required columns in md_df
md_df['Pozo'] = var_pozo
md_df['filename'] = 'your filename' # replace this with your file variable
md_df.drop(columns='index', inplace=True)
md_df.rename(columns={'0': 'MD'}, inplace=True)
md_df
md_df becomes your extracted df
here is the output with the test csv I created
MD Pozo filename
0 (m) NWI-RC-176 calidad your filename
1 0 NWI-RC-176 calidad your filename
2 5 NWI-RC-176 calidad your filename
3 10 NWI-RC-176 calidad your filename
4 15 NWI-RC-176 calidad your filename

Create Column in Dataframe Passing Values from Columns for .iloc in Different Dataframe

I am looking to convert some Excel spreadsheets into a different format and so I have a Dataframe where I have converted the cell position location into integer locations which can be used for .iloc.
Example:
df
Col Row
1 2
5 6
9 6
And so on. The other Dataframe is just a parsed Excel sheet loaded using pd.ExcelFile, so it is returning the the info in the original cell locations without issue (I checked it by exporting a .csv).
I want to create a new column ['Info'] by passing the values for each row of the original Dataframe into a .iloc of the second but my code returns no results.
df['Info'] = df.apply(excel_sheet.iloc[df['Row'], df['Col']])
How do I pass the info from each row to apply into a different Dataframe and return the "cell" info from the Excel sheet?
Since these are positional indexing, you can try numpy:
df['Info'] = excel_sheet.to_numpy()[df['Row'], df['Col']]

Pandas: Creating empty dataframe in for loop, appending

I would like to create a ((25520*43),3) pandas Dataframe in a for loop.
I created the dataframe like:
lst=['Region', 'GeneID', 'DistanceValue']
df=pd.DataFrame(index=lst).T
And now I want to fill 'Region', 43 times with 25520 values. Also GeneID and DistanceValue.
This is my for loop for that:
for i in range(43):
df.DistanceValue = np.sort(distance[i,:])
df.Region = np.ones(25520) * i
args = np.argsort(distance[i,:])
df.GeneID = ids[int(args[i])]
But than my df exists just of (25520, 3). So I just have the last iteration for 43 filled in.
How can I concat all iteration one to 43 in my df?
I can't reproduce your example but there are couple of corrections you can make:
lst=['Region', 'GeneID', 'DistanceValue']
df=pd.DataFrame(index=lst).T
region = []
for i in range(43):
region.append(np.ones(25520))
flat_list = [item for sublist in region for item in sublist]
df.Region = flat_list
First create a new list outside loop and then append values within loop in this list.
The flat_list will consolidate all 43 lists to one and then you can map it to the DataFrame. It is always easier to fill DataFrame values outside of loop.
Similarly you can update all 3 columns.