pandas shuffle data
时间: 2023-10-03 08:03:32 浏览: 66
To shuffle data in pandas, you can use the `sample()` function. Here's an example:
```python
import pandas as pd
# Create a sample DataFrame
data = {'A': [1, 2, 3, 4, 5],
'B': ['a', 'b', 'c', 'd', 'e']}
df = pd.DataFrame(data)
# Shuffle the DataFrame
shuffled_df = df.sample(frac=1).reset_index(drop=True)
```
In the above code, `sample(frac=1)` shuffles the rows randomly by sampling the entire DataFrame with a fraction of 1 (which means all rows are included), and `reset_index(drop=True)` resets the index of the shuffled DataFrame.
After shuffling, the `shuffled_df` DataFrame will contain the original data randomly reordered.
相关问题
如何打乱pandas中的数据
可以使用pandas的shuffle()函数来打乱数据。这个函数可以随机打乱数据的行顺序。下面是一个示例代码:
``` python
import pandas as pd
# 读取数据
data = pd.read_csv('data.csv')
# 打乱数据
data = data.sample(frac=1)
# 输出打乱后的数据
print(data)
```
在这个示例代码中,我们首先使用pandas的read_csv()函数读取了一个CSV文件中的数据。然后使用sample()函数打乱了数据的顺序。frac参数表示采样的比例,这里设置为1表示采样全部数据。最后输出打乱后的数据。
pandas.Dataframe打乱顺序代码
可以使用pandas的shuffle()函数来打乱DataFrame的顺序,代码如下:
import pandas as pd
df = pd.read_csv('data.csv') # 读取数据
df_shuffled = df.sample(frac=1) # 打乱顺序
print(df_shuffled.head()) # 输出前5行