[英]Transformation in Pandas dataframe
I have a data frame (2 columns: Text and HD/TTL) in the format below:我有以下格式的数据框(2 列:文本和 HD/TTL):
Text HD/TTL
ABC HD
DEF
GHI HD
JKL
MNO
PQR HD
I want it transformed into a new data frame (with 2 columns: HD and Text) as:我希望它转换为一个新的数据框(有 2 列:HD 和 Text),如下所示:
HD Text
HD ABC\nDEF
HD GHI\nJKL\nMNO
HD PQR\n
where \n is the new line between the text.其中 \n 是文本之间的新行。 How can I go about it?我怎样才能了解它?
df
###
Text HD/TTL
0 ABC HD
1 DEF NaN
2 GHI HD
3 JKL NaN
4 MNO NaN
5 PQR HD
g = df['HD/TTL'].notnull().cumsum()
v = df.groupby(g).apply(lambda x: x['Text'].str.cat(sep='\\n'))
output = pd.DataFrame({'HD': df.groupby(g)['HD/TTL'].first().values, 'Text': v}).reset_index(drop=True)
output
###
HD Text
0 HD ABC\nDEF
1 HD GHI\nJKL\nMNO
2 HD PQR
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.