简体   繁体   中英

pandas data frame not recognizing index

I'm pretty new to python, and am trying to read in a single row of data to a data frame, and then index it by value to get occurrence counts for each value in the row. This is my code so far:

import pandas as pd
csv=pd.read_csv('filepath/data.csv', 'r', converters={'csv':str})
df=DataFrame(csv, columns=['data'], index=['0.0', '750.0'])
df

When I just view 'csv' after reading in, it looks like this:

0.0 750.0 750.0 750.0 750.0 750.0 750.0

When I attempt to input it to a data frame however, I get this result:

data
0.0   NaN
750.0 NaN

What I'm hoping to get:

data
0.0   1
750.0 6

Thanks in advance for any insight!

Pandas read_csv is designed for tabular data with multiple rows and columns: if your data file has only a single row of values, it is probably cleaner to read it directly using Python's open() . Once you have those results in a list, pandas value_counts method will give you the counts of each value in the list: eg

values = open('data.csv').read().split()
pd.Series(values).value_counts()
# 750.0    6
# 0.0      1
# dtype: int64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM