如何使用 pandas 编辑 Python 中的 .csv 文件(添加行和删除行)

How Do I Edit .csv files in Python using pandas (appending rows & deleting rows)

我正在 python 中处理一个 csv 文件并试图找出...

  1. 如何从文件中删除 10 行(顶部或底部,提示用户选择)
  2. 如何将 10 行附加到 csv 文件的顶部
  3. 如何在新创建的行中输入信息

任何信息都会有帮助!谢谢

尝试:

cols = your_columns  #type list
new_row_as_df = pd.DataFrame([value_col1, value_col2, ..., val_col9], columns=your_columns)
new_row_as_list = [value_col1, value_col2, ..., val_col9]

# Add a new row to the top as df:
df = pd.concat([new_row_as_df, df]).reset_index(drop=True)

# Add a new row to the bottom as list:
df.loc[len(df.index)] = new_row_as_list

# Add a new row to the bottom as df:
df = pd.concat([df, new_row_as_df]).reset_index(drop=True)

# Delete a row at a specific index (int):
df.drop(labels=your_index, axis=0, inplace=True)

删除特定行的简单方法:

# delete a single row by index value 0
data = data.drop(labels=0, axis=0)
# delete a few specified rows at index values 0, 15, 20.
# Note that the index values do not always align to row numbers.
data = data.drop(labels=[1,15,20], axis=0)
# delete a range of rows - index values 10-20
data = data.drop(labels=range(40, 45), axis=0)

@Sergey 刚刚回答了如何将行添加到底部或顶部。