我有以下数据框
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 Aggregation与 Groupby aggregate获取每组的 min
和 max
日期并使用新名称进行设置。 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/