我有看起来像的数据框:
Groupe Id MotherName FatherName Field Advanced 56 Laure James English-107,Economics, Management, History, Philosophy Middle 11 Ann Nicolas Web-development, Java-2 Advanced 6 Helen Franc Literature, English-2 Beginner 43 Laure James Mathematics, History, Philosophy, Literature Middle 14 Naomi Franc Java-2, Management, English-107
为了进一步处理数据,我需要拆分该Field列,然后将其替换为如下所示的多列:
Field
Id English-107 Economics Management History Web-development Java-2 Literature English-2 Mathematics Philosophy 56 1 1 1 1 0 0 0 0 0 1 11 0 0 0 0 1 1 0 0 0 0
因此,这些列可以追加到初始数据帧。我不知道该怎么做,因为像
pd.DataFrame(df.Field.str.split(',',1).tolist())
不能解决我的问题,因为我不仅需要基于列表中位置的列,还需要基于列表中每个唯一值的列。您知道我该如何处理吗?
您可以使用concat和str.get_dummies:
concat
str.get_dummies
print pd.concat([df['Id'], df['Field'].str.get_dummies(sep=",")], axis=1) Id Economics English-107 English-2 History Java-2 Literature \ 0 56 1 1 0 1 0 0 1 11 0 0 0 0 1 0 2 6 0 0 1 0 0 1 3 43 0 0 0 1 0 1 4 14 0 1 0 0 1 0 Management Mathematics Philosophy Web-development 0 1 0 1 0 1 0 0 0 1 2 0 0 0 0 3 0 1 1 0 4 1 0 0 0
如果需要计数值,则可以使用pivot_table(我添加一个字符串Economics进行测试):
pivot_table
Economics
df1 = df['Field'].str.split(',',expand=True).stack() .groupby(level=0) .value_counts() .reset_index() df1.columns=['a','b','c'] print df1.pivot_table(index='a',columns='b',values='c').fillna(0) b Economics English-107 English-2 History Java-2 Literature Management \ a 0 2 1 0 1 0 0 1 1 0 0 0 0 1 0 0 2 0 0 1 0 0 1 0 3 0 0 0 1 0 1 0 4 0 1 0 0 1 0 1 b Mathematics Philosophy Web-development a 0 0 1 0 1 0 0 1 2 0 0 0 3 1 1 0 4 0 0 0