如何基于循环中的行号创建单独的数据帧

2024-04-19 22:57:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读取excel文件中的数据。现在我根据行号把它分解成几个不同的df。 我想做的是创建一个循环,它将迭代输入的行号,并用适当的后缀创建不同的df。 目前,我正在通过在每行中传递行号来创建单独的df

NHE_17= NHE_data.parse('NHE17') 
#Slice DataFrame for only Total National Health Expenditure data, from 
row 0 to 37(Population): total_nhe
total_nhe = NHE_17.iloc[0:37]
print(total_nhe.iloc[0,-1])
#Slice DataFrame for only Health Consumption Expenditures, from row 38 to 
70(Total CMS Programs (Medicaid, CHIP and Medicare): total_hce
total_hce = NHE_17.iloc[38:70]

我希望能够调用带有行号和后缀的函数来创建特定的DF


Tags: fromonlydataframedffordataslice后缀
1条回答
网友
1楼 · 发布于 2024-04-19 22:57:59

该函数如下所示:

   def row_slicer(slice_tuple):

      #This will slice the NHE_17 according to slice_parameters parameters
      # Input slice_tuple = [x1,x1 

      df_temp = NHE_17.iloc[slice_tuple[0]:slice_tuple[1]]
      return df_temp

   dict_dataframes = {}

   #assuming this is a dictionary, else you can  zip lists with pandas columns
   name_list_row = [['total_nhe',[0,37]],['total_hce',[38,70]]...]

   for name,slice_tuple in name_list_row:
      df = row_slicer(slice_tuple)
      dict_dataframes[name] = df

希望这有帮助

相关问题 更多 >