pandas数据框为字典添加值

时间:2017-10-26 09:02:43

标签: python pandas dictionary

我想知道在角色之前添加行的最简单方法是什么。具体来说,我想在数据框中的每个“X”字符前添加一行。下面的人是我的代码,我从字典元素创建数据框,并举例说明我需要的内容:

   # 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[ ]:

请注意,我是从CSV文件中导入的

1 个答案:

答案 0 :(得分:2)

使用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