我有一个固定宽度的数据框:
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
但这对我来说似乎 super 笨重/缓慢/困惑。最好的方法是什么?
最佳答案
不确定您的文件是什么样子,但请尝试使用以下内容来读取文件,而不是稍后尝试对值进行切片。
df = pd.read_fwf(file)
或者
df = pd.read_csv(file, delim_whitespace=True)
关于python - pandas 按切片分割数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45600082/