【发布时间】:2020-01-29 10:38:20
【问题描述】:
我有一个数据框ddd,其中有一个字段date,其中包含混乱的日期值作为文本:
ddd= pd.DataFrame([["80's of 1900"], ["80's of the 19th century"], ["90's of the 18th century"], ["1955"], ["1822"]], columns=['date'])
In [2]: ddd
Out[2]:
index date
0 80's of 1900
1 80's of the 19th century
2 90's of the 18th century
3 1955
4 1822
我正在尝试将文本值转换为第 3 行和第 4 行中的年份,以便进一步分析。 为此,编写了一个带有 if 语句的 for 循环来区分 0 和 1、2 等行。
到目前为止,我有一个代码可以创建一个 numpy 索引数组,其中字段 date 包含 's of 以迭代这些行:
selected_index = ddd[ddd["date"].str.contains('\'s of')].index.values
还有一个带有一些正则表达式的 for 循环来重新排列字符串中的数字,并将 '80's of 1900' 更改为 1980 和 '90's of the 18th Century' 到 1790:
for index in selected_index:
if ddd.at[index, 'date'].str.contains('th century')]:
num = re.findall('[0-9]', ddd.at[index, 'date'])
num2 = ''.join(num)
num3 = str(num2)[2:4]
num4 = int(num3) - 1
num5 = str(num4)
num6 = str(num2)[:2]
ddd.at[index, 'date'] = num5 + num6
else:
num = re.findall('[0-9]', ddd.at[index, 'date'])
num2 = ''.join(num)
num3 = str(num2)[:2]
num4 = str(num2)[2:4]
ddd.at[index, 'date'] = num4 + num3
但我收到以下错误:
AttributeError: 'str' object has no attribute 'str'
预期输出:
index date
0 1980
1 1880
2 1790
3 1955
4 1822
提前感谢您的建议!
【问题讨论】:
标签: python string for-loop if-statement