gpt4 book ai didi

python-3.x - Pandas:更新列的值

转载 作者:行者123 更新时间:2023-12-01 01:53:46 24 4
gpt4 key购买 nike

我有一个包含多列的大型数据框(示例如下所示)。我想通过将一个特定(人口列)列的值除以 1000 来更新它的值。

City     Population
Paris 23456
Lisbon 123466
Madrid 1254
Pekin 86648

我试过了 df['Population'].apply(lambda x: int(str(x))/1000)

df['Population'].apply(lambda x: int(x)/1000)

两者都给我错误

ValueError: invalid literal for int() with base 10: '...'

最佳答案

如果您的 DataFrame 确实看起来像显示的那样,那么第二个示例应该可以正常工作(甚至不需要 int):

In [16]: df
Out[16]:
City Population
0 Paris 23456
1 Lisbon 123466
2 Madrid 1254
3 Pekin 86648

In [17]: df['Population'].apply(lambda x: x/1000)
Out[17]:
0 23.456
1 123.466
2 1.254
3 86.648
Name: Population, dtype: float64

In [18]: df['Population']/1000
Out[18]:
0 23.456
1 123.466
2 1.254
3 86.648

但是,从错误来看,您的 '...' 中似乎有无法解析的字符串 Series ,并且需要进一步清理数据。

关于python-3.x - Pandas:更新列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42100186/

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