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
但這似乎超級笨重/慢/凌亂我。什麼是最好的方法來做到這一點?
你應該嘗試使用pd.read_fwf()讀取數據,而不是後來操縱它讀取數據 – Vaishali