拼接并组合两列以形成新的数据帧(Pandas)

2024-09-28 03:15:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要把我的熊猫数据帧转换成一个奇怪的列表。我有以下熊猫数据帧示例:

输入数据帧:

mydf= pd.DataFrame.from_dict({'ARS':['xx2','xx3','xx1'], 'xyz':['yy1','xx2','xx3'], 'ppp':['xx3','yy2','xx2']}, orient='columns')
mydf= mydf.stack().reset_index()
mydf.columns= ['list1','list2','list3']
newdf= mydf[['list2','list3']]
newdf

  list2 list3
0   ARS   xx2
1   ppp   xx3
2   xyz   yy1
3   ARS   xx3
4   ppp   yy2
5   xyz   xx2
6   ARS   xx1
7   ppp   xx2
8   xyz   xx3

所需数据帧:

^{pr2}$

有没有人有一个简单的熊猫转换方法?


Tags: columns数据列表pppxyzlist2arsmydf
2条回答

以下是我的尝试:

In [173]: v = np.concatenate(
     ...:         pd.DataFrame(
     ...:             newdf.groupby('list2')['list3'].apply(lambda x: [x.name] + x.values.tolist()))
     ...:           .values
     ...:           .reshape(-1,)
     ...: )

In [174]: pd.DataFrame({'col':v})
Out[174]:
    col
0   ARS
1   xx2
2   xx3
3   xx1
4   ppp
5   xx3
6   yy2
7   xx2
8   xyz
9   yy1
10  xx2
11  xx3

我相信一定有更优雅的解决方案。在

以下是Pandas使用groupbypd.concat和索引的方法:

(newdf.groupby('list2',as_index=False)
     .apply(lambda x: pd.concat([pd.Series(x.iloc[0]['list2']),
                                 pd.Series(x.loc[:,'list3'])]))
    .reset_index(drop=True))

输出:

^{pr2}$

如果您真的想要那个“>;”符号,请使用以下内容:

(newdf.groupby('list2',as_index=False)
     .apply(lambda x: pd.concat([pd.Series('>'+x.iloc[0]['list2']),
                                 pd.Series(x.loc[:,'list3'])]))
    .reset_index(drop=True))

输出:

0     >ARS
1      xx2
2      xx3
3      xx1
4     >ppp
5      xx3
6      yy2
7      xx2
8     >xyz
9      yy1
10     xx2
11     xx3
dtype: object

相关问题 更多 >

    热门问题