python - 如何更改 pd DataFrame 的结构,将行值添加到列?

标签 python pandas dataframe

我有以下数据框

df = pd.DataFrame({'Date': ['2020-01-01', '2020-10-01', '2021-01-01', '2021-10-01'],
                   'ID': [101, 101, 102, 102],
                   'number': [10, 10, 11, 11]})

# currently looking like this

    Date        ID  number
0   2020-01-01  101 10
1   2020-10-01  101 10
2   2021-01-01  102 11
3   2021-10-01  102 11

有没有办法重组数据框,使其具有以下形式?

    Start Date  End Date    ID  number
0   2020-01-01  2020-10-01  101 10
1   2021-01-01  2021-10-01  102 11

最佳答案

我们可以使用Named AggregationGroupby aggregate获取每组的 minmax 日期并使用新名称进行设置。 reindex可以选择重新排序列以匹配显示的预期输出:

new_df = df.groupby(
    ['ID', 'number'], as_index=False
).aggregate(
    **{'Start Date': ('Date', 'min'), 'End Date': ('Date', 'max')}
).reindex(columns=['Start Date', 'End Date', 'ID', 'number'])

new_df:

   Start Date    End Date   ID  number
0  2020-01-01  2020-10-01  101      10
1  2021-01-01  2021-10-01  102      11

*需要字典解包 ** 才能允许重命名的列包含空格。

关于python - 如何更改 pd DataFrame 的结构,将行值添加到列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69867311/

相关文章:

python - 尝试使用 Boto3 从 S3 下载特定类型的文件 - TypeError : expected string or bytes-like object

python - PyDev 调试 : do not open "_pydev_execfile" at the end

python - Pandas:在检查另一列中一列的成员资格时创建 NaN?

python - 仅当所有元素都是 pandas 的 groupby 中的 NA 时,如何删除 NA

python - Pandas 根据不同的值移位来计算百分比

python - 如何在 Pandas 中创建多级数据框?

r - 如何在R中计算两个数据帧之间的Jaccard相似度

python - 将图像分割类输出转换为 tensorflow 中的图像

python - 多个类别的出现顺序

python - 如何使用 NLP 和实体识别从文本中正确提取设施和设施等实体?