Reputation: 180
How add label in column as string for numpy array
I need this output
One Two Three A 1, 2, 3 B 4, 5, 6
import numpy as np
import pandas as pd
a=pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
orient='index', columns=['one', 'two', 'three'])
print(a)
when I use this code, the code give me the correct result, but also give me a error; that I don't understand.
Note:I dont understand this line
a=pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
orient='index', columns=['one', 'two', 'three'])
I need another method to implement this.
Output:
one two three A 1 2 3 B 4 5 6 C:\Users\Toufik\Anaconda3\lib\site-packages\ipykernel_launcher.py:4: FutureWarning: from_items is deprecated. Please use DataFrame.from_dict(dict(items), ...) instead. DataFrame.from_dict(OrderedDict(items)) may be used to preserve the key order. after removing the cwd from sys.path.
Upvotes: 0
Views: 10560
Reputation: 15545
The warning you're being given is to tell you you're using a deprecated (to be removed) syntax. It suggests you use from_dict
instead, for example
import numpy as np
import pandas as pd
a=pd.DataFrame.from_dict({
'A': [1, 2, 3],
'B': [4, 5, 6]
},
orient='index', columns=['one', 'two', 'three'])
print(a)
This will give your intended output
one two three
A 1 2 3
B 4 5 6
The following block which you say you don't understand —
a = pd.DataFrame.from_dict({
'A': [1, 2, 3],
'B': [4, 5, 6]
},
orient='index', columns=['one', 'two', 'three'])
print(a)
This creates a DataFrame
from a dictionary (from_dict
) which we're passing in as the first parameter.
{'A': [1, 2, 3], 'B': [4, 5, 6]}
This dictionary has 2 entries, "A" and "B", each of which contain a list of numbers. If you pass this to pd.DataFrame.from_dict
by itself, e.g.
a = pd.DataFrame.from_dict({
'A': [1, 2, 3],
'B': [4, 5, 6]
})
print(a)
You would get the following output.
A B
0 1 4
1 2 5
2 3 6
As you can see, the keys for the dictionary are being output as the column headers. To use the dictionary keys as (row) index headers and rotate the data you can pass in orient='index'
.
a = pd.DataFrame.from_dict({
'A': [1, 2, 3],
'B': [4, 5, 6]
}, orient='index')
print(a)
This will give the following output.
0 1 2
A 1 2 3
B 4 5 6
The final step is to pass in the column headers we want to use.
a = pd.DataFrame.from_dict({
'A': [1, 2, 3],
'B': [4, 5, 6]
},
orient='index', columns=['one', 'two', 'three'])
print(a)
Which gives the intended output
one two three
A 1 2 3
B 4 5 6
Upvotes: 5
Reputation: 353
data = {'A': [1,2,3], 'B': [4,5,6]}
pd.DataFrame.from_dict(data,orient='index',columns=['one', 'two', 'three'])
Upvotes: 4