0

The code below gives me this table:

raw = pd.read_clipboard() raw.head() +---+---------------------+-------------+---------+----------+-------------+ | | Afghanistan | South Asia | 652225 | 26000000 | Unnamed: 4 | +---+---------------------+-------------+---------+----------+-------------+ | 0 | Albania | Europe | 28728 | 3200000 | 6656000000 | | 1 | Algeria | Middle East | 2400000 | 32900000 | 75012000000 | | 2 | Andorra | Europe | 468 | 64000 | NaN | | 3 | Angola | Africa | 1250000 | 14500000 | 14935000000 | | 4 | Antigua and Barbuda | Americas | 442 | 77000 | 770000000 | +---+---------------------+-------------+---------+----------+-------------+ 

But when I attempt to rename the columns and create a DataFrame, all of the data disappears:

df = pd.DataFrame(raw, columns = ['name', 'region', 'area', 'population', 'gdp']) df.head() +---+------+--------+------+------------+-----+ | | name | region | area | population | gdp | +---+------+--------+------+------------+-----+ | 0 | NaN | NaN | NaN | NaN | NaN | | 1 | NaN | NaN | NaN | NaN | NaN | | 2 | NaN | NaN | NaN | NaN | NaN | | 3 | NaN | NaN | NaN | NaN | NaN | | 4 | NaN | NaN | NaN | NaN | NaN | +---+------+--------+------+------------+-----+ 

Any idea why?

2
  • 4
    Why are you making a new DataFrame instead of just doing df.columns = ['name', 'region', ...]? Also, it looks like your data has no header, so the initial read is reading the first row as column names. Might want to fix that by passing header=None to read_clipboard. Commented Aug 14, 2014 at 1:44
  • This fixes my problems. If you post it as an answer I'll accept it. Commented Aug 14, 2014 at 1:52

1 Answer 1

2

You should just write:

df.columns = ['name', 'region', ...] 

This is also much more efficient as you aren't trying to copy the entire DataFrame; as far as I know passing one DataFrame into the constructor for another will make a deep, not shallow copy.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.