python - Pandas concat ignore_index 不起作用

标签 python pandas append concat

我正在尝试对数据帧进行列绑定(bind),但遇到了 pandas concat 问题,因为 ignore_index=True 似乎不起作用:

df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                    'B': ['B0', 'B1', 'B2', 'B3'],
                    'D': ['D0', 'D1', 'D2', 'D3']},
                    index=[0, 2, 3,4])

df2 = pd.DataFrame({'A1': ['A4', 'A5', 'A6', 'A7'],
                    'C': ['C4', 'C5', 'C6', 'C7'],
                    'D2': ['D4', 'D5', 'D6', 'D7']},
                    index=[ 5, 6, 7,3])
df1
#     A   B   D
# 0  A0  B0  D0
# 2  A1  B1  D1
# 3  A2  B2  D2
# 4  A3  B3  D3

df2
#    A1   C  D2
# 5  A4  C4  D4
# 6  A5  C5  D5
# 7  A6  C6  D6
# 3  A7  C7  D7

dfs = [df1,df2]
df = pd.concat( dfs,axis=1,ignore_index=True)     
print df   

结果是

     0    1    2    3    4    5    
0   A0   B0   D0  NaN  NaN  NaN  
2   A1   B1   D1  NaN  NaN  NaN    
3   A2   B2   D2   A7   C7   D7   
4   A3   B3   D3  NaN  NaN  NaN  
5  NaN  NaN  NaN   A4   C4   D4  
6  NaN  NaN  NaN   A5   C5   D5  
7  NaN  NaN  NaN   A6   C6   D6           

即使我使用重置索引

 df1.reset_index()    
 df2.reset_index() 

然后尝试

pd.concat([df1,df2],axis=1) 

它仍然产生相同的结果!

最佳答案

如果我理解正确,这就是你想做的。

import pandas as pd

df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                    'B': ['B0', 'B1', 'B2', 'B3'],
                    'D': ['D0', 'D1', 'D2', 'D3']},
                    index=[0, 2, 3,4])

df2 = pd.DataFrame({'A1': ['A4', 'A5', 'A6', 'A7'],
                    'C': ['C4', 'C5', 'C6', 'C7'],
                    'D2': ['D4', 'D5', 'D6', 'D7']},
                    index=[ 4, 5, 6 ,7])


df1.reset_index(drop=True, inplace=True)
df2.reset_index(drop=True, inplace=True)

df = pd.concat( [df1, df2], axis=1) 

这给出了:

    A   B   D   A1  C   D2
0   A0  B0  D0  A4  C4  D4
1   A1  B1  D1  A5  C5  D5
2   A2  B2  D2  A6  C6  D6
3   A3  B3  D3  A7  C7  D7

实际上,我希望 df = pd.concat(dfs,axis=1,ignore_index=True) 给出相同的结果。

这是 jreback 的精彩解释:

ignore_index=True ‘ignores’, meaning doesn’t align on the joining axis. it simply pastes them together in the order that they are passed, then reassigns a range for the actual index (e.g. range(len(index))) so the difference between joining on non-overlapping indexes (assume axis=1 in the example), is that with ignore_index=False (the default), you get the concat of the indexes, and with ignore_index=True you get a range.

关于python - Pandas concat ignore_index 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32801806/

相关文章:

python - 在包含 M*N 个混洗元素的列表中找到 N 个元素的 M 个算术序列

python - 如果任何列包含关键字之一,则删除行

python - 在 python pandas 中重新编码数据

python - 问题: "argument of type ' float' is not iterable"when iterate rows in Pandas

r - append 到 R 中的列表会导致复制吗?

jquery - 为什么 jQuery 追加会重复我的内容?

python - 有没有办法让numpy矩阵来存储对象?

python - 使用 eval() 函数,如何评估 python 中观察到的代码的表达式

Python 正则表达式匹配 isalnum() 和 isspace() 的任意组合,但不匹配两个同时换行符

javascript - 使用 isOnScreen 检查元素是否在视口(viewport)中