Dancer PhD
Dancer PhD

Reputation: 307

pandas data frame adding value to the dictionary

I would like to know what is the easiest way to add a row before the character. Concretely, I want to add a row before the each 'X' character in the data frame. Guys below is my code where I create data frame from the dictionary element and example what I need:

   # coding: utf-8

# In[1]:

import pandas as pd
df = pd.DataFrame({'Col1':['X','A','B','X','D','X','G','H','Z','X'],
                  'Col2':['B','C','L','E','O','W','F','P','Y','U'], 
                  'Col3':['4','5','1','1','1','1','3','4','3','8']})
df


# In[2]:

import pandas as pd
df = pd.DataFrame({'Col1':['new_r','X','A','B','new_r','X','D','new_r','X','G','H','Z','new_r','X'],
                  'Col2':['new_r','B','C','L','new_r','E','O','new_r','W','F','P','Y','new_r','U'], 
                  'Col3':['new_r','4','5','1','new_r','1','1','new_r','1','3','4','3','new_r','8']})
df


# In[ ]:

Please note that I import this from the CSV file

Upvotes: 0

Views: 43

Answers (1)

cs95
cs95

Reputation: 402263

Use np.flatnonzero + np.insert:

x = np.insert(df.values, np.flatnonzero(df.values[:, 0] == 'X'), 'new_r', axis=0)
pd.DataFrame(x, columns=df.columns)

     Col1   Col2   Col3
0   new_r  new_r  new_r
1       X      B      4
2       A      C      5
3       B      L      1
4   new_r  new_r  new_r
5       X      E      1
6       D      O      1
7   new_r  new_r  new_r
8       X      W      1
9       G      F      3
10      H      P      4
11      Z      Y      3
12  new_r  new_r  new_r
13      X      U      8

Upvotes: 2

Related Questions