如何在连接后重新索引pandas DataFrame

时间:2016-07-14 14:53:33

标签: python pandas

假设我连接两个DataFrame,如下所示:

$1

生成的DataFrame import numpy as np import pandas as pd array1 = np.random.randn(3,3) array2 = np.random.randn(3,3) df1 = pd.DataFrame(array1, columns=list('ABC')) df2 = pd.DataFrame(array2, columns=list('ABC')) df = pd.concat([df1, df2]) 如下所示:

df

请注意,索引与原始DataFrame中的索引相同。我想重新编制 A B C 0 1.297362 0.745510 -0.206756 1 -0.056807 -1.875149 -0.210556 2 0.310837 -1.068873 2.054006 0 1.163739 -0.678165 2.626052 1 -0.557625 -1.448195 -1.391434 2 0.222607 -0.334348 0.672643 索引,以便索引只从df运行到0。我怎么能这样做?

(我已尝试5,但这会产生df = df.reindex(index = range(df.shape[0]))。这是因为原始轴包含重复项(两个ValueError: cannot reindex from a duplicate axis s,两个0 s等。) )。

2 个答案:

答案 0 :(得分:4)

您想将ContentPlaceHolderID="body"传递给concat

ignore_index=True

这将忽略现有的索引,因此实际上它为新连接的索引设置了从0开始的新索引

答案 1 :(得分:0)

使用EdChum的设置

  If Country = wbregion.Worksheets("Country").Name Then  'subscript out of range 
    For i = 1 To cntyn
      For j = 5 To forec
        If Cells(i, "A").value = rcell Then
           If Cells(i, "C").value = wbregion.Worksheets("Country").Cells(j, "B").value Then
              srange1 = "I" & j & ":" & "n" & j
              srange2 = "D" & i & ":" & "i" & i
              wsforecast.Range(srange2).Value2 = wsregion.Range(srange1).Value2
           End If
        End If
      Next j
     Next i
  End If
Next k

enter image description here