簡體   English   中英

DataFrame 對象沒有屬性“名稱”

[英]DataFrame object has no attribute 'name'

我目前有一個 Pandas DataFrames 列表。 我正在嘗試對每個列表元素(即列表中包含的每個 DataFrame)執行操作,然后將該 DataFrame 保存到 CSV 文件。

我為每個 DataFrame 分配了一個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 循環中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)

輸出:

t
   a   b
0  6  10
    a  b
0  10  6
t

一種解決方法是設置一個columns.name並在需要時使用它。

例子:

df = pd.DataFrame()

df.columns.name = 'name'

print(df.columns.name)

name

懷疑這是失去自定義 .name 屬性的逆轉。

In [11]: df = pd.DataFrame()

In [12]: df.name = 'empty'

In [13]: df.name
Out[13]: 'empty'

In [14]: df[::-1].name
AttributeError: 'DataFrame' object has no attribute 'name'

最好存儲數據幀的字典而不是使用 .name:

df_og = {file: pd.read_csv(os.path.join(data_og_dir, 'raw', fn) for fn in raw_og}

然后你可以遍歷這個並反轉需要反轉的值......

for fn, df in df_og.items():
    if (check_reverse(df)):
        df = df[::-1]
        df.to_csv(os.path.join(data_og_dir, 'raw_new', fn), index=False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM