将 pandas df 从 corsstabulation 重塑为长格式
Reshaping pandas df from corsstabulation to long format
我有一个数据框如下:
d = {'Country': ['USA', 'France', 'Germany'], 'USA': ['NaN', 2, 5], 'France': [3, 'NaN', 7], 'Germany': [3.5, 4, 'NaN']}
df = pd.DataFrame(data=d)
Country USA France Germany
0 USA NaN 3 3.5
1 France 2 NaN 4
2 Germany 5 7 NaN
我希望将其重塑为以下格式:
d = {'Country': ['USA', 'USA', 'France', 'France', 'Germany', 'Germany'], 'Country2': ['France', 'Germany', 'USA', 'Germany', 'USA', 'France'],\
'Value': [3, 3.5, 2, 4, 5, 7]}
df = pd.DataFrame(data=d)
Country Country2 Value
0 USA France 3.0
1 USA Germany 3.5
2 France USA 2.0
3 France Germany 4.0
4 Germany USA 5.0
5 Germany France 7.0
我怎样才能rotate/melt/pivot df 达到这个结果?
让我们做
out = df.set_index('Country').stack().reset_index()
我有一个数据框如下:
d = {'Country': ['USA', 'France', 'Germany'], 'USA': ['NaN', 2, 5], 'France': [3, 'NaN', 7], 'Germany': [3.5, 4, 'NaN']}
df = pd.DataFrame(data=d)
Country USA France Germany
0 USA NaN 3 3.5
1 France 2 NaN 4
2 Germany 5 7 NaN
我希望将其重塑为以下格式:
d = {'Country': ['USA', 'USA', 'France', 'France', 'Germany', 'Germany'], 'Country2': ['France', 'Germany', 'USA', 'Germany', 'USA', 'France'],\
'Value': [3, 3.5, 2, 4, 5, 7]}
df = pd.DataFrame(data=d)
Country Country2 Value
0 USA France 3.0
1 USA Germany 3.5
2 France USA 2.0
3 France Germany 4.0
4 Germany USA 5.0
5 Germany France 7.0
我怎样才能rotate/melt/pivot df 达到这个结果?
让我们做
out = df.set_index('Country').stack().reset_index()