Home > Enterprise >  transposed Pandas data frame zeroth column not callable as [:, 0]
transposed Pandas data frame zeroth column not callable as [:, 0]

Time:03-09

I am trying to use Seaborn to plot a simple bar plot using data that was transformed. The data started out looking like this (text follows):initial

element 1 2 3 4 5 6 7 8 9 10 11 12
C 95.6 95.81 96.1 95.89 97.92 96.71 96.1 96.38 96.09 97.12 95.12 95.97

N 1.9 1.55 1.59 1.66 0.53 1.22 1.57 1.63 1.82 0.83 2.37 2.13

O 2.31 2.4 2.14 2.25 1.36 1.89 2.23 1.8 1.93 1.89 2.3 1.71

Co 0.18 0.21 0.16 0.17 0.01 0.03 0.13 0.01 0.02 0.01 0.14 0.01

Zn 0.01 0.03 0.02 0.03 0.18 0.14 0.07 0.17 0.14 0.16 0.07 0.18

and after importing using:

df1 = pd.read_csv(r"C:\path.txt", sep='\t',header = 0, usecols=[0, 1, 2,3,4,5,6,7,8,9,10,11,12], index_col='element').transpose()
display(df1)

after transpose

When I plot the values of an element versus the first column (which represents an observation), the first column of data corresponding to 'C' is used instead. What am I doing wrong and how can I fix it?

I also tried importing, then pivoting the dataframe, which resulted in an undesired shape that repeated the element set as columns 12 times.

ax = sns.barplot(x=df1.iloc[:,0], y='Zn', data=df1)

enter image description here

edited to add that I am not married to using any particular package or technique. I just want to be able to use my data to build a bar plot with 1-12 on the x axis and elemental compositions on the y.

CodePudding user response:

you have different possibilities here. The problem you have is because 'element' is the index of your dataframe, so x=df1.iloc[:,0] is the column of 'C'.

1)

ax = sns.barplot(x=df.index, y='Zn', data=df1)
df.reset_index(inplace=True) #now 'element' is the first column of the df1
ax = sns.barplot(x=df.iloc[:,0], y='Zn', data=df1)

#equal to
ax = sns.barplot(x='element', y='Zn', data=df1
  • Related