pandas按片分割数据帧

时间:2017-08-09 20:27:38

标签: python python-2.7 pandas dataframe

我有一个固定宽度的数据帧:

A
-------------------------------------------
BPE AED USD 2017/07/01  0_27225 1         1
BPE CLF USD 2017/07/01 40.25765 1         1
M   LBP USD 2017/07/20  0.66414 1,000     1
PF4 TRL USD 2005/01/01  0.63055 1,000,000 1

那需要:

A   B   C   D          E        F         G
-------------------------------------------
BPE AED USD 2017/07/01  0_27225 1         1
BPE CLF USD 2017/07/01 40.25765 1         1
M   LBP USD 2017/07/20  0.66414 1,000     1
PF4 TRL USD 2005/01/01  0.63055 1,000,000 1

现在,我在切片中进行硬编码(这里的数字是任意的):

df['A'], df['B'], df['C'], df['D'], df['E'], df['F'], df['G'] = df['A'].str[:4].str.strip(), df['A'].str[4:9].str.strip(), df['A'].str[9:14].str.strip(), df['A'].str[14:26].str.strip(), df['A'].str[26:36].str.strip(), df['A'].str[36:46].str.strip(), df['A'].str[46:None].str.strip()

但我想创建一个函数,以便将来可以重用它,数据帧需要拆分成不同数量的列。 (这不起作用,但是):像:

headers = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
slice_indices = [(0, 4), (4, 9), (9, 14), (14, 26), (26, 36), (36, 46), (46, None)]

def parse_df(headers, slice_indices, df):
     new_df = {}
     for header in headers:
         for slice in slice_indices:
             new_rows = []
             for row in df:
                fields = []
                for slice in slice_indices:
                    fields.append(row[slice[0]:slice[1]].strip())
                new_rows.append(fields)
     return new_df

但这对我来说似乎超级笨拙/缓慢/凌乱。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

不确定文件的外观如何,但请尝试使用以下内容来读取文件,而不是稍后尝试对值进行切片。

df = pd.read_fwf(file) 

OR

df = pd.read_csv(file, delim_whitespace=True)