How to access nested tables in hdf5 with pandas - pandas

I want to retrieve a table from an HDF5 file using pandas.
Following several references I found, I have tried to open the file using:
df = pd.read_hdf('data/test.h5', g_name),
where g_name is the path to the object I want to retrieve, i.e. the table TAB1, for instance, MAIN/Basic/Tables/TAB1.
g_name is retrieved as follows:
def get_all(name):
if 'TAB1' in name:
return name
with h5py.File('data/test.h5') as f:
g_name = f.visit(get_all)
print(g_name)
group = f[g_name]
print(type(group))
I have also tried retrieving the object itself, as seen in the above code snippet, but the object type is
How would I convert this to something I can read as a data frame in pandas?
For the first case, I get the following error:
"cannot create a storer if the object is not existing "
I do not understand why it cannot find the object, if the path is the same as retrieved during the search.

I found the following solution:
hf = h5py.File('data/test.h5')
data = hf.get('MAIN/Basic/Tables/TAB1')
result = data[()]
# This last step just converts the table into a pandas df
df = pd.DataFrame(result)

Related

Synapse Analytics Pyspark: TypeError: list object is not callable

I need to create a new dataframe in Synapse Analytics using column names from another dataframe. The new dataframe will have just one column (column header:col_name and the columns names from the other dataframe are the cell values. Here's my code:
df1= df.columns
colName =[]
for e in df1:
list1 = [e]
colName.append(list1)
col=['col_name']
df2=spark.createDataFrame(colName,col)
display(df2)
The output table created look like below:
With the output dataframe, i can do the following count, display or withColumn command.
df2.count()
df2=df2.withColumn('index',lit(1))
But when i start doing the below filter command, i ended up with 'list' object not callable error message.
display(df2.filter(col('col_name')=='dob'))
I am just wondering if anyone know what I am missing and how I can solve this.At the end i'd like to add a conditional column based on the value in the col_name column.
The problem is that you have two objects called col.
You did this :
col=['col_name']
therefore, when you do this :
display(df2.filter(col('col_name')=='dob'))
you do not call pyspark.sql.functions.col anymore but ['col_name'], hence, TypeError: list object is not callable.
Simply replace here :
# display(df2.filter(col('col_name')=='dob'))
from pyspark.sql import functions as F
display(df2.filter(F.col('col_name')=='dob'))

Groupby for loop to export separate files by group

I'm trying to group dataframe by 'state' column, run calculations on each group, and export to excel with each file being named for the respective state group. If I print the groups, they look correct, but I can't get the files to show the group data correctly. Currently it creates separate files with correct file names, but each file has the complete data set ignoring the groups.
Source data here: https://docs.google.com/spreadsheets/d/1-wdmIz_-AILcBqzvpwAFGZfXqhq8oDRrYFVVdkjZ10o/edit?usp=sharing
df = pd.read_excel("ranker_test.xlsx", sheet_name='DATA')
grouped = df.groupby('state')
for group in grouped:
df.to_excel('test files/ranking_{}.xlsx'.format(group[0]), index=False)
^This creates the correctly named files, but each file has all states.
df = pd.read_excel("ranker_test.xlsx", sheet_name='DATA')
grouped = df.groupby('state')
for group in grouped:
group.to_frame().to_excel('test files/ranking_{}.xlsx'.format(group[0]), index=False)
^Trying to convert it to a dataframe with group.to_frame().to_excel results in this error: AttributeError: 'tuple' object has no attribute 'to_frame'
How can I convert the groups into dataframes to be stored in each file?
It looks like you've missed a parameter when unpacking the grouped values. The grouped values are a list of touples with the following format (group_index, group_dataframe). So, in order to iterate properly over it, you should do something like this:
df = pd.read_excel("ranker_test.xlsx", sheet_name='DATA')
grouped = df.groupby('state')
for name, group in grouped:
group.to_excel('test files/ranking_{}.xlsx'.format(name), index=False)
Notice the name parameter in the for loop

Pandas - Appending data from one Dataframe to

I have a Dataframe (called df) that has list of tickets worked for a given date. I have a script that runs each day where this df gets generated and I would like to have a new master dataframe (lets say df_master) that appends values form df to a new Dataframe. So anytime I view df_master I should be able to see all the tickets worked across multiple days. Also would like to have a new column in df_master that shows date when the row was inserted.
Given below is how df looks like:
1001
1002
1003
1004
I tried to perform concat but it threw an error
TypeError: first argument must be an iterable of pandas objects, you passed an object of type "Series"
Update
df_ticket = tickets['ticket']
df_master = df_ticket
df_master['Date'] = pd.Timestamp('now').normalize()
L = [df_master,tickets]
master_df = pd.concat(L)
master_df.to_csv('file.csv', mode='a', header=False, index=False)
I think you need pass sequence to concat, obviously list is used:
objs : a sequence or mapping of Series, DataFrame, or Panel objects
If a dict is passed, the sorted keys will be used as the keys argument, unless it is passed, in which case the values will be selected (see below). Any None objects will be dropped silently unless they are all None in which case a ValueError will be raised
L = [s1,s2]
df = pd.concat(L)
And it seems you pass only Series, so raised error:
df = pd.concat(s)
For insert Date column is possible set pd.Timestamp('now').normalize(), for master df I suggest create one file and append each day DataFrame:
df_ticket = tickets[['ticket']]
df_ticket['Date'] = pd.Timestamp('now').normalize()
df_ticket.to_csv('file.csv', mode='a', header=False, index=False)
df_master = pd.read_csv('file.csv', header=None)

How can I merge two data sets of different lengths in Python?

I have tried merging with Pandas merge, however, as the length of data is different, merge function is broadcasting the data even when using a key.
The following line of code has been used.
dt = pd.merge(df,data[['Post ID','Sentiment']], on = 'Post ID')
Using join produces the following:
df.join(data[['Post ID','Sentiment']],on = 'Post ID')
You are trying to merge on object and int64 columns. If you wish to proceed you should use pd.concat
This error means that in one of your database, Post ID is an objectand in the other one it is defined as int.
You need to convert them so they have the same type, for instance by doing :
df['Post ID'] = df['Post ID'].astype(int)

Key error: '3' When extracting data from Pandas DataFrame

My code plan is as follows:
1) find csv files in folder using glob and create a list of files
2) covert each csv file into dataframe
3) extract data from a column location and convert into a separate dataframe
4) append the new data into a separate summary csv file
code is as follows:
Result = []
def result(filepath):
files = glob.glob(filepath)
print files
dataframes = [pd.DataFrame.from_csv(f, index_col=None) for f in files]
new_dfb = pd.DataFrame()
for i, df in enumerate(dataframes):
colname = 'Run {}'.format(i+1)
selected_data = df['3'].ix[0:4]
new_dfb[colname] = selected_data
Result.append(new_dfb)
folder = r"C:/Users/Joey/Desktop/tcd/summary.csv"
new_dfb.to_csv(folder)
result("C:/Users/Joey/Desktop/tcd/*.csv")
print Result
The code error is shown below. The issue seems to be with line 36 .. which corresponds to the selected_data = df['3'].ix[0:4].
I show one of my csv files below:
I'm not sure what the problem is with the dataframe constructor?
You're csv snippet is a bit unclear. But as suggested in the comments, read_csv (from_csv in this case) automatically taken the first row as a list of headers. The behaviour you appear to want is the columns to be labelled as 1,2,3 etc. To achieve this you need to have
[pd.DataFrame.from_csv(f, index_col=None,header=None) for f in files]