简体   繁体   中英

Python Pandas Dataframe Constructor Converts List to String

is there a simple solution to solve the following problem:

I'm using Pandas dataframe

dataframe = pandas.DataFrame(data, index=[categorieid], columns=['title', 'categorieid'])

where categorieid is a list of integer values (eg [1,2,3,1]) and title a list of strings ['a','b,'c','d'].

And then i'm trying to access the title at a specific position with

dataframe.ix[i]['title'].values.tolist()

The problem is that i get an exception if only one title exists for a given index because then pandas saves my title as a string and not as a list.

Is there a solution to tell the dataframe constructor always to create a list() at each index even if there is only one item contained?

Thank you for any help

Edit: My printed dataframe looks like this

        categorieid title
0            0     a
0            0     c
1            1     b
1            1     d
0            0     e
2            2     f

Calling my values.tolist() results in for _title in dataframe.ix[i]['title'].values.tolist(): AttributeError: 'unicode' object has no attribute 'values'

I think you're making it more difficult than it has to be by the way you're building the DataFrame. Also, accessing the 'values' attribute is not needed.

Since you only have one dimension, you're probably better off using a Series. Then you can select the entries using the index and convert to a list.

In [12]: s = pd.Series(list('acbdef'), index=[0, 0, 1, 1, 0, 2], name='title')

In [13]: s
Out[13]: 
0    a
0    c
1    b
1    d
0    e
2    f
Name: title, dtype: object

In [14]: s[1].tolist()
Out[14]: ['b', 'd']

If you really need a DataFrame for some reason not mentioned, it will work similarly:

In [15]: df = pd.DataFrame(s)

In [16]: df
Out[16]: 
  title
0     a
0     c
1     b
1     d
0     e
2     f

In [17]: df['title'][1].tolist()
Out[17]: ['b', 'd']

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