Python 基于最新列修改Dataframe列
我的Python 基于最新列修改Dataframe列,python,pandas,Python,Pandas,我的pandas.DataFrame如下所示: runseq custid m6 m7 1 123 x y 1 345 y z 1 213 a b 2 123 a c 2 345 z w 2 213 x k 3 123 m n 3 345 o p 3
pandas.DataFrame
如下所示:
runseq custid m6 m7
1 123 x y
1 345 y z
1 213 a b
2 123 a c
2 345 z w
2 213 x k
3 123 m n
3 345 o p
3 213 a b
我希望所有以前的runseq
(1,2)m6
和m7
值都替换为最新的runseq
(3)。像这样:
runseq custid m6 m7
1 123 m n
1 345 o p
1 213 a b
2 123 m n
2 345 o p
2 213 a b
3 123 m n
3 345 o p
3 213 a b
如何实现这一点?这可以通过以下方式实现:
代码:
测试代码:
结果:
如果没有带(method='bfill'
)的最后一行,则可用于整形,然后用于NaNs
,最后用于整形返回:
df1 = df.pivot(index='runseq',columns='custid')
mask = pd.Series((df1.index == df['runseq'].iat[-1]), index=df1.index)
#if necessary add ffill for forward filling NaNs
#df1 = df1.where(mask).bfill().ffill().stack().reset_index()
df1 = df1.where(mask).bfill().stack().reset_index()
print (df1)
0 1 123 m n
1 1 213 a b
2 1 345 o p
3 2 123 m n
4 2 213 a b
5 2 345 o p
6 3 123 m n
7 3 213 a b
8 3 345 o p
另一个解决方案:
可用于重复转置值:
#columns for repaet
cols = ['m6','m7']
#get last value of column runseq
print (df['runseq'].iat[-1])
3
#create df1 with last group by filtering by boolean indexing
df1 = df.loc[df['runseq'] == df['runseq'].iat[-1], cols]
print (df1)
m6 m7
6 m n
7 o p
8 a b
#repeat values 3 times (length of groups by runseq) and assign back to columns
df[cols] = np.tile(df1.T.values, len(df['runseq'].unique())).transpose()
print (df)
runseq custid m6 m7
0 1 123 m n
1 1 345 o p
2 1 213 a b
3 2 123 m n
4 2 345 o p
5 2 213 a b
6 3 123 m n
7 3 345 o p
8 3 213 a b
对于每个runseq,您是否总是具有相同的custid值?如果是这样的话,那么这是一个很小的问题,因为答案中有很多重复的数据,并且有多种方法可以实现这一点。是的,custid值在所有runseq中都是相同的。在这种情况下,最简单的方法是删除除runseq=3之外的所有行,然后与原始数据合并。因此,我将仅为最新的
runseq
创建数据帧。然后将分别使用runseq
和custid
对2个数据帧进行marge,但m6
和m7
将保持不变。对的
custid runseq m6 m7
0 123 1 m n
1 345 1 o p
2 213 1 a b
3 123 2 m n
4 345 2 o p
5 213 2 a b
6 123 3 m n
7 345 3 o p
8 213 3 a b
df1 = df.pivot(index='runseq',columns='custid')
mask = pd.Series((df1.index == df['runseq'].iat[-1]), index=df1.index)
#if necessary add ffill for forward filling NaNs
#df1 = df1.where(mask).bfill().ffill().stack().reset_index()
df1 = df1.where(mask).bfill().stack().reset_index()
print (df1)
0 1 123 m n
1 1 213 a b
2 1 345 o p
3 2 123 m n
4 2 213 a b
5 2 345 o p
6 3 123 m n
7 3 213 a b
8 3 345 o p
#columns for repaet
cols = ['m6','m7']
#get last value of column runseq
print (df['runseq'].iat[-1])
3
#create df1 with last group by filtering by boolean indexing
df1 = df.loc[df['runseq'] == df['runseq'].iat[-1], cols]
print (df1)
m6 m7
6 m n
7 o p
8 a b
#repeat values 3 times (length of groups by runseq) and assign back to columns
df[cols] = np.tile(df1.T.values, len(df['runseq'].unique())).transpose()
print (df)
runseq custid m6 m7
0 1 123 m n
1 1 345 o p
2 1 213 a b
3 2 123 m n
4 2 345 o p
5 2 213 a b
6 3 123 m n
7 3 345 o p
8 3 213 a b