Pandas 中的多个同名列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39986925/
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-09-14 02:10:55  来源:igfitidea点击:

Multiple columns with the same name in Pandas

pythonpython-2.7csvpandas

提问by vks

I am creating a dataframefrom a CSV file. I have gone through the docs, multiple SO posts, links as I have just started Pandas but didn't get it. The CSV file has multiple columns with same names say a.

我正在dataframe从 CSV 文件创建一个。我已经浏览了文档、多个 SO 帖子、链接,因为我刚刚开始使用 Pandas 但没有得到它。CSV 文件有多个具有相同名称的列,例如a.

So after forming dataframeand when I do df['a']which value will it return? It does not return all values.

那么在形成之后dataframe以及当我执行df['a']哪个值时它会返回?它不会返回所有值。

Also only one of the values will have a string rest will be None. How can I get that column?

此外,只有一个值将具有字符串 rest 将是None. 我怎样才能得到那个专栏?

回答by piRSquared

the relevant parameter is mangle_dupe_cols

相关参数是 mangle_dupe_cols

from the docs

文档

mangle_dupe_cols : boolean, default True
    Duplicate columns will be specified as 'X.0'...'X.N', rather than 'X'...'X'
mangle_dupe_cols : boolean, default True
    Duplicate columns will be specified as 'X.0'...'X.N', rather than 'X'...'X'

by default, all of your 'a'columns get named 'a.0'...'a.N'as specified above.

默认情况下,您的所有'a'列都'a.0'...'a.N'按照上面指定的方式命名。

if you used mangle_dupe_cols=False, importing this csvwould produce an error.

如果您使用mangle_dupe_cols=False,导入它csv会产生错误。

you can get all of your columns with

你可以得到你所有的列

df.filter(like='a')


demonstration

示范

from StringIO import StringIO
import pandas as pd

txt = """a, a, a, b, c, d
1, 2, 3, 4, 5, 6
7, 8, 9, 10, 11, 12"""

df = pd.read_csv(StringIO(txt), skipinitialspace=True)
df

enter image description here

在此处输入图片说明

df.filter(like='a')

enter image description here

在此处输入图片说明