在Python中向pandas数据框插入行,而不将其转换为列表

3
您如何在位置1和2之间插入一个与数据框具有相同参数的变量而不将其转换为列表?
我尝试了 df=(df.ix[:1],foo,df.ix[2:]) 但是 type(df) 返回为 list,这意味着我不能对它执行pandas函数。

你能添加一些带有期望输出的示例吗? - jezrael
2个回答

2

您可以使用扩展设置loc

np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (df)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

foo = [10,20,55,44,22]
s = pd.Series(foo, index=df.columns)
print (s)
A    10
B    20
C    55
D    44
E    22
dtype: int64
#get s to position with index=2
pos = 2
#create new index shifted after pos
df.index = df.index[:pos].tolist() + (df.index[pos:] + 1).tolist()
#add s
df.loc[pos] = s
#sorting index
df = df.sort_index()
print (df)
    A   B   C   D   E
0   8   8   3   7   7
1   0   4   2   5   2
2  10  20  55  44  22
3   2   2   1   0   8
4   4   0   9   6   2
5   4   1   5   3   4

使用concat函数的解决方案:

pos = 2
df = pd.concat([df.iloc[:pos], s.to_frame().T, df.iloc[pos:]], ignore_index=True)
print (df)
    A   B   C   D   E
0   8   8   3   7   7
1   0   4   2   5   2
2  10  20  55  44  22
3   2   2   1   0   8
4   4   0   9   6   2
5   4   1   5   3   4

pos = 2
df = pd.concat([df.iloc[:pos], 
                pd.DataFrame([foo], columns=df.columns), 
                df.iloc[pos:]], ignore_index=True)
print (df)
    A   B   C   D   E
0   8   8   3   7   7
1   0   4   2   5   2
2  10  20  55  44  22
3   2   2   1   0   8
4   4   0   9   6   2
5   4   1   5   3   4

1
如果index是一个范围,一个简单的解决方案可以是:

if index is a range, a simple solution can be :

In [4]: df.loc[1.5]=foo=range(4) # to insert between 1 and 2

In [5]: df.sort_index().reset_index(drop=True)
Out[5]: 
          0         1         2         3
0  0.700147  0.707600  0.857018  0.658797
1  0.655653  0.531352  0.402190  0.497478
2  0.000000  1.000000  2.000000  3.000000
3  0.507261  0.520526  0.365726  0.019579

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接