[英]Properly transpose Pandas dataframe and access first column
我有一个从 csv 文件中读取的 dataframe,如下所示:
original = pd.read_csv("fruit.csv")
print(original)
fruit apple banana pear
0 weight 50 45 48
1 price 100 150 200
2 calories 10 50 40
我想转置它,以便我可以访问现在在“水果”行中的类别作为它们自己的列,即像这样:
print(transposed['fruit'])
0 apple
1 banana
2 pear
这样我就可以做print(transposed[transposed['fruit']=='apple']['weight'])
如果我尝试简单地转置 dataframe 那么我无法访问第一列( KeyError: 'fruit'
)。 我尝试了 dataframe 的各种操作,但要么索引被弄乱,要么第一个列名被删除(当我reset_index()
时,'fruit' 出于某种原因变成了 'index')。
使用melt
和pivot
:
>>> df.melt('fruit').pivot('variable', 'fruit', 'value') \
.rename_axis(index='fruit', columns=None).reset_index()
fruit calories price weight
0 apple 10 100 50
1 banana 50 150 45
2 pear 40 200 48
另一种方式:
transposed = df.T.reset_index().set_axis(df.T.reset_index().iloc[0], axis=1).iloc[1:].rename_axis(None, axis=1)
Output:
>>> transposed
fruit weight price calories
1 apple 50 100 10
2 banana 45 150 50
3 pear 48 200 40
>>> transposed[transposed['fruit']=='apple']['weight']
1 50
Name: weight, dtype: object
IIUC,以fruit
为指标; 选择应该更容易:
temp = df.set_index('fruit')
temp.loc['weight', 'apple']
50
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.