Seaborn Pairplot with Dataframe vs CSV - python

I have a dataframe in a Jupyter notebook and do a pairplot on it to get a bunch of plots against each other.
import seaborn as sns
sns.pairplot(df_merge)
Here is the pairplot as a result.
However, it plots the data incorrectly and in a non-aesthetic way. However, when I export this dataframe to a csv and then read it back into the program as a dataframe:
import seaborn as sns
df_merge.to_csv('dataframe.csv')
x = pd.read_csv('dataframe.csv')
sns.pairplot(x)
Sns plots it fine and the correlations between variables can be seen but I have an unnecessary column called Unnamed which I don't need.
Does anyone know what could cause this issue and how I can go about correcting it without needing to export the dataframe as a csv?

When you do:
df_merge.to_csv('dataframe.csv')
you write also the index of df_merge without a name. Then
x = pd.read_csv('dataframe.csv')
reads the index as Unnamed 0 column. To fix this, either save the data frame without index:
df_merge.to_csv('dataframe.csv', index=False)
x = pd.read_csv('dataframe.csv')
or read the csv with index:
df_merge.to_csv('dataframe.csv')
x = pd.read_csv('dataframe.csv', index_col=[0])

Figured out that the issue I was having was when I was changing the dataframe to a CSV and then changing it back to a dataframe, the values in the dataframe had a float64 type where as in my dataframe before they were all objects. Converting all the numerical columns to float before plotting the graph solved my issue.

Related

Insert new Column in Excel (Python)

I have a python code wherein I take certain data from an excel and work with that data. Now I want that at the end of my code in the already existing Excel table a new column named XY is created. What would be your approach to this?
If you're using pandas to perform operations on the data, and you have it loaded as a df, just add:
import pandas as pd
import numpy as np
# Generating df with random numbers to show example
df = pd.DataFrame(np.random.randint(
0, 100, size=(15, 4)), columns=list('ABCD'))
print(df.head())
# Adding the empty column
df['xy'] = ''
print(df.head())
#exporting to excel
df.to_excel( FileName.xlsx, sheetname= 'sheet1')
This will add an empty column to the df, with the top cell labelled xy. If you want any values in the column, you can replace the empty '' with a list of whatever.
Hope this helps!
The easiest way get the right code is to record a macro in Excel. Go to your table in Excel, command 'Record macro' and manually perform required actions. Then command 'Stop recording' and go to VBA to discover the code. Then use the equivalent code in your Python app.

Getting wrong readings when trying to plot CSV file using pandas

My csv file looks like the following:
As you see there are 7 columns with comma separated. I have spent hours to read and plot the first column starting with 31364 with the following code:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('test.csv', sep=',', header=None, names=['colA','colB','colC','colD','colE','colF','colG'])
y = df['colA']
plt.plot(y)
But the code outputs this plot which does not match the data at all:
I'm using Spyder with Anaconda. What could be the problem?
Is column A all values in the 31,000 range? You're not plotting the whole file.
edit: Don't know what result you're looking for. In your code, the first column in your csv is used as the index to the dataframe (after you read the csv, enter 'df', no quotes, at the python prompt to see what your dataset looks like.
If you don't want the first column in the csv as an index, add 'index_col=False', no quotes, to the parameters when you read the csv in.
Also, not a good idea to end lines in a csv wit the delimiter, comma in this case.

Pandas cannot load the proper column of the CSV File

I have been facing some problems importing a specific column of a CSV file.I needed to import the Longitude and Latitude Column of the dataset (Fig:1).
But in spyder, the variable explorer is showing the wrong values of the variable (Fig:2). And it seems like that my expected column of values is showing inside the Index column. How do I fix this/ How do I import it?
However, When I click the resize button below on the variable explorer window, the index column expands and show something like Fig: 3
The code I am using:
import pandas as pd
import numpy as np
dataset = pd.read_csv('dataset.csv',error_bad_lines=False)
X=dataset.loc[:,['latitude','longitude']]
I suggest making an array of column names, and trying to read the csv like so:
colnames = ["latitude", "longitude",...]
dataset = pd.read_csv('dataset.csv', names=colnames, index_col=0)
# index_col = 0 makes a new index column
# and if you must use error_bad_lines...
dataset = pd.read_csv('dataset.csv', names=colnames, index_col=0, error_bad_lines=False)
When you set error_bad_lines=False you are telling pandas to not raise an error when an error happens. Your previous error instead was telling you exactly what is going wrong:
"Error tokenizing data. C error: Expected 62 fields in line 8, saw 65"
It means you have lines with more fields than the number of headers, which cause the misalignment when you tell pandas to don't care about that. You should clean your data removing the extra column or import just some specific columns using the headers as the other answer suggests.

Plotting from excel to python with pandas

I am new to python,pandas,etc and i was asked to import, and plot an excel file. This file contains 180 rows and 15 columns and i have to plot each column with respect to the first one which is time, in total 14 different graphs. I would like some help with writing the script. Thanks in advance.
The function you are looking for is pandas.read_excel (Link).
It will return a DataFrame-Object from where you can access your data in python. Make sure you Excel-File is well formatted.
import pandas as pd
# Load data
df = pd.read_excel('myfile.xlsx')
Check out these packages/ functions, you'll find some code on these websites and you can tailor it to your needs.
Some useful codes:
Read_excel
import pandas as pd
df = pd.read_excel('your_file.xlsx')
Code above reads an excel file to python and keeps it as a DataFrame, named df.
Matplotlib
import matplotlib.pyplot as plt
plt.plot(df['column - x axis'], df['column - y axis'])
plt.savefig('you_plot_image.png')
plt.show()
This is a basic example of making a plot using matplotlib and saving it as your_plot_image.png, you have to replace column - x axis and column - y axis with desired columns from your file.
For cleaning data and some basics regarding DataFrames have a look at this package: Pandas

How to refer/assign an excel column in python?

I have a csv file (excel spreadsheet) of a column of roughly a million numbers in column A. I want to make a histogram of this data with the frequency of the numbers on the y-axis and the number quantities on the x-axis. I'm using pandas to do so. My code:
import pandas as pd
pd.read_csv('D1.csv', quoting=2)['A'].hist(bins=50)
Python isn't interpreting 'A' as the column name. I've tried various names to reference the column, but all result in a keyword error. Am I missing a step where I have to assign that column a name via python which I don't know how to?
I need more rep to comment, so I put this as answer.
You need to have a header row with the names you want to use on pandas. Also if you want to see the histogram when you are working from python shell or ipython you need to import pyplot
import matplotlib.pyplot as plt
import pandas as pd
pd.read_csv('D1.csv', quoting=2)['A'].hist(bins=50)
plt.show()
Okay I finally got something to work with headings, titles, etc.
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('D1.csv', quoting=2)
data.hist(bins=50)
plt.xlim([0,115000])
plt.title("Data")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
My first problem was that matplotlib is necessary to actually show the graph as stated by #Sauruxum. Also, I needed to set the action
pd.read_csv('D1.csv', quoting=2)
to data so I could plot the histogram of that action with
data.hist
Basically, the problem wasn't finding the name to the header row. The action itself needed to be .hist .Thank you all for the help.

Categories

Resources