gpt4 book ai didi

python - 解析错误,更新 1 行中的多个列

转载 作者:太空狗 更新时间:2023-10-30 01:05:52 25 4
gpt4 key购买 nike

输入到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. 为什么 ... 在最后一行?
  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

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

关于python - 解析错误,更新 1 行中的多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41501758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com