Python在函数中写入数据帧

2024-09-28 05:19:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我相信这一定是直截了当的,但我已经尝试解决这一问题几天了,我想我知道我做错了什么,但我被各种想法难住了:

我使用一个函数来子集一个数据帧,并基于子集在该子集中创建一个新列并填充它。这是可行的,但除非我将其分配回名为mod_df的新数据帧,否则我无法将其返回到df中

似乎在函数结束后,数据丢失了

如果您有任何想法,我将不胜感激

mod_df = []

def Pop_Gen(lower, upper, val):
    x = df[(df['byear'] >= lower) &  (df['byear'] <= upper)].assign(Gen = val)
    mod_df.append(x)

for index, row in gen_Ref_df.iterrows():
    Pop_Gen(row.lower,row.upper,row.val)

输入

第一数据帧:

df:

   Name  byear  
0  John  1980  
1  Mary  1990 

第二数据帧:

gen_Ref_df:

   val   lower   upper  
0  old   1970    1985  
1  new   1986    1995

电流输出

mod_df:

   Name  byear Gen  
0  John  1980  old  
1  Mary  1990  new

预期输出(在df中,无需投入mod_df

df:

   Name  byear Gen  
0  John  1980  old  
1  Mary  1990  new  

Tags: 数据函数namemoddfnewvaljohn
1条回答
网友
1楼 · 发布于 2024-09-28 05:19:20

假设dfgen_Ref_df的行数相同,我将执行以下操作:

# These should be your input DataFrame

d = {'name': ['John', 'Mary'], 'byear': [1980, 1990]}
df = pd.DataFrame(data=d)

d = {'val': ['old', 'new'], 'lower': [1970, 1986], 'upper': [1985, 1995]}
gen_Ref_df = pd.DataFrame(data=d)


# Replace the for loop and the function call with a single line
# Create a new column 'Gen' in df and populate each row with the Gen val obtained by the two conditions 
df['Gen'] = gen_Ref_df[(df['byear'] >= gen_Ref_df.lower) & (df['byear'] <= gen_Ref_df.upper)].assign(Gen = gen_Ref_df.val).Gen

print(df)

结果

   name  byear  Gen
0  John   1980  old
1  Mary   1990  new

相关问题 更多 >

    热门问题