Python 从熊猫数据框中删除标题列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36688022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:13:52  来源:igfitidea点击:

Removing header column from pandas dataframe

pythonpandas

提问by user308827

I have the foll. dataframe:

我有一个愚蠢的。数据框:

df

df

   A   B
0  23  12
1  21  44
2  98  21

How do I remove the column names Aand Bfrom this dataframe? One way might be to write it into a csv file and then read it in specifying header=None. is there a way to do that without writing out to csv and re-reading?

如何删除列名A,并B从该数据帧?一种方法可能是将其写入 csv 文件,然后在指定 header=None 时读取它。有没有办法在不写出 csv 并重新阅读的情况下做到这一点?

回答by jezrael

I think you cant remove column names, only reset them by rangewith shape:

我认为你不能删除列名,只能通过重新设置rangeshape

print df.shape[1]
2

print range(df.shape[1])
[0, 1]

df.columns = range(df.shape[1])
print df
    0   1
0  23  12
1  21  44
2  98  21

This is same as using to_csvand read_csv:

这与使用to_csvand相同read_csv

print df.to_csv(header=None,index=False)
23,12
21,44
98,21

print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)
    0   1
0  23  12
1  21  44
2  98  21

Next solution with skiprows:

下一个解决方案skiprows

print df.to_csv(index=False)
A,B
23,12
21,44
98,21

print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)
    0   1
0  23  12
1  21  44
2  98  21

回答by Max

How to get rid of a header(first row) and an index(first column).

如何摆脱标题(第一行)和索引(第一列)。

To write to CSV file:

写入 CSV 文件:

df = pandas.DataFrame(your_array)
df.to_csv('your_array.csv', header=False, index=False)

To read from CSV file:

从 CSV 文件中读取:

df = pandas.read_csv('your_array.csv')
a = df.values

If you want to read a CSV file that doesn't contain a header, pass additional parameter header:

如果要读取不包含标题的 CSV 文件,请传递附加参数header

df = pandas.read_csv('your_array.csv', header=None)