N = 10
作爲一個單一的步驟,你可以使用range
:
sample_data = pd.DataFrame({
'A': np.random.rand(N),
'B' : range(1, N + 1)}
)
print(sample_data)
A B
0 0.037303 1
1 0.693972 2
2 0.725926 3
3 0.110817 4
4 0.889411 5
5 0.138220 6
6 0.738190 7
7 0.695298 8
8 0.912171 9
9 0.601390 10
您可以使用enumerate
爲好,但你需要重新安排列:
sample_data = pd.DataFrame(list(enumerate(np.random.rand(N), 1)),
columns=['B', 'A'])[['A', 'B']]
print(sample_data)
A B
0 0.431247 1
1 0.004129 2
2 0.321802 3
3 0.866617 4
4 0.805049 5
5 0.767841 6
6 0.677050 7
7 0.293936 8
8 0.923059 9
9 0.953954 10
作爲替代方案,爲什麼不使用構造函數自動創建的索引?
sample_data = pd.DataFrame({
'A': np.random.rand(N)})
sample_data['B'] = sample_data.index + 1
print(sample_data)
A B
0 0.117788 1
1 0.177268 2
2 0.762664 3
3 0.667486 4
4 0.531079 5
5 0.291939 6
6 0.066751 7
7 0.497935 8
8 0.883126 9
9 0.598048 10
枚舉返回值的迭代器並不總是支持'len()'。 'enumerate('A',start = 1)'與iter([(1,'A')])'基本相同,這個迭代器只返回一個值,因爲字符串'A'具有一個項目,我不知道你想要什麼...... –