微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 解析时出错,在1行中更新多个列

输入到pd.read_clipboard()

Ratanhia ,30c x2, 200c x2
Aloe ,30c x2, 200c x2
Nitric Acid ,30c x2, 200c x 2
Sedum Acre ,200c x2, 30c x2
Paeonia ,200c x2, 30c x2
Sulphur ,200c x2, 30c x2
Hamamelis ,30c x1, 200c x1
Aesculus ,30c x1, 200c x1⁠⁠⁠⁠

码:

import pandas as pd

df = pd.read_clipboard(header=None, sep=',')
df.columns = ['Medicine','power30c','power200c']
df.power30c=df.power30c.apply(lambda x: x[-1])
df.power200c=df.power200c.apply(lambda x: x[-1])
print df

输出

       Medicine power30c power200c
0     Ratanhia         2         2
1         Aloe         2         2
2  Nitric Acid         2         2
3   Sedum Acre         2         2
4      Paeonia         2         2
5      Sulphur         2         2
6    Hamamelis         1         1
7     Aesculus         1         �

问题:

>为什么 在最后一排?
>如何在1行中修改1列以上?

df[['power30c','power200c']] = df[['power30c','power200c']].apply(lambda x: x[-1])

Throws error:

ValueError: Length mismatch: Expected axis has 1 elements, new values have 3 elements

Python版本:2.7,Pandas:0.19,IPython:4

解决方法:

你需要参数skipinitialspace:

df = pd.read_clipboard(sep=',',
                       names=['Medicine','power30c','power200c'], 
                       skipinitialspace=True)
print (df)
       Medicine power30c power200c
0     Ratanhia    30c x2   200c x2
1         Aloe    30c x2   200c x2
2  Nitric Acid    30c x2  200c x 2
3   Sedum Acre   200c x2    30c x2
4      Paeonia   200c x2    30c x2
5      Sulphur   200c x2    30c x2
6    Hamamelis    30c x1   200c x1
7     Aesculus    30c x1   200c x1

然后是indexing with str

df[['power30c','power200c']] = df[['power30c','power200c']].apply(lambda x: x.str[-1])
print (df)
       Medicine power30c power200c
0     Ratanhia         2         2
1         Aloe         2         2
2  Nitric Acid         2         2
3   Sedum Acre         2         2
4      Paeonia         2         2
5      Sulphur         2         2
6    Hamamelis         1         1
7     Aesculus         1         1

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐