【发布时间】:2021-07-08 16:22:34
【问题描述】:
我很难将选定的数据从 pd.df 转换为 np.array。相反,我得到了一个数组数组。我现在想知道为什么我不立即返回一个正常的数组,拜托。我知道to_numpy(),但它不会产生预期的结果。我也不能替换 nan 值。请您帮我理解一下,请问这是怎么回事?非常感谢!祝你有美好的一天。
我的小例子:
import pandas as pd
import numpy as np
#prepare the example
d={}
d['key1']=np.array([np.nan,2,np.nan,4])
d['key2']=np.array([5,6,7,8])
d['key3']=np.array([9,10,11,12])
print(d)
print(type(d))
# create example df
df=pd.DataFrame(index=[0,1,2,3,4,5],columns=['A','B'])
df.at[0,'A'] = d
df.at[1,'A'] = d
df.at[2,'A'] = d
df.at[3,'A'] = d
df.at[4,'A'] = d
df.at[5,'A'] = d
df
# extract data from selected rows
res1=df.loc[[1,2,3],'A'].apply(lambda x: x.get('key2')).to_numpy()
print(res1)
print(res1.shape) #(3,)
#res1 is an object filled with arrays.
#Why would I not get back immediately an array (3,4), please?
#How can I get a np.array like this, please?
#res2=np.array([[5, 6, 7, 8],[5, 6, 7, 8],[5, 6, 7, 8]])
#res2.shape #(3,4)
# The solution I found:
res3=np.stack(res1,axis=0)
print(res3)
print(type(res3))
print(res3.shape)
#Is there something better that results immediately in a np.ndarray with (3,4)?
#How can I replace the nan values, please?
res4=df.loc[[1,2,3],'A'].apply(lambda x: x.get('key1')).to_numpy(na_value=0)
print(res4) #nan not 0
谢谢。
编辑:我澄清了第二个问题。例如,我只想用 0 替换 nan。在现实世界的示例中,并非所有 key1 的数组都包含 nan。我需要保持每个数组中的元素数量相同。对不起。有人明白为什么我的例子确实给出了预期的结果吗?谢谢。
【问题讨论】:
标签: python arrays pandas numpy