将项添加到空pandas DataFrame

时间:2016-09-27 06:23:56

标签: python pandas dataframe

我想以下列方式动态扩展空的pandas DataFrame:

df=pd.DataFrame()
indices=['A','B','C']
colums=['C1','C2','C3']
for colum in colums:
    for index in indices:
        #df[index,column] = anyValue

如果索引和列都可以具有事先未知的任意大小,即我无法提前创建具有正确大小的DataFrame。

我可以使用哪种pandas功能

#df[index,column] = anyValue

2 个答案:

答案 0 :(得分:3)

我认为您可以使用loc

df = pd.DataFrame()

df.loc[0,1] = 10
df.loc[2,8] = 100
print(df)
      1      8
0  10.0    NaN
2   NaN  100.0

使用DataFrame.set_value加快解决方案:

df = pd.DataFrame()
indices = ['A', 'B', 'C']
columns = ['C1', 'C2', 'C3']
for column in columns:
    for index in indices:
       df.set_value(index, column, 1)

print(df)
    C1   C2   C3
A  1.0  1.0  1.0
B  1.0  1.0  1.0
C  1.0  1.0  1.0

答案 1 :(得分:2)

loc效果很好,但是......
对于单个作业,请使用at

df = pd.DataFrame()
indices = ['A', 'B', 'C']
columns = ['C1', 'C2', 'C3']
for column in columns:
    for index in indices:
        df.at[index, column] = 1

df

enter image description here

.at vs .loc vs .set_value时间

enter image description here