Python 如何将数据帧转换为新格式?

Python 如何将数据帧转换为新格式?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据帧: import pandas as pd df = pd.DataFrame({'cell': ['A1', 'A2', 'B1', 'A3', 'B2', 'B3', 'A4', 'B4'], 'site': ['A', 'A', 'B', 'A', 'B', 'B', 'A', 'B']}) >>> df cell site 0 A1 A 1 A2 A 2 B1 B 3 A3

我有一个数据帧:

import pandas as pd

df = pd.DataFrame({'cell': ['A1', 'A2', 'B1', 'A3', 'B2', 'B3', 'A4', 'B4'],
                   'site': ['A', 'A', 'B', 'A', 'B', 'B', 'A', 'B']})

>>> df

  cell site
0   A1    A
1   A2    A
2   B1    B
3   A3    A
4   B2    B
5   B3    B
6   A4    A
7   B4    B
我想获得新的格式:

A
A1
A2
A3
A4
B
B1
B2
B3
B4
现在我想转换回这个结果,但我无法进行转换。

选项1
魔方

print(
    df.groupby('site')
      .cell.apply(list)
      .apply(pd.Series)
      .reset_index()
      .stack()
      .reset_index(drop=True)
)
选项2
理解力

pd.Series(
    np.concatenate(
        [[name] + grp.tolist() for name, grp in df.groupby('site').cell]))

两者都屈服

0     A
1    A1
2    A2
3    A3
4    A4
5     B
6    B1
7    B2
8    B3
9    B4
dtype: object
您可以与和一起使用:

或者使用
numpy方法
-和:

如果无法使用
排序
的另一种解决方案-使用自定义功能:

df =  df.groupby('site').cell
        .apply(lambda x: pd.Series([x.name] + x.values.tolist()))
        .reset_index(drop=True)
print (df)
0     A
1    A1
2    A2
3    A3
4    A4
5     B
6    B1
7    B2
8    B3
9    B4
Name: cell, dtype: object

你好欢迎光临。请阅读并提供答案。好吧,我很抱歉learning@piRSquared-晚安,家务对我来说也不愉快;)
df = pd.Series(np.sort(np.concatenate([df.cell.values, df.site.unique()])))
print (df)
0     A
1    A1
2    A2
3    A3
4    A4
5     B
6    B1
7    B2
8    B3
9    B4
dtype: object
df =  df.groupby('site').cell
        .apply(lambda x: pd.Series([x.name] + x.values.tolist()))
        .reset_index(drop=True)
print (df)
0     A
1    A1
2    A2
3    A3
4    A4
5     B
6    B1
7    B2
8    B3
9    B4
Name: cell, dtype: object
print pd.melt(df).iloc[:, 1].drop_duplicates().sort_values().reset_index(drop=True)

0     A
1    A1
2    A2
3    A3
4    A4
5     B
6    B1
7    B2
8    B3
9    B4