如何将此数据帧转换为此数据帧?

2024-10-02 02:38:44 发布

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

如何将df1转换为df2

df1 = pd.DataFrame(
  {
  'item1_aspect1' : ["a", "b", "c"],
  'item1_aspect2' : [1,2,3],
  'item1_aspect3' : ["[12,34]", "[56,78]", "[99,10]"],
  'item2_aspect1' : ["a", "b", "c"],
  'item2_aspect2' : [1,2,3],
  'item2_aspect3' : ["[12,34]", "[56,78]", "[99,10]"],
  'item3_aspect1' : ["a", "b", "c"],
  'item3_aspect2' : [1,2,3],
  'item3_aspect3' : ["[12,34]", "[56,78]", "[99,10]"]
  })


df2 = pd.DataFrame({
  'aspect_1' : ["a", "b", "c", "a", "b", "c", "a", "b", "c"],
  'aspect_2' : [1,2,3,1,2,3,1,2,3],
  'aspect_3' : ["[12,34]", "[56,78]", "[99,10]", "[12,34]", "[56,78]", "[99,10]", "[12,34]", "[56,78]", "[99,10]"]
})

也就是说,列名是一个拆分成行的标识符。我不知道怎么做


Tags: dataframe标识符pddf1df2item1aspectitem2
3条回答

我们需要首先调整列类型,然后调整wide_to_long

df1.columns=df1.columns.str.split('_').map(lambda x : '_'.join(x[::-1]))

yourdf=pd.wide_to_long(df1.reset_index(),
                       ['aspect1','aspect2','aspect3'], 
                       i ='index', 
                       j = 'drop', 
                       sep = '_',suffix='\w+').reset_index(drop=True)
Out[137]: 
  aspect1  aspect2  aspect3
0       a        1  [12,34]
1       b        2  [56,78]
2       c        3  [99,10]
3       a        1  [12,34]
4       b        2  [56,78]
5       c        3  [99,10]
6       a        1  [12,34]
7       b        2  [56,78]
8       c        3  [99,10]

下面是一个相当简单的方法:

df1.columns = [c[6:] for c in df1.columns]
pd.concat([df1.iloc[:, 0:3], df1.iloc[:, 3:6], df1.iloc[:, 6:9]], axis=0)

输出为:

  aspect1  aspect2  aspect3
0       a        1  [12,34]
1       b        2  [56,78]
2       c        3  [99,10]
0       a        1  [12,34]
1       b        2  [56,78]
...

如果您想坚持使用pandas操作,就不要一直更改数据类型,而更喜欢列表理解。。 试试这个方法-

lst = list(df1.columns)
n=3
new_cols = ['aspect_1', 'aspect_2', 'aspect_3']

#break the column list into groups of n = 3 in this case
chunks = [lst[i:i + n] for i in range(0, len(lst), n)]

#concatenate the list of dataframes over axis = 0after renaming columns of each 
pd.concat([df1[i].set_axis(new_cols, axis=1) for i in chunks], axis=0, ignore_index=True)
aspect_1    aspect_2    aspect_3
0   a   1   [12,34]
1   b   2   [56,78]
2   c   3   [99,10]
3   a   1   [12,34]
4   b   2   [56,78]
5   c   3   [99,10]
6   a   1   [12,34]
7   b   2   [56,78]
8   c   3   [99,10]

相关问题 更多 >

    热门问题