简体   繁体   中英

List of Series from a DataFrame in Pandas

Is there a single method to take the list of the Series from a DataFrame?

For example, this way gets the result I want, but I have a sense there's a single method to get this:

In [136]: df=pd.DataFrame(pd.np.random.rand(10,3), columns=list('abc'))
Out[136]: 
          a         b         c
0  0.729100  0.102947  0.589687
1  0.180960  0.514507  0.359253
2  0.003143  0.353437  0.377803
3  0.565025  0.983447  0.380672
4  0.289800  0.256467  0.559850
5  0.177332  0.049220  0.467654
6  0.863002  0.325522  0.308502
7  0.926534  0.327017  0.159471
8  0.688663  0.934143  0.762619
9  0.203271  0.862646  0.317251

In [138]: [item[1] for item in df.items()]
Out[138]: 
[0    0.052074
 1    0.650355
 2    0.011106
 3    0.499441
 4    0.874509
 5    0.429968
 6    0.869368
 7    0.719732
 8    0.441703
 9    0.653455
 Name: a, dtype: float64, 0    0.431164
 1    0.736769
 2    0.235221
 3    0.452332
 4    0.578849
 5    0.116561
 6    0.679606
 7    0.549857
 8    0.761222
 9    0.468103
 Name: b, dtype: float64, 0    0.850285
 1    0.298383
 2    0.511760
 3    0.485509
 4    0.587351
 5    0.332112
 6    0.230234
 7    0.520007
 8    0.127432
 9    0.692219
 Name: c, dtype: float64]

df.values() would be the matching method to df.items() , but the .values gets the numpy values.

This will return a list of series.

import pandas as pd

df = pd.DataFrame(pd.np.random.rand(10,3), columns=list('abc'))
# get a list of Series from the column names
series_list = [df[col] for col in df]
print(series_list)

Prints

[0    0.743692
1    0.364492
2    0.133023
3    0.861350
4    0.108383
5    0.058208
6    0.932846
7    0.462293
8    0.305808
9    0.045466
Name: a, dtype: float64, 0    0.783904
1    0.479855
2    0.407343
3    0.764235
4    0.422370
5    0.076351
6    0.237434
7    0.251543
8    0.600384
9    0.458412
Name: b, dtype: float64, 0    0.918281
1    0.995960
2    0.329548
3    0.036124
4    0.791106
5    0.420298
6    0.068579
7    0.611581
8    0.173925
9    0.652559
Name: c, dtype: float64]

Another way:

columns, columnSeries = zip(*df.iteritems())

and to get rows as Series:

indices, rowSeries = zip(*df.iterrows())

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