通过分隔符拆分 pandas 数据框中的多列

我有一些烦人的调查数据,它以以下方式返回了多项选择题。它位于 Excel 工作表中,大约有 60 列,其中包含从单个到多个的响应,并用 / 分隔。这就是我到目前为止所拥有的,有什么方法可以更快地完成此操作,而不必为每个单独的列执行此操作


data = {'q1': ['one', 'two', 'three'],

   'q2' : ['one/two/three', 'a/b/c', 'd/e/f'],

   'q3' : ['a/b/c', 'd/e/f','g/h/i']}


df = pd.DataFrame(data)


df[['q2a', 'q2b', 'q2c']]= df['q2'].str.split('/', expand = True, n=0)

df[['q3a', 'q3b', 'q3c']]= df['q2'].str.split('/', expand = True, n=0)


clean_df = df.drop(df[['q2', 'q3']], axis=1)


白衣非少年
浏览 66回答 2
2回答

有只小跳蛙

我们可以将列表理解与 一起使用add_prefix,然后将pd.concat所有内容连接到最终的 df:splits = [df[col].str.split(pat='/', expand=True).add_prefix(col) for col in df.columns]clean_df = pd.concat(splits, axis=1)     q10  q20  q21    q22 q30 q31 q320    one  one  two  three   a   b   c1    two    a    b      c   d   e   f2  three    d    e      f   g   h   i如果您确实希望列名称带有字母后缀,则可以使用以下命令执行以下操作string.ascii_lowercase:from string import ascii_lowercasedfs = []for col in df.columns:    d = df[col].str.split('/', expand=True)    c = d.shape[1]    d.columns = [col + l for l in ascii_lowercase[:c]]    dfs.append(d)    clean_df = pd.concat(dfs, axis=1)     q1a  q2a  q2b    q2c q3a q3b q3c0    one  one  two  three   a   b   c1    two    a    b      c   d   e   f2  three    d    e      f   g   h   i

泛舟湖上清波郎朗

您可以创建一个d将数字转换为字母的字典。然后循环遍历列并动态更改它们的名称:输入:import pandas as pddf = pd.DataFrame({'q1': ['one', 'two', 'three'],   'q2' : ['one/two/three', 'a/b/c', 'd/e/f'],   'q3' : ['a/b/c', 'd/e/f','g/h/i']})代码:ltrs = list('abcdefghijklmonpqrstuvwxyz')nmbrs = [i[0] for i in enumerate(ltrs)]d = dict(zip(nmbrs, ltrs)) cols = df.columns[1:]for col in cols:    df1 = df[col].str.split('/', expand = True)    df1.columns = df1.columns.map(d)    df1 = df1.add_prefix(f'{col}')    df = pd.concat([df,df1], axis=1)df = df.drop(cols, axis=1)df输出:Out[1]:       q1  q2a  q2b    q2c q3a q3b q3c0    one  one  two  three   a   b   c1    two    a    b      c   d   e   f2  three    d    e      f   g   h   i
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python