gpt4 book ai didi

python - 如何将 pandas 数据帧的对象值转换为小时数?

转载 作者:行者123 更新时间:2023-12-02 06:33:11 25 4
gpt4 key购买 nike

我有这个数据框

number_of_hrs  number_of_pts
65 1
7 1
31 1
6 DAY 1
23 1
21 1
5.0 1

我想将“6 DAY”之类的值转换为小时数。这可能吗?

最佳答案

使用pd.evalSeries.str.replace .

df['number_of_hrs'] = pd.eval(df['number_of_hrs'].str.replace('DAY','*24'))
print(df)
# number_of_hrs number_of_pts
#0 65 1
#1 7 1
#2 31 1
#3 144 1
#4 23 1
#5 21 1
#6 5 1

from ast import literal_eval
df['number_of_hrs'] = df['number_of_hrs'].str.replace('DAY','*24').apply(literal_eval)
#Alternative
#df['number_of_hrs'] = [literal_eval(s) for s in df['number_of_hrs'].str.replace('DAY','*24')]

关于python - 如何将 pandas 数据帧的对象值转换为小时数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59858745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com