熊猫阅读Excel和所需数据的拆分部分

Panda Reading Excel and Spliting Section of Required Data

您好,我有一个 excel 文件需要排序。 我想拆分数据部分。每段数据由两个换行符分割。

我尝试使用 str(dfs).split('\n\n') 在 \n\n 上拆分数据,但它只是进行一次拆分,其中包括所有数据。简而言之,没有进行拆分。

到目前为止的代码:

import pandas as pd
file_name = "Data of 2020-09-12 .xlsx"

dfs = pd.read_excel(file_name,'Sheet1')
dfs = dfs.fillna('') 
dfs = str(dfs).split("\n\n")
print(dfs)

这是Dataframe的输出

这是您可以执行此操作的一种方法。该代码几乎是不言自明的,但如果有任何混淆,请随时询问。

基本思路是先遍历df,找到df中所有空行的索引位置。 然后将 df 拆分到这些位置。

该解决方案假定第一列值为 '' 的行为空。

import pandas as pd
file_name = "test.xlsx"

df = pd.read_excel(file_name)
df = df.fillna('') 
df_temp = df.copy()

#find all section positions. We are doing p+2 since there are 2 empty rows dividing the section
pos = []
while True:
    try:
        empty = ''
        p = df_temp.index[df_temp.iloc[:, 0] == empty][0]
        df_temp = df_temp.iloc[p+2:]
        pos.append(p)
    except:
        break
print(pos)

#Generate new dfs by splitting on the positions
list_df = []
start = 0
for p in pos:
    print(start,p)
    subdf = df.iloc[start:p]
    list_df.append(subdf)
    start = p+2
    
subdf = df.iloc[start:]
list_df.append(subdf)

#Print your dfs
for d in list_df:
    print(d)