I have a list ['A', 'B', 'C']
and a dataframe
1
2
3
4
The dataframe has no columns as of yet
How can I create a dataframe that looks like this?
A B C
1
2
3
4
CodePudding user response:
Use index
and column
arguments of dataframe constructor as:
import pandas as pd
pd.DataFrame(columns = ['A', 'B', 'C'],
index=range(1,5))
Output:
A | B | C | |
---|---|---|---|
1 | nan | nan | nan |
2 | nan | nan | nan |
3 | nan | nan | nan |
4 | nan | nan | nan |
CodePudding user response:
If you have a dataframe, you can create a column with NaN value by df[col] = pd.NA
. That's also applied to a list of columns
lst = ['A', 'B', 'C']
df[lst] = pd.NA
print(df)
A B C
1 <NA> <NA> <NA>
2 <NA> <NA> <NA>
3 <NA> <NA> <NA>
4 <NA> <NA> <NA>