[英]Python - How to iterate through dataframe to append each row
Quick question on how to append dataframe while keeping the same output.关于如何 append dataframe 同时保持相同的 output 的快速问题。 Example code is below.
示例代码如下。
import pandas as pd
df = pd.read_csv('C:\\Blah\\Code1.csv')
Z = {
df.iloc[0,1]: {df.iloc[0,2]: 100, df.iloc[0,3]: 200, df.iloc[0,4]: 500},
df.iloc[1,1]: {df.iloc[1,2]: 100, df.iloc[1,3]: 200, df.iloc[1,4]: 500},
df.iloc[2,1]: {df.iloc[2,2]: 100, df.iloc[2,3]: 200, df.iloc[2,4]: 500},
df.iloc[3,1]: {df.iloc[3,2]: 100, df.iloc[3,3]: 200, df.iloc[3,4]: 500},
df.iloc[4,1]: {df.iloc[4,2]: 100, df.iloc[4,3]: 200, df.iloc[4,4]: 500},
}
print(Z)
The df.iloc corresponds to an excel file, and the output is: df.iloc对应一个excel文件,output为:
{'Steve': {'Bob': 100, 'Eric': 200, 'Very': 500}, 'Pokemon': {'Yugioh': 100, 'Steve': 200, 'Cool': 500}, 'Save': {'Really': 100, 'Now': 200, 'Stuff': 500}, 'Tons': {'Of': 100, 'Code': 200, 'Filler': 500}, 'Amazing': {'Truly ': 100, 'Incredible': 200, 'Text': 500}}
When I try to run a while loop, I only get the last row (replacing the 0 with a variable) And when I try to input a range into.iloc, I get the "series objects are not mutable" error当我尝试运行 while 循环时,我只得到最后一行(用变量替换 0)当我尝试在.iloc 中输入一个范围时,我得到“系列对象不可变”错误
How do I modify the code so that I get the exact same output as above, but in many fewer lines (original had 100)如何修改代码,以便获得与上面完全相同的 output ,但行数要少得多(原来有 100 行)
EDIT: Simplified question to only include sample code.编辑:简化问题只包含示例代码。 EDIT2: While loop code and output.
EDIT2:While循环代码和output。
import pandas as pd
df = pd.read_csv('C:\\Blah\\Code1.csv')
C = 0
while C < 5:
Z = {
df.iloc[C,1]: {df.iloc[C,2]: 100, df.iloc[C,3]: 200, df.iloc[C,4]: 500},
}
C += 1
print(Z)
Output below: {'Amazing': {'Truly ': 100, 'Incredible': 200, 'Text': 500}} Output 如下: {'Amazing': {'Truly': 100, 'Incredible': 200, 'Text': 500}}
If you want to modify the data-frame in place;如果您想就地修改数据框;
C = 0
while C < 5:
df.iloc[C,2] = 100
df.iloc[C,3] = 200
df.iloc[C,4] = 500
C += 1
If you want to have an extra dictionary;如果你想有一本额外的字典;
Z = {}
C = 0
while C < 5:
Z[df.iloc[C,1]] = {df.iloc[C,2]: 100, df.iloc[C,3]: 200, df.iloc[C,4]: 500}
C += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.