Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在dataframe列中查找以“开始”开头的单词#&引用;对于每行,然后将其添加到新列_Python_Pandas_Dataframe - Fatal编程技术网

Python 在dataframe列中查找以“开始”开头的单词#&引用;对于每行,然后将其添加到新列

Python 在dataframe列中查找以“开始”开头的单词#&引用;对于每行,然后将其添加到新列,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个专栏叫“Tweets”。我想提取所有的hashtaged单词,然后放在一个新的列中。 以下是我尝试的代码: for row in df.split(' '): for word in row: if word.startswith('#'): return row else: return np.nan 问题是它每行只返回一个hashtag。因此,如果一行有“#word1和#word2”,那么它只返回“#wor

我有一个专栏叫“Tweets”。我想提取所有的hashtaged单词,然后放在一个新的列中。 以下是我尝试的代码:

for row in df.split(' '):
    for word in row:
        if word.startswith('#'):
            return row
     else: 
        return np.nan

问题是它每行只返回一个hashtag。因此,如果一行有“#word1和#word2”,那么它只返回“#word1”

,您可能想看看pandas的字符串函数,比如正则表达式。例如:

tweets = ["lorem ipsum #hashtag01 #hashtag02 #another_one",
         "#one ipsum #two lorem #some_more"]

df = pd.DataFrame(tweets, columns=["tweets"])
df.tweets.str.extractall(r"(#\w+)").unstack()
(#\w+
将所有字符串捕获为以
#
开头并具有一个或多个后续单词字符的组

[外]

如果要将所有hashtag提取到一个列中,并确保hashtag始终由空格分隔(如示例所示),则可以使用以下代码行:

df["hashtags] = df.tweets.apply(lambda x: [x for x in x.split(" ") if x.startswith("#")])
[外]


然后我如何将它们合并到一个列表中,使其成为具有行值的单个列[#hashtag01、#hashtag02、#另一个]我已根据您的问题为第二个选项添加了代码。您只需使用
apply()
函数的结果在数据框中创建一个新列。
df["hashtags] = df.tweets.apply(lambda x: [x for x in x.split(" ") if x.startswith("#")])
0    [#hashtag01, #hashtag02, #another_one]
1                  [#one, #two, #some_more]