构建4个3*5的dataframe,如果第一个dataframe的元素大于等于0,则第四个dataframe的元素是第二个和第三个dataframe元素的差,如果第一个dataframe的元素小于0,则第四个dataframe的元素是第二个和第三个dataframe元素的和
时间: 2023-11-18 15:24:14 浏览: 98
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randint(-5, 5, size=(3, 5)), columns=list('ABCDE'))
df2 = pd.DataFrame(np.random.randint(-5, 5, size=(3, 5)), columns=list('ABCDE'))
df3 = pd.DataFrame(np.random.randint(-5, 5, size=(3, 5)), columns=list('ABCDE'))
df4 = pd.DataFrame(np.zeros((3, 5)), columns=list('ABCDE'))
for i in range(3):
for j in range(5):
if df1.iloc[i, j] >= 0:
df4.iloc[i, j] = df2.iloc[i, j] - df3.iloc[i, j]
else:
df4.iloc[i, j] = df2.iloc[i, j] + df3.iloc[i, j]
print(df1)
print(df2)
print(df3)
print(df4)
相关问题
构建3个3*5的dataframe,第三个dataframe的元素是前两个dataframe元素的差
```python
import pandas as pd
import numpy as np
# 构建第一个dataframe
df1 = pd.DataFrame(np.random.randint(0, 10, size=(3, 5)), columns=list('ABCDE'))
print("df1:\n", df1)
# 构建第二个dataframe
df2 = pd.DataFrame(np.random.randint(0, 10, size=(3, 5)), columns=list('ABCDE'))
print("df2:\n", df2)
# 构建第三个dataframe,元素为前两个dataframe元素的差
df3 = df1 - df2
print("df3:\n", df3)
```
输出结果:
```
df1:
A B C D E
0 7 9 8 0 8
1 6 5 7 1 0
2 9 0 8 8 2
df2:
A B C D E
0 9 9 8 6 3
1 5 0 8 3 6
2 0 2 4 4 7
df3:
A B C D E
0 -2 0 0 -6 5
1 1 5 -1 -2 -6
2 9 -2 4 4 -5
```
构建3个3*5的dataframe,如果第1个dataframe的元素大于等于0,则第3个dataframe的元素是第2个dataframe元素的值加1,如果第1个dataframe的元素小于0,则第3个dataframe的元素是第2个dataframe元素的值减1
import numpy as np
import pandas as pd
# 构建第1个dataframe
df1 = pd.DataFrame(np.random.randn(3, 5) * 10)
print("df1:")
print(df1)
# 构建第2个dataframe
df2 = pd.DataFrame(np.zeros((3, 5)))
print("df2:")
print(df2)
# 根据条件构建第3个dataframe
df3 = pd.DataFrame(np.zeros((3, 5)))
for i in range(3):
for j in range(5):
if df1.iloc[i, j] >= 0:
df3.iloc[i, j] = df2.iloc[i, j] + 1
else:
df3.iloc[i, j] = df2.iloc[i, j] - 1
print("df3:")
print(df3)
阅读全文