2013-08-17 315 views
13

我怎么能在大熊猫数据帧丢弃或禁用索引?禁用索引大熊猫数据帧

我正在从“python for data analysis”一书中学习熊猫,我已经知道我可以使用dataframe.drop删除一列或一行。但是我没有发现任何有关禁用所有指数的事情。

回答

10

df.values给你生与NumPy ndarray没有索引。

>>> df 
    x y 
0 4 GE 
1 1 RE 
2 1 AE 
3 4 CD 
>>> df.values 
array([[4, 'GE'], 
     [1, 'RE'], 
     [1, 'AE'], 
     [4, 'CD']], dtype=object) 

你不能没有索引的数据帧,它们是数据帧:)

但仅仅是明确的,这种操作是不就地整点:

>>> df.values is df.values 
False 

DataFrame将数据保存在按类型分组的二维数组中,因此当您需要整个数据框时,它必须找到所有dtype的LCD并构建该类型的二维数组。

从旧的实例化值的新的数据帧,只是通过旧数据框到新的构造,没有数据将被复制相同的数据结构将被重用:

>>> df1 = pd.DataFrame([[1, 2], [3, 4]]) 
>>> df2 = pd.DataFrame(df1) 
>>> df2.iloc[0,0] = 42 
>>> df1 
    0 1 
0 42 2 
1 3 4 

但你可以明确指定copy参数:

>>> df1 = pd.DataFrame([[1, 2], [3, 4]]) 
>>> df2 = pd.DataFrame(df1, copy=True) 
>>> df2.iloc[0,0] = 42 
>>> df1 
    0 1 
0 1 2 
1 3 4 
+0

谢谢。我所做的就是用旧数据帧的值启动一个新的数据帧。 – GeauxEric

+1

更新了答案。 –

+0

我想我真正想要做的是将数据写入没有索引的文件,并且可以通过设置index = False轻松完成。对不起,我并没有把问题放在第一位。你的回答非常直观。 – GeauxEric

0

我有一个功能,可以帮助一些。我以下列方式在python结合CSV文件以及头:

def combine_csvs(filedict, combined_file): 
     files = filedict['files'] 
     df = pd.read_csv(files[0]) 
     for file in files[1:]: 
      df = pd.concat([df, pd.read_csv(file)]) 
     df.to_csv(combined_file, index=False) 
     return df 

,因为你需要它可以采取尽可能多的文件。调用此为:

combine_csvs(dict(files=["file1.csv","file2.csv", "file3.csv"]), 'output.csv') 

或者,如果你正在阅读的数据帧中的蟒蛇为:

df = combine_csvs(dict(files=["file1.csv","file2.csv"]), 'output.csv') 

的combine_csvs温控功能不保存索引。如果您需要索引,请使用'index = True'。

0
d.index = range(len(d)) 

执行一个简单的就地索引复位 - 即,它会删除所有现有索引的,并增加了一个基本的整数之一,这是最基本的折射率型熊猫数据帧可以具有。

1

我有一个类似的问题,试图从无索引CSV获取DataFrame并将其写回到另一个文件。

我想出了以下内容:

import pandas as pd 
import os 

def csv_to_df(csv_filepath): 
    # the read_table method allows you to set an index_col to False, from_csv does not 
    dataframe_conversion = pd.io.parsers.read_table(csv_filepath, sep='\t', header=0, index_col=False) 
    return dataframe_conversion 

def df_to_excel(df): 
    from pandas import ExcelWriter 
    # Get the path and filename w/out extension 
    file_name = 'foo.xlsx' 
    # Add the above w/ .xslx 
    file_path = os.path.join('some/directory/', file_name) 
    # Write the file out 
    writer = ExcelWriter(file_path) 
    # index_label + index are set to `False` so that all the data starts on row 
    # index 1 and column labels (called headers by pandas) are all on row index 0. 
    df.to_excel(writer, 'Attributions Detail', index_label=False, index=False, header=True) 
    writer.save() 
0

此外,如果您使用的是pd.ExcelWriterdf.to_excel功能,这是它被写入到一个Excel工作表中,你可以指定你的参数index=False有。

创建Excel作者:

writer = pd.ExcelWriter(type_box + '-rules_output-' + date_string + '.xlsx',engine='xlsxwriter') 

我们有一个叫做lines列表:

# create a dataframe called 'df' 
df = pd.DataFrame([sub.split(",") for sub in lines], columns=["Rule", "Device", "Status"])) 

#convert df to Excel worksheet 
df.to_excel(writer, sheet_name='all_status',**index=False**) 
writer.save()