我有一个包含评论的列的数据集。这些评论是用逗号分隔的单词。
df_pat ['reason'] =
我想在数据框中生成单独的列,以便一列代表所有单词集中的每个单词,然后将1或0放到我最初在评论中包含该单词的行中。
例如: df_pat ['chest_pain'] = 1 1 1 1 1 1 0 1
df_pat ['dyspnea'] = 0 1 0 0 0 0 1
等等......
谢谢!
答案 0 :(得分:0)
sklearn.feature_extraction.text
有适合你的东西!看起来你可能正在尝试预测某些事情。如果是这样 - 并且如果您计划在某些时候使用sci-kit学习,那么您可以绕过使用len(set(words))列数来制作数据帧并使用CountVectorizer
。此方法将返回一个矩阵,其中包含维度(行,列)=(数据框中的行数,整个'reason'
列中的唯一字数)。
from sklearn.feature_extraction.text import CountVectorizer
df = pd.DataFrame({'reason': ['chest pain', 'chest pain, dyspnea', 'chest pain, hypertrophic obstructive cariomyop', 'chest pain', 'chest pain', 'cad, rca stents', 'non-ischemic cardiomyopathy, chest pain, dyspnea']})
# turns body of text into a matrix of features
# split string on commas instead of spaces
vectorizer = CountVectorizer(tokenizer = lambda x: x.split(","))
# X is now a n_documents by n_distinct_words-dimensioned matrix of features
X = vectorizer.fit_transform(df['reason'])
pandas
与sklearn
非常相称。
或者,一个严格的pandas
解决方案应该可以进行矢量化,但是如果你没有那么多的数据,应该可以工作:
# split on the comma instead of spaces to get "chest pain" instead of "chest" and "pain"
reasons = [reason for case in df['reason'] for reason in case.split(",")]
for reason in reasons:
for idx in df.index:
if reason in df.loc[idx, 'reason']:
df.loc[idx, reason] = 1
else:
df.loc[idx, reason] = 0