サンプルデータの作成
import pandas as pd
data = {
"Name": ["user1", "user2", "user3", "user1", "user2", "user1"],
"Reserve_Data": ["1/1/2024", "2/1/2024", "3/1/2024", "4/1/2024", "5/1/2024", "6/1/2024"],
"Money": ["1000", "12000", "36000","400", "26","403330"],
}
df = pd.DataFrame(data, columns=["Name", "Reserve_Data", "Money"])
df
Name Reserve_Data Money
0 user1 1/1/2024 1000
1 user2 2/1/2024 12000
2 user3 3/1/2024 36000
3 user1 4/1/2024 400
4 user2 5/1/2024 26
5 user1 6/1/2024 403330
dfの単独列をリストで取得する
name_list = df["Name"].tolist()
print(name_list)
['user1', 'user2', 'user3', 'user1', 'user2', 'user1']
dfから特定の値を持つ行を抽出する
#1つの値との一致
print(df[df['Name'] == 'user1'])
Name Reserve_Data Money
0 user1 1/1/2024 1000
3 user1 4/1/2024 400
5 user1 6/1/2024 403330
#複数の値との一致 参考:https://hk29.hatenablog.jp/entry/2021/07/16/235822
target_list = ["user1","user3"]
df2 = df.query('Name in @target_list')
print(df2)
Name Reserve_Data Money
0 user1 1/1/2024 1000
2 user3 3/1/2024 36000
3 user1 4/1/2024 400
5 user1 6/1/2024 403330
行の並び替え
print(df.sort_values('Name'))
Name Reserve_Data Money
0 user1 1/1/2024 1000
3 user1 4/1/2024 400
5 user1 6/1/2024 403330
1 user2 2/1/2024 12000
4 user2 5/1/2024 26
2 user3 3/1/2024 36000
print(df2.sort_values('Name'))
Name Reserve_Data Money
0 user1 1/1/2024 1000
3 user1 4/1/2024 400
5 user1 6/1/2024 403330
2 user3 3/1/2024 36000