This post is also available in: 日本語 (Japanese)
This is a note about how to create pandas dataframe columns by serial number or list items using for statement.
f"sample_{i}" in the code below is used f-string which is introduced from Python3.6.
Especially, it is usefull to create a lot of features when program machine learning.
Contents
Create dataframe columns by serial number using for statement.
import pandas as pd #Create dataframe columns by serial number df = pd.DataFrame() for i in range(1,5,1): df[f"sample_{i}"] = [11,22,33] print(df) """ #output sample_1 sample_2 sample_3 sample_4 0 11 11 11 11 1 22 22 22 22 2 33 33 33 33 """
Create dataframe columns by list items using for statement.
import pandas as pd #Create dataframe columns by list items df2 = pd.DataFrame() items = [1,5,'a','b'] for i in items: df2[f"sample_{i}"] = [11,22,33] print(df2) """ #output sample_1 sample_5 sample_a sample_b 0 11 11 11 11 1 22 22 22 22 2 33 33 33 33 """No tags for this post.