如何根据数据框架和值列表的零值创建新列表?
我有一个数据框架和列表op
,如下所示。
data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, np.nan, 19, np.nan]}
df1=pd.DataFrame(data)
print(df1)
Name Age
Tom 20.0
Joseph NaN
Krish 19.0
John NaN
op=[1,2]
现在,我想根据列'Age'
创建创建一个新列表。如果列age
具有一个值,则新列表li
应附加op
第一个值以及列age
具有null
,那么新列表应将该值以Null为单位。我该如何实现? 尽管我试图循环遍历每一行以创建列表,但是输出是错误的,并且在我穿过每一行时需要花费时间来运行。
li=[]
for k in range(len(df1)) :
if df1.loc[k,'Age']== np.nan:
print('i')
li.append(np.nan)
else:
for j in op:
li.append(j)
print(li)
输出: - [1,2,1,2,1,2,1,2]
执行的输出: -
[1,np.nan,2,np.nan]
I have a data frame and list op
like below.
data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, np.nan, 19, np.nan]}
df1=pd.DataFrame(data)
print(df1)
Name Age
Tom 20.0
Joseph NaN
Krish 19.0
John NaN
op=[1,2]
Now I want to create create a new list based on the column 'age'
. If the column age
has a value then the new list li
should append op
first value and if the column age
has a null
then the new list should append the value at that position as null. How can I achieve this?
Though I tried to loop through every row to create list but the output is wrong and it takes a loot of time to run as I am lopping through every row.
li=[]
for k in range(len(df1)) :
if df1.loc[k,'Age']== np.nan:
print('i')
li.append(np.nan)
else:
for j in op:
li.append(j)
print(li)
output:- [1, 2, 1, 2, 1, 2, 1, 2]
Execpted output:-
[1,np.nan,2,np.nan]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设
op
的大小必须是年龄的非nan值的大小:输出:
[1.0,NAN,2.0,NAN]
Assuming the size of
op
is necessarily that of the non-nan values of Age:output:
[1.0, nan, 2.0, nan]