【问题标题】:Why does Pandas add numbers at beginning of csv-file after converting [duplicate]为什么熊猫转换后在csv文件的开头添加数字[重复]
【发布时间】:2019-10-24 04:55:48
【问题描述】:

我是一名 Python 初学者,目前正在尝试删除 csv 中的一些列 - 效果很好!但是:当我使用熊猫时,它会在文件的开头自动添加另一列并添加行号。我怎样才能避免这种情况?

输入数据如下(json):

    [
      {
        "source": "twitter",
        "cashtag": "$FB",
        "sentiment score": "0.366",
        "id": "719659409228451840",
        "spans": [
          "watching for bounce tomorrow"
    ]
  }, ... ]

转换为 csv 效果很好。

我这样做的代码:

import pandas as pd

# Convert son to csv
pd.read_json("test.json").to_csv("test.csv")

# Delete cashtag, id, source column
data = pd.read_csv("test.csv")
data = data.drop(["cashtag", "id", "source"], axis=1)
data.to_csv("test_cleaned.csv")
data.head()

输出:

Unnamed: 0  sentiment score spans
0   0   0.366   ['watching for bounce tomorrow']
1   1   0.638   ['record number of passengers served in 2015']
2   2   -0.494  ['out $NFLX -.35']
3   3   0.460   ['Looking for a strong bounce', 'Lunchtime 
4   4   0.403   ['Very intrigued with the technology and 

我想拥有什么:

sentiment score spans
    0.366   ['watching for bounce tomorrow']
    0.638   ['record number of passengers served in 2015']
    -0.494  ['out $NFLX -.35']
    0.460   ['Looking for a strong bounce', 'Lunchtime 
    0.403   ['Very intrigued with the technology and 

所以转换和删除效果很好,但是对于使用 pandas 的每个操作,它都会在文件的开头添加另一列。在此示例中,转换为 csv 后的 1 列和删除列后的 1 列。我怎样才能避免这种情况?

【问题讨论】:

  • 熊猫在线文档是一个很好的资源。当试图弄清楚一个函数是如何工作的时,这是一个很好的起点。

标签: python pandas


【解决方案1】:

这叫索引,你可以通过下面的方式来防止它被写入

df.to_csv(‘FileMaker.csv’, index=False)

【讨论】:

    【解决方案2】:

    您所指的列是索引。在保存 csv 时尝试这样做:

    data.to_csv("test_cleaned.csv", index=False)
    

    Pandas 会自动为您初始化的每个 Dataframe 创建一个索引,除非您明确执行此操作。我强烈建议阅读panda's documentation 以获取更多信息。

    【讨论】:

      猜你喜欢
      • 2021-07-20
      • 2021-12-19
      • 2020-12-01
      • 2014-06-13
      • 2018-09-20
      • 2018-05-10
      • 2023-01-21
      • 2021-09-30
      相关资源
      最近更新 更多