1

I'm creating manually a dictionary of features and numpy array.

columns = ['a', 'b', 'c', 'd']
features = {'a': df_train.values[:, 0],
            'b': df_train.values[:, 1],
            'c': df_train.values[:, 2],
            'd': df_train.values[:, 3]}

df_train is a Pandas dataframe originated from pandas.read_csv()

I'm using this code to simplify it:

features = {c: df_train.values[:, i] for i, c in enumerate(columns)}

Is there a more Pythonic way? (dict with zip for example?)

9
  • 1
    You got it in a single line. That's as Pythonic as it gets I am afraid. You can probably use different methods as you suggest, but the outcome will be the same. Are you implying a more computationally efficient way? Commented Oct 24, 2018 at 3:52
  • 1
    No, I don't think there's a more pythonic way. Following up on the comment by @b-fg you don't necessarily get "pythonic" from having a 1-liner but, in this case, it's perfectly readable and efficient. Commented Oct 24, 2018 at 3:58
  • 2
    @b-fg spend a bit more time on SO and you'll see some catastrophic 1-liners :P. The dict comprehension here is fine, but there's also a broader misunderstanding with some people that cramming everything into one line with horrible time complexity wins. Commented Oct 24, 2018 at 4:06
  • 2
    @roganjosh, Yes understand where you come from hehe. And we are on the same page ;) Commented Oct 24, 2018 at 4:08
  • 1
    "dict with zip"? Yes, there is: dict(zip(columns, df_train.values.T)) Commented Oct 24, 2018 at 4:38

1 Answer 1

3

You can use the transpose:

dict(zip(columns, df_train.values.T))

or

{k: v for k, v in zip(columns, df_train.values.T)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.