解析时出错,更新1行中的多个列

MYG*_*YGz 5 python python-2.7 pandas

输入到 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????
Run Code Online (Sandbox Code Playgroud)

码:

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
Run Code Online (Sandbox Code Playgroud)

输出:

       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         ?
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 为什么?在最后一排?
  2. 如何在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
Run Code Online (Sandbox Code Playgroud)

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

jez*_*ael 2

您需要参数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
Run Code Online (Sandbox Code Playgroud)

然后用 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
Run Code Online (Sandbox Code Playgroud)