> For the complete documentation index, see [llms.txt](https://igb.mit.edu/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://igb.mit.edu/mini-courses/python/data-processing-with-python/pandas/editing-dataframes.md).

# Editing DataFrames

You can trivially add new columns or change the values in existing column.

### Add a new column

1. Be sure that the column you are adding has the same indices as the old dataframe.
2. This is most easily accomplished by manipulating an old column and saving the value
3. Example: `dataframe['new_column_name'] = ms['old_column']*value`
4. Example: `dataframe['new_column_name'] = ms['old_column1']*ms['old_column2']`

### Alter a column

1. You select a set of cells using the tools from above change their values
2. Note that dataframes are MUTABLE!
3. `dataframe.loc[selection,selection] = 7`

### Dealing with missing data

1. The `dataframe.dropna()` and `.fillna()` funtions are super helpful in removing/replacing missing values
2. Example: `only_complete_rows = dataframe.dropna(how='any')`
3. Example: `replace_with_0 = dataframe.fillna(value=0.0)`

```
# what is this line doing?
ms['light +1 charge mass']=ms['light Precursor Mz']*ms['Precursor Charge'] - ((ms['Precursor Charge']-1)*1.0078)
```

```
ms[['Peptide Modified Sequence', 'light Precursor Mz', 'Precursor Charge', 'light +1 charge mass']]
```

<figure><img src="https://498238201-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWuHhstIreJ3jFvE4gQ3y%2Fuploads%2FLazpFLpOOCnMckOYEEg0%2Fimage.png?alt=media&amp;token=f6832ed3-ec23-4df1-95bc-62f31c047359" alt=""><figcaption></figcaption></figure>

```
#think through what this line is doing
ms.loc[ms['light +1 charge mass']>2000,['Peptide Modified Sequence', 'light Precursor Mz', 'Precursor Charge', 'light +1 charge mass']]
```

<figure><img src="https://498238201-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWuHhstIreJ3jFvE4gQ3y%2Fuploads%2F4nMQidaBuevPjD5qDhIV%2Fimage.png?alt=media&amp;token=d65c341d-b397-49e1-abee-030e78c9a247" alt=""><figcaption></figcaption></figure>

```
ms.loc[ms['light +1 charge mass']>2000,'light +1 charge mass'] = 'way too big!'
```

<figure><img src="https://498238201-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWuHhstIreJ3jFvE4gQ3y%2Fuploads%2Fo1B18jtQw7HYCdwcKAJz%2Fimage.png?alt=media&amp;token=1c2b63a1-3134-4739-bd23-e1796baf5a67" alt=""><figcaption></figcaption></figure>

```
#you can quickly save your work at a .csv using the command .to_csv(path_to_file)
ms.to_csv("C:\\Users\duan\Desktop\PythonDataProcessingVisualization\mass_spec_new.csv")
#look in your directory for a new .csv file!
```
