如何得到pivottablereturn的值连同对应的列
How to get the pivot table return the value together with the corresponding column
我有以下数据框:
位置 1
位置 2
月份
行程
一个
b
1
200
一个
b
4
500
一个
b
7
600
c
d
6
400
c
d
4
300
我需要找出每条路线(Loc1 到 Loc2)哪个月的行程最多以及对应的行程数。
我运行一些代码但是我得到的输出如下。如何让“行程”列一起显示。
位置 1
位置 2
月份
一个
b
7
c
d
6
我使用的代码如下:
df = pd.read_csv('data.csv')
df = df[['Loc1','Loc2','Month','Trips']]
df = df.pivot_table(index = ['Loc1', 'Loc2'],
columns = 'Month',
values = 'Trips',)
df = df.idxmax(axis = 1)
df = df.reset_index()
print(f"Each route's busiest month : \n {df.to_string()}")
尝试按 Trips 降序排序并获取每组的第一行
df.sort_values(by='Trips', ascending=False).groupby(['Loc1', 'Loc2'], as_index=False).first()
或者:
df.sort_values(by='Trips').groupby(['Loc1', 'Loc2'], as_index=False).last()
注意。我无法 运行 要测试的代码,但您已经了解了大概的想法。
我有以下数据框:
位置 1 | 位置 2 | 月份 | 行程 |
---|---|---|---|
一个 | b | 1 | 200 |
一个 | b | 4 | 500 |
一个 | b | 7 | 600 |
c | d | 6 | 400 |
c | d | 4 | 300 |
我需要找出每条路线(Loc1 到 Loc2)哪个月的行程最多以及对应的行程数。
我运行一些代码但是我得到的输出如下。如何让“行程”列一起显示。
位置 1 | 位置 2 | 月份 |
---|---|---|
一个 | b | 7 |
c | d | 6 |
我使用的代码如下: df = pd.read_csv('data.csv') df = df[['Loc1','Loc2','Month','Trips']]
df = df.pivot_table(index = ['Loc1', 'Loc2'],
columns = 'Month',
values = 'Trips',)
df = df.idxmax(axis = 1)
df = df.reset_index()
print(f"Each route's busiest month : \n {df.to_string()}")
尝试按 Trips 降序排序并获取每组的第一行
df.sort_values(by='Trips', ascending=False).groupby(['Loc1', 'Loc2'], as_index=False).first()
或者:
df.sort_values(by='Trips').groupby(['Loc1', 'Loc2'], as_index=False).last()
注意。我无法 运行 要测试的代码,但您已经了解了大概的想法。