从数据框中的 "comments" 列生成特征
Generate features from "comments" column in dataframe
我有一个数据集,其中有一列有评论。本条评论以逗号分隔。
df_pat['reason'] =
- 胸痛
- 胸痛、呼吸困难
- 胸痛,肥厚性梗阻性近视...
- 胸痛
- 胸痛
- cad、rca支架
- 非缺血性心肌病、胸痛、呼吸困难
我想在数据框中生成单独的列,以便一列代表所有单词集中的每个单词,然后在我最初在评论中包含该单词的行中添加 1 或 0。
例如:
df_pat['chest_pain'] =
1个
1个
1个
1个
1个
1个
0
1
df_pat['dyspnea'] =
0
1个
0
0
0
0
1
等等...
谢谢!
sklearn.feature_extraction.text
有适合你的东西!看起来您可能正在尝试预测某些事情。如果是这样 - 如果您打算在某个时候使用 sci-kit 学习,那么您可以绕过使用 len(set(words)) 列数制作数据框,而只需使用 CountVectorizer
。此方法将 return 一个矩阵,其维度(行,列)=(数据框中的行数,整个 '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
我有一个数据集,其中有一列有评论。本条评论以逗号分隔。
df_pat['reason'] =
- 胸痛
- 胸痛、呼吸困难
- 胸痛,肥厚性梗阻性近视...
- 胸痛
- 胸痛
- cad、rca支架
- 非缺血性心肌病、胸痛、呼吸困难
我想在数据框中生成单独的列,以便一列代表所有单词集中的每个单词,然后在我最初在评论中包含该单词的行中添加 1 或 0。
例如: df_pat['chest_pain'] = 1个 1个 1个 1个 1个 1个 0 1
df_pat['dyspnea'] = 0 1个 0 0 0 0 1
等等...
谢谢!
sklearn.feature_extraction.text
有适合你的东西!看起来您可能正在尝试预测某些事情。如果是这样 - 如果您打算在某个时候使用 sci-kit 学习,那么您可以绕过使用 len(set(words)) 列数制作数据框,而只需使用 CountVectorizer
。此方法将 return 一个矩阵,其维度(行,列)=(数据框中的行数,整个 '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