【问题标题】:How to edit the values in one column when a certain value is realised in another in pandas DataFrame?当在 pandas DataFrame 中的另一列中实现某个值时,如何编辑一列中的值?
【发布时间】:2020-06-04 15:46:11
【问题描述】:

我有以下 DataFrame,其中包含此处之外的几列:

    Col2      Col3    Col4
0   3682   US91892      US
1   7568   US91234      US
2   3546     UKIPD      GB
3   7892     UKI43      GB
4   1243   US92345      US

为此,如果 col4 = US 我只想获取 col3 的最后 5 位数字,例如:

    Col2      Col3    Col4
0   3682     91892      US
1   7568     91234      US
2   3546     UKIPD      GB
3   7892     UKI43      GB
4   1243     92345      US

为此我已经尝试过:

for a in df.index:
    if df["col4"][a] == "US":
        df["col3"][a] = df["col3"][a][-5:]

但是,运行需要几个小时(该数据集大约有 170,000 个数据点,其中包含多个此类数据集)。我想知道是否有更快更有效的方法来做到这一点?

【问题讨论】:

    标签: python pandas multiple-columns


    【解决方案1】:

    另一种方法是使用布尔索引:

    df.loc[df.Col4=='US', 'Col3'] = df.Col3.str[-5:]
    

    输出:

       Col2   Col3 Col4
    0  3682  91892   US
    1  7568  91234   US
    2  3546  UKIPD   GB
    3  7892  UKI43   GB
    4  1243  92345   US
    

    【讨论】:

    • 非常感谢!也非常快速有效地工作
    【解决方案2】:

    你可以试试:

    df['Col3'] = df['Col3'].str[-5:].where(df['Col4'].eq('US'),df['Col3'])
    #or df['Col3'] = np.where(df['Col4'].eq('US'),df['Col3'].str[-5:],df['Col3'])
    print(df)
    

       Col2   Col3 Col4
    0  3682  91892   US
    1  7568  91234   US
    2  3546  UKIPD   GB
    3  7892  UKI43   GB
    4  1243  92345   US
    

    【讨论】:

    • 这太好了,谢谢!它运行了将近一秒钟而不是一个小时
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多