作者:用户ll08sq9y2x | 来源:互联网 | 2023-08-26 19:41
我有一个csv文件,其中包含多个包含空字符串的列.在将csv读入pandas数据帧后,空字符串将转换为NaN.现在我想将一个字符串标签附加到已经存在于列中的字符串,但仅添加到其中包
我有一个csv文件,其中包含多个包含空字符串的列.在将csv读入pandas数据帧后,空字符串将转换为NaN.
现在我想将一个字符串标签附加到已经存在于列中的字符串,但仅添加到其中包含某些值的字符串而不是那些具有NaN的字符串
这就是我想要做的:
with open('file1.csv','r') as file:
for chunk in pd.read_csv(file,chunksize=1000, header=0, names=['A','B','C','D'])
if len(chunk) >=1:
if chunk['A'].notna:
chunk['A'] = "tag-"+chunk['A'].astype(str)
if chunk['B'].notna:
chunk['B'] = "tag-"+chunk['B'].astype(str)
if chunk['C'].notna:
chunk['C'] = "tag-"+chunk['C'].astype(str)
if chunk['D'].notna:
chunk['D'] = "tag-"+chunk['D'].astype(str)
这是我得到的错误:
AttributeError: 'Series' object has no attribute 'notna'
我想要的最终输出应该是这样的:
A,B,C,D
tag-a,tab-b,tag-c,
tag-a,tag-b,,
tag-a,,,
,,tag-c,
,,,tag-d
,tag-b,,tag-d
解决方法:
我相信你需要mask
为所有列添加标签:
for chunk in pd.read_csv('file1.csv',chunksize=2, header=0, names=['A','B','C','D']):
if len(chunk) >=1:
m1 = chunk.notna()
chunk = chunk.mask(m1, "tag-" + chunk.astype(str))
您需要升级到最新版本的pandas,0.21.0.
你可以查看docs:
In order to promote more consistency among the pandas API, we have added additional top-level functions isna()
and notna()
that are aliases for isnull()
and notnull()
. The naming scheme is now more consistent with methods like .dropna()
and .fillna()
. Furthermore in all cases where .isnull() and .notnull() methods are defined, these have additional methods named .isna()
and .notna()
, these are included for classes Categorical, Index, Series, and DataFrame. (GH15001).
The configuration option pd.options.mode.use_inf_as_null is deprecated, and pd.options.mode.use_inf_as_na is added as a replacement.