Python函数写入CSV

时间:2017-05-23 22:27:14

标签: python csv dataframe

def write_csv(mydf):
    nominal = mydf.name 
    csvname = nominal + ".csv"
    mydf.to_csv( csvname , encoding='utf-8', header='False')

当我调用该函数时,这没有用:

write_csv(ulangp) 
Attribute Error:  'DataFrame' object has no attribute 'name'

假设我想传入数据帧,在函数中执行此操作的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

如果数据帧没有预设名称,您可以传递[n可选] name参数:

def write_csv(mydf, name="default"): # Use any good default name here
    try:
        nominal = mydf.name 
    except AttributeError:
        nominal = name
    csvname = nominal + ".csv"
    mydf.to_csv( csvname , encoding='utf-8', header='False')