python - pandas 按切片分割数据框列

标签 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

但这对我来说似乎 super 笨重/缓慢/困惑。最好的方法是什么?

最佳答案

不确定您的文件是什么样子,但请尝试使用以下内容来读取文件,而不是稍后尝试对值进行切片。

df = pd.read_fwf(file) 

或者

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

关于python - pandas 按切片分割数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45600082/

相关文章:

python - 显示文件名,而不是文本小部件tkinter Python中的内容

python - 在随机列表生成中强制执行 "no 2 same contiguous elements"

python - 类型错误 : "' TrieNode' object is not callable"- What is wrong with my code?

python - 为什么 ";"违反格式标准而存在?

python - PyQt - 使用 pandas DataFrame 在 QAbstractTableModel (QTableView) 中加载 SQL - 在 GUI 中编辑数据

python - 尝试使用 pandas 从网站中提取 html 表

python - Concat 未按预期工作

javascript - 访问 Jupyter 扩展中的数据对象

Python2.5到Python2.7性能下降

python - 根据数据框制作 2 个变量的条形图