gpt4 book ai didi

python - 使用许多 Pandas 列创建一个新列的字符串格式

转载 作者:行者123 更新时间:2023-12-04 01:31:25 27 4
gpt4 key购买 nike

我想在 Pandas DataFrame 中创建一个新列,就像我使用 python f-Strings 或 format 函数一样。
下面是一个例子:

df = pd.DataFrame({"str": ["a", "b", "c", "d", "e"],
"int": [1, 2, 3, 4, 5]})

print(df)

str int
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5

我想获得:
  str  int concat
0 a 1 a-01
1 b 2 b-02
2 c 3 c-03
3 d 4 d-04
4 e 5 e-05

所以像:
concat = f"{str}-{int:02d}"

但直接使用 Pandas 列的元素。我想解决方案是使用 pandas map、apply、agg 但没有成功。

非常感谢您的帮助。

最佳答案

使用 lsit comprehension 和 f-string s:

df['concat'] = [f"{a}-{b:02d}" for a, b in zip(df['str'], df['int'])]

或者可以使用 apply :
df['concat'] = df.apply(lambda x: f"{x['str']}-{x['int']:02d}", axis=1)

或来自 Series.str.zfill 评论的解决方案:
df["concat"] = df["str"] + "-" + df["int"].astype(str).str.zfill(2)
print (df)
str int concat
0 a 1 a-01
1 b 2 b-02
2 c 3 c-03
3 d 4 d-04
4 e 5 e-05

关于python - 使用许多 Pandas 列创建一个新列的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60945542/

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