如何用零分隔我的数据帧的象限

时间:2017-09-15 06:38:36

标签: python pandas numpy

考虑我的数据框09-15 16:20:34.277 10119-10119/com.example D/MATCH: +19447223311 09-15 16:20:34.277 10119-10119/com.example D/MATCH: 872881122

df

如何将数据框的象限与零分开

df = pd.DataFrame(np.ones((4, 4), dtype=int), list('ABDE'), list('VWYZ'))

df

   V  W  Y  Z
A  1  1  1  1
B  1  1  1  1
D  1  1  1  1
E  1  1  1  1

4 个答案:

答案 0 :(得分:4)

一种丑陋的方式是

In [860]: df.insert(df.shape[1]/2, 'X', 0)

In [861]: df.reindex(df.index.insert(df.shape[0]/2, 'C'), fill_value=0)
Out[861]:
   V  W  X  Y  Z
A  1  1  0  1  1
B  1  1  0  1  1
C  0  0  0  0  0
D  1  1  0  1  1
E  1  1  0  1  1

,另一位来自Divarkar的灵感来自

In [897]: df.reindex(index=df.index.insert(df.shape[0]/2, 'C'),
                     columns=df.columns.insert(df.shape[1]/2, 'X'), fill_value=0)
Out[897]:
   V  W  X  Y  Z
A  1  1  0  1  1
B  1  1  0  1  1
C  0  0  0  0  0
D  1  1  0  1  1
E  1  1  0  1  1

答案 1 :(得分:3)

df['X'] = 0
df.loc['C'] = [0]*len(df.columns)
df = df.sort_index()
df = df[[sorted(df.columns)]]

如果我无法对标签进行排序,那么:

df['X'] = 0
col = list(df.columns)
col.insert(len(col)/2,'X')
df = df[col[:-1]]
df.loc['C'] = 0
rows = list(df.index)
rows.insert(len(df)/2,'C')
df.reindex(rows[:-1])

答案 2 :(得分:2)

这是一个带有数组的数组,用np.ix_ -

创建要插入的地方网格
a = df.values
m,n = a.shape
mask_row = np.r_[:m//2+1,m//2-1:-1:-1] < m//2
mask_col = np.r_[:n//2+1,n//2-1:-1:-1] < n//2

out = np.zeros((m+1,n+1), dtype=a.dtype)
out[np.ix_(mask_row, mask_col)] = a
df_out = pd.DataFrame(out)
df_out.columns = np.insert(df.columns, n//2, 'New')
df_out.index = np.insert(df.index, m//2, 'New')

示例输出 -

In [375]: df_out
Out[375]: 
     V  W  New  Y  Z
A    1  1    0  1  1
B    1  1    0  1  1
New  0  0    0  0  0
D    1  1    0  1  1
E    1  1    0  1  1

答案 3 :(得分:1)

创建新的索引和列值,然后reindex

a = int(len(df.columns) / 2)
cols =np.concatenate([df.columns[:a], ['X'], df.columns[a:]])
b = int(len(df.index) / 2)
idx =np.concatenate([df.index[:b], ['C'], df.index[b:]])

df = df.reindex(index=idx, columns=cols, fill_value=0)
print (df)
   V  W  X  Y  Z
A  1  1  0  1  1
B  1  1  0  1  1
C  0  0  0  0  0
D  1  1  0  1  1
E  1  1  0  1  1