Python 如何在表中插入列
我读了一些关于熊猫的文章,我想在最后一篇文章后面加一篇文章。在我这样做之后,问题是这些值从零开始,我希望它们从一开始 我有12800行,希望添加的列从1开始到100,然后重新开始从1到100。我希望所有行都有这种图案。基本上,我希望这个循环128次,从1到100。谁能告诉我怎么做Python 如何在表中插入列,python,pandas,insert,Python,Pandas,Insert,我读了一些关于熊猫的文章,我想在最后一篇文章后面加一篇文章。在我这样做之后,问题是这些值从零开始,我希望它们从一开始 我有12800行,希望添加的列从1开始到100,然后重新开始从1到100。我希望所有行都有这种图案。基本上,我希望这个循环128次,从1到100。谁能告诉我怎么做 import numpy as np import pandas as pd df = pd.read_csv('...csv') df1=pd.DataFrame(df.values.reshape(12800, -
import numpy as np
import pandas as pd
df = pd.read_csv('...csv')
df1=pd.DataFrame(df.values.reshape(12800, -1))
df1['10'] = df1.index
包含的图片不正确。我希望最后一列是10号,从1开始,有一个我上面说过的模式
要重复模式
1..100
并分配给列,您可以执行以下操作:
df['1_to_100'] = np.tile(
np.arange(1, 101), int(len(df) * 0.01) + 1)[:len(df)]
df['by_100'] = np.floor(df.index / 100)
要添加每步100的图案,可以执行以下操作:
df['1_to_100'] = np.tile(
np.arange(1, 101), int(len(df) * 0.01) + 1)[:len(df)]
df['by_100'] = np.floor(df.index / 100)
测试代码:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(2002, 3))
df['1_to_100'] = np.tile(
np.arange(1, 101), int(len(df) * 0.01) + 1 )[:len(df)]
df['by_100'] = np.floor(df.index / 100)
print(df.head())
print(df.tail())
0 1 2 1_to_100 by_100
0 0.301862 0.824019 0.267810 1 0.0
1 0.568186 0.040328 0.799634 2 0.0
2 0.887218 0.407702 0.351990 3 0.0
3 0.871072 0.583761 0.498725 4 0.0
4 0.169657 0.026824 0.446667 5 0.0
0 1 2 1_to_100 by_100
1997 0.370640 0.662019 0.541747 98 19.0
1998 0.545908 0.682259 0.970764 99 19.0
1999 0.416177 0.665771 0.926145 100 19.0
2000 0.207109 0.762653 0.813754 1 20.0
2001 0.711998 0.236817 0.025387 2 20.0
结果:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(2002, 3))
df['1_to_100'] = np.tile(
np.arange(1, 101), int(len(df) * 0.01) + 1 )[:len(df)]
df['by_100'] = np.floor(df.index / 100)
print(df.head())
print(df.tail())
0 1 2 1_to_100 by_100
0 0.301862 0.824019 0.267810 1 0.0
1 0.568186 0.040328 0.799634 2 0.0
2 0.887218 0.407702 0.351990 3 0.0
3 0.871072 0.583761 0.498725 4 0.0
4 0.169657 0.026824 0.446667 5 0.0
0 1 2 1_to_100 by_100
1997 0.370640 0.662019 0.541747 98 19.0
1998 0.545908 0.682259 0.970764 99 19.0
1999 0.416177 0.665771 0.926145 100 19.0
2000 0.207109 0.762653 0.813754 1 20.0
2001 0.711998 0.236817 0.025387 2 20.0
你想要这样的吗
df1['10']=list(范围(1101))*128
@unmutto是的,谢谢,你能告诉我,如果我添加另一列,希望第0行到第99行的值为零,第100行到第199行的值为1,这个过程一直持续到值127,我如何更改代码?你可以使用np.repeat(np.arange(0128),100)对于从第0行到第99行的值为零,第100行到第199行的值,依此类推,并将np.tile(np.arange(1101),128))打印1到100 128次