我现在有一个熊猫数据帧列表。我正在尝试对每个列表元素(即列表中包含的每个数据帧)执行一个操作,然后将该数据帧保存到CSV文件中。
我为每个数据帧分配了一个name
属性,但我意识到在某些情况下,程序会抛出一个错误AttributeError: 'DataFrame' object has no attribute 'name'
。
这是我的密码。
# raw_og contains the file names for each CSV file.
# df_og is the list containing the DataFrame of each file.
for idx, file in enumerate(raw_og):
df_og.append(pd.read_csv(os.path.join(data_og_dir, 'raw', file)))
df_og[idx].name = file
# I'm basically checking if the DataFrame is in reverse-chronological order using the
# check_reverse function. If it is then I simply reverse the order and save the file.
for df in df_og:
if (check_reverse(df)):
df = df[::-1]
df.to_csv(os.path.join(data_og_dir, 'raw_new', df.name), index=False)
else:
continue
程序在我使用df.name
的第二个for循环中抛出错误。
这特别奇怪,因为当我运行print(df.name)
时,它会打印出文件名。有人知道我做错了什么吗?
谢谢你。
解决方法是设置一个
columns.name
,并在需要时使用它。示例:
我怀疑是反向操作丢失了custom.name属性。
最好是存储数据帧而不是使用.name:
然后你可以遍历这个并反转需要反转的值。。。
解决方案是使用loc设置值,而不是创建副本。
创建df的副本会丢失名称:
设置值“保持”原始对象和名称的完整性
沿列轴反转值的示例代码:
输出:
相关问题 更多 >
编程相关推荐