gpt4 book ai didi

python - 基于列值 reshape Pandas 数据框

转载 作者:行者123 更新时间:2023-12-03 21:11:11 25 4
gpt4 key购买 nike

我想根据特定列中的值 reshape Pandas 数据帧,以便为起始数据帧中的每个值列对获得一个新列。我想从中得到:

import pandas as pd

d = {'city': ['Berlin', 'Berlin', 'Berlin', 'London', 'London', 'London'],
'weather': ['sunny', 'sunny', 'cloudy','sunny', 'cloudy', 'cloudy'], 'temp': [20,22,19, 21, 18, 17]}
df = pd.DataFrame(data=d)
df

city weather temp
0 Berlin sunny 20
1 Berlin sunny 22
2 Berlin cloudy 19
3 London sunny 21
4 London cloudy 18
5 London cloudy 17
对此:
d_2 = {'Berlin_weather': ['sunny', 'sunny', 'cloudy'], 'Berlin_temp': [20,22,19],
'London_weather': ['sunny', 'cloudy', 'cloudy'], 'London_temp': [21, 18, 17]}
df_2 = pd.DataFrame(data=d_2)
df_2

Berlin_weather Berlin_temp London_weather London_temp
0 sunny 20 sunny 21
1 sunny 22 cloudy 18
2 cloudy 19 cloudy 17
我曾尝试使用 .unstack() 但我无法让它正常工作。循环很明显,但我的实际数据集的大小使它有点不可行。

最佳答案

让我们创建一个新索引然后使用 unstack

df1 = df.set_index([df['city'],df.groupby('city').cumcount()]).drop('city',1).unstack(0)
然后展平多索引列。
df1.columns = [f'{y}_{x}' for x,y in df1.columns]
print(df1)

Berlin_weather London_weather Berlin_temp London_temp
0 sunny sunny 20 21
1 sunny cloudy 22 18
2 cloudy cloudy 19 17
如果订单很重要,我们可以使用 pd.CategoricalIndex在展平列之前。
cati = pd.CategoricalIndex(df1.columns.get_level_values(0).unique(),
['weather','temp'],
ordered=True)

df1.columns = df1.columns.set_levels(cati, level=0)

df1 = df1.sort_index(1,1) # level = 1 and axis = 1 -- columns.
df1.columns = [f'{y}_{x}' for x,y in df1.columns]


Berlin_weather Berlin_temp London_weather London_temp
0 sunny 20 sunny 21
1 sunny 22 cloudy 18
2 cloudy 19 cloudy 17

关于python - 基于列值 reshape Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63812587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com