我目前有一个 Pandas DataFrame 列表。我试图对每个列表元素(即列表中包含的每个 DataFrame)执行操作,然后将该 DataFrame 保存到 CSV 文件。
我分配了一个name
属性到每个 DataFrame,但我意识到在某些情况下程序会抛出错误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
该程序在我使用的第二个 for 循环中抛出错误df.name
.
这特别奇怪,因为当我跑步时print(df.name)
它打印出文件名。有人会知道我做错了什么吗?
谢谢。
解决方案是使用 loc 来设置值,而不是创建副本。
创建 df 的副本会丢失名称:
df = df[::-1] # creates a copy
设置值“保持”原始对象以及名称完整
df.loc[:] = df[:, ::-1] # reversal maintaining the original object
沿列轴反转值的示例代码:
df = pd.DataFrame([[6,10]], columns=['a','b'])
df.name='t'
print(df.name)
print(df)
df.iloc[:] = df.iloc[:,::-1]
print(df)
print(df.name)
outputs:
t
a b
0 6 10
a b
0 10 6
t
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)