【问题标题】:How do I set the column and row indexes on a multidimensional list in pandas如何在熊猫中的多维列表上设置列和行索引
【发布时间】:2019-06-23 13:24:25
【问题描述】:

我有一组从 Google 表格中检索的数据。它以以下格式返回:

[['Incident Severity', '# of Incidents by Severity'], ['Sev 1', '0'], ['Sev 2', '0'], ['Sev 3', '3'], ['Sev 4', '2']]

我已经使用 from_records 将它导入到 Pandas 中,它使用 df.head() 为我提供了以下信息:

                   0                           1
0  Incident Severity  # of Incidents by Severity
1              Sev 1                           0
2              Sev 2                           0
3              Sev 3                           3
4              Sev 4                           2

但是第一行需要设置为标题,第一列应该是索引。我已设法通过执行以下操作更改列标题:

df.columns = df.iloc[0]
df = df.reindex(df.index.drop(0))

这给了我:

0 Incident Severity # of Incidents by Severity
1             Sev 1                          0
2             Sev 2                          0
3             Sev 3                          3
4             Sev 4                          2

如何删除第一个索引列,以便最终得到下表:

Incident Severity # of Incidents by Severity
            Sev 1                          0
            Sev 2                          0
            Sev 3                          3
            Sev 4                          2

我对 pandas 和数据框很陌生,所以如果我遗漏了一些明显的东西,请原谅我。我已经尝试谷歌它,但没有找到我需要知道的!

【问题讨论】:

  • 看看set_index
  • 谢谢你,我会看看:)

标签: python pandas list dataframe multidimensional-array


【解决方案1】:

使用列表索引创建DataFrame

L = [['Incident Severity', '# of Incidents by Severity'],
      ['Sev 1', '0'],
      ['Sev 2', '0'], 
      ['Sev 3', '3'], 
      ['Sev 4', '2']]

df = pd.DataFrame(L[1:], columns=L[0])
print (df)

  Incident Severity # of Incidents by Severity
0             Sev 1                          0
1             Sev 2                          0
2             Sev 3                          3
3             Sev 4                          2

无法删除索引,一种解决方案(非常糟糕)是将索引转换为空值:

df.index = [''] * len(df)
print (df)
 Incident Severity # of Incidents by Severity
             Sev 1                          0
             Sev 2                          0
             Sev 3                          3
             Sev 4                          2

但是如果需要写入没有索引的DataFrame到文件添加参数index=Falseto_csv:

print (df.to_csv(index=False))
Incident Severity,# of Incidents by Severity
Sev 1,0
Sev 2,0
Sev 3,3
Sev 4,2

【讨论】:

  • 哇。很简单!惊人的!我不知道您在导入数据时可以这样做!感谢您提供详细而快速的答复!
猜你喜欢
  • 2021-10-10
  • 2017-05-03
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多