pandas 将 Dataframe 中的一些列转换为 Dataframe 中列表的列

rbl8hiat  于 2023-01-15  发布在  其他
关注(0)|答案(2)|浏览(238)

我想把一些列转换为adataframe中的列表。
Dataframe df:

Name  salary  department  days other
     0  ben   1000     A           90   abc
     1  alex  3000     B           80    gf
     2  linn  600      C           55   jgj
     3  luke  5000     D           88    gg

所需输出df1:

Name    list       other
 0  ben   [1000,A,90]   abc
 1  alex  [3000,B,80]    gf
 2  linn  [600,C,55]    jgj
 3  luke  [5000,D,88]    gg
00jrzges

00jrzges1#

如果你想保持这个顺序,那么我们可以把它分成3个部分,就像@mozway在他的回答中提到的那样
1.定义我们想要分组的列(如@mozway在他的回答中提到的)
1.查找第一个元素的索引(您可以向前一步查找最小的一个,因为列表不一定按照DataFrame排序)
1.将系列插入到 Dataframe 中我们生成的位置

cols = ['salary', 'department', 'other']

first_location = df.columns.get_loc(cols[0])
list_values = pd.Series(df[cols].values.tolist()) # converting values to one list
df.insert(loc=first_location, column='list', value=list_values) # inserting the Series in the desired location
df = df.drop(columns=cols) # dropping the columns we grouped together.
print(df)

结果是:

Name           list other
0   ben  [1000, A, 90]   abc
1  alex  [3000, B, 80]    gf
...
kkbh8khc

kkbh8khc2#

您可以将列切片并转换为list的list,然后转换为Series

cols = ['salary', 'department', 'days']
out = (df.drop(columns=cols)
         .join(pd.Series(df[cols].to_numpy().tolist(), name='list', index=df.index))
      )

输出:

Name other           list
0   ben   abc  [1000, A, 90]
1  alex    gf  [3000, B, 80]
2  linn   jgj   [600, C, 55]
3  luke    gg  [5000, D, 88]

相关问题