首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在熊猫数据栏中重新排列行

在熊猫数据栏中重新排列行
EN

Stack Overflow用户
提问于 2018-05-11 01:03:03
回答 2查看 117关注 0票数 2

我正在努力寻找一些优雅的方法来重新安排熊猫的数据。

我的初始数据看起来如下所示:

代码语言:javascript
复制
    PS  PSS 10PS 10PSS  5PS 5PSS
1   6   263 5    23     2   101
2   5   49  2    30     1   30

所希望的安排是:

代码语言:javascript
复制
  1-PS  1-PSS 1-10PS 1-10PSS  1-5PS 1-5PSS 2-PS  2-PSS 2-10PS 2-10PSS 2-5PS 2-5PSS 
A 6     263   5      23       2      101   5     49     2     30      1     30  

其中,A是一个新的索引,我希望将行与列合并。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-11 02:12:28

这里需要stack,并使用列联接

代码语言:javascript
复制
s=df.stack().to_frame('A')
s.index=s.index.map('{0[0]}-{0[1]}'.format) 
s.T
Out[42]: 
   1-PS  1-PSS  1-10PS  1-10PSS  1-5PS  1-5PSS  2-PS  2-PSS  2-10PS  2-10PSS  \
A     6    263       5       23      2     101     5     49       2       30   
   2-5PS  2-5PSS  
A      1      30  
票数 1
EN

Stack Overflow用户

发布于 2018-05-11 01:13:58

希望这些台词能帮到你:

代码语言:javascript
复制
# Put a pandas Series from each line in a generator
series = (pd.Series(i, index=['{}-{}'.format(ind,x) for x in df.columns]) 
          for ind, i in zip(df.index,df.values))

# Concatenate and convert to frame + transpose
df = pd.concat(series).to_frame('A').T

完整的例子:

代码语言:javascript
复制
import pandas as pd

data = '''\
index    PS  PSS 10PS 10PSS  5PS 5PSS
1   6   263 5    23     2   101
2   5   49  2    30     1   30'''

df = pd.read_csv(pd.compat.StringIO(data), sep='\s+').set_index('index')

# Put a pandas Series from each line in a generator
series = (pd.Series(i, index=['{}-{}'.format(ind,x) for x in df.columns]) 
          for ind, i in zip(df.index,df.values))

# Concatenate and convert to frame + transpose
df = pd.concat(series).to_frame('A').T
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50283539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档