我有一个数据框,其中包含一个名为 start_year
的列。
里面写了很多样式,我只需要在这里写。 例如:
表中的start_year | start_year 根据我的需要 |
---|---|
1949 年 12 月 27 日 | 1949 |
公元前 168 年 | -168 |
正在进行 | 2021(今天) |
1902(马尔瓦投降)1913(Irreconcilables active) | 1902 |
1903-1905 | 1903 |
我希望这张表能帮助你理解我的问题。
答案 0 :(得分:2)
通过 extract()
和 fillna()
尝试:
val=df['start_year in table'].str.extract('(-?[0-9]+)').fillna('2021')
df['start_year as I need']=df['start_year in table'].str.extract('(\d{4})').fillna(val)
如果 -
符号最初没有出现在 'start_year as I need' 列中,其中值是 BC,那么您可以在运行上述操作后使用布尔掩码代码:
m=df['start_year in table'].str.contains('BC')
df.loc[m,'start_year as I need']='-'+df.loc[m,'start_year as I need']