python pandas 连接索引列标签
python pandas concat- reindex column labels
我有两个数据帧,我想将它们 column-wise 连接在一起。他们没有headers。所以第一个数据框的列被标记为 0-356。第二个 df 是单列并标记为 0.
DF1
0 1 2 3 ..356
1 1 1 2 3 4
2 5 7 8 9 10
3 11 12 13 14 15
DF2
0
1 76
2 77
3 78
当我结合 concat
DF3=pd.concat([DF1, DF2],axis=1)
我得到两列标记为 0
DF3
0 0 1 2 3 ...356
1 76 1 1 2 3 4
2 77 5 7 8 9 10
3 78 11 12 13 14 15
有两个“0”列显然会在以后的分析中给我带来问题。
如何更改或重新索引以便我在 DF3 中的列被标记为 0-357?
您需要传递 ignore_index=True
,如果发生冲突,这将重新索引 rhs:
In [39]:
pd.concat([df,df1], axis=1, ignore_index=True)
Out[39]:
0 1 2 3 4 5
1 1 1 2 3 4 76
2 5 7 8 9 10 77
3 11 12 13 14 15 78
与默认值比较,如果您不传递参数,则默认值为 False
:
In [40]:
pd.concat([df,df1], axis=1)
Out[40]:
0 1 2 3 4 0
1 1 1 2 3 4 76
2 5 7 8 9 10 77
3 11 12 13 14 15 78
重命名 concat
之后的列,如下所示:
import numpy as np
import pandas as pd
df1 =pd.DataFrame(np.random.rand(3,1))
df2 =pd.DataFrame(np.random.rand(3,356))
df3 =pd.concat([df1,df2],axis=1)
df3.columns = range(357)
我有两个数据帧,我想将它们 column-wise 连接在一起。他们没有headers。所以第一个数据框的列被标记为 0-356。第二个 df 是单列并标记为 0.
DF1
0 1 2 3 ..356
1 1 1 2 3 4
2 5 7 8 9 10
3 11 12 13 14 15
DF2
0
1 76
2 77
3 78
当我结合 concat
DF3=pd.concat([DF1, DF2],axis=1)
我得到两列标记为 0
DF3
0 0 1 2 3 ...356
1 76 1 1 2 3 4
2 77 5 7 8 9 10
3 78 11 12 13 14 15
有两个“0”列显然会在以后的分析中给我带来问题。
如何更改或重新索引以便我在 DF3 中的列被标记为 0-357?
您需要传递 ignore_index=True
,如果发生冲突,这将重新索引 rhs:
In [39]:
pd.concat([df,df1], axis=1, ignore_index=True)
Out[39]:
0 1 2 3 4 5
1 1 1 2 3 4 76
2 5 7 8 9 10 77
3 11 12 13 14 15 78
与默认值比较,如果您不传递参数,则默认值为 False
:
In [40]:
pd.concat([df,df1], axis=1)
Out[40]:
0 1 2 3 4 0
1 1 1 2 3 4 76
2 5 7 8 9 10 77
3 11 12 13 14 15 78
重命名 concat
之后的列,如下所示:
import numpy as np
import pandas as pd
df1 =pd.DataFrame(np.random.rand(3,1))
df2 =pd.DataFrame(np.random.rand(3,356))
df3 =pd.concat([df1,df2],axis=1)
df3.columns = range(357)