我想向 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不是 dtype int?我可以以某種方式指定這個嗎?像.apply(..., dtypes=[int, float])什么?
uj5u.com熱心網友回復:
你可以鏈接 astype
df.apply(apply_fn, axis=1, result_type='expand').astype({0:'int', 1:'float'})
Out[147]:
0 1
0 1 0.0
1 2 1.0
2 3 0.5
uj5u.com熱心網友回復:
我相信發生這種情況是因為result_type='expand'導致擴展為一個系列,所以第一行在它自己的系列中,然后是下一行,等等。但是,因為系列物件只能有一個 dtype,整數被轉換為浮點數。
例如,看看這個:
>>> pd.Series([1, 0.0])
0 1.0
1 0.0
dtype: float64
一種解決方法是呼叫tolist呼叫apply,并將其包裝在呼叫中DataFrame:
>>> df[['c', 'd']] = pd.DataFrame(df.apply(apply_fn, axis=1).tolist())
a b c d
0 0 1 1 0.0
1 1 1 2 1.0
2 1 2 3 0.5
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/422944.html
標籤:
