在python中使用Pandas将列添加到数据框

时间:2018-02-13 11:55:20

标签: python pandas

我正在尝试使用pandas对Excel文件进​​行一些操作。我想从excel文件中提取一些列,并将另一列添加到这些提取的列中。并希望将所有列写入新的excel文件。为此,我必须将新列附加到旧列。

这是我的代码 -

import pandas as pd

#Reading ExcelFIle 
#Work.xlsx is input file

ex_file = 'Work.xlsx'
data = pd.read_excel(ex_file,'Data')

#Create subset of columns by extracting  columns D,I,J,AU from the file 
data_subset_columns = pd.read_excel(ex_file, 'Data', parse_cols="D,I,J,AU") 

#Compute new column 'Percentage' 
#'Num Labels' and 'Num Tracks' are two different columns in given file 

data['Percentage'] = data['Num Labels'] / data['Num Tracks']
data1 = data['Percentage']
print data1

#Here I'm trying to append data['Percentage'] to data_subset_columns 
Final_data = data_subset_columns.append(data1)
print Final_data
Final_data.to_excel('111.xlsx') 

未显示错误。但是Final_data没有给我预期的结果。 (数据未附加)

2 个答案:

答案 0 :(得分:3)

无需在pandas中明确附加列。计算新列时,它将包含在数据框中。将其导出为ex​​cel时,将包含新列。

试试这个,假设'Num Labels'和'Num Tracks'在“D,I,J,AU”中[另外添加]:

import pandas as pd

data_subset = pd.read_excel(ex_file, 'Data', parse_cols="D,I,J,AU") 
data_subset['Percentage'] = data_subset['Num Labels'] / data_subset['Num Tracks']
data_subset.to_excel('111.xlsx') 

答案 1 :(得分:1)

数据框的append函数会向数据框添加行而不是列。好吧,如果附加行的列数多于源数据帧中的列数,它会添加列。

  

DataFrame.append(其他,ignore_index = False,verify_integrity = False)[来源]

     

将其他追加到此框架的末尾,返回一个新对象。不在此框架中的列将添加为新列。

我认为您正在寻找类似concat的内容。

  

通过传入轴= 1,沿x轴水平组合DataFrame对象。

>>> df1 = pd.DataFrame([['a', 1], ['b', 2]],
...                    columns=['letter', 'number'])
>>> df4 = pd.DataFrame([['bird', 'polly'], ['monkey', 'george']],
...                    columns=['animal', 'name'])
>>> pd.concat([df1, df4], axis=1)
  letter  number  animal    name
0      a       1    bird   polly
1      b       2  monkey  george