简体   繁体   中英

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

I'm working with a csv file in python and trying to figure out...

  1. How to delete 10 rows from the file (either top or bottom, prompt the User to pick)
  2. How to append 10 rows to the top of the csv file
  3. How to input information within those newly made rows

Any information would be helpful! Thank you

csv文件的图片

Try:

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)

Easy way to drop specific rows:

# 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)

And @Sergey just answered on how to add rows to bottom or top.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM