我想向DataFrame中添加多列:
import pandas as pd
df = pd.DataFrame(
[
(0, 1),
(1, 1),
(1, 2),
],
columns=['a', 'b']
)
def apply_fn(row) -> (int, float):
return int(row.a + row.b), float(row.a / row.b)
df[['c', 'd']] = df.apply(apply_fn, result_type='expand', axis=1)
结果:
>>> df
a b c d
0 0 1 1.0 0.0
1 1 1 2.0 1.0
2 1 2 3.0 0.5
>>> df.dtypes
a int64
b int64
c float64
d float64
dtype: object
为什么列
c
的数据类型不是int
?有没有办法指定它为int
类型?例如像.apply(..., dtypes=[int, float])
这样的方式。
df['c'] = df['a'] + df['b']
呢?是的,有一个很好的理由。这只是一个玩具示例。 - MrTomRod