我有一个包含此列结构的数据框:
<pre>
In [179]: df.dtypes
Out[179]:
layer int32
row int32
column int32
segment int32
reach int32
Qin float64
Qaquifer float64
Qout float64
Qovr float64
Qprecip float64
Qet float64
stage float64
depth float64
width float64
Cond float64
Qwt float64
deltaUZ float64
GWh float64
kstpkper object
k int32
i int32
j int32
dtype: object
In [180]: df.kstpkper
Out[180]:
0 (0, 0)
1 (0, 0)
2 (0, 0)
3 (0, 0)
4 (0, 0)
5 (0, 0)
...
18207 (35, 10)
18208 (35, 10)
18209 (35, 10)
18210 (35, 10)
18211 (35, 10)
18212 (35, 10)
Name: kstpkper, dtype: object
</pre>
我想将kstpkper变量分成两部分并将它们添加到我的数据帧中。有可能吗?
如何调用kstpkper变量中的每个元素?
任何帮助将不胜感激。
答案 0 :(得分:0)
列表理解是一种方式:
df['kstpkper1'] = [x[0] for x in df.kstpkper.values]
df['kstpkper2'] = [x[1] for x in df.kstpkper.values]
答案 1 :(得分:0)
有效的方法是从kstpkper
值构建新数据框,并使用现有数据框构建join
考虑测试数据框df
df = pd.DataFrame(dict(
A=[1, 2, 3],
kstpkper=[(0, 0), (1, 2), (5, 11)],
C=np.ones(3)
))
print(df)
A C kstpkper
0 1 1.0 (0, 0)
1 2 1.0 (1, 2)
2 3 1.0 (5, 11)
然后我们像这样构建和加入
df.join(pd.DataFrame(df.kstpkper.tolist(), df.index, ['kstpkper1', 'kstpkper2']))
A C kstpkper kstpkper1 kstpkper2
0 1 1.0 (0, 0) 0 0
1 2 1.0 (1, 2) 1 2
2 3 1.0 (5, 11) 5 11