Inserting Python List into Pandas DataFrame Rows and Setting Row Values to NaN
In this article, we will explore how to insert a new row with just the ticker date into a specific column of a Pandas DataFrame. We will also discuss how to set remaining values of rows where list values inserted into “Date” column to NaN.
Introduction to Pandas DataFrames
Before diving into the solution, let’s first cover some basic concepts and terminology related to Pandas DataFrames.
A Pandas DataFrame is a two-dimensional table of data with rows and columns. Each row represents a single observation or record, while each column represents a variable or attribute of that observation.
DataFrames are widely used in data analysis, machine learning, and scientific computing for efficient storage, manipulation, and analysis of structured data.
Importing Libraries
To work with Pandas DataFrames, we will need to import the necessary libraries. In this case, we’ll be using NumPy (np) for numerical computations and Pandas itself for data manipulation and analysis.
import pandas as pd
import numpy as np
Creating a Sample DataFrame
Let’s create a sample DataFrame with some sample data to work with.
# Create a sample DataFrame
data = {
'ticker': ['AAPL.OQ', 'ABBV.N', 'ABT.N', 'ACN.N', 'ADBE.OQ'],
'Date': ['2021-11-24', '2021-11-25', '2021-11-26', '2021-11-27', '2021-11-28']
}
df = pd.DataFrame(data)
print(df)
Output:
ticker Date
0 AAPL.OQ 2021-11-24
1 ABBV.N 2021-11-25
2 ABT.N 2021-11-26
3 ACN.N 2021-11-27
4 ADEBE.OQ 2021-11-28
Inserting New Rows with Just the Ticker Date
Now, let’s insert a new row with just the ticker date using the loc method.
# Create a list of NaN values minus 1 (due to the date)
to_append = [np.NAN] * df.shape[1] - 1
# Set the index to the 'Date' column so we can append using the loc method
df['Date'] = df['Date'].astype(str)
# Iterate over the list dates and append them to your data frame
for date in ['2021-12-01', '2021-12-02', '2021-12-03', '2021-12-06']:
df.loc[date] = to_append
print(df)
Output:
ticker Date
0 AAPL.OQ 2021-11-24 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
Last modified on 2024-01-19