随机播放给定的 Pandas DataFrame 行
让我们看看如何打乱 DataFrame 的行。我们将使用 pandas 模块的 sample() 方法随机打乱 Pandas 中的 DataFrame 行。
示例 1:
Python3
# import the module
import pandas as pd
# create a DataFrame
data = {'Name': ['Mukul', 'Rohan', 'Mayank',
'Shubham', 'Aakash'],
'Class': ['BCA', 'BBA', 'BCA', 'MBA', 'BBA'],
'Location' : ['Saharanpur', 'Meerut', 'Agra',
'Saharanpur', 'Meerut']}
df1 = pd.DataFrame(data)
# print the original DataFrame
print("Original DataFrame :")
display(df1)
# shuffle the DataFrame rows
df2 = df1.sample(frac = 1)
# print the shuffled DataFrame
print("\nAfter Shuffle:")
display(df2)
Python3
# import the module
import pandas as pd
# create a DataFrame
ODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Pointing',
'Jayasurya', 'Jayawardene', 'Kohli',
'Haq', 'Kallis', 'Ganguly', 'Dravid'],
'runs': [18426, 14234, 13704, 13430, 12650,
11867, 11739, 11579, 11363, 10889]}
df1 = pd.DataFrame(ODI_runs)
# print the original DataFrame
print("Original DataFrame :")
display(df1)
# shuffle the DataFrame rows
df2 = df1.sample(frac = 1)
# print the shuffled DataFrame
print("\nAfter Shuffle:")
display(df2)
输出:
示例 2:
Python3
# import the module
import pandas as pd
# create a DataFrame
ODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Pointing',
'Jayasurya', 'Jayawardene', 'Kohli',
'Haq', 'Kallis', 'Ganguly', 'Dravid'],
'runs': [18426, 14234, 13704, 13430, 12650,
11867, 11739, 11579, 11363, 10889]}
df1 = pd.DataFrame(ODI_runs)
# print the original DataFrame
print("Original DataFrame :")
display(df1)
# shuffle the DataFrame rows
df2 = df1.sample(frac = 1)
# print the shuffled DataFrame
print("\nAfter Shuffle:")
display(df2)
输出: