python - 用时间戳格式的变量替换 pandas 数据帧上的年份

标签 python python-3.x pandas datetime

我使用以下代码创建了以下 df:

df = pd.read_table('https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data', sep = "\s+", parse_dates = [[0,1,2]]) 

如果我们运行以下命令:

type(df['Yr_Mo_Dy'][0])

我们将看到 ['Yr_Mo_Dy'] 下的观察结果采用 pandas._libs.tslibs.timestamps.Timestamp 格式。

我想做的是:每当我看到年份 >= 2061 (['Yr_Mo_Dy']) 时,我想减去 -100,否则我只保留年份并继续迭代。

我尝试过以下代码:

for i in list(range(df.shape[0])):
    # assign all the observations under df['Yr_Mo_Dy'] to ts
    ts = df['Yr_Mo_Dy'][i]

    if df['Yr_Mo_Dy'][i].year >=2061:
        # replace the year in ts by year - 100
        ts.replace(year=df['Yr_Mo_Dy'][i].year - 100)
    else:
        continue

但是循环什么也不做。我觉得这与变量赋值ts = df['Yr_Mo_Dy'][i]有关。但我想不出另一种方法来完成这件事。

考虑到我在 this post 中看到的答案,我尝试在每次循环迭代后分配一个变量。

最佳答案

您应该致力于避免可矢量化操作的手动循环。

在这种情况下,您可以使用numpy.where创建条件序列:

df = pd.DataFrame({'A': pd.to_datetime(['2018-01-01', '2080-11-30',
                                        '1955-04-05', '2075-10-09'])})

df['B'] = np.where(df['A'].dt.year >= 2061,
                   df['A'] - pd.DateOffset(years=100), df['A'])

print(df)

           A          B
0 2018-01-01 2018-01-01
1 2080-11-30 1980-11-30
2 1955-04-05 1955-04-05
3 2075-10-09 1975-10-09

关于python - 用时间戳格式的变量替换 pandas 数据帧上的年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52519046/

相关文章:

python - Scikit-learn 中逻辑回归的第一次迭代的初始估计是多少?

python - 如何在 python 3 中将字符串转换为字典

Python 单行 while 循环

python - 拆分数据框列,其中 dtype 是 Object 但里面有 list ,如何拆分?

python - Pygame 显示在 If 条件下不工作

python - 如何不断更新 tkinter 标签直到按下按钮?

python - 如何简化 if 语句中的多个 or 条件?

pandas - 将 pandas 列表转换为虚拟变量

pandas - 除以 pandas 数据框中一组内的最大值

Python mock.patch autospec 具有属性的类