我要向df.Dataframe
添加新列,如下所示:
VAL001
VAL002
VAL003
...
...
...
VAL498
VAL499
VAL500
我想知道有没有一种方法可以快速生成它,而不必一一键入。
答案 0 :(得分:2)
将list comprehension
与zfill
一起使用:
df['New Column'] = ['VAL'+str(i).zfill(3) for i in range(1,501)]
或:
df['New Column'] = [str(i).zfill(3) for i in range(1,501)]
df['New Column'] = 'VAL'+df['New Column']
或:
df['New Column'] = range(1,501)
df['New Column'] = 'VAL'+df['New Column'].astype('str').str.zfill(3)
答案 1 :(得分:2)
初始化users: [{
Username: "test1",
sub: "1234",
email: "test1@gmail.com}, {
Username: "test2",
sub: "5678",
email: "test2@gmail.com}]
(或Private Sub btnTotal_Click(sender As Object, e As EventArgs) Handles btnTotal.Click
itemcost(0) = Convert.ToUInt32(txtClassic.Text) * 15000
itemcost(1) = Convert.ToUInt32(txtGreentea.Text) * 15000
itemcost(2) = Convert.ToUInt32(txtBlacksesame.Text) * 15000
itemcost(3) = Convert.ToUInt32(txtPeppermint.Text) * 15000
)中的序列,并使用range
填充左侧的零:
arange
将str.zfill
更改为所需的输出。
答案 2 :(得分:2)
借用cs95's进行设置
'VAL'+s.str.pad(width=3,fillchar='0')
Out[404]:
0 VAL001
1 VAL002
2 VAL003
3 VAL004
4 VAL005
5 VAL006
6 VAL007
7 VAL008
8 VAL009
9 VAL010
dtype: object
答案 3 :(得分:1)
您可以使用以下代码在不一一键入的情况下生成值:
import pandas as pd
lst=[('VAL'+('%0*d' % (3,i+1))) for i in range(500)]
df=pd.DataFrame(lst)
print(df)
输出:
0
0 VAL001
1 VAL002
2 VAL003
3 VAL004
4 VAL005
5 VAL006
.. ...
495 VAL496
496 VAL497
497 VAL498
498 VAL499
499 VAL500
[500 rows x 1 columns]