Im使用此语法预分配列并将0分配给所有列:
data['Base'] = 0
data['Base_Chg'] = 0
data['Base_5D_Chg'] = 0
data['Year_Low'] = 0
data['Year_High'] = 0
data['Market_Cap'] = 0
data['PE_Ratio'] = 0
data['SMA_50'] = 0
data['SMA_100'] = 0
data['SMA_200'] = 0
data['RSI'] = 0
data['ADX'] = 0
data['ATR'] = 0
data['STDEV'] = 0
有什么方法可以用更少的代码行做同样的事情吗?
在python中使用熊猫。
Thx!
您可以使用OrderedDict对关键字参数进行解包。
import collections as co
od = co.OrderedDict({'Base':0,'Base_Chg':0,'Base_5D_Chg':0})
data.assign(**od)
结果:
In [18]: data.assign(**od)
Out[18]:
a Base Base_Chg Base_5D_Chg
0 1 0 0 0
1 2 0 0 0
2 3 0 0 0
至少,您仍然需要写出所有新列的名称。
你可以使用一个循环:
columns=['Base', 'Base_Chg', 'Base_5D_Chg', 'Year_Low', 'Year_High', 'Market_Cap', 'PE_Ratio', 'SMA_50', 'SMA_100', 'SMA_200', 'RSI', 'ADX', 'ATR', 'STDEV']
for col in columns:
df[col] = 0
或pd.concat
:
columns=['Base', 'Base_Chg', 'Base_5D_Chg', 'Year_Low', 'Year_High', 'Market_Cap', 'PE_Ratio', 'SMA_50', 'SMA_100', 'SMA_200', 'RSI', 'ADX', 'ATR', 'STDEV']
new_df = pd.DataFrame(0, columns=columns, index=df.index)
df = pd.concat([df, new_df], axis=1)
测试一下哪一个更适合您的用例。
假设列名在列表中,我们创建一个以键为列名、以0为值的字典。然后,我们对df1进行插入式连接。
cols = ['Base',
'Base_Chg',
'Base_5D_Chg',
'Year_Low',
'Year_High',
'Market_Cap',
'PE_Ratio',
'SMA_50',
'SMA_100',
'SMA_200',
'RSI',
'ADX',
'ATR',
'STDEV']
df1 = pd.DataFrame({'A' : [0,1,2,3]}) # your original dataframe.
df2 = pd.DataFrame(dict(zip(cols,[0] * len(cols))),index=[0])
#new dataframe from list of cols.
df3 = pd.merge(df1.assign(key='key'),df2.assign(key='key'),how='outer').drop('key',axis=1)
#merge of your old dataframe and new.
print(df1)
A
0 0
1 1
2 2
3 3
print(df2)
Base Base_Chg Base_5D_Chg Year_Low Year_High Market_Cap PE_Ratio
0 0 0 0 0 0 0 0
SMA_50 SMA_100 SMA_200 RSI ADX ATR STDEV
0 0 0 0 0 0 0 0
print(df3)
A Base Base_Chg Base_5D_Chg Year_Low Year_High Market_Cap PE_Ratio
0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0
2 2 0 0 0 0 0 0 0
3 3 0 0 0 0 0 0 0
SMA_50 SMA_100 SMA_200 RSI ADX ATR STDEV
0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0