【问题标题】:Pandas - How to convert row data to columns [closed]Pandas - 如何将行数据转换为列[关闭]
【发布时间】:2019-12-06 12:45:07
【问题描述】:

我想使用一列 (No) groupby 我的数据,并将列 date1results 的每个结果保存在不同的列中。

这里是一个输入的例子和相应的预期输出:

enter image description here

我添加了更多数据。还有很多数据。

【问题讨论】:

  • 请将您的数据以数据而非图像的形式呈现。见:stackoverflow.com/questions/20109391/…
  • 有更多可用数据和固定代码....... df = pd.DataFrame({'No.' : df['date_1'], 'date_1' : [datetime. now() for x in range(3)], 'results' : df['results']})
  • 然后将更多数据和固定代码添加到问题正文中,而不是在评论中
  • ...为什么一个问题在两个用户已经理解并回答后会被搁置?

标签: python pandas pandas-groupby


【解决方案1】:

这是一种方法:

from datetime import datetime

df = pd.DataFrame({'No.' : ['s1', 's2', 's2'], 'date_1' : [datetime.now() for x in range(3)],
                  'results' : [1.2, 9.73, 3.71]})

# Use groupby to get the lists of dates and result
result = df.groupby('No.')[['date_1', 'results']].agg({'date_1' : list, 'results' : list})
# if you are running a pandas version <0.24.2 uncomment the following line and comment the one above
#result = df.groupby('No.')[['date_1', 'results']].agg({'date_1' : lambda x: list(x), 'results' : lambda x: list(x)})

# Look at the number of columns we will have to create
len_max = np.max([len(x) for x in result['results']])

# Create all the required columns  
for i in range(1,len_max):
    result['date__{}'.format(i+1)] = [x[i] if len(x)>i else 0 for x in result['date_1']]
    result['results_{}'.format(i+1)] = [x[i] if len(x)>i else 0 for x in result['results']]

# Modify the first  two columns that still contain the lists of the groupby
result['date_1'] = [x[0] for x in result['date_1']]
result['results'] = [x[0] for x in result['results']]

输出:

                        date_1  results                     date__2  results_2
No.                                                                           
s1  2019-07-29 08:00:45.878494     1.20                           0       0.00
s2  2019-07-29 08:00:45.878499     9.73  2019-07-29 08:00:45.878500       3.71

【讨论】:

  • 这个运行时不会报错吧?
  • 不是我的,运行代码时出现什么错误?
  • 我运行的是 0.24.2,很多关于 groupby 功能的工作都是在 0.24 中完成的。尝试将您的 pandas 版本至少升级到 0.24,代码应该可以正常工作。否则,如果您无法升级熊猫版本,我会添加 @ItamarMushkin 修复
  • 我在 0.21.1。当然最好使用list关键字,只是提醒使用旧版本的读者。
  • 感谢您的帮助。
【解决方案2】:

以 vlemaistre 的回答为基础 - 您可以采用更紧凑的方式:

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
df = pd.DataFrame({'No.' : ['s1', 's2', 's2'], 'date' : [datetime.now()+timedelta(days=x) for x in range(3)],
                  'results' : [1.2, 9.73, 3.71]})

joint_df = df.groupby('No.')[['date', 'results']].agg(lambda x: list(x))
result = pd.DataFrame(index=joint_df.index)
for column in df.columns.difference({'No.'}):
    result = result.join(pd.DataFrame.from_records(
        list(joint_df[column]), index=joint_df.index).rename(lambda x: column+str(x+1), axis=1), how='outer')

输出是:

    date1                       date2                       results1    results2
No.             
s1  2019-07-29 12:58:28.627950  NaT                         1.20        NaN
s2  2019-07-30 12:58:28.627957  2019-07-31 12:58:28.627960  9.73        3.71

【讨论】:

  • 小心 OP 不想有重复的 s2 行
  • 谢谢!我已经更改了答案,所以没有重复。
猜你喜欢
  • 2020-12-21
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 2020-12-19
相关资源
最近更新 更多