gpt4 book ai didi

python - pandas 数据框,将 index_col 设置为我的 csv 名称

转载 作者:行者123 更新时间:2023-12-01 04:30:08 25 4
gpt4 key购买 nike

我有一个关于使用 pd.read_csv 的问题我目前正在从文件夹中的多个 csv 文件构建数据框,csv 文件命名如下:“C2__1979H”或“C2_1999Z”

我想将数据帧的索引设置为等于当前拉取以创建数据帧的 CSV 文件的名称。我还没有找到办法做到这一点。这是我当前的代码

我的数据框如下所示:

    Date     Open    High     Low   Close     Vol  OI  Roll
0 19780106 236.00 237.50 234.50 235.50 0 0 0
1 19780113 235.50 239.00 235.00 238.25 0 0 0
2 19780120 238.00 239.00 234.50 237.00 0 0 0
3 19780127 237.00 238.50 235.50 236.00 0 0 0

我希望它看起来像这样

            Date       Open    High     Low   Close    Vol  OI  Roll
C2__1979N 19780106 236.00 237.50 234.50 235.50 0 0 0
C2__1979N 19780113 235.50 239.00 235.00 238.25 0 0 0
C2__1979N 19780120 238.00 239.00 234.50 237.00 0 0 0
C2__1979Z 19780127 237.00 238.50 235.50 236.00 0 0 0 ##(assuming this is where the next csv file began)

最佳答案

它确实有效。

import os

df_temp = pd.DataFrame({'Close': [235.5, 238.25, 237.0, 236.0],
'Date': [19780106, 19780113, 19780120, 19780127],
'High': [237.5, 239.0, 239.0, 238.5],
'Low': [234.5, 235.0, 234.5, 235.5],
'OI': [0, 0, 0, 0],
'Open': [236.0, 235.5, 238.0, 237.0],
'Roll': [0, 0, 0, 0],
'Vol': [0, 0, 0, 0]})

df = pd.DataFrame()

# To simulate several df
x=0
for file_ in ['the_path/C2__1979N.csv', 'other_path/C2__1979H.csv']:
filename, file_extension = os.path.splitext(file_)
df_temp['name'] = os.path.basename(filename)
df = df.append(df_temp.loc[x:x+1,:])
x+=1

df.set_index('name', inplace=True)
df.index.name = None
print(df)

# Result
Close Date High Low OI Open Roll Vol
C2__1979N 235.50 19780106 237.5 234.5 0 236.0 0 0
C2__1979N 238.25 19780113 239.0 235.0 0 235.5 0 0
C2__1979H 237.00 19780120 239.0 234.5 0 238.0 0 0
C2__1979H 236.00 19780127 238.5 235.5 0 237.0 0 0

在原始代码中:

for file_ in allFiles:
names = ['Date', 'Open', 'High', 'Low', 'Close', 'Vol', 'OI', 'Roll']
df_temp = pd.read_csv(file_, index_col = None, names = names)
df_temp['Roll'] = 0
df_temp.iloc[-2,-1] = 1
filename, file_extension = os.path.splitext(file_)
df_temp['name'] = os.path.basename(filename)
df = df.append(df_temp)

df = df.reset_index(drop=True)
df.set_index('name', inplace=True)
df.index.name = None
df = df[names]

df = df.drop_duplicates('Date') ## remove duplicate rows with same date

关于python - pandas 数据框,将 index_col 设置为我的 csv 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32511150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com