我有以下pandas数据帧:
Category Symbol Quantity Cost Price
1 Stocks AKAM 200 49.22696796
3 Stocks APA 1900 50.607305856
8 Options AA 30JUN17 27.0 P 17 0.127931
11 Options AA 30JUN17 28.0 P -17 0.172045076
14 Options AABA 21JUL17 60.0 C -7 0.34204137
17 Options AABA 21JUL17 62.5 C 7 0.217931
我想在符号选项类别中插入列。像这样:
Category Symbol Expiry Strike Right Quantity Cost Price
1 Stocks AKAM 200 49.22696796
3 Stocks APA 1900 50.607305856
8 Options AA 30JUN17 27.0 P 17 0.127931
11 Options AA 30JUN17 28.0 P -17 0.172045076
14 Options AABA 21JUL17 60.0 C -7 0.34204137
17 Options AABA 21JUL17 62.5 C 7 0.217931
我尝试了以下代码,但它不起作用:
for i, row in s.iterrows():
if len(s.Symbol[i])>4:
s = s.set_value(i, "Symbol", s.Symbol[i].split(' ',1).tolist(), columns = ["Symbol", "Expiry", "Strike", "Right" ])
感谢任何帮助。谢谢!
答案 0 :(得分:3)
让我们assign
和split
:
df.assign(**df.Symbol.str.split(' ',expand=True).rename(columns={0:'Symbol',1:'Expiry',2:'Strike',3:'Right'}))
输出:
Category Symbol Quantity Cost Price Expiry Right Strike
1 Stocks AKAM 200 49.226968 None None None
3 Stocks APA 1900 50.607306 None None None
8 Options AA 17 0.127931 30JUN17 P 27.0
11 Options AA -17 0.172045 30JUN17 P 28.0
14 Options AABA -7 0.342041 21JUL17 C 60.0
17 Options AABA 7 0.217931 21JUL17 C 62.5
答案 1 :(得分:1)
使用pd.DataFrame([x.split() for x in df.Symbol])
In [34]: df
Out[34]:
Symbol
0 a
1 a b c
2 d e f
In [35]: df[['Symbol','c1','c2']]=pd.DataFrame([x.split() for x in df.Symbol])
In [36]: df
Out[36]:
Symbol c1 c2
0 a None None
1 a b c
2 d e f