使用熊猫读取csv中的特定单元格

Utt*_*ara 4 python csv pandas

我有一个如下所示的 CSV 文件:

patient_id, age_in_years,   CENSUS_REGION,  URBAN_RURAL_STATUS

11511,  7   Northeast,  Urban,

9882613,    73, South,  Urban,

32190339,   49, West,   Urban,

32190339,   49, West,   Urban,

32190339,   49, West,   Urban,
32190339,   49, West,   Urban,

.....
Run Code Online (Sandbox Code Playgroud)

现在我的代码是这样的:

df = pd.read_csv(filename, index_col = 0)
Run Code Online (Sandbox Code Playgroud)

这给出了以下输出:

patient_id age_in_years CENSUS_REGION URBAN_RURAL_STATUS  YEAR  MONTH  

11511                  7     Northeast              Urban  2011      6   
9882613               73         South              Urban  2011      7   
32190339              49          West              Urban  2011      8   
32190339              49          West              Urban  2011      8   
32190339              49          West              Urban  2011      8   
32190339              49          West              Urban  2011      8   
32190339              49          West              Urban  2011      8   
32190339              49          West              Urban  2011      8
...
Run Code Online (Sandbox Code Playgroud)

我可以通过以下方式获取特定的列,例如 CENSUS_REGION

print(df['CENSUS_REGION'])
Run Code Online (Sandbox Code Playgroud)

但我想获取 CSV 中的特定单元格。任何人都可以帮我解决这个问题吗?

Ana*_*mar 5

After getting the column, you can subscript using the index to get the specific value for that cell.

Example , in your case, your first column seems to be patient_id , so that is the index, you can index using that.

Example -

print(df['CENSUS_REGION'][11511])
Run Code Online (Sandbox Code Playgroud)

The above would get the data of CENSUS_REGION column for the patient with id - 11511 .


Example/Demo -

In [32]: df
Out[32]:
             age_in_years    CENSUS_REGION   URBAN_RURAL_STATUS
patient_id
11511                   7        Northeast                Urban
9882613                73            South                Urban
32190339               49             West                Urban
32190339               49             West                Urban
32190339               49             West                Urban
32190339               49             West                Urban

In [33]: df['   CENSUS_REGION']
Out[33]:
patient_id
11511          Northeast
9882613            South
32190339            West
32190339            West
32190339            West
32190339            West
Name:    CENSUS_REGION, dtype: object

In [34]: df['   CENSUS_REGION'][11511]
Out[34]: '   Northeast'
Run Code Online (Sandbox Code Playgroud)

Please note, I had to use lots of spaces, since the csv was messed up, but ' CENSUS_REGION' is just the column name.