假设你的行总是有 'a' 列值,你可以这样做:
#standard imports
import pandas as pd
initial = pd.DataFrame(
{
'Column1' : [
'a',
'b',
'c',
'd',
'a',
'b',
'a',
'c',
'd'
],
'Column2':[
'12',
't1',
't3',
'798',
'87',
'g1',
'478',
'f1',
'906'
]
}
)
pivoted = initial.pivot(columns='Column1', values='Column2')
target = pivoted.groupby(pivoted.apply(lambda x: 1 if x[0]!=None else 0, axis=1).cumsum())[pivoted.columns].agg(lambda x: ''.join([el for el in x if el!=None]))
如果您可以缺少“a”值,那么它会变得更加棘手。这就是为什么在您的问题中提供具有代表性的示例如此重要的原因。
编辑:
迭代方法,如果您可以连续有不存在的 'a' 值:
#use `initial` dataframe from answer above
target = pd.DataFrame(columns=['a', 'b', 'c', 'd'])
newrow = dict()
for index, row in initial.iterrows():
if row['Column1'] in newrow:
target=target.append(newrow, ignore_index=True)
newrow=dict()
newrow[row['Column1']]=row['Column2']
target=target.append(newrow, ignore_index=True)