【发布时间】:2020-07-11 16:57:52
【问题描述】:
我想在 pandas DataFrame 中创建一个新列,就像使用 python f-Strings 或格式函数一样。 这是一个例子:
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 但没有成功。
非常感谢您的帮助。
【问题讨论】:
-
df["concat"] = df["str"]+"-"+(df["int"].astype(str).str.zfill(2))
标签: python string pandas formatting