选择具有不同标头python的csv / df中的特定列

问题描述 投票:0回答:1

我有几个包含相同信息变体的CSV文件。我想根据关键字从每个列中提取列。但是,每个文件的标题不一定从第1行开始,因此很难识别'skiprows ='的静态变量。

以下是CSV的一些示例

CSV1

Here are the instructions that you should follow.
Follow them closely, OK, to define the Type and Place.

Type    Number  Place   Exists
cat 2   home    yes
dog 2   field   yes
fish    3   sea yes

CSV2

   .



I know have this type of information.
This is not easy to define when the location and style are the same.

Animal Style    Quantity    Location    Exists
horse   3   field   yes
lion    2   safari  no
tiger 3 jungle  yes


CSV3

Number  Local   Species
2   home    rabbit
3   tank    turtle
3   sea shark   

如果'CSV'都有一个易于识别的标题,我会遵循的“熊猫”方法如下:

colFilters = ['number','local','species','style','quantity','location','type','number','place']
df = read_CSV(CSV1,skip_blanks_rows=True)
df.columns = map(str.lower, df.columns)
df = df.filter(regex='|'.join(colFiltersFilters),axis=1) 
df.head

我本可以跳过不包含关键词的行,但有时会出现在“指令”中的关键词放在标题上方的不同位置。

有没有'熊猫'可以使用特定信息来识别标题列的方法?除了依赖标题信息和/或标题数量之外,还有更好的解决方法吗?

python pandas csv dataframe header
1个回答
0
投票

所以基本上你的字符串存储在第1列?如果在读入数据时删除所有NULL值,该怎么办?之后,您可以使用第一行重命名列标题。

import pandas as pd
import numpy as np
df = pd.read_csv(r'CSV1',header=None)
df=df.dropna()
df=df.rename(columns=df.iloc[0])
df=df.drop(df.index[[0]])
df.head(10)

如果您在任何其他列中缺少值,那么我将删除包含“。”的所有行。或删除所有缺失值超过2的行

© www.soinside.com 2019 - 2024. All rights reserved.