Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Can';t根据数据帧中的条件为值添加前缀_Python_Pandas - Fatal编程技术网

Python Can';t根据数据帧中的条件为值添加前缀

Python Can';t根据数据帧中的条件为值添加前缀,python,pandas,Python,Pandas,首先,我是Python新手,所以我不是专家 这是我的问题。我有这个数据框: CODE_IRIS PDL_RESIDENTIEL PDL_TOTAL CONSO_RESIDENTIEL CONSO_TOTALE 0 10040101 500 510 11264 26677 1 10040102 806 809 16234

首先,我是Python新手,所以我不是专家

这是我的问题。我有这个数据框:

   CODE_IRIS  PDL_RESIDENTIEL  PDL_TOTAL  CONSO_RESIDENTIEL  CONSO_TOTALE
0  10040101               500        510              11264         26677
1  10040102               806        809              16234         17318
2  10040201               921        925              14451         17065
3  10040202               937        943              13036         19516
4  10049999                94         94               1287          1287
问题是,
code\u IRIS
是一个
对象
,应该有9个字符,如下所示:

       CODE_IRIS  PDL_RESIDENTIEL  PDL_TOTAL  CONSO_RESIDENTIEL  CONSO_TOTALE
17861  766810113              588        593               9344         14743
因此,当
code\u IRIS
中的字符长度小于9时,我需要传递一个前缀
0
,就像我在Excel上使用公式
=IF(LEN([@[code IRIS]])<9;0&[@[code IRIS]];[@[code IRIS]])

现在,当我尝试用
elec.loc[elec['code\u IRIS'].str.len()<9]
查找只有8个字符的值时,得到的结果是:

Out[393]: 
Empty DataFrame
Columns: [CODE_IRIS, PDL_RESIDENTIEL, PDL_TOTAL, CONSO_RESIDENTIEL, CONSO_TOTALE]
Index: []
然后,当我尝试使用
elec['code\u IRIS'].str.len()
查看每个值的长度时,得到的结果是:

Out[396]: 
0       NaN
1       NaN
...
Name: CODE_IRIS, Length: 23905, dtype: float64
虽然列
code\u IRIS
肯定是一个
对象
,但是您可以在这里看到:

elec.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 23905 entries, 0 to 23904
Data columns (total 5 columns):
CODE_IRIS            23905 non-null object
PDL_RESIDENTIEL      23905 non-null int64
PDL_TOTAL            23905 non-null int64
CONSO_RESIDENTIEL    23905 non-null int64
CONSO_TOTALE         23905 non-null int64
dtypes: int64(4), object(1)
memory usage: 1.1+ MB
elec.info()
INT64索引:23905个条目,0到23904
数据列(共5列):
代码_IRIS 23905非空对象
PDL_RESIDENTIEL 23905非空int64
PDL_总计23905非空int64
CONSO_RESIDENTIEL 23905非空int64
CONSO_总计23905非空int64
数据类型:int64(4),对象(1)
内存使用率:1.1+MB
我不明白。有人能解释一下怎么了吗

(我希望我已经尽可能让自己理解了)。 谢谢

您可以在每个
code\u虹膜上使用:

df['CODE_IRIS'] = df['CODE_IRIS'].map(lambda x: str(x).zfill(9))