【问题标题】:replace dataframe values from another list with specific indexes用特定索引替换另一个列表中的数据框值
【发布时间】:2021-01-24 01:39:23
【问题描述】:

我有一个包含日期列的数据框,我正在尝试用另一个基于索引的列表替换,例如: wrong_dates_indexes 具有原始数据帧 df 中日期格式错误的索引列表:

dirty_dates_indexes=[4,33,48,54,59,91,95,132,160,175,180,197,203,206,229,237,266,271,278,294,298,333,348,373,380,420,442]

formated_dates=['2019-04-25','2019-12-01','2019-06-16','2019-10-07','2019-08-06','2019-02-17','2019-11-20','2019-03-10','2019-10-11','2019-03-04','2019-07-31','2019-10-12','2019-09-13','2019-08-26','2019-12-29','2019-10-11','2019-11-20','2019-06-16','2019-12-12','2019-03-22','2019-01-21','2019-03-21','2019-10-15','2019-12-01','2019-03-20','2019-09-08','2019-08-19']

我正在尝试用索引替换 df 中的所有值 wrong_dates_indexes 的值在 formated_dates 中。

我尝试了以下代码,但收到错误:

for index in dirty_dates_indexes:
    df.loc[index].date.replace(df.loc[index].date,formated_dates(f for f in range(0,len(range(formated_dates)))))

错误:

TypeError: 'list' object cannot be interpreted as an integer

如何解决这个问题?还是有更好的方法?

【问题讨论】:

    标签: python python-3.x pandas dataframe data-science


    【解决方案1】:

    您正在尝试从dirty_dates_indexes 获取值并使用它来查找formatted_dates 中的位置。它可能会搞砸你。

    您正在使用 loc 而不是 iloc 来到达特定行。

    这就是我所做的。

    dirty_dates_indexes=[4,33,48,54,
                         59,91,95,132,
                         160,175,180,197,
                         203,206,229,237,
                         266,271,278,294,
                         298,333,348,373,
                         380,420,442]
    formated_dates=['2019-04-25','2019-12-01','2019-06-16','2019-10-07',
                    '2019-08-06','2019-02-17','2019-11-20','2019-03-10',
                    '2019-10-11','2019-03-04','2019-07-31','2019-10-12',
                    '2019-09-13','2019-08-26','2019-12-29','2019-10-11',
                    '2019-11-20','2019-06-16','2019-12-12','2019-03-22',
                    '2019-01-21','2019-03-21','2019-10-15','2019-12-01',
                    '2019-03-20','2019-09-08','2019-08-19']
    
    import pandas as pd
    df = pd.DataFrame()
    df['dirty_dates'] = pd.date_range('2019-01-01', periods=500,freq='D')
    
    for i,row_id in enumerate(dirty_dates_indexes):
        df.dirty_dates.iloc[row_id] = pd.to_datetime(formated_dates[i])
    
    
    print (df.head(20))
    

    结果如下:

       dirty_dates
    0   2019-01-01
    1   2019-01-02
    2   2019-01-03
    3   2019-01-04
    4   2019-04-25  # <-- this row changed
    5   2019-01-06
    6   2019-01-07
    7   2019-01-08
    8   2019-01-09
    9   2019-01-10
    10  2019-01-11
    11  2019-01-12
    12  2019-01-13
    13  2019-01-14
    14  2019-01-15
    15  2019-01-16
    16  2019-01-17
    17  2019-01-18
    18  2019-01-19
    19  2019-01-20
    

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 1970-01-01
      • 2020-10-23
      • 2021-06-11
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 2020-10-17
      相关资源
      最近更新 更多