我有一个 .xlsx 文件,我将使用以下代码打开它:
import pandas as pd
df = pd.read_excel(open('file.xlsx','rb'))
df['Description'].head
我得到了以下结果,看起来很不错。
ID | Description
:----- | :-----------------------------
0 | Some Description with no hash
1 | Text with #one hash
2 | Text with #two #hashes
现在我想创建一个新列,只保留以# 开头的单词,如下所示:
ID | Description | Only_Hash
:----- | :----------------------------- | :-----------------
0 | Some Description with no hash | Nan
1 | Text with #one hash | #one
2 | Text with #two #hashes | #two #hashes
我能够用#数/分隔行:
descriptionWithHash = df['Description'].str.contains('#').sum()
但现在我想像上面描述的那样创建列。最简单的方法是什么?
问候!
PS:问题中应该显示表格格式,但我不明白为什么显示错误!
最佳答案
您可以使用 str.findall
与 str.join
:
df['new'] = df['Description'].str.findall('(\#\w+)').str.join(' ')
print(df)
ID Description new
0 0 Some Description with no hash
1 1 Text with #one hash #one
2 2 Text with #two #hashes #two #hashes
对于 NaN:
df['new'] = df['Description'].str.findall('(\#\w+)').str.join(' ').replace('',np.nan)
print(df)
ID Description new
0 0 Some Description with no hash NaN
1 1 Text with #one hash #one
2 2 Text with #two #hashes #two #hashes
关于过滤列然后创建新列的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45414418/