gpt4 book ai didi

python - 仅使用 Pandas 转换某些行

转载 作者:太空宇宙 更新时间:2023-11-04 00:19:44 31 4
gpt4 key购买 nike

我有一个 Pandas DataFrame。我正在尝试操纵一列来显示月数。如果记录是 01m,则将其设为 1。否则,如果它是 01y,则乘以 1 x 12 得到 12。但是有时我确实有一个名为 的字段_variable_value 我想保留原样。 (忽略)

当前的 dataframe 看起来像这样:

      institution_short_name            product_name             Term  term
0 One Standard _01y_value 4.85
1 One Standard _02y_value 5.15
2 One Standard _03y_value 5.49
3 One Standard _04y_value 5.89
4 One Standard _05y_value 6.09
5 One Standard _06m_value 4.99
6 One Standard _18m_value 5.15
7 One Standard _variable_value 5.79

我目前遇到一个错误,因为它正在尝试将 'va' 转换为 int,这是不可能的。

df['Time'] = np.where(df['Time'].str.contains("y"), df['Time'].map(lambda x: str(x)[1:3]).astype(int).apply(lambda x: x*12), df['Time'].map(lambda x: str(x)[1:3]).astype(int))

这是我的预期输出:

      institution_short_name            product_name             Term  term
0 One Standard 12 4.85
1 One Standard 24 5.15
2 One Standard 36 5.49
3 One Standard 48 5.89
4 One Standard 60 6.09
5 One Standard 6 4.99
6 One Standard 18 5.15
7 One Standard _variable_value 5.79

最佳答案

一种使用 str.replace 和正则表达式的方法:

df['Time'] = df.Time.str.replace(
r"_(\d{2})([ym]).*",
lambda m: str(int(m.group(1)) * (12 if m.group(2) == "y" else 1))
)

df

# institution_short_name product_name Time term
#0 One Standard 12 4.85
#1 One Standard 24 5.15
#2 One Standard 36 5.49
#3 One Standard 48 5.89
#4 One Standard 60 6.09
#5 One Standard 6 4.99
#6 One Standard 18 5.15
#7 One Standard _variable_value 5.79

_(\d{2})([ym]).* 匹配以 _ + 两位数字 + y 或 m 开头的字符串,并捕获数字并将单位分为两个不同的组;基于单位,你可以通过引用lambda函数中的组来根据需要修改匹配的数值;与模式不匹配的情况,如 _variable_value 将被忽略。

关于python - 仅使用 Pandas 转换某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49621811/

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