我希望根据特定列中的值来重塑pandas数据框,以便我可以获得起始数据框中每个值-列对应关系的新列。我想从这里开始:
我尝试使用.unstack(),但无法正常工作。循环显而易见,但我实际数据集的大小使得这有点不可行。
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(),但无法正常工作。循环显而易见,但我实际数据集的大小使得这有点不可行。