[英]Store np.float64 and np.array values as column values in dataframe
I have two numpy arrays and dataframe as given below我有两个 numpy arrays 和 dataframe 如下所示
val = np.array([0.501,0.32])
values = np.arange(24).reshape((2,3,4))
input_df = pd.DataFrame(columns=['colname_' + str(i) for i in range(4)])
I would like to我想要
a) Create a new dataframe (dummy) with 3 columns such as ROW_ID
, FEATURE NAME
, Contribution
a) 创建一个新的 dataframe(虚拟),其中包含 3 列,例如
ROW_ID
、 FEATURE NAME
、 Contribution
b) values for dummy dataframe should be populated using np.array
above and column names from
input_df` b) 虚拟 dataframe 的值应该使用上面的
np.array
和 input_df 中的column names from
填充
c) Under the Feature Name
column use the input_df column names c) 在
Feature Name
列下使用 input_df 列名称
b) Populate the val[0]
as contribution
in dummy dataframe and also use each element from values[0][1]
to populate it in contribution
column. b) 将
val[0]
填充为虚拟 dataframe 中的contribution
,并使用values[0][1]
中的每个元素将其填充到contribution
列中。 I tried the below code我试过下面的代码
pd.DataFrame({
"Feature Name": ["Base value"] + [f"{col}" for col in df.columns.tolist()],
"Contribution": (val[0].tolist()) + list(values[0][1])
})
But I get an error message但我收到一条错误消息
TypeError: unsupported operand type(s) for +: 'float' and 'list'
类型错误:+ 不支持的操作数类型:'float' 和 'list'
Or I also receive another error which is或者我也收到另一个错误是
ValueError: All arrays must be of the same length
ValueError:所有 arrays 必须具有相同的长度
I expect my output to be like as shown below我希望我的 output 如下所示
update - real data issue更新 - 真实数据问题
Try:尝试:
pd.DataFrame({
"Feature Name": ["Base value"] + [f"{col}" for col in df.columns.tolist()],
"Contribution": (val[:1].tolist()) + list(values[0][1])
# ^^^^
})
val[0]
makes it a scalar value, even followed by .tolist()
val[0]
使其成为标量值,甚至后跟.tolist()
>>> type(val[0].tolist())
<class 'float'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.