过滤列然后创建新列的 Pythonic 方法

标签 python pandas

我有一个 .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.findallstr.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/

相关文章:

python - 创建 django 项目后可以更改文件夹名称吗?

python - 将 python dict 转换为带有单反斜杠和双引号的字符串

regex - Python读取带有开始和停止条件的文件

python - 使用 .agg() 进行 pandas DataFrame 多项操作的进度条

python - 如何从请求中解析 xml?

python - 在 PyGTK 中获取要阻止的接口(interface)

python - 质因数,帮助理解平方根的用途

python-2.7 - 将 Pandas 中的每日数据转换为每周数据

python - 从序列中减去数据框(或其唯一的列)

python - 类型错误 : unsupported operand type(s) for/: 'Decimal' and 'float'