0

Is it possible to get all columns of a dataframe into individual series.

For e.g. if I have the following dataframe:

account = pd.Series(["Petty cash", "Lucky Money", "RBC USD"])
amount = pd.Series([-2.59, 1111111, 66170.97])
mapping = pd.Series(["Debt", "Equity", "Cash"])
mapping2 = pd.Series(["Yes", "Yes", "No"])

data = pd.DataFrame({
    "Account Description": account,
    "Amount": amount,
    "mapping": mapping,
    "mapping2": mapping
})

Assuming the above dataframe was obtained from an excel file and not created from the code above, I want to get the following without typing line by line:

account = data['account']
amount = data['amount']
mapping = data['mapping']
mapping2 = data['mapping2']

Regards,

bbd108
  • 958
  • 2
  • 10
  • 26

1 Answers1

0

In order to access each columns of a Pandas dataframe you can iterate over them.

Try the following tutorial if this solves your problem.

# Yields a tuple of column name and series for each column in the dataframe
for (columnName, columnData) in df.iteritems():
   print('Colunm Name : ', columnName)
   print('Column Contents : ', columnData.values)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Timo Frionnet
  • 474
  • 3
  • 16
  • Hi Timo thanks for your answer, how to I get it to return the individual series object instead of just printing it? – user7800072 Mar 03 '20 at 01:46
  • It depends on what you want to do with it. You can put them in a list, but in that case it would be better to just access the columns in the way you noted in the original question. Can you elaborate on what you're trying to achieve and why you think you need the columns in separate variables? – Timo Frionnet Mar 03 '20 at 01:51
  • Maybe this previous [post](https://stackoverflow.com/questions/32485488/create-a-tuple-from-columns-in-a-pandas-dataframe) can help you to create a tuple. If it's just two columns, I don't seem to have an improved way of doing so. If you need to do it for all columns you can use a for loop or one of the other answers from the linked post. – Timo Frionnet Mar 03 '20 at 02:47
  • I'm actually trying to create a tuple of itself for mapping and mapping2 columns.mapping = (("Debt","Debt"), ("Equity","Equity"),( "Cash", "Cash")). There are more than the two columns in the dataset and there are some where there are nan values so lets say mapping 3 = (("Hi,Hi"), ("Bye, "Bye"),(nan,nan)). So I am planning to dropna for each series in the column and then only combining it into the tuple I required. – user7800072 Mar 03 '20 at 02:48
  • pandas 1.5.1: *FutureWarning: .iteritems() is deprecated and will be removed in a future version. Use .items() instead.* – Claudio Feb 03 '23 at 23:54