Ama*_*ngh 4 python dataframe python-3.x pandas
我有一个csv文件,其中包含多个包含空字符串的列.在将csv读入pandas数据帧后,空字符串将转换为NaN.
现在我想将一个字符串追加tag-到列中已经存在的字符串,但只包含那些在其中有一些值的字符串而不是那些带有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)
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
AttributeError: 'Series' object has no attribute 'notna'
Run Code Online (Sandbox Code Playgroud)
我想要的最终输出应该是这样的:
A,B,C,D
tag-a,tab-b,tag-c,
tag-a,tag-b,,
tag-a,,,
,,tag-c,
,,,tag-d
,tag-b,,tag-d
Run Code Online (Sandbox Code Playgroud)
我相信你需要在一起mask添加tag-所有列:
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))
Run Code Online (Sandbox Code Playgroud)
您需要升级到最新版本的熊猫,0.21.0.
你可以查看文档:
为了促进大熊猫API之间的一致性,我们增加了额外的顶级功能
isna()和notna()是为别名isnull()和notnull().命名方案现在更像是.dropna()和.fillna().此外,在定义.isnull()和.notnull()方法的所有情况下,这些方法都有其他命名的方法,.isna()并且.notna()这些方法包含在类别,索引,系列和数据框架中.(GH15001).不推荐使用配置选项pd.options.mode.use_inf_as_null,并添加pd.options.mode.use_inf_as_na作为替换.