【问题标题】:Replace Value in DataFrame with Regex function return Value [duplicate]用正则表达式函数返回值替换DataFrame中的值[重复]
【发布时间】:2020-02-19 21:31:51
【问题描述】:

目标:

在包含串联专有名称的数据框中,将名称大写的每个名称用空格分开,并在相应的数据框元素中替换该值。在对独立值进行测试时,对 regex 函数的测试会产生正确的结果。

流程

data = {'Full_Name' : ["JackSmithDanielsSmith", "JoeShmoeDoeBoe", "MikeJohnChaoCow"]
        'First_Name': ["JackSmith", "JoeShmoeDoe", "Mike"]
        'Last_Name' : ["DanielsSmith", "Boe", "JohnChaoCow"]}

df = pd.DataFrame(data)


# Regex Function (returns expected results)

def CapitalizeWord(word):
    word = str(word)
    return re.sub("([A-Z])", " \\1", word).strip()

# Procedure
for column in df:
    replace_data = []
    columnObj = df[column]
    for word in columnObj:
        word_split = CapitalizeWord(word)
        replace_data.append(word_split)
    df.replace(columnObj, append_data)  

错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-80-b8089f04c8c8> in <module>
----> 9     df.replace(columnObj, replace_data)


~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in replace(self, to_replace, value, inplace, limit, regex, method)
   4261             limit=limit,
   4262             regex=regex,
-> 4263             method=method,
   4264         )
   4265 

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in replace(self, to_replace, value, inplace, limit, regex, method)
   6719                         )
   6720                 else:
-> 6721                     raise TypeError("value argument must be scalar, dict, or " "Series")
   6722 
   6723             elif is_list_like(to_replace):  # [NA, ''] -> [0, 'missing']

TypeError: value argument must be scalar, dict, or Series

研究:

df.replace Docs 中,我注意到我的问题与结尾段落中提到的问题相似。当与regex 一起使用时,我并不完全理解这个定义。

【问题讨论】:

  • 你能添加一个显示你预期输出的数据框吗
  • 反映在所选答案@sammywemmy

标签: regex python-3.x pandas


【解决方案1】:

试试这个:

df.apply(lambda x: x.str.replace('([A-Z])', " \\1"))

输出:

                   Full_Name      First_Name       Last_Name
0   Jack Smith Daniels Smith      Jack Smith   Daniels Smith
1          Joe Shmoe Doe Boe   Joe Shmoe Doe             Boe
2         Mike John Chao Cow            Mike   John Chao Cow

【讨论】:

  • 这个很有见地,省去了很多步骤,大大提高了处理速度!
【解决方案2】:

这可能不是最好的,但我会stackunstack

(df.stack()
   .str.extractall('([A-Z][a-z]*)')
   .groupby(level=[0,1])
   .agg(' '.join)[0]
   .unstack()
)

输出:

      First_Name                 Full_Name      Last_Name
0     Jack Smith  Jack Smith Daniels Smith  Daniels Smith
1  Joe Shmoe Doe         Joe Shmoe Doe Boe            Boe
2           Mike        Mike John Chao Cow  John Chao Cow

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多