mystery man
mystery man

Reputation: 437

Insert a row in a pandas dataframe without changing to a list in Python

How would you insert a variable with the same parameters as the dataframe between position 1 and 2 without turning it into a list?

I've tried df=(df.ix[:1],foo,df.ix[2:]) but type(df) returns as list, meaning that I cant then perform pandas functions on it.

Upvotes: 3

Views: 2061

Answers (2)

B. M.
B. M.

Reputation: 18628

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

Upvotes: 1

jezrael
jezrael

Reputation: 862481

You can use setting with enlargement with 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

Solution with 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

Upvotes: 2

Related Questions