我有一个DataFrame。我想创建一个名为sum_columns的新列,它是所有现有数值列的总和。当我尝试这样做时:
sum_columns
df["sum_columns"] = df.select_dtypes(include="number").apply(np.sum)
该列仅包含NaN。显然我漏掉了什么。
NaN
ajsxfq5m1#
import pandas as pd df = pd.DataFrame({"col1": ['a', 'b', 'c'], "col2": [1, 2, 3], "col3": ['d', '1', 2], "col4": [4, 5, 6]}) df['sum_col'] = df.select_dtypes(include='number').sum(axis=1) print(df) col1 col2 col3 col4 sum_col 0 a 1 d 4 5 1 b 2 1 5 7 2 c 3 2 6 9
1条答案
按热度按时间ajsxfq5m1#