我想在python中的plotly express中更改变量/标签名称。我首先创建一个情节:
import pandas as pd
import plotly.express as px
d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
fig = px.line(df, x=df.index, y=['col1', 'col2'])
fig.show()
Run Code Online (Sandbox Code Playgroud)
其中产生:
我想将标签名称从col1更改为hello并将col2更改为hi。我曾尝试在图中使用标签,但无法使其正常工作:
fig = px.line(df, x=df.index, y=['col1', 'col2'], labels={'col1': "hello", 'col2': "hi"})
fig.show()
Run Code Online (Sandbox Code Playgroud)
但这似乎没有任何作用,同时不会产生错误。显然我可以通过更改列名来实现我的目标,但我试图创建的实际图并没有真正允许这样做,因为它来自几个不同的数据框。
我想根据特定列中的值重塑 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
Run Code Online (Sandbox Code Playgroud)
对此:
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 …
Run Code Online (Sandbox Code Playgroud)