简体   繁体   English

如何使用Pandas转换数据框

[英]How to pivot this data frame with pandas

I'm trying to pivot this DataFrame 'a': 我正在尝试透视此DataFrame'a':

  algoasdaa      rc      rmse
0       asa   20-50  0.585161
1       asa  20-100  0.462159
2       asa  40-100  2.664910
3       asa  60-200  3.957400
4       asa  60-300  3.799590
5      lorl   20-50  0.696916
6      lorl  20-100  0.456810
7      lorl  40-100  2.489900
8      lorl  60-200  4.004530
9      lorl  60-300  3.736500

by calling the pivot method 通过调用数据透视方法

a.pivot('rc', 'algoasdaa', 'rmse')

but I keep getting the error 但我不断收到错误

KeyError: 'no item named rmse'

even though this case looks exactly like the one described in the docs 即使这种情况看起来与文档中描述的情况完全一样

Thanks in advance! 提前致谢!

That should work, and works for me: 那应该工作,并为我工作:

>>> df.pivot("rc", "algoasdaa", "rmse")
algoasdaa       asa      lorl
rc                           
20-100     0.462159  0.456810
20-50      0.585161  0.696916
40-100     2.664910  2.489900
60-200     3.957400  4.004530
60-300     3.799590  3.736500

I suspect your rmse column name has some whitespace there you can't see. 我怀疑您的rmse列名称中有一些空格,您看不到。 For example, if I add a space, it looks the same: 例如,如果我添加一个空格,它看起来是一样的:

>>> df.columns = ["rc", "algoasdaa", " rmse"]
>>> df
     rc algoasdaa      rmse
0   asa     20-50  0.585161
1   asa    20-100  0.462159
2   asa    40-100  2.664910
3   asa    60-200  3.957400
4   asa    60-300  3.799590
5  lorl     20-50  0.696916
6  lorl    20-100  0.456810
7  lorl    40-100  2.489900
8  lorl    60-200  4.004530
9  lorl    60-300  3.736500

but: 但:

>>> df.pivot("rc", "algoasdaa", "rmse")
Traceback (most recent call last):
[...]
KeyError: u'no item named rmse'

Try 尝试

>>> print df.columns
Index([u'rc', u'algoasdaa', u' rmse'], dtype=object)

to confirm this. 确认这一点。 You can then either fix your read operation (best) or patch them after the fact with something like 然后,您可以(最好)修复您的读取操作,或者在出现类似问题的情况后对其进行修补

>>> df.columns = [col.strip() for col in df.columns]

or 要么

>>> df.columns = pd.Series(df.columns).str.strip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM