【问题标题】:Apply string function to data frame将字符串函数应用于数据框
【发布时间】:2020-11-23 19:15:35
【问题描述】:

任务是用 html 标记将 URL 包装在 excel 文件中。 为此,我有一个函数和以下代码适用于一个名为 ANSWER 的列:

import pandas as pd
import numpy as np
import string
import re

def hyperlinksWrapper(myString):
    #finding all substrings that look like a URL

    URLs = re.findall("(?P<url>https?://[^','')'' ''<'';'\s\n]+)", myString)
    #print(URLs)
    
    #replacing each URL by a link wrapped into <a> html-tags
    for link in URLs:
        wrappedLink = '<a href="' + link + '">' + link + '</a>'
        myString = myString.replace(link, wrappedLink)
    
    return(myString)
#Opening the original XLS file
filename = "Excel.xlsx"
df = pd.read_excel(filename)

#Filling all the empty cells in the ANSWER cell with the value "n/a"
df.ANSWER.replace(np.NaN, "n/a", inplace=True)

#Going through the ANSWER column and applying hyperlinksWrapper to each cell
for i in range(len(df.ANSWER)):
    df.ANSWER[i] = hyperlinksWrapper(df.ANSWER[i])

#Export to CSV
df.to_excel('Excel_refined.xlsx')

问题是,我如何不查看一列,而是查看数据框中的所有列(每个单元格)而不指定确切的列名?

【问题讨论】:

  • 要遍历列,您可以使用:for col in df.columns。要逐行遍历整个 DataFrame(绝对效率低下,不推荐),您可以使用:for idx, row in df.iteritems()正确答案是:研究df.apply()函数。
  • 欢迎您! Pandas Dataframes 有一个方法.replace()read the docs。您可以将您的正则表达式模式直接传递给它,它将用参数value 替换每一列的每一行中的每个实例(即 df 中的所有出现)。记得传递regex=True
  • 还有一些建议。您可以将NaN 替换为.fillna()。此外,每当您觉得需要遍历 dfs 中的行时,请阅读 Q&A 关于矢量化与 pandas 循环的内容。很可能有针对您想要的优化的 pandas 函数。

标签: python python-3.x pandas


【解决方案1】:

也许你正在寻找这样的东西:

import pandas as pd
import numpy as np
import string
import re

def hyperlinksWrapper(myString):
    #finding all substrings that look like a URL

    URLs = re.findall("(?P<url>https?://[^','')'' ''<'';'\s\n]+)", myString)
    #print(URLs)
    
    #replacing each URL by a link wrapped into <a> html-tags
    for link in URLs:
        wrappedLink = '<a href="' + link + '">' + link + '</a>'
        myString = myString.replace(link, wrappedLink)
    
    return(myString)

# dummy dataframe
df = pd.DataFrame(
    {'answer_col1': ['https://example.com', 'https://example.org', np.nan], 
     'answer_col2': ['https://example.net', 'Hello', 'World']}
)

# as suggested in the comments (replaces all NaNs in df)
df.fillna("n/a", inplace=True)

# option 1
# loops over every column of df
for col in df.columns:
    # applies hyperlinksWrapper to every row in col
    df[col] = df[col].apply(hyperlinksWrapper)
    
# [UPDATED] option 2
# applies hyperlinksWrapper to every element of df
df = df.applymap(hyperlinksWrapper) 

df.head()

【讨论】:

  • 谢谢@akensert,但您的两个选项都返回以下错误:文件“C:\Users\ihor.vinnyk\AppData\Local\Programs\Python\Python38\lib\re.py” ,第 241 行,在 findall 中返回 _compile(pattern, flags).findall(string) TypeError: expected string or bytes-like object
  • 嗯,我使用的是 Python3.6,它对我来说很好用。虚拟示例/数据框对您有用吗?也许您的数据框中有一个单元格不是“字符串或类似字节的对象”。
猜你喜欢
  • 2021-12-22
  • 2021-05-14
  • 2020-03-29
  • 2020-03-23
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多