我有下表,基于St_date
,En_date
是否为空,我们必须将Des
中的数据与即将出现的行合并,直到找到notnull
St_date En_date Des Ch Deb Cr Tot
0 01/06/18 01/06/18 CSH NaN NaN 1000 5786
1 NaN NaN DEPOSIT NaN NaN NaN NaN
2 01/06/18 01/06/18 DEP TFR NaN 100 Nan 5686
3 NaN NaN through NaN NaN NaN NaN
我想要的是这样的:
St_date En_date Des Ch Deb Cr Tot
0 01/06/18 01/06/18 CSH DEPOSIT NaN NaN 1000 5786
1 01/06/18 01/06/18 DEP TFR through NaN 100 Nan 5686
任何人都知道使用
pandas
怎么做? 最佳答案
您可以那样做(请注意,我认为St_Date Nan
就像下面答案中的空字符串一样):
# Add a field containing previous index if St_date is empty
df["idx"] = df.apply(lambda x: x.name if x.St_date!='' else None, axis=1).ffill()
df
应该返回这个:
St_date En_date Des Ch Deb Cr Tot idx
0 01/06/18 01/06/18 CSH nan nan 1000 5786 0.0
1 nan DEPOSIT nan nan nan nan 0.0
2 01/06/18 01/06/18 DEP TFR nan 100 nan 5686 2.0
3 nan through nan nan nan nan 2.0
然后,您可以将此新列分组并合并您的
Des
字段:dfg = pd.DataFrame(df.groupby('idx')["Des"].apply(lambda x: "{%s}" % ', '.join(x)))
# Then you merge the result with the original dataframe on index
df = pd.merge(df.drop('Des',axis=1), dfg , left_index=True, right_index=True, how='left')
# Filter rows with empty values in Des (not merged) and reset index
df = df[df.Des.isna()==False].reset_index(drop=True)
df
你去了:
St_date En_date Ch Deb Cr Tot idx Des
0 01/06/18 01/06/18 nan nan 1000 5786 0.0 {CSH, DEPOSIT}
1 01/06/18 01/06/18 nan 100 nan 5686 2.0 {DEP TFR, through}
关于python - 在 Pandas 中为行中的空单元格附加单元格值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53959258/