Open4
Pandas
ピン留めされたアイテム
Show all of columns/rows in pandas
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
Conditioning
import pandas as pd
# Create a sample DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Age': [25, 30, 35, 40, 45],
'City': ['New York', 'Los Angeles', 'New York', 'New York', 'Los Angeles']
}
df = pd.DataFrame(data)
age_threshold = 30
result = df.query('Age > @age_threshold and City == "New York"')
print(result)
# Name Age City
# 2 Charlie 35 New York
# 3 David 40 New York
・If comlun name contain space
query('`First Name` == "Alice"')
Change name of columns
・Create Data
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
})
- rename()
# Rename columns 'A' to 'Alpha' and 'B' to 'Beta'
# If `inplace=Ture`, modify original df
df.rename(columns={'A': 'Alpha', 'B': 'Beta'}, inplace=True)
print(df)
# Alpha Beta C
# 0 1 4 7
# 1 2 5 8
# 2 3 6 9
- df.columns
# Assign new column names
df.columns = ['Alpha', 'Beta', 'Gamma']
print(df)
# Alpha Beta C
# 0 1 4 7
# 1 2 5 8
# 2 3 6 9
Replace
・Create Data
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
})
- replace()
# Take care with type
replace_dict = {'1':'4', '2':'5', '3':'6'}
df['A'] = df['A'].astype(str).replace(replace_dict)
print(df)
# A B C
# 0 4 4 7
# 1 5 5 8
# 2 6 6 9