Reputation: 10058
I'm getting:
AssertionError: 14 columns passed, passed data had 12
columns.
Error is self-explanatory, I'm creating a DataFrame from a list of lists, each list in fact contains 12 fields. How can I force pandas.DataFrame to add extra columns with NaN in one operation. This is how Im creating the df.
pandas.DataFrame(results, columns=FIELDS)
Is there a way to simplify this in DataFrame creation, without having to do this:
pandas.DataFrame(results, columns=FIELDS_12)
df["ExtraField13"] = np.nan
df["ExtraField14"] = np.nan
Upvotes: 0
Views: 1923
Reputation: 12515
Well, you don't really have to hard-code things like you have above with individual column assignments, line-by-line. This does a similar thing but uses a loop instead to pad columns:
>>> import pandas as pd
>>> df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})
>>> df
A B
0 1 4
1 2 5
2 3 6
>>> def pad_cols(df, n_cols):
... while len(df.columns) < n_cols:
... df['padded' + str(len(df.columns)+1)] = None
... return df
...
>>> pad_cols(df, 4)
A B padded3 padded4
0 1 4 None None
1 2 5 None None
2 3 6 None None
Upvotes: 1