gpt4 book ai didi

python - 使用 Pandas 读取数据并将其设置为 DataFrame 的索引

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:56 24 4
gpt4 key购买 nike

我想遍历 DataFrame 的行并将值分配给新的 DataFrame。我已经像这样间接地完成了这项任务:

#first I read the data from df1 and assign it to df2 if something happens
counter = 0 #line1
for index,row in df1.iterrows(): #line2
value = row['df1_col'] #line3
value2 = row['df1_col2'] #line4
#try unzipping a file (pseudo code)
df2.loc[counter,'df2_col'] = value #line5
counter += 1 #line6
#except
print("Error, could not unzip {}") #line7

#then I set the desired index for df2
df2 = df2.set_index(['df2_col']) #line7

有没有办法直接在第 5 行中将值分配给 df2 的索引?对不起,我原来的问题不清楚。我正在根据正在发生的事情创建一个索引。

最佳答案

有很多方法可以做到这一点。根据您的代码,您所做的只是创建一个空的 df2 数据框,其中包含 df1.df1_col 中的值索引。您可以像这样直接执行此操作:

df2 = pd.DataFrame([], df1.df1_col)
# ^ ^
# | |
# specifies no data, yet |
# defines the index

如果您担心必须过滤 df1 那么您可以这样做:

# cond is some boolean mask representing a condition to filter on.
# I'll make one up for you.
cond = df1.df1_col > 10
df2 = pd.DataFrame([], df1.loc[cond, 'df1_col'])

关于python - 使用 Pandas 读取数据并将其设置为 DataFrame 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com