内容不对齐时如何拆分列

时间:2019-08-15 18:43:46

标签: python excel pandas

我有一个包含调查数据的CSV文件。列之一包含来自多选问题的答案。该列中的值用“;”分隔。

|     Q10    |
----------------
| A; B; C    |
| A; B; D    |
| A; D       |
| A; D; E    |
| B; C; D; E |

我想将该列分成多列,每个选项一个:

| A | B | C | D | E |
---------------------
| A | B | C |   |   |
| A | B |   | D |   |
| A |   |   | D |   |
| A |   |   | D | E |
|   | B | C | D | E |

有没有用excel或python或其他方式做到这一点?

3 个答案:

答案 0 :(得分:3)

这是一个简单的公式,可以执行以下操作:

=IF(ISNUMBER(SEARCH("; "&B$1&";","; "&$A2&";")),B$1,"")

这假设;与查找值之间始终存在空格。如果没有,我们可以用替换符删除空间:

=IF(ISNUMBER(SEARCH(";"&B$1&";",";"&SUBSTITUTE($A2," ","")&";")),B$1,"")

enter image description here

答案 1 :(得分:0)

我知道这个问题已经回答了,但是对于那些寻求用Python方式解决它的人来说,这是(虽然可能不是最有效的方法):

首先拆分列值,将其爆炸并获得假人。接下来,在给定的5(或N)列中将虚拟值分组在一起:

<projectid>

您将获得:

df['Q10'] = df['Q10'].str.split('; ')
df = df.explode('Q10')
df = pd.get_dummies(df, columns=['Q10'])
dummy_col_list = df.columns.tolist()
df['New'] = df.index
new_df = df.groupby('New')[dummy_col_list].sum().reset_index()
del new_df['New']

现在,如果需要,您可以重命名列,并将 Q10_A Q10_B Q10_C Q10_D Q10_E 0 1 1 1 0 0 1 1 1 0 1 0 2 1 0 0 1 0 3 1 0 0 1 1 4 0 1 1 1 1 替换为列名:

1

最终输出:

colName = new_df.columns.tolist()
newColList = []
for i in colName:
    newColName = i.split('_', 1)[1]
    newColList.append(newColName)

new_df.columns = newColList

for col in list(new_df.columns):
    new_df[col] = np.where(new_df[col] == 1, col, '')

答案 2 :(得分:-1)

如果您想在python中完成这项工作:

import pandas as pd
import numpy as np

df = pd.read_csv('file.csv')
df['A'] = np.where(df.Q10.str.contains('A'), 'A', '')
df['B'] = np.where(df.Q10.str.contains('B'), 'B', '')
df['C'] = np.where(df.Q10.str.contains('C'), 'C', '')
df['D'] = np.where(df.Q10.str.contains('D'), 'D', '')
df['E'] = np.where(df.Q10.str.contains('E'), 'E', '')
df.drop('Q10', axis=1, inplace=True)
df

输出:

    A   B   C   D   E
 0  A   B   C       
 1  A   B       D   
 2  A           D   
 3  A           D   E
 4      B   C   D   E

这不是最有效的方法,但是有效;)