Difference between revisions of "Pandas"

From RHS Wiki
Jump to navigation Jump to search
Tag: visualeditor
Tag: visualeditor
Line 9: Line 9:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
== DataSeries ==
+
==DataSeries==
 
<syntaxhighlight lang="python3">
 
<syntaxhighlight lang="python3">
 
s = pd.Series(['banana', 42])
 
s = pd.Series(['banana', 42])
Line 17: Line 17:
 
==Dataframe==
 
==Dataframe==
  
=== Create ===
+
===Create===
 
<syntaxhighlight lang="python3">
 
<syntaxhighlight lang="python3">
 
scientists = pd.DataFrame({
 
scientists = pd.DataFrame({
Line 25: Line 25:
 
     'Died': ['1958-04-16', '1937-10-16'],
 
     'Died': ['1958-04-16', '1937-10-16'],
 
})
 
})
 +
</syntaxhighlight>If you want to keep the order of columns:<syntaxhighlight lang="python3">
 +
scientists = pd.DataFrame({
 +
    'Occupation': ['Chemist', 'Statistician'],
 +
    'Born': ['1920-07-25', '1876-06-13'],
 +
    'Died': ['1958-04-16', '1937-10-16'],
 +
}, index='Name': ['Rosaline Franklin', 'William Gosset'], columns=['Occupation', 'Born', ''Died'])
 
</syntaxhighlight>
 
</syntaxhighlight>
  
=== From CSV ===
+
===From CSV===
 
<syntaxhighlight lang="python3">
 
<syntaxhighlight lang="python3">
 
news = pd.read_csv('news_2019.05.10.csv')
 
news = pd.read_csv('news_2019.05.10.csv')

Revision as of 11:13, 21 May 2019

Install

pip install pandas

Read CSV

df = pd.read_csv('news_2019.05.10.csv')

DataSeries

s = pd.Series(['banana', 42])
s = pd.Series(['banana', 42], index=['Fruit', 'Calories'])

Dataframe

Create

scientists = pd.DataFrame({
    'Name': ['Rosaline Franklin', 'William Gosset'],
    'Occupation': ['Chemist', 'Statistician'],
    'Born': ['1920-07-25', '1876-06-13'],
    'Died': ['1958-04-16', '1937-10-16'],
})

If you want to keep the order of columns:

scientists = pd.DataFrame({
    'Occupation': ['Chemist', 'Statistician'],
    'Born': ['1920-07-25', '1876-06-13'],
    'Died': ['1958-04-16', '1937-10-16'],
}, index='Name': ['Rosaline Franklin', 'William Gosset'], columns=['Occupation', 'Born', ''Died'])

From CSV

news = pd.read_csv('news_2019.05.10.csv')

Info

df.index
df.columns
df.values
df.shape
df.dtypes
df.head()
df.tail()
df.info()

Select 1 row

df.iloc[[1]] # for positional indexing
df.loc[0]    # for label based 
df.iloc[-1] == df.loc[df.shape[0]-1]

Select specific rows

df.loc[[9, 99, 999]]

Select 1 column

sumarys = df[['summary']]
# Or
list(df['one'])
dfToList = df['one'].tolist()

Select multiple columns

df[['column1', 'column2', 'column3']]

Select 1 cell

df.iloc[1][1]
df.iloc[1]['summary']
df.iloc[1, 3]

df.loc[1, 'summary']

Subset multiple rows and multiple columns

df.iloc[[1,34,56],[2,4,5]]
df.loc[[1,34,56],['modification_date', 'content']]