python - 仅当相邻列中同一行的单元格为空白时,如何基于字符拆分字符串

标签 python python-3.x

我有一个如下所示的数据框。

这是我之前的观点。

              string  the_date

-rw-r--r--   12 30067    10224
-rw-r--r--   64 30067    10224
-rw-r--r--   64 30067    10224

我正在寻找一行或几行代码,它将“_”字符后面的日期拆分到名为“the_date”的字段中,但前提是“the_date”为空。我想是这样的:

df_all_files = pd.DataFrame(df_all_files.string.str.rsplit('',1).tolist(), columns = ['string','the_date'])

最佳答案

假设您使用 pandas,并且 df 变量是上面的数据框,您可以尝试以下操作:

df.loc[df['the_date'].isnull(), 'the_date'] = df['string'].apply(lambda x:x.split('_')[-1])

关于python - 仅当相邻列中同一行的单元格为空白时,如何基于字符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54103251/

相关文章:

python - 在selenium中使用文本文件交替或逐一搜索

Python:如何通过切片插入列表?

python - 在 Apache2 中执行 Python 脚本

python - Flask 使用带有 LIKE % % 的 mysql 查询

python - 如何克服 "datetime.datetime not JSON serializable"?

python - 在 Python 中重构 For 循环

python - 将 Boto3 与 freezegun 一起使用会导致 403

python - ModelForm 返回服务器错误 (500)

python - 为什么我可以将元素分配给没有 setter 的列表?

python-3.x - Python3 : implicit import from submodules, 避免递归导入