如何根据数据框架和值列表的零值创建新列表?

发布于 2025-01-30 05:34:50 字数 805 浏览 2 评论 0原文

我有一个数据框架和列表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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

与君绝 2025-02-06 05:34:50

假设op的大小必须是年龄的非nan值的大小:

s = df1['Age'].copy()
op=[1,2]
s[s.notna()] = op
out = s.to_list()

输出:[1.0,NAN,2.0,NAN]

Assuming the size of op is necessarily that of the non-nan values of Age:

s = df1['Age'].copy()
op=[1,2]
s[s.notna()] = op
out = s.to_list()

output: [1.0, nan, 2.0, nan]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文