我想在数据框中添加一列,以便求和相应行中所有值的总和
例如:
1 2 Column I Want to Add
4 9 13
7 1 8
答案 0 :(得分:2)
您可以df.sum(axis = 1)
,这将创建一个新列(而不是一行):
import pandas as pd
df = pd.DataFrame({1: [4, 7], 2: [9, 1]})
df['COLUMN I Want to Add'] = df.sum(axis = 1)
print(df)
输出:
1 2 COLUMN I Want to Add
0 4 9 13
1 7 1 8
答案 1 :(得分:0)
public static IEnumerableExt {
public static List<MemberInfo> GetPropertiesOrFields(this Type t, BindingFlags bf = BindingFlags.Public | BindingFlags.Instance) =>
t.GetMembers(bf).Where(mi => mi.MemberType == MemberTypes.Field || mi.MemberType == MemberTypes.Property).ToList();
public static DataTable ToDataTable<T>(this IEnumerable<T> rows) {
var dt = new DataTable();
if (rows.Any()) {
var memberInfos = typeof(T).GetPropertiesOrFields();
foreach (var info in memberInfos)
dt.Columns.Add(new DataColumn(info.Name, info.GetMemberType()));
foreach (var r in rows)
dt.Rows.Add(memberInfos.Select(i => i.GetValue(r)).ToArray());
}
return dt;
}
}