2017-08-09 160 views
0

我有一个固定宽度的数据帧分成数据框柱:大熊猫由片

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 

现在,我是硬编码在片(这里NUMS是任意):

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() 

但我想创建一个函数,这样我可以在将来重复使用,与需要被分成dataframes不同的列数。 (这不工作,但)喜欢的东西:

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

你应该尝试使用pd.read_fwf()读取数据,而不是后来操纵它读取数据 – Vaishali

回答

0

不知道你的文件是怎么样的,但尝试使用以下来读取文件,而不是稍后尝试切片的值。

df = pd.read_fwf(file) 

OR

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