【问题标题】:Naming dataframe columns based on the content of one of the row indices根据行索引之一的内容命名数据框列
【发布时间】:2021-04-10 21:26:48
【问题描述】:

这是我读取 csv 文件并将其拆分为列后的数据框。

Index         0                  1         2

0   Dylos Logger v 1.6.0.0      None      None
1   Unit: DC1700 v 2.08         None      None

2   Date/Time: 12-07-15 11:11   None      None

3   -------------------------   None      None

4   Particles per cubic foot    None      None

5   -------------------------   None      None

6   Date/Time                   Small     Large

7   11-27-15 10:08              161200    8300

8   11-27-15 10:09              136500    8700

9   11-27-15 10:10              124000    8400
 
10  11-27-15 10:11              127300    7900

我想根据第 6 行索引中的内容命名我的列,然后去掉前 6 个索引,并将索引从零重置。这意味着我希望我的数据看起来像这样:

0   Date/Time                  Small     Large

1   11-27-15 10:08             161200    8300

2   11-27-15 10:09             136500    8700

3   11-27-15 10:10             124000    8400

4   11-27-15 10:11             127300    7900

我知道如何删除前 6 行并保留索引。但我不知道如何在第一步根据第 6 行重命名列名。你能帮帮我吗?

谢谢

【问题讨论】:

标签: python dataframe multiple-columns rename spyder


【解决方案1】:
import pandas as pd

df = pd.DataFrame({'0':['a','Date/Time','x'],'1':['b','Small','y'],'2':['c','Large','z']})
row_with_column_names = 1 #would be 6 for you
df = df.rename(columns={cur_name:new_name for cur_name,new_name in zip(df,df.iloc[row_with_column_names,:])}) #rename
df = df.drop(row_with_column_names,axis='index') #remove the row with the names in it
df = df.reset_index(drop=True) 
df

#Produces
#   Date/Time   Small   Large
#0  a   b   c
#1  x   y   z

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2014-03-04
    • 2018-10-22
    • 1970-01-01
    • 2019-11-01
    • 2018-08-14
    • 1970-01-01
    相关资源
    最近更新 更多