如何插入一个与位置1和2之间的数据框相同的变量而不将其变成列表的变量?
我已经尝试过df=(df.ix[:1],foo,df.ix[2:])
,但是type(df)
返回为list
,这意味着我不能在其上执行PANDAS功能。
您可以使用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
如果索引是一个范围,则可以:
一个简单的解决方案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