首页 > 解决方案 > 如果另一列上的值相同,则将 pandas 列的所有值更改为第一次出现

问题描述

如果文本列相同,我想将日期列中的所有日期更改为最早的日期。

import pandas as pd
df = pd.DataFrame({'text': ['I like python pandas', 
                                 'find all function input from help jupyter',
                                 'function input',
                           'function input',
                            'function input'],'date': ['March 1st',"March 2nd","March 3rd","March 4th","March 5th"]})

所以 3 月 4 日和 3 月 5 日,我想改成 3 月 3 日,因为它是最早出现的文本列有“功能输入”列出的时间。任何帮助将不胜感激。

标签: pythonpandasdate

解决方案


你可以这样做:

def update_col(col):
    col[:] = col.iloc[0]
    return col

df['date'] = df.groupby('text').date.apply(update_col)
df
#                                        text       date
# 0                       I like python pandas  March 1st
# 1  find all function input from help jupyter  March 2nd
# 2                             function input  March 3rd
# 3                             function input  March 3rd
# 4                             function input  March 3rd

推荐阅读