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

标签 python pandas dataframe

我想迭代 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/

相关文章:

python - 如何计算 Pandas 数据框中列中唯一元素的数量

python - Xlsxwriter:类型错误: "expected string or buffer"

python - '..' 中的未知列 'field list' -on 将对象插入到 mySQL 中

Python:将 n 元组转换为 x 元组,其中 x < n

python - 使用 Python 根据某些条件搜索数据集并返回值

python - 如何替换数据框中行中的字符?

python - scikit-learn 中聚类超参数评估的网格搜索

python - 从日期时间对象中提取两位而不是四位数字年份

python - 将 numpy.digitize 扩展到多维数据

python - 在 Pandas 中,如何在 groupby.agg() 方法中应用 2 个自定义公式?