我有一个pandas.DataFrame
对象,我想将其折叠为一行,以便将每个前一列的值都转换为列表。
有没有比使用.agg
和传递分配了每个列名称的字典便宜的方法了list
?
这是我的数据:
指数 | 第1栏 | 专栏2 |
---|---|---|
0 | 一种 | d |
1个 | 乙 | E |
这是我想要的输出:
指数 | 第1栏 | 专栏2 |
---|---|---|
0 | [A,B] | [D,E] |
注意:索引不相关。
假设您的数据如下所示:
df = pd.DataFrame({'col1':['A','B','C','D','E'],
'col2':['F','G','H','I','J']})
print(df)
col1 col2
0 A F
1 B G
2 C H
3 D I
4 E J
# Turn the columns to an index and drop the old one
df = df.stack().reset_index(level=0, drop=True)
# Turn the values of each column into lists and transpose the result
df.groupby(df.index).apply(list).to_frame().transpose()
for
循环将列折叠为列表:# Create a dummy data frame to fill in
df2 = df[0:1].copy()
# Fill in the dataset with the collapsed columns
for col in df.columns:
df2.loc[0, col] = df[col].tolist()
两种解决方案均会导致以下结果:
col1 col2
0 [A, B, C, D, E] [F, G, H, I, J]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句