Pandas 如何有条件地更改数据帧中的单元格?

Pandas 如何有条件地更改数据帧中的单元格?,pandas,Pandas,我有一个对象类型的时间列 我想在时间长度为3时添加一个前导0 所以“1200”应该保持不变,但“900”应该转换为“0900” 我的猜测是这样做: sample['Time'] = ('0' + sample['Time']) if sample['Time'].str.len() == 3 else sample['Time'] 但是我得到了这个错误: 级数的真值是模糊的。使用a.empty,a.bool(), a、 item()、a.any()或a.all() 您可以将列视为str并使用:

我有一个对象类型的时间列

我想在时间长度为3时添加一个前导0

所以“1200”应该保持不变,但“900”应该转换为“0900”

我的猜测是这样做:

sample['Time'] = ('0' + sample['Time']) if sample['Time'].str.len() == 3 else sample['Time']
但是我得到了这个错误:

级数的真值是模糊的。使用a.empty,a.bool(), a、 item()、a.any()或a.all()


您可以将列视为str并使用:

sample['Time'] = sample['Time'].str.zfill(4)
注意-这将使所有字符串至少有4个字符-从前面填充零。对于长度大于4的字符串-它将不起任何作用

例如:

为您提供以下内容的
r

0      0900    # <- prefixed
1      1200    # <- unchanged
2      0040
3      0004
4      0000
5       NaN    # <- nothing happens here
6    999999    # <- string remains 6 characters

0 0900 35;您可以将列视为str并使用:

sample['Time'] = sample['Time'].str.zfill(4)
注意-这将使所有字符串至少有4个字符-从前面填充零。对于长度大于4的字符串-它将不起任何作用

例如:

为您提供以下内容的
r

0      0900    # <- prefixed
1      1200    # <- unchanged
2      0040
3      0004
4      0000
5       NaN    # <- nothing happens here
6    999999    # <- string remains 6 characters

0 0900#是否
sample['Time'].str.zfill(4)
返回您期望的结果?是的。不知道该函数存在。感谢您的
sample['Time'].str.zfill(4)
返回您期望的内容?是的。不知道该函数存在。谢谢