【问题标题】:I get a KeyError when trying to plot these group of dataframes with Pandas尝试使用 Pandas 绘制这些数据帧组时出现 KeyError
【发布时间】:2019-10-15 06:38:43
【问题描述】:

当我尝试使用 pandas 为这些数据帧组绘制 Force against Displacement 时,我收到“Displacement”的关键错误。请帮忙。

正在使用的 Excel 工作表的链接: https://www.dropbox.com/s/f8lnp973ojv3ish/neurospheress.xlsx?dl=0

我尝试清除列标题中的所有空格,但它不起作用

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_excel('neurospheress.xlsx', sep='\s*,\s*', sheet_name = 'LS')

df1 = data.iloc[:80,:2]
df2 = data.iloc[:80,2:4]
df3 = data.iloc[:80,4:]
dfs = [df1,df2,df3]

for i,df in enumerate(dfs):
    plt.plot(df['Displacement'], df['Force'], linestyle='--', alpha= 0.8, label='df{}'.format(i))
plt.legend(loc='best')
plt.show()

【问题讨论】:

    标签: excel pandas dataframe keyerror


    【解决方案1】:

    以下解决方案有效,它基本上为您的解决方案添加了两件事

    a) 跳过 excel 的第一行 b) 重命名 df2 和 df3 的列名

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = pd.read_excel('neurospheress.xlsx', sep='\s*,\s*', sheet_name = 'LS',skiprows=1)
    
    df1 = data.iloc[:80,:2]
    df2 = data.iloc[:80,2:4]
    df3 = data.iloc[:80,4:]
    dfs = [df1,df2,df3]
    
    df2.rename(columns={'Force.1':'Force','Displacement.1':'Displacement'},inplace=True)
    df3.rename(columns={'Force.2':'Force','Displacement.2':'Displacement'},inplace=True)
    
    print(data.columns)
    print(df1.columns)
    print(df2.columns)
    
    for i,df in enumerate(dfs):
        plt.plot(df['Displacement'], df['Force'], linestyle='--', alpha= 0.8, label='df{}'.format(i))
    plt.legend(loc='best')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 1970-01-01
      • 2023-03-12
      • 2016-03-11
      • 2016-02-22
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 2020-07-20
      相关资源
      最近更新 更多