【问题标题】:Is there any way to set row to column-row in DataFrame? or How to get DataFrame from Excel file with setting any index row to column_row?有没有办法在 DataFrame 中将行设置为列行?或如何通过将索引行设置为列行从 Excel 文件中获取 DataFrame?
【发布时间】:2020-11-05 19:24:42
【问题描述】:

Q1) 有没有办法在 DataFrame 中将行设置为列行?

     (DF)                                      (DF)
   A  B  C  D                                a  b  c  d
0  a  b  c  d       pandas function       0  4  5  3  6
1  4  5  3  6 ==========================> 1  3  2  5  3
2  3  2  5  3  0-idx row to columns-row   2  4  7  9  0
3  4  7  9  0

Q2) 如何通过将任何索引行设置为 column_row 从 Excel 文件中获取 DataFrame?

(EXCEL or CSV)                                 (DF)
   A  B  C  D                                a  b  c  d
0  a  b  c  d       pd.read_excel()       0  4  5  3  6
1  4  5  3  6 ==========================> 1  3  2  5  3
2  3  2  5  3  0-idx row to columns-row   2  4  7  9  0
3  4  7  9  0

【问题讨论】:

标签: python excel pandas dataframe csv


【解决方案1】:

你可以试试:

import pandas as pd
data={"A":['a',4,3,4],"B":['b',5,2,7],"C":['c',3,5,9],"D":['d',6,3,0]}

df=pd.DataFrame(data)

#define the column name from line index 0
df.columns=df.iloc[0].tolist()
#remove the line index 0
df = df.drop(0)

结果:

   a  b  c  d
1  4  5  3  6
2  3  2  5  3
3  4  7  9  0

【讨论】:

    【解决方案2】:

    这样就可以了:

    new_header = df.iloc[0] #first_row
    df = df[1:] #remaining_dataframe
    df.columns = new_header
    

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 2020-08-27
      • 2019-10-27
      • 1970-01-01
      • 2021-12-09
      • 2020-11-14
      • 2017-05-05
      • 2016-05-16
      • 1970-01-01
      相关资源
      最近更新 更多