gpt4 book ai didi

python - Pandas :将新列添加到数据框,这是索引列的副本

转载 作者:太空狗 更新时间:2023-10-29 18:28:42 25 4
gpt4 key购买 nike

我有一个数据框,我想用 matplotlib 绘制它,但索引列是时间,我无法绘制它。

这是数据框 (df3):

enter image description here

但是当我尝试以下操作时:

plt.plot(df3['magnetic_mag mean'], df3['YYYY-MO-DD HH-MI-SS_SSS'], label='FDI')

我明显收到一个错误:

KeyError: 'YYYY-MO-DD HH-MI-SS_SSS'

所以我想做的是向我的数据框添加一个新的额外列(名为“Time”),它只是索引列的副本。

我该怎么做?

这是完整的代码:

#Importing the csv file into df
df = pd.read_csv('university2.csv', sep=";", skiprows=1)

#Changing datetime
df['YYYY-MO-DD HH-MI-SS_SSS'] = pd.to_datetime(df['YYYY-MO-DD HH-MI-SS_SSS'],
format='%Y-%m-%d %H:%M:%S:%f')

#Set index from column
df = df.set_index('YYYY-MO-DD HH-MI-SS_SSS')

#Add Magnetic Magnitude Column
df['magnetic_mag'] = np.sqrt(df['MAGNETIC FIELD X (μT)']**2 + df['MAGNETIC FIELD Y (μT)']**2 + df['MAGNETIC FIELD Z (μT)']**2)

#Subtract Earth's Average Magnetic Field from 'magnetic_mag'
df['magnetic_mag'] = df['magnetic_mag'] - 30

#Copy interesting values
df2 = df[[ 'ATMOSPHERIC PRESSURE (hPa)',
'TEMPERATURE (C)', 'magnetic_mag']].copy()

#Hourly Average and Standard Deviation for interesting values
df3 = df2.resample('H').agg(['mean','std'])
df3.columns = [' '.join(col) for col in df3.columns]

df3.reset_index()
plt.plot(df3['magnetic_mag mean'], df3['YYYY-MO-DD HH-MI-SS_SSS'], label='FDI')

谢谢!!

最佳答案

我想你需要reset_index :

df3 = df3.reset_index()

可能的解决方案,但我认为 inplace 不是好的做法,检查 thisthis :

df3.reset_index(inplace=True)

但如果您需要新列,请使用:

df3['new'] = df3.index

我想你可以read_csv更好:

df = pd.read_csv('university2.csv', 
sep=";",
skiprows=1,
index_col='YYYY-MO-DD HH-MI-SS_SSS',
parse_dates='YYYY-MO-DD HH-MI-SS_SSS') #if doesnt work, use pd.to_datetime

然后省略:

#Changing datetime
df['YYYY-MO-DD HH-MI-SS_SSS'] = pd.to_datetime(df['YYYY-MO-DD HH-MI-SS_SSS'],
format='%Y-%m-%d %H:%M:%S:%f')
#Set index from column
df = df.set_index('YYYY-MO-DD HH-MI-SS_SSS')

关于python - Pandas :将新列添加到数据框,这是索引列的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36932759/

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