我像这样加载一个数据集:
df_performance = pd.read_csv('.local.csv')
df_performance.head()csv文件中的数据已显示为表格。打印头和普通的一样。但是,当我尝试运行此代码片段时:
df_performance["Day"] = ""
df_performance.loc['Day'] = [str(x) for x in df_performance.loc["From"]]我得到这样的错误:
KeyError Traceback (most recent call last)
/opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2645 try:
-> 2646 return self._engine.get_loc(key)
2647 except KeyError:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
KeyError: 'From'
During handling of the above exception, another exception occurred:我还尝试打印列的名称,我知道'From‘是存在的。那么为什么我会得到这样的错误呢?
for col_name in df_performance:
print(col_name) From Cost helps
0 Jan 1, 2020 3 4 发布于 2020-11-23 20:00:13
如果使用loc,它将按标签而不是列名选择索引。因此,如果不存在标签,则会引发错误:
df_performance.loc['Day'] = [str(x) for x in df_performance.loc["From"]]因此似乎需要将列转换为字符串:
#by list comprehension
df_performance['Day'] = [str(x) for x in df_performance["From"]]
#by function
df_performance['Day'] = df_performance["From"].astype(str)https://stackoverflow.com/questions/64967990
复制相似问题