猿问

Pandas 合并列中的行

拥有这个数据框:


A      B                 C    D 

Train  Superfast         10   20 

NaN    Convernient       NaN NaN

NaN    Newest model      NaN NaN

NaN    Year 2002/099     NaN NaN

Car    Fastest           20   30

NaN    Can be more fast  NaN NaN

NsN    Year/2020/AYD     NaN NaN

是否可以将列中的行B向上移动到其他列中具有剩余值的行?


A      B                                                  C  D 

Train  Superfast Convernient Newest model Year 2002/099  10 20 

Car    Fastest Can be more fast Year/2020/AYD            20 30


蝴蝶刀刀
浏览 115回答 2
2回答

慕容森

让我们用cumsum它来识别块和分组:blocks = df['C'].notna().cumsum()agg_dict = {col:' '.join if col=='B' else 'first' for col in df}df.groupby(blocks).agg(agg_dict).reset_index(drop=True)输出:       A                                                 B     C     D0  Train  Superfast Convernient Newest model Year 2002/099  10.0  20.01    Car            Fastest Can be more fast Year/2020/AYD  20.0  30.0

肥皂起泡泡

一个有点复杂的解决方案,仅使用numpy,但对于大数据来说工作速度非常快:尝试在线运行它!import pandas as pd, numpy as np, mathdf = pd.DataFrame([&nbsp; &nbsp; ['Train', 'Superfast', 10, 20],&nbsp; &nbsp; [np.nan, 'Convernient', np.nan, np.nan],&nbsp; &nbsp; [np.nan, 'Newest model', np.nan, np.nan],&nbsp; &nbsp; [np.nan, 'Year 2002/099', np.nan, np.nan],&nbsp; &nbsp; ['Car', 'Fastest', 20, 30],&nbsp; &nbsp; [np.nan, 'Can be more fast', np.nan, np.nan],&nbsp; &nbsp; [np.nan, 'Year/2020/AYD', np.nan, np.nan],], columns = ['A', 'B', 'C', 'D'])a = df.valuesi = np.append(np.flatnonzero(~(a[:, 0] != a[:, 0])), a.shape[0])b = a[i[:-1], :]diffs = np.diff(i)maxs = np.amax(diffs)c = np.zeros([i.shape[0], maxs], dtype = np.str_)begs, ends = i[:-1], i[1:]for j in range(1, maxs):&nbsp; &nbsp; chosen = begs + j < ends&nbsp; &nbsp; b[chosen, 1] += ' ' + a[begs[chosen] + j, 1]df = pd.DataFrame(b, columns = df.columns.values.tolist())print(df)代码输出:&nbsp; &nbsp; &nbsp; &nbsp;A&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;B&nbsp; &nbsp;C&nbsp; &nbsp;D0&nbsp; Train&nbsp; Superfast Convernient Newest model Year 2002/099&nbsp; 10&nbsp; 201&nbsp; &nbsp; Car&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Fastest Can be more fast Year/2020/AYD&nbsp; 20&nbsp; 30
随时随地看视频慕课网APP

相关分类

Python
我要回答