将列值转换为标题熊猫

时间:2021-04-07 09:46:32

标签: python pandas dataframe

我有以下格式的 Pandas DataFrame

|Header|Text   |
|------|-------|
|  AB  |yale   |
|  BC  |grass  |
|  BC  |window |
|  AB  |school |
|  BC  |student|

我的期望是将该 DataFrame 转换为以下格式

|  AB  | BC    |
|------|-------|
| yale | grass |
| yale | window|
|school|student|

直到现在我似乎都找不到获得预期格式的方法。需要帮助。

1 个答案:

答案 0 :(得分:0)

使用 DataFrame.insert 作为第一列的新列,将 AB 列中的 HeaderSeries.eq 进行比较,并将 Text 的不匹配值替换为缺失值Series.where 与前向填充它们,然后通过比较 Series.ne 中的不相等并仅过滤 {{3} 中指定的列,如果 TextAB 列中的值相同,则重新生成行}:

df.insert(0, 'AB',  df['Text'].where(df['Header'].eq('AB')).ffill())
df = df.loc[df['Text'].ne(df['AB']), ['AB','Text']].rename(columns={'Text':'BC'})

print (df)
       AB       BC
1    yale    grass
2    yale   window
4  school  student