In [37]: df = pd.DataFrame([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]])
In [38]: df2 = pd.concat([df, df])
In [39]: df2.reset_index()
Out[39]:
index 0 1 2 3
0 0 1 2 3 4
1 1 2 3 4 5
2 2 3 4 5 6
3 0 1 2 3 4
4 1 2 3 4 5
5 2 3 4 5 6
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果reset_index不添加新列,我该怎么index办?
一个经常遇到的问题是reset_index()返回一个副本,因此必须将其分配给另一个变量(或其本身)才能修改数据帧。您还可以使用该inplace=参数就地删除旧索引。
df = df.reset_index(drop=True)
# or
df.reset_index(drop=True, inplace=True)
df
Run Code Online (Sandbox Code Playgroud)
请记住,许多删除行或以其他方式更改索引(例如,dropna等)的 pandas 函数/方法都有参数,当设置为 True 时,会将索引重置为函数调用的一部分。例如,在OP中使用的示例中,简单地传递就避免了首先重置索引的需要。drop_duplicatespd.concatignore_indexignore_index=True
df2 = pd.concat([df, df], ignore_index=True) # <--- no need for `reset_index()`
Run Code Online (Sandbox Code Playgroud)